promptfoo 0.45.0 → 0.45.2

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 (52) hide show
  1. package/dist/package.json +1 -1
  2. package/dist/src/evaluator.d.ts.map +1 -1
  3. package/dist/src/evaluator.js +5 -7
  4. package/dist/src/evaluator.js.map +1 -1
  5. package/dist/src/onboarding.d.ts +1 -1
  6. package/dist/src/onboarding.d.ts.map +1 -1
  7. package/dist/src/onboarding.js +3 -1
  8. package/dist/src/onboarding.js.map +1 -1
  9. package/dist/src/providers/pythonCompletion.d.ts.map +1 -1
  10. package/dist/src/providers/pythonCompletion.js +7 -3
  11. package/dist/src/providers/pythonCompletion.js.map +1 -1
  12. package/dist/src/python/wrapper.d.ts +1 -1
  13. package/dist/src/python/wrapper.d.ts.map +1 -1
  14. package/dist/src/python/wrapper.js.map +1 -1
  15. package/dist/src/web/nextui/404/index.html +1 -1
  16. package/dist/src/web/nextui/404.html +1 -1
  17. package/dist/src/web/nextui/_next/static/chunks/445-74742af8ab1894f2.js +1 -1
  18. package/dist/src/web/nextui/_next/static/chunks/82-ca0360e473d81167.js +7 -0
  19. package/dist/src/web/nextui/_next/static/chunks/app/auth/login/{page-37e317d648a9930d.js → page-1c10570a7e431039.js} +1 -1
  20. package/dist/src/web/nextui/_next/static/chunks/app/auth/signup/{page-9d29227b6f856832.js → page-57f3e1b961ec3eac.js} +1 -1
  21. package/dist/src/web/nextui/_next/static/chunks/app/datasets/{page-1bd1830ab8cae4aa.js → page-44ab188f3b846712.js} +1 -1
  22. package/dist/src/web/nextui/_next/static/chunks/app/eval/[id]/not-found-366629541fd598e9.js +1 -0
  23. package/dist/src/web/nextui/_next/static/chunks/app/eval/[id]/{page-b6830ba38bc2e4d4.js → page-aec85c1e519871fb.js} +1 -1
  24. package/dist/src/web/nextui/_next/static/chunks/app/eval/page-5439c164205bd74d.js +1 -0
  25. package/dist/src/web/nextui/_next/static/chunks/app/layout-f887d1009f0f8cf1.js +1 -0
  26. package/dist/src/web/nextui/_next/static/chunks/app/{page-ccc61e117e42e5f8.js → page-ceb22f8e1a2af9dc.js} +1 -1
  27. package/dist/src/web/nextui/_next/static/chunks/app/prompts/{page-cdce512070f5f3a1.js → page-0bf3409d6a6bfa22.js} +1 -1
  28. package/dist/src/web/nextui/_next/static/chunks/app/setup/page-bd58a8506813a971.js +1 -0
  29. package/dist/src/web/nextui/_next/static/chunks/{main-app-a18517c2b68322ff.js → main-app-581ccf0003955b21.js} +1 -1
  30. package/dist/src/web/nextui/api/results +1 -1
  31. package/dist/src/web/nextui/auth/login/index.html +1 -1
  32. package/dist/src/web/nextui/auth/login/index.txt +3 -3
  33. package/dist/src/web/nextui/auth/signup/index.html +1 -1
  34. package/dist/src/web/nextui/auth/signup/index.txt +3 -3
  35. package/dist/src/web/nextui/datasets/index.html +1 -1
  36. package/dist/src/web/nextui/datasets/index.txt +3 -3
  37. package/dist/src/web/nextui/eval/index.html +1 -1
  38. package/dist/src/web/nextui/eval/index.txt +3 -3
  39. package/dist/src/web/nextui/index.html +1 -1
  40. package/dist/src/web/nextui/index.txt +2 -2
  41. package/dist/src/web/nextui/prompts/index.html +1 -1
  42. package/dist/src/web/nextui/prompts/index.txt +3 -3
  43. package/dist/src/web/nextui/setup/index.html +2 -2
  44. package/dist/src/web/nextui/setup/index.txt +3 -3
  45. package/package.json +1 -1
  46. package/dist/src/web/nextui/_next/static/chunks/82-ffdebabf7ccab1b7.js +0 -7
  47. package/dist/src/web/nextui/_next/static/chunks/app/eval/[id]/not-found-14c00147c1eba0de.js +0 -1
  48. package/dist/src/web/nextui/_next/static/chunks/app/eval/page-32d7177e7cac7a21.js +0 -1
  49. package/dist/src/web/nextui/_next/static/chunks/app/layout-300292a8e3404545.js +0 -1
  50. package/dist/src/web/nextui/_next/static/chunks/app/setup/page-dc69b72919062cfe.js +0 -1
  51. /package/dist/src/web/nextui/_next/static/{-X20qnE0oe9CD9UyAkWa1 → dpOPOkbjyEnq8K-_tq4vY}/_buildManifest.js +0 -0
  52. /package/dist/src/web/nextui/_next/static/{-X20qnE0oe9CD9UyAkWa1 → dpOPOkbjyEnq8K-_tq4vY}/_ssgManifest.js +0 -0
@@ -5,13 +5,13 @@
5
5
  5:HL["/_next/static/media/699512af39861afa-s.p.woff2",{"as":"font","type":"font/woff2"}]
6
6
  6:HL["/_next/static/media/934c4b7cb736f2a3-s.p.woff2",{"as":"font","type":"font/woff2"}]
7
7
  7:HL["/_next/static/css/51a17e8edcdfdbb2.css",{"as":"style"}]
8
- 0:["-X20qnE0oe9CD9UyAkWa1",[[["",{"children":["setup",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],"$L8",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/51a17e8edcdfdbb2.css","precedence":"next"}]],"$L9"]]]]
8
+ 0:["dpOPOkbjyEnq8K-_tq4vY",[[["",{"children":["setup",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],"$L8",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/51a17e8edcdfdbb2.css","precedence":"next"}]],"$L9"]]]]
9
9
  a:HL["/_next/static/css/16c1dd82fc87c9d7.css",{"as":"style"}]
10
- b:I{"id":2112,"chunks":["293:static/chunks/293-fa7b9b02f62ab5d8.js","548:static/chunks/548-ffb8dd99ad3940cb.js","82:static/chunks/82-ffdebabf7ccab1b7.js","886:static/chunks/886-ed0ff9e461fce55a.js","445:static/chunks/445-74742af8ab1894f2.js","185:static/chunks/app/layout-300292a8e3404545.js"],"name":"PageShell","async":false}
10
+ b:I{"id":2112,"chunks":["293:static/chunks/293-fa7b9b02f62ab5d8.js","548:static/chunks/548-ffb8dd99ad3940cb.js","82:static/chunks/82-ca0360e473d81167.js","886:static/chunks/886-ed0ff9e461fce55a.js","445:static/chunks/445-74742af8ab1894f2.js","185:static/chunks/app/layout-f887d1009f0f8cf1.js"],"name":"PageShell","async":false}
11
11
  c:I{"id":7767,"chunks":["272:static/chunks/webpack-4590f5da0889fc85.js","971:static/chunks/fd9d1056-a95b789c94c05ff6.js","596:static/chunks/596-f3a131b7c336dd5d.js"],"name":"default","async":false}
12
12
  d:I{"id":7920,"chunks":["272:static/chunks/webpack-4590f5da0889fc85.js","971:static/chunks/fd9d1056-a95b789c94c05ff6.js","596:static/chunks/596-f3a131b7c336dd5d.js"],"name":"default","async":false}
13
13
  f:I{"id":4839,"chunks":["272:static/chunks/webpack-4590f5da0889fc85.js","971:static/chunks/fd9d1056-a95b789c94c05ff6.js","596:static/chunks/596-f3a131b7c336dd5d.js"],"name":"default","async":false}
14
- 10:I{"id":2378,"chunks":["293:static/chunks/293-fa7b9b02f62ab5d8.js","808:static/chunks/808-b64f39fb5aa81c36.js","548:static/chunks/548-ffb8dd99ad3940cb.js","420:static/chunks/420-c4133cd89d8c5e4b.js","975:static/chunks/975-41f6ad20b4031b30.js","886:static/chunks/886-ed0ff9e461fce55a.js","683:static/chunks/683-31836dfcc9c45e50.js","339:static/chunks/339-501c32916b785ef1.js","376:static/chunks/376-1c0d6e6983c73fe2.js","413:static/chunks/app/setup/page-dc69b72919062cfe.js"],"name":"","async":false}
14
+ 10:I{"id":2378,"chunks":["293:static/chunks/293-fa7b9b02f62ab5d8.js","808:static/chunks/808-b64f39fb5aa81c36.js","548:static/chunks/548-ffb8dd99ad3940cb.js","420:static/chunks/420-c4133cd89d8c5e4b.js","975:static/chunks/975-41f6ad20b4031b30.js","886:static/chunks/886-ed0ff9e461fce55a.js","683:static/chunks/683-31836dfcc9c45e50.js","339:static/chunks/339-501c32916b785ef1.js","376:static/chunks/376-1c0d6e6983c73fe2.js","413:static/chunks/app/setup/page-bd58a8506813a971.js"],"name":"","async":false}
15
15
  8:[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_c5054f","children":["$","$Lb",null,{"children":["$","$Lc",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","loading":"$undefined","loadingStyles":"$undefined","hasLoading":false,"template":["$","$Ld",null,{}],"templateStyles":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":"$undefined","childProp":{"current":["$","$Lc",null,{"parallelRouterKey":"children","segmentPath":["children","setup","children"],"error":"$undefined","errorStyles":"$undefined","loading":"$undefined","loadingStyles":"$undefined","hasLoading":false,"template":["$","$Ld",null,{}],"templateStyles":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$Le",["$","$Lf",null,{"propsForComponent":{"params":{}},"Component":"$10"}],null],"segment":"__PAGE__"},"styles":[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/16c1dd82fc87c9d7.css","precedence":"next"}]]}],"segment":"setup"},"styles":[]}]}]}]}],null]
16
16
  9:[["$","meta","0",{"charSet":"utf-8"}],["$","title","1",{"children":"promptfoo"}],["$","meta","2",{"name":"description","content":"LLM testing and evaluation"}],["$","meta","3",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","4",{"property":"og:image","content":"https://www.promptfoo.dev/img/thumbnail.png"}],["$","meta","5",{"name":"twitter:card","content":"summary"}],["$","meta","6",{"name":"twitter:image","content":"https://www.promptfoo.dev/img/thumbnail.png"}],["$","meta","7",{"name":"next-size-adjust"}]]
17
17
  e:null
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "promptfoo",
3
3
  "description": "LLM eval & testing toolkit",
4
4
  "author": "Ian Webster",
5
- "version": "0.45.0",
5
+ "version": "0.45.2",
6
6
  "license": "MIT",
7
7
  "type": "commonjs",
8
8
  "repository": "promptfoo/promptfoo",
@@ -1,7 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[82],{3082:function(e,t,r){"use strict";var s,i=Object.defineProperty,n=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,l={};((e,t)=>{for(var r in t)i(e,r,{get:t[r],enumerable:!0})})(l,{createBrowserSupabaseClient:()=>j,createClientComponentClient:()=>c,createMiddlewareClient:()=>b,createMiddlewareSupabaseClient:()=>x,createPagesBrowserClient:()=>u,createPagesServerClient:()=>g,createRouteHandlerClient:()=>E,createServerActionClient:()=>O,createServerComponentClient:()=>k,createServerSupabaseClient:()=>C}),e.exports=((e,t,r,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let r of a(t))o.call(e,r)||void 0===r||i(e,r,{get:()=>t[r],enumerable:!(s=n(t,r))||s.enumerable});return e})(i({},"__esModule",{value:!0}),l);var h=r(9335);function c({supabaseUrl:e="https://vhywkeydkitmauabqnwv.supabase.co",supabaseKey:t="abc123",options:r,cookieOptions:i,isSingleton:n=!0}={}){if(!e||!t)throw Error("either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!");let a=()=>{var s;return(0,h.createSupabaseClient)(e,t,{...r,global:{...null==r?void 0:r.global,headers:{...null==(s=null==r?void 0:r.global)?void 0:s.headers,"X-Client-Info":"@supabase/auth-helpers-nextjs@0.7.4"}},auth:{storageKey:null==i?void 0:i.name,storage:new h.BrowserCookieAuthStorageAdapter(i)}})};if(n){let e=s??a();return"undefined"==typeof window?e:(s||(s=e),s)}return a()}var u=c,d=r(9335),f=r(8027),p=class extends d.CookieAuthStorageAdapter{constructor(e,t){super(t),this.context=e}getCookie(e){var t;let r=(0,f.splitCookiesString)((null==(t=this.context.res.getHeader("set-cookie"))?void 0:t.toString())??"").map(t=>(0,d.parseCookies)(t)[e]).find(e=>!!e),s=r??this.context.req.cookies[e];return s}setCookie(e,t){this._setCookie(e,t)}deleteCookie(e){this._setCookie(e,"",{maxAge:0})}_setCookie(e,t,r){var s;let i=(0,f.splitCookiesString)((null==(s=this.context.res.getHeader("set-cookie"))?void 0:s.toString())??"").filter(t=>!(e in(0,d.parseCookies)(t))),n=(0,d.serializeCookie)(e,t,{...this.cookieOptions,...r,httpOnly:!1});this.context.res.setHeader("set-cookie",[...i,n])}};function g(e,{supabaseUrl:t="https://vhywkeydkitmauabqnwv.supabase.co",supabaseKey:r="abc123",options:s,cookieOptions:i}={}){var n;if(!t||!r)throw Error("either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!");return(0,d.createSupabaseClient)(t,r,{...s,global:{...null==s?void 0:s.global,headers:{...null==(n=null==s?void 0:s.global)?void 0:n.headers,"X-Client-Info":"@supabase/auth-helpers-nextjs@0.7.4"}},auth:{storageKey:null==i?void 0:i.name,storage:new p(e,i)}})}var y=r(9335),m=r(8027),v=class extends y.CookieAuthStorageAdapter{constructor(e,t){super(t),this.context=e}getCookie(e){var t;let r=(0,m.splitCookiesString)((null==(t=this.context.res.headers.get("set-cookie"))?void 0:t.toString())??"").map(t=>(0,y.parseCookies)(t)[e]).find(e=>!!e);return r||(0,y.parseCookies)(this.context.req.headers.get("cookie")??"")[e]}setCookie(e,t){this._setCookie(e,t)}deleteCookie(e){this._setCookie(e,"",{maxAge:0})}_setCookie(e,t,r){let s=(0,y.serializeCookie)(e,t,{...this.cookieOptions,...r,httpOnly:!1});this.context.res.headers&&(this.context.res.headers.append("set-cookie",s),this.context.res.headers.append("cookie",s))}};function b(e,{supabaseUrl:t="https://vhywkeydkitmauabqnwv.supabase.co",supabaseKey:r="abc123",options:s,cookieOptions:i}={}){var n;if(!t||!r)throw Error("either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!");return(0,y.createSupabaseClient)(t,r,{...s,global:{...null==s?void 0:s.global,headers:{...null==(n=null==s?void 0:s.global)?void 0:n.headers,"X-Client-Info":"@supabase/auth-helpers-nextjs@0.7.4"}},auth:{storageKey:null==i?void 0:i.name,storage:new v(e,i)}})}var _=r(9335),w=class extends _.CookieAuthStorageAdapter{constructor(e,t){super(t),this.context=e}getCookie(e){var t;let r=this.context.cookies();return null==(t=r.get(e))?void 0:t.value}setCookie(e,t){}deleteCookie(e){}};function k(e,{supabaseUrl:t="https://vhywkeydkitmauabqnwv.supabase.co",supabaseKey:r="abc123",options:s,cookieOptions:i}={}){var n;if(!t||!r)throw Error("either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!");return(0,_.createSupabaseClient)(t,r,{...s,global:{...null==s?void 0:s.global,headers:{...null==(n=null==s?void 0:s.global)?void 0:n.headers,"X-Client-Info":"@supabase/auth-helpers-nextjs@0.7.4"}},auth:{storageKey:null==i?void 0:i.name,storage:new w(e,i)}})}var S=r(9335),T=class extends S.CookieAuthStorageAdapter{constructor(e,t){super(t),this.context=e}getCookie(e){var t;let r=this.context.cookies();return null==(t=r.get(e))?void 0:t.value}setCookie(e,t){let r=this.context.cookies();r.set(e,t,this.cookieOptions)}deleteCookie(e){let t=this.context.cookies();t.set(e,"",{maxAge:0})}};function E(e,{supabaseUrl:t="https://vhywkeydkitmauabqnwv.supabase.co",supabaseKey:r="abc123",options:s,cookieOptions:i}={}){var n;if(!t||!r)throw Error("either NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY env variables or supabaseUrl and supabaseKey are required!");return(0,S.createSupabaseClient)(t,r,{...s,global:{...null==s?void 0:s.global,headers:{...null==(n=null==s?void 0:s.global)?void 0:n.headers,"X-Client-Info":"@supabase/auth-helpers-nextjs@0.7.4"}},auth:{storageKey:null==i?void 0:i.name,storage:new T(e,i)}})}var O=E;function j({supabaseUrl:e="https://vhywkeydkitmauabqnwv.supabase.co",supabaseKey:t="abc123",options:r,cookieOptions:s}={}){return console.warn("Please utilize the `createPagesBrowserClient` function instead of the deprecated `createBrowserSupabaseClient` function. Learn more: https://supabase.com/docs/guides/auth/auth-helpers/nextjs-pages"),u({supabaseUrl:e,supabaseKey:t,options:r,cookieOptions:s})}function C(e,{supabaseUrl:t="https://vhywkeydkitmauabqnwv.supabase.co",supabaseKey:r="abc123",options:s,cookieOptions:i}={}){return console.warn("Please utilize the `createPagesServerClient` function instead of the deprecated `createServerSupabaseClient` function. Learn more: https://supabase.com/docs/guides/auth/auth-helpers/nextjs-pages"),g(e,{supabaseUrl:t,supabaseKey:r,options:s,cookieOptions:i})}function x(e,{supabaseUrl:t="https://vhywkeydkitmauabqnwv.supabase.co",supabaseKey:r="abc123",options:s,cookieOptions:i}={}){return console.warn("Please utilize the `createMiddlewareClient` function instead of the deprecated `createMiddlewareSupabaseClient` function. Learn more: https://supabase.com/docs/guides/auth/auth-helpers/nextjs#middleware"),b(e,{supabaseUrl:t,supabaseKey:r,options:s,cookieOptions:i})}},7992:function(e,t,r){"use strict";var s=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==r.g)return r.g;throw Error("unable to locate global object")}();e.exports=t=s.fetch,s.fetch&&(t.default=s.fetch.bind(s)),t.Headers=s.Headers,t.Request=s.Request,t.Response=s.Response},9366:function(e,t){var r="undefined"!=typeof self?self:this,s=function(){function e(){this.fetch=!1,this.DOMException=r.DOMException}return e.prototype=r,new e}();(function(e){var t={searchParams:"URLSearchParams"in s,iterable:"Symbol"in s&&"iterator"in Symbol,blob:"FileReader"in s&&"Blob"in s&&function(){try{return new Blob,!0}catch(e){return!1}}(),formData:"FormData"in s,arrayBuffer:"ArrayBuffer"in s};if(t.arrayBuffer)var r=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],i=ArrayBuffer.isView||function(e){return e&&r.indexOf(Object.prototype.toString.call(e))>-1};function n(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw TypeError("Invalid character in header field name");return e.toLowerCase()}function a(e){return"string"!=typeof e&&(e=String(e)),e}function o(e){var r={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return t.iterable&&(r[Symbol.iterator]=function(){return r}),r}function l(e){this.map={},e instanceof l?e.forEach(function(e,t){this.append(t,e)},this):Array.isArray(e)?e.forEach(function(e){this.append(e[0],e[1])},this):e&&Object.getOwnPropertyNames(e).forEach(function(t){this.append(t,e[t])},this)}function h(e){if(e.bodyUsed)return Promise.reject(TypeError("Already read"));e.bodyUsed=!0}function c(e){return new Promise(function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}})}function u(e){var t=new FileReader,r=c(t);return t.readAsArrayBuffer(e),r}function d(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function f(){return this.bodyUsed=!1,this._initBody=function(e){if(this._bodyInit=e,e){if("string"==typeof e)this._bodyText=e;else if(t.blob&&Blob.prototype.isPrototypeOf(e))this._bodyBlob=e;else if(t.formData&&FormData.prototype.isPrototypeOf(e))this._bodyFormData=e;else if(t.searchParams&&URLSearchParams.prototype.isPrototypeOf(e))this._bodyText=e.toString();else{var r;t.arrayBuffer&&t.blob&&(r=e)&&DataView.prototype.isPrototypeOf(r)?(this._bodyArrayBuffer=d(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):t.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(e)||i(e))?this._bodyArrayBuffer=d(e):this._bodyText=e=Object.prototype.toString.call(e)}}else this._bodyText="";!this.headers.get("content-type")&&("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):t.searchParams&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},t.blob&&(this.blob=function(){var e=h(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(!this._bodyFormData)return Promise.resolve(new Blob([this._bodyText]));throw Error("could not read FormData body as blob")},this.arrayBuffer=function(){return this._bodyArrayBuffer?h(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(u)}),this.text=function(){var e,t,r,s=h(this);if(s)return s;if(this._bodyBlob)return e=this._bodyBlob,r=c(t=new FileReader),t.readAsText(e),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=Array(t.length),s=0;s<t.length;s++)r[s]=String.fromCharCode(t[s]);return r.join("")}(this._bodyArrayBuffer));if(!this._bodyFormData)return Promise.resolve(this._bodyText);throw Error("could not read FormData body as text")},t.formData&&(this.formData=function(){return this.text().then(y)}),this.json=function(){return this.text().then(JSON.parse)},this}l.prototype.append=function(e,t){e=n(e),t=a(t);var r=this.map[e];this.map[e]=r?r+", "+t:t},l.prototype.delete=function(e){delete this.map[n(e)]},l.prototype.get=function(e){return e=n(e),this.has(e)?this.map[e]:null},l.prototype.has=function(e){return this.map.hasOwnProperty(n(e))},l.prototype.set=function(e,t){this.map[n(e)]=a(t)},l.prototype.forEach=function(e,t){for(var r in this.map)this.map.hasOwnProperty(r)&&e.call(t,this.map[r],r,this)},l.prototype.keys=function(){var e=[];return this.forEach(function(t,r){e.push(r)}),o(e)},l.prototype.values=function(){var e=[];return this.forEach(function(t){e.push(t)}),o(e)},l.prototype.entries=function(){var e=[];return this.forEach(function(t,r){e.push([r,t])}),o(e)},t.iterable&&(l.prototype[Symbol.iterator]=l.prototype.entries);var p=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function g(e,t){var r,s,i=(t=t||{}).body;if(e instanceof g){if(e.bodyUsed)throw TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new l(e.headers)),this.method=e.method,this.mode=e.mode,this.signal=e.signal,i||null==e._bodyInit||(i=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"same-origin",(t.headers||!this.headers)&&(this.headers=new l(t.headers)),this.method=(s=(r=t.method||this.method||"GET").toUpperCase(),p.indexOf(s)>-1?s:r),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&i)throw TypeError("Body not allowed for GET or HEAD requests");this._initBody(i)}function y(e){var t=new FormData;return e.trim().split("&").forEach(function(e){if(e){var r=e.split("="),s=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(s),decodeURIComponent(i))}}),t}function m(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new l(t.headers),this.url=t.url||"",this._initBody(e)}g.prototype.clone=function(){return new g(this,{body:this._bodyInit})},f.call(g.prototype),f.call(m.prototype),m.prototype.clone=function(){return new m(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new l(this.headers),url:this.url})},m.error=function(){var e=new m(null,{status:0,statusText:""});return e.type="error",e};var v=[301,302,303,307,308];m.redirect=function(e,t){if(-1===v.indexOf(t))throw RangeError("Invalid status code");return new m(null,{status:t,headers:{location:e}})},e.DOMException=s.DOMException;try{new e.DOMException}catch(t){e.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},e.DOMException.prototype=Object.create(Error.prototype),e.DOMException.prototype.constructor=e.DOMException}function b(r,s){return new Promise(function(i,n){var a=new g(r,s);if(a.signal&&a.signal.aborted)return n(new e.DOMException("Aborted","AbortError"));var o=new XMLHttpRequest;function h(){o.abort()}o.onload=function(){var e,t,r={status:o.status,statusText:o.statusText,headers:(e=o.getAllResponseHeaders()||"",t=new l,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach(function(e){var r=e.split(":"),s=r.shift().trim();if(s){var i=r.join(":").trim();t.append(s,i)}}),t)};r.url="responseURL"in o?o.responseURL:r.headers.get("X-Request-URL");var s="response"in o?o.response:o.responseText;i(new m(s,r))},o.onerror=function(){n(TypeError("Network request failed"))},o.ontimeout=function(){n(TypeError("Network request failed"))},o.onabort=function(){n(new e.DOMException("Aborted","AbortError"))},o.open(a.method,a.url,!0),"include"===a.credentials?o.withCredentials=!0:"omit"===a.credentials&&(o.withCredentials=!1),"responseType"in o&&t.blob&&(o.responseType="blob"),a.headers.forEach(function(e,t){o.setRequestHeader(t,e)}),a.signal&&(a.signal.addEventListener("abort",h),o.onreadystatechange=function(){4===o.readyState&&a.signal.removeEventListener("abort",h)}),o.send(void 0===a._bodyInit?null:a._bodyInit)})}b.polyfill=!0,s.fetch||(s.fetch=b,s.Headers=l,s.Request=g,s.Response=m),e.Headers=l,e.Request=g,e.Response=m,e.fetch=b,Object.defineProperty(e,"__esModule",{value:!0})})({}),s.fetch.ponyfill=!0,delete s.fetch.polyfill,(t=s.fetch).default=s.fetch,t.fetch=s.fetch,t.Headers=s.Headers,t.Request=s.Request,t.Response=s.Response,e.exports=t},9472:function(e){var t=function(){if("object"==typeof self&&self)return self;if("object"==typeof window&&window)return window;throw Error("Unable to resolve global `this`")};e.exports=function(){if(this)return this;if("object"==typeof globalThis&&globalThis)return globalThis;try{Object.defineProperty(Object.prototype,"__global__",{get:function(){return this},configurable:!0})}catch(e){return t()}try{if(!__global__)return t();return __global__}finally{delete Object.prototype.__global__}}()},8027:function(e){"use strict";var t={decodeValues:!0,map:!1,silent:!1};function r(e){return"string"==typeof e&&!!e.trim()}function s(e,s){var i,n,a,o,l=e.split(";").filter(r),h=(i=l.shift(),n="",a="",(o=i.split("=")).length>1?(n=o.shift(),a=o.join("=")):a=i,{name:n,value:a}),c=h.name,u=h.value;s=s?Object.assign({},t,s):t;try{u=s.decodeValues?decodeURIComponent(u):u}catch(e){console.error("set-cookie-parser encountered an error while decoding a cookie with value '"+u+"'. Set options.decodeValues to false to disable this feature.",e)}var d={name:c,value:u};return l.forEach(function(e){var t=e.split("="),r=t.shift().trimLeft().toLowerCase(),s=t.join("=");"expires"===r?d.expires=new Date(s):"max-age"===r?d.maxAge=parseInt(s,10):"secure"===r?d.secure=!0:"httponly"===r?d.httpOnly=!0:"samesite"===r?d.sameSite=s:d[r]=s}),d}function i(e,i){if(i=i?Object.assign({},t,i):t,!e)return i.map?{}:[];if(e.headers){if("function"==typeof e.headers.getSetCookie)e=e.headers.getSetCookie();else if(e.headers["set-cookie"])e=e.headers["set-cookie"];else{var n=e.headers[Object.keys(e.headers).find(function(e){return"set-cookie"===e.toLowerCase()})];n||!e.headers.cookie||i.silent||console.warn("Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."),e=n}}return(Array.isArray(e)||(e=[e]),(i=i?Object.assign({},t,i):t).map)?e.filter(r).reduce(function(e,t){var r=s(t,i);return e[r.name]=r,e},{}):e.filter(r).map(function(e){return s(e,i)})}e.exports=i,e.exports.parse=i,e.exports.parseString=s,e.exports.splitCookiesString=function(e){if(Array.isArray(e))return e;if("string"!=typeof e)return[];var t,r,s,i,n,a=[],o=0;function l(){for(;o<e.length&&/\s/.test(e.charAt(o));)o+=1;return o<e.length}for(;o<e.length;){for(t=o,n=!1;l();)if(","===(r=e.charAt(o))){for(s=o,o+=1,l(),i=o;o<e.length&&"="!==(r=e.charAt(o))&&";"!==r&&","!==r;)o+=1;o<e.length&&"="===e.charAt(o)?(n=!0,o=i,a.push(e.substring(t,s)),t=o):o=s+1}else o+=1;(!n||o>=e.length)&&a.push(e.substring(t,e.length))}return a}},1775:function(e,t,r){if("object"==typeof globalThis)s=globalThis;else try{s=r(9472)}catch(e){}finally{if(s||"undefined"==typeof window||(s=window),!s)throw Error("Could not determine global this")}var s,i=s.WebSocket||s.MozWebSocket,n=r(5506);function a(e,t){return t?new i(e,t):new i(e)}i&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach(function(e){Object.defineProperty(a,e,{get:function(){return i[e]}})}),e.exports={w3cwebsocket:i?a:null,version:n}},5506:function(e,t,r){e.exports=r(2151).version},9335:function(e,t,r){"use strict";r.r(t),r.d(t,{BrowserCookieAuthStorageAdapter:function(){return tz},CookieAuthStorageAdapter:function(){return tK},DEFAULT_COOKIE_OPTIONS:function(){return tM},createSupabaseClient:function(){return tJ},isBrowser:function(){return tq},parseCookies:function(){return tH},parseSupabaseCookie:function(){return tB},serializeCookie:function(){return tG},stringifySupabaseSession:function(){return tF}}),new TextEncoder;let s=new TextDecoder,i=e=>{let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r};var n,a,o,l,h,c,u,d,f,p,g,y,m,v,b,_,w,k,S,T,E,O=crypto;O.getRandomValues.bind(O),Symbol();let j=e=>{let t=e;t instanceof Uint8Array&&(t=s.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return i(t)}catch(e){throw TypeError("The input to be decoded is not correctly encoded.")}},C=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>{var t,s,i,n;return t=void 0,s=void 0,i=void 0,n=function*(){return yield(yield Promise.resolve().then(r.t.bind(r,9366,23))).fetch(...e)},new(i||(i=Promise))(function(e,r){function a(e){try{l(n.next(e))}catch(e){r(e)}}function o(e){try{l(n.throw(e))}catch(e){r(e)}}function l(t){var r;t.done?e(t.value):((r=t.value)instanceof i?r:new i(function(e){e(r)})).then(a,o)}l((n=n.apply(t,s||[])).next())})}:fetch),(...e)=>t(...e)};class x extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class P extends x{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class A extends x{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class $ extends x{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}class R{constructor(e,{headers:t={},customFetch:r}={}){this.url=e,this.headers=t,this.fetch=C(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r,s,i,n,a;return s=this,i=void 0,n=void 0,a=function*(){try{let s;let{headers:i,method:n,body:a}=t,o={};a&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&("undefined"!=typeof Blob&&a instanceof Blob||a instanceof ArrayBuffer?(o["Content-Type"]="application/octet-stream",s=a):"string"==typeof a?(o["Content-Type"]="text/plain",s=a):"undefined"!=typeof FormData&&a instanceof FormData?s=a:(o["Content-Type"]="application/json",s=JSON.stringify(a)));let l=yield this.fetch(`${this.url}/${e}`,{method:n||"POST",headers:Object.assign(Object.assign(Object.assign({},o),this.headers),i),body:s}).catch(e=>{throw new P(e)}),h=l.headers.get("x-relay-error");if(h&&"true"===h)throw new A(l);if(!l.ok)throw new $(l);let c=(null!==(r=l.headers.get("Content-Type"))&&void 0!==r?r:"text/plain").split(";")[0].trim();return{data:"application/json"===c?yield l.json():"application/octet-stream"===c?yield l.blob():"multipart/form-data"===c?yield l.formData():yield l.text(),error:null}}catch(e){return{data:null,error:e}}},new(n||(n=Promise))(function(e,t){function r(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var s;t.done?e(t.value):((s=t.value)instanceof n?s:new n(function(e){e(s)})).then(r,o)}l((a=a.apply(s,i||[])).next())})}}var I=r(7992),U=r.n(I);class L{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:"undefined"==typeof fetch?this.fetch=U():this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),"GET"!==this.method&&"HEAD"!==this.method&&(this.headers["Content-Type"]="application/json");let r=this.fetch,s=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{var t,r,s;let i=null,n=null,a=null,o=e.status,l=e.statusText;if(e.ok){if("HEAD"!==this.method){let t=await e.text();""===t||(n="text/csv"===this.headers.Accept?t:this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?t:JSON.parse(t))}let s=null===(t=this.headers.Prefer)||void 0===t?void 0:t.match(/count=(exact|planned|estimated)/),h=null===(r=e.headers.get("content-range"))||void 0===r?void 0:r.split("/");s&&h&&h.length>1&&(a=parseInt(h[1])),this.isMaybeSingle&&"GET"===this.method&&Array.isArray(n)&&(n.length>1?(i={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,a=null,o=406,l="Not Acceptable"):n=1===n.length?n[0]:null)}else{let t=await e.text();try{i=JSON.parse(t),Array.isArray(i)&&404===e.status&&(n=[],i=null,o=200,l="OK")}catch(r){404===e.status&&""===t?(o=204,l="No Content"):i={message:t}}if(i&&this.isMaybeSingle&&(null===(s=null==i?void 0:i.details)||void 0===s?void 0:s.includes("Results contain 0 rows"))&&(i=null,o=200,l="OK"),i&&this.shouldThrowOnError)throw i}let h={error:i,data:n,count:a,status:o,statusText:l};return h});return this.shouldThrowOnError||(s=s.catch(e=>{var t,r,s;return{error:{message:`${null!==(t=null==e?void 0:e.name)&&void 0!==t?t:"FetchError"}: ${null==e?void 0:e.message}`,details:`${null!==(r=null==e?void 0:e.stack)&&void 0!==r?r:""}`,hint:"",code:`${null!==(s=null==e?void 0:e.code)&&void 0!==s?s:""}`},data:null,count:null,status:0,statusText:""}})),s.then(e,t)}}class N extends L{select(e){let t=!1,r=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:s}={}){let i=s?`${s}.order`:"order",n=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${n?`${n},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t}={}){let r=void 0===t?"limit":`${t}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:r}={}){let s=void 0===r?"offset":`${r}.offset`,i=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(s,`${e}`),this.url.searchParams.set(i,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return"GET"===this.method?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:s=!1,wal:i=!1,format:n="text"}={}){let a=[e?"analyze":null,t?"verbose":null,r?"settings":null,s?"buffers":null,i?"wal":null].filter(Boolean).join("|"),o=this.headers.Accept;return this.headers.Accept=`application/vnd.pgrst.plan+${n}; for="${o}"; options=${a};`,this}rollback(){var e;return(null!==(e=this.headers.Prefer)&&void 0!==e?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}}class D extends N{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let r=t.map(e=>"string"==typeof e&&RegExp("[,()]").test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:s}={}){let i="";"plain"===s?i="pl":"phrase"===s?i="ph":"websearch"===s&&(i="w");let n=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${i}fts${n}.${t}`),this}match(e){return Object.entries(e).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t}={}){let r=t?`${t}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}}class B{constructor(e,{headers:t={},schema:r,fetch:s}){this.url=e,this.headers=t,this.schema=r,this.fetch=s}select(e,{head:t=!1,count:r}={}){let s=!1,i=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!s?"":('"'===e&&(s=!s),e)).join("");return this.url.searchParams.set("select",i),r&&(this.headers.Prefer=`count=${r}`),new D({method:t?"HEAD":"GET",url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:r=!0}={}){let s=[];if(this.headers.Prefer&&s.push(this.headers.Prefer),t&&s.push(`count=${t}`),r||s.push("missing=default"),this.headers.Prefer=s.join(","),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);this.url.searchParams.set("columns",e.join(","))}}return new D({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:s,defaultToNull:i=!0}={}){let n=[`resolution=${r?"ignore":"merge"}-duplicates`];if(void 0!==t&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&n.push(this.headers.Prefer),s&&n.push(`count=${s}`),i||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);this.url.searchParams.set("columns",e.join(","))}}return new D({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let r=[];return this.headers.Prefer&&r.push(this.headers.Prefer),t&&r.push(`count=${t}`),this.headers.Prefer=r.join(","),new D({method:"PATCH",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t=[];return e&&t.push(`count=${e}`),this.headers.Prefer&&t.unshift(this.headers.Prefer),this.headers.Prefer=t.join(","),new D({method:"DELETE",url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}}let F={"X-Client-Info":"postgrest-js/1.8.4"};class q{constructor(e,{headers:t={},schema:r,fetch:s}={}){this.url=e,this.headers=Object.assign(Object.assign({},F),t),this.schemaName=r,this.fetch=s}from(e){let t=new URL(`${this.url}/${e}`);return new B(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new q(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,count:s}={}){let i,n;let a=new URL(`${this.url}/rpc/${e}`);r?(i="HEAD",Object.entries(t).forEach(([e,t])=>{a.searchParams.append(e,`${t}`)})):(i="POST",n=t);let o=Object.assign({},this.headers);return s&&(o.Prefer=`count=${s}`),new D({method:i,url:a,headers:o,schema:this.schemaName,body:n,fetch:this.fetch,allowEmpty:!1})}}var M=r(1775);let K={"X-Client-Info":"realtime-js/2.7.4"};(n=y||(y={}))[n.connecting=0]="connecting",n[n.open=1]="open",n[n.closing=2]="closing",n[n.closed=3]="closed",(a=m||(m={})).closed="closed",a.errored="errored",a.joined="joined",a.joining="joining",a.leaving="leaving",(o=v||(v={})).close="phx_close",o.error="phx_error",o.join="phx_join",o.reply="phx_reply",o.leave="phx_leave",o.access_token="access_token",(b||(b={})).websocket="websocket",(l=_||(_={})).Connecting="connecting",l.Open="open",l.Closing="closing",l.Closed="closed";class z{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}class J{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):"string"==typeof e?t(JSON.parse(e)):t({})}_binaryDecode(e){let t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){let s=t.getUint8(1),i=t.getUint8(2),n=this.HEADER_LENGTH+2,a=r.decode(e.slice(n,n+s));n+=s;let o=r.decode(e.slice(n,n+i));n+=i;let l=JSON.parse(r.decode(e.slice(n,e.byteLength)));return{ref:null,topic:a,event:o,payload:l}}}class H{constructor(e,t,r={},s=1e4){this.channel=e,this.event=t,this.payload=r,this.timeout=s,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null,this.rateLimited=!1}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){if(this._hasReceived("timeout"))return;this.startTimeout(),this.sent=!0;let e=this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()});"rate limited"===e&&(this.rateLimited=!0)}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t(null===(r=this.receivedResp)||void 0===r?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){this.timeoutTimer||(this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref),this.channel._on(this.refEvent,{},e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout))}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}(h=w||(w={})).SYNC="sync",h.JOIN="join",h.LEAVE="leave";class G{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};let r=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},e=>{let{onJoin:t,onLeave:r,onSync:s}=this.caller;this.joinRef=this.channel._joinRef(),this.state=G.syncState(this.state,e,t,r),this.pendingDiffs.forEach(e=>{this.state=G.syncDiff(this.state,e,t,r)}),this.pendingDiffs=[],s()}),this.channel._on(r.diff,{},e=>{let{onJoin:t,onLeave:r,onSync:s}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=G.syncDiff(this.state,e,t,r),s())}),this.onJoin((e,t,r)=>{this.channel._trigger("presence",{event:"join",key:e,currentPresences:t,newPresences:r})}),this.onLeave((e,t,r)=>{this.channel._trigger("presence",{event:"leave",key:e,currentPresences:t,leftPresences:r})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,s){let i=this.cloneDeep(e),n=this.transformState(t),a={},o={};return this.map(i,(e,t)=>{n[e]||(o[e]=t)}),this.map(n,(e,t)=>{let r=i[e];if(r){let s=t.map(e=>e.presence_ref),i=r.map(e=>e.presence_ref),n=t.filter(e=>0>i.indexOf(e.presence_ref)),l=r.filter(e=>0>s.indexOf(e.presence_ref));n.length>0&&(a[e]=n),l.length>0&&(o[e]=l)}else a[e]=t}),this.syncDiff(i,{joins:a,leaves:o},r,s)}static syncDiff(e,t,r,s){let{joins:i,leaves:n}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),s||(s=()=>{}),this.map(i,(t,s)=>{var i;let n=null!==(i=e[t])&&void 0!==i?i:[];if(e[t]=this.cloneDeep(s),n.length>0){let r=e[t].map(e=>e.presence_ref),s=n.filter(e=>0>r.indexOf(e.presence_ref));e[t].unshift(...s)}r(t,n,s)}),this.map(n,(t,r)=>{let i=e[t];if(!i)return;let n=r.map(e=>e.presence_ref);i=i.filter(e=>0>n.indexOf(e.presence_ref)),e[t]=i,s(t,i,r),0===i.length&&delete e[t]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return Object.getOwnPropertyNames(e=this.cloneDeep(e)).reduce((t,r)=>{let s=e[r];return"metas"in s?t[r]=s.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):t[r]=s,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}(c=k||(k={})).abstime="abstime",c.bool="bool",c.date="date",c.daterange="daterange",c.float4="float4",c.float8="float8",c.int2="int2",c.int4="int4",c.int4range="int4range",c.int8="int8",c.int8range="int8range",c.json="json",c.jsonb="jsonb",c.money="money",c.numeric="numeric",c.oid="oid",c.reltime="reltime",c.text="text",c.time="time",c.timestamp="timestamp",c.timestamptz="timestamptz",c.timetz="timetz",c.tsrange="tsrange",c.tstzrange="tstzrange";let V=(e,t,r={})=>{var s;let i=null!==(s=r.skipTypes)&&void 0!==s?s:[];return Object.keys(t).reduce((r,s)=>(r[s]=X(s,e,t,i),r),{})},X=(e,t,r,s)=>{let i=t.find(t=>t.name===e),n=null==i?void 0:i.type,a=r[e];return n&&!s.includes(n)?W(n,a):Y(a)},W=(e,t)=>{if("_"===e.charAt(0)){let r=e.slice(1,e.length);return et(t,r)}switch(e){case k.bool:return Q(t);case k.float4:case k.float8:case k.int2:case k.int4:case k.int8:case k.numeric:case k.oid:return Z(t);case k.json:case k.jsonb:return ee(t);case k.timestamp:return er(t);case k.abstime:case k.date:case k.daterange:case k.int4range:case k.int8range:case k.money:case k.reltime:case k.text:case k.time:case k.timestamptz:case k.timetz:case k.tsrange:case k.tstzrange:default:return Y(t)}},Y=e=>e,Q=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},Z=e=>{if("string"==typeof e){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},ee=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(e){console.log(`JSON parse error: ${e}`)}return e},et=(e,t)=>{if("string"!=typeof e)return e;let r=e.length-1,s=e[r],i=e[0];if("{"===i&&"}"===s){let s;let i=e.slice(1,r);try{s=JSON.parse("["+i+"]")}catch(e){s=i?i.split(","):[]}return s.map(e=>W(t,e))}return e},er=e=>"string"==typeof e?e.replace(" ","T"):e;var es=function(e,t,r,s){return new(r||(r=Promise))(function(i,n){function a(e){try{l(s.next(e))}catch(e){n(e)}}function o(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(a,o)}l((s=s.apply(e,t||[])).next())})};(u=S||(S={})).ALL="*",u.INSERT="INSERT",u.UPDATE="UPDATE",u.DELETE="DELETE",(d=T||(T={})).BROADCAST="broadcast",d.PRESENCE="presence",d.POSTGRES_CHANGES="postgres_changes",(f=E||(E={})).SUBSCRIBED="SUBSCRIBED",f.TIMED_OUT="TIMED_OUT",f.CLOSED="CLOSED",f.CHANNEL_ERROR="CHANNEL_ERROR";class ei{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=m.closed,this.joinedOnce=!1,this.pushBuffer=[],this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""}},t.config),this.timeout=this.socket.timeout,this.joinPush=new H(this,v.join,this.params,this.timeout),this.rejoinTimer=new z(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=m.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=m.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=m.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=m.errored,this.rejoinTimer.scheduleTimeout())}),this._on(v.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new G(this)}subscribe(e,t=this.timeout){var r,s;if(this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:i,presence:n}}=this.params;this._onError(t=>e&&e("CHANNEL_ERROR",t)),this._onClose(()=>e&&e("CLOSED"));let a={},o={broadcast:i,presence:n,postgres_changes:null!==(s=null===(r=this.bindings.postgres_changes)||void 0===r?void 0:r.map(e=>e.filter))&&void 0!==s?s:[]};this.socket.accessToken&&(a.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:o},a)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:t})=>{var r;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),void 0===t){e&&e("SUBSCRIBED");return}{let s=this.bindings.postgres_changes,i=null!==(r=null==s?void 0:s.length)&&void 0!==r?r:0,n=[];for(let r=0;r<i;r++){let i=s[r],{filter:{event:a,schema:o,table:l,filter:h}}=i,c=t&&t[r];if(c&&c.event===a&&c.schema===o&&c.table===l&&c.filter===h)n.push(Object.assign(Object.assign({},i),{id:c.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=n,e&&e("SUBSCRIBED");return}}).receive("error",t=>{e&&e("CHANNEL_ERROR",Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}track(e,t={}){return es(this,void 0,void 0,function*(){return yield this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)})}untrack(e={}){return es(this,void 0,void 0,function*(){return yield this.send({type:"presence",event:"untrack"},e)})}on(e,t,r){return this._on(e,t,r)}send(e,t={}){return new Promise(r=>{var s,i,n;let a=this._push(e.type,e,t.timeout||this.timeout);a.rateLimited&&r("rate limited"),"broadcast"!==e.type||(null===(n=null===(i=null===(s=this.params)||void 0===s?void 0:s.config)||void 0===i?void 0:i.broadcast)||void 0===n?void 0:n.ack)||r("ok"),a.receive("ok",()=>r("ok")),a.receive("timeout",()=>r("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=m.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(v.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let s=new H(this,v.leave,{},e);s.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),s.send(),this._canPush()||s.trigger("ok",{})})}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let s=new H(this,e,t,r);return this._canPush()?s.send():(s.startTimeout(),this.pushBuffer.push(s)),s}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var s,i;let n=e.toLocaleLowerCase(),{close:a,error:o,leave:l,join:h}=v;if(r&&[a,o,l,h].indexOf(n)>=0&&r!==this._joinRef())return;let c=this._onMessage(n,t,r);if(t&&!c)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(n)?null===(s=this.bindings.postgres_changes)||void 0===s||s.filter(e=>{var t,r,s;return(null===(t=e.filter)||void 0===t?void 0:t.event)==="*"||(null===(s=null===(r=e.filter)||void 0===r?void 0:r.event)||void 0===s?void 0:s.toLocaleLowerCase())===n}).map(e=>e.callback(c,r)):null===(i=this.bindings[n])||void 0===i||i.filter(e=>{var r,s,i,a,o,l;if(!["broadcast","presence","postgres_changes"].includes(n))return e.type.toLocaleLowerCase()===n;if("id"in e){let n=e.id,a=null===(r=e.filter)||void 0===r?void 0:r.event;return n&&(null===(s=t.ids)||void 0===s?void 0:s.includes(n))&&("*"===a||(null==a?void 0:a.toLocaleLowerCase())===(null===(i=t.data)||void 0===i?void 0:i.type.toLocaleLowerCase()))}{let r=null===(o=null===(a=null==e?void 0:e.filter)||void 0===a?void 0:a.event)||void 0===o?void 0:o.toLocaleLowerCase();return"*"===r||r===(null===(l=null==t?void 0:t.event)||void 0===l?void 0:l.toLocaleLowerCase())}}).map(e=>{if("object"==typeof c&&"ids"in c){let e=c.data,{schema:t,table:r,commit_timestamp:s,type:i,errors:n}=e;c=Object.assign(Object.assign({},{schema:t,table:r,commit_timestamp:s,eventType:i,new:{},old:{},errors:n}),this._getPayloadRecords(e))}e.callback(c,r)})}_isClosed(){return this.state===m.closed}_isJoined(){return this.state===m.joined}_isJoining(){return this.state===m.joining}_isLeaving(){return this.state===m.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){let s=e.toLocaleLowerCase(),i={type:s,filter:t,callback:r};return this.bindings[s]?this.bindings[s].push(i):this.bindings[s]=[i],this}_off(e,t){let r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(e=>{var s;return!((null===(s=e.type)||void 0===s?void 0:s.toLocaleLowerCase())===r&&ei.isEqual(e.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(v.close,{},e)}_onError(e){this._on(v.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=m.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return("INSERT"===e.type||"UPDATE"===e.type)&&(t.new=V(e.columns,e.record)),("UPDATE"===e.type||"DELETE"===e.type)&&(t.old=V(e.columns,e.old_record)),t}}var en=function(e,t,r,s){return new(r||(r=Promise))(function(i,n){function a(e){try{l(s.next(e))}catch(e){n(e)}}function o(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(a,o)}l((s=s.apply(e,t||[])).next())})};let ea=()=>{};class eo{constructor(e,t){var r,s;this.accessToken=null,this.channels=[],this.endPoint="",this.headers=K,this.params={},this.timeout=1e4,this.transport=M.w3cwebsocket,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=ea,this.conn=null,this.sendBuffer=[],this.serializer=new J,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.eventsPerSecondLimitMs=100,this.inThrottle=!1,this.endPoint=`${e}/${b.websocket}`,(null==t?void 0:t.params)&&(this.params=t.params),(null==t?void 0:t.headers)&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),(null==t?void 0:t.timeout)&&(this.timeout=t.timeout),(null==t?void 0:t.logger)&&(this.logger=t.logger),(null==t?void 0:t.transport)&&(this.transport=t.transport),(null==t?void 0:t.heartbeatIntervalMs)&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);let i=null===(r=null==t?void 0:t.params)||void 0===r?void 0:r.eventsPerSecond;i&&(this.eventsPerSecondLimitMs=Math.floor(1e3/i));let n=null===(s=null==t?void 0:t.params)||void 0===s?void 0:s.apikey;n&&(this.accessToken=n),this.reconnectAfterMs=(null==t?void 0:t.reconnectAfterMs)?t.reconnectAfterMs:e=>[1e3,2e3,5e3,1e4][e-1]||1e4,this.encode=(null==t?void 0:t.encode)?t.encode:(e,t)=>t(JSON.stringify(e)),this.decode=(null==t?void 0:t.decode)?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new z(()=>en(this,void 0,void 0,function*(){this.disconnect(),this.connect()}),this.reconnectAfterMs)}connect(){!this.conn&&(this.conn=new this.transport(this._endPointURL(),[],null,this.headers),this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e)))}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,null!=t?t:""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}removeChannel(e){return en(this,void 0,void 0,function*(){let t=yield e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t})}removeAllChannels(){return en(this,void 0,void 0,function*(){let e=yield Promise.all(this.channels.map(e=>e.unsubscribe()));return this.disconnect(),e})}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case y.connecting:return _.Connecting;case y.open:return _.Open;case y.closing:return _.Closing;default:return _.Closed}}isConnected(){return this.connectionState()===_.Open}channel(e,t={config:{}}){this.isConnected()||this.connect();let r=new ei(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){let{topic:t,event:r,payload:s,ref:i}=e,n=()=>{this.encode(e,e=>{var t;null===(t=this.conn)||void 0===t||t.send(e)})};if(this.log("push",`${t} ${r} (${i})`,s),this.isConnected()){if(["broadcast","presence","postgres_changes"].includes(r)){let e=this._throttle(n)();if(e)return"rate limited"}else n()}else this.sendBuffer.push(n)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(v.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:"1.0.0"}))}_onConnMessage(e){this.decode(e.data,e=>{let{topic:t,event:r,payload:s,ref:i}=e;(i&&i===this.pendingHeartbeatRef||r===(null==s?void 0:s.type))&&(this.pendingHeartbeatRef=null),this.log("receive",`${s.status||""} ${t} ${r} ${i&&"("+i+")"||""}`,s),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(r,s,i)),this.stateChangeCallbacks.message.forEach(t=>t(e))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(v.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;let r=e.match(/\?/)?"&":"?",s=new URLSearchParams(t);return`${e}${r}${s}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),null===(e=this.conn)||void 0===e||e.close(1e3,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}_throttle(e,t=this.eventsPerSecondLimitMs){return()=>!!this.inThrottle||(e(),t>0&&(this.inThrottle=!0,setTimeout(()=>{this.inThrottle=!1},t)),!1)}}class el extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function eh(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}class ec extends el{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class eu extends el{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}var ed=function(e,t,r,s){return new(r||(r=Promise))(function(i,n){function a(e){try{l(s.next(e))}catch(e){n(e)}}function o(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(a,o)}l((s=s.apply(e,t||[])).next())})};let ef=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>ed(void 0,void 0,void 0,function*(){return yield(yield Promise.resolve().then(r.t.bind(r,9366,23))).fetch(...e)}):fetch),(...e)=>t(...e)},ep=()=>ed(void 0,void 0,void 0,function*(){return"undefined"==typeof Response?(yield Promise.resolve().then(r.t.bind(r,9366,23))).Response:Response});var eg=function(e,t,r,s){return new(r||(r=Promise))(function(i,n){function a(e){try{l(s.next(e))}catch(e){n(e)}}function o(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(a,o)}l((s=s.apply(e,t||[])).next())})};let ey=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),em=(e,t)=>eg(void 0,void 0,void 0,function*(){let r=yield ep();e instanceof r?e.json().then(r=>{t(new ec(ey(r),e.status||500))}).catch(e=>{t(new eu(ey(e),e))}):t(new eu(ey(e),e))}),ev=(e,t,r,s)=>{let i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?i:(i.headers=Object.assign({"Content-Type":"application/json"},null==t?void 0:t.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),r))};function eb(e,t,r,s,i,n){return eg(this,void 0,void 0,function*(){return new Promise((a,o)=>{e(r,ev(t,s,i,n)).then(e=>{if(!e.ok)throw e;return(null==s?void 0:s.noResolveJson)?e:e.json()}).then(e=>a(e)).catch(e=>em(e,o))})})}function e_(e,t,r,s){return eg(this,void 0,void 0,function*(){return eb(e,"GET",t,r,s)})}function ew(e,t,r,s,i){return eg(this,void 0,void 0,function*(){return eb(e,"POST",t,s,i,r)})}function ek(e,t,r,s,i){return eg(this,void 0,void 0,function*(){return eb(e,"DELETE",t,s,i,r)})}var eS=function(e,t,r,s){return new(r||(r=Promise))(function(i,n){function a(e){try{l(s.next(e))}catch(e){n(e)}}function o(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(a,o)}l((s=s.apply(e,t||[])).next())})};let eT={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},eE={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class eO{constructor(e,t={},r,s){this.url=e,this.headers=t,this.bucketId=r,this.fetch=ef(s)}uploadOrUpdate(e,t,r,s){return eS(this,void 0,void 0,function*(){try{let i;let n=Object.assign(Object.assign({},eE),s),a=Object.assign(Object.assign({},this.headers),"POST"===e&&{"x-upsert":String(n.upsert)});"undefined"!=typeof Blob&&r instanceof Blob?((i=new FormData).append("cacheControl",n.cacheControl),i.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(i=r).append("cacheControl",n.cacheControl):(i=r,a["cache-control"]=`max-age=${n.cacheControl}`,a["content-type"]=n.contentType);let o=this._removeEmptyFolders(t),l=this._getFinalPath(o),h=yield this.fetch(`${this.url}/object/${l}`,Object.assign({method:e,body:i,headers:a},(null==n?void 0:n.duplex)?{duplex:n.duplex}:{}));if(h.ok)return{data:{path:o},error:null};{let e=yield h.json();return{data:null,error:e}}}catch(e){if(eh(e))return{data:null,error:e};throw e}})}upload(e,t,r){return eS(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,s){return eS(this,void 0,void 0,function*(){let i=this._removeEmptyFolders(e),n=this._getFinalPath(i),a=new URL(this.url+`/object/upload/sign/${n}`);a.searchParams.set("token",t);try{let e;let t=Object.assign({upsert:eE.upsert},s),n=Object.assign(Object.assign({},this.headers),{"x-upsert":String(t.upsert)});"undefined"!=typeof Blob&&r instanceof Blob?((e=new FormData).append("cacheControl",t.cacheControl),e.append("",r)):"undefined"!=typeof FormData&&r instanceof FormData?(e=r).append("cacheControl",t.cacheControl):(e=r,n["cache-control"]=`max-age=${t.cacheControl}`,n["content-type"]=t.contentType);let o=yield this.fetch(a.toString(),{method:"PUT",body:e,headers:n});if(o.ok)return{data:{path:i},error:null};{let e=yield o.json();return{data:null,error:e}}}catch(e){if(eh(e))return{data:null,error:e};throw e}})}createSignedUploadUrl(e){return eS(this,void 0,void 0,function*(){try{let t=this._getFinalPath(e),r=yield ew(this.fetch,`${this.url}/object/upload/sign/${t}`,{},{headers:this.headers}),s=new URL(this.url+r.url),i=s.searchParams.get("token");if(!i)throw new el("No token returned by API");return{data:{signedUrl:s.toString(),path:e,token:i},error:null}}catch(e){if(eh(e))return{data:null,error:e};throw e}})}update(e,t,r){return eS(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t){return eS(this,void 0,void 0,function*(){try{let r=yield ew(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t},{headers:this.headers});return{data:r,error:null}}catch(e){if(eh(e))return{data:null,error:e};throw e}})}copy(e,t){return eS(this,void 0,void 0,function*(){try{let r=yield ew(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t},{headers:this.headers});return{data:{path:r.Key},error:null}}catch(e){if(eh(e))return{data:null,error:e};throw e}})}createSignedUrl(e,t,r){return eS(this,void 0,void 0,function*(){try{let s=this._getFinalPath(e),i=yield ew(this.fetch,`${this.url}/object/sign/${s}`,Object.assign({expiresIn:t},(null==r?void 0:r.transform)?{transform:r.transform}:{}),{headers:this.headers}),n=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"",a=encodeURI(`${this.url}${i.signedURL}${n}`);return{data:i={signedUrl:a},error:null}}catch(e){if(eh(e))return{data:null,error:e};throw e}})}createSignedUrls(e,t,r){return eS(this,void 0,void 0,function*(){try{let s=yield ew(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return{data:s.map(e=>Object.assign(Object.assign({},e),{signedUrl:e.signedURL?encodeURI(`${this.url}${e.signedURL}${i}`):null})),error:null}}catch(e){if(eh(e))return{data:null,error:e};throw e}})}download(e,t){return eS(this,void 0,void 0,function*(){let r=void 0!==(null==t?void 0:t.transform),s=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),i=s?`?${s}`:"";try{let t=this._getFinalPath(e),s=yield e_(this.fetch,`${this.url}/${r?"render/image/authenticated":"object"}/${t}${i}`,{headers:this.headers,noResolveJson:!0}),n=yield s.blob();return{data:n,error:null}}catch(e){if(eh(e))return{data:null,error:e};throw e}})}getPublicUrl(e,t){let r=this._getFinalPath(e),s=[],i=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==i&&s.push(i);let n=void 0!==(null==t?void 0:t.transform),a=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==a&&s.push(a);let o=s.join("&");return""!==o&&(o=`?${o}`),{data:{publicUrl:encodeURI(`${this.url}/${n?"render/image":"object"}/public/${r}${o}`)}}}remove(e){return eS(this,void 0,void 0,function*(){try{let t=yield ek(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers});return{data:t,error:null}}catch(e){if(eh(e))return{data:null,error:e};throw e}})}list(e,t,r){return eS(this,void 0,void 0,function*(){try{let s=Object.assign(Object.assign(Object.assign({},eT),t),{prefix:e||""}),i=yield ew(this.fetch,`${this.url}/object/list/${this.bucketId}`,s,{headers:this.headers},r);return{data:i,error:null}}catch(e){if(eh(e))return{data:null,error:e};throw e}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}let ej={"X-Client-Info":"storage-js/2.5.3"};var eC=function(e,t,r,s){return new(r||(r=Promise))(function(i,n){function a(e){try{l(s.next(e))}catch(e){n(e)}}function o(e){try{l(s.throw(e))}catch(e){n(e)}}function l(e){var t;e.done?i(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(a,o)}l((s=s.apply(e,t||[])).next())})};class ex{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},ej),t),this.fetch=ef(r)}listBuckets(){return eC(this,void 0,void 0,function*(){try{let e=yield e_(this.fetch,`${this.url}/bucket`,{headers:this.headers});return{data:e,error:null}}catch(e){if(eh(e))return{data:null,error:e};throw e}})}getBucket(e){return eC(this,void 0,void 0,function*(){try{let t=yield e_(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers});return{data:t,error:null}}catch(e){if(eh(e))return{data:null,error:e};throw e}})}createBucket(e,t={public:!1}){return eC(this,void 0,void 0,function*(){try{let r=yield ew(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers});return{data:r,error:null}}catch(e){if(eh(e))return{data:null,error:e};throw e}})}updateBucket(e,t){return eC(this,void 0,void 0,function*(){try{let r=yield function(e,t,r,s,i){return eg(this,void 0,void 0,function*(){return eb(e,"PUT",t,s,void 0,r)})}(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers});return{data:r,error:null}}catch(e){if(eh(e))return{data:null,error:e};throw e}})}emptyBucket(e){return eC(this,void 0,void 0,function*(){try{let t=yield ew(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers});return{data:t,error:null}}catch(e){if(eh(e))return{data:null,error:e};throw e}})}deleteBucket(e){return eC(this,void 0,void 0,function*(){try{let t=yield ek(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers});return{data:t,error:null}}catch(e){if(eh(e))return{data:null,error:e};throw e}})}}class eP extends ex{constructor(e,t={},r){super(e,t,r)}from(e){return new eO(this.url,this.headers,e,this.fetch)}}var eA=r(9366),e$=r.n(eA);let eR=e=>{let t;return t=e||("undefined"==typeof fetch?e$():fetch),(...e)=>t(...e)},eI=()=>"undefined"==typeof Headers?eA.Headers:Headers,eU=(e,t,r)=>{let s=eR(r),i=eI();return(r,n)=>{var a,o,l,h;return a=void 0,o=void 0,l=void 0,h=function*(){var a;let o=null!==(a=yield t())&&void 0!==a?a:e,l=new i(null==n?void 0:n.headers);return l.has("apikey")||l.set("apikey",e),l.has("Authorization")||l.set("Authorization",`Bearer ${o}`),s(r,Object.assign(Object.assign({},n),{headers:l}))},new(l||(l=Promise))(function(e,t){function r(e){try{i(h.next(e))}catch(e){t(e)}}function s(e){try{i(h.throw(e))}catch(e){t(e)}}function i(t){var i;t.done?e(t.value):((i=t.value)instanceof l?i:new l(function(e){e(i)})).then(r,s)}i((h=h.apply(a,o||[])).next())})}},eL=()=>"undefined"!=typeof document,eN={tested:!1,writable:!1},eD=()=>{if(!eL())return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(eN.tested)return eN.writable;let e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),eN.tested=!0,eN.writable=!0}catch(e){eN.tested=!0,eN.writable=!1}return eN.writable};function eB(e){let t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{let e=new URLSearchParams(r.hash.substring(1));e.forEach((e,r)=>{t[r]=e})}catch(e){}return r.searchParams.forEach((e,r)=>{t[r]=e}),t}let eF=e=>{let t;return t=e||("undefined"==typeof fetch?(...e)=>Promise.resolve().then(r.t.bind(r,7992,23)).then(({default:t})=>t(...e)):fetch),(...e)=>t(...e)},eq=e=>"object"==typeof e&&null!==e&&"status"in e&&"ok"in e&&"json"in e&&"function"==typeof e.json,eM=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},eK=async(e,t)=>{let r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return r}},ez=async(e,t)=>{await e.removeItem(t)};class eJ{constructor(){this.promise=new eJ.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function eH(e){let t=e.split(".");if(3!==t.length)throw Error("JWT is not valid: not a JWT structure");if(!/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i.test(t[1]))throw Error("JWT is not valid: payload is not in base64url format");let r=t[1];return JSON.parse(function(e){let t,r,s,i,n,a,o;let l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h="",c=0;for(e=e.replace("-","+").replace("_","/");c<e.length;)i=l.indexOf(e.charAt(c++)),n=l.indexOf(e.charAt(c++)),a=l.indexOf(e.charAt(c++)),o=l.indexOf(e.charAt(c++)),t=i<<2|n>>4,r=(15&n)<<4|a>>2,s=(3&a)<<6|o,h+=String.fromCharCode(t),64!=a&&0!=r&&(h+=String.fromCharCode(r)),64!=o&&0!=s&&(h+=String.fromCharCode(s));return h}(r))}async function eG(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function eV(e){return("0"+e.toString(16)).substr(-2)}function eX(){let e=new Uint32Array(56);if("undefined"==typeof crypto){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length,r="";for(let s=0;s<56;s++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(e),Array.from(e,eV).join("")}async function eW(e){let t=new TextEncoder,r=t.encode(e),s=await crypto.subtle.digest("SHA-256",r),i=new Uint8Array(s);return Array.from(i).map(e=>String.fromCharCode(e)).join("")}async function eY(e){if("undefined"==typeof crypto)return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e;let t=await eW(e);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}eJ.promiseConstructor=Promise;class eQ extends Error{constructor(e,t){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t}}function eZ(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class e0 extends eQ{constructor(e,t){super(e,t),this.name="AuthApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class e1 extends eQ{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class e3 extends eQ{constructor(e,t,r){super(e),this.name=t,this.status=r}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class e2 extends e3{constructor(){super("Auth session missing!","AuthSessionMissingError",400)}}class e4 extends e3{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500)}}class e5 extends e3{constructor(e){super(e,"AuthInvalidCredentialsError",400)}}class e6 extends e3{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class e8 extends e3{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class e9 extends e3{constructor(e,t){super(e,"AuthRetryableFetchError",t)}}function e7(e){return eZ(e)&&"AuthRetryableFetchError"===e.name}var te=function(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&0>t.indexOf(s)&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,s=Object.getOwnPropertySymbols(e);i<s.length;i++)0>t.indexOf(s[i])&&Object.prototype.propertyIsEnumerable.call(e,s[i])&&(r[s[i]]=e[s[i]]);return r};let tt=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),tr=[502,503,504];async function ts(e){let t;if(!eq(e))throw new e9(tt(e),0);if(tr.includes(e.status))throw new e9(tt(e),e.status);try{t=await e.json()}catch(e){throw new e1(tt(e),e)}throw new e0(tt(t),e.status||500)}let ti=(e,t,r,s)=>{let i={method:e,headers:(null==t?void 0:t.headers)||{}};return"GET"===e?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==t?void 0:t.headers),i.body=JSON.stringify(s),Object.assign(Object.assign({},i),r))};async function tn(e,t,r,s){var i;let n=Object.assign({},null==s?void 0:s.headers);(null==s?void 0:s.jwt)&&(n.Authorization=`Bearer ${s.jwt}`);let a=null!==(i=null==s?void 0:s.query)&&void 0!==i?i:{};(null==s?void 0:s.redirectTo)&&(a.redirect_to=s.redirectTo);let o=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",l=await ta(e,t,r+o,{headers:n,noResolveJson:null==s?void 0:s.noResolveJson},{},null==s?void 0:s.body);return(null==s?void 0:s.xform)?null==s?void 0:s.xform(l):{data:Object.assign({},l),error:null}}async function ta(e,t,r,s,i,n){let a;let o=ti(t,s,i,n);try{a=await e(r,o)}catch(e){throw console.error(e),new e9(tt(e),0)}if(a.ok||await ts(a),null==s?void 0:s.noResolveJson)return a;try{return await a.json()}catch(e){await ts(e)}}function to(e){var t;let r=null;e.access_token&&e.refresh_token&&e.expires_in&&(r=Object.assign({},e),e.expires_at||(r.expires_at=function(e){let t=Math.round(Date.now()/1e3);return t+e}(e.expires_in)));let s=null!==(t=e.user)&&void 0!==t?t:e;return{data:{session:r,user:s},error:null}}function tl(e){var t;let r=null!==(t=e.user)&&void 0!==t?t:e;return{data:{user:r},error:null}}function th(e){return{data:e,error:null}}function tc(e){let{action_link:t,email_otp:r,hashed_token:s,redirect_to:i,verification_type:n}=e,a=te(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o=Object.assign({},a);return{data:{properties:{action_link:t,email_otp:r,hashed_token:s,redirect_to:i,verification_type:n},user:o},error:null}}function tu(e){return e}var td=function(e,t){var r={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&0>t.indexOf(s)&&(r[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,s=Object.getOwnPropertySymbols(e);i<s.length;i++)0>t.indexOf(s[i])&&Object.prototype.propertyIsEnumerable.call(e,s[i])&&(r[s[i]]=e[s[i]]);return r};class tf{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=eF(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await tn(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(eZ(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await tn(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:tl})}catch(e){if(eZ(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:t}=e,r=td(e,["options"]),s=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(s.new_email=null==r?void 0:r.newEmail,delete s.newEmail),await tn(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:s,headers:this.headers,xform:tc,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(eZ(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await tn(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:tl})}catch(e){if(eZ(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,r,s,i,n,a,o;try{let l={nextPage:null,lastPage:0,total:0},h=await tn(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!==(r=null===(t=null==e?void 0:e.page)||void 0===t?void 0:t.toString())&&void 0!==r?r:"",per_page:null!==(i=null===(s=null==e?void 0:e.perPage)||void 0===s?void 0:s.toString())&&void 0!==i?i:""},xform:tu});if(h.error)throw h.error;let c=await h.json(),u=null!==(n=h.headers.get("x-total-count"))&&void 0!==n?n:0,d=null!==(o=null===(a=h.headers.get("link"))||void 0===a?void 0:a.split(","))&&void 0!==o?o:[];return d.length>0&&(d.forEach(e=>{let t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(u)),{data:Object.assign(Object.assign({},c),l),error:null}}catch(e){if(eZ(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){try{return await tn(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:tl})}catch(e){if(eZ(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){try{return await tn(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:tl})}catch(e){if(eZ(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){try{return await tn(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:tl})}catch(e){if(eZ(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){try{let{data:t,error:r}=await tn(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(e){if(eZ(e))return{data:null,error:e};throw e}}async _deleteFactor(e){try{let t=await tn(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers});return{data:t,error:null}}catch(e){if(eZ(e))return{data:null,error:e};throw e}}}let tp="2.51.0",tg={"X-Client-Info":`gotrue-js/${tp}`};var ty={getItem:e=>eD()?globalThis.localStorage.getItem(e):null,setItem:(e,t)=>{eD()&&globalThis.localStorage.setItem(e,t)},removeItem:e=>{eD()&&globalThis.localStorage.removeItem(e)}};globalThis&&eD()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug");class tm extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}!function(){if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"undefined"!=typeof self&&(self.globalThis=self)}}();let tv={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:tg,flowType:"implicit",debug:!1};async function tb(e,t,r){return await r()}class t_{constructor(e){var t;this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.instanceID=t_.nextInstanceID,t_.nextInstanceID+=1,this.instanceID>0&&eL()&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");let r=Object.assign(Object.assign({},tv),e);if(this.logDebugMessages=r.debug,this.inMemorySession=null,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.persistSession=r.persistSession,this.storage=r.storage||ty,this.admin=new tf({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=eF(r.fetch),this.lock=r.lock||tb,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession&&this.storage===ty&&!eD()&&console.warn(`No storage option exists to persist the session, which may result in unexpected behavior when using auth.
2
- If you want to set persistSession to true, please provide a storage option or you may set persistSession to false to disable this warning.`),eL()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null===(t=this.broadcastChannel)||void 0===t||t.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&console.log(`GoTrueClient@${this.instanceID} (${tp}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){try{let e=!!eL()&&await this._isPKCEFlow();if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:r}=await this._getSessionFromURL(e);if(r)return this._debug("#_initialize()","error detecting session from URL",r),await this._removeSession(),{error:r};let{session:s,redirectType:i}=t;return this._debug("#_initialize()","detected session in URL",s,"redirect type",i),await this._saveSession(s),setTimeout(async()=>{"recovery"===i?await this._notifyAllSubscribers("PASSWORD_RECOVERY",s):await this._notifyAllSubscribers("SIGNED_IN",s)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){if(eZ(e))return{error:e};return{error:new e1("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signUp(e){var t,r,s;try{let i;if(await this._removeSession(),"email"in e){let{email:r,password:s,options:n}=e,a=null,o=null;if("pkce"===this.flowType){let e=eX();await eM(this.storage,`${this.storageKey}-code-verifier`,e),a=await eY(e),o=e===a?"plain":"s256"}i=await tn(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==n?void 0:n.emailRedirectTo,body:{email:r,password:s,data:null!==(t=null==n?void 0:n.data)&&void 0!==t?t:{},gotrue_meta_security:{captcha_token:null==n?void 0:n.captchaToken},code_challenge:a,code_challenge_method:o},xform:to})}else if("phone"in e){let{phone:t,password:n,options:a}=e;i=await tn(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:n,data:null!==(r=null==a?void 0:a.data)&&void 0!==r?r:{},channel:null!==(s=null==a?void 0:a.channel)&&void 0!==s?s:"sms",gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken}},xform:to})}else throw new e5("You must provide either an email or phone number and a password");let{data:n,error:a}=i;if(a||!n)return{data:{user:null,session:null},error:a};let o=n.session,l=n.user;return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",o)),{data:{user:l,session:o},error:null}}catch(e){if(eZ(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithPassword(e){try{let t;if(await this._removeSession(),"email"in e){let{email:r,password:s,options:i}=e;t=await tn(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:r,password:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:to})}else if("phone"in e){let{phone:r,password:s,options:i}=e;t=await tn(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:r,password:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:to})}else throw new e5("You must provide either an email or phone number and a password");let{data:r,error:s}=t;if(s)return{data:{user:null,session:null},error:s};if(!r||!r.session||!r.user)return{data:{user:null,session:null},error:new e4};return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:{user:r.user,session:r.session},error:s}}catch(e){if(eZ(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithOAuth(e){var t,r,s,i;return await this._removeSession(),await this._handleProviderSignIn(e.provider,{redirectTo:null===(t=e.options)||void 0===t?void 0:t.redirectTo,scopes:null===(r=e.options)||void 0===r?void 0:r.scopes,queryParams:null===(s=e.options)||void 0===s?void 0:s.queryParams,skipBrowserRedirect:null===(i=e.options)||void 0===i?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await eK(this.storage,`${this.storageKey}-code-verifier`),{data:r,error:s}=await tn(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:t},xform:to});return(await ez(this.storage,`${this.storageKey}-code-verifier`),s)?{data:{user:null,session:null},error:s}:r&&r.session&&r.user?(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:r,error:s}):{data:{user:null,session:null},error:new e4}}async signInWithIdToken(e){await this._removeSession();try{let{options:t,provider:r,token:s,access_token:i,nonce:n}=e,a=await tn(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:s,access_token:i,nonce:n,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:to}),{data:o,error:l}=a;if(l)return{data:{user:null,session:null},error:l};if(!o||!o.session||!o.user)return{data:{user:null,session:null},error:new e4};return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",o.session)),{data:o,error:l}}catch(e){if(eZ(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithOtp(e){var t,r,s,i,n;try{if(await this._removeSession(),"email"in e){let{email:s,options:i}=e,n=null,a=null;if("pkce"===this.flowType){let e=eX();await eM(this.storage,`${this.storageKey}-code-verifier`,e),n=await eY(e),a=e===n?"plain":"s256"}let{error:o}=await tn(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:s,data:null!==(t=null==i?void 0:i.data)&&void 0!==t?t:{},create_user:null===(r=null==i?void 0:i.shouldCreateUser)||void 0===r||r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:n,code_challenge_method:a},redirectTo:null==i?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:o}}if("phone"in e){let{phone:t,options:r}=e,{data:a,error:o}=await tn(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!==(s=null==r?void 0:r.data)&&void 0!==s?s:{},create_user:null===(i=null==r?void 0:r.shouldCreateUser)||void 0===i||i,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},channel:null!==(n=null==r?void 0:r.channel)&&void 0!==n?n:"sms"}});return{data:{user:null,session:null,messageId:null==a?void 0:a.message_id},error:o}}throw new e5("You must provide either an email or phone number.")}catch(e){if(eZ(e))return{data:{user:null,session:null},error:e};throw e}}async verifyOtp(e){var t,r;try{let s,i;"email_change"!==e.type&&"phone_change"!==e.type&&await this._removeSession(),"options"in e&&(s=null===(t=e.options)||void 0===t?void 0:t.redirectTo,i=null===(r=e.options)||void 0===r?void 0:r.captchaToken);let{data:n,error:a}=await tn(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:s,xform:to});if(a)throw a;if(!n)throw Error("An error occurred on token verification.");let o=n.session,l=n.user;return(null==o?void 0:o.access_token)&&(await this._saveSession(o),await this._notifyAllSubscribers("SIGNED_IN",o)),{data:{user:l,session:o},error:null}}catch(e){if(eZ(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithSSO(e){var t,r,s;try{return await this._removeSession(),await tn(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:null!==(r=null===(t=e.options)||void 0===t?void 0:t.redirectTo)&&void 0!==r?r:void 0}),(null===(s=null==e?void 0:e.options)||void 0===s?void 0:s.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0}),headers:this.headers,xform:th})}catch(e){if(eZ(e))return{data:null,error:e};throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new e2;let{error:s}=await tn(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:s}})}catch(e){if(eZ(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{"email_change"!=e.type&&"phone_change"!=e.type&&await this._removeSession();let t=`${this.url}/resend`;if("email"in e){let{email:r,type:s,options:i}=e,{error:n}=await tn(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},redirectTo:null==i?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:n}}if("phone"in e){let{phone:r,type:s,options:i}=e,{data:n,error:a}=await tn(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:null==n?void 0:n.message_id},error:a}}throw new e5("You must provide either an email or phone number and a type")}catch(e){if(eZ(e))return{data:{user:null,session:null},error:e};throw e}}async getSession(){return await this.initializePromise,this._acquireLock(-1,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){let e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch(e){}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){let e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",Error().stack);try{let e=null;if(this.persistSession){let t=await eK(this.storage,this.storageKey);this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession()))}else e=this.inMemorySession,this._debug("#getSession()","session from memory",e);if(!e)return{data:{session:null},error:null};let t=!!e.expires_at&&e.expires_at<=Date.now()/1e3;if(this._debug("#__loadSession()",`session has${t?"":" not"} expired`,"expires_at",e.expires_at),!t)return{data:{session:e},error:null};let{session:r,error:s}=await this._callRefreshToken(e.refresh_token);if(s)return{data:{session:null},error:s};return{data:{session:r},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{if(e)return await tn(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:tl});return await this._useSession(async e=>{var t,r;let{data:s,error:i}=e;if(i)throw i;return await tn(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!==(r=null===(t=s.session)||void 0===t?void 0:t.access_token)&&void 0!==r?r:void 0,xform:tl})})}catch(e){if(eZ(e))return{data:{user:null},error:e};throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{let{data:s,error:i}=r;if(i)throw i;if(!s.session)throw new e2;let n=s.session,a=null,o=null;if("pkce"===this.flowType&&null!=e.email){let e=eX();await eM(this.storage,`${this.storageKey}-code-verifier`,e),a=await eY(e),o=e===a?"plain":"s256"}let{data:l,error:h}=await tn(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:o}),jwt:n.access_token,xform:tl});if(h)throw h;return n.user=l.user,await this._saveSession(n),await this._notifyAllSubscribers("USER_UPDATED",n),{data:{user:n.user},error:null}})}catch(e){if(eZ(e))return{data:{user:null},error:e};throw e}}_decodeJWT(e){return eH(e)}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new e2;let t=Date.now()/1e3,r=t,s=!0,i=null,n=eH(e.access_token);if(n.exp&&(s=(r=n.exp)<=t),s){let{session:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return{data:{user:null,session:null},error:r};if(!t)return{data:{user:null,session:null},error:null};i=t}else{let{data:s,error:n}=await this._getUser(e.access_token);if(n)throw n;i={access_token:e.access_token,refresh_token:e.refresh_token,user:s.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(e){if(eZ(e))return{data:{session:null,user:null},error:e};throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:s,error:i}=t;if(i)throw i;e=null!==(r=s.session)&&void 0!==r?r:void 0}if(!(null==e?void 0:e.refresh_token))throw new e2;let{session:s,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:s?{data:{user:s.user,session:s},error:null}:{data:{user:null,session:null},error:null}})}catch(e){if(eZ(e))return{data:{user:null,session:null},error:e};throw e}}async _getSessionFromURL(e){try{if(!eL())throw new e6("No browser detected.");if("implicit"!==this.flowType||this._isImplicitGrantFlow()){if("pkce"==this.flowType&&!e)throw new e8("Not a valid PKCE flow url.")}else throw new e6("Not a valid implicit grant flow url.");let t=eB(window.location.href);if(e){if(!t.code)throw new e8("No code detected.");let{data:e,error:r}=await this._exchangeCodeForSession(t.code);if(r)throw r;let s=new URL(window.location.href);return s.searchParams.delete("code"),window.history.replaceState(window.history.state,"",s.toString()),{data:{session:e.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new e6(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:r,provider_refresh_token:s,access_token:i,refresh_token:n,expires_in:a,expires_at:o,token_type:l}=t;if(!i||!a||!n||!l)throw new e6("No session defined in URL");let h=Math.round(Date.now()/1e3),c=parseInt(a),u=h+c;o&&(u=parseInt(o));let d=u-h;1e3*d<=3e4&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${d}s, should have been closer to ${c}s`);let f=u-c;h-f>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",f,u,h):h-f<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",f,u,h);let{data:p,error:g}=await this._getUser(i);if(g)throw g;let y={provider_token:r,provider_refresh_token:s,access_token:i,expires_in:c,expires_at:u,refresh_token:n,token_type:l,user:p.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:y,redirectType:t.type},error:null}}catch(e){if(eZ(e))return{data:{session:null,redirectType:null},error:e};throw e}}_isImplicitGrantFlow(){let e=eB(window.location.href);return!!(eL()&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=eB(window.location.href),t=await eK(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return{error:i};let n=null===(r=s.session)||void 0===r?void 0:r.access_token;if(n){let{error:t}=await this.admin.signOut(n,e);if(t&&!(eZ(t)&&"AuthApiError"===t.name&&(404===t.status||401===t.status)))return{error:t}}return"others"!==e&&(await this._removeSession(),await ez(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>{await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,s;try{let{data:{session:s},error:i}=t;if(i)throw i;await (null===(r=this.stateChangeEmitters.get(e))||void 0===r?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(t){await (null===(s=this.stateChangeEmitters.get(e))||void 0===s?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),console.error(t)}})}async resetPasswordForEmail(e,t={}){let r=null,s=null;if("pkce"===this.flowType){let e=eX();await eM(this.storage,`${this.storageKey}-code-verifier`,e),r=await eY(e),s=e===r?"plain":"s256"}try{return await tn(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(eZ(e))return{data:null,error:e};throw e}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{let r=Date.now();return await function(e,t){let r=new Promise((r,s)=>{(async()=>{for(let i=0;i<1/0;i++)try{let s=await e(i);if(!t(i,null,s)){r(s);return}}catch(e){if(!t(i,e)){s(e);return}}})()});return r}(async r=>(await eG(200*r),this._debug(t,"refreshing attempt",r),await tn(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:to})),(e,t,s)=>s&&s.error&&e7(s.error)&&Date.now()+(e+1)*200-r<3e4)}catch(e){if(this._debug(t,"error",e),eZ(e))return{data:{session:null,user:null},error:e};throw e}finally{this._debug(t,"end")}}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider(e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),eL()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let r=await eK(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r)){this._debug(t,"session is not valid"),null!==r&&await this._removeSession();return}let s=Math.round(Date.now()/1e3),i=(null!==(e=r.expires_at)&&void 0!==e?e:1/0)<s+10;if(this._debug(t,`session has${i?"":" not"} expired with margin of 10s`),i){if(this.autoRefreshToken&&r.refresh_token){let{error:e}=await this._callRefreshToken(r.refresh_token);e&&(console.error(e),e7(e)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(e){this._debug(t,"error",e),console.error(e);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new e2;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(s,"begin");try{this.refreshingDeferred=new eJ;let{data:t,error:r}=await this._refreshAccessToken(e);if(r)throw r;if(!t.session)throw new e2;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);let s={session:t.session,error:null};return this.refreshingDeferred.resolve(s),s}catch(e){if(this._debug(s,"error",e),eZ(e)){let r={session:null,error:e};return null===(t=this.refreshingDeferred)||void 0===t||t.resolve(r),r}throw null===(r=this.refreshingDeferred)||void 0===r||r.reject(e),e}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(e,t,r=!0){let s=`#_notifyAllSubscribers(${e})`;this._debug(s,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let s=[],i=Array.from(this.stateChangeEmitters.values()).map(async r=>{try{await r.callback(e,t)}catch(e){s.push(e)}});if(await Promise.all(i),s.length>0){for(let e=0;e<s.length;e+=1)console.error(s[e]);throw s[0]}}finally{this._debug(s,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.persistSession||(this.inMemorySession=e),this.persistSession&&e.expires_at&&await this._persistSession(e)}_persistSession(e){return this._debug("#_persistSession()",e),eM(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),this.persistSession?await ez(this.storage,this.storageKey):this.inMemorySession=null}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&eL()&&(null==window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),3e4);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"undefined"!=typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((1e3*r.expires_at-e)/3e4);this._debug("#_autoRefreshTokenTick()",`access token expires in ${s} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),s<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof tm)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!eL()||!(null==window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),null==window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if("visible"!==document.visibilityState){this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t){let r=[`provider=${encodeURIComponent(e)}`];if((null==t?void 0:t.redirectTo)&&r.push(`redirect_to=${encodeURIComponent(t.redirectTo)}`),(null==t?void 0:t.scopes)&&r.push(`scopes=${encodeURIComponent(t.scopes)}`),"pkce"===this.flowType){let e=eX();await eM(this.storage,`${this.storageKey}-code-verifier`,e);let t=await eY(e),s=e===t?"plain":"s256";this._debug("PKCE","code verifier",`${e.substring(0,5)}...`,"code challenge",t,"method",s);let i=new URLSearchParams({code_challenge:`${encodeURIComponent(t)}`,code_challenge_method:`${encodeURIComponent(s)}`});r.push(i.toString())}if(null==t?void 0:t.queryParams){let e=new URLSearchParams(t.queryParams);r.push(e.toString())}return`${this.url}/authorize?${r.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;return i?{data:null,error:i}:await tn(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token})})}catch(e){if(eZ(e))return{data:null,error:e};throw e}}async _enroll(e){try{return await this._useSession(async t=>{var r,s;let{data:i,error:n}=t;if(n)return{data:null,error:n};let{data:a,error:o}=await tn(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:null===(r=null==i?void 0:i.session)||void 0===r?void 0:r.access_token});return o?{data:null,error:o}:((null===(s=null==a?void 0:a.totp)||void 0===s?void 0:s.qr_code)&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(e){if(eZ(e))return{data:null,error:e};throw e}}async _verify(e){try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;if(i)return{data:null,error:i};let{data:n,error:a}=await tn(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+n.expires_in},n)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",n),{data:n,error:a})})}catch(e){if(eZ(e))return{data:null,error:e};throw e}}async _challenge(e){try{return await this._useSession(async t=>{var r;let{data:s,error:i}=t;return i?{data:null,error:i}:await tn(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:null===(r=null==s?void 0:s.session)||void 0===r?void 0:r.access_token})})}catch(e){if(eZ(e))return{data:null,error:e};throw e}}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this._getUser();if(t)return{data:null,error:t};let r=(null==e?void 0:e.factors)||[],s=r.filter(e=>"totp"===e.factor_type&&"verified"===e.status);return{data:{all:r,totp:s},error:null}}async _getAuthenticatorAssuranceLevel(){return await this._useSession(async e=>{var t,r;let{data:{session:s},error:i}=e;if(i)return{data:null,error:i};if(!s)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let n=this._decodeJWT(s.access_token),a=null;n.aal&&(a=n.aal);let o=a,l=null!==(r=null===(t=s.user.factors)||void 0===t?void 0:t.filter(e=>"verified"===e.status))&&void 0!==r?r:[];l.length>0&&(o="aal2");let h=n.amr||[];return{data:{currentLevel:a,nextLevel:o,currentAuthenticationMethods:h},error:null}})}}t_.nextInstanceID=0;class tw extends t_{constructor(e){super(e)}}let tk={headers:{"X-Client-Info":"supabase-js/2.33.1"}},tS={schema:"public"},tT={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},tE={};class tO{constructor(e,t,r){var s,i,n,a,o,l,h,c;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw Error("supabaseUrl is required.");if(!t)throw Error("supabaseKey is required.");let u=e.replace(/\/$/,"");this.realtimeUrl=`${u}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${u}/auth/v1`,this.storageUrl=`${u}/storage/v1`,this.functionsUrl=`${u}/functions/v1`;let d=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,f={db:tS,realtime:tE,auth:Object.assign(Object.assign({},tT),{storageKey:d}),global:tk},p=function(e,t){let{db:r,auth:s,realtime:i,global:n}=e,{db:a,auth:o,realtime:l,global:h}=t;return{db:Object.assign(Object.assign({},a),r),auth:Object.assign(Object.assign({},o),s),realtime:Object.assign(Object.assign({},l),i),global:Object.assign(Object.assign({},h),n)}}(null!=r?r:{},f);this.storageKey=null!==(i=null===(s=p.auth)||void 0===s?void 0:s.storageKey)&&void 0!==i?i:"",this.headers=null!==(a=null===(n=p.global)||void 0===n?void 0:n.headers)&&void 0!==a?a:{},this.auth=this._initSupabaseAuthClient(null!==(o=p.auth)&&void 0!==o?o:{},this.headers,null===(l=p.global)||void 0===l?void 0:l.fetch),this.fetch=eU(t,this._getAccessToken.bind(this),null===(h=p.global)||void 0===h?void 0:h.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},p.realtime)),this.rest=new q(`${u}/rest/v1`,{headers:this.headers,schema:null===(c=p.db)||void 0===c?void 0:c.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new R(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new eP(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t,r,s,i,n;return r=this,s=void 0,i=void 0,n=function*(){let{data:r}=yield this.auth.getSession();return null!==(t=null===(e=r.session)||void 0===e?void 0:e.access_token)&&void 0!==t?t:null},new(i||(i=Promise))(function(e,t){function a(e){try{l(n.next(e))}catch(e){t(e)}}function o(e){try{l(n.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):((r=t.value)instanceof i?r:new i(function(e){e(r)})).then(a,o)}l((n=n.apply(r,s||[])).next())})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,storageKey:i,flowType:n,debug:a},o,l){let h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new tw({url:this.authUrl,headers:Object.assign(Object.assign({},h),o),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:s,flowType:n,debug:a,fetch:l})}_initRealtimeClient(e){return new eo(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,r){("TOKEN_REFRESHED"===e||"SIGNED_IN"===e)&&this.changedAccessToken!==r?(this.realtime.setAuth(null!=r?r:null),this.changedAccessToken=r):"SIGNED_OUT"===e&&(this.realtime.setAuth(this.supabaseKey),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0)}}let tj=(e,t,r)=>new tO(e,t,r);var tC=Object.create,tx=Object.defineProperty,tP=Object.getOwnPropertyDescriptor,tA=Object.getOwnPropertyNames,t$=Object.getPrototypeOf,tR=Object.prototype.hasOwnProperty,tI=(e,t,r,s)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of tA(t))tR.call(e,i)||i===r||tx(e,i,{get:()=>t[i],enumerable:!(s=tP(t,i))||s.enumerable});return e},tU=(e,t,r)=>(r=null!=e?tC(t$(e)):{},tI(!t&&e&&e.__esModule?r:tx(r,"default",{value:e,enumerable:!0}),e)),tL=(p={"../../node_modules/.pnpm/cookie@0.5.0/node_modules/cookie/index.js"(e){e.parse=function(e,t){if("string"!=typeof e)throw TypeError("argument str must be a string");for(var r={},i=(t||{}).decode||s,n=0;n<e.length;){var a=e.indexOf("=",n);if(-1===a)break;var o=e.indexOf(";",n);if(-1===o)o=e.length;else if(o<a){n=e.lastIndexOf(";",a-1)+1;continue}var l=e.slice(n,a).trim();if(void 0===r[l]){var h=e.slice(a+1,o).trim();34===h.charCodeAt(0)&&(h=h.slice(1,-1)),r[l]=function(e,t){try{return t(e)}catch(t){return e}}(h,i)}n=o+1}return r},e.serialize=function(e,s,n){var a=n||{},o=a.encode||i;if("function"!=typeof o)throw TypeError("option encode is invalid");if(!r.test(e))throw TypeError("argument name is invalid");var l=o(s);if(l&&!r.test(l))throw TypeError("argument val is invalid");var h=e+"="+l;if(null!=a.maxAge){var c=a.maxAge-0;if(isNaN(c)||!isFinite(c))throw TypeError("option maxAge is invalid");h+="; Max-Age="+Math.floor(c)}if(a.domain){if(!r.test(a.domain))throw TypeError("option domain is invalid");h+="; Domain="+a.domain}if(a.path){if(!r.test(a.path))throw TypeError("option path is invalid");h+="; Path="+a.path}if(a.expires){var u=a.expires;if("[object Date]"!==t.call(u)&&!(u instanceof Date)||isNaN(u.valueOf()))throw TypeError("option expires is invalid");h+="; Expires="+u.toUTCString()}if(a.httpOnly&&(h+="; HttpOnly"),a.secure&&(h+="; Secure"),a.priority)switch("string"==typeof a.priority?a.priority.toLowerCase():a.priority){case"low":h+="; Priority=Low";break;case"medium":h+="; Priority=Medium";break;case"high":h+="; Priority=High";break;default:throw TypeError("option priority is invalid")}if(a.sameSite)switch("string"==typeof a.sameSite?a.sameSite.toLowerCase():a.sameSite){case!0:case"strict":h+="; SameSite=Strict";break;case"lax":h+="; SameSite=Lax";break;case"none":h+="; SameSite=None";break;default:throw TypeError("option sameSite is invalid")}return h};var t=Object.prototype.toString,r=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function s(e){return -1!==e.indexOf("%")?decodeURIComponent(e):e}function i(e){return encodeURIComponent(e)}}},function(){return g||(0,p[tA(p)[0]])((g={exports:{}}).exports,g),g.exports}),tN=tU(tL()),tD=tU(tL());function tB(e){if(!e)return null;try{let t=JSON.parse(e);if(!t)return null;if("Object"===t.constructor.name)return t;if("Array"!==t.constructor.name)throw Error(`Unexpected format: ${t.constructor.name}`);let[r,s,i]=t[0].split("."),n=j(s),a=new TextDecoder,{exp:o,sub:l,...h}=JSON.parse(a.decode(n));return{expires_at:o,expires_in:o-Math.round(Date.now()/1e3),token_type:"bearer",access_token:t[0],refresh_token:t[1],provider_token:t[2],provider_refresh_token:t[3],user:{id:l,factors:t[4],...h}}}catch(e){return console.warn("Failed to parse cookie string:",e),null}}function tF(e){var t;return JSON.stringify([e.access_token,e.refresh_token,e.provider_token,e.provider_refresh_token,(null==(t=e.user)?void 0:t.factors)??null])}function tq(){return"undefined"!=typeof window&&void 0!==window.document}var tM={path:"/",maxAge:31536e6},tK=class{constructor(e){this.cookieOptions={...tM,...e}}getItem(e){let t=this.getCookie(e);return t?e.endsWith("-code-verifier")?t:JSON.stringify(tB(t)):null}setItem(e,t){if(e.endsWith("-code-verifier")){this.setCookie(e,t);return}let r=JSON.parse(t),s=tF(r);this.setCookie(e,s)}removeItem(e){this.deleteCookie(e)}},tz=class extends tK{constructor(e){super(e)}getCookie(e){if(!tq())return null;let t=(0,tN.parse)(document.cookie);return t[e]}setCookie(e,t){if(!tq())return null;document.cookie=(0,tN.serialize)(e,t,{...this.cookieOptions,httpOnly:!1})}deleteCookie(e){if(!tq())return null;document.cookie=(0,tN.serialize)(e,"",{...this.cookieOptions,maxAge:0,httpOnly:!1})}};function tJ(e,t,r){var s;let i=tq();return tj(e,t,{...r,auth:{flowType:"pkce",autoRefreshToken:i,detectSessionInUrl:i,persistSession:!0,storage:r.auth.storage,...(null==(s=r.auth)?void 0:s.storageKey)?{storageKey:r.auth.storageKey}:{}}})}var tH=tD.parse,tG=tD.serialize;/*!
3
- * cookie
4
- * Copyright(c) 2012-2014 Roman Shtylman
5
- * Copyright(c) 2015 Douglas Christopher Wilson
6
- * MIT Licensed
7
- */},2151:function(e){"use strict";e.exports={version:"1.0.34"}}}]);
@@ -1 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[466],{8556:function(n,e,u){Promise.resolve().then(u.t.bind(u,4116,23))},4116:function(){}},function(n){n.O(0,[971,596,744],function(){return n(n.s=8556)}),_N_E=n.O()}]);
@@ -1 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[11],{9716:function(e,n,s){Promise.resolve().then(s.t.bind(s,6685,23)),Promise.resolve().then(s.bind(s,9952))}},function(e){e.O(0,[674,293,808,548,82,420,975,886,683,631,782,952,971,596,744],function(){return e(e.s=9716)}),_N_E=e.O()}]);
@@ -1 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[185],{9444:function(e,t,n){Promise.resolve().then(n.bind(n,2112)),Promise.resolve().then(n.t.bind(n,8384,23)),Promise.resolve().then(n.t.bind(n,2471,23))},2112:function(e,t,n){"use strict";n.r(t),n.d(t,{PageShell:function(){return Z}});var r=n(7437),s=n(2265),i=n(2135),o=n(606),a=n(5573),l=n(3571),u=n(1396),c=n.n(u),d=n(3457),h=n(4033),f=n(6691),m=n.n(f),x=n(6507);function g(){return(0,r.jsxs)(x.Z,{className:"logo",children:[(0,r.jsx)(m(),{width:25,height:25,src:"/logo.svg",alt:"Promptfoo logo"})," ",(0,r.jsx)("span",{children:"promptfoo"})]})}n(1320);var j=n(3283),p=n(3375),v=n(5507),b=n(2653);function E(){let{user:e,logout:t}=(0,l.aC)(),[n,i]=s.useState(null),o=async()=>{null==t||t(),a()},a=()=>{i(null)};return e?(0,r.jsxs)("div",{children:[(0,r.jsx)(b.Z,{edge:"end","aria-label":"account of current user","aria-controls":"menu-appbar","aria-haspopup":"true",onClick:e=>{i(e.currentTarget)},color:"inherit",children:(0,r.jsx)(j.Z,{sx:{width:"1em",height:"1em",bgcolor:"#1976d2"}})}),(0,r.jsxs)(p.Z,{id:"menu-appbar",anchorEl:n,anchorOrigin:{vertical:"top",horizontal:"right"},keepMounted:!0,transformOrigin:{vertical:"top",horizontal:"right"},open:!!n,onClose:a,children:[(0,r.jsxs)(v.Z,{disabled:!0,children:["Logged in as ",e.email]}),(0,r.jsx)(v.Z,{onClick:o,children:"Logout"})]})]}):(0,r.jsx)(c(),{href:"/auth/signup/",children:(0,r.jsx)(b.Z,{edge:"end","aria-label":"User not logged in","aria-controls":"menu-appbar","aria-haspopup":"true",color:"inherit",children:(0,r.jsx)(j.Z,{sx:{width:"1em",height:"1em"}})})})}var _=n(9864),k=n(7028);function N(e){let{darkMode:t,onToggleDarkMode:n}=e;return(0,r.jsx)("div",{className:"dark-mode-toggle",onClick:n,children:t?(0,r.jsx)(_.Z,{}):(0,r.jsx)(k.Z,{})})}n(2794);var O=n(279);n(5154);var C=n(7580);function P(e){let{href:t,label:n}=e,s=(0,h.usePathname)()||"";return(0,r.jsx)(c(),{href:t,className:s.startsWith(t)?"active":"",children:n})}function S(e){let{darkMode:t,onToggleDarkMode:n}=e;return C.env.NEXT_PUBLIC_NO_BROWSING?(0,r.jsxs)(d.Z,{direction:"row",spacing:2,className:"nav",children:[(0,r.jsx)(g,{}),(0,r.jsx)(N,{darkMode:t,onToggleDarkMode:n})]}):(0,r.jsxs)(d.Z,{direction:"row",spacing:2,className:"nav",children:[(0,r.jsx)(g,{}),(0,r.jsx)(P,{href:"/setup",label:"New Eval"}),(0,r.jsx)(P,{href:"/eval",label:"Evals"}),(0,r.jsx)(P,{href:"/prompts",label:"Prompts"}),(0,r.jsx)(P,{href:"/datasets",label:"Datasets"}),(0,r.jsxs)("div",{className:"right-aligned",children:[O.Ox?null:(0,r.jsx)(E,{}),(0,r.jsx)(N,{darkMode:t,onToggleDarkMode:n})]})]})}function Z(e){let{children:t}=e,n=(0,i.Z)("(prefers-color-scheme: dark)"),[u,c]=s.useState(n),d=s.useMemo(()=>(0,o.Z)({typography:{fontFamily:"inherit"},palette:{mode:u||n?"dark":"light"}}),[u,n]);return s.useEffect(()=>{n&&document.documentElement.setAttribute("data-theme","dark")},[n]),(0,r.jsx)(s.StrictMode,{children:(0,r.jsx)(a.Z,{theme:d,children:(0,r.jsx)(l.Ho,{children:(0,r.jsxs)(T,{children:[(0,r.jsx)(S,{darkMode:u,onToggleDarkMode:()=>{c(!u),u?document.documentElement.removeAttribute("data-theme"):document.documentElement.setAttribute("data-theme","dark")}}),(0,r.jsx)("div",{children:t})]})})})})}function T(e){let{children:t}=e;return(0,r.jsx)("div",{children:t})}n(5587)},279:function(e,t,n){"use strict";n.d(t,{Ox:function(){return i},T8:function(){return s},eA:function(){return o}});var r=n(7580);let s=!r.env.NEXT_PUBLIC_PROMPTFOO_BUILD_STANDALONE_SERVER,i=!!r.env.NEXT_PUBLIC_PROMPTFOO_USE_SUPABASE,o=""},3571:function(e,t,n){"use strict";n.d(t,{Ho:function(){return d},OQ:function(){return o},aC:function(){return l}});var r=n(7437),s=n(2265),i=n(3082);let o=(0,i.createClientComponentClient)(),a=(0,s.createContext)({}),l=()=>(0,s.useContext)(a),u=(e,t)=>o.auth.signInWithPassword({email:e,password:t}),c=()=>o.auth.signOut(),d=e=>{let{children:t}=e,[n,i]=(0,s.useState)(null),[l,d]=(0,s.useState)(!1),h=(0,s.useCallback)(async()=>{let{data:e,error:t}=await o.auth.refreshSession();e&&i(e.user)},[]);return(0,s.useEffect)(()=>{h();let{data:e}=o.auth.onAuthStateChange(async(e,t)=>{"PASSWORD_RECOVERY"==e?d(!1):"SIGNED_IN"===e&&t?(i(t.user),d(!0)):"SIGNED_OUT"===e&&(d(!1),i(null))});return()=>{e.subscription.unsubscribe()}},[h]),(0,r.jsx)(a.Provider,{value:{loggedIn:l,user:n,login:u,logout:c},children:t})}},2794:function(){},1320:function(){},5154:function(){},5587:function(){},2471:function(){}},function(e){e.O(0,[293,548,82,886,445,971,596,744],function(){return e(e.s=9444)}),_N_E=e.O()}]);
@@ -1 +0,0 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[413],{875:function(e,t,n){Promise.resolve().then(n.bind(n,2378))},2378:function(e,t,n){"use strict";n.r(t),n.d(t,{default:function(){return ed}});var a=n(7437),r=n(2265),i=n(5551),l=n(8938),s=n(3226),o=n(6507),c=n(3457),d=n(9394),p=n(2834),u=n(6337),h=n(4173),x=n(1797),m=n(4740),f=n(4033),j=n(6882),g=n(1938),v=n(279),Z=()=>{let e=(0,f.useRouter)(),{env:t,description:n,providers:l,prompts:s,testCases:o}=(0,g.o)(),[c,d]=(0,r.useState)(!1),[p,u]=(0,r.useState)(0),h=async()=>{d(!0);try{let a=await fetch("".concat(v.eA,"/api/eval/job/"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({env:t,description:n,providers:l,prompts:s,tests:o})});if(!a.ok)throw Error("HTTP error! status: ".concat(a.status));let r=await a.json(),i=setInterval(async()=>{let t=await fetch("".concat(v.eA,"/api/eval/job/").concat(r.id,"/"));if(!t.ok)throw clearInterval(i),Error("HTTP error! status: ".concat(t.status));let n=await t.json();if("complete"===n.status)clearInterval(i),d(!1),v.T8?e.push("/eval"):e.push("/eval/remote:".concat(encodeURIComponent(r.id)));else if("failed"===n.status)throw clearInterval(i),d(!1),Error("Job failed");else{let e=0===n.total?0:Math.round(n.progress/n.total*100);u(e)}},1e3)}catch(e){console.error(e),d(!1),alert("An error occurred: ".concat(e.message))}};return(0,a.jsx)(i.Z,{variant:"contained",color:"primary",onClick:h,disabled:c,children:c?(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(j.Z,{size:24,sx:{marginRight:2}}),p.toFixed(0),"% complete"]}):"Run Evaluation"})},b=n(2057),y=n(8768),C=n(5873),_=n(1975),k=n(3295),A=()=>{let{env:e,setEnv:t}=(0,g.o)(),[n,l]=(0,r.useState)(!1),[s,o]=(0,r.useState)(e),c=()=>{l(!1)};return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(i.Z,{variant:"outlined",startIcon:(0,a.jsx)(k.Z,{}),onClick:()=>{l(!0)},children:"API keys"}),(0,a.jsxs)(d.Z,{open:n,onClose:c,fullWidth:!0,maxWidth:"md",children:[(0,a.jsx)(x.Z,{children:"Provider settings"}),(0,a.jsxs)(u.Z,{children:[(0,a.jsxs)(b.Z,{defaultExpanded:!0,children:[(0,a.jsx)(C.Z,{children:"OpenAI"}),(0,a.jsxs)(y.Z,{children:[(0,a.jsx)(_.Z,{label:"OpenAI API key",fullWidth:!0,margin:"normal",value:s.OPENAI_API_KEY,onChange:e=>o({...s,OPENAI_API_KEY:e.target.value})}),(0,a.jsx)(_.Z,{label:"OpenAI API host",fullWidth:!0,margin:"normal",value:s.OPENAI_API_HOST,onChange:e=>o({...s,OPENAI_API_HOST:e.target.value})}),(0,a.jsx)(_.Z,{label:"OpenAI organization",fullWidth:!0,margin:"normal",value:s.OPENAI_ORGANIZATION,onChange:e=>o({...s,OPENAI_ORGANIZATION:e.target.value})})]})]}),(0,a.jsxs)(b.Z,{children:[(0,a.jsx)(C.Z,{children:"Azure"}),(0,a.jsx)(y.Z,{children:(0,a.jsx)(_.Z,{label:"Azure API key",fullWidth:!0,margin:"normal",value:s.AZURE_OPENAI_API_KEY,onChange:e=>o({...s,AZURE_OPENAI_API_KEY:e.target.value})})})]}),(0,a.jsxs)(b.Z,{children:[(0,a.jsx)(C.Z,{children:"Amazon Bedrock"}),(0,a.jsx)(y.Z,{children:(0,a.jsx)(_.Z,{label:"Bedrock Region",fullWidth:!0,margin:"normal",value:s.AWS_BEDROCK_REGION,onChange:e=>o({...s,AWS_BEDROCK_REGION:e.target.value})})})]}),(0,a.jsxs)(b.Z,{children:[(0,a.jsx)(C.Z,{children:"Anthropic"}),(0,a.jsx)(y.Z,{children:(0,a.jsx)(_.Z,{label:"Anthropic API key",fullWidth:!0,margin:"normal",value:s.ANTHROPIC_API_KEY,onChange:e=>o({...s,ANTHROPIC_API_KEY:e.target.value})})})]}),(0,a.jsxs)(b.Z,{children:[(0,a.jsx)(C.Z,{children:"Google Vertex AI"}),(0,a.jsx)(y.Z,{children:(0,a.jsx)(_.Z,{label:"Vertex API Key",fullWidth:!0,margin:"normal",value:s.VERTEX_API_KEY,onChange:e=>o({...s,VERTEX_API_KEY:e.target.value})})}),(0,a.jsx)(y.Z,{children:(0,a.jsx)(_.Z,{label:"Vertex Project ID",fullWidth:!0,margin:"normal",value:s.VERTEX_PROJECT_ID,onChange:e=>o({...s,VERTEX_PROJECT_ID:e.target.value})})}),(0,a.jsx)(y.Z,{children:(0,a.jsx)(_.Z,{label:"Vertex Region",fullWidth:!0,margin:"normal",value:s.VERTEX_REGION,onChange:e=>o({...s,VERTEX_REGION:e.target.value})})})]}),(0,a.jsxs)(b.Z,{children:[(0,a.jsx)(C.Z,{children:"Replicate"}),(0,a.jsx)(y.Z,{children:(0,a.jsx)(_.Z,{label:"Replicate API key",fullWidth:!0,margin:"normal",value:s.REPLICATE_API_KEY,onChange:e=>o({...s,REPLICATE_API_KEY:e.target.value})})})]})]}),(0,a.jsxs)(p.Z,{children:[(0,a.jsx)(i.Z,{onClick:c,color:"primary",children:"Cancel"}),(0,a.jsx)(i.Z,{onClick:()=>{t(s),c()},color:"primary",variant:"contained",children:"Save"})]})]})]})},E=n(2653),I=n(3701),P=n(9279),S=n(666),O=n(5795),w=n(4147),T=n(8276),R=n(3391),W=n(6446),N=n(1280),z=n(9329),V=e=>{let{open:t,prompt:n,index:l,onAdd:s,onCancel:o}=e,[c,h]=r.useState(n),m=r.useRef(null);r.useEffect(()=>{h(n)},[n]);let f=e=>{s(c),h(""),e?o():m.current&&m.current.focus()};return(0,a.jsxs)(d.Z,{open:t,onClose:o,fullWidth:!0,maxWidth:"md",children:[(0,a.jsx)(x.Z,{children:"Edit Prompt ".concat(l+1)}),(0,a.jsx)(u.Z,{children:(0,a.jsx)(_.Z,{value:c,onChange:e=>h(e.target.value),fullWidth:!0,margin:"normal",multiline:!0,placeholder:"The quick brown {{animal1}} jumps over the lazy {{animal2}}.",helperText:"Tip: use the {{varname}} syntax to add variables to your prompt.",inputRef:m})}),(0,a.jsxs)(p.Z,{children:[(0,a.jsx)(i.Z,{onClick:f.bind(null,!0),color:"primary",variant:"contained",disabled:!c.length,children:"Add"}),(0,a.jsx)(i.Z,{onClick:f.bind(null,!1),color:"primary",variant:"contained",disabled:!c.length,children:"Add Another"}),(0,a.jsx)(i.Z,{onClick:o,color:"secondary",children:"Cancel"})]})]})};n(2280);var F=()=>{let[e,t]=(0,r.useState)(!1),[n,l]=(0,r.useState)(null),{prompts:o,setPrompts:d}=(0,g.o)(),p=(0,r.useRef)(null);(0,r.useEffect)(()=>{null!==n&&n>0&&p.current&&p.current.focus()},[n]);let u=e=>{l(e),t(!0)},h=(e,t)=>{e.stopPropagation();let n=o[t];d([...o,n])},x=(e,t)=>{d(o.map((n,a)=>a===e?t:n))},m=(e,t)=>{e.stopPropagation(),confirm("Are you sure you want to remove this prompt?")&&d(o.filter((e,n)=>n!==t))};return(0,a.jsxs)("div",{children:[(0,a.jsxs)(c.Z,{direction:"row",spacing:2,justifyContent:"space-between",children:[(0,a.jsx)(s.Z,{variant:"h5",children:"Prompts"}),(0,a.jsxs)("div",{children:[(0,a.jsx)("label",{htmlFor:"file-input-add-prompt",children:(0,a.jsx)(T.Z,{title:"Upload prompt from file",children:(0,a.jsxs)("span",{children:[(0,a.jsx)(E.Z,{component:"span",children:(0,a.jsx)(N.Z,{})}),(0,a.jsx)("input",{id:"file-input-add-prompt",type:"file",accept:".txt,.md",onChange:e=>{var t;e.stopPropagation(),e.preventDefault();let n=null===(t=e.target.files)||void 0===t?void 0:t[0];if(n){let e=new FileReader;e.onload=e=>{var t,n;let a=null===(n=e.target)||void 0===n?void 0:null===(t=n.result)||void 0===t?void 0:t.toString();a&&d([...o,a])},e.readAsText(n)}},style:{display:"none"}})]})})}),(0,a.jsx)(i.Z,{color:"primary",onClick:()=>{t(!0)},variant:"contained",children:"Add Prompt"})]})]}),(0,a.jsx)(O.Z,{children:(0,a.jsx)(I.Z,{children:(0,a.jsx)(P.Z,{children:0===o.length?(0,a.jsx)(w.Z,{children:(0,a.jsx)(S.Z,{colSpan:2,align:"center",children:"No prompts added yet."})}):o.map((e,t)=>(0,a.jsxs)(w.Z,{sx:{"&:hover":{backgroundColor:"rgba(0, 0, 0, 0.04)",cursor:"pointer"}},onClick:()=>u(t),children:[(0,a.jsx)(S.Z,{children:(0,a.jsxs)(s.Z,{variant:"body2",children:["Prompt #".concat(t+1,": "),(e.length>250?e.slice(0,250)+" ...":e).split(/({{\w+}})/g).map((e,t)=>/{{\w+}}/g.test(e)?(0,a.jsx)("span",{className:"prompt-var-highlight",children:e},t):e)]})}),(0,a.jsxs)(S.Z,{align:"right",sx:{minWidth:150},children:[(0,a.jsx)(E.Z,{onClick:()=>u(t),size:"small",children:(0,a.jsx)(R.Z,{})}),(0,a.jsx)(E.Z,{onClick:e=>h(e,t),size:"small",children:(0,a.jsx)(z.Z,{})}),(0,a.jsx)(E.Z,{onClick:e=>m(e,t),size:"small",children:(0,a.jsx)(W.Z,{})})]})]},t))})})}),(0,a.jsx)(V,{open:e,prompt:null!==n?o[n]:"",index:null!==n?n:0,onAdd:e=>{null!==n?x(n,e):d([...o,e]),l(null)},onCancel:()=>{l(null),t(!1)}})]})},L=n(6988),U=e=>{let{onAdd:t,varsList:n,initialValues:i}=e,[l,d]=r.useState(i||{});return(0,r.useEffect)(()=>{let e={};n.forEach(t=>{e[t]=(null==i?void 0:i[t])||""}),d(e)},[n,i]),(0,a.jsxs)(o.Z,{my:2,children:[(0,a.jsx)(s.Z,{variant:"h6",mb:2,children:"Vars"}),n.length>0?(0,a.jsx)(c.Z,{direction:"row",spacing:2,alignItems:"center",children:Object.keys(l).map((e,n)=>(0,a.jsx)(c.Z,{direction:"row",spacing:2,alignItems:"center",children:(0,a.jsx)(_.Z,{placeholder:e,label:e,value:l[e],fullWidth:!0,onChange:n=>{let a=n.target.value,r={...l,[e]:a};d(r),t(r)}})},n))}):(0,a.jsxs)(s.Z,{variant:"subtitle1",gutterBottom:!0,children:["Add variables to your prompt using the ","{{varname}}"," syntax."]})]})},B=n(8440);let K=["equals","contains","icontains","contains-all","contains-any","starts-with","regex","is-json","contains-json","similar","llm-rubric","model-graded-closedqa","factuality","webhook","rouge-n","rouge-s","rouge-l","not-equals","not-contains","not-icontains","not-contains-all","not-contains-any","not-starts-with","not-regex","not-is-json","not-contains-json","not-similar","not-webhook","not-rouge-n","not-rouge-s","not-rouge-l","is-valid-openai-function-call","is-valid-openai-tools-call","latency","perplexity","perplexity-score","cost","answer-relevance","context-faithfulness","context-recall","context-relevance","select-best"];var Y=e=>{let{onAdd:t,initialValues:n}=e,[l,d]=(0,r.useState)(n||[]),p=e=>{let n=l.filter((t,n)=>n!==e);d(n),t(n)};return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(s.Z,{variant:"h6",children:"Asserts"}),(0,a.jsx)(o.Z,{my:l.length>0?2:0,children:(0,a.jsx)(c.Z,{direction:"column",spacing:2,children:l.map((e,n)=>(0,a.jsxs)(c.Z,{direction:"row",spacing:2,alignItems:"center",children:[(0,a.jsx)(B.Z,{value:e.type,options:K,sx:{minWidth:200},onChange:(e,a)=>{let r=l.map((e,t)=>t===n?{...e,type:a}:e);d(r),t(r)},renderInput:e=>(0,a.jsx)(_.Z,{...e,label:"Type"})}),(0,a.jsx)(_.Z,{label:"Value",value:e.value,fullWidth:!0,onChange:e=>{let a=e.target.value,r=l.map((e,t)=>t===n?{...e,value:a}:e);d(r),t(r)}}),(0,a.jsx)(E.Z,{onClick:()=>p(n),size:"small",children:(0,a.jsx)(W.Z,{})})]},n))})}),(0,a.jsx)(i.Z,{color:"primary",onClick:()=>{let e=[...l,{type:"equals",value:""}];d(e),t(e)},children:"Add Assert"})]})},q=e=>{let{open:t,onAdd:n,varsList:l,initialValues:s,onCancel:c}=e,[h,m]=(0,r.useState)((null==s?void 0:s.description)||""),[f,j]=(0,r.useState)((null==s?void 0:s.vars)||{}),[g,v]=(0,r.useState)((null==s?void 0:s.assert)||[]),[Z,b]=(0,r.useState)(0);r.useEffect(()=>{s?(m(s.description||""),j(s.vars||{}),v(s.assert||[])):(m(""),j({}),v([]))},[s]);let y=e=>{n({description:h,vars:f,assert:g},e),e&&c(),m(""),j({}),v([]),b(e=>e+1)};return(0,a.jsxs)(d.Z,{open:t,onClose:c,fullWidth:!0,maxWidth:"md",children:[(0,a.jsx)(x.Z,{children:s?"Edit Test Case":"Add Test Case"}),(0,a.jsx)(u.Z,{children:(0,a.jsxs)(o.Z,{children:[(0,a.jsx)(U,{onAdd:e=>j(e),varsList:l,initialValues:null==s?void 0:s.vars}),(0,a.jsx)(Y,{onAdd:e=>v(e),initialValues:(null==s?void 0:s.assert)||[]},Z)]})}),(0,a.jsxs)(p.Z,{children:[(0,a.jsx)(i.Z,{onClick:y.bind(void 0,!0),color:"primary",variant:"contained",children:s?"Update Test Case":"Add Test Case"}),!s&&(0,a.jsx)(i.Z,{onClick:y.bind(void 0,!1),color:"primary",variant:"contained",children:"Add Another"}),(0,a.jsx)(i.Z,{onClick:c,color:"secondary",children:"Cancel"})]})]})},D=n(5320),J=e=>{let{varsList:t}=e,{testCases:l,setTestCases:o}=(0,g.o)(),[d,p]=r.useState(null),[u,h]=r.useState(!1),x=(e,t)=>{e.stopPropagation(),confirm("Are you sure you want to delete this test case?")&&o(l.filter((e,n)=>n!==t))},m=(e,t)=>{e.stopPropagation();let n=JSON.parse(JSON.stringify(l[t]));o([...l,n])};return(0,a.jsxs)(a.Fragment,{children:[(0,a.jsxs)(c.Z,{direction:"row",spacing:2,justifyContent:"space-between",children:[(0,a.jsx)(s.Z,{variant:"h5",children:"Test Cases"}),(0,a.jsxs)("div",{children:[(0,a.jsx)("label",{htmlFor:"file-input-add-test-case",children:(0,a.jsx)(T.Z,{title:"Upload test cases from csv",children:(0,a.jsxs)("span",{children:[(0,a.jsx)(E.Z,{component:"span",children:(0,a.jsx)(N.Z,{})}),(0,a.jsx)("input",{id:"file-input-add-test-case",type:"file",accept:".csv",onChange:e=>{var t;e.stopPropagation(),e.preventDefault();let a=null===(t=e.target.files)||void 0===t?void 0:t[0];if(a){let e=new FileReader;e.onload=async e=>{var t,a;let r=null===(a=e.target)||void 0===a?void 0:null===(t=a.result)||void 0===t?void 0:t.toString();if(r){let{parse:e}=await Promise.all([n.e(631),n.e(922)]).then(n.bind(n,8922)),t=e(r,{columns:!0});o([...l,...t.map(e=>(0,D.It)(e))])}},e.readAsText(a)}},style:{display:"none"}})]})})}),(0,a.jsx)(i.Z,{color:"primary",onClick:()=>h(!0),variant:"contained",children:"Add Test Case"})]})]}),(0,a.jsx)(O.Z,{children:(0,a.jsxs)(I.Z,{children:[(0,a.jsx)(L.Z,{children:(0,a.jsxs)(w.Z,{children:[(0,a.jsx)(S.Z,{children:"Description"}),(0,a.jsx)(S.Z,{children:"Assertions"}),(0,a.jsx)(S.Z,{children:"Variables"}),(0,a.jsx)(S.Z,{align:"right"})]})}),(0,a.jsx)(P.Z,{children:0===l.length?(0,a.jsx)(w.Z,{children:(0,a.jsx)(S.Z,{colSpan:4,align:"center",children:"No test cases added yet."})}):l.map((e,t)=>{var n;return(0,a.jsxs)(w.Z,{sx:{"&:hover":{backgroundColor:"rgba(0, 0, 0, 0.04)",cursor:"pointer"}},onClick:()=>{p(t),h(!0)},children:[(0,a.jsx)(S.Z,{children:(0,a.jsx)(s.Z,{variant:"body2",children:e.description||"Test Case #".concat(t+1)})}),(0,a.jsxs)(S.Z,{children:[(null===(n=e.assert)||void 0===n?void 0:n.length)||0," assertions"]}),(0,a.jsx)(S.Z,{children:Object.entries(e.vars||{}).map(e=>{let[t,n]=e;return t+"="+n}).join(", ")}),(0,a.jsxs)(S.Z,{align:"right",sx:{minWidth:150},children:[(0,a.jsx)(E.Z,{onClick:()=>{p(t),h(!0)},size:"small",children:(0,a.jsx)(R.Z,{})}),(0,a.jsx)(E.Z,{onClick:e=>m(e,t),size:"small",children:(0,a.jsx)(z.Z,{})}),(0,a.jsx)(E.Z,{onClick:e=>x(e,t),size:"small",children:(0,a.jsx)(W.Z,{})})]})]},t)})})]})}),(0,a.jsx)(q,{open:u,onAdd:(e,t)=>{if(null===d)o([...l,e]);else{let t=l.map((t,n)=>n===d?e:t);o(t),p(null)}t&&h(!1)},varsList:t,initialValues:null!==d?l[d]:void 0,onCancel:()=>{p(null),h(!1)}})]})},X=n(7827),G=e=>{let{onChange:t,...n}=e,[i,l]=r.useState(""),[s,o]=r.useState(!1);return(0,a.jsx)(_.Z,{...n,error:s,helperText:s?"Invalid JSON":"",value:i,onChange:e=>{let n=e.target.value;try{let e=JSON.parse(n);l(n),o(!1),t&&t(e)}catch(e){l(n),o(!0)}}})},H=e=>{let{open:t,providerId:n,config:l,onClose:s,onSave:c}=e,[h,m]=r.useState(l);return r.useEffect(()=>{m(l)},[l]),(0,a.jsxs)(d.Z,{open:t,onClose:s,fullWidth:!0,maxWidth:"md",children:[(0,a.jsxs)(x.Z,{children:["Edit ",n.length>50?n.slice(0,50)+"...":n]}),(0,a.jsx)(u.Z,{children:Object.keys(h).map(e=>{let t;let n=h[e];return"number"==typeof n||"boolean"==typeof n||"string"==typeof n?(t="number"==typeof n?t=>m({...h,[e]:parseFloat(t.target.value)}):"boolean"==typeof n?t=>m({...h,[e]:"true"===t.target.value}):t=>{let n=t.target.value.trim();if(n.startsWith("{")||n.startsWith("["))try{m({...h,[e]:JSON.parse(n)})}catch(t){m({...h,[e]:n})}else"null"===n?m({...h,[e]:null}):"undefined"===n?m({...h,[e]:void 0}):m({...h,[e]:n})},(0,a.jsx)(o.Z,{my:2,children:(0,a.jsx)(_.Z,{label:e,value:n,onChange:t,fullWidth:!0,InputLabelProps:{shrink:!0},type:"number"==typeof n?"number":"text"})},e)):(0,a.jsx)(o.Z,{my:2,children:(0,a.jsx)(G,{label:e,defaultValue:JSON.stringify(n),onChange:t=>{m({...h,[e]:t})},fullWidth:!0,multiline:!0,minRows:2,InputLabelProps:{shrink:!0}})},e)})}),(0,a.jsxs)(p.Z,{children:[(0,a.jsx)(i.Z,{onClick:s,children:"Cancel"}),(0,a.jsx)(i.Z,{onClick:()=>{c(h)},children:"Save"})]})]})};let M=[].concat(["replicate:replicate/flan-t5-small:69716ad8c34274043bf4a135b7315c7c569ec931d8f23d6826e249e1c142a264"].map(e=>({id:e,config:{temperature:.5,max_length:1024,repetition_penality:1}}))).concat(["replicate:replicate/codellama-7b-instruct:0103579e86fc75ba0d65912890fa19ef03c84a68554635319accf2e0ba93d3ae","replicate:replicate/codellama-13b-instruct:da5676342de1a5a335b848383af297f592b816b950a43d251a0a9edd0113604b","replicate:replicate/llama-2-70b-chat:2796ee9483c3fd7aa2e171d38f4ca12251a30609463dcfd4cd76703f22e96cdf"].map(e=>({id:e,config:{system_prompt:"",temperature:.75,top_p:.9,top_k:50,max_new_tokens:128,min_new_tokens:-1}}))).concat(["replicate:replicate/codellama-7b:6880b103613a9cd23950c5fd6c140197e519905bd0dd00e448c4858bdd06090a","replicate:replicate/codellama-13b-python:09b87c02dfa403e0c3289166dece62286b3bce49bae39a9c9204713cf94b8b7d","replicate:replicate/codellama-13b:1c914d844307b0588599b8393480a3ba917b660c7e9dfae681542b5325f228db","replicate:replicate/codellama-34b-python:9048743d22a7b19cd0abb018066809ea6af4f2b4717bef9aad3c5ae21ceac00d","replicate:replicate/codellama-34b:0666717e5ead8557dff55ee8f11924b5c0309f5f1ca52f64bb8eec405fdb38a7"].map(e=>({id:e,config:{temperature:.75,top_p:.9,top_k:50,max_new_tokens:128,min_new_tokens:-1}}))).concat(["replicate:a16z-infra/llama-2-7b-chat:7b0bfc9aff140d5b75bacbed23e91fd3c34b01a1e958d32132de6e0a19796e2c","replicate:a16z-infra/llama-2-13b-chat:2a7f981751ec7fdf87b5b91ad4db53683a98082e9ff7bfd12c8cd5ea85980a52"].map(e=>({id:e,config:{temperature:.95,top_p:.95,top_k:250,max_new_tokens:500,min_new_tokens:-1,repetition_penality:1,system_prompt:""}}))).concat(["anthropic:claude-1","anthropic:claude-1-100k","anthropic:claude-instant-1","anthropic:claude-instant-1-100k"].map(e=>({id:e,config:{max_tokens_to_sample:256,temperature:.5}}))).concat(["bedrock:anthropic.claude-instant-v1","bedrock:anthropic.claude-v1","bedrock:anthropic.claude-v2"].map(e=>({id:e,config:{max_tokens_to_sample:256,temperature:.5}}))).concat(["openai:gpt-3.5-turbo","openai:gpt-3.5-turbo-0301","openai:gpt-3.5-turbo-0613","openai:gpt-3.5-turbo-16k","openai:gpt-3.5-turbo-16k-0613","openai:gpt-4","openai:gpt-4-0314","openai:gpt-4-0613","openai:gpt-4-32k","openai:gpt-4-32k-0314"].map(e=>({id:e,config:{organization:"",temperature:.5,max_tokens:1024,top_p:1,frequency_penalty:0,presence_penalty:0,function_call:void 0,functions:void 0,stop:void 0}}))).concat(["azureopenai:gpt-3.5-turbo","azureopenai:gpt-3.5-turbo-0301","azureopenai:gpt-3.5-turbo-0613","azureopenai:gpt-3.5-turbo-16k","azureopenai:gpt-3.5-turbo-16k-0613","azureopenai:gpt-4","azureopenai:gpt-4-0314","azureopenai:gpt-4-0613","azureopenai:gpt-4-32k","azureopenai:gpt-4-32k-0314"].map(e=>({id:e,config:{temperature:.5,max_tokens:1024,top_p:1,frequency_penalty:0,presence_penalty:0,function_call:void 0,functions:void 0,stop:void 0}}))).concat(["vertex:chat-bison@001","vertex:chat-bison","vertex:chat-bison-32k","vertex:chat-bison-32k@001"].map(e=>({id:e,config:{context:void 0,examples:void 0,temperature:0,maxOutputTokens:1024,topP:.95,topK:40,safetySettings:void 0,stopSequence:void 0}}))).sort((e,t)=>e.id.localeCompare(t.id)),$={anthropic:"Anthropic",bedrock:"Amazon Web Services",azureopenai:"Azure",openai:"OpenAI",replicate:"Replicate"};var Q=e=>{let{providers:t,onChange:n}=e,[i,l]=r.useState(null),s=e=>"string"==typeof e?e:e.id||"Unknown provider",c=(e,t)=>"string"==typeof e?e:e.id||t,d=e=>{"string"==typeof e?alert("Cannot edit custom providers"):e.config?l(e):alert("There is no config for this provider")};return(0,a.jsxs)(o.Z,{mt:2,children:[(0,a.jsx)(B.Z,{multiple:!0,freeSolo:!0,options:M,value:t,groupBy:e=>(function(e){if(!e)return"Other";let t=e.split(":")[0];return $[t]||t})(e.id),onChange:(e,t)=>{n(t.map(e=>"string"==typeof e?{id:e}:e))},getOptionLabel:e=>{if(!e)return"";let t="";"string"==typeof e&&(t=e),e.id&&"string"==typeof e.id&&(t=e.id);let n=t.split(":");return n.length>1?n[1]:"Unknown provider"},renderTags:(e,t)=>e.map((e,n)=>{let a=s(e),i=c(e,n);return(0,r.createElement)(X.Z,{variant:"outlined",label:a,...t({index:n}),key:i,onClick:()=>d(e)})}),renderInput:e=>(0,a.jsx)(_.Z,{...e,variant:"outlined",placeholder:"Select LLM providers",helperText:t.length>0?"Click a provider to configure its settings.":null})}),i&&i.id&&(0,a.jsx)(H,{open:!!i,providerId:i.id,config:i.config,onClose:()=>l(null),onSave:e=>{if(i){let a=t.map(t=>t.id===i.id?{...t,config:e}:t);n(a),l(null)}}})]})},ee=n(2666),et=n.n(ee),en=n(4759);n(5341),n(7555);var ea=n(8339),er=n(9963),ei=n(1396),el=n.n(ei);n(695);var es=()=>{let{env:e,setEnv:t,description:n,setDescription:l,providers:c,setProviders:d,prompts:p,setPrompts:u,testCases:h,setTestCases:x}=(0,g.o)(),[m,f]=r.useState(""),[j,v]=r.useState(!0);r.useEffect(()=>{f(ea.default.dump({env:e,description:n,providers:c,prompts:p,tests:h}))},[e,n,c,p,h]);let Z=e=>{t(e.env||{}),l(e.description||""),d(e.providers||[]),u(e.prompts||[]),x(e.tests||[])};return(0,a.jsxs)(o.Z,{mt:4,children:[(0,a.jsx)(s.Z,{variant:"h5",gutterBottom:!0,children:"Configuration"}),(0,a.jsxs)(s.Z,{variant:"body1",gutterBottom:!0,children:["This is the YAML config that defines the evaluation and is processed by promptfoo. See"," ",(0,a.jsx)(el(),{target:"_blank",href:"https://promptfoo.dev/docs/configuration/guide",children:"configuration docs"})," ","to learn more."]}),(0,a.jsx)(i.Z,{variant:"text",color:"primary",startIcon:j?(0,a.jsx)(R.Z,{}):(0,a.jsx)(er.Z,{}),onClick:()=>{if(!j)try{let e=ea.default.load(m,{json:!0});Z(e)}catch(e){}v(!j)},children:j?"Edit YAML":"Save"}),(0,a.jsx)(et(),{autoCapitalize:"off",value:m,onValueChange:e=>{j||f(e)},highlight:e=>(0,en.highlight)(e,en.languages.yaml),padding:10,style:{fontFamily:'"Fira code", "Fira Mono", monospace',fontSize:14},disabled:j,className:j?"":"glowing-border"})]})};n(284);var eo=n(7580);function ec(e){let{error:t,resetErrorBoundary:n}=e;return(0,a.jsxs)("div",{role:"alert",children:[(0,a.jsx)("p",{children:"Something went wrong:"}),(0,a.jsx)("pre",{children:t.message}),(0,a.jsx)("button",{onClick:n,children:"Try again"})]})}var ed=()=>{let[e,t]=(0,r.useState)(!1),{description:n,setDescription:f,providers:j,setProviders:v,prompts:b,setPrompts:y,testCases:C,setTestCases:_}=(0,g.o)();if((0,r.useEffect)(()=>{g.o.persist.rehydrate()},[]),eo.env.NEXT_PUBLIC_NO_BROWSING)return null;let k=(e=>{let t=/{{(\w+)}}/g,n=new Set;return e.forEach(e=>{let a;for(;null!==(a=t.exec(e));)n.add(a[1])}),Array.from(n)})(b);return(0,a.jsxs)(l.Z,{maxWidth:"lg",sx:{marginTop:"2rem"},children:[(0,a.jsxs)(c.Z,{direction:"row",spacing:2,justifyContent:"space-between",children:[(0,a.jsx)(s.Z,{variant:"h4",children:"Set up an evaluation"}),(0,a.jsxs)(c.Z,{direction:"row",spacing:2,children:[(0,a.jsx)(Z,{}),(0,a.jsx)(A,{}),(0,a.jsx)(i.Z,{variant:"outlined",color:"primary",onClick:()=>t(!0),children:"Reset"})]})]}),(0,a.jsx)(o.Z,{mt:4}),(0,a.jsx)(o.Z,{mt:2,children:(0,a.jsx)(m.SV,{FallbackComponent:ec,onReset:()=>{v([])},children:(0,a.jsxs)(c.Z,{direction:"column",spacing:2,justifyContent:"space-between",children:[(0,a.jsx)(s.Z,{variant:"h5",children:"Providers"}),(0,a.jsx)(Q,{providers:j,onChange:v})]})})}),(0,a.jsx)(o.Z,{mt:4}),(0,a.jsx)(m.SV,{FallbackComponent:ec,onReset:()=>{y([])},children:(0,a.jsx)(F,{})}),(0,a.jsx)(o.Z,{mt:6}),(0,a.jsx)(m.SV,{FallbackComponent:ec,onReset:()=>{_([])},children:(0,a.jsx)(J,{varsList:k})}),(0,a.jsx)(es,{}),(0,a.jsxs)(d.Z,{open:e,onClose:()=>t(!1),"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[(0,a.jsx)(x.Z,{id:"alert-dialog-title",children:"Confirm Reset"}),(0,a.jsx)(u.Z,{children:(0,a.jsx)(h.Z,{id:"alert-dialog-description",children:"Are you sure you want to reset all the fields? This action cannot be undone."})}),(0,a.jsxs)(p.Z,{children:[(0,a.jsx)(i.Z,{onClick:()=>t(!1),children:"Cancel"}),(0,a.jsx)(i.Z,{onClick:()=>{f(""),v([]),y([]),_([]),t(!1)},autoFocus:!0,children:"Reset"})]})]})]})}},279:function(e,t,n){"use strict";n.d(t,{Ox:function(){return i},T8:function(){return r},eA:function(){return l}});var a=n(7580);let r=!a.env.NEXT_PUBLIC_PROMPTFOO_BUILD_STANDALONE_SERVER,i=!!a.env.NEXT_PUBLIC_PROMPTFOO_USE_SUPABASE,l=""},1938:function(e,t,n){"use strict";n.d(t,{o:function(){return i}});var a=n(4660),r=n(4810);let i=(0,a.Ue)()((0,r.tJ)((e,t)=>({env:{},testCases:[],description:"",providers:[],prompts:[],setEnv:t=>e({env:t}),setTestCases:t=>e({testCases:t}),setDescription:t=>e({description:t}),setProviders:t=>e({providers:t}),setPrompts:t=>e({prompts:t}),setStateFromConfig:t=>{let n={};t.description&&(n.description=t.description||""),t.tests&&(n.testCases=t.tests),t.providers&&(n.providers=t.providers),t.prompts&&("string"==typeof t.prompts?n.prompts=[t.prompts]:Array.isArray(t.prompts)?n.prompts=t.prompts.filter(e=>!e.endsWith(".txt")&&!e.endsWith(".json")&&!e.endsWith(".yaml")):console.warn("Invalid prompts config",t.prompts)),e(n)},getTestSuite:()=>{let{description:e,testCases:n,providers:a,prompts:r,env:i}=t();return{env:i,description:e,providers:a,prompts:r,tests:n}}}),{name:"promptfoo",skipHydration:!0}))},2280:function(){},695:function(){},284:function(){},5320:function(e,t){"use strict";t.It=void 0,t.It=function(e){let t={},n=[],a={};for(let[r,i]of Object.entries(e))r.startsWith("__expected")?""!==i.trim()&&n.push(function(e){if(e.startsWith("javascript:")||e.startsWith("fn:")||e.startsWith("eval:")){let t;e.startsWith("javascript:")&&(t=11),e.startsWith("fn:")&&(t=3),e.startsWith("eval:")&&(t=5);let n=e.slice(t);return{type:"javascript",value:n}}if(e.startsWith("grade:")||e.startsWith("llm-rubric:"))return{type:"llm-rubric",value:e.slice(6)};if(e.startsWith("python:")){let t=e.slice(7);return{type:"python",value:t}}let t=e.match(/^(not-)?(equals|contains-any|contains-all|icontains-any|icontains-all|contains-json|is-json|regex|icontains|contains|webhook|rouge-n|similar|starts-with|levenshtein|classifier|model-graded-factuality|factuality|model-graded-closedqa|answer-relevance|context-recall|context-relevance|context-faithfulness|is-valid-openai-function-call|is-valid-openai-tools-call|latency|perplexity|perplexity-score|cost)(?:\((\d+(?:\.\d+)?)\))?(?::(.*))?$/);if(t){let[e,n,a,r,i]=t,l=n?`not-${a}`:a,s=parseFloat(r);return"contains-any"===a||"contains-all"===a||"icontains-any"===a||"icontains-all"===a?{type:l,value:i.split(",").map(e=>e.trim())}:"contains-json"===a||"is-json"===a?{type:l}:"rouge-n"===a||"similar"===a||"starts-with"===a||"levenshtein"===a||"classifier"===a||"answer-relevance"===a||"context-recall"===a||"context-relevance"===a||"context-faithfulness"===a||"latency"===a||"perplexity"===a||"perplexity-score"===a||"cost"===a?{type:l,value:i,threshold:s||("similar"===a?.8:.75)}:{type:l,value:i}}return{type:"equals",value:e}}(i)):"__prefix"===r?a.prefix=i:"__suffix"===r?a.suffix=i:t[r]=i;return{vars:t,assert:n,options:a}}}},function(e){e.O(0,[293,808,548,420,975,886,683,339,376,971,596,744],function(){return e(e.s=875)}),_N_E=e.O()}]);