heyio 1.2.1 → 1.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/copilot/skills.js +4 -2
- package/dist/copilot/tools.js +10 -8
- package/dist/store/instances.js +8 -13
- package/package.json +1 -1
- package/web-dist/assets/{ChatView-DytZu0cf.js → ChatView-mZaaw3pd.js} +1 -1
- package/web-dist/assets/{FeedView-DUzIJzQn.js → FeedView-BHacQwXQ.js} +1 -1
- package/web-dist/assets/{LoginView-BHfb407L.js → LoginView-B6aSD9II.js} +1 -1
- package/web-dist/assets/{MarkdownContent.vue_vue_type_script_setup_true_lang-D8hVymut.js → MarkdownContent.vue_vue_type_script_setup_true_lang-CEo_ckIb.js} +1 -1
- package/web-dist/assets/{McpView-BkHmXIqT.js → McpView-BAVRUHIE.js} +1 -1
- package/web-dist/assets/{SchedulesView-DBSQJ90f.js → SchedulesView-dOd1SQiP.js} +1 -1
- package/web-dist/assets/{SettingsView-4qaRAFne.js → SettingsView-CCDeEsVg.js} +1 -1
- package/web-dist/assets/{SkillsView-BdkKL3Qz.js → SkillsView-gCfQ35FQ.js} +1 -1
- package/web-dist/assets/{SquadDetailView-D3b9HzUp.js → SquadDetailView-CQhFfZTc.js} +1 -1
- package/web-dist/assets/{SquadsView-DgdgxMw_.js → SquadsView-CZFxtOao.js} +1 -1
- package/web-dist/assets/{WikiView-Cl67wuwR.js → WikiView-B0cuUFfm.js} +1 -1
- package/web-dist/assets/api-DdW5uOZf.js +1 -0
- package/web-dist/assets/{index-DdP1fu_7.js → index-BQdXxKfc.js} +3 -3
- package/web-dist/assets/{plus-iT8CnKtn.js → plus-Cvp1w2CO.js} +1 -1
- package/web-dist/assets/{trash-2-C7RWmI2-.js → trash-2-Cr3vrmL5.js} +1 -1
- package/web-dist/assets/{x-B56ATU_7.js → x-O3fBd1Cr.js} +1 -1
- package/web-dist/index.html +1 -1
- package/web-dist/assets/api-CuAKFds2.js +0 -1
package/dist/copilot/skills.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { existsSync, readdirSync, readFileSync, rmSync } from "node:fs";
|
|
2
2
|
import { join, basename } from "node:path";
|
|
3
|
-
import {
|
|
3
|
+
import { exec } from "node:child_process";
|
|
4
|
+
import { promisify } from "node:util";
|
|
4
5
|
import { PATHS } from "../paths.js";
|
|
6
|
+
const execAsync = promisify(exec);
|
|
5
7
|
export async function listSkills() {
|
|
6
8
|
if (!existsSync(PATHS.skills))
|
|
7
9
|
return [];
|
|
@@ -35,7 +37,7 @@ export async function addSkill(url) {
|
|
|
35
37
|
if (existsSync(dest)) {
|
|
36
38
|
throw new Error(`Skill "${slug}" is already installed.`);
|
|
37
39
|
}
|
|
38
|
-
|
|
40
|
+
await execAsync(`git clone --depth 1 ${url} ${dest}`);
|
|
39
41
|
// Verify SKILL.md exists
|
|
40
42
|
if (!existsSync(join(dest, "SKILL.md"))) {
|
|
41
43
|
rmSync(dest, { recursive: true, force: true });
|
package/dist/copilot/tools.js
CHANGED
|
@@ -69,10 +69,12 @@ export function createTools() {
|
|
|
69
69
|
const squad = createSquad(name, universe, repo_url);
|
|
70
70
|
let cloneMsg = "";
|
|
71
71
|
if (repo_url) {
|
|
72
|
-
const {
|
|
72
|
+
const { exec } = await import("node:child_process");
|
|
73
|
+
const { promisify } = await import("node:util");
|
|
73
74
|
const { existsSync, mkdirSync } = await import("node:fs");
|
|
74
75
|
const { join } = await import("node:path");
|
|
75
76
|
const { PATHS } = await import("../paths.js");
|
|
77
|
+
const execAsync = promisify(exec);
|
|
76
78
|
// Extract owner/repo from URL (supports https and git@ formats)
|
|
77
79
|
const match = repo_url.match(/[/:]([^/]+)\/([^/.]+?)(?:\.git)?$/);
|
|
78
80
|
if (match) {
|
|
@@ -83,8 +85,7 @@ export function createTools() {
|
|
|
83
85
|
if (!existsSync(parentDir))
|
|
84
86
|
mkdirSync(parentDir, { recursive: true });
|
|
85
87
|
try {
|
|
86
|
-
|
|
87
|
-
encoding: "utf-8",
|
|
88
|
+
await execAsync(`git clone ${repo_url} ${sourceDir}`, {
|
|
88
89
|
timeout: 120_000,
|
|
89
90
|
});
|
|
90
91
|
cloneMsg = ` Repo cloned to ~/.io/source/${owner}/${repo}.`;
|
|
@@ -313,22 +314,23 @@ export function createTools() {
|
|
|
313
314
|
cwd: z.string().optional().describe("Working directory (defaults to home directory)"),
|
|
314
315
|
}),
|
|
315
316
|
handler: async ({ command, cwd }) => {
|
|
316
|
-
const {
|
|
317
|
+
const { exec } = await import("node:child_process");
|
|
318
|
+
const { promisify } = await import("node:util");
|
|
317
319
|
const { homedir } = await import("node:os");
|
|
320
|
+
const execAsync = promisify(exec);
|
|
318
321
|
try {
|
|
319
|
-
const
|
|
322
|
+
const { stdout } = await execAsync(command, {
|
|
320
323
|
cwd: cwd ?? homedir(),
|
|
321
|
-
encoding: "utf-8",
|
|
322
324
|
timeout: 60_000,
|
|
323
325
|
maxBuffer: 1024 * 1024,
|
|
324
326
|
env: { ...process.env, GH_PROMPT_DISABLED: "1" },
|
|
325
327
|
});
|
|
326
|
-
return
|
|
328
|
+
return stdout.trim() || "(no output)";
|
|
327
329
|
}
|
|
328
330
|
catch (err) {
|
|
329
331
|
const stderr = err.stderr?.toString().trim() ?? "";
|
|
330
332
|
const stdout = err.stdout?.toString().trim() ?? "";
|
|
331
|
-
return `Error (exit ${err.
|
|
333
|
+
return `Error (exit ${err.code}): ${stderr || stdout || err.message}`;
|
|
332
334
|
}
|
|
333
335
|
},
|
|
334
336
|
}),
|
package/dist/store/instances.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import {
|
|
2
|
+
import { exec } from "node:child_process";
|
|
3
|
+
import { promisify } from "node:util";
|
|
3
4
|
import { getDb } from "./db.js";
|
|
5
|
+
const execAsync = promisify(exec);
|
|
4
6
|
const MAX_INSTANCES_PER_SQUAD = 3;
|
|
5
7
|
export async function createInstance(squadId, branch) {
|
|
6
8
|
const db = getDb();
|
|
@@ -19,18 +21,13 @@ export async function createInstance(squadId, branch) {
|
|
|
19
21
|
const id = randomUUID();
|
|
20
22
|
const worktreePath = `/tmp/io-worktrees/${squadId}/${branch}`;
|
|
21
23
|
// Create git worktree
|
|
24
|
+
const repoCwd = squad.repo_url.startsWith("/") ? squad.repo_url : process.cwd();
|
|
22
25
|
try {
|
|
23
|
-
|
|
24
|
-
cwd: squad.repo_url.startsWith("/") ? squad.repo_url : process.cwd(),
|
|
25
|
-
stdio: "pipe",
|
|
26
|
-
});
|
|
26
|
+
await execAsync(`git worktree add ${worktreePath} -b ${branch}`, { cwd: repoCwd });
|
|
27
27
|
}
|
|
28
|
-
catch
|
|
28
|
+
catch {
|
|
29
29
|
// Branch may already exist
|
|
30
|
-
|
|
31
|
-
cwd: squad.repo_url.startsWith("/") ? squad.repo_url : process.cwd(),
|
|
32
|
-
stdio: "pipe",
|
|
33
|
-
});
|
|
30
|
+
await execAsync(`git worktree add ${worktreePath} ${branch}`, { cwd: repoCwd });
|
|
34
31
|
}
|
|
35
32
|
db.prepare(`INSERT INTO instances (id, squad_id, branch, worktree_path, status)
|
|
36
33
|
VALUES (?, ?, ?, ?, 'active')`).run(id, squadId, branch, worktreePath);
|
|
@@ -45,9 +42,7 @@ export async function destroyInstance(instanceId) {
|
|
|
45
42
|
throw new Error(`Instance ${instanceId} not found.`);
|
|
46
43
|
// Remove worktree
|
|
47
44
|
try {
|
|
48
|
-
|
|
49
|
-
stdio: "pipe",
|
|
50
|
-
});
|
|
45
|
+
await execAsync(`git worktree remove ${instance.worktree_path} --force`);
|
|
51
46
|
}
|
|
52
47
|
catch {
|
|
53
48
|
// Already removed or doesn't exist
|
package/package.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{f as _,j as b,r as m,i as k,D as h,o as w,m as o,e as c,a as n,u,d as x,F as S,p as M,G as C,A as D,b as g,k as y,n as v}from"./index-
|
|
1
|
+
import{f as _,j as b,r as m,i as k,D as h,o as w,m as o,e as c,a as n,u,d as x,F as S,p as M,G as C,A as D,b as g,k as y,n as v}from"./index-BQdXxKfc.js";import{c as I}from"./api-DdW5uOZf.js";import{_ as U}from"./MarkdownContent.vue_vue_type_script_setup_true_lang-CEo_ckIb.js";/**
|
|
2
2
|
* @license lucide-vue-next v0.474.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{f as $,i as I,o as F,m as a,e as n,a as o,F as b,p as g,h as i,u as _,I as M,r as d,k as m,t as u,J as y,d as k}from"./index-
|
|
1
|
+
import{f as $,i as I,o as F,m as a,e as n,a as o,F as b,p as g,h as i,u as _,I as M,r as d,k as m,t as u,J as y,d as k}from"./index-BQdXxKfc.js";import{b as N,c as V,a as B}from"./api-DdW5uOZf.js";import{_ as D}from"./MarkdownContent.vue_vue_type_script_setup_true_lang-CEo_ckIb.js";import{T as L}from"./trash-2-Cr3vrmL5.js";/**
|
|
2
2
|
* @license lucide-vue-next v0.474.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as b,v,m as d,e as u,a as e,J as y,G as m,A as p,t as c,d as w,u as f,r as i,x as h}from"./index-
|
|
1
|
+
import{i as b,v,m as d,e as u,a as e,J as y,G as m,A as p,t as c,d as w,u as f,r as i,x as h}from"./index-BQdXxKfc.js";const k={class:"min-h-screen flex items-center justify-center bg-background p-4"},S={class:"w-full max-w-sm space-y-6"},_={key:0,class:"text-sm text-destructive"},V=["disabled"],q=b({__name:"LoginView",setup(B){const o=v(),g=h(),n=i(""),r=i(""),s=i("");async function x(){s.value="";try{await o.login(n.value,r.value),g.push("/")}catch(l){s.value=l.message??"Login failed"}}return(l,t)=>(d(),u("div",k,[e("div",S,[t[4]||(t[4]=e("div",{class:"text-center"},[e("div",{class:"text-4xl mb-2"},"🤖"),e("h1",{class:"text-2xl font-bold"},"IO"),e("p",{class:"text-sm text-muted-foreground mt-1"},"Sign in to your dashboard")],-1)),e("form",{onSubmit:y(x,["prevent"]),class:"space-y-4"},[e("div",null,[t[2]||(t[2]=e("label",{class:"text-sm font-medium",for:"email"},"Email",-1)),m(e("input",{id:"email","onUpdate:modelValue":t[0]||(t[0]=a=>n.value=a),type:"email",required:"",class:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"you@example.com"},null,512),[[p,n.value]])]),e("div",null,[t[3]||(t[3]=e("label",{class:"text-sm font-medium",for:"password"},"Password",-1)),m(e("input",{id:"password","onUpdate:modelValue":t[1]||(t[1]=a=>r.value=a),type:"password",required:"",class:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"••••••••"},null,512),[[p,r.value]])]),s.value?(d(),u("div",_,c(s.value),1)):w("",!0),e("button",{type:"submit",disabled:f(o).loading,class:"w-full rounded-md bg-primary text-primary-foreground px-4 py-2 text-sm font-medium hover:bg-primary/90 disabled:opacity-50 transition-colors"},c(f(o).loading?"Signing in...":"Sign In"),9,V)],32)])]))}});export{q as default};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var me=Object.defineProperty;var we=(n,e,t)=>e in n?me(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var d=(n,e,t)=>we(n,typeof e!="symbol"?e+"":e,t);import{i as ye,m as Re,e as Se,c as $e}from"./index-
|
|
1
|
+
var me=Object.defineProperty;var we=(n,e,t)=>e in n?me(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var d=(n,e,t)=>we(n,typeof e!="symbol"?e+"":e,t);import{i as ye,m as Re,e as Se,c as $e}from"./index-BQdXxKfc.js";function j(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var $=j();function ae(n){$=n}var z={exec:()=>null};function u(n,e=""){let t=typeof n=="string"?n:n.source;const r={replace:(s,i)=>{let c=typeof i=="string"?i:i.source;return c=c.replace(b.caret,"$1"),t=t.replace(s,c),r},getRegex:()=>new RegExp(t,e)};return r}var b={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:n=>new RegExp(`^( {0,3}${n})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}#`),htmlBeginRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}<(?:[a-z].*>|!--)`,"i")},ve=/^(?:[ \t]*(?:\n|$))+/,Te=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,_e=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,A=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ze=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,H=/(?:[*+-]|\d{1,9}[.)])/,oe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ce=u(oe).replace(/bull/g,H).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Ae=u(oe).replace(/bull/g,H).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Q=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Le=/^[^\n]+/,F=/(?!\s*\])(?:\\.|[^\[\]\\])+/,Ce=u(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",F).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ie=u(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,H).getRegex(),E="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",U=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Pe=u("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",U).replace("tag",E).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),he=u(Q).replace("hr",A).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",E).getRegex(),Be=u(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",he).getRegex(),X={blockquote:Be,code:Te,def:Ce,fences:_e,heading:ze,hr:A,html:Pe,lheading:ce,list:Ie,newline:ve,paragraph:he,table:z,text:Le},ne=u("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",A).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",E).getRegex(),Ee={...X,lheading:Ae,table:ne,paragraph:u(Q).replace("hr",A).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",ne).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",E).getRegex()},qe={...X,html:u(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",U).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:z,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:u(Q).replace("hr",A).replace("heading",` *#{1,6} *[^
|
|
2
2
|
]`).replace("lheading",ce).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Ze=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,De=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,pe=/^( {2,}|\\)\n(?!\s*$)/,Me=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,q=/[\p{P}\p{S}]/u,W=/[\s\p{P}\p{S}]/u,ue=/[^\s\p{P}\p{S}]/u,Ge=u(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,W).getRegex(),ge=/(?!~)[\p{P}\p{S}]/u,Oe=/(?!~)[\s\p{P}\p{S}]/u,Ne=/(?:[^\s\p{P}\p{S}]|~)/u,je=/\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g,fe=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,He=u(fe,"u").replace(/punct/g,q).getRegex(),Qe=u(fe,"u").replace(/punct/g,ge).getRegex(),de="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Fe=u(de,"gu").replace(/notPunctSpace/g,ue).replace(/punctSpace/g,W).replace(/punct/g,q).getRegex(),Ue=u(de,"gu").replace(/notPunctSpace/g,Ne).replace(/punctSpace/g,Oe).replace(/punct/g,ge).getRegex(),Xe=u("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ue).replace(/punctSpace/g,W).replace(/punct/g,q).getRegex(),We=u(/\\(punct)/,"gu").replace(/punct/g,q).getRegex(),Je=u(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Ke=u(U).replace("(?:-->|$)","-->").getRegex(),Ve=u("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Ke).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),I=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,Ye=u(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",I).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ke=u(/^!?\[(label)\]\[(ref)\]/).replace("label",I).replace("ref",F).getRegex(),xe=u(/^!?\[(ref)\](?:\[\])?/).replace("ref",F).getRegex(),et=u("reflink|nolink(?!\\()","g").replace("reflink",ke).replace("nolink",xe).getRegex(),J={_backpedal:z,anyPunctuation:We,autolink:Je,blockSkip:je,br:pe,code:De,del:z,emStrongLDelim:He,emStrongRDelimAst:Fe,emStrongRDelimUnd:Xe,escape:Ze,link:Ye,nolink:xe,punctuation:Ge,reflink:ke,reflinkSearch:et,tag:Ve,text:Me,url:z},tt={...J,link:u(/^!?\[(label)\]\((.*?)\)/).replace("label",I).getRegex(),reflink:u(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",I).getRegex()},G={...J,emStrongRDelimAst:Ue,emStrongLDelim:Qe,url:u(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},nt={...G,br:u(pe).replace("{2,}","*").getRegex(),text:u(G.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},L={normal:X,gfm:Ee,pedantic:qe},T={normal:J,gfm:G,breaks:nt,pedantic:tt},rt={"&":"&","<":"<",">":">",'"':""","'":"'"},re=n=>rt[n];function w(n,e){if(e){if(b.escapeTest.test(n))return n.replace(b.escapeReplace,re)}else if(b.escapeTestNoEncode.test(n))return n.replace(b.escapeReplaceNoEncode,re);return n}function se(n){try{n=encodeURI(n).replace(b.percentDecode,"%")}catch{return null}return n}function ie(n,e){var i;const t=n.replace(b.findPipe,(c,l,h)=>{let a=!1,o=l;for(;--o>=0&&h[o]==="\\";)a=!a;return a?"|":" |"}),r=t.split(b.splitPipe);let s=0;if(r[0].trim()||r.shift(),r.length>0&&!((i=r.at(-1))!=null&&i.trim())&&r.pop(),e)if(r.length>e)r.splice(e);else for(;r.length<e;)r.push("");for(;s<r.length;s++)r[s]=r[s].trim().replace(b.slashPipe,"|");return r}function _(n,e,t){const r=n.length;if(r===0)return"";let s=0;for(;s<r&&n.charAt(r-s-1)===e;)s++;return n.slice(0,r-s)}function st(n,e){if(n.indexOf(e[1])===-1)return-1;let t=0;for(let r=0;r<n.length;r++)if(n[r]==="\\")r++;else if(n[r]===e[0])t++;else if(n[r]===e[1]&&(t--,t<0))return r;return t>0?-2:-1}function le(n,e,t,r,s){const i=e.href,c=e.title||null,l=n[1].replace(s.other.outputLinkReplace,"$1");r.state.inLink=!0;const h={type:n[0].charAt(0)==="!"?"image":"link",raw:t,href:i,title:c,text:l,tokens:r.inlineTokens(l)};return r.state.inLink=!1,h}function it(n,e,t){const r=n.match(t.other.indentCodeCompensation);if(r===null)return e;const s=r[1];return e.split(`
|
|
3
3
|
`).map(i=>{const c=i.match(t.other.beginningSpace);if(c===null)return i;const[l]=c;return l.length>=s.length?i.slice(s.length):i}).join(`
|
|
4
4
|
`)}var P=class{constructor(n){d(this,"options");d(this,"rules");d(this,"lexer");this.options=n||$}space(n){const e=this.rules.block.newline.exec(n);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(n){const e=this.rules.block.code.exec(n);if(e){const t=e[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:e[0],codeBlockStyle:"indented",text:this.options.pedantic?t:_(t,`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as w,o as C,m as a,e as n,a as t,h as m,u as p,g as h,G as u,A as v,z as S,d as _,S as V,F as M,p as N,r as i,t as b,k as y}from"./index-
|
|
1
|
+
import{i as w,o as C,m as a,e as n,a as t,h as m,u as p,g as h,G as u,A as v,z as S,d as _,S as V,F as M,p as N,r as i,t as b,k as y}from"./index-BQdXxKfc.js";import{b as P,c as T,d as U,a as $}from"./api-DdW5uOZf.js";import{P as A}from"./plus-Cvp1w2CO.js";import{T as B}from"./trash-2-Cr3vrmL5.js";const D={class:"p-6"},L={class:"flex items-center justify-between mb-6"},j={key:0,class:"border border-border rounded-lg p-4 mb-6 space-y-3"},z={class:"grid grid-cols-2 gap-3"},F={key:0},G={key:1},E={key:1,class:"text-muted-foreground"},R={key:2,class:"text-center py-12 text-muted-foreground"},q={key:3,class:"space-y-2"},H={class:"font-medium text-sm"},I={class:"ml-2 text-xs text-muted-foreground bg-secondary px-1.5 py-0.5 rounded"},J={class:"flex items-center gap-3"},K=["onClick"],O=["onClick"],ee=w({__name:"McpView",setup(Q){const d=i([]),c=i(!0),r=i(!1),o=i({name:"",type:"stdio",command:"",url:""});C(async()=>{try{d.value=await P("/mcp")}finally{c.value=!1}});async function f(l){await U(`/mcp/${l.id}`,{enabled:!l.enabled}),l.enabled=!l.enabled}async function x(l){await $(`/mcp/${l}`),d.value=d.value.filter(e=>e.id!==l)}async function g(){const l={name:o.value.name,type:o.value.type};o.value.type==="stdio"?l.command=o.value.command:l.url=o.value.url;const e=await T("/mcp",l);d.value.push(e),r.value=!1,o.value={name:"",type:"stdio",command:"",url:""}}return(l,e)=>(a(),n("div",D,[t("div",L,[e[6]||(e[6]=t("h1",{class:"text-2xl font-bold"},"MCP Servers",-1)),t("button",{onClick:e[0]||(e[0]=s=>r.value=!r.value),class:"inline-flex items-center gap-1 px-3 py-1.5 text-sm rounded-md bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"},[m(p(A),{class:"w-4 h-4"}),e[5]||(e[5]=h(" Add Server ",-1))])]),r.value?(a(),n("div",j,[t("div",z,[t("div",null,[e[7]||(e[7]=t("label",{class:"text-sm font-medium"},"Name",-1)),u(t("input",{"onUpdate:modelValue":e[1]||(e[1]=s=>o.value.name=s),class:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"},null,512),[[v,o.value.name]])]),t("div",null,[e[9]||(e[9]=t("label",{class:"text-sm font-medium"},"Type",-1)),u(t("select",{"onUpdate:modelValue":e[2]||(e[2]=s=>o.value.type=s),class:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"},[...e[8]||(e[8]=[t("option",{value:"stdio"},"stdio",-1),t("option",{value:"http"},"http",-1)])],512),[[S,o.value.type]])])]),o.value.type==="stdio"?(a(),n("div",F,[e[10]||(e[10]=t("label",{class:"text-sm font-medium"},"Command",-1)),u(t("input",{"onUpdate:modelValue":e[3]||(e[3]=s=>o.value.command=s),placeholder:"npx @my/mcp-server",class:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"},null,512),[[v,o.value.command]])])):(a(),n("div",G,[e[11]||(e[11]=t("label",{class:"text-sm font-medium"},"URL",-1)),u(t("input",{"onUpdate:modelValue":e[4]||(e[4]=s=>o.value.url=s),placeholder:"https://...",class:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"},null,512),[[v,o.value.url]])])),t("button",{onClick:g,class:"px-4 py-2 text-sm rounded-md bg-primary text-primary-foreground hover:bg-primary/90"},"Save")])):_("",!0),c.value?(a(),n("div",E,"Loading...")):d.value.length===0?(a(),n("div",R,[m(p(V),{class:"w-12 h-12 mx-auto mb-3 opacity-50"}),e[12]||(e[12]=t("p",null,"No MCP servers configured.",-1))])):(a(),n("div",q,[(a(!0),n(M,null,N(d.value,s=>(a(),n("div",{key:s.id,class:"flex items-center justify-between border border-border rounded-lg px-4 py-3"},[t("div",null,[t("span",H,b(s.name),1),t("span",I,b(s.type),1)]),t("div",J,[t("button",{onClick:k=>f(s),class:y(["relative w-10 h-5 rounded-full transition-colors",s.enabled?"bg-primary":"bg-muted"])},[t("span",{class:y(["absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform",s.enabled?"translate-x-5":"translate-x-0.5"])},null,2)],10,K),t("button",{onClick:k=>x(s.id),class:"p-1.5 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive"},[m(p(B),{class:"w-4 h-4"})],8,O)])]))),128))]))]))}});export{ee as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as q,o as V,m as d,e as r,a as t,h as c,u as v,g as $,F as y,p as k,G as p,z as w,A as h,d as P,C as T,t as m,r as n,k as b}from"./index-
|
|
1
|
+
import{i as q,o as V,m as d,e as r,a as t,h as c,u as v,g as $,F as y,p as k,G as p,z as w,A as h,d as P,C as T,t as m,r as n,k as b}from"./index-BQdXxKfc.js";import{b as A,c as N,d as z,a as U}from"./api-DdW5uOZf.js";import{P as B}from"./plus-Cvp1w2CO.js";import{T as D}from"./trash-2-Cr3vrmL5.js";const I={class:"p-6"},M={class:"flex items-center justify-between mb-6"},j={class:"flex gap-1 border-b border-border mb-4"},E=["onClick"],F={key:0,class:"border border-border rounded-lg p-4 mb-4 space-y-3"},G={class:"grid grid-cols-2 gap-3"},L={key:0},O={key:1},H={key:1,class:"text-muted-foreground"},J={key:2,class:"text-center py-12 text-muted-foreground"},K={key:3,class:"space-y-2"},Q={class:"text-sm font-medium font-mono"},R={class:"text-xs text-muted-foreground mt-0.5"},W={class:"flex items-center gap-3"},X=["onClick"],Y=["onClick"],ae=q({__name:"SchedulesView",setup(Z){const l=n([]),g=n(!0),u=n("squad"),i=n(!1),s=n({type:"squad",cron:"",squad_id:"",agenda:"triage",prompt:""});V(async()=>{try{l.value=await A("/schedules")}finally{g.value=!1}});const f=()=>l.value.filter(a=>a.type===u.value);async function _(){const a={type:s.value.type,cron:s.value.cron};s.value.type==="squad"?(a.squad_id=s.value.squad_id,a.agenda=s.value.agenda):a.prompt=s.value.prompt;const e=await N("/schedules",a);l.value.push(e),i.value=!1}async function S(a){const e=!a.enabled;await z(`/schedules/${a.id}`,{enabled:e}),a.enabled=e?1:0}async function C(a){await U(`/schedules/${a}`),l.value=l.value.filter(e=>e.id!==a)}return(a,e)=>(d(),r("div",I,[t("div",M,[e[6]||(e[6]=t("h1",{class:"text-2xl font-bold"},"Schedules",-1)),t("button",{onClick:e[0]||(e[0]=o=>i.value=!i.value),class:"inline-flex items-center gap-1 px-3 py-1.5 text-sm rounded-md bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"},[c(v(B),{class:"w-4 h-4"}),e[5]||(e[5]=$(" Add Schedule ",-1))])]),t("div",j,[(d(),r(y,null,k(["squad","io"],o=>t("button",{key:o,onClick:x=>u.value=o,class:b(["px-4 py-2 text-sm font-medium border-b-2 transition-colors",u.value===o?"border-primary text-foreground":"border-transparent text-muted-foreground hover:text-foreground"])},m(o==="squad"?"Squad Schedules":"IO Schedules"),11,E)),64))]),i.value?(d(),r("div",F,[t("div",G,[t("div",null,[e[8]||(e[8]=t("label",{class:"text-sm font-medium"},"Type",-1)),p(t("select",{"onUpdate:modelValue":e[1]||(e[1]=o=>s.value.type=o),class:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"},[...e[7]||(e[7]=[t("option",{value:"squad"},"Squad",-1),t("option",{value:"io"},"IO",-1)])],512),[[w,s.value.type]])]),t("div",null,[e[9]||(e[9]=t("label",{class:"text-sm font-medium"},"Cron Expression",-1)),p(t("input",{"onUpdate:modelValue":e[2]||(e[2]=o=>s.value.cron=o),placeholder:"0 9 * * 1-5",class:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"},null,512),[[h,s.value.cron]])])]),s.value.type==="squad"?(d(),r("div",L,[e[11]||(e[11]=t("label",{class:"text-sm font-medium"},"Agenda",-1)),p(t("select",{"onUpdate:modelValue":e[3]||(e[3]=o=>s.value.agenda=o),class:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"},[...e[10]||(e[10]=[t("option",{value:"triage"},"Triage",-1),t("option",{value:"prioritize"},"Prioritize",-1),t("option",{value:"ideation"},"Ideation",-1)])],512),[[w,s.value.agenda]])])):(d(),r("div",O,[e[12]||(e[12]=t("label",{class:"text-sm font-medium"},"Prompt",-1)),p(t("textarea",{"onUpdate:modelValue":e[4]||(e[4]=o=>s.value.prompt=o),rows:"2",class:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"},null,512),[[h,s.value.prompt]])])),t("button",{onClick:_,class:"px-4 py-2 text-sm rounded-md bg-primary text-primary-foreground hover:bg-primary/90"},"Save")])):P("",!0),g.value?(d(),r("div",H,"Loading...")):f().length===0?(d(),r("div",J,[c(v(T),{class:"w-12 h-12 mx-auto mb-3 opacity-50"}),t("p",null,"No "+m(u.value)+" schedules configured.",1)])):(d(),r("div",K,[(d(!0),r(y,null,k(f(),o=>(d(),r("div",{key:o.id,class:"flex items-center justify-between border border-border rounded-lg px-4 py-3"},[t("div",null,[t("div",Q,m(o.cron),1),t("div",R,m(o.type==="squad"?`Agenda: ${o.agenda}`:o.prompt.slice(0,60)),1)]),t("div",W,[t("button",{onClick:x=>S(o),class:b(["relative w-10 h-5 rounded-full transition-colors",o.enabled?"bg-primary":"bg-muted"])},[t("span",{class:b(["absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform",o.enabled?"translate-x-5":"translate-x-0.5"])},null,2)],10,X),t("button",{onClick:x=>C(o.id),class:"p-1.5 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive"},[c(v(D),{class:"w-4 h-4"})],8,Y)])]))),128))]))]))}});export{ae as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as w,o as E,m as d,e as s,a as t,t as g,F as x,p as U,G as a,A as n,z as M,y as p,d as b,r,k as T}from"./index-
|
|
1
|
+
import{i as w,o as E,m as d,e as s,a as t,t as g,F as x,p as U,G as a,A as n,z as M,y as p,d as b,r,k as T}from"./index-BQdXxKfc.js";import{b as V,d as S}from"./api-DdW5uOZf.js";const z={class:"p-6"},A={class:"flex items-center justify-between mb-6"},B=["disabled"],N={key:0,class:"text-muted-foreground"},C={class:"flex gap-1 border-b border-border mb-6"},I=["onClick"],D={key:0,class:"space-y-4 max-w-lg"},K={class:"flex items-center gap-3"},G={key:1,class:"space-y-4 max-w-lg"},L={class:"flex items-center gap-3"},j={key:2,class:"space-y-4 max-w-lg"},F={key:3,class:"space-y-4 max-w-lg"},O={class:"flex items-center gap-3"},P={class:"flex items-center gap-3"},H=w({__name:"SettingsView",setup(R){const f=r(!0),i=r(!1),m=r(!1),u=r("general"),y=[{id:"general",label:"General"},{id:"telegram",label:"Telegram"},{id:"auth",label:"Auth"},{id:"advanced",label:"Advanced"}],o=r({defaultModel:"",port:3170,telegramEnabled:!1,telegramBotToken:"",authorizedUserId:null,supabaseUrl:"",supabaseAnonKey:"",authorizedEmail:"",backgroundNotifyMode:"meaningful",backgroundNotifyTelegram:!0,selfEditEnabled:!1,watchdogEnabled:!0});async function k(){f.value=!0;try{const v=await V("/settings");o.value=v}finally{f.value=!1}}async function c(){i.value=!0,m.value=!1;try{await S("/settings",o.value),m.value=!0,setTimeout(()=>m.value=!1,2e3)}finally{i.value=!1}}return E(k),(v,e)=>(d(),s("div",z,[t("div",A,[e[12]||(e[12]=t("h1",{class:"text-2xl font-bold"},"Settings",-1)),t("button",{onClick:c,disabled:i.value,class:"px-4 py-2 rounded-md bg-primary text-primary-foreground text-sm hover:bg-primary/90 disabled:opacity-50"},g(i.value?"Saving...":m.value?"Saved ✓":"Save"),9,B)]),f.value?(d(),s("div",N,"Loading...")):(d(),s(x,{key:1},[t("div",C,[(d(),s(x,null,U(y,l=>t("button",{key:l.id,onClick:q=>u.value=l.id,class:T(["px-4 py-2 text-sm font-medium border-b-2 transition-colors",u.value===l.id?"border-primary text-foreground":"border-transparent text-muted-foreground hover:text-foreground"])},g(l.label),11,I)),64))]),u.value==="general"?(d(),s("div",D,[t("div",null,[e[13]||(e[13]=t("label",{class:"text-sm font-medium"},"Default Model",-1)),a(t("input",{"onUpdate:modelValue":e[0]||(e[0]=l=>o.value.defaultModel=l),class:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"},null,512),[[n,o.value.defaultModel]])]),t("div",null,[e[14]||(e[14]=t("label",{class:"text-sm font-medium"},"Port",-1)),a(t("input",{"onUpdate:modelValue":e[1]||(e[1]=l=>o.value.port=l),type:"number",class:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"},null,512),[[n,o.value.port,void 0,{number:!0}]]),e[15]||(e[15]=t("p",{class:"text-xs text-muted-foreground mt-1"},"Requires restart to take effect",-1))]),t("div",null,[e[17]||(e[17]=t("label",{class:"text-sm font-medium"},"Background Notify Mode",-1)),a(t("select",{"onUpdate:modelValue":e[2]||(e[2]=l=>o.value.backgroundNotifyMode=l),class:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"},[...e[16]||(e[16]=[t("option",{value:"all"},"All",-1),t("option",{value:"meaningful"},"Meaningful",-1),t("option",{value:"off"},"Off",-1)])],512),[[M,o.value.backgroundNotifyMode]])]),t("div",K,[a(t("input",{"onUpdate:modelValue":e[3]||(e[3]=l=>o.value.backgroundNotifyTelegram=l),type:"checkbox",id:"notifyTelegram",class:"rounded"},null,512),[[p,o.value.backgroundNotifyTelegram]]),e[18]||(e[18]=t("label",{for:"notifyTelegram",class:"text-sm font-medium"},"Send notifications via Telegram",-1))])])):b("",!0),u.value==="telegram"?(d(),s("div",G,[t("div",null,[e[19]||(e[19]=t("label",{class:"text-sm font-medium"},"Bot Token",-1)),a(t("input",{"onUpdate:modelValue":e[4]||(e[4]=l=>o.value.telegramBotToken=l),type:"password",placeholder:"Enter new token to update",class:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"},null,512),[[n,o.value.telegramBotToken]])]),t("div",null,[e[20]||(e[20]=t("label",{class:"text-sm font-medium"},"Authorized User ID",-1)),a(t("input",{"onUpdate:modelValue":e[5]||(e[5]=l=>o.value.authorizedUserId=l),type:"number",placeholder:"123456789",class:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"},null,512),[[n,o.value.authorizedUserId,void 0,{number:!0}]])]),t("div",L,[a(t("input",{"onUpdate:modelValue":e[6]||(e[6]=l=>o.value.telegramEnabled=l),type:"checkbox",id:"telegramEnabled",class:"rounded"},null,512),[[p,o.value.telegramEnabled]]),e[21]||(e[21]=t("label",{for:"telegramEnabled",class:"text-sm font-medium"},"Enable Telegram Bot",-1))])])):b("",!0),u.value==="auth"?(d(),s("div",j,[t("div",null,[e[22]||(e[22]=t("label",{class:"text-sm font-medium"},"Supabase URL",-1)),a(t("input",{"onUpdate:modelValue":e[7]||(e[7]=l=>o.value.supabaseUrl=l),placeholder:"https://your-project.supabase.co",class:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"},null,512),[[n,o.value.supabaseUrl]])]),t("div",null,[e[23]||(e[23]=t("label",{class:"text-sm font-medium"},"Supabase Anon Key",-1)),a(t("input",{"onUpdate:modelValue":e[8]||(e[8]=l=>o.value.supabaseAnonKey=l),type:"password",placeholder:"Enter new key to update",class:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"},null,512),[[n,o.value.supabaseAnonKey]])]),t("div",null,[e[24]||(e[24]=t("label",{class:"text-sm font-medium"},"Authorized Email",-1)),a(t("input",{"onUpdate:modelValue":e[9]||(e[9]=l=>o.value.authorizedEmail=l),type:"email",placeholder:"you@example.com",class:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"},null,512),[[n,o.value.authorizedEmail]])])])):b("",!0),u.value==="advanced"?(d(),s("div",F,[t("div",O,[a(t("input",{"onUpdate:modelValue":e[10]||(e[10]=l=>o.value.selfEditEnabled=l),type:"checkbox",id:"selfEdit",class:"rounded"},null,512),[[p,o.value.selfEditEnabled]]),e[25]||(e[25]=t("div",null,[t("label",{for:"selfEdit",class:"text-sm font-medium"},"Self-Edit Mode"),t("p",{class:"text-xs text-muted-foreground"},"Allow IO to modify its own source code")],-1))]),t("div",P,[a(t("input",{"onUpdate:modelValue":e[11]||(e[11]=l=>o.value.watchdogEnabled=l),type:"checkbox",id:"watchdog",class:"rounded"},null,512),[[p,o.value.watchdogEnabled]]),e[26]||(e[26]=t("div",null,[t("label",{for:"watchdog",class:"text-sm font-medium"},"Watchdog"),t("p",{class:"text-xs text-muted-foreground"},"Monitor event loop and zombie instances")],-1))])])):b("",!0)],64))]))}});export{H as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as E,o as M,m as l,e as o,a as e,h as u,u as d,g as T,G as $,A as P,H as A,t as m,d as _,P as V,F as w,p as D,b as I,r as a,k as K,J as U}from"./index-
|
|
1
|
+
import{i as E,o as M,m as l,e as o,a as e,h as u,u as d,g as T,G as $,A as P,H as A,t as m,d as _,P as V,F as w,p as D,b as I,r as a,k as K,J as U}from"./index-BQdXxKfc.js";import{b as F,c as G,d as H,a as J}from"./api-DdW5uOZf.js";import{_ as R}from"./MarkdownContent.vue_vue_type_script_setup_true_lang-CEo_ckIb.js";import{P as X}from"./plus-Cvp1w2CO.js";import{P as q,S as O,X as Q}from"./x-O3fBd1Cr.js";import{T as W}from"./trash-2-Cr3vrmL5.js";const Y={class:"flex h-full"},Z={class:"w-72 border-r border-border flex flex-col shrink-0"},ee={class:"p-3 border-b border-border space-y-2"},te={key:0,class:"space-y-1.5"},se={class:"flex gap-1"},le=["disabled"],oe={class:"flex-1 overflow-y-auto p-2"},ae={key:0,class:"text-xs text-muted-foreground p-2"},ne={key:1,class:"text-center py-8 text-muted-foreground"},re=["onClick"],ie={class:"min-w-0 flex-1"},ue={class:"font-medium truncate"},de={class:"text-muted-foreground truncate"},ce=["onClick"],ve={class:"flex-1 flex flex-col"},fe={key:0,class:"flex items-center justify-center h-full text-muted-foreground"},me={class:"text-center"},pe={class:"flex items-center justify-between px-4 py-2 border-b border-border"},xe={class:"text-sm font-medium"},ge={class:"text-xs text-muted-foreground ml-2 font-mono"},ye={class:"flex gap-1"},be={class:"flex-1 overflow-y-auto p-4"},ke={key:0,class:"text-muted-foreground text-sm"},he={key:0,class:"absolute bottom-4 left-4 text-sm text-destructive bg-background border border-destructive/30 px-3 py-2 rounded-md"},Fe=E({__name:"SkillsView",setup(_e){const b=a([]),k=a(!0),p=a(!1),i=a(""),g=a(!1),c=a(""),r=a(null),v=a(""),f=a(!1),x=a(""),h=a(!1);async function y(){k.value=!0;try{b.value=await F("/skills")}finally{k.value=!1}}async function C(){if(i.value.trim()){g.value=!0,c.value="";try{await G("/skills",{url:i.value.trim()}),i.value="",p.value=!1,await y()}catch(n){c.value=n.message||"Failed to install skill"}finally{g.value=!1}}}async function L(n){var t;try{await J(`/skills/${n}`),((t=r.value)==null?void 0:t.slug)===n&&(r.value=null,v.value=""),await y()}catch(s){c.value=s.message||"Failed to remove skill"}}async function N(n){r.value=n,f.value=!1,h.value=!0;try{const t=await F(`/skills/${n.slug}/content`);v.value=t.content}catch(t){v.value=`Error loading skill: ${t.message}`}finally{h.value=!1}}function j(){x.value=v.value,f.value=!0}async function z(){if(r.value)try{await H(`/skills/${r.value.slug}/content`,{content:x.value}),v.value=x.value,f.value=!1,await y()}catch(n){c.value=n.message||"Failed to save skill"}}return M(y),(n,t)=>(l(),o("div",Y,[e("div",Z,[e("div",ee,[e("button",{onClick:t[0]||(t[0]=s=>p.value=!p.value),class:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs rounded-md bg-primary text-primary-foreground hover:bg-primary/90"},[u(d(X),{class:"w-3.5 h-3.5"}),t[5]||(t[5]=T(" Add Skill ",-1))]),p.value?(l(),o("div",te,[$(e("input",{"onUpdate:modelValue":t[1]||(t[1]=s=>i.value=s),type:"text",placeholder:"https://github.com/user/skill-repo.git",class:"w-full rounded-md border border-input bg-background px-2 py-1.5 text-xs focus:outline-none focus:ring-1 focus:ring-ring",onKeyup:A(C,["enter"])},null,544),[[P,i.value]]),e("div",se,[e("button",{onClick:C,disabled:g.value||!i.value.trim(),class:"flex-1 px-2 py-1 text-xs rounded bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50"},m(g.value?"Installing...":"Install"),9,le),e("button",{onClick:t[2]||(t[2]=s=>{p.value=!1,i.value=""}),class:"px-2 py-1 text-xs rounded border border-border hover:bg-accent"}," Cancel ")])])):_("",!0)]),e("div",oe,[k.value?(l(),o("div",ae,"Loading...")):b.value.length===0?(l(),o("div",ne,[u(d(V),{class:"w-8 h-8 mx-auto mb-2 opacity-50"}),t[6]||(t[6]=e("p",{class:"text-xs"},"No skills installed.",-1))])):_("",!0),(l(!0),o(w,null,D(b.value,s=>{var S;return l(),o("div",{key:s.slug,onClick:B=>N(s),class:K(["flex items-center justify-between px-2 py-2 text-xs rounded cursor-pointer hover:bg-accent transition-colors group",{"bg-accent font-medium":((S=r.value)==null?void 0:S.slug)===s.slug}])},[e("div",ie,[e("div",ue,m(s.name),1),e("div",de,m(s.slug),1)]),e("button",{onClick:U(B=>L(s.slug),["stop"]),class:"opacity-0 group-hover:opacity-100 p-1 rounded hover:bg-destructive/10 text-destructive transition-opacity shrink-0",title:"Remove"},[u(d(W),{class:"w-3.5 h-3.5"})],8,ce)],10,re)}),128))])]),e("div",ve,[r.value?(l(),o(w,{key:1},[e("div",pe,[e("div",null,[e("span",xe,m(r.value.name),1),e("span",ge,m(r.value.slug)+"/SKILL.md",1)]),e("div",ye,[f.value?(l(),o(w,{key:1},[e("button",{onClick:z,class:"p-1.5 rounded hover:bg-accent text-green-500",title:"Save"},[u(d(O),{class:"w-4 h-4"})]),e("button",{onClick:t[3]||(t[3]=s=>f.value=!1),class:"p-1.5 rounded hover:bg-accent text-muted-foreground",title:"Cancel"},[u(d(Q),{class:"w-4 h-4"})])],64)):(l(),o("button",{key:0,onClick:j,class:"p-1.5 rounded hover:bg-accent text-muted-foreground",title:"Edit"},[u(d(q),{class:"w-4 h-4"})]))])]),e("div",be,[h.value?(l(),o("div",ke,"Loading...")):f.value?$((l(),o("textarea",{key:1,"onUpdate:modelValue":t[4]||(t[4]=s=>x.value=s),class:"w-full h-full min-h-[400px] font-mono text-sm bg-background border border-input rounded-md p-3 focus:outline-none focus:ring-1 focus:ring-ring resize-none"},null,512)),[[P,x.value]]):(l(),I(R,{key:2,content:v.value},null,8,["content"]))])],64)):(l(),o("div",fe,[e("div",me,[u(d(V),{class:"w-12 h-12 mx-auto mb-3 opacity-50"}),t[7]||(t[7]=e("p",null,"Select a skill to view",-1))])]))]),c.value?(l(),o("p",he,m(c.value),1)):_("",!0)]))}});export{Fe as default};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{f as m,i as w,o as C,m as o,e as l,h as d,E as q,F as c,a as e,t as a,p as b,d as r,w as A,r as i,q as L,k as g,u as p,g as x}from"./index-
|
|
1
|
+
import{f as m,i as w,o as C,m as o,e as l,h as d,E as q,F as c,a as e,t as a,p as b,d as r,w as A,r as i,q as L,k as g,u as p,g as x}from"./index-BQdXxKfc.js";import{b as M}from"./api-DdW5uOZf.js";/**
|
|
2
2
|
* @license lucide-vue-next v0.474.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as _}from"./api-
|
|
1
|
+
import{b as _}from"./api-DdW5uOZf.js";import{f,i as x,o as y,m as o,e as r,a as e,h as u,u as m,U as h,F as v,p as k,r as c,b,E as q,q as w,t as n,g as B,d as N}from"./index-BQdXxKfc.js";/**
|
|
2
2
|
* @license lucide-vue-next v0.474.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{f as _,i as L,D as H,m as l,e as p,F as k,p as I,c as D,l as z,k as E,b as P,u as f,h as m,a as s,t as j,r as v,o as Q,G as S,A as V,g as U,H as W,d as A,B as G}from"./index-
|
|
1
|
+
import{f as _,i as L,D as H,m as l,e as p,F as k,p as I,c as D,l as z,k as E,b as P,u as f,h as m,a as s,t as j,r as v,o as Q,G as S,A as V,g as U,H as W,d as A,B as G}from"./index-BQdXxKfc.js";import{b as N,d as T,a as K}from"./api-DdW5uOZf.js";import{_ as R}from"./MarkdownContent.vue_vue_type_script_setup_true_lang-CEo_ckIb.js";import{P as Z}from"./plus-Cvp1w2CO.js";import{P as O,S as X,X as J}from"./x-O3fBd1Cr.js";import{T as Y}from"./trash-2-Cr3vrmL5.js";/**
|
|
2
2
|
* @license lucide-vue-next v0.474.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{v as c,s as i}from"./index-BQdXxKfc.js";const o="/api";function u(t){try{return JSON.parse(atob(t.split(".")[1])).exp*1e3<=Date.now()+6e4}catch{return!0}}async function s(){const t=c(),e={"Content-Type":"application/json"};return t.token&&u(t.token)&&await t.refreshToken(),t.token&&(e.Authorization=`Bearer ${t.token}`),e}async function n(t,e){if(t.status===401){const r=c();try{if(await r.refreshToken(),r.token){const a=await e();if(a.status===401)throw r.logout(),i.push("/login"),new Error("Session expired");return a}}catch{}throw r.logout(),i.push("/login"),new Error("Session expired")}return t}async function w(t){const e=await n(await fetch(`${o}${t}`,{headers:await s()}),async()=>fetch(`${o}${t}`,{headers:await s()}));if(!e.ok)throw new Error(`API error: ${e.status}`);return e.json()}async function f(t,e){const r={method:"POST",headers:await s(),body:e?JSON.stringify(e):void 0},a=await n(await fetch(`${o}${t}`,r),async()=>fetch(`${o}${t}`,{...r,headers:await s()}));if(!a.ok)throw new Error(`API error: ${a.status}`);return a.json()}async function d(t,e){const r={method:"PUT",headers:await s(),body:e?JSON.stringify(e):void 0},a=await n(await fetch(`${o}${t}`,r),async()=>fetch(`${o}${t}`,{...r,headers:await s()}));if(!a.ok)throw new Error(`API error: ${a.status}`);return a.json()}async function $(t){const e={method:"DELETE",headers:await s()},r=await n(await fetch(`${o}${t}`,e),async()=>fetch(`${o}${t}`,{...e,headers:await s()}));if(!r.ok)throw new Error(`API error: ${r.status}`);return r.json()}export{$ as a,w as b,f as c,d};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ChatView-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ChatView-mZaaw3pd.js","assets/api-DdW5uOZf.js","assets/MarkdownContent.vue_vue_type_script_setup_true_lang-CEo_ckIb.js","assets/SquadsView-CZFxtOao.js","assets/SquadDetailView-CQhFfZTc.js","assets/FeedView-BHacQwXQ.js","assets/trash-2-Cr3vrmL5.js","assets/SkillsView-gCfQ35FQ.js","assets/plus-Cvp1w2CO.js","assets/x-O3fBd1Cr.js","assets/McpView-BAVRUHIE.js","assets/SchedulesView-dOd1SQiP.js","assets/WikiView-B0cuUFfm.js","assets/SettingsView-CCDeEsVg.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))s(n);new MutationObserver(n=>{for(const i of n)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&s(o)}).observe(document,{childList:!0,subtree:!0});function r(n){const i={};return n.integrity&&(i.integrity=n.integrity),n.referrerPolicy&&(i.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?i.credentials="include":n.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function s(n){if(n.ep)return;n.ep=!0;const i=r(n);fetch(n.href,i)}})();const Rc="modulepreload",Oc=function(t){return"/"+t},Wi={},We=function(e,r,s){let n=Promise.resolve();if(r&&r.length>0){let o=function(c){return Promise.all(c.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),l=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));n=o(r.map(c=>{if(c=Oc(c),c in Wi)return;Wi[c]=!0;const u=c.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${h}`))return;const d=document.createElement("link");if(d.rel=u?"stylesheet":Rc,u||(d.as="script"),d.crossOrigin="",d.href=c,l&&d.setAttribute("nonce",l),document.head.appendChild(d),u)return new Promise((f,m)=>{d.addEventListener("load",f),d.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return n.then(o=>{for(const a of o||[])a.status==="rejected"&&i(a.reason);return e().catch(i)})};/**
|
|
3
3
|
* @vue/shared v3.5.34
|
|
4
4
|
* (c) 2018-present Yuxi (Evan) You and Vue contributors
|
|
@@ -70,7 +70,7 @@ Request ID: ${l}`),c){let _=`
|
|
|
70
70
|
Resources:`;for(const b of c){if(!b||typeof b!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${b}`);_+=`
|
|
71
71
|
- ${b}`}E+=_}return`${A}
|
|
72
72
|
${E}`}class ge extends Error{constructor({message:e,code:r,cause:s,name:n}){var i;super(e,{cause:s}),this.__isWebAuthnError=!0,this.name=(i=n??(s instanceof Error?s.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=r}toJSON(){return{name:this.name,message:this.message,code:this.code}}}class Ys extends ge{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r}}function jg({error:t,options:e}){var r,s,n;const{publicKey:i}=e;if(!i)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ge({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=i.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===!0)return new ge({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((s=i.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new ge({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new ge({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if(t.name==="InvalidStateError")return new ge({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new ge({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return i.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new ge({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new ge({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){const o=window.location.hostname;if(Sc(o)){if(i.rp.id!==o)return new ge({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new ge({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new ge({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if(t.name==="UnknownError")return new ge({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new ge({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Ng({error:t,options:e}){const{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new ge({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if(t.name==="NotAllowedError")return new ge({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){const s=window.location.hostname;if(Sc(s)){if(r.rpId!==s)return new ge({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new ge({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new ge({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return new ge({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}class $g{createNewAbortSignal(){if(this.controller){const r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}const e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){const e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0}}}const wi=new $g;function ya(t){if(!t)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(t);const{challenge:e,user:r,excludeCredentials:s}=t,n=bn(t,["challenge","user","excludeCredentials"]),i=Er(e).buffer,o=Object.assign(Object.assign({},r),{id:Er(r.id).buffer}),a=Object.assign(Object.assign({},n),{challenge:i,user:o});if(s&&s.length>0){a.excludeCredentials=new Array(s.length);for(let l=0;l<s.length;l++){const c=s[l];a.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:Er(c.id).buffer,type:c.type||"public-key",transports:c.transports})}}return a}function va(t){if(!t)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(t);const{challenge:e,allowCredentials:r}=t,s=bn(t,["challenge","allowCredentials"]),n=Er(e).buffer,i=Object.assign(Object.assign({},s),{challenge:n});if(r&&r.length>0){i.allowCredentials=new Array(r.length);for(let o=0;o<r.length;o++){const a=r[o];i.allowCredentials[o]=Object.assign(Object.assign({},a),{id:Er(a.id).buffer,type:a.type||"public-key",transports:a.transports})}}return i}function _a(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t;return{id:t.id,rawId:t.id,response:{attestationObject:er(new Uint8Array(t.response.attestationObject)),clientDataJSON:er(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function ba(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();const r=t,s=t.getClientExtensionResults(),n=t.response;return{id:t.id,rawId:t.id,response:{authenticatorData:er(new Uint8Array(n.authenticatorData)),clientDataJSON:er(new Uint8Array(n.clientDataJSON)),signature:er(new Uint8Array(n.signature)),userHandle:n.userHandle?er(new Uint8Array(n.userHandle)):void 0},type:"public-key",clientExtensionResults:s,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Sc(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Xs(){var t,e;return!!(we()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator==null?void 0:navigator.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.get)=="function")}async function Ec(t){try{const e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ys("Browser returned unexpected credential type",e)}:{data:null,error:new Ys("Empty credential response",e)}}catch(e){return{data:null,error:jg({error:e,options:t})}}}async function kc(t){try{const e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new Ys("Browser returned unexpected credential type",e)}:{data:null,error:new Ys("Empty credential response",e)}}catch(e){return{data:null,error:Ng({error:e,options:t})}}}const Lg={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Dg={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function Qs(...t){const e=n=>n!==null&&typeof n=="object"&&!Array.isArray(n),r=n=>n instanceof ArrayBuffer||ArrayBuffer.isView(n),s={};for(const n of t)if(n)for(const i in n){const o=n[i];if(o!==void 0)if(Array.isArray(o))s[i]=o;else if(r(o))s[i]=o;else if(e(o)){const a=s[i];e(a)?s[i]=Qs(a,o):s[i]=Qs(o)}else s[i]=o}return s}function Ug(t,e){return Qs(Lg,t,e||{})}function Bg(t,e){return Qs(Dg,t,e||{})}class Mg{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:"webauthn"}))}async _challenge({factorId:e,webauthn:r,friendlyName:s,signal:n},i){var o;try{const{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return{data:null,error:l};const c=n??wi.createNewAbortSignal();if(a.webauthn.type==="create"){const{user:u}=a.webauthn.credential_options.publicKey;if(!u.name){const h=s;if(h)u.name=`${u.id}:${h}`;else{const f=(await this.client.getUser()).data.user,m=((o=f==null?void 0:f.user_metadata)===null||o===void 0?void 0:o.name)||(f==null?void 0:f.email)||(f==null?void 0:f.id)||"User";u.name=`${u.id}:${m}`}}u.displayName||(u.displayName=u.name)}switch(a.webauthn.type){case"create":{const u=Ug(a.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:h,error:d}=await Ec({publicKey:u,signal:c});return h?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:h}},error:null}:{data:null,error:d}}case"request":{const u=Bg(a.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:h,error:d}=await kc(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:u,signal:c}));return h?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:h}},error:null}:{data:null,error:d}}}}catch(a){return x(a)?{data:null,error:a}:{data:null,error:new Ye("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:s}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:s})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new Cr("rpId is required for WebAuthn authentication")};try{if(!Xs())return{data:null,error:new Ye("Browser does not support WebAuthn",null)};const{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:s},signal:n},{request:i});if(!o)return{data:null,error:a};const{webauthn:l}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:s,credential_response:l.credential_response}})}catch(o){return x(o)?{data:null,error:o}:{data:null,error:new Ye("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:s=typeof window<"u"?[window.location.origin]:void 0,signal:n}={}},i){if(!r)return{data:null,error:new Cr("rpId is required for WebAuthn registration")};try{if(!Xs())return{data:null,error:new Ye("Browser does not support WebAuthn",null)};const{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(u=>{var h;return(h=u.data)===null||h===void 0?void 0:h.all.find(d=>d.factor_type==="webauthn"&&d.friendly_name===e&&d.status!=="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u==null?void 0:u.id}):void 0),{data:null,error:a};const{data:l,error:c}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:s},signal:n},{create:i});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:s,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(o){return x(o)?{data:null,error:o}:{data:null,error:new Ye("Unexpected error in register",o)}}}}Cg();const Hg={url:Kp,storageKey:Wp,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Gp,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};async function wa(t,e,r){return await r()}const hr={};class ps{get jwks(){var e,r;return(r=(e=hr[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){hr[this.storageKey]=Object.assign(Object.assign({},hr[this.storageKey]),{jwks:e})}get jwks_cached_at(){var e,r;return(r=(e=hr[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){hr[this.storageKey]=Object.assign(Object.assign({},hr[this.storageKey]),{cachedAt:e})}constructor(e){var r,s,n,i;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const o=Object.assign(Object.assign({},Hg),e);if(this.storageKey=o.storageKey,this.instanceID=(r=ps.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,ps.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!o.debug,typeof o.debug=="function"&&(this.logger=o.debug),this.instanceID>0&&we()){const a=`${this._logPrefix()} 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.`;console.warn(a),this.logDebugMessages&&console.trace(a)}if(this.persistSession=o.persistSession,this.autoRefreshToken=o.autoRefreshToken,this.experimental=(s=o.experimental)!==null&&s!==void 0?s:{},this.admin=new Rg({url:o.url,headers:o.headers,fetch:o.fetch,experimental:this.experimental}),this.url=o.url,this.headers=o.headers,this.fetch=_c(o.fetch),this.lock=o.lock||wa,this.detectSessionInUrl=o.detectSessionInUrl,this.flowType=o.flowType,this.hasCustomAuthorizationHeader=o.hasCustomAuthorizationHeader,this.throwOnError=o.throwOnError,this.lockAcquireTimeout=o.lockAcquireTimeout,o.lock?this.lock=o.lock:this.persistSession&&we()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=Og:this.lock=wa,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),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),webauthn:new Mg(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(o.storage?this.storage=o.storage:vc()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=ga(this.memoryStorage)),o.userStorage&&(this.userStorage=o.userStorage)):(this.memoryStorage={},this.storage=ga(this.memoryStorage)),we()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(a){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",a)}(i=this.broadcastChannel)===null||i===void 0||i.addEventListener("message",async a=>{this._debug("received broadcast notification from other tab or client",a);try{await this._notifyAllSubscribers(a.data.event,a.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}o.skipAutoInitialize||this.initialize().catch(a=>{this._debug("#initialize()","error",a)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${gc}) ${new Date().toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var e;try{let r={},s="none";if(we()&&(r=ag(window.location.href),this._isImplicitGrantCallback(r)?s="implicit":await this._isPKCECallback(r)&&(s="pkce")),we()&&this.detectSessionInUrl&&s!=="none"){const{data:n,error:i}=await this._getSessionFromURL(r,s);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Qp(i)){const l=(e=i.details)===null||e===void 0?void 0:e.code;if(l==="identity_already_exists"||l==="identity_not_found"||l==="single_identity_not_deletable")return{error:i}}return{error:i}}const{session:o,redirectType:a}=n;return this._debug("#_initialize()","detected session in URL",o,"redirect type",a),await this._saveSession(o),setTimeout(async()=>{a==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(r){return x(r)?this._returnResult({error:r}):this._returnResult({error:new Ye("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var r,s,n;try{const i=await L(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(s=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.data)!==null&&s!==void 0?s:{},gotrue_meta_security:{captcha_token:(n=e==null?void 0:e.options)===null||n===void 0?void 0:n.captchaToken}},xform:qe}),{data:o,error:a}=i;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});const l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(x(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(e){var r,s,n;try{let i;if("email"in e){const{email:u,password:h,options:d}=e;let f=null,m=null;this.flowType==="pkce"&&([f,m]=await ur(this.storage,this.storageKey)),i=await L(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d==null?void 0:d.emailRedirectTo,body:{email:u,password:h,data:(r=d==null?void 0:d.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken},code_challenge:f,code_challenge_method:m},xform:qe})}else if("phone"in e){const{phone:u,password:h,options:d}=e;i=await L(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:h,data:(s=d==null?void 0:d.data)!==null&&s!==void 0?s:{},channel:(n=d==null?void 0:d.channel)!==null&&n!==void 0?n:"sms",gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken}},xform:qe})}else throw new Cs("You must provide either an email or phone number and a password");const{data:o,error:a}=i;if(a||!o)return await be(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});const l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(i){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithPassword(e){try{let r;if("email"in e){const{email:i,password:o,options:a}=e;r=await L(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:fa})}else if("phone"in e){const{phone:i,password:o,options:a}=e;r=await L(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:fa})}else throw new Cs("You must provide either an email or phone number and a password");const{data:s,error:n}=r;if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!s||!s.session||!s.user){const i=new cr;return this._returnResult({data:{user:null,session:null},error:i})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign({user:s.user,session:s.session},s.weak_password?{weakPassword:s.weak_password}:null),error:n})}catch(r){if(x(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,s,n,i;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(s=e.options)===null||s===void 0?void 0:s.scopes,queryParams:(n=e.options)===null||n===void 0?void 0:n.queryParams,skipBrowserRedirect:(i=e.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){const{chain:r}=e;switch(r){case"ethereum":return await this.signInWithEthereum(e);case"solana":return await this.signInWithSolana(e);default:throw new Error(`@supabase/auth-js: Unsupported chain "${r}"`)}}async signInWithEthereum(e){var r,s,n,i,o,a,l,c,u,h,d;let f,m;if("message"in e)f=e.message,m=e.signature;else{const{chain:v,wallet:A,statement:E,options:_}=e;let b;if(we())if(typeof A=="object")b=A;else{const V=window;if("ethereum"in V&&typeof V.ethereum=="object"&&"request"in V.ethereum&&typeof V.ethereum.request=="function")b=V.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof A!="object"||!(_!=null&&_.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");b=A}const O=new URL((r=_==null?void 0:_.url)!==null&&r!==void 0?r:window.location.href),B=await b.request({method:"eth_requestAccounts"}).then(V=>V).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!B||B.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const W=wc(B[0]);let q=(s=_==null?void 0:_.signInWithEthereum)===null||s===void 0?void 0:s.chainId;if(!q){const V=await b.request({method:"eth_chainId"});q=Pg(V)}const J={domain:O.host,address:W,statement:E,uri:O.href,version:"1",chainId:q,nonce:(n=_==null?void 0:_.signInWithEthereum)===null||n===void 0?void 0:n.nonce,issuedAt:(o=(i=_==null?void 0:_.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=_==null?void 0:_.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=_==null?void 0:_.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=_==null?void 0:_.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(u=_==null?void 0:_.signInWithEthereum)===null||u===void 0?void 0:u.resources};f=Ig(J),m=await b.request({method:"personal_sign",params:[xg(f),W]})}try{const{data:v,error:A}=await L(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:f,signature:m},!((h=e.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(d=e.options)===null||d===void 0?void 0:d.captchaToken}}:null),xform:qe});if(A)throw A;if(!v||!v.session||!v.user){const E=new cr;return this._returnResult({data:{user:null,session:null},error:E})}return v.session&&(await this._saveSession(v.session),await this._notifyAllSubscribers("SIGNED_IN",v.session)),this._returnResult({data:Object.assign({},v),error:A})}catch(v){if(x(v))return this._returnResult({data:{user:null,session:null},error:v});throw v}}async signInWithSolana(e){var r,s,n,i,o,a,l,c,u,h,d,f;let m,v;if("message"in e)m=e.message,v=e.signature;else{const{chain:A,wallet:E,statement:_,options:b}=e;let O;if(we())if(typeof E=="object")O=E;else{const W=window;if("solana"in W&&typeof W.solana=="object"&&("signIn"in W.solana&&typeof W.solana.signIn=="function"||"signMessage"in W.solana&&typeof W.solana.signMessage=="function"))O=W.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof E!="object"||!(b!=null&&b.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");O=E}const B=new URL((r=b==null?void 0:b.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in O&&O.signIn){const W=await O.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},b==null?void 0:b.signInWithSolana),{version:"1",domain:B.host,uri:B.href}),_?{statement:_}:null));let q;if(Array.isArray(W)&&W[0]&&typeof W[0]=="object")q=W[0];else if(W&&typeof W=="object"&&"signedMessage"in W&&"signature"in W)q=W;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in q&&"signature"in q&&(typeof q.signedMessage=="string"||q.signedMessage instanceof Uint8Array)&&q.signature instanceof Uint8Array)m=typeof q.signedMessage=="string"?q.signedMessage:new TextDecoder().decode(q.signedMessage),v=q.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in O)||typeof O.signMessage!="function"||!("publicKey"in O)||typeof O!="object"||!O.publicKey||!("toBase58"in O.publicKey)||typeof O.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");m=[`${B.host} wants you to sign in with your Solana account:`,O.publicKey.toBase58(),..._?["",_,""]:[""],"Version: 1",`URI: ${B.href}`,`Issued At: ${(n=(s=b==null?void 0:b.signInWithSolana)===null||s===void 0?void 0:s.issuedAt)!==null&&n!==void 0?n:new Date().toISOString()}`,...!((i=b==null?void 0:b.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${b.signInWithSolana.notBefore}`]:[],...!((o=b==null?void 0:b.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${b.signInWithSolana.expirationTime}`]:[],...!((a=b==null?void 0:b.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${b.signInWithSolana.chainId}`]:[],...!((l=b==null?void 0:b.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${b.signInWithSolana.nonce}`]:[],...!((c=b==null?void 0:b.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${b.signInWithSolana.requestId}`]:[],...!((h=(u=b==null?void 0:b.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||h===void 0)&&h.length?["Resources",...b.signInWithSolana.resources.map(q=>`- ${q}`)]:[]].join(`
|
|
73
|
-
`);const W=await O.signMessage(new TextEncoder().encode(m),"utf8");if(!W||!(W instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");v=W}}try{const{data:A,error:E}=await L(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:m,signature:er(v)},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:qe});if(E)throw E;if(!A||!A.session||!A.user){const _=new cr;return this._returnResult({data:{user:null,session:null},error:_})}return A.session&&(await this._saveSession(A.session),await this._notifyAllSubscribers("SIGNED_IN",A.session)),this._returnResult({data:Object.assign({},A),error:E})}catch(A){if(x(A))return this._returnResult({data:{user:null,session:null},error:A});throw A}}async _exchangeCodeForSession(e){const r=await Yt(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new Zp;const{data:i,error:o}=await L(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:qe});if(await be(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){const a=new cr;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers(n==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:n??null}),error:o})}catch(i){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{const{options:r,provider:s,token:n,access_token:i,nonce:o}=e,a=await L(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:qe}),{data:l,error:c}=a;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l||!l.session||!l.user){const u=new cr;return this._returnResult({data:{user:null,session:null},error:u})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:c})}catch(r){if(x(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,o;try{if("email"in e){const{email:a,options:l}=e;let c=null,u=null;this.flowType==="pkce"&&([c,u]=await ur(this.storage,this.storageKey));const{error:h}=await L(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l==null?void 0:l.data)!==null&&r!==void 0?r:{},create_user:(s=l==null?void 0:l.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l==null?void 0:l.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:h})}if("phone"in e){const{phone:a,options:l}=e,{data:c,error:u}=await L(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(n=l==null?void 0:l.data)!==null&&n!==void 0?n:{},create_user:(i=l==null?void 0:l.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},channel:(o=l==null?void 0:l.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:u})}throw new Cs("You must provide either an email or phone number.")}catch(a){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,s;try{let n,i;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:o,error:a}=await L(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:qe});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");const l=o.session,c=o.user;return l!=null&&l.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(n){if(x(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await ur(this.storage,this.storageKey));const c=await L(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:(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&s!==void 0?s:void 0}),!((n=e==null?void 0:e.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:l}),headers:this.headers,xform:kg});return!((i=c.data)===null||i===void 0)&&i.url&&we()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(a){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new ve;const{error:n}=await L(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(x(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:s,type:n,options:i}=e,{error:o}=await L(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){const{phone:s,type:n,options:i}=e,{data:o,error:a}=await L(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:a})}throw new Cs("You must provide either an email or phone number and a type")}catch(r){if(x(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}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{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await Yt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()<Mn:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const o=await Yt(this.userStorage,this.storageKey+"-user");o!=null&&o.user?e.user=o.user:e.user=Fn()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const o={value:this.suppressGetSessionWarning};e.user=bg(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await L(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Ft}):await this._useSession(async r=>{var s,n,i;const{data:o,error:a}=r;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new ve}:await L(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=o.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:Ft})})}catch(r){if(x(r))return Os(r)&&(await this._removeSession(),await be(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async s=>{const{data:n,error:i}=s;if(i)throw i;if(!n.session)throw new ve;const o=n.session;let a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await ur(this.storage,this.storageKey));const{data:c,error:u}=await L(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:Ft});if(u)throw u;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(s){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(s))return this._returnResult({data:{user:null},error:s});throw s}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new ve;const r=Date.now()/1e3;let s=r,n=!0,i=null;const{payload:o}=xs(e.access_token);if(o.exp&&(s=o.exp,n=s<=r),n){const{data:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return{data:{user:null,session:null},error:null};i=a}else{const{data:a,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});i={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-r,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(r){if(x(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var s;if(!e){const{data:o,error:a}=r;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!(e!=null&&e.refresh_token))throw new ve;const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(x(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var s;try{if(!we())throw new Ps("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ps(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new oa("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ps("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new oa("No code detected.");const{data:b,error:O}=await this._exchangeCodeForSession(e.code);if(O)throw O;const B=new URL(window.location.href);return B.searchParams.delete("code"),window.history.replaceState(window.history.state,"",B.toString()),{data:{session:b.session,redirectType:(s=b.redirectType)!==null&&s!==void 0?s:null},error:null}}const{provider_token:n,provider_refresh_token:i,access_token:o,refresh_token:a,expires_in:l,expires_at:c,token_type:u}=e;if(!o||!l||!a||!u)throw new Ps("No session defined in URL");const h=Math.round(Date.now()/1e3),d=parseInt(l);let f=h+d;c&&(f=parseInt(c));const m=f-h;m*1e3<=mr&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${d}s`);const v=f-d;h-v>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",v,f,h):h-v<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",v,f,h);const{data:A,error:E}=await this._getUser(o);if(E)throw E;const _={provider_token:n,provider_refresh_token:i,access_token:o,expires_in:d,expires_at:f,refresh_token:a,token_type:u,user:A.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:_,redirectType:e.type},error:null})}catch(n){if(x(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){const r=await Yt(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i&&!Os(i))return this._returnResult({error:i});const o=(s=n.session)===null||s===void 0?void 0:s.access_token;if(o){const{error:a}=await this.admin.signOut(o,e);if(a&&!(Xp(a)&&(a.status===404||a.status===401||a.status===403)||Os(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await be(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=og(),s={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,s),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,n;try{const{data:{session:i},error:o}=r;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),Os(i)?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await ur(this.storage,this.storageKey,!0));try{return await L(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{const{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{const{data:s,error:n}=await this._useSession(async i=>{var o,a,l,c,u;const{data:h,error:d}=i;if(d)throw d;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await L(this.fetch,"GET",f,{headers:this.headers,jwt:(u=(c=h.session)===null||c===void 0?void 0:c.access_token)!==null&&u!==void 0?u:void 0})});if(n)throw n;return we()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(s==null?void 0:s.url),this._returnResult({data:{provider:e.provider,url:s==null?void 0:s.url},error:null})}catch(s){if(x(s))return this._returnResult({data:{provider:e.provider,url:null},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{const{error:n,data:{session:i}}=r;if(n)throw n;const{options:o,provider:a,token:l,access_token:c,nonce:u}=e,h=await L(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i==null?void 0:i.access_token)!==null&&s!==void 0?s:void 0,body:{provider:a,id_token:l,access_token:c,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:qe}),{data:d,error:f}=h;return f?this._returnResult({data:{user:null,session:null},error:f}):!d||!d.session||!d.user?this._returnResult({data:{user:null,session:null},error:new cr}):(d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("USER_UPDATED",d.session)),this._returnResult({data:d,error:f}))}catch(n){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:o}=r;if(o)throw o;return await L(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{const s=Date.now();return await ug(async n=>(n>0&&await cg(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await L(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:qe})),(n,i)=>{const o=200*Math.pow(2,n);return i&&Hn(i)&&Date.now()+o-s<mr})}catch(s){if(this._debug(r,"error",s),x(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",s),we()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,r;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const n=await Yt(this.storage,this.storageKey);if(n&&this.userStorage){let o=await Yt(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:n.user},await yr(this.userStorage,this.storageKey+"-user",o)),n.user=(e=o==null?void 0:o.user)!==null&&e!==void 0?e:Fn()}else if(n&&!n.user&&!n.user){const o=await Yt(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(n.user=o.user,await be(this.storage,this.storageKey+"-user"),await yr(this.storage,this.storageKey,n)):n.user=Fn()}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}const i=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Mn;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${Mn}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:o}=await this._callRefreshToken(n.refresh_token);o&&(console.error(o),Hn(o)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:o,error:a}=await this._getUser(n.access_token);!a&&(o!=null&&o.user)?(n.user=o.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(s,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new ve;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new En;const{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new ve;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const a={data:i.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(i){if(this._debug(n,"error",i),x(i)){const o={data:null,error:i};return Hn(i)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});const i=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(l){i.push(l)}});if(await Promise.all(o),i.length>0){for(let a=0;a<i.length;a+=1)console.error(i[a]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await be(this.storage,`${this.storageKey}-code-verifier`);const r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await yr(this.userStorage,this.storageKey+"-user",{user:r.user});const n=Object.assign({},r);delete n.user;const i=ha(n);await yr(this.storage,this.storageKey,i)}else{const n=ha(r);await yr(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await be(this.storage,this.storageKey),await be(this.storage,this.storageKey+"-code-verifier"),await be(this.storage,this.storageKey+"-user"),this.userStorage&&await be(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&we()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),mr);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}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{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/mr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${mr}ms, refresh threshold is ${yi} ticks`),n<=yi&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof bc)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!we()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,s){const n=[`provider=${encodeURIComponent(r)}`];if(s!=null&&s.redirectTo&&n.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s!=null&&s.scopes&&n.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[i,o]=await ur(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});n.push(a.toString())}if(s!=null&&s.queryParams){const i=new URLSearchParams(s.queryParams);n.push(i.toString())}return s!=null&&s.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await L(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});const a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:c}=await L(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((n=l==null?void 0:l.totp)===null||n===void 0)&&n.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});const o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?_a(e.webauthn.credential_response):ba(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await L(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:l}))})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});const o=await L(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token});if(o.error)return o;const{data:a}=o;if(a.type!=="webauthn")return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:ya(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:va(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){const{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};const n={all:[],phone:[],totp:[],webauthn:[]};for(const i of(e=r==null?void 0:r.factors)!==null&&e!==void 0?e:[])n.all.push(i),i.status==="verified"&&n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,s,n,i;if(e)try{const{payload:f}=xs(e);let m=null;f.aal&&(m=f.aal);let v=m;const{data:{user:A},error:E}=await this.getUser(e);if(E)return this._returnResult({data:null,error:E});((s=(r=A==null?void 0:A.factors)===null||r===void 0?void 0:r.filter(O=>O.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(v="aal2");const b=f.amr||[];return{data:{currentLevel:m,nextLevel:v,currentAuthenticationMethods:b},error:null}}catch(f){if(x(f))return this._returnResult({data:null,error:f});throw f}const{data:{session:o},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:l}=xs(o.access_token);let c=null;l.aal&&(c=l.aal);let u=c;((i=(n=o.user.factors)===null||n===void 0?void 0:n.filter(f=>f.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(u="aal2");const d=l.amr||[];return{data:{currentLevel:c,nextLevel:u,currentAuthenticationMethods:d},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await L(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new ve})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new ve});const o=await L(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&we()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(s){if(x(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new ve});const o=await L(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&we()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(s){if(x(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await L(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new ve})})}catch(e){if(x(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await L(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new ve})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(a=>a.kid===e);if(s)return s;const n=Date.now();if(s=this.jwks.keys.find(a=>a.kid===e),s&&this.jwks_cached_at+Jp>n)return s;const{data:i,error:o}=await L(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=n,s=i.keys.find(a=>a.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){const{data:f,error:m}=await this.getSession();if(m||!f.session)return this._returnResult({data:null,error:m});s=f.session.access_token}const{header:n,payload:i,signature:o,raw:{header:a,payload:l}}=xs(s);r!=null&&r.allowExpired||yg(i.exp);const c=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r!=null&&r.keys?{keys:r.keys}:r==null?void 0:r.jwks);if(!c){const{error:f}=await this.getUser(s);if(f)throw f;return{data:{claims:i,header:n,signature:o},error:null}}const u=vg(n.alg),h=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,h,o,ng(`${a}.${l}`)))throw new bi("Invalid JWT signature");return{data:{claims:i,header:n,signature:o},error:null}}catch(s){if(x(s))return this._returnResult({data:null,error:s});throw s}}async signInWithPasskey(e){var r,s,n;Ge(this.experimental);try{if(!Xs())return this._returnResult({data:null,error:new Ye("Browser does not support WebAuthn",null)});const{data:i,error:o}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.captchaToken}});if(o||!i)return this._returnResult({data:null,error:o});const a=va(i.options),l=(n=(s=e==null?void 0:e.options)===null||s===void 0?void 0:s.signal)!==null&&n!==void 0?n:wi.createNewAbortSignal(),{data:c,error:u}=await kc({publicKey:a,signal:l});if(u||!c)return this._returnResult({data:null,error:u??new Ye("WebAuthn ceremony failed",null)});const h=ba(c);return this._verifyPasskeyAuthentication({challengeId:i.challenge_id,credential:h})}catch(i){if(x(i))return this._returnResult({data:null,error:i});throw i}}async registerPasskey(e){var r,s;Ge(this.experimental);try{if(!Xs())return this._returnResult({data:null,error:new Ye("Browser does not support WebAuthn",null)});const{data:n,error:i}=await this._startPasskeyRegistration();if(i||!n)return this._returnResult({data:null,error:i});const o=ya(n.options),a=(s=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:wi.createNewAbortSignal(),{data:l,error:c}=await Ec({publicKey:o,signal:a});if(c||!l)return this._returnResult({data:null,error:c??new Ye("WebAuthn ceremony failed",null)});const u=_a(l);return this._verifyPasskeyRegistration({challengeId:n.challenge_id,credential:u})}catch(n){if(x(n))return this._returnResult({data:null,error:n});throw n}}async _startPasskeyRegistration(){Ge(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new ve});const{data:n,error:i}=await L(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:r.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(x(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){Ge(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new ve});const{data:i,error:o}=await L(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:s.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;Ge(this.experimental);try{const{data:s,error:n}=await L(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.captchaToken}}});return n?this._returnResult({data:null,error:n}):this._returnResult({data:s,error:null})}catch(s){if(x(s))return this._returnResult({data:null,error:s});throw s}}async _verifyPasskeyAuthentication(e){Ge(this.experimental);try{const{data:r,error:s}=await L(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:qe});return s?this._returnResult({data:null,error:s}):(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:r,error:null}))}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){Ge(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new ve});const{data:n,error:i}=await L(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:o=>({data:o,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(x(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){Ge(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new ve});const{data:i,error:o}=await L(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){Ge(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new ve});const{error:i}=await L(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}}ps.nextInstanceID={};const Fg=ps,qg="2.106.2";let Hr="";typeof Deno<"u"?Hr="deno":typeof document<"u"?Hr="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Hr="react-native":Hr="node";const Vg={"X-Client-Info":`supabase-js-${Hr}/${qg}`},Kg={headers:Vg},Wg={schema:"public"},Gg={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},zg={},Jg={enabled:!1,respectSamplingDecision:!0};function Yg(t,e,r,s){function n(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function a(u){try{c(s.next(u))}catch(h){o(h)}}function l(u){try{c(s.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):n(u.value).then(a,l)}c((s=s.apply(t,[])).next())})}let Vn=null;const Xg="@opentelemetry/api";function Qg(){return Vn===null&&(Vn=import(Xg).catch(()=>null)),Vn}function Zg(){return Yg(this,void 0,void 0,function*(){try{const t=yield Qg();if(!t||!t.propagation||!t.context)return null;const e={};t.propagation.inject(t.context.active(),e);const r=e.traceparent;return r?{traceparent:r,tracestate:e.tracestate,baggage:e.baggage}:null}catch{return null}})}function em(t){if(!t||typeof t!="string")return null;const e=t.split("-");if(e.length!==4)return null;const[r,s,n,i]=e;if(r.length!==2||s.length!==32||n.length!==16||i.length!==2)return null;const o=/^[0-9a-f]+$/i;return!o.test(r)||!o.test(s)||!o.test(n)||!o.test(i)||s==="00000000000000000000000000000000"||n==="0000000000000000"?null:{version:r,traceId:s,parentId:n,traceFlags:i,isSampled:(parseInt(i,16)&1)===1}}function tm(t,e){if(!t||!e||e.length===0)return!1;let r;if(t instanceof URL)r=t;else try{r=new URL(t)}catch{return!1}for(const s of e)try{if(typeof s=="string"){if(rm(r.hostname,s))return!0}else if(s instanceof RegExp){if(s.test(r.hostname))return!0}else if(typeof s=="function"&&s(r))return!0}catch{continue}return!1}function rm(t,e){if(e===t)return!0;if(e.startsWith("*.")){const r=e.slice(2);if(t.endsWith(r)&&(t===r||t.endsWith("."+r)))return!0}return!1}function sm(t){const e=[];try{const r=new URL(t);e.push(r.hostname)}catch{}return e.push("*.supabase.co","*.supabase.in"),e.push("localhost","127.0.0.1","[::1]"),e}function gs(t){"@babel/helpers - typeof";return gs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},gs(t)}function nm(t,e){if(gs(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(gs(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function im(t){var e=nm(t,"string");return gs(e)=="symbol"?e:e+""}function om(t,e,r){return(e=im(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Sa(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function de(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Sa(Object(r),!0).forEach(function(s){om(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Sa(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const am=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),lm=()=>Headers,cm=(t,e,r,s,n)=>{const i=am(s),o=lm(),a=(n==null?void 0:n.enabled)===!0,l=(n==null?void 0:n.respectSamplingDecision)!==!1,c=a?sm(e):null;return async(u,h)=>{var d;const f=(d=await r())!==null&&d!==void 0?d:t;let m=new o(h==null?void 0:h.headers);if(m.has("apikey")||m.set("apikey",t),m.has("Authorization")||m.set("Authorization",`Bearer ${f}`),c){const v=await um(u,c,l);v&&(v.traceparent&&!m.has("traceparent")&&m.set("traceparent",v.traceparent),v.tracestate&&!m.has("tracestate")&&m.set("tracestate",v.tracestate),v.baggage&&!m.has("baggage")&&m.set("baggage",v.baggage))}return i(u,de(de({},h),{},{headers:m}))}};async function um(t,e,r){if(!tm(typeof t=="string"||t instanceof URL?t:t.url,e))return null;const s=await Zg();if(!s||!s.traceparent)return null;if(r){const n=em(s.traceparent);if(n&&!n.isSampled)return null}return s}function Ea(t){return typeof t=="boolean"?{enabled:t}:t}function hm(t){return t.endsWith("/")?t:t+"/"}function dm(t,e){var r,s,n,i,o,a;const{db:l,auth:c,realtime:u,global:h}=t,{db:d,auth:f,realtime:m,global:v}=e,A=Ea(t.tracePropagation),E=Ea(e.tracePropagation),_={db:de(de({},d),l),auth:de(de({},f),c),realtime:de(de({},m),u),storage:{},global:de(de(de({},v),h),{},{headers:de(de({},(r=v==null?void 0:v.headers)!==null&&r!==void 0?r:{}),(s=h==null?void 0:h.headers)!==null&&s!==void 0?s:{})}),tracePropagation:{enabled:(n=(i=A==null?void 0:A.enabled)!==null&&i!==void 0?i:E==null?void 0:E.enabled)!==null&&n!==void 0?n:!1,respectSamplingDecision:(o=(a=A==null?void 0:A.respectSamplingDecision)!==null&&a!==void 0?a:E==null?void 0:E.respectSamplingDecision)!==null&&o!==void 0?o:!0},accessToken:async()=>""};return t.accessToken?_.accessToken=t.accessToken:delete _.accessToken,_}function fm(t){const e=t==null?void 0:t.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(hm(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var pm=class extends Fg{constructor(t){super(t)}},gm=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;const i=fm(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const o=`sb-${i.hostname.split(".")[0]}-auth-token`,a={db:Wg,realtime:zg,auth:de(de({},Gg),{},{storageKey:o}),global:Kg,tracePropagation:Jg},l=dm(r??{},a);if(this.settings=l,this.storageKey=(s=l.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(u,h)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(h)} is not possible`)}});else{var c;this.auth=this._initSupabaseAuthClient((c=l.auth)!==null&&c!==void 0?c:{},this.headers,l.global.fetch)}this.fetch=cm(e,t,this._getAccessToken.bind(this),l.global.fetch,l.tracePropagation),this.realtime=this._initRealtimeClient(de({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(u=>this.realtime.setAuth(u)).catch(u=>console.warn("Failed to set initial Realtime auth token:",u)),this.rest=new xf(new URL("rest/v1",i).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new Vp(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new wf(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:s}=await t.auth.getSession();return(e=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:o,lock:a,debug:l,throwOnError:c,experimental:u,lockAcquireTimeout:h,skipAutoInitialize:d},f,m){const v={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new pm({url:this.authUrl.href,headers:de(de({},v),f),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:o,lock:a,debug:l,throwOnError:c,experimental:u,fetch:m,lockAcquireTimeout:h,skipAutoInitialize:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(A=>A.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new fp(this.realtimeUrl.href,de(de({},t),{},{params:de(de({},{apikey:this.supabaseKey}),t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const mm=(t,e,r)=>new gm(t,e,r);function ym(){if(typeof window<"u")return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}ym()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");let Ac=null,ka=!1;async function vm(){if(!ka){ka=!0;try{const t=await fetch("/api/auth/config");if(!t.ok)return;const{supabaseUrl:e,supabaseAnonKey:r}=await t.json();e&&r&&(Ac=mm(e,r))}catch{}}}function Is(){return Ac}const kn=cd("auth",()=>{const t=Kr(localStorage.getItem("io_token")),e=Kr(localStorage.getItem("io_email")),r=Kr(!1),s=$e(()=>!!t.value);function n(){const l=Is();l&&l.auth.onAuthStateChange((c,u)=>{var h,d;u?(t.value=u.access_token,e.value=((h=u.user)==null?void 0:h.email)??null,localStorage.setItem("io_token",u.access_token),(d=u.user)!=null&&d.email&&localStorage.setItem("io_email",u.user.email)):(t.value=null,e.value=null,localStorage.removeItem("io_token"),localStorage.removeItem("io_email"))})}async function i(l,c){var h,d;const u=Is();if(!u)throw new Error("Auth not configured");r.value=!0;try{const{data:f,error:m}=await u.auth.signInWithPassword({email:l,password:c});if(m)throw m;t.value=((h=f.session)==null?void 0:h.access_token)??null,e.value=((d=f.user)==null?void 0:d.email)??null,t.value&&localStorage.setItem("io_token",t.value),e.value&&localStorage.setItem("io_email",e.value)}finally{r.value=!1}}async function o(){const l=Is();l&&await l.auth.signOut(),t.value=null,e.value=null,localStorage.removeItem("io_token"),localStorage.removeItem("io_email")}async function a(){const l=Is();if(!l)return;const{data:c,error:u}=await l.auth.refreshSession();u||!c.session||(t.value=c.session.access_token,localStorage.setItem("io_token",c.session.access_token))}return{token:t,email:e,loading:r,isAuthenticated:s,login:i,logout:o,refreshToken:a,initAuthListener:n}}),_m=Object.freeze(Object.defineProperty({__proto__:null,useAuthStore:kn},Symbol.toStringTag,{value:"Module"}));/**
|
|
73
|
+
`);const W=await O.signMessage(new TextEncoder().encode(m),"utf8");if(!W||!(W instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");v=W}}try{const{data:A,error:E}=await L(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:m,signature:er(v)},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(f=e.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:qe});if(E)throw E;if(!A||!A.session||!A.user){const _=new cr;return this._returnResult({data:{user:null,session:null},error:_})}return A.session&&(await this._saveSession(A.session),await this._notifyAllSubscribers("SIGNED_IN",A.session)),this._returnResult({data:Object.assign({},A),error:E})}catch(A){if(x(A))return this._returnResult({data:{user:null,session:null},error:A});throw A}}async _exchangeCodeForSession(e){const r=await Yt(this.storage,`${this.storageKey}-code-verifier`),[s,n]=(r??"").split("/");try{if(!s&&this.flowType==="pkce")throw new Zp;const{data:i,error:o}=await L(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:s},xform:qe});if(await be(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!i||!i.session||!i.user){const a=new cr;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers(n==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",i.session)),this._returnResult({data:Object.assign(Object.assign({},i),{redirectType:n??null}),error:o})}catch(i){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(i))return this._returnResult({data:{user:null,session:null,redirectType:null},error:i});throw i}}async signInWithIdToken(e){try{const{options:r,provider:s,token:n,access_token:i,nonce:o}=e,a=await L(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:s,id_token:n,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:r==null?void 0:r.captchaToken}},xform:qe}),{data:l,error:c}=a;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l||!l.session||!l.user){const u=new cr;return this._returnResult({data:{user:null,session:null},error:u})}return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),this._returnResult({data:l,error:c})}catch(r){if(x(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,s,n,i,o;try{if("email"in e){const{email:a,options:l}=e;let c=null,u=null;this.flowType==="pkce"&&([c,u]=await ur(this.storage,this.storageKey));const{error:h}=await L(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l==null?void 0:l.data)!==null&&r!==void 0?r:{},create_user:(s=l==null?void 0:l.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l==null?void 0:l.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:h})}if("phone"in e){const{phone:a,options:l}=e,{data:c,error:u}=await L(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(n=l==null?void 0:l.data)!==null&&n!==void 0?n:{},create_user:(i=l==null?void 0:l.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},channel:(o=l==null?void 0:l.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:u})}throw new Cs("You must provide either an email or phone number.")}catch(a){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,s;try{let n,i;"options"in e&&(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo,i=(s=e.options)===null||s===void 0?void 0:s.captchaToken);const{data:o,error:a}=await L(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:qe});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");const l=o.session,c=o.user;return l!=null&&l.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers(e.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",l)),this._returnResult({data:{user:c,session:l},error:null})}catch(n){if(x(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithSSO(e){var r,s,n,i,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await ur(this.storage,this.storageKey));const c=await L(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:(s=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&s!==void 0?s:void 0}),!((n=e==null?void 0:e.options)===null||n===void 0)&&n.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:a,code_challenge_method:l}),headers:this.headers,xform:kg});return!((i=c.data)===null||i===void 0)&&i.url&&we()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(a){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(a))return this._returnResult({data:null,error:a});throw a}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)throw s;if(!r)throw new ve;const{error:n}=await L(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:n})})}catch(e){if(x(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{const r=`${this.url}/resend`;if("email"in e){const{email:s,type:n,options:i}=e,{error:o}=await L(this.fetch,"POST",r,{headers:this.headers,body:{email:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){const{phone:s,type:n,options:i}=e,{data:o,error:a}=await L(this.fetch,"POST",r,{headers:this.headers,body:{phone:s,type:n,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:a})}throw new Cs("You must provide either an email or phone number and a type")}catch(r){if(x(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async r=>r))}async _acquireLock(e,r){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const s=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await s,await r()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const s=r();for(this.pendingInLock.push((async()=>{try{await s}catch{}})()),await s;this.pendingInLock.length;){const n=[...this.pendingInLock];await Promise.all(n),this.pendingInLock.splice(0,n.length)}return await s}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{const r=await this.__loadSession();return await e(r)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let e=null;const r=await Yt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",r),r!==null&&(this._isValidSession(r)?e=r:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};const s=e.expires_at?e.expires_at*1e3-Date.now()<Mn:!1;if(this._debug("#__loadSession()",`session has${s?"":" not"} expired`,"expires_at",e.expires_at),!s){if(this.userStorage){const o=await Yt(this.userStorage,this.storageKey+"-user");o!=null&&o.user?e.user=o.user:e.user=Fn()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){const o={value:this.suppressGetSessionWarning};e.user=bg(e.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:e},error:null}}const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{session:null},error:i}):this._returnResult({data:{session:n},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;const r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=!0),r}async _getUser(e){try{return e?await L(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Ft}):await this._useSession(async r=>{var s,n,i;const{data:o,error:a}=r;if(a)throw a;return!(!((s=o.session)===null||s===void 0)&&s.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new ve}:await L(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(n=o.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0,xform:Ft})})}catch(r){if(x(r))return Os(r)&&(await this._removeSession(),await be(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:r});throw r}}async updateUser(e,r={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,r))}async _updateUser(e,r={}){try{return await this._useSession(async s=>{const{data:n,error:i}=s;if(i)throw i;if(!n.session)throw new ve;const o=n.session;let a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await ur(this.storage,this.storageKey));const{data:c,error:u}=await L(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r==null?void 0:r.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:Ft});if(u)throw u;return o.user=c.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),this._returnResult({data:{user:o.user},error:null})})}catch(s){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(s))return this._returnResult({data:{user:null},error:s});throw s}}async setSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new ve;const r=Date.now()/1e3;let s=r,n=!0,i=null;const{payload:o}=xs(e.access_token);if(o.exp&&(s=o.exp,n=s<=r),n){const{data:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!a)return{data:{user:null,session:null},error:null};i=a}else{const{data:a,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});i={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:s-r,expires_at:s},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(r){if(x(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async r=>{var s;if(!e){const{data:o,error:a}=r;if(a)throw a;e=(s=o.session)!==null&&s!==void 0?s:void 0}if(!(e!=null&&e.refresh_token))throw new ve;const{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(x(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){var s;try{if(!we())throw new Ps("No browser detected.");if(e.error||e.error_description||e.error_code)throw new Ps(e.error_description||"Error in URL with unspecified error_description",{error:e.error||"unspecified_error",code:e.error_code||"unspecified_code"});switch(r){case"implicit":if(this.flowType==="pkce")throw new oa("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Ps("Not a valid implicit grant flow url.");break;default:}if(r==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!e.code)throw new oa("No code detected.");const{data:b,error:O}=await this._exchangeCodeForSession(e.code);if(O)throw O;const B=new URL(window.location.href);return B.searchParams.delete("code"),window.history.replaceState(window.history.state,"",B.toString()),{data:{session:b.session,redirectType:(s=b.redirectType)!==null&&s!==void 0?s:null},error:null}}const{provider_token:n,provider_refresh_token:i,access_token:o,refresh_token:a,expires_in:l,expires_at:c,token_type:u}=e;if(!o||!l||!a||!u)throw new Ps("No session defined in URL");const h=Math.round(Date.now()/1e3),d=parseInt(l);let f=h+d;c&&(f=parseInt(c));const m=f-h;m*1e3<=mr&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${m}s, should have been closer to ${d}s`);const v=f-d;h-v>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",v,f,h):h-v<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",v,f,h);const{data:A,error:E}=await this._getUser(o);if(E)throw E;const _={provider_token:n,provider_refresh_token:i,access_token:o,expires_in:d,expires_at:f,refresh_token:a,token_type:u,user:A.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:_,redirectType:e.type},error:null})}catch(n){if(x(n))return this._returnResult({data:{session:null,redirectType:null},error:n});throw n}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error_description)}async _isPKCECallback(e){const r=await Yt(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&r)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i&&!Os(i))return this._returnResult({error:i});const o=(s=n.session)===null||s===void 0?void 0:s.access_token;if(o){const{error:a}=await this.admin.signOut(o,e);if(a&&!(Xp(a)&&(a.status===404||a.status===401||a.status===403)||Os(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await be(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){const r=og(),s={id:r,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",r),this.stateChangeEmitters.delete(r)}};return this._debug("#onAuthStateChange()","registered callback with id",r),this.stateChangeEmitters.set(r,s),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r)})))(),{data:{subscription:s}}}async _emitInitialSession(e){return await this._useSession(async r=>{var s,n;try{const{data:{session:i},error:o}=r;if(o)throw o;await((s=this.stateChangeEmitters.get(e))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",e,"session",i)}catch(i){await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",i),Os(i)?console.warn(i):console.error(i)}})}async resetPasswordForEmail(e,r={}){let s=null,n=null;this.flowType==="pkce"&&([s,n]=await ur(this.storage,this.storageKey,!0));try{return await L(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:s,code_challenge_method:n,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(i){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(i))return this._returnResult({data:null,error:i});throw i}}async getUserIdentities(){var e;try{const{data:r,error:s}=await this.getUser();if(s)throw s;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async linkIdentity(e){return"token"in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){var r;try{const{data:s,error:n}=await this._useSession(async i=>{var o,a,l,c,u;const{data:h,error:d}=i;if(d)throw d;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:(o=e.options)===null||o===void 0?void 0:o.redirectTo,scopes:(a=e.options)===null||a===void 0?void 0:a.scopes,queryParams:(l=e.options)===null||l===void 0?void 0:l.queryParams,skipBrowserRedirect:!0});return await L(this.fetch,"GET",f,{headers:this.headers,jwt:(u=(c=h.session)===null||c===void 0?void 0:c.access_token)!==null&&u!==void 0?u:void 0})});if(n)throw n;return we()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(s==null?void 0:s.url),this._returnResult({data:{provider:e.provider,url:s==null?void 0:s.url},error:null})}catch(s){if(x(s))return this._returnResult({data:{provider:e.provider,url:null},error:s});throw s}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var s;try{const{error:n,data:{session:i}}=r;if(n)throw n;const{options:o,provider:a,token:l,access_token:c,nonce:u}=e,h=await L(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(s=i==null?void 0:i.access_token)!==null&&s!==void 0?s:void 0,body:{provider:a,id_token:l,access_token:c,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:qe}),{data:d,error:f}=h;return f?this._returnResult({data:{user:null,session:null},error:f}):!d||!d.session||!d.user?this._returnResult({data:{user:null,session:null},error:new cr}):(d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("USER_UPDATED",d.session)),this._returnResult({data:d,error:f}))}catch(n){if(await be(this.storage,`${this.storageKey}-code-verifier`),x(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:o}=r;if(o)throw o;return await L(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(n=(s=i.session)===null||s===void 0?void 0:s.access_token)!==null&&n!==void 0?n:void 0})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){const r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{const s=Date.now();return await ug(async n=>(n>0&&await cg(200*Math.pow(2,n-1)),this._debug(r,"refreshing attempt",n),await L(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:qe})),(n,i)=>{const o=200*Math.pow(2,n);return i&&Hn(i)&&Date.now()+o-s<mr})}catch(s){if(this._debug(r,"error",s),x(s))return this._returnResult({data:{session:null,user:null},error:s});throw s}finally{this._debug(r,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,r){const s=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:r.redirectTo,scopes:r.scopes,queryParams:r.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",r,"url",s),we()&&!r.skipBrowserRedirect&&window.location.assign(s),{data:{provider:e,url:s},error:null}}async _recoverAndRefresh(){var e,r;const s="#_recoverAndRefresh()";this._debug(s,"begin");try{const n=await Yt(this.storage,this.storageKey);if(n&&this.userStorage){let o=await Yt(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:n.user},await yr(this.userStorage,this.storageKey+"-user",o)),n.user=(e=o==null?void 0:o.user)!==null&&e!==void 0?e:Fn()}else if(n&&!n.user&&!n.user){const o=await Yt(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(n.user=o.user,await be(this.storage,this.storageKey+"-user"),await yr(this.storage,this.storageKey,n)):n.user=Fn()}if(this._debug(s,"session from storage",n),!this._isValidSession(n)){this._debug(s,"session is not valid"),n!==null&&await this._removeSession();return}const i=((r=n.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Mn;if(this._debug(s,`session has${i?"":" not"} expired with margin of ${Mn}s`),i){if(this.autoRefreshToken&&n.refresh_token){const{error:o}=await this._callRefreshToken(n.refresh_token);o&&(console.error(o),Hn(o)||(this._debug(s,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else if(n.user&&n.user.__isUserNotAvailableProxy===!0)try{const{data:o,error:a}=await this._getUser(n.access_token);!a&&(o!=null&&o.user)?(n.user=o.user,await this._saveSession(n),await this._notifyAllSubscribers("SIGNED_IN",n)):this._debug(s,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(s,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",n)}catch(n){this._debug(s,"error",n),console.error(n);return}finally{this._debug(s,"end")}}async _callRefreshToken(e){var r,s;if(!e)throw new ve;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new En;const{data:i,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!i.session)throw new ve;await this._saveSession(i.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",i.session);const a={data:i.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(i){if(this._debug(n,"error",i),x(i)){const o={data:null,error:i};return Hn(i)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw(s=this.refreshingDeferred)===null||s===void 0||s.reject(i),i}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,r,s=!0){const n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",r,`broadcast = ${s}`);try{this.broadcastChannel&&s&&this.broadcastChannel.postMessage({event:e,session:r});const i=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r)}catch(l){i.push(l)}});if(await Promise.all(o),i.length>0){for(let a=0;a<i.length;a+=1)console.error(i[a]);throw i[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await be(this.storage,`${this.storageKey}-code-verifier`);const r=Object.assign({},e),s=r.user&&r.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!s&&r.user&&await yr(this.userStorage,this.storageKey+"-user",{user:r.user});const n=Object.assign({},r);delete n.user;const i=ha(n);await yr(this.storage,this.storageKey,i)}else{const n=ha(r);await yr(this.storage,this.storageKey,n)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await be(this.storage,this.storageKey),await be(this.storage,this.storageKey+"-code-verifier"),await be(this.storage,this.storageKey+"-user"),this.userStorage&&await be(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&we()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(r){console.error("removing visibilitychange callback failed",r)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),mr);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);const r=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=r,r&&typeof r=="object"&&typeof r.unref=="function"?r.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(r)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);const r=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,r&&clearTimeout(r)}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{const e=Date.now();try{return await this._useSession(async r=>{const{data:{session:s}}=r;if(!s||!s.refresh_token||!s.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const n=Math.floor((s.expires_at*1e3-e)/mr);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts ${mr}ms, refresh threshold is ${yi} ticks`),n<=yi&&await this._callRefreshToken(s.refresh_token)})}catch(r){console.error("Auto refresh tick failed with error. This is likely a transient error.",r)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e instanceof bc)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!we()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug("#visibilityChangedCallback","error",e)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const r=`#_onVisibilityChanged(${e})`;this._debug(r,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(r,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,r,s){const n=[`provider=${encodeURIComponent(r)}`];if(s!=null&&s.redirectTo&&n.push(`redirect_to=${encodeURIComponent(s.redirectTo)}`),s!=null&&s.scopes&&n.push(`scopes=${encodeURIComponent(s.scopes)}`),this.flowType==="pkce"){const[i,o]=await ur(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});n.push(a.toString())}if(s!=null&&s.queryParams){const i=new URLSearchParams(s.queryParams);n.push(i.toString())}return s!=null&&s.skipBrowserRedirect&&n.push(`skip_http_redirect=${s.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;return i?this._returnResult({data:null,error:i}):await L(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var s,n;const{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});const a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType==="phone"?{phone:e.phone}:e.factorType==="totp"?{issuer:e.issuer}:{}),{data:l,error:c}=await L(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(s=i==null?void 0:i.session)===null||s===void 0?void 0:s.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((n=l==null?void 0:l.totp)===null||n===void 0)&&n.qr_code)&&(l.totp.qr_code=`data:image/svg+xml;utf-8,${l.totp.qr_code}`),this._returnResult({data:l,error:null}))})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _verify(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});const o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?_a(e.webauthn.credential_response):ba(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await L(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token});return l?this._returnResult({data:null,error:l}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),this._returnResult({data:a,error:l}))})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}})}async _challenge(e){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async r=>{var s;const{data:n,error:i}=r;if(i)return this._returnResult({data:null,error:i});const o=await L(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(s=n==null?void 0:n.session)===null||s===void 0?void 0:s.access_token});if(o.error)return o;const{data:a}=o;if(a.type!=="webauthn")return{data:a,error:null};switch(a.webauthn.type){case"create":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:ya(a.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},a),{webauthn:Object.assign(Object.assign({},a.webauthn),{credential_options:Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:va(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){const{data:r,error:s}=await this._challenge({factorId:e.factorId});return s?this._returnResult({data:null,error:s}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;const{data:{user:r},error:s}=await this.getUser();if(s)return{data:null,error:s};const n={all:[],phone:[],totp:[],webauthn:[]};for(const i of(e=r==null?void 0:r.factors)!==null&&e!==void 0?e:[])n.all.push(i),i.status==="verified"&&n[i.factor_type].push(i);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,s,n,i;if(e)try{const{payload:f}=xs(e);let m=null;f.aal&&(m=f.aal);let v=m;const{data:{user:A},error:E}=await this.getUser(e);if(E)return this._returnResult({data:null,error:E});((s=(r=A==null?void 0:A.factors)===null||r===void 0?void 0:r.filter(O=>O.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(v="aal2");const b=f.amr||[];return{data:{currentLevel:m,nextLevel:v,currentAuthenticationMethods:b},error:null}}catch(f){if(x(f))return this._returnResult({data:null,error:f});throw f}const{data:{session:o},error:a}=await this.getSession();if(a)return this._returnResult({data:null,error:a});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:l}=xs(o.access_token);let c=null;l.aal&&(c=l.aal);let u=c;((i=(n=o.user.factors)===null||n===void 0?void 0:n.filter(f=>f.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(u="aal2");const d=l.amr||[];return{data:{currentLevel:c,nextLevel:u,currentAuthenticationMethods:d},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?await L(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:s.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new ve})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new ve});const o=await L(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&we()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(s){if(x(s))return this._returnResult({data:null,error:s});throw s}}async _denyAuthorization(e,r){try{return await this._useSession(async s=>{const{data:{session:n},error:i}=s;if(i)return this._returnResult({data:null,error:i});if(!n)return this._returnResult({data:null,error:new ve});const o=await L(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:n.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&we()&&!(r!=null&&r.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(s){if(x(s))return this._returnResult({data:null,error:s});throw s}}async _listOAuthGrants(){try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;return s?this._returnResult({data:null,error:s}):r?await L(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:n=>({data:n,error:null})}):this._returnResult({data:null,error:new ve})})}catch(e){if(x(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;return n?this._returnResult({data:null,error:n}):s?(await L(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:s.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new ve})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let s=r.keys.find(a=>a.kid===e);if(s)return s;const n=Date.now();if(s=this.jwks.keys.find(a=>a.kid===e),s&&this.jwks_cached_at+Jp>n)return s;const{data:i,error:o}=await L(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=n,s=i.keys.find(a=>a.kid===e),!s)?null:s}async getClaims(e,r={}){try{let s=e;if(!s){const{data:f,error:m}=await this.getSession();if(m||!f.session)return this._returnResult({data:null,error:m});s=f.session.access_token}const{header:n,payload:i,signature:o,raw:{header:a,payload:l}}=xs(s);r!=null&&r.allowExpired||yg(i.exp);const c=!n.alg||n.alg.startsWith("HS")||!n.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(n.kid,r!=null&&r.keys?{keys:r.keys}:r==null?void 0:r.jwks);if(!c){const{error:f}=await this.getUser(s);if(f)throw f;return{data:{claims:i,header:n,signature:o},error:null}}const u=vg(n.alg),h=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,h,o,ng(`${a}.${l}`)))throw new bi("Invalid JWT signature");return{data:{claims:i,header:n,signature:o},error:null}}catch(s){if(x(s))return this._returnResult({data:null,error:s});throw s}}async signInWithPasskey(e){var r,s,n;Ge(this.experimental);try{if(!Xs())return this._returnResult({data:null,error:new Ye("Browser does not support WebAuthn",null)});const{data:i,error:o}=await this._startPasskeyAuthentication({options:{captchaToken:(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.captchaToken}});if(o||!i)return this._returnResult({data:null,error:o});const a=va(i.options),l=(n=(s=e==null?void 0:e.options)===null||s===void 0?void 0:s.signal)!==null&&n!==void 0?n:wi.createNewAbortSignal(),{data:c,error:u}=await kc({publicKey:a,signal:l});if(u||!c)return this._returnResult({data:null,error:u??new Ye("WebAuthn ceremony failed",null)});const h=ba(c);return this._verifyPasskeyAuthentication({challengeId:i.challenge_id,credential:h})}catch(i){if(x(i))return this._returnResult({data:null,error:i});throw i}}async registerPasskey(e){var r,s;Ge(this.experimental);try{if(!Xs())return this._returnResult({data:null,error:new Ye("Browser does not support WebAuthn",null)});const{data:n,error:i}=await this._startPasskeyRegistration();if(i||!n)return this._returnResult({data:null,error:i});const o=ya(n.options),a=(s=(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:wi.createNewAbortSignal(),{data:l,error:c}=await Ec({publicKey:o,signal:a});if(c||!l)return this._returnResult({data:null,error:c??new Ye("WebAuthn ceremony failed",null)});const u=_a(l);return this._verifyPasskeyRegistration({challengeId:n.challenge_id,credential:u})}catch(n){if(x(n))return this._returnResult({data:null,error:n});throw n}}async _startPasskeyRegistration(){Ge(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new ve});const{data:n,error:i}=await L(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:r.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(x(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){Ge(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new ve});const{data:i,error:o}=await L(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:s.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _startPasskeyAuthentication(e){var r;Ge(this.experimental);try{const{data:s,error:n}=await L(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(r=e==null?void 0:e.options)===null||r===void 0?void 0:r.captchaToken}}});return n?this._returnResult({data:null,error:n}):this._returnResult({data:s,error:null})}catch(s){if(x(s))return this._returnResult({data:null,error:s});throw s}}async _verifyPasskeyAuthentication(e){Ge(this.experimental);try{const{data:r,error:s}=await L(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:qe});return s?this._returnResult({data:null,error:s}):(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:r,error:null}))}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _listPasskeys(){Ge(this.experimental);try{return await this._useSession(async e=>{const{data:{session:r},error:s}=e;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new ve});const{data:n,error:i}=await L(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:r.access_token,xform:o=>({data:o,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:n,error:null})})}catch(e){if(x(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){Ge(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new ve});const{data:i,error:o}=await L(this.fetch,"PATCH",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,body:{friendly_name:e.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}async _deletePasskey(e){Ge(this.experimental);try{return await this._useSession(async r=>{const{data:{session:s},error:n}=r;if(n)return this._returnResult({data:null,error:n});if(!s)return this._returnResult({data:null,error:new ve});const{error:i}=await L(this.fetch,"DELETE",`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:s.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(r){if(x(r))return this._returnResult({data:null,error:r});throw r}}}ps.nextInstanceID={};const Fg=ps,qg="2.106.2";let Hr="";typeof Deno<"u"?Hr="deno":typeof document<"u"?Hr="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Hr="react-native":Hr="node";const Vg={"X-Client-Info":`supabase-js-${Hr}/${qg}`},Kg={headers:Vg},Wg={schema:"public"},Gg={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},zg={},Jg={enabled:!1,respectSamplingDecision:!0};function Yg(t,e,r,s){function n(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function a(u){try{c(s.next(u))}catch(h){o(h)}}function l(u){try{c(s.throw(u))}catch(h){o(h)}}function c(u){u.done?i(u.value):n(u.value).then(a,l)}c((s=s.apply(t,[])).next())})}let Vn=null;const Xg="@opentelemetry/api";function Qg(){return Vn===null&&(Vn=import(Xg).catch(()=>null)),Vn}function Zg(){return Yg(this,void 0,void 0,function*(){try{const t=yield Qg();if(!t||!t.propagation||!t.context)return null;const e={};t.propagation.inject(t.context.active(),e);const r=e.traceparent;return r?{traceparent:r,tracestate:e.tracestate,baggage:e.baggage}:null}catch{return null}})}function em(t){if(!t||typeof t!="string")return null;const e=t.split("-");if(e.length!==4)return null;const[r,s,n,i]=e;if(r.length!==2||s.length!==32||n.length!==16||i.length!==2)return null;const o=/^[0-9a-f]+$/i;return!o.test(r)||!o.test(s)||!o.test(n)||!o.test(i)||s==="00000000000000000000000000000000"||n==="0000000000000000"?null:{version:r,traceId:s,parentId:n,traceFlags:i,isSampled:(parseInt(i,16)&1)===1}}function tm(t,e){if(!t||!e||e.length===0)return!1;let r;if(t instanceof URL)r=t;else try{r=new URL(t)}catch{return!1}for(const s of e)try{if(typeof s=="string"){if(rm(r.hostname,s))return!0}else if(s instanceof RegExp){if(s.test(r.hostname))return!0}else if(typeof s=="function"&&s(r))return!0}catch{continue}return!1}function rm(t,e){if(e===t)return!0;if(e.startsWith("*.")){const r=e.slice(2);if(t.endsWith(r)&&(t===r||t.endsWith("."+r)))return!0}return!1}function sm(t){const e=[];try{const r=new URL(t);e.push(r.hostname)}catch{}return e.push("*.supabase.co","*.supabase.in"),e.push("localhost","127.0.0.1","[::1]"),e}function gs(t){"@babel/helpers - typeof";return gs=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},gs(t)}function nm(t,e){if(gs(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var s=r.call(t,e);if(gs(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function im(t){var e=nm(t,"string");return gs(e)=="symbol"?e:e+""}function om(t,e,r){return(e=im(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Sa(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(n){return Object.getOwnPropertyDescriptor(t,n).enumerable})),r.push.apply(r,s)}return r}function de(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Sa(Object(r),!0).forEach(function(s){om(t,s,r[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Sa(Object(r)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(r,s))})}return t}const am=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),lm=()=>Headers,cm=(t,e,r,s,n)=>{const i=am(s),o=lm(),a=(n==null?void 0:n.enabled)===!0,l=(n==null?void 0:n.respectSamplingDecision)!==!1,c=a?sm(e):null;return async(u,h)=>{var d;const f=(d=await r())!==null&&d!==void 0?d:t;let m=new o(h==null?void 0:h.headers);if(m.has("apikey")||m.set("apikey",t),m.has("Authorization")||m.set("Authorization",`Bearer ${f}`),c){const v=await um(u,c,l);v&&(v.traceparent&&!m.has("traceparent")&&m.set("traceparent",v.traceparent),v.tracestate&&!m.has("tracestate")&&m.set("tracestate",v.tracestate),v.baggage&&!m.has("baggage")&&m.set("baggage",v.baggage))}return i(u,de(de({},h),{},{headers:m}))}};async function um(t,e,r){if(!tm(typeof t=="string"||t instanceof URL?t:t.url,e))return null;const s=await Zg();if(!s||!s.traceparent)return null;if(r){const n=em(s.traceparent);if(n&&!n.isSampled)return null}return s}function Ea(t){return typeof t=="boolean"?{enabled:t}:t}function hm(t){return t.endsWith("/")?t:t+"/"}function dm(t,e){var r,s,n,i,o,a;const{db:l,auth:c,realtime:u,global:h}=t,{db:d,auth:f,realtime:m,global:v}=e,A=Ea(t.tracePropagation),E=Ea(e.tracePropagation),_={db:de(de({},d),l),auth:de(de({},f),c),realtime:de(de({},m),u),storage:{},global:de(de(de({},v),h),{},{headers:de(de({},(r=v==null?void 0:v.headers)!==null&&r!==void 0?r:{}),(s=h==null?void 0:h.headers)!==null&&s!==void 0?s:{})}),tracePropagation:{enabled:(n=(i=A==null?void 0:A.enabled)!==null&&i!==void 0?i:E==null?void 0:E.enabled)!==null&&n!==void 0?n:!1,respectSamplingDecision:(o=(a=A==null?void 0:A.respectSamplingDecision)!==null&&a!==void 0?a:E==null?void 0:E.respectSamplingDecision)!==null&&o!==void 0?o:!0},accessToken:async()=>""};return t.accessToken?_.accessToken=t.accessToken:delete _.accessToken,_}function fm(t){const e=t==null?void 0:t.trim();if(!e)throw new Error("supabaseUrl is required.");if(!e.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(hm(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var pm=class extends Fg{constructor(t){super(t)}},gm=class{constructor(t,e,r){var s,n;this.supabaseUrl=t,this.supabaseKey=e;const i=fm(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const o=`sb-${i.hostname.split(".")[0]}-auth-token`,a={db:Wg,realtime:zg,auth:de(de({},Gg),{},{storageKey:o}),global:Kg,tracePropagation:Jg},l=dm(r??{},a);if(this.settings=l,this.storageKey=(s=l.auth.storageKey)!==null&&s!==void 0?s:"",this.headers=(n=l.global.headers)!==null&&n!==void 0?n:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(u,h)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(h)} is not possible`)}});else{var c;this.auth=this._initSupabaseAuthClient((c=l.auth)!==null&&c!==void 0?c:{},this.headers,l.global.fetch)}this.fetch=cm(e,t,this._getAccessToken.bind(this),l.global.fetch,l.tracePropagation),this.realtime=this._initRealtimeClient(de({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},l.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(u=>this.realtime.setAuth(u)).catch(u=>console.warn("Failed to set initial Realtime auth token:",u)),this.rest=new xf(new URL("rest/v1",i).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new Vp(this.storageUrl.href,this.headers,this.fetch,r==null?void 0:r.storage),l.accessToken||this._listenForAuthEvents()}get functions(){return new wf(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,e={},r={head:!1,get:!1,count:void 0}){return this.rest.rpc(t,e,r)}channel(t,e={config:{}}){return this.realtime.channel(t,e)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var t=this,e,r;if(t.accessToken)return await t.accessToken();const{data:s}=await t.auth.getSession();return(e=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&e!==void 0?e:t.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,storageKey:i,flowType:o,lock:a,debug:l,throwOnError:c,experimental:u,lockAcquireTimeout:h,skipAutoInitialize:d},f,m){const v={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new pm({url:this.authUrl.href,headers:de(de({},v),f),storageKey:i,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:s,userStorage:n,flowType:o,lock:a,debug:l,throwOnError:c,experimental:u,fetch:m,lockAcquireTimeout:h,skipAutoInitialize:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(A=>A.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new fp(this.realtimeUrl.href,de(de({},t),{},{params:de(de({},{apikey:this.supabaseKey}),t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",e==null?void 0:e.access_token)})}_handleTokenChanged(t,e,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?(this.changedAccessToken=r,this.realtime.setAuth(r)):t==="SIGNED_OUT"&&(this.realtime.setAuth(),e=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const mm=(t,e,r)=>new gm(t,e,r);function ym(){if(typeof window<"u")return!1;const t=globalThis.process;if(!t)return!1;const e=t.version;if(e==null)return!1;const r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:!1}ym()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");let Ac=null,ka=!1;async function vm(){if(!ka){ka=!0;try{const t=await fetch("/api/auth/config");if(!t.ok)return;const{supabaseUrl:e,supabaseAnonKey:r}=await t.json();e&&r&&(Ac=mm(e,r))}catch{}}}function Is(){return Ac}const kn=cd("auth",()=>{const t=Kr(localStorage.getItem("io_token")),e=Kr(localStorage.getItem("io_email")),r=Kr(!1),s=$e(()=>!!t.value);function n(){const l=Is();l&&l.auth.onAuthStateChange((c,u)=>{var h,d;u?(t.value=u.access_token,e.value=((h=u.user)==null?void 0:h.email)??null,localStorage.setItem("io_token",u.access_token),(d=u.user)!=null&&d.email&&localStorage.setItem("io_email",u.user.email)):(t.value=null,e.value=null,localStorage.removeItem("io_token"),localStorage.removeItem("io_email"))})}async function i(l,c){var h,d;const u=Is();if(!u)throw new Error("Auth not configured");r.value=!0;try{const{data:f,error:m}=await u.auth.signInWithPassword({email:l,password:c});if(m)throw m;t.value=((h=f.session)==null?void 0:h.access_token)??null,e.value=((d=f.user)==null?void 0:d.email)??null,t.value&&localStorage.setItem("io_token",t.value),e.value&&localStorage.setItem("io_email",e.value)}finally{r.value=!1}}async function o(){const l=Is();l&&await l.auth.signOut(),t.value=null,e.value=null,localStorage.removeItem("io_token"),localStorage.removeItem("io_email")}async function a(){const l=Is();if(!l)return;const{data:c,error:u}=await l.auth.refreshSession();if(u||!c.session){t.value=null,localStorage.removeItem("io_token");return}t.value=c.session.access_token,localStorage.setItem("io_token",c.session.access_token)}return{token:t,email:e,loading:r,isAuthenticated:s,login:i,logout:o,refreshToken:a,initAuthListener:n}}),_m=Object.freeze(Object.defineProperty({__proto__:null,useAuthStore:kn},Symbol.toStringTag,{value:"Module"}));/**
|
|
74
74
|
* @license lucide-vue-next v0.474.0 - ISC
|
|
75
75
|
*
|
|
76
76
|
* This source code is licensed under the ISC license.
|
|
@@ -135,4 +135,4 @@ ${E}`}class ge extends Error{constructor({message:e,code:r,cause:s,name:n}){var
|
|
|
135
135
|
*
|
|
136
136
|
* This source code is licensed under the ISC license.
|
|
137
137
|
* See the LICENSE file in the root directory of this source tree.
|
|
138
|
-
*/const Pm=jt("UsersIcon",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]),xm={class:"w-64 border-r border-border bg-card flex flex-col h-full shrink-0"},Im={class:"flex-1 p-2 space-y-1 overflow-y-auto"},jm={class:"p-3 border-t border-border"},Nm={class:"flex items-center justify-between"},$m={class:"text-xs text-muted-foreground truncate"},Lm=dn({__name:"AppSidebar",setup(t){const e=rc(),r=yf(),s=kn(),n=[{name:"Chat",icon:Tm,path:"/"},{name:"Squads",icon:Pm,path:"/squads"},{name:"Feed",icon:km,path:"/feed"},{name:"Skills",icon:Rm,path:"/skills"},{name:"MCP Servers",icon:Om,path:"/mcp"},{name:"Schedules",icon:Em,path:"/schedules"},{name:"Wiki",icon:Sm,path:"/wiki"},{name:"Settings",icon:Cm,path:"/settings"}];async function i(){await s.logout(),r.push("/login")}return(o,a)=>{const l=dl("router-link");return Sr(),ei("aside",xm,[a[0]||(a[0]=ze("div",{class:"p-4 border-b border-border"},[ze("h1",{class:"text-xl font-bold tracking-tight"},"🤖 IO"),ze("p",{class:"text-xs text-muted-foreground mt-1"},"Personal AI Assistant")],-1)),ze("nav",Im,[(Sr(),ei(ut,null,Bu(n,c=>Ae(l,{key:c.path,to:c.path,class:an(["flex items-center gap-3 px-3 py-2 rounded-md text-sm transition-colors",[Xe(e).path===c.path||c.path!=="/"&&Xe(e).path.startsWith(c.path)?"bg-accent text-accent-foreground font-medium":"text-muted-foreground hover:bg-accent/50 hover:text-accent-foreground"]])},{default:nl(()=>[(Sr(),Di(Uu(c.icon),{class:"w-4 h-4"})),Nl(" "+Kn(c.name),1)]),_:2},1032,["to","class"])),64))]),ze("div",jm,[ze("div",Nm,[ze("span",$m,Kn(Xe(s).email),1),ze("button",{onClick:i,class:"p-1.5 rounded-md hover:bg-accent text-muted-foreground hover:text-foreground transition-colors",title:"Sign out"},[Ae(Xe(Am),{class:"w-4 h-4"})])])])])}}}),Dm={class:"flex h-screen overflow-hidden"},Um={class:"flex-1 overflow-auto"},Bm=dn({__name:"App",setup(t){const e=kn(),r=rc(),s=$e(()=>e.isAuthenticated&&r.name!=="login");return(n,i)=>{const o=dl("router-view");return Sr(),ei("div",Dm,[s.value?(Sr(),Di(Lm,{key:0})):gh("",!0),ze("main",Um,[Ae(o)])])}}}),Mm=[{path:"/login",name:"login",component:()=>We(()=>import("./LoginView-
|
|
138
|
+
*/const Pm=jt("UsersIcon",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]),xm={class:"w-64 border-r border-border bg-card flex flex-col h-full shrink-0"},Im={class:"flex-1 p-2 space-y-1 overflow-y-auto"},jm={class:"p-3 border-t border-border"},Nm={class:"flex items-center justify-between"},$m={class:"text-xs text-muted-foreground truncate"},Lm=dn({__name:"AppSidebar",setup(t){const e=rc(),r=yf(),s=kn(),n=[{name:"Chat",icon:Tm,path:"/"},{name:"Squads",icon:Pm,path:"/squads"},{name:"Feed",icon:km,path:"/feed"},{name:"Skills",icon:Rm,path:"/skills"},{name:"MCP Servers",icon:Om,path:"/mcp"},{name:"Schedules",icon:Em,path:"/schedules"},{name:"Wiki",icon:Sm,path:"/wiki"},{name:"Settings",icon:Cm,path:"/settings"}];async function i(){await s.logout(),r.push("/login")}return(o,a)=>{const l=dl("router-link");return Sr(),ei("aside",xm,[a[0]||(a[0]=ze("div",{class:"p-4 border-b border-border"},[ze("h1",{class:"text-xl font-bold tracking-tight"},"🤖 IO"),ze("p",{class:"text-xs text-muted-foreground mt-1"},"Personal AI Assistant")],-1)),ze("nav",Im,[(Sr(),ei(ut,null,Bu(n,c=>Ae(l,{key:c.path,to:c.path,class:an(["flex items-center gap-3 px-3 py-2 rounded-md text-sm transition-colors",[Xe(e).path===c.path||c.path!=="/"&&Xe(e).path.startsWith(c.path)?"bg-accent text-accent-foreground font-medium":"text-muted-foreground hover:bg-accent/50 hover:text-accent-foreground"]])},{default:nl(()=>[(Sr(),Di(Uu(c.icon),{class:"w-4 h-4"})),Nl(" "+Kn(c.name),1)]),_:2},1032,["to","class"])),64))]),ze("div",jm,[ze("div",Nm,[ze("span",$m,Kn(Xe(s).email),1),ze("button",{onClick:i,class:"p-1.5 rounded-md hover:bg-accent text-muted-foreground hover:text-foreground transition-colors",title:"Sign out"},[Ae(Xe(Am),{class:"w-4 h-4"})])])])])}}}),Dm={class:"flex h-screen overflow-hidden"},Um={class:"flex-1 overflow-auto"},Bm=dn({__name:"App",setup(t){const e=kn(),r=rc(),s=$e(()=>e.isAuthenticated&&r.name!=="login");return(n,i)=>{const o=dl("router-view");return Sr(),ei("div",Dm,[s.value?(Sr(),Di(Lm,{key:0})):gh("",!0),ze("main",Um,[Ae(o)])])}}}),Mm=[{path:"/login",name:"login",component:()=>We(()=>import("./LoginView-B6aSD9II.js"),[]),meta:{public:!0}},{path:"/",name:"chat",component:()=>We(()=>import("./ChatView-mZaaw3pd.js"),__vite__mapDeps([0,1,2]))},{path:"/squads",name:"squads",component:()=>We(()=>import("./SquadsView-CZFxtOao.js"),__vite__mapDeps([3,1]))},{path:"/squads/:id",name:"squad-detail",component:()=>We(()=>import("./SquadDetailView-CQhFfZTc.js"),__vite__mapDeps([4,1]))},{path:"/feed",name:"feed",component:()=>We(()=>import("./FeedView-BHacQwXQ.js"),__vite__mapDeps([5,1,2,6]))},{path:"/skills",name:"skills",component:()=>We(()=>import("./SkillsView-gCfQ35FQ.js"),__vite__mapDeps([7,1,2,8,9,6]))},{path:"/mcp",name:"mcp",component:()=>We(()=>import("./McpView-BAVRUHIE.js"),__vite__mapDeps([10,1,8,6]))},{path:"/schedules",name:"schedules",component:()=>We(()=>import("./SchedulesView-dOd1SQiP.js"),__vite__mapDeps([11,1,8,6]))},{path:"/wiki",name:"wiki",component:()=>We(()=>import("./WikiView-B0cuUFfm.js"),__vite__mapDeps([12,1,2,8,9,6]))},{path:"/settings",name:"settings",component:()=>We(()=>import("./SettingsView-CCDeEsVg.js"),__vite__mapDeps([13,1]))}],Tc=mf({history:Gd(),routes:Mm});Tc.beforeEach(t=>{const e=kn();if(!t.meta.public&&!e.isAuthenticated)return{name:"login"}});async function Hm(){await vm();const t=ed(Bm);t.use(sd()),t.use(Tc);const{useAuthStore:e}=await We(async()=>{const{useAuthStore:s}=await Promise.resolve().then(()=>_m);return{useAuthStore:s}},void 0),r=e();r.initAuthListener(),r.token&&await r.refreshToken(),t.mount("#app")}Hm();export{qm as A,Sm as B,Em as C,Wr as D,nl as E,ut as F,Fm as G,Gm as H,km as I,Wm as J,Rm as P,Om as S,Pm as U,ze as a,Di as b,$e as c,gh as d,ei as e,jt as f,Nl as g,Ae as h,dn as i,cd as j,an as k,ki as l,Sr as m,hn as n,Pu as o,Bu as p,dl as q,Kr as r,Tc as s,Kn as t,Xe as u,kn as v,rc as w,yf as x,Vm as y,Km as z};
|
package/web-dist/index.html
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
6
|
<title>IO — Dashboard</title>
|
|
7
7
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
|
8
|
-
<script type="module" crossorigin src="/assets/index-
|
|
8
|
+
<script type="module" crossorigin src="/assets/index-BQdXxKfc.js"></script>
|
|
9
9
|
<link rel="stylesheet" crossorigin href="/assets/index-BbSJ0cfF.css">
|
|
10
10
|
</head>
|
|
11
11
|
<body class="bg-background text-foreground">
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{v as c,s as i}from"./index-DdP1fu_7.js";const s="/api";async function o(){const t=c(),e={"Content-Type":"application/json"};return t.token&&(e.Authorization=`Bearer ${t.token}`),e}async function n(t,e){if(t.status===401){const r=c();try{if(await r.refreshToken(),r.token){const a=await e();if(a.status===401)throw r.logout(),i.push("/login"),new Error("Session expired");return a}}catch{}throw r.logout(),i.push("/login"),new Error("Session expired")}return t}async function u(t){const e=await n(await fetch(`${s}${t}`,{headers:await o()}),async()=>fetch(`${s}${t}`,{headers:await o()}));if(!e.ok)throw new Error(`API error: ${e.status}`);return e.json()}async function w(t,e){const r={method:"POST",headers:await o(),body:e?JSON.stringify(e):void 0},a=await n(await fetch(`${s}${t}`,r),async()=>fetch(`${s}${t}`,{...r,headers:await o()}));if(!a.ok)throw new Error(`API error: ${a.status}`);return a.json()}async function f(t,e){const r={method:"PUT",headers:await o(),body:e?JSON.stringify(e):void 0},a=await n(await fetch(`${s}${t}`,r),async()=>fetch(`${s}${t}`,{...r,headers:await o()}));if(!a.ok)throw new Error(`API error: ${a.status}`);return a.json()}async function $(t){const e={method:"DELETE",headers:await o()},r=await n(await fetch(`${s}${t}`,e),async()=>fetch(`${s}${t}`,{...e,headers:await o()}));if(!r.ok)throw new Error(`API error: ${r.status}`);return r.json()}export{$ as a,u as b,w as c,f as d};
|