@pathrule/cli 0.0.6 → 0.0.7
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/index.js +60 -60
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {randomUUID,randomBytes,createHash}from'crypto';import {homedir,tmpdir}from'os';import Ge,{dirname,join,basename,normalize,resolve,relative,isAbsolute,sep,posix,win32}from'path';import {rm as rm$1,mkdir,chmod,appendFile,writeFile,unlink,readFile,stat,rename,access,mkdtemp,readdir,open,realpath,rmdir}from'fs/promises';import {createServer}from'http';import {execFile,spawn,execFileSync}from'child_process';import {createRequire}from'module';import {emitKeypressEvents}from'readline';import {createInterface}from'readline/promises';import {promisify}from'util';import {constants,promises}from'fs';import {fileURLToPath}from'url';var Zh=Object.create;var Vi=Object.defineProperty;var Qh=Object.getOwnPropertyDescriptor;var ef=Object.getOwnPropertyNames;var tf=Object.getPrototypeOf,rf=Object.prototype.hasOwnProperty;var R=(t,e)=>()=>(t&&(e=t(t=0)),e);var nf=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),sf=(t,e)=>{for(var r in e)Vi(t,r,{get:e[r],enumerable:true});},of=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ef(e))!rf.call(t,i)&&i!==r&&Vi(t,i,{get:()=>e[i],enumerable:!(n=Qh(e,i))||n.enumerable});return t};var af=(t,e,r)=>(r=t!=null?Zh(tf(t)):{},of(Vi(r,"default",{value:t,enumerable:true}),t));var Ma=nf((jE,Da)=>{var{hasOwnProperty:Gi}=Object.prototype,Yi=(t,e={})=>{typeof e=="string"&&(e={section:e}),e.align=e.align===true,e.newline=e.newline===true,e.sort=e.sort===true,e.whitespace=e.whitespace===true||e.align===true,e.platform=e.platform||typeof process<"u"&&process.platform,e.bracketedArray=e.bracketedArray!==false;let r=e.platform==="win32"?`\r
|
|
3
3
|
`:`
|
|
4
|
-
`,n=e.whitespace?" = ":"=",i=[],s=e.sort?Object.keys(t).sort():Object.keys(t),o=0;e.align&&(o=Ae(s.filter(c=>t[c]===null||Array.isArray(t[c])||typeof t[c]!="object").map(c=>Array.isArray(t[c])?`${c}[]`:c).concat([""]).reduce((c,u)=>Ae(c).length>=Ae(u).length?c:u)).length);let a="",l=e.bracketedArray?"[]":"";for(let c of s){let u=t[c];if(u&&Array.isArray(u))for(let d of u)a+=Ae(`${c}${l}`).padEnd(o," ")+n+Ae(d)+r;else u&&typeof u=="object"?i.push(c):a+=Ae(c).padEnd(o," ")+n+Ae(u)+r;}e.section&&a.length&&(a="["+Ae(e.section)+"]"+(e.newline?r+r:r)+a);for(let c of i){let u=Na(c,".").join("\\."),d=(e.section?e.section+".":"")+u,p=Yi(t[c],{...e,section:d});a.length&&p.length&&(a+=r),a+=p;}return a};function Na(t,e){var r=0,n=0,i=0,s=[];do if(i=t.indexOf(e,r),i!==-1){if(r=i+e.length,i>0&&t[i-1]==="\\")continue;s.push(t.slice(n,i)),n=i+e.length;}while(i!==-1);return s.push(t.slice(n)),s}var $a=(t,e={})=>{e.bracketedArray=e.bracketedArray!==false;let r=Object.create(null),n=r,i=null,s=/^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i,o=t.split(/[\r\n]+/g),a={};for(let c of o){if(!c||c.match(/^\s*[;#]/)||c.match(/^\s*$/))continue;let u=c.match(s);if(!u)continue;if(u[1]!==void 0){if(i=wn(u[1]),i==="__proto__"){n=Object.create(null);continue}n=r[i]=r[i]||Object.create(null);continue}let d=wn(u[2]),p;e.bracketedArray?p=d.length>2&&d.slice(-2)==="[]":(a[d]=(a?.[d]||0)+1,p=a[d]>1);let h=p&&d.endsWith("[]")?d.slice(0,-2):d;if(h==="__proto__")continue;let f=u[3]?wn(u[4]):true,m=f==="true"||f==="false"||f==="null"?JSON.parse(f):f;p&&(Gi.call(n,h)?Array.isArray(n[h])||(n[h]=[n[h]]):n[h]=[]),Array.isArray(n[h])?n[h].push(m):n[h]=m;}let l=[];for(let c of Object.keys(r)){if(!Gi.call(r,c)||typeof r[c]!="object"||Array.isArray(r[c]))continue;let u=Na(c,".");n=r;let d=u.pop(),p=d.replace(/\\\./g,".");for(let h of u)h!=="__proto__"&&((!Gi.call(n,h)||typeof n[h]!="object")&&(n[h]=Object.create(null)),n=n[h]);n===r&&p===d||(n[p]=r[c],l.push(c));}for(let c of l)delete r[c];return r},ja=t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"),Ae=t=>typeof t!="string"||t.match(/[=\r\n]/)||t.match(/^\[/)||t.length>1&&ja(t)||t!==t.trim()?JSON.stringify(t):t.split(";").join("\\;").split("#").join("\\#"),wn=t=>{if(t=(t||"").trim(),ja(t)){t.charAt(0)==="'"&&(t=t.slice(1,-1));try{t=JSON.parse(t);}catch{}}else {let e=false,r="";for(let n=0,i=t.length;n<i;n++){let s=t.charAt(n);if(e)"\\;#".indexOf(s)!==-1?r+=s:r+="\\"+s,e=false;else {if(";#".indexOf(s)!==-1)break;s==="\\"?e=true:r+=s;}}return e&&(r+="\\"),r.trim()}return t};Da.exports={parse:$a,decode:$a,stringify:Yi,encode:Yi,safe:Ae,unsafe:wn};});function lg(t){return createHash("sha256").update(t,"utf8").digest("hex").slice(0,32)}function Rl(t=process.env){return t.PATHRULE_HOME&&t.PATHRULE_HOME.trim()!==""?t.PATHRULE_HOME:join(homedir(),".pathrule")}function A(t=process.env){let e=Rl(t);return {home:e,activeUserFile:join(e,"active-user"),credentialsFile:join(e,"credentials.json"),desktopFile:join(e,"desktop.json"),daemonFile:join(e,"daemon.json"),bridgePairFile:join(e,"bridge-pair.json"),tokenLockFile:join(e,".token-lock"),logsDir:join(e,"logs"),supportDir:join(e,"support")}}function rt(t,e=0,r=process.env){let n=Rl(r),i=lg(t),s=join(n,"config","users",i),o=join(n,"cache","users",i),a=join(o,`epoch-${e}`);return {userHash:i,userConfigDir:s,userConfigFile:join(s,"config.json"),userCacheDir:o,epochCacheDir:a}}var D,O,K=R(()=>{D=448,O=384;});function nt(t=process.env){let e=A(t);async function r(){try{let i=await readFile(e.credentialsFile,"utf8"),s=JSON.parse(i);return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}catch(i){if(i.code==="ENOENT")return {};throw i}}async function n(i){let s=dirname(e.credentialsFile);await mkdir(s,{recursive:true,mode:D}),await chmod(s,D).catch(()=>{});let o=`${e.credentialsFile}.tmp`;await writeFile(o,JSON.stringify(i),{encoding:"utf8",mode:O}),await chmod(o,O).catch(()=>{}),await rename(o,e.credentialsFile);}return {paths:e,async set(i,s){let o=await r();o[i]=s,await n(o);},async get(i){return (await r())[i]??null},async delete(i){let s=await r();return i in s?(delete s[i],Object.keys(s).length===0?await rm$1(e.credentialsFile,{force:true}):await n(s),true):false},async findAll(){let i=await r();return Object.entries(i).map(([s,o])=>({account:s,value:o}))}}}var ms=R(()=>{K();});function it(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function Pl(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s);})}return new(r||(r=Promise))(function(s,o){function a(u){try{c(n.next(u));}catch(d){o(d);}}function l(u){try{c(n.throw(u));}catch(d){o(d);}}function c(u){u.done?s(u.value):i(u.value).then(a,l);}c((n=n.apply(t,e||[])).next());})}var mr=R(()=>{});var Tl,Al=R(()=>{Tl=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);});var Lt,_r,Ut,Wt,wr,Il=R(()=>{Lt=class extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n;}toJSON(){return {name:this.name,message:this.message,context:this.context}}},_r=class extends Lt{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e);}},Ut=class extends Lt{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e);}},Wt=class extends Lt{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e);}};(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2";})(wr||(wr={}));});var yr,Ol=R(()=>{mr();Al();Il();yr=class{constructor(e,{headers:r={},customFetch:n,region:i=wr.Any}={}){this.url=e,this.headers=r,this.region=i,this.fetch=Tl(n);}setAuth(e){this.headers.Authorization=`Bearer ${e}`;}invoke(e){return Pl(this,arguments,void 0,function*(r,n={}){var i;let s,o;try{let{headers:a,method:l,body:c,signal:u,timeout:d}=n,p={},{region:h}=n;h||(h=this.region);let f=new URL(`${this.url}/${r}`);h&&h!=="any"&&(p["x-region"]=h,f.searchParams.set("forceFunctionRegion",h));let m;c&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(p["Content-Type"]="application/octet-stream",m=c):typeof c=="string"?(p["Content-Type"]="text/plain",m=c):typeof FormData<"u"&&c instanceof FormData?m=c:(p["Content-Type"]="application/json",m=JSON.stringify(c)):c&&typeof c!="string"&&!(typeof Blob<"u"&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<"u"&&c instanceof FormData)?m=JSON.stringify(c):m=c;let _=u;d&&(o=new AbortController,s=setTimeout(()=>o.abort(),d),u?(_=o.signal,u.addEventListener("abort",()=>o.abort())):_=o.signal);let b=yield this.fetch(f.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},p),this.headers),a),body:m,signal:_}).catch(Z=>{throw new _r(Z)}),w=b.headers.get("x-relay-error");if(w&&w==="true")throw new Ut(b);if(!b.ok)throw new Wt(b);let y=((i=b.headers.get("Content-Type"))!==null&&i!==void 0?i:"text/plain").split(";")[0].trim(),I;return y==="application/json"?I=yield b.json():y==="application/octet-stream"||y==="application/pdf"?I=yield b.blob():y==="text/event-stream"?I=b:y==="multipart/form-data"?I=yield b.formData():I=yield b.text(),{data:I,error:null,response:b}}catch(a){return {data:null,error:a,response:a instanceof Wt||a instanceof Ut?a.context:void 0}}finally{s&&clearTimeout(s);}})}};});var $l=R(()=>{Ol();});function jl(t,e){return new Promise(r=>{if(e?.aborted){r();return}let n=setTimeout(()=>{e?.removeEventListener("abort",i),r();},t);function i(){clearTimeout(n),r();}e?.addEventListener("abort",i);})}function bg(t,e,r,n){return !(!n||r>=3||!Ll.includes(t)||!kg.includes(e))}function kr(t){"@babel/helpers - typeof";return kr=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},kr(t)}function Eg(t,e){if(kr(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(kr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(t)}function Rg(t){var e=Eg(t,"string");return kr(e)=="symbol"?e:e+""}function xg(t,e,r){return (e=Rg(e))in t?Object.defineProperty(t,e,{value:r,enumerable:true,configurable:true,writable:true}):t[e]=r,t}function Ml(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n);}return r}function Tn(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Ml(Object(r),true).forEach(function(n){xg(t,n,r[n]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Ml(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n));});}return t}var Nl,kg,Ll,Ul,vg,Sg,Dl,Bt,Cg,Wl,Fl=R(()=>{Nl=t=>Math.min(1e3*2**t,3e4),kg=[520,503],Ll=["GET","HEAD","OPTIONS"],Ul=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code;}toJSON(){return {name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};vg=class{constructor(t){var e,r,n,i,s;this.shouldThrowOnError=false,this.retryEnabled=true,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:false,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:false,this.shouldStripNulls=(n=t.shouldStripNulls)!==null&&n!==void 0?n:false,this.urlLengthLimit=(i=t.urlLengthLimit)!==null&&i!==void 0?i:8e3,this.retryEnabled=(s=t.retry)!==null&&s!==void 0?s:true,t.fetch?this.fetch=t.fetch:this.fetch=fetch;}throwOnError(){return this.shouldThrowOnError=true,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=true,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}retry(t){return this.retryEnabled=t,this}then(t,e){var r=this;if(this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){let o=this.headers.get("Accept");o==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!o||o==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped");}let n=this.fetch,s=(async()=>{let o=0;for(;;){let c=new Headers(r.headers);o>0&&c.set("X-Retry-Count",String(o));let u;try{u=await n(r.url.toString(),{method:r.method,headers:c,body:JSON.stringify(r.body,(d,p)=>typeof p=="bigint"?p.toString():p),signal:r.signal});}catch(d){if(d?.name==="AbortError"||d?.code==="ABORT_ERR"||!Ll.includes(r.method))throw d;if(r.retryEnabled&&o<3){let p=Nl(o);o++,await jl(p,r.signal);continue}throw d}if(bg(r.method,u.status,o,r.retryEnabled)){var a,l;let d=(a=(l=u.headers)===null||l===void 0?void 0:l.get("Retry-After"))!==null&&a!==void 0?a:null,p=d!==null?Math.max(0,parseInt(d,10)||0)*1e3:Nl(o);await u.text(),o++,await jl(p,r.signal);continue}return await r.processResponse(u)}})();return this.shouldThrowOnError||(s=s.catch(o=>{var a;let l="",c="",u="",d=o?.cause;if(d){var p,h,f,m;let w=(p=d?.message)!==null&&p!==void 0?p:"",y=(h=d?.code)!==null&&h!==void 0?h:"";l=`${(f=o?.name)!==null&&f!==void 0?f:"FetchError"}: ${o?.message}`,l+=`
|
|
4
|
+
`,n=e.whitespace?" = ":"=",i=[],s=e.sort?Object.keys(t).sort():Object.keys(t),o=0;e.align&&(o=Ae(s.filter(c=>t[c]===null||Array.isArray(t[c])||typeof t[c]!="object").map(c=>Array.isArray(t[c])?`${c}[]`:c).concat([""]).reduce((c,u)=>Ae(c).length>=Ae(u).length?c:u)).length);let a="",l=e.bracketedArray?"[]":"";for(let c of s){let u=t[c];if(u&&Array.isArray(u))for(let d of u)a+=Ae(`${c}${l}`).padEnd(o," ")+n+Ae(d)+r;else u&&typeof u=="object"?i.push(c):a+=Ae(c).padEnd(o," ")+n+Ae(u)+r;}e.section&&a.length&&(a="["+Ae(e.section)+"]"+(e.newline?r+r:r)+a);for(let c of i){let u=Na(c,".").join("\\."),d=(e.section?e.section+".":"")+u,p=Yi(t[c],{...e,section:d});a.length&&p.length&&(a+=r),a+=p;}return a};function Na(t,e){var r=0,n=0,i=0,s=[];do if(i=t.indexOf(e,r),i!==-1){if(r=i+e.length,i>0&&t[i-1]==="\\")continue;s.push(t.slice(n,i)),n=i+e.length;}while(i!==-1);return s.push(t.slice(n)),s}var $a=(t,e={})=>{e.bracketedArray=e.bracketedArray!==false;let r=Object.create(null),n=r,i=null,s=/^\[([^\]]*)\]\s*$|^([^=]+)(=(.*))?$/i,o=t.split(/[\r\n]+/g),a={};for(let c of o){if(!c||c.match(/^\s*[;#]/)||c.match(/^\s*$/))continue;let u=c.match(s);if(!u)continue;if(u[1]!==void 0){if(i=yn(u[1]),i==="__proto__"){n=Object.create(null);continue}n=r[i]=r[i]||Object.create(null);continue}let d=yn(u[2]),p;e.bracketedArray?p=d.length>2&&d.slice(-2)==="[]":(a[d]=(a?.[d]||0)+1,p=a[d]>1);let h=p&&d.endsWith("[]")?d.slice(0,-2):d;if(h==="__proto__")continue;let f=u[3]?yn(u[4]):true,m=f==="true"||f==="false"||f==="null"?JSON.parse(f):f;p&&(Gi.call(n,h)?Array.isArray(n[h])||(n[h]=[n[h]]):n[h]=[]),Array.isArray(n[h])?n[h].push(m):n[h]=m;}let l=[];for(let c of Object.keys(r)){if(!Gi.call(r,c)||typeof r[c]!="object"||Array.isArray(r[c]))continue;let u=Na(c,".");n=r;let d=u.pop(),p=d.replace(/\\\./g,".");for(let h of u)h!=="__proto__"&&((!Gi.call(n,h)||typeof n[h]!="object")&&(n[h]=Object.create(null)),n=n[h]);n===r&&p===d||(n[p]=r[c],l.push(c));}for(let c of l)delete r[c];return r},ja=t=>t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"),Ae=t=>typeof t!="string"||t.match(/[=\r\n]/)||t.match(/^\[/)||t.length>1&&ja(t)||t!==t.trim()?JSON.stringify(t):t.split(";").join("\\;").split("#").join("\\#"),yn=t=>{if(t=(t||"").trim(),ja(t)){t.charAt(0)==="'"&&(t=t.slice(1,-1));try{t=JSON.parse(t);}catch{}}else {let e=false,r="";for(let n=0,i=t.length;n<i;n++){let s=t.charAt(n);if(e)"\\;#".indexOf(s)!==-1?r+=s:r+="\\"+s,e=false;else {if(";#".indexOf(s)!==-1)break;s==="\\"?e=true:r+=s;}}return e&&(r+="\\"),r.trim()}return t};Da.exports={parse:$a,decode:$a,stringify:Yi,encode:Yi,safe:Ae,unsafe:yn};});function lg(t){return createHash("sha256").update(t,"utf8").digest("hex").slice(0,32)}function Rl(t=process.env){return t.PATHRULE_HOME&&t.PATHRULE_HOME.trim()!==""?t.PATHRULE_HOME:join(homedir(),".pathrule")}function A(t=process.env){let e=Rl(t);return {home:e,activeUserFile:join(e,"active-user"),credentialsFile:join(e,"credentials.json"),desktopFile:join(e,"desktop.json"),daemonFile:join(e,"daemon.json"),bridgePairFile:join(e,"bridge-pair.json"),tokenLockFile:join(e,".token-lock"),logsDir:join(e,"logs"),supportDir:join(e,"support")}}function rt(t,e=0,r=process.env){let n=Rl(r),i=lg(t),s=join(n,"config","users",i),o=join(n,"cache","users",i),a=join(o,`epoch-${e}`);return {userHash:i,userConfigDir:s,userConfigFile:join(s,"config.json"),userCacheDir:o,epochCacheDir:a}}var D,O,K=R(()=>{D=448,O=384;});function nt(t=process.env){let e=A(t);async function r(){try{let i=await readFile(e.credentialsFile,"utf8"),s=JSON.parse(i);return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}catch(i){if(i.code==="ENOENT")return {};throw i}}async function n(i){let s=dirname(e.credentialsFile);await mkdir(s,{recursive:true,mode:D}),await chmod(s,D).catch(()=>{});let o=`${e.credentialsFile}.tmp`;await writeFile(o,JSON.stringify(i),{encoding:"utf8",mode:O}),await chmod(o,O).catch(()=>{}),await rename(o,e.credentialsFile);}return {paths:e,async set(i,s){let o=await r();o[i]=s,await n(o);},async get(i){return (await r())[i]??null},async delete(i){let s=await r();return i in s?(delete s[i],Object.keys(s).length===0?await rm$1(e.credentialsFile,{force:true}):await n(s),true):false},async findAll(){let i=await r();return Object.entries(i).map(([s,o])=>({account:s,value:o}))}}}var ms=R(()=>{K();});function it(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function Pl(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s);})}return new(r||(r=Promise))(function(s,o){function a(u){try{c(n.next(u));}catch(d){o(d);}}function l(u){try{c(n.throw(u));}catch(d){o(d);}}function c(u){u.done?s(u.value):i(u.value).then(a,l);}c((n=n.apply(t,e||[])).next());})}var mr=R(()=>{});var Tl,Al=R(()=>{Tl=t=>t?(...e)=>t(...e):(...e)=>fetch(...e);});var Lt,_r,Ut,Wt,wr,Il=R(()=>{Lt=class extends Error{constructor(e,r="FunctionsError",n){super(e),this.name=r,this.context=n;}toJSON(){return {name:this.name,message:this.message,context:this.context}}},_r=class extends Lt{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e);}},Ut=class extends Lt{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e);}},Wt=class extends Lt{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e);}};(function(t){t.Any="any",t.ApNortheast1="ap-northeast-1",t.ApNortheast2="ap-northeast-2",t.ApSouth1="ap-south-1",t.ApSoutheast1="ap-southeast-1",t.ApSoutheast2="ap-southeast-2",t.CaCentral1="ca-central-1",t.EuCentral1="eu-central-1",t.EuWest1="eu-west-1",t.EuWest2="eu-west-2",t.EuWest3="eu-west-3",t.SaEast1="sa-east-1",t.UsEast1="us-east-1",t.UsWest1="us-west-1",t.UsWest2="us-west-2";})(wr||(wr={}));});var yr,Ol=R(()=>{mr();Al();Il();yr=class{constructor(e,{headers:r={},customFetch:n,region:i=wr.Any}={}){this.url=e,this.headers=r,this.region=i,this.fetch=Tl(n);}setAuth(e){this.headers.Authorization=`Bearer ${e}`;}invoke(e){return Pl(this,arguments,void 0,function*(r,n={}){var i;let s,o;try{let{headers:a,method:l,body:c,signal:u,timeout:d}=n,p={},{region:h}=n;h||(h=this.region);let f=new URL(`${this.url}/${r}`);h&&h!=="any"&&(p["x-region"]=h,f.searchParams.set("forceFunctionRegion",h));let m;c&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)?typeof Blob<"u"&&c instanceof Blob||c instanceof ArrayBuffer?(p["Content-Type"]="application/octet-stream",m=c):typeof c=="string"?(p["Content-Type"]="text/plain",m=c):typeof FormData<"u"&&c instanceof FormData?m=c:(p["Content-Type"]="application/json",m=JSON.stringify(c)):c&&typeof c!="string"&&!(typeof Blob<"u"&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<"u"&&c instanceof FormData)?m=JSON.stringify(c):m=c;let _=u;d&&(o=new AbortController,s=setTimeout(()=>o.abort(),d),u?(_=o.signal,u.addEventListener("abort",()=>o.abort())):_=o.signal);let b=yield this.fetch(f.toString(),{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},p),this.headers),a),body:m,signal:_}).catch(Z=>{throw new _r(Z)}),w=b.headers.get("x-relay-error");if(w&&w==="true")throw new Ut(b);if(!b.ok)throw new Wt(b);let y=((i=b.headers.get("Content-Type"))!==null&&i!==void 0?i:"text/plain").split(";")[0].trim(),I;return y==="application/json"?I=yield b.json():y==="application/octet-stream"||y==="application/pdf"?I=yield b.blob():y==="text/event-stream"?I=b:y==="multipart/form-data"?I=yield b.formData():I=yield b.text(),{data:I,error:null,response:b}}catch(a){return {data:null,error:a,response:a instanceof Wt||a instanceof Ut?a.context:void 0}}finally{s&&clearTimeout(s);}})}};});var $l=R(()=>{Ol();});function jl(t,e){return new Promise(r=>{if(e?.aborted){r();return}let n=setTimeout(()=>{e?.removeEventListener("abort",i),r();},t);function i(){clearTimeout(n),r();}e?.addEventListener("abort",i);})}function bg(t,e,r,n){return !(!n||r>=3||!Ll.includes(t)||!kg.includes(e))}function kr(t){"@babel/helpers - typeof";return kr=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},kr(t)}function Eg(t,e){if(kr(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(kr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(t)}function Rg(t){var e=Eg(t,"string");return kr(e)=="symbol"?e:e+""}function xg(t,e,r){return (e=Rg(e))in t?Object.defineProperty(t,e,{value:r,enumerable:true,configurable:true,writable:true}):t[e]=r,t}function Ml(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n);}return r}function An(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?Ml(Object(r),true).forEach(function(n){xg(t,n,r[n]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):Ml(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n));});}return t}var Nl,kg,Ll,Ul,vg,Sg,Dl,Bt,Cg,Wl,Fl=R(()=>{Nl=t=>Math.min(1e3*2**t,3e4),kg=[520,503],Ll=["GET","HEAD","OPTIONS"],Ul=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code;}toJSON(){return {name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};vg=class{constructor(t){var e,r,n,i,s;this.shouldThrowOnError=false,this.retryEnabled=true,this.method=t.method,this.url=t.url,this.headers=new Headers(t.headers),this.schema=t.schema,this.body=t.body,this.shouldThrowOnError=(e=t.shouldThrowOnError)!==null&&e!==void 0?e:false,this.signal=t.signal,this.isMaybeSingle=(r=t.isMaybeSingle)!==null&&r!==void 0?r:false,this.shouldStripNulls=(n=t.shouldStripNulls)!==null&&n!==void 0?n:false,this.urlLengthLimit=(i=t.urlLengthLimit)!==null&&i!==void 0?i:8e3,this.retryEnabled=(s=t.retry)!==null&&s!==void 0?s:true,t.fetch?this.fetch=t.fetch:this.fetch=fetch;}throwOnError(){return this.shouldThrowOnError=true,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=true,this}setHeader(t,e){return this.headers=new Headers(this.headers),this.headers.set(t,e),this}retry(t){return this.retryEnabled=t,this}then(t,e){var r=this;if(this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers.set("Accept-Profile",this.schema):this.headers.set("Content-Profile",this.schema)),this.method!=="GET"&&this.method!=="HEAD"&&this.headers.set("Content-Type","application/json"),this.shouldStripNulls){let o=this.headers.get("Accept");o==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!o||o==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped");}let n=this.fetch,s=(async()=>{let o=0;for(;;){let c=new Headers(r.headers);o>0&&c.set("X-Retry-Count",String(o));let u;try{u=await n(r.url.toString(),{method:r.method,headers:c,body:JSON.stringify(r.body,(d,p)=>typeof p=="bigint"?p.toString():p),signal:r.signal});}catch(d){if(d?.name==="AbortError"||d?.code==="ABORT_ERR"||!Ll.includes(r.method))throw d;if(r.retryEnabled&&o<3){let p=Nl(o);o++,await jl(p,r.signal);continue}throw d}if(bg(r.method,u.status,o,r.retryEnabled)){var a,l;let d=(a=(l=u.headers)===null||l===void 0?void 0:l.get("Retry-After"))!==null&&a!==void 0?a:null,p=d!==null?Math.max(0,parseInt(d,10)||0)*1e3:Nl(o);await u.text(),o++,await jl(p,r.signal);continue}return await r.processResponse(u)}})();return this.shouldThrowOnError||(s=s.catch(o=>{var a;let l="",c="",u="",d=o?.cause;if(d){var p,h,f,m;let w=(p=d?.message)!==null&&p!==void 0?p:"",y=(h=d?.code)!==null&&h!==void 0?h:"";l=`${(f=o?.name)!==null&&f!==void 0?f:"FetchError"}: ${o?.message}`,l+=`
|
|
5
5
|
|
|
6
6
|
Caused by: ${(m=d?.name)!==null&&m!==void 0?m:"Error"}: ${w}`,y&&(l+=` (${y})`),d?.stack&&(l+=`
|
|
7
|
-
${d.stack}`);}else {var _;l=(_=o?.stack)!==null&&_!==void 0?_:"";}let b=this.url.toString().length;return o?.name==="AbortError"||o?.code==="ABORT_ERR"?(u="",c="Request was aborted (timeout or manual cancellation)",b>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${b} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(d?.name==="HeadersOverflowError"||d?.code==="UND_ERR_HEADERS_OVERFLOW")&&(u="",c="HTTP headers exceeded server limits (typically 16KB)",b>this.urlLengthLimit&&(c+=`. Your request URL is ${b} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:false,error:{message:`${(a=o?.name)!==null&&a!==void 0?a:"FetchError"}: ${o?.message}`,details:l,hint:c,code:u},data:null,count:null,status:0,statusText:""}})),s.then(t,e)}async processResponse(t){var e=this;let r=null,n=null,i=null,s=t.status,o=t.statusText;if(t.ok){var a,l;if(e.method!=="HEAD"){var c;let p=await t.text();p===""||(e.headers.get("Accept")==="text/csv"||e.headers.get("Accept")&&(!((c=e.headers.get("Accept"))===null||c===void 0)&&c.includes("application/vnd.pgrst.plan+text"))?n=p:n=JSON.parse(p));}let u=(a=e.headers.get("Prefer"))===null||a===void 0?void 0:a.match(/count=(exact|planned|estimated)/),d=(l=t.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");u&&d&&d.length>1&&(i=parseInt(d[1])),e.isMaybeSingle&&Array.isArray(n)&&(n.length>1?(r={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,i=null,s=406,o="Not Acceptable"):n.length===1?n=n[0]:n=null);}else {let u=await t.text();try{r=JSON.parse(u),Array.isArray(r)&&t.status===404&&(n=[],r=null,s=200,o="OK");}catch{t.status===404&&u===""?(s=204,o="No Content"):r={message:u};}if(r&&e.shouldThrowOnError)throw new Ul(r)}return {success:r===null,error:r,data:n,count:i,status:s,statusText:o}}returns(){return this}overrideTypes(){return this}},Sg=class extends vg{select(t){let e=false,r=(t??"*").split("").map(n=>/\s/.test(n)&&!e?"":(n==='"'&&(e=!e),n)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=true,nullsFirst:r,foreignTable:n,referencedTable:i=n}={}){let s=i?`${i}.order`:"order",o=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:n=r}={}){let i=typeof n>"u"?"offset":`${n}.offset`,s=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(i,`${t}`),this.url.searchParams.set(s,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=true,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=false,verbose:e=false,settings:r=false,buffers:n=false,wal:i=false,format:s="text"}={}){var o;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,n?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${l}"; options=${a};`),s==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},Dl=new RegExp("[,()]"),Bt=class extends Sg{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&Dl.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&Dl.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:n}={}){let i="";n==="plain"?i="pl":n==="phrase"?i="ph":n==="websearch"&&(i="w");let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${i}fts${s}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`);}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let n=r?`${r}.or`:"or";return this.url.searchParams.append(n,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Cg=class{constructor(t,{headers:e={},schema:r,fetch:n,urlLengthLimit:i=8e3,retry:s}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=n,this.urlLengthLimit=i,this.retry=s;}cloneRequestState(){return {url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=false,count:n}=e??{},i=r?"HEAD":"GET",s=false,o=(t??"*").split("").map(c=>/\s/.test(c)&&!s?"":(c==='"'&&(s=!s),c)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",o),n&&l.append("Prefer",`count=${n}`),new Bt({method:i,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(t,{count:e,defaultToNull:r=true}={}){var n;let i="POST",{url:s,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),r||o.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(a.length>0){let l=[...new Set(a)].map(c=>`"${c}"`);s.searchParams.set("columns",l.join(","));}}return new Bt({method:i,url:s,headers:o,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(t,{onConflict:e,ignoreDuplicates:r=false,count:n,defaultToNull:i=true}={}){var s;let o="POST",{url:a,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&a.searchParams.set("on_conflict",e),n&&l.append("Prefer",`count=${n}`),i||l.append("Prefer","missing=default"),Array.isArray(t)){let c=t.reduce((u,d)=>u.concat(Object.keys(d)),[]);if(c.length>0){let u=[...new Set(c)].map(d=>`"${d}"`);a.searchParams.set("columns",u.join(","));}}return new Bt({method:o,url:a,headers:l,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(t,{count:e}={}){var r;let n="PATCH",{url:i,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new Bt({method:n,url:i,headers:s,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:t}={}){var e;let r="DELETE",{url:n,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new Bt({method:r,url:n,headers:i,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};Wl=class Bl{constructor(e,{headers:r={},schema:n,fetch:i,timeout:s,urlLengthLimit:o=8e3,retry:a}={}){this.url=e,this.headers=new Headers(r),this.schemaName=n,this.urlLengthLimit=o;let l=i??globalThis.fetch;s!==void 0&&s>0?this.fetch=(c,u)=>{let d=new AbortController,p=setTimeout(()=>d.abort(),s),h=u?.signal;if(h){if(h.aborted)return clearTimeout(p),l(c,u);let f=()=>{clearTimeout(p),d.abort();};return h.addEventListener("abort",f,{once:true}),l(c,Tn(Tn({},u),{},{signal:d.signal})).finally(()=>{clearTimeout(p),h.removeEventListener("abort",f);})}return l(c,Tn(Tn({},u),{},{signal:d.signal})).finally(()=>clearTimeout(p))}:this.fetch=l,this.retry=a;}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Cg(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(e){return new Bl(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,r={},{head:n=false,get:i=false,count:s}={}){var o;let a,l=new URL(`${this.url}/rpc/${e}`),c,u=h=>h!==null&&typeof h=="object"&&(!Array.isArray(h)||h.some(u)),d=n&&Object.values(r).some(u);d?(a="POST",c=r):n||i?(a=n?"HEAD":"GET",Object.entries(r).filter(([h,f])=>f!==void 0).map(([h,f])=>[h,Array.isArray(f)?`{${f.join(",")}}`:`${f}`]).forEach(([h,f])=>{l.searchParams.append(h,f);})):(a="POST",c=r);let p=new Headers(this.headers);return d?p.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&p.set("Prefer",`count=${s}`),new Bt({method:a,url:l,headers:p,schema:this.schemaName,body:c,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};});var _s,ws,ys=R(()=>{_s=class{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return {type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return {type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return {type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return {type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return {type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let r=globalThis.process;if(r){let n=r.versions;if(n&&n.node){let i=n.node,s=parseInt(i.replace(/^v/,"").split(".")[0]);return s>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${s} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
|
|
7
|
+
${d.stack}`);}else {var _;l=(_=o?.stack)!==null&&_!==void 0?_:"";}let b=this.url.toString().length;return o?.name==="AbortError"||o?.code==="ABORT_ERR"?(u="",c="Request was aborted (timeout or manual cancellation)",b>this.urlLengthLimit&&(c+=`. Note: Your request URL is ${b} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(d?.name==="HeadersOverflowError"||d?.code==="UND_ERR_HEADERS_OVERFLOW")&&(u="",c="HTTP headers exceeded server limits (typically 16KB)",b>this.urlLengthLimit&&(c+=`. Your request URL is ${b} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:false,error:{message:`${(a=o?.name)!==null&&a!==void 0?a:"FetchError"}: ${o?.message}`,details:l,hint:c,code:u},data:null,count:null,status:0,statusText:""}})),s.then(t,e)}async processResponse(t){var e=this;let r=null,n=null,i=null,s=t.status,o=t.statusText;if(t.ok){var a,l;if(e.method!=="HEAD"){var c;let p=await t.text();p===""||(e.headers.get("Accept")==="text/csv"||e.headers.get("Accept")&&(!((c=e.headers.get("Accept"))===null||c===void 0)&&c.includes("application/vnd.pgrst.plan+text"))?n=p:n=JSON.parse(p));}let u=(a=e.headers.get("Prefer"))===null||a===void 0?void 0:a.match(/count=(exact|planned|estimated)/),d=(l=t.headers.get("content-range"))===null||l===void 0?void 0:l.split("/");u&&d&&d.length>1&&(i=parseInt(d[1])),e.isMaybeSingle&&Array.isArray(n)&&(n.length>1?(r={code:"PGRST116",details:`Results contain ${n.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},n=null,i=null,s=406,o="Not Acceptable"):n.length===1?n=n[0]:n=null);}else {let u=await t.text();try{r=JSON.parse(u),Array.isArray(r)&&t.status===404&&(n=[],r=null,s=200,o="OK");}catch{t.status===404&&u===""?(s=204,o="No Content"):r={message:u};}if(r&&e.shouldThrowOnError)throw new Ul(r)}return {success:r===null,error:r,data:n,count:i,status:s,statusText:o}}returns(){return this}overrideTypes(){return this}},Sg=class extends vg{select(t){let e=false,r=(t??"*").split("").map(n=>/\s/.test(n)&&!e?"":(n==='"'&&(e=!e),n)).join("");return this.url.searchParams.set("select",r),this.headers.append("Prefer","return=representation"),this}order(t,{ascending:e=true,nullsFirst:r,foreignTable:n,referencedTable:i=n}={}){let s=i?`${i}.order`:"order",o=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${o?`${o},`:""}${t}.${e?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:e,referencedTable:r=e}={}){let n=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${t}`),this}range(t,e,{foreignTable:r,referencedTable:n=r}={}){let i=typeof n>"u"?"offset":`${n}.offset`,s=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(i,`${t}`),this.url.searchParams.set(s,`${e-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=true,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:t=false,verbose:e=false,settings:r=false,buffers:n=false,wal:i=false,format:s="text"}={}){var o;let a=[t?"analyze":null,e?"verbose":null,r?"settings":null,n?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${s}; for="${l}"; options=${a};`),s==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(t){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${t}`),this}},Dl=new RegExp("[,()]"),Bt=class extends Sg{eq(t,e){return this.url.searchParams.append(t,`eq.${e}`),this}neq(t,e){return this.url.searchParams.append(t,`neq.${e}`),this}gt(t,e){return this.url.searchParams.append(t,`gt.${e}`),this}gte(t,e){return this.url.searchParams.append(t,`gte.${e}`),this}lt(t,e){return this.url.searchParams.append(t,`lt.${e}`),this}lte(t,e){return this.url.searchParams.append(t,`lte.${e}`),this}like(t,e){return this.url.searchParams.append(t,`like.${e}`),this}likeAllOf(t,e){return this.url.searchParams.append(t,`like(all).{${e.join(",")}}`),this}likeAnyOf(t,e){return this.url.searchParams.append(t,`like(any).{${e.join(",")}}`),this}ilike(t,e){return this.url.searchParams.append(t,`ilike.${e}`),this}ilikeAllOf(t,e){return this.url.searchParams.append(t,`ilike(all).{${e.join(",")}}`),this}ilikeAnyOf(t,e){return this.url.searchParams.append(t,`ilike(any).{${e.join(",")}}`),this}regexMatch(t,e){return this.url.searchParams.append(t,`match.${e}`),this}regexIMatch(t,e){return this.url.searchParams.append(t,`imatch.${e}`),this}is(t,e){return this.url.searchParams.append(t,`is.${e}`),this}isDistinct(t,e){return this.url.searchParams.append(t,`isdistinct.${e}`),this}in(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&Dl.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}notIn(t,e){let r=Array.from(new Set(e)).map(n=>typeof n=="string"&&Dl.test(n)?`"${n}"`:`${n}`).join(",");return this.url.searchParams.append(t,`not.in.(${r})`),this}contains(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cs.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cs.{${e.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(e)}`),this}containedBy(t,e){return typeof e=="string"?this.url.searchParams.append(t,`cd.${e}`):Array.isArray(e)?this.url.searchParams.append(t,`cd.{${e.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(e)}`),this}rangeGt(t,e){return this.url.searchParams.append(t,`sr.${e}`),this}rangeGte(t,e){return this.url.searchParams.append(t,`nxl.${e}`),this}rangeLt(t,e){return this.url.searchParams.append(t,`sl.${e}`),this}rangeLte(t,e){return this.url.searchParams.append(t,`nxr.${e}`),this}rangeAdjacent(t,e){return this.url.searchParams.append(t,`adj.${e}`),this}overlaps(t,e){return typeof e=="string"?this.url.searchParams.append(t,`ov.${e}`):this.url.searchParams.append(t,`ov.{${e.join(",")}}`),this}textSearch(t,e,{config:r,type:n}={}){let i="";n==="plain"?i="pl":n==="phrase"?i="ph":n==="websearch"&&(i="w");let s=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${i}fts${s}.${e}`),this}match(t){return Object.entries(t).filter(([e,r])=>r!==void 0).forEach(([e,r])=>{this.url.searchParams.append(e,`eq.${r}`);}),this}not(t,e,r){return this.url.searchParams.append(t,`not.${e}.${r}`),this}or(t,{foreignTable:e,referencedTable:r=e}={}){let n=r?`${r}.or`:"or";return this.url.searchParams.append(n,`(${t})`),this}filter(t,e,r){return this.url.searchParams.append(t,`${e}.${r}`),this}},Cg=class{constructor(t,{headers:e={},schema:r,fetch:n,urlLengthLimit:i=8e3,retry:s}){this.url=t,this.headers=new Headers(e),this.schema=r,this.fetch=n,this.urlLengthLimit=i,this.retry=s;}cloneRequestState(){return {url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(t,e){let{head:r=false,count:n}=e??{},i=r?"HEAD":"GET",s=false,o=(t??"*").split("").map(c=>/\s/.test(c)&&!s?"":(c==='"'&&(s=!s),c)).join(""),{url:a,headers:l}=this.cloneRequestState();return a.searchParams.set("select",o),n&&l.append("Prefer",`count=${n}`),new Bt({method:i,url:a,headers:l,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(t,{count:e,defaultToNull:r=true}={}){var n;let i="POST",{url:s,headers:o}=this.cloneRequestState();if(e&&o.append("Prefer",`count=${e}`),r||o.append("Prefer","missing=default"),Array.isArray(t)){let a=t.reduce((l,c)=>l.concat(Object.keys(c)),[]);if(a.length>0){let l=[...new Set(a)].map(c=>`"${c}"`);s.searchParams.set("columns",l.join(","));}}return new Bt({method:i,url:s,headers:o,schema:this.schema,body:t,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(t,{onConflict:e,ignoreDuplicates:r=false,count:n,defaultToNull:i=true}={}){var s;let o="POST",{url:a,headers:l}=this.cloneRequestState();if(l.append("Prefer",`resolution=${r?"ignore":"merge"}-duplicates`),e!==void 0&&a.searchParams.set("on_conflict",e),n&&l.append("Prefer",`count=${n}`),i||l.append("Prefer","missing=default"),Array.isArray(t)){let c=t.reduce((u,d)=>u.concat(Object.keys(d)),[]);if(c.length>0){let u=[...new Set(c)].map(d=>`"${d}"`);a.searchParams.set("columns",u.join(","));}}return new Bt({method:o,url:a,headers:l,schema:this.schema,body:t,fetch:(s=this.fetch)!==null&&s!==void 0?s:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(t,{count:e}={}){var r;let n="PATCH",{url:i,headers:s}=this.cloneRequestState();return e&&s.append("Prefer",`count=${e}`),new Bt({method:n,url:i,headers:s,schema:this.schema,body:t,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:t}={}){var e;let r="DELETE",{url:n,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new Bt({method:r,url:n,headers:i,schema:this.schema,fetch:(e=this.fetch)!==null&&e!==void 0?e:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};Wl=class Bl{constructor(e,{headers:r={},schema:n,fetch:i,timeout:s,urlLengthLimit:o=8e3,retry:a}={}){this.url=e,this.headers=new Headers(r),this.schemaName=n,this.urlLengthLimit=o;let l=i??globalThis.fetch;s!==void 0&&s>0?this.fetch=(c,u)=>{let d=new AbortController,p=setTimeout(()=>d.abort(),s),h=u?.signal;if(h){if(h.aborted)return clearTimeout(p),l(c,u);let f=()=>{clearTimeout(p),d.abort();};return h.addEventListener("abort",f,{once:true}),l(c,An(An({},u),{},{signal:d.signal})).finally(()=>{clearTimeout(p),h.removeEventListener("abort",f);})}return l(c,An(An({},u),{},{signal:d.signal})).finally(()=>clearTimeout(p))}:this.fetch=l,this.retry=a;}from(e){if(!e||typeof e!="string"||e.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Cg(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(e){return new Bl(this.url,{headers:this.headers,schema:e,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(e,r={},{head:n=false,get:i=false,count:s}={}){var o;let a,l=new URL(`${this.url}/rpc/${e}`),c,u=h=>h!==null&&typeof h=="object"&&(!Array.isArray(h)||h.some(u)),d=n&&Object.values(r).some(u);d?(a="POST",c=r):n||i?(a=n?"HEAD":"GET",Object.entries(r).filter(([h,f])=>f!==void 0).map(([h,f])=>[h,Array.isArray(f)?`{${f.join(",")}}`:`${f}`]).forEach(([h,f])=>{l.searchParams.append(h,f);})):(a="POST",c=r);let p=new Headers(this.headers);return d?p.set("Prefer",s?`count=${s},return=minimal`:"return=minimal"):s&&p.set("Prefer",`count=${s}`),new Bt({method:a,url:l,headers:p,schema:this.schemaName,body:c,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};});var _s,ws,ys=R(()=>{_s=class{constructor(){}static detectEnvironment(){var e;if(typeof WebSocket<"u")return {type:"native",constructor:WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocket<"u")return {type:"native",constructor:globalThis.WebSocket};if(typeof global<"u"&&typeof global.WebSocket<"u")return {type:"native",constructor:global.WebSocket};if(typeof globalThis<"u"&&typeof globalThis.WebSocketPair<"u"&&typeof globalThis.WebSocket>"u")return {type:"cloudflare",error:"Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.",workaround:"Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime."};if(typeof globalThis<"u"&&globalThis.EdgeRuntime||typeof navigator<"u"&&(!((e=navigator.userAgent)===null||e===void 0)&&e.includes("Vercel-Edge")))return {type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};let r=globalThis.process;if(r){let n=r.versions;if(n&&n.node){let i=n.node,s=parseInt(i.replace(/^v/,"").split(".")[0]);return s>=22?typeof globalThis.WebSocket<"u"?{type:"native",constructor:globalThis.WebSocket}:{type:"unsupported",error:`Node.js ${s} detected but native WebSocket not found.`,workaround:"Provide a WebSocket implementation via the transport option."}:{type:"unsupported",error:`Node.js ${s} detected without native WebSocket support.`,workaround:`For Node.js < 22, install "ws" package and provide it via the transport option:
|
|
8
8
|
import ws from "ws"
|
|
9
9
|
new RealtimeClient(url, { transport: ws })`}}}return {type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){let e=this.detectEnvironment();if(e.constructor)return e.constructor;let r=e.error||"WebSocket not supported in this environment.";throw e.workaround&&(r+=`
|
|
10
10
|
|
|
11
|
-
Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return false}}},ws=_s;});var Hl,ql=R(()=>{Hl="2.103.2";});var zl,Jl,ks,Kl,Vl,Gl,we,An,br,vr=R(()=>{ql();zl=`realtime-js/${Hl}`,Jl="1.0.0",ks="2.0.0",Kl=ks,Vl=1e4,Gl=100,we={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},An={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"},br={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};});var Sr,Yl=R(()=>{Sr=class{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[];}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,n;let i=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,i)}_encodeJsonUserBroadcastPush(e){var r,n;let i=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:{},o=new TextEncoder().encode(JSON.stringify(i)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,r,n){var i,s;let o=e.topic,a=(i=e.ref)!==null&&i!==void 0?i:"",l=(s=e.join_ref)!==null&&s!==void 0?s:"",c=e.payload.event,u=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},d=Object.keys(u).length===0?"":JSON.stringify(u);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`metadata length ${d.length} exceeds maximum of 255`);let p=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+o.length+c.length+d.length,h=new ArrayBuffer(this.HEADER_LENGTH+p),f=new DataView(h),m=0;f.setUint8(m++,this.KINDS.userBroadcastPush),f.setUint8(m++,l.length),f.setUint8(m++,a.length),f.setUint8(m++,o.length),f.setUint8(m++,c.length),f.setUint8(m++,d.length),f.setUint8(m++,r),Array.from(l,b=>f.setUint8(m++,b.charCodeAt(0))),Array.from(a,b=>f.setUint8(m++,b.charCodeAt(0))),Array.from(o,b=>f.setUint8(m++,b.charCodeAt(0))),Array.from(c,b=>f.setUint8(m++,b.charCodeAt(0))),Array.from(d,b=>f.setUint8(m++,b.charCodeAt(0)));var _=new Uint8Array(h.byteLength+n.byteLength);return _.set(new Uint8Array(h),0),_.set(new Uint8Array(n),h.byteLength),_.buffer}decode(e,r){if(this._isArrayBuffer(e)){let n=this._binaryDecode(e);return r(n)}if(typeof e=="string"){let n=JSON.parse(e),[i,s,o,a,l]=n;return r({join_ref:i,ref:s,topic:o,event:a,payload:l})}return r({})}_binaryDecode(e){let r=new DataView(e),n=r.getUint8(0),i=new TextDecoder;if(n===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,i)}_decodeUserBroadcast(e,r,n){let i=r.getUint8(1),s=r.getUint8(2),o=r.getUint8(3),a=r.getUint8(4),l=this.HEADER_LENGTH+4,c=n.decode(e.slice(l,l+i));l=l+i;let u=n.decode(e.slice(l,l+s));l=l+s;let d=n.decode(e.slice(l,l+o));l=l+o;let p=e.slice(l,e.byteLength),h=a===this.JSON_ENCODING?JSON.parse(n.decode(p)):p,f={type:this.BROADCAST_EVENT,event:u,payload:h};return o>0&&(f.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:f}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return !e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([n])=>r.includes(n)))}};});var N,vs,Pg,Xl,bs,Tg,Ag,Ig,Og,$g,In,On=R(()=>{(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange";})(N||(N={}));vs=(t,e,r={})=>{var n;let i=(n=r.skipTypes)!==null&&n!==void 0?n:[];return e?Object.keys(e).reduce((s,o)=>(s[o]=Pg(o,t,e,i),s),{}):{}},Pg=(t,e,r,n)=>{let i=e.find(a=>a.name===t),s=i?.type,o=r[t];return s&&!n.includes(s)?Xl(s,o):bs(o)},Xl=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return Og(e,r)}switch(t){case N.bool:return Tg(e);case N.float4:case N.float8:case N.int2:case N.int4:case N.int8:case N.numeric:case N.oid:return Ag(e);case N.json:case N.jsonb:return Ig(e);case N.timestamp:return $g(e);case N.abstime:case N.date:case N.daterange:case N.int4range:case N.int8range:case N.money:case N.reltime:case N.text:case N.time:case N.timestamptz:case N.timetz:case N.tsrange:case N.tstzrange:return bs(e);default:return bs(e)}},bs=t=>t,Tg=t=>{switch(t){case "t":return true;case "f":return false;default:return t}},Ag=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t},Ig=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Og=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,n=t[r];if(t[0]==="{"&&n==="}"){let s,o=t.slice(1,r);try{s=JSON.parse("["+o+"]");}catch{s=o?o.split(","):[];}return s.map(a=>Xl(e,a))}return t},$g=t=>typeof t=="string"?t.replace(" ","T"):t,In=t=>{let e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};});var Er,jg,Ht,ye,Dg,Mg,Lg,ke,Q,Ie,Ss,Ug,Cs,$n,Zl,Wg,jn,Bg,Ft,Ql,Nn,ec,Es=R(()=>{Er=t=>typeof t=="function"?t:function(){return t},jg=typeof self<"u"?self:null,Ht=typeof window<"u"?window:null,ye=jg||Ht||globalThis,Dg="2.0.0",Mg=1e4,Lg=1e3,ke={connecting:0,open:1,closing:2,closed:3},Q={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Ie={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Ss={longpoll:"longpoll",websocket:"websocket"},Ug={complete:4},Cs="base64url.bearer.phx.",$n=class{constructor(t,e,r,n){this.channel=t,this.event=e,this.payload=r||function(){return {}},this.receivedResp=null,this.timeout=n,this.timeoutTimer=null,this.recHooks=[],this.sent=false,this.ref=void 0;}resend(t){this.timeout=t,this.reset(),this.send();}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=true,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}));}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=false;}destroy(){this.cancelRefEvent(),this.cancelTimeout();}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(n=>n.status===t).forEach(n=>n.callback(e));}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent);}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null;}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t);}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{});},this.timeout);}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e});}},Zl=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0;}reset(){this.tries=0,clearTimeout(this.timer);}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback();},this.timerCalc(this.tries+1));}},Wg=class{constructor(t,e,r){this.state=Q.closed,this.topic=t,this.params=Er(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=false,this.joinPush=new $n(this,Ie.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Zl(()=>{this.socket.isConnected()&&this.rejoin();},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin();})),this.joinPush.receive("ok",()=>{this.state=Q.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(n=>n.send()),this.pushBuffer=[];}),this.joinPush.receive("error",n=>{this.state=Q.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout();}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Q.closed,this.socket.remove(this);}),this.onError(n=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.isJoining()&&this.joinPush.reset(),this.state=Q.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout();}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new $n(this,Ie.leave,Er({}),this.timeout).send(),this.state=Q.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout();}),this.on(Ie.reply,(n,i)=>{this.trigger(this.replyEventName(i),n);});}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=true,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Q.closed,this.bindings=[];}onClose(t){this.on(Ie.close,t);}onError(t){return this.on(Ie.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)));}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let n=new $n(this,t,function(){return e},r);return this.canPush()?n.send():(n.startTimeout(),this.pushBuffer.push(n)),n}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Q.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(Ie.close,"leave");},r=new $n(this,Ie.leave,Er({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return true}isMember(t,e,r,n){return this.topic!==t?false:n&&n!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:n}),false):true}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Q.joining,this.joinPush.resend(t));}trigger(t,e,r,n){let i=this.onMessage(t,e,r,n);if(e&&!i)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let s=this.bindings.filter(o=>o.event===t&&this.filterBindings(o,e,r));for(let o=0;o<s.length;o++)s[o].callback(i,r,n||this.joinRef());}replyEventName(t){return `chan_reply_${t}`}isClosed(){return this.state===Q.closed}isErrored(){return this.state===Q.errored}isJoined(){return this.state===Q.joined}isJoining(){return this.state===Q.joining}isLeaving(){return this.state===Q.leaving}},jn=class{static request(t,e,r,n,i,s,o){if(ye.XDomainRequest){let a=new ye.XDomainRequest;return this.xdomainRequest(a,t,e,n,i,s,o)}else if(ye.XMLHttpRequest){let a=new ye.XMLHttpRequest;return this.xhrRequest(a,t,e,r,n,i,s,o)}else {if(ye.fetch&&ye.AbortController)return this.fetchRequest(t,e,r,n,i,s,o);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,n,i,s,o){let a={method:t,headers:r,body:n},l=null;if(i){l=new AbortController;setTimeout(()=>l.abort(),i);a.signal=l.signal;}return ye.fetch(e,a).then(c=>c.text()).then(c=>this.parseJSON(c)).then(c=>o&&o(c)).catch(c=>{c.name==="AbortError"&&s?s():o&&o(null);}),l}static xdomainRequest(t,e,r,n,i,s,o){return t.timeout=i,t.open(e,r),t.onload=()=>{let a=this.parseJSON(t.responseText);o&&o(a);},s&&(t.ontimeout=s),t.onprogress=()=>{},t.send(n),t}static xhrRequest(t,e,r,n,i,s,o,a){t.open(e,r,true),t.timeout=s;for(let[l,c]of Object.entries(n))t.setRequestHeader(l,c);return t.onerror=()=>a&&a(null),t.onreadystatechange=()=>{if(t.readyState===Ug.complete&&a){let l=this.parseJSON(t.responseText);a(l);}},o&&(t.ontimeout=o),t.send(i),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let i=e?`${e}[${n}]`:n,s=t[n];typeof s=="object"?r.push(this.serialize(s,i)):r.push(encodeURIComponent(i)+"="+encodeURIComponent(s));}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return `${t}${r}${this.serialize(e)}`}},Bg=t=>{let e="",r=new Uint8Array(t),n=r.byteLength;for(let i=0;i<n;i++)e+=String.fromCharCode(r[i]);return btoa(e)},Ft=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(Cs)&&(this.authToken=atob(e[1].slice(Cs.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=true,this.reqs=new Set,this.awaitingBatchAck=false,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=ke.connecting,setTimeout(()=>this.poll(),0);}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Ss.websocket),"$1/"+Ss.longpoll)}endpointURL(){return jn.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=ke.connecting;}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",false);}isActive(){return this.readyState===ke.open||this.readyState===ke.connecting}poll(){let t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:n,messages:i}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",false);return}this.token=n;}else r=0;switch(r){case 200:i.forEach(s=>{setTimeout(()=>this.onmessage({data:s}),0);}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=ke.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",false);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}});}send(t){typeof t!="string"&&(t=Bg(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null;},0));}batchSend(t){this.awaitingBatchAck=true,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(`
|
|
12
|
-
`),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=false,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",false)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[]);});}close(t,e,r){for(let i of this.reqs)i.abort();this.readyState=ke.closed;let n=Object.assign({code:1e3,reason:void 0,wasClean:true},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",n)):this.onclose(n);}ajax(t,e,r,n,i){let s,o=()=>{this.reqs.delete(s),n();};s=jn.request(t,this.endpointURL(),e,r,this.timeout,o,a=>{this.reqs.delete(s),this.isActive()&&i(a);}),this.reqs.add(s);}},Ql=class Cr{constructor(e,r={}){let n=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(n.state,i=>{let{onJoin:s,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel.joinRef(),this.state=Cr.syncState(this.state,i,s,o),this.pendingDiffs.forEach(l=>{this.state=Cr.syncDiff(this.state,l,s,o);}),this.pendingDiffs=[],a();}),this.channel.on(n.diff,i=>{let{onJoin:s,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=Cr.syncDiff(this.state,i,s,o),a());});}onJoin(e){this.caller.onJoin=e;}onLeave(e){this.caller.onLeave=e;}onSync(e){this.caller.onSync=e;}list(e){return Cr.list(this.state,e)}inPendingSyncState(){return !this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,n,i){let s=this.clone(e),o={},a={};return this.map(s,(l,c)=>{r[l]||(a[l]=c);}),this.map(r,(l,c)=>{let u=s[l];if(u){let d=c.metas.map(m=>m.phx_ref),p=u.metas.map(m=>m.phx_ref),h=c.metas.filter(m=>p.indexOf(m.phx_ref)<0),f=u.metas.filter(m=>d.indexOf(m.phx_ref)<0);h.length>0&&(o[l]=c,o[l].metas=h),f.length>0&&(a[l]=this.clone(u),a[l].metas=f);}else o[l]=c;}),this.syncDiff(s,{joins:o,leaves:a},n,i)}static syncDiff(e,r,n,i){let{joins:s,leaves:o}=this.clone(r);return n||(n=function(){}),i||(i=function(){}),this.map(s,(a,l)=>{let c=e[a];if(e[a]=this.clone(l),c){let u=e[a].metas.map(p=>p.phx_ref),d=c.metas.filter(p=>u.indexOf(p.phx_ref)<0);e[a].metas.unshift(...d);}n(a,c,l);}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;let u=l.metas.map(d=>d.phx_ref);c.metas=c.metas.filter(d=>u.indexOf(d.phx_ref)<0),i(a,c,l),c.metas.length===0&&delete e[a];}),e}static list(e,r){return r||(r=function(n,i){return i}),this.map(e,(n,i)=>r(n,i))}static map(e,r){return Object.getOwnPropertyNames(e).map(n=>r(n,e[n]))}static clone(e){return JSON.parse(JSON.stringify(e))}},Nn={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,n,i,s,o]=JSON.parse(t);return e({join_ref:r,ref:n,topic:i,event:s,payload:o})}},binaryEncode(t){let{join_ref:e,ref:r,event:n,topic:i,payload:s}=t,o=this.META_LENGTH+e.length+r.length+i.length+n.length,a=new ArrayBuffer(this.HEADER_LENGTH+o),l=new DataView(a),c=0;l.setUint8(c++,this.KINDS.push),l.setUint8(c++,e.length),l.setUint8(c++,r.length),l.setUint8(c++,i.length),l.setUint8(c++,n.length),Array.from(e,d=>l.setUint8(c++,d.charCodeAt(0))),Array.from(r,d=>l.setUint8(c++,d.charCodeAt(0))),Array.from(i,d=>l.setUint8(c++,d.charCodeAt(0))),Array.from(n,d=>l.setUint8(c++,d.charCodeAt(0)));var u=new Uint8Array(a.byteLength+s.byteLength);return u.set(new Uint8Array(a),0),u.set(new Uint8Array(s),a.byteLength),u.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),n=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,n);case this.KINDS.reply:return this.decodeReply(t,e,n);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,n)}},decodePush(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),s=e.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,a=r.decode(t.slice(o,o+n));o=o+n;let l=r.decode(t.slice(o,o+i));o=o+i;let c=r.decode(t.slice(o,o+s));o=o+s;let u=t.slice(o,t.byteLength);return {join_ref:a,ref:null,topic:l,event:c,payload:u}},decodeReply(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),s=e.getUint8(3),o=e.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(t.slice(a,a+n));a=a+n;let c=r.decode(t.slice(a,a+i));a=a+i;let u=r.decode(t.slice(a,a+s));a=a+s;let d=r.decode(t.slice(a,a+o));a=a+o;let p=t.slice(a,t.byteLength),h={status:d,response:p};return {join_ref:l,ref:c,topic:u,event:Ie.reply,payload:h}},decodeBroadcast(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),s=this.HEADER_LENGTH+2,o=r.decode(t.slice(s,s+n));s=s+n;let a=r.decode(t.slice(s,s+i));s=s+i;let l=t.slice(s,t.byteLength);return {join_ref:null,ref:null,topic:o,event:a,payload:l}}},ec=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||Mg,this.transport=e.transport||ye.WebSocket||Ft,this.conn=void 0,this.primaryPassedHealthCheck=false,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||ye&&ye.sessionStorage,this.establishedConnections=0,this.defaultEncoder=Nn.encode.bind(Nn),this.defaultDecoder=Nn.decode.bind(Nn),this.closeWasClean=true,this.disconnecting=false,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=false,this.encode=void 0,this.decode=void 0,this.transport!==Ft?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let r=null;Ht&&Ht.addEventListener&&(Ht.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),r=this.connectClock);}),Ht.addEventListener("pageshow",n=>{r===this.connectClock&&(r=null,this.connect());}),Ht.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=true:(this.pageHidden=false,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()));})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??true,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=n=>e.rejoinAfterMs?e.rejoinAfterMs(n):[1e3,2e3,5e3][n-1]||1e4,this.reconnectAfterMs=n=>e.reconnectAfterMs?e.reconnectAfterMs(n):[10,50,100,150,200,250,500,1e3,2e3][n-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(n,i,s)=>{console.log(`${n}: ${i}`,s);}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=Er(e.params||{}),this.endPoint=`${t}/${Ss.websocket}`,this.vsn=e.vsn||Dg,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Zl(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect();});},this.reconnectAfterMs),this.authToken=e.authToken;}getLongPollTransport(){return Ft}replaceTransport(t){this.connectClock++,this.closeWasClean=true,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t;}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=jn.appendParams(jn.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=true,this.closeWasClean=true,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=false,t&&t();},e,r);}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Er(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Ft?this.connectWithFallback(Ft,this.longPollFallbackMs):this.transportConnect());}log(t,e,r){this.logger&&this.logger(t,e,r);}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t;}ping(t){if(!this.isConnected())return false;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let n=this.onMessage(i=>{i.ref===e&&(this.off([n]),t(Date.now()-r));});return true}transportName(t){return t===Ft?"LongPoll":t.name}transportConnect(){this.connectClock++,this.closeWasClean=false;let t;this.authToken&&(t=["phoenix",`${Cs}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e);}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e);}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=false,n=true,i,s,o=this.transportName(t),a=l=>{this.log("transport",`falling back to ${o}...`,l),this.off([i,s]),n=false,this.replaceTransport(t),this.transportConnect();};if(this.getSession(`phx:fallback:${o}`))return a("memorized");this.fallbackTimer=setTimeout(a,e),s=this.onError(l=>{this.log("transport","error",l),n&&!r&&(clearTimeout(this.fallbackTimer),a(l));}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=true,!n){let l=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(a,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=true,clearTimeout(this.fallbackTimer);});}),this.transportConnect();}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer);}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=false,this.disconnecting=false,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open");}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout");}catch(t){this.log("error","error in heartbeat callback",t);}this.triggerChanError(),this.closeWasClean=false,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Lg,"heartbeat timeout");}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs));}teardown(t,e,r){if(!this.conn)return t&&t();let n=this.conn;this.waitForBufferDone(n,()=>{e?n.close(e,r||""):n.close(),this.waitForSocketClosed(n,()=>{this.conn===n&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t();});});}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1);},150*r);}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===ke.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1);},150*r);}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t);}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError();}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(Ie.error);});}connectionState(){switch(this.conn&&this.conn.readyState){case ke.connecting:return "connecting";case ke.open:return "open";case ke.closing:return "closing";default:return "closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t);}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1);}channel(t,e={}){let r=new Wg(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:n,ref:i,join_ref:s}=t;this.log("push",`${e} ${r} (${s}, ${i})`,n);}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)));}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected");}catch(t){this.log("error","error in heartbeat callback",t);}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent");}catch(t){this.log("error","error in heartbeat callback",t);}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs);}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[]);}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:n,payload:i,ref:s,join_ref:o}=e;if(s&&s===this.pendingHeartbeatRef){let a=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(i.status==="ok"?"ok":"error",a);}catch(l){this.log("error","error in heartbeat callback",l);}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs));}this.hasLogger()&&this.log("receive",`${i.status||""} ${r} ${n} ${s&&"("+s+")"||""}`.trim(),i);for(let a=0;a<this.channels.length;a++){let l=this.channels[a];l.isMember(r,n,i,o)&&l.trigger(n,i,s,o);}this.triggerStateCallbacks("message",e);});}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,n])=>{try{n(...e);}catch(i){this.log("error",`error in ${t} callback`,i);}});}catch(r){this.log("error",`error triggering ${t} callbacks`,r);}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave());}};});function Dn(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function Fg(t){return JSON.parse(JSON.stringify(t))}function Hg(t){return t?.events&&{events:t.events}}function tc(t){return t?.metas?Dn(t):[]}var Rr,rc=R(()=>{Es();Rr=class t{constructor(e,r){let n=Hg(r);this.presence=new Ql(e.getChannel(),n),this.presence.onJoin((i,s,o)=>{let a=t.onJoinPayload(i,s,o);e.getChannel().trigger("presence",a);}),this.presence.onLeave((i,s,o)=>{let a=t.onLeavePayload(i,s,o);e.getChannel().trigger("presence",a);}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"});});}get state(){return t.transformState(this.presence.state)}static transformState(e){return e=Fg(e),Object.getOwnPropertyNames(e).reduce((r,n)=>{let i=e[n];return r[n]=Dn(i),r},{})}static onJoinPayload(e,r,n){let i=tc(r),s=Dn(n);return {event:"join",key:e,currentPresences:i,newPresences:s}}static onLeavePayload(e,r,n){let i=tc(r),s=Dn(n);return {event:"leave",key:e,currentPresences:i,leftPresences:s}}};});var Rs,qt,xs=R(()=>{rc();(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave";})(Rs||(Rs={}));qt=class{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new Rr(this.channel.channelAdapter,r);}};});function qg(t){return {config:Object.assign({broadcast:{ack:false,self:false},presence:{key:"",enabled:false},private:false},t.config)}}var xr,nc=R(()=>{vr();xr=class{constructor(e,r,n){let i=qg(n);this.channel=e.getSocket().channel(r,i),this.socket=e;}get state(){return this.channel.state}set state(e){this.channel.state=e;}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r);}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown();}onClose(e){this.channel.onClose(e);}onError(e){return this.channel.onError(e)}push(e,r,n){let i;try{i=this.channel.push(e,r,n);}catch{throw `tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>Gl){let s=this.channel.pushBuffer.shift();s.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${s.event}`,s.payload());}return i}updateJoinPayload(e){let r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e);}canPush(){return this.socket.isConnected()&&this.state===we.joined}isJoined(){return this.state===we.joined}isJoining(){return this.state===we.joining}isClosed(){return this.state===we.closed}isLeaving(){return this.state===we.leaving}updateFilterBindings(e){this.channel.filterBindings=e;}updatePayloadTransform(e){this.channel.onMessage=e;}getChannel(){return this.channel}};});var Ps,st,be,zt,Ts=R(()=>{vr();xs();On();On();nc();(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE";})(Ps||(Ps={}));(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system";})(st||(st={}));(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR";})(be||(be={}));zt=class t{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e;}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},n){var i,s;if(this.topic=e,this.params=r,this.socket=n,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:false,self:false},presence:{key:"",enabled:false},private:false},r.config),this.channelAdapter=new xr(this.socket.socketAdapter,e,this.params),this.presence=new qt(this),this._onClose(()=>{this.socket._remove(this);}),this._updateFilterTransform(),this.broadcastEndpointURL=In(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||false,!this.private&&(!((s=(i=this.params.config)===null||i===void 0?void 0:i.broadcast)===null||s===void 0)&&s.replay))throw `tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var n,i,s;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:o,presence:a,private:l}}=this.params,c=(i=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(h=>h.filter))!==null&&i!==void 0?i:[],u=!!this.bindings[st.PRESENCE]&&this.bindings[st.PRESENCE].length>0||((s=this.params.config.presence)===null||s===void 0?void 0:s.enabled)===true,d={},p={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:u}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(h=>{e?.(be.CHANNEL_ERROR,h);}),this._onClose(()=>e?.(be.CLOSED)),this.updateJoinPayload(Object.assign({config:p},d)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:h})=>{if(this.socket._isManualToken()||this.socket.setAuth(),h===void 0){e?.(be.SUBSCRIBED);return}this._updatePostgresBindings(h,e);}).receive("error",h=>{this.state=we.errored,e?.(be.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(h).join(", ")||"error")));}).receive("timeout",()=>{e?.(be.TIMED_OUT);});}return this}_updatePostgresBindings(e,r){var n;let i=this.bindings.postgres_changes,s=(n=i?.length)!==null&&n!==void 0?n:0,o=[];for(let a=0;a<s;a++){let l=i[a],{filter:{event:c,schema:u,table:d,filter:p}}=l,h=e&&e[a];if(h&&h.event===c&&t.isFilterValueEqual(h.schema,u)&&t.isFilterValueEqual(h.table,d)&&t.isFilterValueEqual(h.filter,p))o.push(Object.assign(Object.assign({},l),{id:h.id}));else {this.unsubscribe(),this.state=we.errored,r?.(be.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=o,this.state!=we.errored&&r&&r(be.SUBSCRIBED);}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,n){let i=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),s=e===st.PRESENCE||e===st.POSTGRES_CHANGES;if(i&&s)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,r,n)}async httpSend(e,r,n={}){var i;if(r==null)return Promise.reject("Payload is required for httpSend()");let s={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(s.Authorization=`Bearer ${this.socket.accessTokenValue}`);let o={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(i=n.timeout)!==null&&i!==void 0?i:this.timeout);if(a.status===202)return {success:true};let l=a.statusText;try{let c=await a.json();l=c.error||c.message||l;}catch{}return Promise.reject(new Error(l))}async send(e,r={}){var n,i;if(!this.channelAdapter.canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");let{event:s,payload:o}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let l={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:s,payload:o,private:this.private}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(s=>{var o,a,l;let c=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&s("ok"),c.receive("ok",()=>s("ok")),c.receive("error",()=>s("error")),c.receive("timeout",()=>s("timed out"));})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e);}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"));})}teardown(){this.channelAdapter.teardown();}async _fetchWithTimeout(e,r,n){let i=new AbortController,s=setTimeout(()=>i.abort(),n),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:i.signal}));return clearTimeout(s),o}_on(e,r,n){let i=e.toLocaleLowerCase(),s=this.channelAdapter.on(e,n),o={type:i,filter:r,callback:n,ref:s};return this.bindings[i]?this.bindings[i].push(o):this.bindings[i]=[o],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e);}_onError(e){this.channelAdapter.onError(e);}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,n)=>{var i,s,o,a,l,c,u;let d=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(d,n))return false;let p=(i=this.bindings[d])===null||i===void 0?void 0:i.find(h=>h.ref===e.ref);if(!p)return true;if(["broadcast","presence","postgres_changes"].includes(d))if("id"in p){let h=p.id,f=(s=p.filter)===null||s===void 0?void 0:s.event;return h&&((o=r.ids)===null||o===void 0?void 0:o.includes(h))&&(f==="*"||f?.toLocaleLowerCase()===((a=r.data)===null||a===void 0?void 0:a.type.toLocaleLowerCase()))}else {let h=(c=(l=p?.filter)===null||l===void 0?void 0:l.event)===null||c===void 0?void 0:c.toLocaleLowerCase();return h==="*"||h===((u=r?.event)===null||u===void 0?void 0:u.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===d});}_notThisChannelEvent(e,r){let{close:n,error:i,leave:s,join:o}=An;return r&&[n,i,s,o].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,n)=>{if(typeof r=="object"&&"ids"in r){let i=r.data,{schema:s,table:o,commit_timestamp:a,type:l,errors:c}=i;return Object.assign(Object.assign({},{schema:s,table:o,commit_timestamp:a,eventType:l,new:{},old:{},errors:c}),this._getPayloadRecords(i))}return r});}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(let r in e.bindings)for(let n of e.bindings[r])this._on(n.type,n.filter,n.callback);}static isFilterValueEqual(e,r){return (e??void 0)===(r??void 0)}_getPayloadRecords(e){let r={new:{},old:{}};return (e.type==="INSERT"||e.type==="UPDATE")&&(r.new=vs(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=vs(e.columns,e.old_record)),r}};});var Pr,ic=R(()=>{Es();vr();Pr=class{constructor(e,r){this.socket=new ec(e,r);}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e;}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect();}disconnect(e,r,n,i=1e4){return new Promise(s=>{setTimeout(()=>s("timeout"),i),this.socket.disconnect(()=>{e(),s("ok");},r,n);})}push(e){this.socket.push(e);}log(e,r,n){this.socket.log(e,r,n);}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e);}onClose(e){this.socket.onClose(e);}onError(e){this.socket.onError(e);}onMessage(e){this.socket.onMessage(e);}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==br.connecting}isDisconnecting(){return this.socket.connectionState()==br.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat();}getSocket(){return this.socket}};});var zg,Jg,Kg,Vg,Jt,sc=R(()=>{ys();vr();Yl();On();Ts();ic();zg={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Jg=[1e3,2e3,5e3,1e4],Kg=1e4,Vg=`
|
|
11
|
+
Suggested solution: ${e.workaround}`),new Error(r)}static isWebSocketSupported(){try{let e=this.detectEnvironment();return e.type==="native"||e.type==="ws"}catch{return false}}},ws=_s;});var Hl,ql=R(()=>{Hl="2.103.2";});var zl,Jl,ks,Kl,Vl,Gl,ye,In,br,vr=R(()=>{ql();zl=`realtime-js/${Hl}`,Jl="1.0.0",ks="2.0.0",Kl=ks,Vl=1e4,Gl=100,ye={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},In={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave",access_token:"access_token"},br={connecting:"connecting",open:"open",closing:"closing",closed:"closed"};});var Sr,Yl=R(()=>{Sr=class{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[];}encode(e,r){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event=="string")return r(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return r(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){var r;return this._isArrayBuffer((r=e.payload)===null||r===void 0?void 0:r.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){var r,n;let i=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,i)}_encodeJsonUserBroadcastPush(e){var r,n;let i=(n=(r=e.payload)===null||r===void 0?void 0:r.payload)!==null&&n!==void 0?n:{},o=new TextEncoder().encode(JSON.stringify(i)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(e,r,n){var i,s;let o=e.topic,a=(i=e.ref)!==null&&i!==void 0?i:"",l=(s=e.join_ref)!==null&&s!==void 0?s:"",c=e.payload.event,u=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},d=Object.keys(u).length===0?"":JSON.stringify(u);if(l.length>255)throw new Error(`joinRef length ${l.length} exceeds maximum of 255`);if(a.length>255)throw new Error(`ref length ${a.length} exceeds maximum of 255`);if(o.length>255)throw new Error(`topic length ${o.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`userEvent length ${c.length} exceeds maximum of 255`);if(d.length>255)throw new Error(`metadata length ${d.length} exceeds maximum of 255`);let p=this.USER_BROADCAST_PUSH_META_LENGTH+l.length+a.length+o.length+c.length+d.length,h=new ArrayBuffer(this.HEADER_LENGTH+p),f=new DataView(h),m=0;f.setUint8(m++,this.KINDS.userBroadcastPush),f.setUint8(m++,l.length),f.setUint8(m++,a.length),f.setUint8(m++,o.length),f.setUint8(m++,c.length),f.setUint8(m++,d.length),f.setUint8(m++,r),Array.from(l,b=>f.setUint8(m++,b.charCodeAt(0))),Array.from(a,b=>f.setUint8(m++,b.charCodeAt(0))),Array.from(o,b=>f.setUint8(m++,b.charCodeAt(0))),Array.from(c,b=>f.setUint8(m++,b.charCodeAt(0))),Array.from(d,b=>f.setUint8(m++,b.charCodeAt(0)));var _=new Uint8Array(h.byteLength+n.byteLength);return _.set(new Uint8Array(h),0),_.set(new Uint8Array(n),h.byteLength),_.buffer}decode(e,r){if(this._isArrayBuffer(e)){let n=this._binaryDecode(e);return r(n)}if(typeof e=="string"){let n=JSON.parse(e),[i,s,o,a,l]=n;return r({join_ref:i,ref:s,topic:o,event:a,payload:l})}return r({})}_binaryDecode(e){let r=new DataView(e),n=r.getUint8(0),i=new TextDecoder;if(n===this.KINDS.userBroadcast)return this._decodeUserBroadcast(e,r,i)}_decodeUserBroadcast(e,r,n){let i=r.getUint8(1),s=r.getUint8(2),o=r.getUint8(3),a=r.getUint8(4),l=this.HEADER_LENGTH+4,c=n.decode(e.slice(l,l+i));l=l+i;let u=n.decode(e.slice(l,l+s));l=l+s;let d=n.decode(e.slice(l,l+o));l=l+o;let p=e.slice(l,e.byteLength),h=a===this.JSON_ENCODING?JSON.parse(n.decode(p)):p,f={type:this.BROADCAST_EVENT,event:u,payload:h};return o>0&&(f.meta=JSON.parse(d)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:f}}_isArrayBuffer(e){var r;return e instanceof ArrayBuffer||((r=e?.constructor)===null||r===void 0?void 0:r.name)==="ArrayBuffer"}_pick(e,r){return !e||typeof e!="object"?{}:Object.fromEntries(Object.entries(e).filter(([n])=>r.includes(n)))}};});var N,vs,Pg,Xl,bs,Tg,Ag,Ig,Og,$g,On,$n=R(()=>{(function(t){t.abstime="abstime",t.bool="bool",t.date="date",t.daterange="daterange",t.float4="float4",t.float8="float8",t.int2="int2",t.int4="int4",t.int4range="int4range",t.int8="int8",t.int8range="int8range",t.json="json",t.jsonb="jsonb",t.money="money",t.numeric="numeric",t.oid="oid",t.reltime="reltime",t.text="text",t.time="time",t.timestamp="timestamp",t.timestamptz="timestamptz",t.timetz="timetz",t.tsrange="tsrange",t.tstzrange="tstzrange";})(N||(N={}));vs=(t,e,r={})=>{var n;let i=(n=r.skipTypes)!==null&&n!==void 0?n:[];return e?Object.keys(e).reduce((s,o)=>(s[o]=Pg(o,t,e,i),s),{}):{}},Pg=(t,e,r,n)=>{let i=e.find(a=>a.name===t),s=i?.type,o=r[t];return s&&!n.includes(s)?Xl(s,o):bs(o)},Xl=(t,e)=>{if(t.charAt(0)==="_"){let r=t.slice(1,t.length);return Og(e,r)}switch(t){case N.bool:return Tg(e);case N.float4:case N.float8:case N.int2:case N.int4:case N.int8:case N.numeric:case N.oid:return Ag(e);case N.json:case N.jsonb:return Ig(e);case N.timestamp:return $g(e);case N.abstime:case N.date:case N.daterange:case N.int4range:case N.int8range:case N.money:case N.reltime:case N.text:case N.time:case N.timestamptz:case N.timetz:case N.tsrange:case N.tstzrange:return bs(e);default:return bs(e)}},bs=t=>t,Tg=t=>{switch(t){case "t":return true;case "f":return false;default:return t}},Ag=t=>{if(typeof t=="string"){let e=parseFloat(t);if(!Number.isNaN(e))return e}return t},Ig=t=>{if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t},Og=(t,e)=>{if(typeof t!="string")return t;let r=t.length-1,n=t[r];if(t[0]==="{"&&n==="}"){let s,o=t.slice(1,r);try{s=JSON.parse("["+o+"]");}catch{s=o?o.split(","):[];}return s.map(a=>Xl(e,a))}return t},$g=t=>typeof t=="string"?t.replace(" ","T"):t,On=t=>{let e=new URL(t);return e.protocol=e.protocol.replace(/^ws/i,"http"),e.pathname=e.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),e.pathname===""||e.pathname==="/"?e.pathname="/api/broadcast":e.pathname=e.pathname+"/api/broadcast",e.href};});var Er,jg,Ht,ke,Dg,Mg,Lg,be,Q,Ie,Ss,Ug,Cs,Nn,Zl,Wg,Dn,Bg,Ft,Ql,jn,ec,Es=R(()=>{Er=t=>typeof t=="function"?t:function(){return t},jg=typeof self<"u"?self:null,Ht=typeof window<"u"?window:null,ke=jg||Ht||globalThis,Dg="2.0.0",Mg=1e4,Lg=1e3,be={connecting:0,open:1,closing:2,closed:3},Q={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Ie={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},Ss={longpoll:"longpoll",websocket:"websocket"},Ug={complete:4},Cs="base64url.bearer.phx.",Nn=class{constructor(t,e,r,n){this.channel=t,this.event=e,this.payload=r||function(){return {}},this.receivedResp=null,this.timeout=n,this.timeoutTimer=null,this.recHooks=[],this.sent=false,this.ref=void 0;}resend(t){this.timeout=t,this.reset(),this.send();}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=true,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}));}receive(t,e){return this.hasReceived(t)&&e(this.receivedResp.response),this.recHooks.push({status:t,callback:e}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=false;}destroy(){this.cancelRefEvent(),this.cancelTimeout();}matchReceive({status:t,response:e,_ref:r}){this.recHooks.filter(n=>n.status===t).forEach(n=>n.callback(e));}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent);}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null;}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,t=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=t,this.matchReceive(t);}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{});},this.timeout);}hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}trigger(t,e){this.channel.trigger(this.refEvent,{status:t,response:e});}},Zl=class{constructor(t,e){this.callback=t,this.timerCalc=e,this.timer=void 0,this.tries=0;}reset(){this.tries=0,clearTimeout(this.timer);}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback();},this.timerCalc(this.tries+1));}},Wg=class{constructor(t,e,r){this.state=Q.closed,this.topic=t,this.params=Er(e||{}),this.socket=r,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=false,this.joinPush=new Nn(this,Ie.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new Zl(()=>{this.socket.isConnected()&&this.rejoin();},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin();})),this.joinPush.receive("ok",()=>{this.state=Q.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(n=>n.send()),this.pushBuffer=[];}),this.joinPush.receive("error",n=>{this.state=Q.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout();}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Q.closed,this.socket.remove(this);}),this.onError(n=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,n),this.isJoining()&&this.joinPush.reset(),this.state=Q.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout();}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new Nn(this,Ie.leave,Er({}),this.timeout).send(),this.state=Q.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout();}),this.on(Ie.reply,(n,i)=>{this.trigger(this.replyEventName(i),n);});}join(t=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=t,this.joinedOnce=true,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Q.closed,this.bindings=[];}onClose(t){this.on(Ie.close,t);}onError(t){return this.on(Ie.error,e=>t(e))}on(t,e){let r=this.bindingRef++;return this.bindings.push({event:t,ref:r,callback:e}),r}off(t,e){this.bindings=this.bindings.filter(r=>!(r.event===t&&(typeof e>"u"||e===r.ref)));}canPush(){return this.socket.isConnected()&&this.isJoined()}push(t,e,r=this.timeout){if(e=e||{},!this.joinedOnce)throw new Error(`tried to push '${t}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let n=new Nn(this,t,function(){return e},r);return this.canPush()?n.send():(n.startTimeout(),this.pushBuffer.push(n)),n}leave(t=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Q.leaving;let e=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(Ie.close,"leave");},r=new Nn(this,Ie.leave,Er({}),t);return r.receive("ok",()=>e()).receive("timeout",()=>e()),r.send(),this.canPush()||r.trigger("ok",{}),r}onMessage(t,e,r){return e}filterBindings(t,e,r){return true}isMember(t,e,r,n){return this.topic!==t?false:n&&n!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:t,event:e,payload:r,joinRef:n}),false):true}joinRef(){return this.joinPush.ref}rejoin(t=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Q.joining,this.joinPush.resend(t));}trigger(t,e,r,n){let i=this.onMessage(t,e,r,n);if(e&&!i)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let s=this.bindings.filter(o=>o.event===t&&this.filterBindings(o,e,r));for(let o=0;o<s.length;o++)s[o].callback(i,r,n||this.joinRef());}replyEventName(t){return `chan_reply_${t}`}isClosed(){return this.state===Q.closed}isErrored(){return this.state===Q.errored}isJoined(){return this.state===Q.joined}isJoining(){return this.state===Q.joining}isLeaving(){return this.state===Q.leaving}},Dn=class{static request(t,e,r,n,i,s,o){if(ke.XDomainRequest){let a=new ke.XDomainRequest;return this.xdomainRequest(a,t,e,n,i,s,o)}else if(ke.XMLHttpRequest){let a=new ke.XMLHttpRequest;return this.xhrRequest(a,t,e,r,n,i,s,o)}else {if(ke.fetch&&ke.AbortController)return this.fetchRequest(t,e,r,n,i,s,o);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(t,e,r,n,i,s,o){let a={method:t,headers:r,body:n},l=null;if(i){l=new AbortController;setTimeout(()=>l.abort(),i);a.signal=l.signal;}return ke.fetch(e,a).then(c=>c.text()).then(c=>this.parseJSON(c)).then(c=>o&&o(c)).catch(c=>{c.name==="AbortError"&&s?s():o&&o(null);}),l}static xdomainRequest(t,e,r,n,i,s,o){return t.timeout=i,t.open(e,r),t.onload=()=>{let a=this.parseJSON(t.responseText);o&&o(a);},s&&(t.ontimeout=s),t.onprogress=()=>{},t.send(n),t}static xhrRequest(t,e,r,n,i,s,o,a){t.open(e,r,true),t.timeout=s;for(let[l,c]of Object.entries(n))t.setRequestHeader(l,c);return t.onerror=()=>a&&a(null),t.onreadystatechange=()=>{if(t.readyState===Ug.complete&&a){let l=this.parseJSON(t.responseText);a(l);}},o&&(t.ontimeout=o),t.send(i),t}static parseJSON(t){if(!t||t==="")return null;try{return JSON.parse(t)}catch{return console&&console.log("failed to parse JSON response",t),null}}static serialize(t,e){let r=[];for(var n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let i=e?`${e}[${n}]`:n,s=t[n];typeof s=="object"?r.push(this.serialize(s,i)):r.push(encodeURIComponent(i)+"="+encodeURIComponent(s));}return r.join("&")}static appendParams(t,e){if(Object.keys(e).length===0)return t;let r=t.match(/\?/)?"&":"?";return `${t}${r}${this.serialize(e)}`}},Bg=t=>{let e="",r=new Uint8Array(t),n=r.byteLength;for(let i=0;i<n;i++)e+=String.fromCharCode(r[i]);return btoa(e)},Ft=class{constructor(t,e){e&&e.length===2&&e[1].startsWith(Cs)&&(this.authToken=atob(e[1].slice(Cs.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=true,this.reqs=new Set,this.awaitingBatchAck=false,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(t),this.readyState=be.connecting,setTimeout(()=>this.poll(),0);}normalizeEndpoint(t){return t.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+Ss.websocket),"$1/"+Ss.longpoll)}endpointURL(){return Dn.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(t,e,r){this.close(t,e,r),this.readyState=be.connecting;}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",false);}isActive(){return this.readyState===be.open||this.readyState===be.connecting}poll(){let t={Accept:"application/json"};this.authToken&&(t["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",t,null,()=>this.ontimeout(),e=>{if(e){var{status:r,token:n,messages:i}=e;if(r===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",false);return}this.token=n;}else r=0;switch(r){case 200:i.forEach(s=>{setTimeout(()=>this.onmessage({data:s}),0);}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=be.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",false);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${r}`)}});}send(t){typeof t!="string"&&(t=Bg(t)),this.currentBatch?this.currentBatch.push(t):this.awaitingBatchAck?this.batchBuffer.push(t):(this.currentBatch=[t],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null;},0));}batchSend(t){this.awaitingBatchAck=true,this.ajax("POST",{"Content-Type":"application/x-ndjson"},t.join(`
|
|
12
|
+
`),()=>this.onerror("timeout"),e=>{this.awaitingBatchAck=false,!e||e.status!==200?(this.onerror(e&&e.status),this.closeAndRetry(1011,"internal server error",false)):this.batchBuffer.length>0&&(this.batchSend(this.batchBuffer),this.batchBuffer=[]);});}close(t,e,r){for(let i of this.reqs)i.abort();this.readyState=be.closed;let n=Object.assign({code:1e3,reason:void 0,wasClean:true},{code:t,reason:e,wasClean:r});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",n)):this.onclose(n);}ajax(t,e,r,n,i){let s,o=()=>{this.reqs.delete(s),n();};s=Dn.request(t,this.endpointURL(),e,r,this.timeout,o,a=>{this.reqs.delete(s),this.isActive()&&i(a);}),this.reqs.add(s);}},Ql=class Cr{constructor(e,r={}){let n=r.events||{state:"presence_state",diff:"presence_diff"};this.state={},this.pendingDiffs=[],this.channel=e,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(n.state,i=>{let{onJoin:s,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel.joinRef(),this.state=Cr.syncState(this.state,i,s,o),this.pendingDiffs.forEach(l=>{this.state=Cr.syncDiff(this.state,l,s,o);}),this.pendingDiffs=[],a();}),this.channel.on(n.diff,i=>{let{onJoin:s,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=Cr.syncDiff(this.state,i,s,o),a());});}onJoin(e){this.caller.onJoin=e;}onLeave(e){this.caller.onLeave=e;}onSync(e){this.caller.onSync=e;}list(e){return Cr.list(this.state,e)}inPendingSyncState(){return !this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,r,n,i){let s=this.clone(e),o={},a={};return this.map(s,(l,c)=>{r[l]||(a[l]=c);}),this.map(r,(l,c)=>{let u=s[l];if(u){let d=c.metas.map(m=>m.phx_ref),p=u.metas.map(m=>m.phx_ref),h=c.metas.filter(m=>p.indexOf(m.phx_ref)<0),f=u.metas.filter(m=>d.indexOf(m.phx_ref)<0);h.length>0&&(o[l]=c,o[l].metas=h),f.length>0&&(a[l]=this.clone(u),a[l].metas=f);}else o[l]=c;}),this.syncDiff(s,{joins:o,leaves:a},n,i)}static syncDiff(e,r,n,i){let{joins:s,leaves:o}=this.clone(r);return n||(n=function(){}),i||(i=function(){}),this.map(s,(a,l)=>{let c=e[a];if(e[a]=this.clone(l),c){let u=e[a].metas.map(p=>p.phx_ref),d=c.metas.filter(p=>u.indexOf(p.phx_ref)<0);e[a].metas.unshift(...d);}n(a,c,l);}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;let u=l.metas.map(d=>d.phx_ref);c.metas=c.metas.filter(d=>u.indexOf(d.phx_ref)<0),i(a,c,l),c.metas.length===0&&delete e[a];}),e}static list(e,r){return r||(r=function(n,i){return i}),this.map(e,(n,i)=>r(n,i))}static map(e,r){return Object.getOwnPropertyNames(e).map(n=>r(n,e[n]))}static clone(e){return JSON.parse(JSON.stringify(e))}},jn={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(t,e){if(t.payload.constructor===ArrayBuffer)return e(this.binaryEncode(t));{let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return e(JSON.stringify(r))}},decode(t,e){if(t.constructor===ArrayBuffer)return e(this.binaryDecode(t));{let[r,n,i,s,o]=JSON.parse(t);return e({join_ref:r,ref:n,topic:i,event:s,payload:o})}},binaryEncode(t){let{join_ref:e,ref:r,event:n,topic:i,payload:s}=t,o=this.META_LENGTH+e.length+r.length+i.length+n.length,a=new ArrayBuffer(this.HEADER_LENGTH+o),l=new DataView(a),c=0;l.setUint8(c++,this.KINDS.push),l.setUint8(c++,e.length),l.setUint8(c++,r.length),l.setUint8(c++,i.length),l.setUint8(c++,n.length),Array.from(e,d=>l.setUint8(c++,d.charCodeAt(0))),Array.from(r,d=>l.setUint8(c++,d.charCodeAt(0))),Array.from(i,d=>l.setUint8(c++,d.charCodeAt(0))),Array.from(n,d=>l.setUint8(c++,d.charCodeAt(0)));var u=new Uint8Array(a.byteLength+s.byteLength);return u.set(new Uint8Array(a),0),u.set(new Uint8Array(s),a.byteLength),u.buffer},binaryDecode(t){let e=new DataView(t),r=e.getUint8(0),n=new TextDecoder;switch(r){case this.KINDS.push:return this.decodePush(t,e,n);case this.KINDS.reply:return this.decodeReply(t,e,n);case this.KINDS.broadcast:return this.decodeBroadcast(t,e,n)}},decodePush(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),s=e.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,a=r.decode(t.slice(o,o+n));o=o+n;let l=r.decode(t.slice(o,o+i));o=o+i;let c=r.decode(t.slice(o,o+s));o=o+s;let u=t.slice(o,t.byteLength);return {join_ref:a,ref:null,topic:l,event:c,payload:u}},decodeReply(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),s=e.getUint8(3),o=e.getUint8(4),a=this.HEADER_LENGTH+this.META_LENGTH,l=r.decode(t.slice(a,a+n));a=a+n;let c=r.decode(t.slice(a,a+i));a=a+i;let u=r.decode(t.slice(a,a+s));a=a+s;let d=r.decode(t.slice(a,a+o));a=a+o;let p=t.slice(a,t.byteLength),h={status:d,response:p};return {join_ref:l,ref:c,topic:u,event:Ie.reply,payload:h}},decodeBroadcast(t,e,r){let n=e.getUint8(1),i=e.getUint8(2),s=this.HEADER_LENGTH+2,o=r.decode(t.slice(s,s+n));s=s+n;let a=r.decode(t.slice(s,s+i));s=s+i;let l=t.slice(s,t.byteLength);return {join_ref:null,ref:null,topic:o,event:a,payload:l}}},ec=class{constructor(t,e={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=e.timeout||Mg,this.transport=e.transport||ke.WebSocket||Ft,this.conn=void 0,this.primaryPassedHealthCheck=false,this.longPollFallbackMs=e.longPollFallbackMs,this.fallbackTimer=null,this.sessionStore=e.sessionStorage||ke&&ke.sessionStorage,this.establishedConnections=0,this.defaultEncoder=jn.encode.bind(jn),this.defaultDecoder=jn.decode.bind(jn),this.closeWasClean=true,this.disconnecting=false,this.binaryType=e.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=false,this.encode=void 0,this.decode=void 0,this.transport!==Ft?(this.encode=e.encode||this.defaultEncoder,this.decode=e.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let r=null;Ht&&Ht.addEventListener&&(Ht.addEventListener("pagehide",n=>{this.conn&&(this.disconnect(),r=this.connectClock);}),Ht.addEventListener("pageshow",n=>{r===this.connectClock&&(r=null,this.connect());}),Ht.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=true:(this.pageHidden=false,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()));})),this.heartbeatIntervalMs=e.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=e.autoSendHeartbeat??true,this.heartbeatCallback=e.heartbeatCallback??(()=>{}),this.rejoinAfterMs=n=>e.rejoinAfterMs?e.rejoinAfterMs(n):[1e3,2e3,5e3][n-1]||1e4,this.reconnectAfterMs=n=>e.reconnectAfterMs?e.reconnectAfterMs(n):[10,50,100,150,200,250,500,1e3,2e3][n-1]||5e3,this.logger=e.logger||null,!this.logger&&e.debug&&(this.logger=(n,i,s)=>{console.log(`${n}: ${i}`,s);}),this.longpollerTimeout=e.longpollerTimeout||2e4,this.params=Er(e.params||{}),this.endPoint=`${t}/${Ss.websocket}`,this.vsn=e.vsn||Dg,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new Zl(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{e.beforeReconnect&&await e.beforeReconnect(),this.connect();});},this.reconnectAfterMs),this.authToken=e.authToken;}getLongPollTransport(){return Ft}replaceTransport(t){this.connectClock++,this.closeWasClean=true,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=t;}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let t=Dn.appendParams(Dn.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return t.charAt(0)!=="/"?t:t.charAt(1)==="/"?`${this.protocol()}:${t}`:`${this.protocol()}://${location.host}${t}`}disconnect(t,e,r){this.connectClock++,this.disconnecting=true,this.closeWasClean=true,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=false,t&&t();},e,r);}connect(t){t&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Er(t)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==Ft?this.connectWithFallback(Ft,this.longPollFallbackMs):this.transportConnect());}log(t,e,r){this.logger&&this.logger(t,e,r);}hasLogger(){return this.logger!==null}onOpen(t){let e=this.makeRef();return this.stateChangeCallbacks.open.push([e,t]),e}onClose(t){let e=this.makeRef();return this.stateChangeCallbacks.close.push([e,t]),e}onError(t){let e=this.makeRef();return this.stateChangeCallbacks.error.push([e,t]),e}onMessage(t){let e=this.makeRef();return this.stateChangeCallbacks.message.push([e,t]),e}onHeartbeat(t){this.heartbeatCallback=t;}ping(t){if(!this.isConnected())return false;let e=this.makeRef(),r=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:e});let n=this.onMessage(i=>{i.ref===e&&(this.off([n]),t(Date.now()-r));});return true}transportName(t){return t===Ft?"LongPoll":t.name}transportConnect(){this.connectClock++,this.closeWasClean=false;let t;this.authToken&&(t=["phoenix",`${Cs}${btoa(this.authToken).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),t),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e);}getSession(t){return this.sessionStore&&this.sessionStore.getItem(t)}storeSession(t,e){this.sessionStore&&this.sessionStore.setItem(t,e);}connectWithFallback(t,e=2500){clearTimeout(this.fallbackTimer);let r=false,n=true,i,s,o=this.transportName(t),a=l=>{this.log("transport",`falling back to ${o}...`,l),this.off([i,s]),n=false,this.replaceTransport(t),this.transportConnect();};if(this.getSession(`phx:fallback:${o}`))return a("memorized");this.fallbackTimer=setTimeout(a,e),s=this.onError(l=>{this.log("transport","error",l),n&&!r&&(clearTimeout(this.fallbackTimer),a(l));}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(r=true,!n){let l=this.transportName(t);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${l}`,"true"),this.log("transport",`established ${l} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(a,e),this.ping(l=>{this.log("transport","connected to primary after",l),this.primaryPassedHealthCheck=true,clearTimeout(this.fallbackTimer);});}),this.transportConnect();}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer);}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=false,this.disconnecting=false,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open");}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout");}catch(t){this.log("error","error in heartbeat callback",t);}this.triggerChanError(),this.closeWasClean=false,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Lg,"heartbeat timeout");}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs));}teardown(t,e,r){if(!this.conn)return t&&t();let n=this.conn;this.waitForBufferDone(n,()=>{e?n.close(e,r||""):n.close(),this.waitForSocketClosed(n,()=>{this.conn===n&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),t&&t();});});}waitForBufferDone(t,e,r=1){if(r===5||!t.bufferedAmount){e();return}setTimeout(()=>{this.waitForBufferDone(t,e,r+1);},150*r);}waitForSocketClosed(t,e,r=1){if(r===5||t.readyState===be.closed){e();return}setTimeout(()=>{this.waitForSocketClosed(t,e,r+1);},150*r);}onConnClose(t){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",t),this.triggerChanError(),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",t);}onConnError(t){this.hasLogger()&&this.log("transport",t);let e=this.transport,r=this.establishedConnections;this.triggerStateCallbacks("error",t,e,r),(e===this.transport||r>0)&&this.triggerChanError();}triggerChanError(){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(Ie.error);});}connectionState(){switch(this.conn&&this.conn.readyState){case be.connecting:return "connecting";case be.open:return "open";case be.closing:return "closing";default:return "closed"}}isConnected(){return this.connectionState()==="open"}remove(t){this.off(t.stateChangeRefs),this.channels=this.channels.filter(e=>e!==t);}off(t){for(let e in this.stateChangeCallbacks)this.stateChangeCallbacks[e]=this.stateChangeCallbacks[e].filter(([r])=>t.indexOf(r)===-1);}channel(t,e={}){let r=new Wg(t,e,this);return this.channels.push(r),r}push(t){if(this.hasLogger()){let{topic:e,event:r,payload:n,ref:i,join_ref:s}=t;this.log("push",`${e} ${r} (${s}, ${i})`,n);}this.isConnected()?this.encode(t,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(t,e=>this.conn.send(e)));}makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected");}catch(t){this.log("error","error in heartbeat callback",t);}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent");}catch(t){this.log("error","error in heartbeat callback",t);}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs);}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[]);}onConnMessage(t){this.decode(t.data,e=>{let{topic:r,event:n,payload:i,ref:s,join_ref:o}=e;if(s&&s===this.pendingHeartbeatRef){let a=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(i.status==="ok"?"ok":"error",a);}catch(l){this.log("error","error in heartbeat callback",l);}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs));}this.hasLogger()&&this.log("receive",`${i.status||""} ${r} ${n} ${s&&"("+s+")"||""}`.trim(),i);for(let a=0;a<this.channels.length;a++){let l=this.channels[a];l.isMember(r,n,i,o)&&l.trigger(n,i,s,o);}this.triggerStateCallbacks("message",e);});}triggerStateCallbacks(t,...e){try{this.stateChangeCallbacks[t].forEach(([r,n])=>{try{n(...e);}catch(i){this.log("error",`error in ${t} callback`,i);}});}catch(r){this.log("error",`error triggering ${t} callbacks`,r);}}leaveOpenTopic(t){let e=this.channels.find(r=>r.topic===t&&(r.isJoined()||r.isJoining()));e&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${t}"`),e.leave());}};});function Mn(t){return t.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e))}function Fg(t){return JSON.parse(JSON.stringify(t))}function Hg(t){return t?.events&&{events:t.events}}function tc(t){return t?.metas?Mn(t):[]}var Rr,rc=R(()=>{Es();Rr=class t{constructor(e,r){let n=Hg(r);this.presence=new Ql(e.getChannel(),n),this.presence.onJoin((i,s,o)=>{let a=t.onJoinPayload(i,s,o);e.getChannel().trigger("presence",a);}),this.presence.onLeave((i,s,o)=>{let a=t.onLeavePayload(i,s,o);e.getChannel().trigger("presence",a);}),this.presence.onSync(()=>{e.getChannel().trigger("presence",{event:"sync"});});}get state(){return t.transformState(this.presence.state)}static transformState(e){return e=Fg(e),Object.getOwnPropertyNames(e).reduce((r,n)=>{let i=e[n];return r[n]=Mn(i),r},{})}static onJoinPayload(e,r,n){let i=tc(r),s=Mn(n);return {event:"join",key:e,currentPresences:i,newPresences:s}}static onLeavePayload(e,r,n){let i=tc(r),s=Mn(n);return {event:"leave",key:e,currentPresences:i,leftPresences:s}}};});var Rs,qt,xs=R(()=>{rc();(function(t){t.SYNC="sync",t.JOIN="join",t.LEAVE="leave";})(Rs||(Rs={}));qt=class{get state(){return this.presenceAdapter.state}constructor(e,r){this.channel=e,this.presenceAdapter=new Rr(this.channel.channelAdapter,r);}};});function qg(t){return {config:Object.assign({broadcast:{ack:false,self:false},presence:{key:"",enabled:false},private:false},t.config)}}var xr,nc=R(()=>{vr();xr=class{constructor(e,r,n){let i=qg(n);this.channel=e.getSocket().channel(r,i),this.socket=e;}get state(){return this.channel.state}set state(e){this.channel.state=e;}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,r){return this.channel.on(e,r)}off(e,r){this.channel.off(e,r);}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown();}onClose(e){this.channel.onClose(e);}onError(e){return this.channel.onError(e)}push(e,r,n){let i;try{i=this.channel.push(e,r,n);}catch{throw `tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`}if(this.channel.pushBuffer.length>Gl){let s=this.channel.pushBuffer.shift();s.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${s.event}`,s.payload());}return i}updateJoinPayload(e){let r=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},r),e);}canPush(){return this.socket.isConnected()&&this.state===ye.joined}isJoined(){return this.state===ye.joined}isJoining(){return this.state===ye.joining}isClosed(){return this.state===ye.closed}isLeaving(){return this.state===ye.leaving}updateFilterBindings(e){this.channel.filterBindings=e;}updatePayloadTransform(e){this.channel.onMessage=e;}getChannel(){return this.channel}};});var Ps,st,ve,zt,Ts=R(()=>{vr();xs();$n();$n();nc();(function(t){t.ALL="*",t.INSERT="INSERT",t.UPDATE="UPDATE",t.DELETE="DELETE";})(Ps||(Ps={}));(function(t){t.BROADCAST="broadcast",t.PRESENCE="presence",t.POSTGRES_CHANGES="postgres_changes",t.SYSTEM="system";})(st||(st={}));(function(t){t.SUBSCRIBED="SUBSCRIBED",t.TIMED_OUT="TIMED_OUT",t.CLOSED="CLOSED",t.CHANNEL_ERROR="CHANNEL_ERROR";})(ve||(ve={}));zt=class t{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e;}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,r={config:{}},n){var i,s;if(this.topic=e,this.params=r,this.socket=n,this.bindings={},this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:false,self:false},presence:{key:"",enabled:false},private:false},r.config),this.channelAdapter=new xr(this.socket.socketAdapter,e,this.params),this.presence=new qt(this),this._onClose(()=>{this.socket._remove(this);}),this._updateFilterTransform(),this.broadcastEndpointURL=On(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||false,!this.private&&(!((s=(i=this.params.config)===null||i===void 0?void 0:i.broadcast)===null||s===void 0)&&s.replay))throw `tried to use replay on public channel '${this.topic}'. It must be a private channel.`}subscribe(e,r=this.timeout){var n,i,s;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:o,presence:a,private:l}}=this.params,c=(i=(n=this.bindings.postgres_changes)===null||n===void 0?void 0:n.map(h=>h.filter))!==null&&i!==void 0?i:[],u=!!this.bindings[st.PRESENCE]&&this.bindings[st.PRESENCE].length>0||((s=this.params.config.presence)===null||s===void 0?void 0:s.enabled)===true,d={},p={broadcast:o,presence:Object.assign(Object.assign({},a),{enabled:u}),postgres_changes:c,private:l};this.socket.accessTokenValue&&(d.access_token=this.socket.accessTokenValue),this._onError(h=>{e?.(ve.CHANNEL_ERROR,h);}),this._onClose(()=>e?.(ve.CLOSED)),this.updateJoinPayload(Object.assign({config:p},d)),this._updateFilterMessage(),this.channelAdapter.subscribe(r).receive("ok",async({postgres_changes:h})=>{if(this.socket._isManualToken()||this.socket.setAuth(),h===void 0){e?.(ve.SUBSCRIBED);return}this._updatePostgresBindings(h,e);}).receive("error",h=>{this.state=ye.errored,e?.(ve.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(h).join(", ")||"error")));}).receive("timeout",()=>{e?.(ve.TIMED_OUT);});}return this}_updatePostgresBindings(e,r){var n;let i=this.bindings.postgres_changes,s=(n=i?.length)!==null&&n!==void 0?n:0,o=[];for(let a=0;a<s;a++){let l=i[a],{filter:{event:c,schema:u,table:d,filter:p}}=l,h=e&&e[a];if(h&&h.event===c&&t.isFilterValueEqual(h.schema,u)&&t.isFilterValueEqual(h.table,d)&&t.isFilterValueEqual(h.filter,p))o.push(Object.assign(Object.assign({},l),{id:h.id}));else {this.unsubscribe(),this.state=ye.errored,r?.(ve.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=o,this.state!=ye.errored&&r&&r(ve.SUBSCRIBED);}presenceState(){return this.presence.state}async track(e,r={}){return await this.send({type:"presence",event:"track",payload:e},r.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,r,n){let i=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),s=e===st.PRESENCE||e===st.POSTGRES_CHANGES;if(i&&s)throw this.socket.log("channel",`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,r,n)}async httpSend(e,r,n={}){var i;if(r==null)return Promise.reject("Payload is required for httpSend()");let s={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(s.Authorization=`Bearer ${this.socket.accessTokenValue}`);let o={method:"POST",headers:s,body:JSON.stringify({messages:[{topic:this.subTopic,event:e,payload:r,private:this.private}]})},a=await this._fetchWithTimeout(this.broadcastEndpointURL,o,(i=n.timeout)!==null&&i!==void 0?i:this.timeout);if(a.status===202)return {success:true};let l=a.statusText;try{let c=await a.json();l=c.error||c.message||l;}catch{}return Promise.reject(new Error(l))}async send(e,r={}){var n,i;if(!this.channelAdapter.canPush()&&e.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");let{event:s,payload:o}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let l={method:"POST",headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:s,payload:o,private:this.private}]})};try{let c=await this._fetchWithTimeout(this.broadcastEndpointURL,l,(n=r.timeout)!==null&&n!==void 0?n:this.timeout);return await((i=c.body)===null||i===void 0?void 0:i.cancel()),c.ok?"ok":"error"}catch(c){return c.name==="AbortError"?"timed out":"error"}}else return new Promise(s=>{var o,a,l;let c=this.channelAdapter.push(e.type,e,r.timeout||this.timeout);e.type==="broadcast"&&!(!((l=(a=(o=this.params)===null||o===void 0?void 0:o.config)===null||a===void 0?void 0:a.broadcast)===null||l===void 0)&&l.ack)&&s("ok"),c.receive("ok",()=>s("ok")),c.receive("error",()=>s("error")),c.receive("timeout",()=>s("timed out"));})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e);}async unsubscribe(e=this.timeout){return new Promise(r=>{this.channelAdapter.unsubscribe(e).receive("ok",()=>r("ok")).receive("timeout",()=>r("timed out")).receive("error",()=>r("error"));})}teardown(){this.channelAdapter.teardown();}async _fetchWithTimeout(e,r,n){let i=new AbortController,s=setTimeout(()=>i.abort(),n),o=await this.socket.fetch(e,Object.assign(Object.assign({},r),{signal:i.signal}));return clearTimeout(s),o}_on(e,r,n){let i=e.toLocaleLowerCase(),s=this.channelAdapter.on(e,n),o={type:i,filter:r,callback:n,ref:s};return this.bindings[i]?this.bindings[i].push(o):this.bindings[i]=[o],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e);}_onError(e){this.channelAdapter.onError(e);}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,r,n)=>{var i,s,o,a,l,c,u;let d=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(d,n))return false;let p=(i=this.bindings[d])===null||i===void 0?void 0:i.find(h=>h.ref===e.ref);if(!p)return true;if(["broadcast","presence","postgres_changes"].includes(d))if("id"in p){let h=p.id,f=(s=p.filter)===null||s===void 0?void 0:s.event;return h&&((o=r.ids)===null||o===void 0?void 0:o.includes(h))&&(f==="*"||f?.toLocaleLowerCase()===((a=r.data)===null||a===void 0?void 0:a.type.toLocaleLowerCase()))}else {let h=(c=(l=p?.filter)===null||l===void 0?void 0:l.event)===null||c===void 0?void 0:c.toLocaleLowerCase();return h==="*"||h===((u=r?.event)===null||u===void 0?void 0:u.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===d});}_notThisChannelEvent(e,r){let{close:n,error:i,leave:s,join:o}=In;return r&&[n,i,s,o].includes(e)&&r!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,r,n)=>{if(typeof r=="object"&&"ids"in r){let i=r.data,{schema:s,table:o,commit_timestamp:a,type:l,errors:c}=i;return Object.assign(Object.assign({},{schema:s,table:o,commit_timestamp:a,eventType:l,new:{},old:{},errors:c}),this._getPayloadRecords(i))}return r});}copyBindings(e){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(let r in e.bindings)for(let n of e.bindings[r])this._on(n.type,n.filter,n.callback);}static isFilterValueEqual(e,r){return (e??void 0)===(r??void 0)}_getPayloadRecords(e){let r={new:{},old:{}};return (e.type==="INSERT"||e.type==="UPDATE")&&(r.new=vs(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(r.old=vs(e.columns,e.old_record)),r}};});var Pr,ic=R(()=>{Es();vr();Pr=class{constructor(e,r){this.socket=new ec(e,r);}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e;}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect();}disconnect(e,r,n,i=1e4){return new Promise(s=>{setTimeout(()=>s("timeout"),i),this.socket.disconnect(()=>{e(),s("ok");},r,n);})}push(e){this.socket.push(e);}log(e,r,n){this.socket.log(e,r,n);}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e);}onClose(e){this.socket.onClose(e);}onError(e){this.socket.onError(e);}onMessage(e){this.socket.onMessage(e);}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==br.connecting}isDisconnecting(){return this.socket.connectionState()==br.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat();}getSocket(){return this.socket}};});var zg,Jg,Kg,Vg,Jt,sc=R(()=>{ys();vr();Yl();$n();Ts();ic();zg={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},Jg=[1e3,2e3,5e3,1e4],Kg=1e4,Vg=`
|
|
13
13
|
addEventListener("message", (e) => {
|
|
14
14
|
if (e.data.event === "start") {
|
|
15
15
|
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
|
|
16
16
|
}
|
|
17
|
-
});`,Jt=class{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var n;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new Sr,this._manuallySetToken=false,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=s=>s?(...o)=>s(...o):(...o)=>fetch(...o),!(!((n=r?.params)===null||n===void 0)&&n.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;let i=this._initializeOptions(r);this.socketAdapter=new Pr(e,i),this.httpEndpoint=
|
|
17
|
+
});`,Jt=class{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,r){var n;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={},this.ref=0,this.serializer=new Sr,this._manuallySetToken=false,this._authPromise=null,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._resolveFetch=s=>s?(...o)=>s(...o):(...o)=>fetch(...o),!(!((n=r?.params)===null||n===void 0)&&n.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=r.params.apikey;let i=this._initializeOptions(r);this.socketAdapter=new Pr(e,i),this.httpEndpoint=On(e),this.fetch=this._resolveFetch(r?.fetch);}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect();}catch(e){let r=e.message;throw r.includes("Node.js")?new Error(`${r}
|
|
18
18
|
|
|
19
19
|
To use Realtime in Node.js, you need to provide a WebSocket implementation:
|
|
20
20
|
|
|
@@ -27,8 +27,8 @@ Option 2: Install and provide the "ws" package:
|
|
|
27
27
|
const client = new RealtimeClient(url, {
|
|
28
28
|
...options,
|
|
29
29
|
transport: ws
|
|
30
|
-
})`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition();}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker();},e,r)}getChannels(){return this.channels}async removeChannel(e){let r=await e.unsubscribe();return r==="ok"&&e.teardown(),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){let e=this.channels.map(async n=>{let i=await n.unsubscribe();return n.teardown(),i}),r=await Promise.all(e);return this.disconnect(),r}log(e,r,n){this.socketAdapter.log(e,r,n);}connectionState(){return this.socketAdapter.connectionState()||br.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){let n=`realtime:${e}`,i=this.getChannels().find(s=>s.topic===n);if(i)return i;{let s=new zt(`realtime:${e}`,r,this);return this.channels.push(s),s}}push(e){this.socketAdapter.push(e);}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise;}finally{this._authPromise=null;}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat();}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e);}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic);}async _performAuth(e=null){let r,n=false;if(e)r=e,n=true;else if(this.accessToken)try{r=await this.accessToken();}catch(i){this.log("error","Error fetching access token from callback",i),r=this.accessTokenValue;}else r=this.accessTokenValue;n?this._manuallySetToken=true:this.accessToken&&(this._manuallySetToken=false),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(i=>{let s={access_token:r,version:zl};r&&i.updateJoinPayload(s),i.joinedOnce&&i.channelAdapter.isJoined()&&i.channelAdapter.push(An.access_token,{access_token:r});}));}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise;}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r);});}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r);}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat();}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker();}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null);});}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen();}_wrapHeartbeatCallback(e){return (r,n)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,n);}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect();},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat();},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs});}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0);}_workerObjectUrl(e){let r;if(e)r=e;else {let n=new Blob([Vg],{type:"application/javascript"});r=URL.createObjectURL(n);}return r}_initializeOptions(e){var r,n,i,s,o,a,l,c,u;this.worker=(r=e?.worker)!==null&&r!==void 0?r:false,this.accessToken=(n=e?.accessToken)!==null&&n!==void 0?n:null;let d={};d.timeout=(i=e?.timeout)!==null&&i!==void 0?i:Vl,d.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:zg.HEARTBEAT_INTERVAL,d.transport=(o=e?.transport)!==null&&o!==void 0?o:ws.getWebSocketConstructor(),d.params=e?.params,d.logger=e?.logger,d.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),d.reconnectAfterMs=(a=e?.reconnectAfterMs)!==null&&a!==void 0?a:(m=>Jg[m-1]||Kg);let p,h,f=(l=e?.vsn)!==null&&l!==void 0?l:Kl;switch(f){case Jl:p=(m,_)=>_(JSON.stringify(m)),h=(m,_)=>_(JSON.parse(m));break;case ks:p=this.serializer.encode.bind(this.serializer),h=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${d.vsn}`)}if(d.vsn=f,d.encode=(c=e?.encode)!==null&&c!==void 0?c:p,d.decode=(u=e?.decode)!==null&&u!==void 0?u:h,d.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,d.params=Object.assign(Object.assign({},d.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,d.autoSendHeartbeat=!this.worker;}return d}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect();}};});var As=R(()=>{sc();Ts();xs();ys();});function Gg(t,e,r){let n=new URL(e,t);if(r)for(let[i,s]of Object.entries(r))s!==void 0&&n.searchParams.set(i,s);return n.toString()}async function Yg(t){return !t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function Xg(t){let e=t.fetchImpl??globalThis.fetch;return {async request({method:r,path:n,query:i,body:s,headers:o}){let a=Gg(t.baseUrl,n,i),l=await Yg(t.auth),c=await e(a,{method:r,headers:{...s?{"Content-Type":"application/json"}:{},...l,...o},body:s?JSON.stringify(s):void 0}),u=await c.text(),d=(c.headers.get("content-type")||"").includes("application/json"),p=d&&u?JSON.parse(u):u;if(!c.ok){let h=d?p:void 0,f=h?.error;throw new Tr(f?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:f?.type,icebergCode:f?.code,details:h})}return {status:c.status,headers:c.headers,data:p}}}}function Mn(t){return t.join("")}function Kt(t){return t.join("")}var Tr,Zg,Qg,oc,ac=R(()=>{Tr=class extends Error{constructor(t,e){super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&e.icebergType?.includes("CommitState")===true;}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};Zg=class{constructor(t,e=""){this.client=t,this.prefix=e;}async listNamespaces(t){let e=t?{parent:Mn(t.namespace)}:void 0;return (await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(n=>({namespace:n}))}async createNamespace(t,e){let r={namespace:t.namespace,properties:e?.properties};return (await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Mn(t.namespace)}`});}async loadNamespaceMetadata(t){return {properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Mn(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Mn(t.namespace)}`}),!0}catch(e){if(e instanceof Tr&&e.status===404)return false;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof Tr&&r.status===409)return;throw r}}};Qg=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r;}async listTables(t){return (await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Kt(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Kt(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Kt(t.namespace)}/tables/${t.name}`,body:e});return {"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Kt(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String(e?.purge??false)}});}async loadTable(t){let e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Kt(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){let e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Kt(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof Tr&&r.status===404)return false;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof Tr&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},oc=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);let r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Xg({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new Zg(this.client,e),this.tableOps=new Qg(this.client,e,this.accessDelegation);}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t);}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e);}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};});function Ir(t){"@babel/helpers - typeof";return Ir=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},Ir(t)}function em(t,e){if(Ir(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(Ir(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(t)}function tm(t){var e=em(t,"string");return Ir(e)=="symbol"?e:e+""}function rm(t,e,r){return (e=tm(e))in t?Object.defineProperty(t,e,{value:r,enumerable:true,configurable:true,writable:true}):t[e]=r,t}function lc(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n);}return r}function E(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?lc(Object(r),true).forEach(function(n){rm(t,n,r[n]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):lc(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n));});}return t}function Wn(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}function lm(t,e,r){let n=E({},t);for(let i of Object.keys(n))i.toLowerCase()===e.toLowerCase()&&delete n[i];return n[e]=r,n}async function Ar(t,e,r,n,i,s,o){return new Promise((a,l)=>{t(r,am(e,n,i,s)).then(c=>{if(!c.ok)throw c;if(n?.noResolveJson)return c;if(o==="vectors"){let u=c.headers.get("content-type");if(c.headers.get("content-length")==="0"||c.status===204)return {};if(!u||!u.includes("application/json"))return {}}return c.json()}).then(c=>a(c)).catch(c=>om(c,l,n,o));})}function pc(t="storage"){return {get:async(e,r,n,i)=>Ar(e,"GET",r,n,i,void 0,t),post:async(e,r,n,i,s)=>Ar(e,"POST",r,i,s,n,t),put:async(e,r,n,i,s)=>Ar(e,"PUT",r,i,s,n,t),head:async(e,r,n,i)=>Ar(e,"HEAD",r,E(E({},n),{},{noResolveJson:true}),i,void 0,t),remove:async(e,r,n,i,s)=>Ar(e,"DELETE",r,i,s,n,t)}}var Un,Ln,dc,nm,im,Is,sm,cc,om,am,cm,Or,fe,Os,um,$s,re,Vt,dm,hc,pm,hm,uc,fm,gm,$r,mm,_m,wm,ym,km,bm,vm,Sm,fc,gc=R(()=>{ac();Un=class extends Error{constructor(t,e="storage",r,n){super(t),this.__isStorageError=true,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=n;}toJSON(){return {name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};Ln=class extends Un{constructor(t,e,r,n="storage"){super(t,n,e,r),this.name=n==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r;}toJSON(){return E({},super.toJSON())}},dc=class extends Un{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e;}},nm=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),im=t=>{if(typeof t!="object"||t===null)return false;let e=Object.getPrototypeOf(t);return (e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},Is=t=>{if(Array.isArray(t))return t.map(r=>Is(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,n])=>{let i=r.replace(/([-_][a-z])/gi,s=>s.toUpperCase().replace(/[-_]/g,""));e[i]=Is(n);}),e},sm=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?false:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t),cc=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},om=async(t,e,r,n)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){let i=t,s=parseInt(i.status,10);Number.isFinite(s)||(s=500),i.json().then(o=>{let a=o?.statusCode||o?.code||s+"";e(new Ln(cc(o),s,a,n));}).catch(()=>{let o=s+"";e(new Ln(i.statusText||`HTTP ${s} error`,s,o,n));});}else e(new dc(cc(t),t,n));},am=(t,e,r,n)=>{let i={method:t,headers:e?.headers||{}};if(t==="GET"||t==="HEAD"||!n)return E(E({},i),r);if(im(n)){var s;let o=e?.headers||{},a;for(let[l,c]of Object.entries(o))l.toLowerCase()==="content-type"&&(a=c);i.headers=lm(o,"Content-Type",(s=a)!==null&&s!==void 0?s:"application/json"),i.body=JSON.stringify(n);}else i.body=n;return e?.duplex&&(i.duplex=e.duplex),E(E({},i),r)};cm=pc("storage"),{get:Or,post:fe,put:Os,head:um,remove:$s}=cm,re=pc("vectors"),Vt=class{constructor(t,e={},r,n="storage"){this.shouldThrowOnError=false,this.url=t,this.headers=Object.fromEntries(Object.entries(e).map(([i,s])=>[i.toLowerCase(),s])),this.fetch=nm(r),this.namespace=n;}throwOnError(){return this.shouldThrowOnError=true,this}setHeader(t,e){return this.headers=E(E({},this.headers),{},{[t.toLowerCase()]:e}),this}async handleOperation(t){var e=this;try{return {data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(Wn(r))return {data:null,error:r};throw r}}},dm=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e;}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return {data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Wn(e))return {data:null,error:e};throw e}}};hc=Symbol.toStringTag;pm=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[hc]="BlobDownloadBuilder",this.promise=null;}asStream(){return new dm(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return {data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Wn(e))return {data:null,error:e};throw e}}},hm={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},uc={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:false},fm=class extends Vt{constructor(t,e={},r,n){super(t,e,n,"storage"),this.bucketId=r;}async uploadOrUpdate(t,e,r,n){var i=this;return i.handleOperation(async()=>{let s,o=E(E({},uc),n),a=E(E({},i.headers),t==="POST"&&{"x-upsert":String(o.upsert)}),l=o.metadata;typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",o.cacheControl),l&&s.append("metadata",i.encodeMetadata(l)),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.has("cacheControl")||s.append("cacheControl",o.cacheControl),l&&!s.has("metadata")&&s.append("metadata",i.encodeMetadata(l))):(s=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=i.toBase64(i.encodeMetadata(l))),(typeof ReadableStream<"u"&&s instanceof ReadableStream||s&&typeof s=="object"&&"pipe"in s&&typeof s.pipe=="function")&&!o.duplex&&(o.duplex="half")),n?.headers&&(a=E(E({},a),n.headers));let c=i._removeEmptyFolders(e),u=i._getFinalPath(c),d=await(t=="PUT"?Os:fe)(i.fetch,`${i.url}/object/${u}`,s,E({headers:a},o?.duplex?{duplex:o.duplex}:{}));return {path:c,id:d.Id,fullPath:d.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,n){var i=this;let s=i._removeEmptyFolders(t),o=i._getFinalPath(s),a=new URL(i.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",e),i.handleOperation(async()=>{let l,c=E(E({},uc),n),u=E(E({},i.headers),{"x-upsert":String(c.upsert)});return typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",c.cacheControl)):(l=r,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType),{path:s,fullPath:(await Os(i.fetch,a.toString(),l,{headers:u})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let n=r._getFinalPath(t),i=E({},r.headers);e?.upsert&&(i["x-upsert"]="true");let s=await fe(r.fetch,`${r.url}/object/upload/sign/${n}`,{},{headers:i}),o=new URL(r.url+s.url),a=o.searchParams.get("token");if(!a)throw new Un("No token returned by API");return {signedUrl:o.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var n=this;return n.handleOperation(async()=>await fe(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers}))}async copy(t,e,r){var n=this;return n.handleOperation(async()=>({path:(await fe(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers})).Key}))}async createSignedUrl(t,e,r){var n=this;return n.handleOperation(async()=>{let i=n._getFinalPath(t),s=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0,o=await fe(n.fetch,`${n.url}/object/sign/${i}`,E({expiresIn:e},s?{transform:r.transform}:{}),{headers:n.headers}),a=new URLSearchParams;r?.download&&a.set("download",r.download===true?"":r.download),r?.cacheNonce!=null&&a.set("cacheNonce",String(r.cacheNonce));let l=a.toString();return {signedUrl:encodeURI(`${n.url}${o.signedURL}${l?`&${l}`:""}`)}})}async createSignedUrls(t,e,r){var n=this;return n.handleOperation(async()=>{let i=await fe(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:e,paths:t},{headers:n.headers}),s=new URLSearchParams;r?.download&&s.set("download",r.download===true?"":r.download),r?.cacheNonce!=null&&s.set("cacheNonce",String(r.cacheNonce));let o=s.toString();return i.map(a=>E(E({},a),{},{signedUrl:a.signedURL?encodeURI(`${n.url}${a.signedURL}${o?`&${o}`:""}`):null}))})}download(t,e,r){let n=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image/authenticated":"object",i=new URLSearchParams;e?.transform&&this.applyTransformOptsToQuery(i,e.transform),e?.cacheNonce!=null&&i.set("cacheNonce",String(e.cacheNonce));let s=i.toString(),o=this._getFinalPath(t),a=()=>Or(this.fetch,`${this.url}/${n}/${o}${s?`?${s}`:""}`,{headers:this.headers,noResolveJson:true},r);return new pm(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>Is(await Or(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await um(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(i){if(e.shouldThrowOnError)throw i;if(Wn(i)){var n;let s=i instanceof Ln?i.status:i instanceof dc?(n=i.originalError)===null||n===void 0?void 0:n.status:void 0;if(s!==void 0&&[400,404].includes(s))return {data:false,error:i}}throw i}}getPublicUrl(t,e){let r=this._getFinalPath(t),n=new URLSearchParams;e?.download&&n.set("download",e.download===true?"":e.download),e?.transform&&this.applyTransformOptsToQuery(n,e.transform),e?.cacheNonce!=null&&n.set("cacheNonce",String(e.cacheNonce));let i=n.toString(),s=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image":"object";return {data:{publicUrl:encodeURI(`${this.url}/${s}/public/${r}`)+(i?`?${i}`:"")}}}async remove(t){var e=this;return e.handleOperation(async()=>await $s(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var n=this;return n.handleOperation(async()=>{let i=E(E(E({},hm),e),{},{prefix:t||""});return await fe(n.fetch,`${n.url}/object/list/${n.bucketId}`,i,{headers:n.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let n=E({},t);return await fe(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,n,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return `${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(t,e){return e.width&&t.set("width",e.width.toString()),e.height&&t.set("height",e.height.toString()),e.resize&&t.set("resize",e.resize),e.format&&t.set("format",e.format),e.quality&&t.set("quality",e.quality.toString()),t}},gm="2.103.2",$r={"X-Client-Info":`storage-js/${gm}`},mm=class extends Vt{constructor(t,e={},r,n){let i=new URL(t);n?.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase."));let s=i.href.replace(/\/$/,""),o=E(E({},$r),e);super(s,o,r,"storage");}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await Or(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Or(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:false}){var r=this;return r.handleOperation(async()=>await fe(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await Os(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await fe(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await $s(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){let e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},_m=class extends Vt{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=E(E({},$r),e);super(n,i,r,"storage");}async createBucket(t){var e=this;return e.handleOperation(async()=>await fe(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);let n=r.toString(),i=n?`${e.url}/bucket?${n}`:`${e.url}/bucket`;return await Or(e.fetch,i,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await $s(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!sm(t))throw new Un("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let r=new oc({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(r,{get(i,s){let o=i[s];return typeof o!="function"?o:async(...a)=>{try{return {data:await o.apply(i,a),error:null}}catch(l){if(n)throw l;return {data:null,error:l}}}}})}},wm=class extends Vt{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=E(E({},$r),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors");}async createIndex(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await re.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await re.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},ym=class extends Vt{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=E(E({},$r),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors");}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},km=class extends Vt{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=E(E({},$r),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors");}async createBucket(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},bm=class extends km{constructor(t,e={}){super(t,e.headers||{},e.fetch);}from(t){return new vm(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},vm=class extends wm{constructor(t,e,r,n){super(t,e,n),this.vectorBucketName=r;}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new Sm(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},Sm=class extends ym{constructor(t,e,r,n,i){super(t,e,i),this.vectorBucketName=r,this.indexName=n;}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},fc=class extends mm{constructor(t,e={},r,n){super(t,e,r,n);}from(t){return new fm(this.url,this.headers,t,this.fetch)}get vectors(){return new bm(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new _m(this.url+"/iceberg",this.headers,this.fetch)}};});var Bn,Ns=R(()=>{Bn="2.103.2";});var ot,Fn,Hn,mc,_c,wc,Nr,js,yc,kc,qn=R(()=>{Ns();ot=30*1e3,Fn=3,Hn=Fn*ot,mc="http://localhost:9999",_c="supabase.auth.token",wc={"X-Client-Info":`gotrue-js/${Bn}`},Nr="X-Supabase-Api-Version",js={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},yc=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,kc=600*1e3;});function v(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}function bc(t){return v(t)&&t.name==="AuthApiError"}function Mr(t){return v(t)&&t.name==="AuthSessionMissingError"}function vc(t){return v(t)&&t.name==="AuthImplicitGrantRedirectError"}function Kn(t){return v(t)&&t.name==="AuthRetryableFetchError"}var qe,zn,ue,ge,J,Oe,at,lt,jr,Jn,Gt,Dr,ct,ut=R(()=>{qe=class extends Error{constructor(e,r,n){super(e),this.__isAuthError=true,this.name="AuthError",this.status=r,this.code=n;}toJSON(){return {name:this.name,message:this.message,status:this.status,code:this.code}}};zn=class extends qe{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n;}};ue=class extends qe{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r;}},ge=class extends qe{constructor(e,r,n,i){super(e,n,i),this.name=r,this.status=n;}},J=class extends ge{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0);}};Oe=class extends ge{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0);}},at=class extends ge{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0);}},lt=class extends ge{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r;}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}};jr=class extends ge{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r;}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}},Jn=class extends ge{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found");}},Gt=class extends ge{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0);}};Dr=class extends ge{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n;}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}},ct=class extends ge{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt");}};});function Cc(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(Vn[n]),e.queuedBits-=6;}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(Vn[n]),e.queuedBits-=6;}}function Ec(t,e,r){let n=Cm[t];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else {if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function Ds(t){let e=[],r=o=>{e.push(String.fromCodePoint(o));},n={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},s=o=>{xm(o,n,r);};for(let o=0;o<t.length;o+=1)Ec(t.charCodeAt(o),i,s);return e.join("")}function Em(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function Rm(t,e){for(let r=0;r<t.length;r+=1){let n=t.charCodeAt(r);if(n>55295&&n<=56319){let i=(n-55296)*1024&65535;n=(t.charCodeAt(r+1)-56320&65535|i)+65536,r+=1;}Em(n,e);}}function xm(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let n=1;n<6;n+=1)if((t>>7-n&1)===0){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1;}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint);}}function ze(t){let e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i);};for(let i=0;i<t.length;i+=1)Ec(t.charCodeAt(i),r,n);return new Uint8Array(e)}function Rc(t){let e=[];return Rm(t,r=>e.push(r)),new Uint8Array(e)}function $e(t){let e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i);};return t.forEach(i=>Cc(i,r,n)),Cc(null,r,n),e.join("")}var Vn,Sc,Cm,Gn=R(()=>{Vn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Sc=`
|
|
31
|
-
\r=`.split(""),Cm=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<Sc.length;e+=1)t[Sc[e].charCodeAt(0)]=-2;for(let e=0;e<Vn.length;e+=1)t[Vn[e].charCodeAt(0)]=e;return t})();});function xc(t){return Math.round(Date.now()/1e3)+t}function Pc(){return Symbol("auth-callback")}function Tc(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((i,s)=>{e[s]=i;});}catch{}return r.searchParams.forEach((n,i)=>{e[i]=n;}),e}function Ur(t){let e=t.split(".");if(e.length!==3)throw new ct("Invalid JWT structure");for(let n=0;n<e.length;n++)if(!yc.test(e[n]))throw new ct("JWT not in base64url format");return {header:JSON.parse(Ds(e[0])),payload:JSON.parse(Ds(e[1])),signature:ze(e[2]),raw:{header:e[0],payload:e[1]}}}async function Ic(t){return await new Promise(e=>{setTimeout(()=>e(null),t);})}function Oc(t,e){return new Promise((n,i)=>{(async()=>{for(let s=0;s<1/0;s++)try{let o=await t(s);if(!e(s,null,o)){n(o);return}}catch(o){if(!e(s,o)){i(o);return}}})();})}function Pm(t){return ("0"+t.toString(16)).substr(-2)}function Tm(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length,i="";for(let s=0;s<56;s++)i+=r.charAt(Math.floor(Math.random()*n));return i}return crypto.getRandomValues(e),Array.from(e,Pm).join("")}async function Am(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r),i=new Uint8Array(n);return Array.from(i).map(s=>String.fromCharCode(s)).join("")}async function Im(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;let r=await Am(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ht(t,e,r=false){let n=Tm(),i=n;r&&(i+="/PASSWORD_RECOVERY"),await pt(t,`${e}-code-verifier`,i);let s=await Im(n);return [s,n===s?"plain":"s256"]}function $c(t){let e=t.headers.get(Nr);if(!e||!e.match(Om))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Nc(t){if(!t)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function jc(t){switch(t){case "RS256":return {name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case "ES256":return {name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}function ft(t){if(!$m.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Zn(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return true;if(typeof r=="symbol"){let n=r.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Dc(t,e){return new Proxy(t,{get:(r,n,i)=>{if(n==="__isInsecureUserWarningProxy")return true;if(typeof n=="symbol"){let s=n.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)"||s==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,n,i)}return !e.value&&typeof n=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=true),Reflect.get(r,n,i)}})}function Ms(t){return JSON.parse(JSON.stringify(t))}var q,dt,Yn,Xn,Ac,pt,Je,z,Lr,Om,$m,Yt=R(()=>{qn();ut();Gn();q=()=>typeof window<"u"&&typeof document<"u",dt={tested:false,writable:false},Yn=()=>{if(!q())return false;try{if(typeof globalThis.localStorage!="object")return !1}catch{return false}if(dt.tested)return dt.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),dt.tested=!0,dt.writable=!0;}catch{dt.tested=true,dt.writable=false;}return dt.writable};Xn=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Ac=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",pt=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r));},Je=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},z=async(t,e)=>{await t.removeItem(e);},Lr=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r;});}};Lr.promiseConstructor=Promise;Om=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;$m=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;});async function Mc(t){var e;if(!Ac(t))throw new Gt(gt(t),0);if(Nm.includes(t.status))throw new Gt(gt(t),t.status);let r;try{r=await t.json();}catch(s){throw new ue(gt(s),s)}let n,i=$c(t);if(i&&i.getTime()>=js["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new Dr(gt(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new J}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((s,o)=>s&&typeof o=="string",true))throw new Dr(gt(r),t.status,r.weak_password.reasons);throw new zn(gt(r),t.status||500,n)}async function S(t,e,r,n){var i;let s=Object.assign({},n?.headers);s[Nr]||(s[Nr]=js["2024-01-01"].name),n?.jwt&&(s.Authorization=`Bearer ${n.jwt}`);let o=(i=n?.query)!==null&&i!==void 0?i:{};n?.redirectTo&&(o.redirect_to=n.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Dm(t,e,r+a,{headers:s,noResolveJson:n?.noResolveJson},{},n?.body);return n?.xform?n?.xform(l):{data:Object.assign({},l),error:null}}async function Dm(t,e,r,n,i,s){let o=jm(e,n,i,s),a;try{a=await t(r,Object.assign({},o));}catch(l){throw console.error(l),new Gt(gt(l),0)}if(a.ok||await Mc(a),n?.noResolveJson)return a;try{return await a.json()}catch(l){await Mc(l);}}function de(t){var e;let r=null;Mm(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=xc(t.expires_in)));let n=(e=t.user)!==null&&e!==void 0?e:t;return {data:{session:r,user:n},error:null}}function Ls(t){let e=de(t);return !e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",true)&&(e.data.weak_password=t.weak_password),e}function ve(t){var e;return {data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Lc(t){return {data:t,error:null}}function Uc(t){let{action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:s}=t,o=it(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:s},l=Object.assign({},o);return {data:{properties:a,user:l},error:null}}function Us(t){return t}function Mm(t){return t.access_token&&t.refresh_token&&t.expires_in}var gt,Nm,jm,Ws=R(()=>{mr();qn();Yt();ut();gt=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),Nm=[502,503,504,520,521,522,523,524,530];jm=(t,e,r,n)=>{let i={method:t,headers:e?.headers||{}};return t==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(n),Object.assign(Object.assign({},i),r))};});var Qn,Bs=R(()=>{Qn=["global","local","others"];});var mt,ei=R(()=>{mr();Ws();Yt();Bs();ut();mt=class{constructor({url:e="",headers:r={},fetch:n}){this.url=e,this.headers=r,this.fetch=Xn(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)};}async signOut(e,r=Qn[0]){if(Qn.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Qn.join(", ")}`);try{return await S(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(v(n))return {data:null,error:n};throw n}}async inviteUserByEmail(e,r={}){try{return await S(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:ve})}catch(n){if(v(n))return {data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:r}=e,n=it(e,["options"]),i=Object.assign(Object.assign({},n),r);return "newEmail"in n&&(i.new_email=n?.newEmail,delete i.newEmail),await S(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Uc,redirectTo:r?.redirectTo})}catch(r){if(v(r))return {data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await S(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:ve})}catch(r){if(v(r))return {data:{user:null},error:r};throw r}}async listUsers(e){var r,n,i,s,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},u=await S(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(s=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:Us});if(u.error)throw u.error;let d=await u.json(),p=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,h=(l=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return h.length>0&&(h.forEach(f=>{let m=parseInt(f.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(f.split(";")[1].split("=")[1]);c[`${_}Page`]=m;}),c.total=parseInt(p)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(v(c))return {data:{users:[]},error:c};throw c}}async getUserById(e){ft(e);try{return await S(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:ve})}catch(r){if(v(r))return {data:{user:null},error:r};throw r}}async updateUserById(e,r){ft(e);try{return await S(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:ve})}catch(n){if(v(n))return {data:{user:null},error:n};throw n}}async deleteUser(e,r=false){ft(e);try{return await S(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:ve})}catch(n){if(v(n))return {data:{user:null},error:n};throw n}}async _listFactors(e){ft(e.userId);try{let{data:r,error:n}=await S(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return {data:r,error:n}}catch(r){if(v(r))return {data:null,error:r};throw r}}async _deleteFactor(e){ft(e.userId),ft(e.id);try{return {data:await S(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(v(r))return {data:null,error:r};throw r}}async _listOAuthClients(e){var r,n,i,s,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},u=await S(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(s=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:Us});if(u.error)throw u.error;let d=await u.json(),p=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,h=(l=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return h.length>0&&(h.forEach(f=>{let m=parseInt(f.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(f.split(";")[1].split("=")[1]);c[`${_}Page`]=m;}),c.total=parseInt(p)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(v(c))return {data:{clients:[]},error:c};throw c}}async _createOAuthClient(e){try{return await S(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _getOAuthClient(e){try{return await S(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await S(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(v(n))return {data:null,error:n};throw n}}async _deleteOAuthClient(e){try{return await S(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(v(r))return {data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await S(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _listCustomProviders(e){try{let r={};return e?.type&&(r.type=e.type),await S(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:n=>{var i;return {data:{providers:(i=n?.providers)!==null&&i!==void 0?i:[]},error:null}}})}catch(r){if(v(r))return {data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await S(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _getCustomProvider(e){try{return await S(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await S(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(v(n))return {data:null,error:n};throw n}}async _deleteCustomProvider(e){try{return await S(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(v(r))return {data:null,error:r};throw r}}};});function Fs(t={}){return {getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r;},removeItem:e=>{delete t[e];}}}var Wc=R(()=>{});async function Hs(t,e,r){me.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);let n=new globalThis.AbortController,i;e>0&&(i=setTimeout(()=>{n.abort(),me.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t);},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async s=>{if(s){clearTimeout(i),me.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await r()}finally{me.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name);}}else {if(e===0)throw me.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Br(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(me.debug)try{let o=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(o,null," "));}catch(o){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",o);}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),clearTimeout(i),await r()}})}catch(s){if(e>0&&clearTimeout(i),s?.name==="AbortError"&&e>0){if(n.signal.aborted)return me.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,{mode:"exclusive",steal:true},async o=>{if(o){me.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,o.name);try{return await r()}finally{me.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,o.name);}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw me.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new Br(`Lock "${t}" was released because another request stole it`)}throw s}}var me,Wr,Br,qs=R(()=>{Yt();me={debug:!!(globalThis&&Yn()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Wr=class extends Error{constructor(e){super(e),this.isAcquireTimeout=true;}},Br=class extends Wr{};});function Bc(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__;}catch{typeof self<"u"&&(self.globalThis=self);}}var Fc=R(()=>{});function zs(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Hc(t){return parseInt(t,16)}function qc(t){let e=new TextEncoder().encode(t);return "0x"+Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}function zc(t){var e;let{chainId:r,domain:n,expirationTime:i,issuedAt:s=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:u,uri:d,version:p}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(p!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${p}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
|
|
30
|
+
})`):new Error(`WebSocket not available: ${r}`)}this._handleNodeJsRaceCondition();}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,r){return this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker();},e,r)}getChannels(){return this.channels}async removeChannel(e){let r=await e.unsubscribe();return r==="ok"&&e.teardown(),this.channels.length===0&&this.disconnect(),r}async removeAllChannels(){let e=this.channels.map(async n=>{let i=await n.unsubscribe();return n.teardown(),i}),r=await Promise.all(e);return this.disconnect(),r}log(e,r,n){this.socketAdapter.log(e,r,n);}connectionState(){return this.socketAdapter.connectionState()||br.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,r={config:{}}){let n=`realtime:${e}`,i=this.getChannels().find(s=>s.topic===n);if(i)return i;{let s=new zt(`realtime:${e}`,r,this);return this.channels.push(s),s}}push(e){this.socketAdapter.push(e);}async setAuth(e=null){this._authPromise=this._performAuth(e);try{await this._authPromise;}finally{this._authPromise=null;}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat();}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e);}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(r=>r.topic!==e.topic);}async _performAuth(e=null){let r,n=false;if(e)r=e,n=true;else if(this.accessToken)try{r=await this.accessToken();}catch(i){this.log("error","Error fetching access token from callback",i),r=this.accessTokenValue;}else r=this.accessTokenValue;n?this._manuallySetToken=true:this.accessToken&&(this._manuallySetToken=false),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(i=>{let s={access_token:r,version:zl};r&&i.updateJoinPayload(s),i.joinedOnce&&i.channelAdapter.isJoined()&&i.channelAdapter.push(In.access_token,{access_token:r});}));}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise;}_setAuthSafely(e="general"){this._isManualToken()||this.setAuth().catch(r=>{this.log("error",`Error setting auth in ${e}`,r);});}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(r=>{this.log("error","error waiting for auth on connect",r);}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat();}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker();}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null);});}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen();}_wrapHeartbeatCallback(e){return (r,n)=>{r=="sent"&&this._setAuthSafely(),e&&e(r,n);}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=r=>{this.log("worker","worker error",r.message),this._terminateWorker(),this.disconnect();},this.workerRef.onmessage=r=>{r.data.event==="keepAlive"&&this.sendHeartbeat();},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs});}_terminateWorker(){this.workerRef&&(this.log("worker","terminating worker"),this.workerRef.terminate(),this.workerRef=void 0);}_workerObjectUrl(e){let r;if(e)r=e;else {let n=new Blob([Vg],{type:"application/javascript"});r=URL.createObjectURL(n);}return r}_initializeOptions(e){var r,n,i,s,o,a,l,c,u;this.worker=(r=e?.worker)!==null&&r!==void 0?r:false,this.accessToken=(n=e?.accessToken)!==null&&n!==void 0?n:null;let d={};d.timeout=(i=e?.timeout)!==null&&i!==void 0?i:Vl,d.heartbeatIntervalMs=(s=e?.heartbeatIntervalMs)!==null&&s!==void 0?s:zg.HEARTBEAT_INTERVAL,d.transport=(o=e?.transport)!==null&&o!==void 0?o:ws.getWebSocketConstructor(),d.params=e?.params,d.logger=e?.logger,d.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),d.reconnectAfterMs=(a=e?.reconnectAfterMs)!==null&&a!==void 0?a:(m=>Jg[m-1]||Kg);let p,h,f=(l=e?.vsn)!==null&&l!==void 0?l:Kl;switch(f){case Jl:p=(m,_)=>_(JSON.stringify(m)),h=(m,_)=>_(JSON.parse(m));break;case ks:p=this.serializer.encode.bind(this.serializer),h=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${d.vsn}`)}if(d.vsn=f,d.encode=(c=e?.encode)!==null&&c!==void 0?c:p,d.decode=(u=e?.decode)!==null&&u!==void 0?u:h,d.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,d.params=Object.assign(Object.assign({},d.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=e?.workerUrl,d.autoSendHeartbeat=!this.worker;}return d}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect();}};});var As=R(()=>{sc();Ts();xs();ys();});function Gg(t,e,r){let n=new URL(e,t);if(r)for(let[i,s]of Object.entries(r))s!==void 0&&n.searchParams.set(i,s);return n.toString()}async function Yg(t){return !t||t.type==="none"?{}:t.type==="bearer"?{Authorization:`Bearer ${t.token}`}:t.type==="header"?{[t.name]:t.value}:t.type==="custom"?await t.getHeaders():{}}function Xg(t){let e=t.fetchImpl??globalThis.fetch;return {async request({method:r,path:n,query:i,body:s,headers:o}){let a=Gg(t.baseUrl,n,i),l=await Yg(t.auth),c=await e(a,{method:r,headers:{...s?{"Content-Type":"application/json"}:{},...l,...o},body:s?JSON.stringify(s):void 0}),u=await c.text(),d=(c.headers.get("content-type")||"").includes("application/json"),p=d&&u?JSON.parse(u):u;if(!c.ok){let h=d?p:void 0,f=h?.error;throw new Tr(f?.message??`Request failed with status ${c.status}`,{status:c.status,icebergType:f?.type,icebergCode:f?.code,details:h})}return {status:c.status,headers:c.headers,data:p}}}}function Ln(t){return t.join("")}function Kt(t){return t.join("")}var Tr,Zg,Qg,oc,ac=R(()=>{Tr=class extends Error{constructor(t,e){super(t),this.name="IcebergError",this.status=e.status,this.icebergType=e.icebergType,this.icebergCode=e.icebergCode,this.details=e.details,this.isCommitStateUnknown=e.icebergType==="CommitStateUnknownException"||[500,502,504].includes(e.status)&&e.icebergType?.includes("CommitState")===true;}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};Zg=class{constructor(t,e=""){this.client=t,this.prefix=e;}async listNamespaces(t){let e=t?{parent:Ln(t.namespace)}:void 0;return (await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:e})).data.namespaces.map(n=>({namespace:n}))}async createNamespace(t,e){let r={namespace:t.namespace,properties:e?.properties};return (await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:r})).data}async dropNamespace(t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Ln(t.namespace)}`});}async loadNamespaceMetadata(t){return {properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Ln(t.namespace)}`})).data.properties}}async namespaceExists(t){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Ln(t.namespace)}`}),!0}catch(e){if(e instanceof Tr&&e.status===404)return false;throw e}}async createNamespaceIfNotExists(t,e){try{return await this.createNamespace(t,e)}catch(r){if(r instanceof Tr&&r.status===409)return;throw r}}};Qg=class{constructor(t,e="",r){this.client=t,this.prefix=e,this.accessDelegation=r;}async listTables(t){return (await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Kt(t.namespace)}/tables`})).data.identifiers}async createTable(t,e){let r={};return this.accessDelegation&&(r["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Kt(t.namespace)}/tables`,body:e,headers:r})).data.metadata}async updateTable(t,e){let r=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Kt(t.namespace)}/tables/${t.name}`,body:e});return {"metadata-location":r.data["metadata-location"],metadata:r.data.metadata}}async dropTable(t,e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Kt(t.namespace)}/tables/${t.name}`,query:{purgeRequested:String(e?.purge??false)}});}async loadTable(t){let e={};return this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Kt(t.namespace)}/tables/${t.name}`,headers:e})).data.metadata}async tableExists(t){let e={};this.accessDelegation&&(e["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Kt(t.namespace)}/tables/${t.name}`,headers:e}),!0}catch(r){if(r instanceof Tr&&r.status===404)return false;throw r}}async createTableIfNotExists(t,e){try{return await this.createTable(t,e)}catch(r){if(r instanceof Tr&&r.status===409)return await this.loadTable({namespace:t.namespace,name:e.name});throw r}}},oc=class{constructor(t){let e="v1";t.catalogName&&(e+=`/${t.catalogName}`);let r=t.baseUrl.endsWith("/")?t.baseUrl:`${t.baseUrl}/`;this.client=Xg({baseUrl:r,auth:t.auth,fetchImpl:t.fetch}),this.accessDelegation=t.accessDelegation?.join(","),this.namespaceOps=new Zg(this.client,e),this.tableOps=new Qg(this.client,e,this.accessDelegation);}async listNamespaces(t){return this.namespaceOps.listNamespaces(t)}async createNamespace(t,e){return this.namespaceOps.createNamespace(t,e)}async dropNamespace(t){await this.namespaceOps.dropNamespace(t);}async loadNamespaceMetadata(t){return this.namespaceOps.loadNamespaceMetadata(t)}async listTables(t){return this.tableOps.listTables(t)}async createTable(t,e){return this.tableOps.createTable(t,e)}async updateTable(t,e){return this.tableOps.updateTable(t,e)}async dropTable(t,e){await this.tableOps.dropTable(t,e);}async loadTable(t){return this.tableOps.loadTable(t)}async namespaceExists(t){return this.namespaceOps.namespaceExists(t)}async tableExists(t){return this.tableOps.tableExists(t)}async createNamespaceIfNotExists(t,e){return this.namespaceOps.createNamespaceIfNotExists(t,e)}async createTableIfNotExists(t,e){return this.tableOps.createTableIfNotExists(t,e)}};});function Ir(t){"@babel/helpers - typeof";return Ir=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},Ir(t)}function em(t,e){if(Ir(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(Ir(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(t)}function tm(t){var e=em(t,"string");return Ir(e)=="symbol"?e:e+""}function rm(t,e,r){return (e=tm(e))in t?Object.defineProperty(t,e,{value:r,enumerable:true,configurable:true,writable:true}):t[e]=r,t}function lc(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n);}return r}function E(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?lc(Object(r),true).forEach(function(n){rm(t,n,r[n]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):lc(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n));});}return t}function Bn(t){return typeof t=="object"&&t!==null&&"__isStorageError"in t}function lm(t,e,r){let n=E({},t);for(let i of Object.keys(n))i.toLowerCase()===e.toLowerCase()&&delete n[i];return n[e]=r,n}async function Ar(t,e,r,n,i,s,o){return new Promise((a,l)=>{t(r,am(e,n,i,s)).then(c=>{if(!c.ok)throw c;if(n?.noResolveJson)return c;if(o==="vectors"){let u=c.headers.get("content-type");if(c.headers.get("content-length")==="0"||c.status===204)return {};if(!u||!u.includes("application/json"))return {}}return c.json()}).then(c=>a(c)).catch(c=>om(c,l,n,o));})}function pc(t="storage"){return {get:async(e,r,n,i)=>Ar(e,"GET",r,n,i,void 0,t),post:async(e,r,n,i,s)=>Ar(e,"POST",r,i,s,n,t),put:async(e,r,n,i,s)=>Ar(e,"PUT",r,i,s,n,t),head:async(e,r,n,i)=>Ar(e,"HEAD",r,E(E({},n),{},{noResolveJson:true}),i,void 0,t),remove:async(e,r,n,i,s)=>Ar(e,"DELETE",r,i,s,n,t)}}var Wn,Un,dc,nm,im,Is,sm,cc,om,am,cm,Or,ge,Os,um,$s,re,Vt,dm,hc,pm,hm,uc,fm,gm,$r,mm,_m,wm,ym,km,bm,vm,Sm,fc,gc=R(()=>{ac();Wn=class extends Error{constructor(t,e="storage",r,n){super(t),this.__isStorageError=true,this.namespace=e,this.name=e==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=n;}toJSON(){return {name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};Un=class extends Wn{constructor(t,e,r,n="storage"){super(t,n,e,r),this.name=n==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=e,this.statusCode=r;}toJSON(){return E({},super.toJSON())}},dc=class extends Wn{constructor(t,e,r="storage"){super(t,r),this.name=r==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=e;}},nm=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),im=t=>{if(typeof t!="object"||t===null)return false;let e=Object.getPrototypeOf(t);return (e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},Is=t=>{if(Array.isArray(t))return t.map(r=>Is(r));if(typeof t=="function"||t!==Object(t))return t;let e={};return Object.entries(t).forEach(([r,n])=>{let i=r.replace(/([-_][a-z])/gi,s=>s.toUpperCase().replace(/[-_]/g,""));e[i]=Is(n);}),e},sm=t=>!t||typeof t!="string"||t.length===0||t.length>100||t.trim()!==t||t.includes("/")||t.includes("\\")?false:/^[\w!.\*'() &$@=;:+,?-]+$/.test(t),cc=t=>{var e;return t.msg||t.message||t.error_description||(typeof t.error=="string"?t.error:(e=t.error)===null||e===void 0?void 0:e.message)||JSON.stringify(t)},om=async(t,e,r,n)=>{if(t!==null&&typeof t=="object"&&typeof t.json=="function"){let i=t,s=parseInt(i.status,10);Number.isFinite(s)||(s=500),i.json().then(o=>{let a=o?.statusCode||o?.code||s+"";e(new Un(cc(o),s,a,n));}).catch(()=>{let o=s+"";e(new Un(i.statusText||`HTTP ${s} error`,s,o,n));});}else e(new dc(cc(t),t,n));},am=(t,e,r,n)=>{let i={method:t,headers:e?.headers||{}};if(t==="GET"||t==="HEAD"||!n)return E(E({},i),r);if(im(n)){var s;let o=e?.headers||{},a;for(let[l,c]of Object.entries(o))l.toLowerCase()==="content-type"&&(a=c);i.headers=lm(o,"Content-Type",(s=a)!==null&&s!==void 0?s:"application/json"),i.body=JSON.stringify(n);}else i.body=n;return e?.duplex&&(i.duplex=e.duplex),E(E({},i),r)};cm=pc("storage"),{get:Or,post:ge,put:Os,head:um,remove:$s}=cm,re=pc("vectors"),Vt=class{constructor(t,e={},r,n="storage"){this.shouldThrowOnError=false,this.url=t,this.headers=Object.fromEntries(Object.entries(e).map(([i,s])=>[i.toLowerCase(),s])),this.fetch=nm(r),this.namespace=n;}throwOnError(){return this.shouldThrowOnError=true,this}setHeader(t,e){return this.headers=E(E({},this.headers),{},{[t.toLowerCase()]:e}),this}async handleOperation(t){var e=this;try{return {data:await t(),error:null}}catch(r){if(e.shouldThrowOnError)throw r;if(Bn(r))return {data:null,error:r};throw r}}},dm=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e;}then(t,e){return this.execute().then(t,e)}async execute(){var t=this;try{return {data:(await t.downloadFn()).body,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Bn(e))return {data:null,error:e};throw e}}};hc=Symbol.toStringTag;pm=class{constructor(t,e){this.downloadFn=t,this.shouldThrowOnError=e,this[hc]="BlobDownloadBuilder",this.promise=null;}asStream(){return new dm(this.downloadFn,this.shouldThrowOnError)}then(t,e){return this.getPromise().then(t,e)}catch(t){return this.getPromise().catch(t)}finally(t){return this.getPromise().finally(t)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var t=this;try{return {data:await(await t.downloadFn()).blob(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(Bn(e))return {data:null,error:e};throw e}}},hm={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},uc={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:false},fm=class extends Vt{constructor(t,e={},r,n){super(t,e,n,"storage"),this.bucketId=r;}async uploadOrUpdate(t,e,r,n){var i=this;return i.handleOperation(async()=>{let s,o=E(E({},uc),n),a=E(E({},i.headers),t==="POST"&&{"x-upsert":String(o.upsert)}),l=o.metadata;typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",o.cacheControl),l&&s.append("metadata",i.encodeMetadata(l)),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.has("cacheControl")||s.append("cacheControl",o.cacheControl),l&&!s.has("metadata")&&s.append("metadata",i.encodeMetadata(l))):(s=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType,l&&(a["x-metadata"]=i.toBase64(i.encodeMetadata(l))),(typeof ReadableStream<"u"&&s instanceof ReadableStream||s&&typeof s=="object"&&"pipe"in s&&typeof s.pipe=="function")&&!o.duplex&&(o.duplex="half")),n?.headers&&(a=E(E({},a),n.headers));let c=i._removeEmptyFolders(e),u=i._getFinalPath(c),d=await(t=="PUT"?Os:ge)(i.fetch,`${i.url}/object/${u}`,s,E({headers:a},o?.duplex?{duplex:o.duplex}:{}));return {path:c,id:d.Id,fullPath:d.Key}})}async upload(t,e,r){return this.uploadOrUpdate("POST",t,e,r)}async uploadToSignedUrl(t,e,r,n){var i=this;let s=i._removeEmptyFolders(t),o=i._getFinalPath(s),a=new URL(i.url+`/object/upload/sign/${o}`);return a.searchParams.set("token",e),i.handleOperation(async()=>{let l,c=E(E({},uc),n),u=E(E({},i.headers),{"x-upsert":String(c.upsert)});return typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",c.cacheControl)):(l=r,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType),{path:s,fullPath:(await Os(i.fetch,a.toString(),l,{headers:u})).Key}})}async createSignedUploadUrl(t,e){var r=this;return r.handleOperation(async()=>{let n=r._getFinalPath(t),i=E({},r.headers);e?.upsert&&(i["x-upsert"]="true");let s=await ge(r.fetch,`${r.url}/object/upload/sign/${n}`,{},{headers:i}),o=new URL(r.url+s.url),a=o.searchParams.get("token");if(!a)throw new Wn("No token returned by API");return {signedUrl:o.toString(),path:t,token:a}})}async update(t,e,r){return this.uploadOrUpdate("PUT",t,e,r)}async move(t,e,r){var n=this;return n.handleOperation(async()=>await ge(n.fetch,`${n.url}/object/move`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers}))}async copy(t,e,r){var n=this;return n.handleOperation(async()=>({path:(await ge(n.fetch,`${n.url}/object/copy`,{bucketId:n.bucketId,sourceKey:t,destinationKey:e,destinationBucket:r?.destinationBucket},{headers:n.headers})).Key}))}async createSignedUrl(t,e,r){var n=this;return n.handleOperation(async()=>{let i=n._getFinalPath(t),s=typeof r?.transform=="object"&&r.transform!==null&&Object.keys(r.transform).length>0,o=await ge(n.fetch,`${n.url}/object/sign/${i}`,E({expiresIn:e},s?{transform:r.transform}:{}),{headers:n.headers}),a=new URLSearchParams;r?.download&&a.set("download",r.download===true?"":r.download),r?.cacheNonce!=null&&a.set("cacheNonce",String(r.cacheNonce));let l=a.toString();return {signedUrl:encodeURI(`${n.url}${o.signedURL}${l?`&${l}`:""}`)}})}async createSignedUrls(t,e,r){var n=this;return n.handleOperation(async()=>{let i=await ge(n.fetch,`${n.url}/object/sign/${n.bucketId}`,{expiresIn:e,paths:t},{headers:n.headers}),s=new URLSearchParams;r?.download&&s.set("download",r.download===true?"":r.download),r?.cacheNonce!=null&&s.set("cacheNonce",String(r.cacheNonce));let o=s.toString();return i.map(a=>E(E({},a),{},{signedUrl:a.signedURL?encodeURI(`${n.url}${a.signedURL}${o?`&${o}`:""}`):null}))})}download(t,e,r){let n=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image/authenticated":"object",i=new URLSearchParams;e?.transform&&this.applyTransformOptsToQuery(i,e.transform),e?.cacheNonce!=null&&i.set("cacheNonce",String(e.cacheNonce));let s=i.toString(),o=this._getFinalPath(t),a=()=>Or(this.fetch,`${this.url}/${n}/${o}${s?`?${s}`:""}`,{headers:this.headers,noResolveJson:true},r);return new pm(a,this.shouldThrowOnError)}async info(t){var e=this;let r=e._getFinalPath(t);return e.handleOperation(async()=>Is(await Or(e.fetch,`${e.url}/object/info/${r}`,{headers:e.headers})))}async exists(t){var e=this;let r=e._getFinalPath(t);try{return await um(e.fetch,`${e.url}/object/${r}`,{headers:e.headers}),{data:!0,error:null}}catch(i){if(e.shouldThrowOnError)throw i;if(Bn(i)){var n;let s=i instanceof Un?i.status:i instanceof dc?(n=i.originalError)===null||n===void 0?void 0:n.status:void 0;if(s!==void 0&&[400,404].includes(s))return {data:false,error:i}}throw i}}getPublicUrl(t,e){let r=this._getFinalPath(t),n=new URLSearchParams;e?.download&&n.set("download",e.download===true?"":e.download),e?.transform&&this.applyTransformOptsToQuery(n,e.transform),e?.cacheNonce!=null&&n.set("cacheNonce",String(e.cacheNonce));let i=n.toString(),s=typeof e?.transform=="object"&&e.transform!==null&&Object.keys(e.transform).length>0?"render/image":"object";return {data:{publicUrl:encodeURI(`${this.url}/${s}/public/${r}`)+(i?`?${i}`:"")}}}async remove(t){var e=this;return e.handleOperation(async()=>await $s(e.fetch,`${e.url}/object/${e.bucketId}`,{prefixes:t},{headers:e.headers}))}async list(t,e,r){var n=this;return n.handleOperation(async()=>{let i=E(E(E({},hm),e),{},{prefix:t||""});return await ge(n.fetch,`${n.url}/object/list/${n.bucketId}`,i,{headers:n.headers},r)})}async listV2(t,e){var r=this;return r.handleOperation(async()=>{let n=E({},t);return await ge(r.fetch,`${r.url}/object/list-v2/${r.bucketId}`,n,{headers:r.headers},e)})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return `${this.bucketId}/${t.replace(/^\/+/,"")}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(t,e){return e.width&&t.set("width",e.width.toString()),e.height&&t.set("height",e.height.toString()),e.resize&&t.set("resize",e.resize),e.format&&t.set("format",e.format),e.quality&&t.set("quality",e.quality.toString()),t}},gm="2.103.2",$r={"X-Client-Info":`storage-js/${gm}`},mm=class extends Vt{constructor(t,e={},r,n){let i=new URL(t);n?.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes("storage.supabase.")&&(i.hostname=i.hostname.replace("supabase.","storage.supabase."));let s=i.href.replace(/\/$/,""),o=E(E({},$r),e);super(s,o,r,"storage");}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=e.listBucketOptionsToQueryString(t);return await Or(e.fetch,`${e.url}/bucket${r}`,{headers:e.headers})})}async getBucket(t){var e=this;return e.handleOperation(async()=>await Or(e.fetch,`${e.url}/bucket/${t}`,{headers:e.headers}))}async createBucket(t,e={public:false}){var r=this;return r.handleOperation(async()=>await ge(r.fetch,`${r.url}/bucket`,{id:t,name:t,type:e.type,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async updateBucket(t,e){var r=this;return r.handleOperation(async()=>await Os(r.fetch,`${r.url}/bucket/${t}`,{id:t,name:t,public:e.public,file_size_limit:e.fileSizeLimit,allowed_mime_types:e.allowedMimeTypes},{headers:r.headers}))}async emptyBucket(t){var e=this;return e.handleOperation(async()=>await ge(e.fetch,`${e.url}/bucket/${t}/empty`,{},{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await $s(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}listBucketOptionsToQueryString(t){let e={};return t&&("limit"in t&&(e.limit=String(t.limit)),"offset"in t&&(e.offset=String(t.offset)),t.search&&(e.search=t.search),t.sortColumn&&(e.sortColumn=t.sortColumn),t.sortOrder&&(e.sortOrder=t.sortOrder)),Object.keys(e).length>0?"?"+new URLSearchParams(e).toString():""}},_m=class extends Vt{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=E(E({},$r),e);super(n,i,r,"storage");}async createBucket(t){var e=this;return e.handleOperation(async()=>await ge(e.fetch,`${e.url}/bucket`,{name:t},{headers:e.headers}))}async listBuckets(t){var e=this;return e.handleOperation(async()=>{let r=new URLSearchParams;t?.limit!==void 0&&r.set("limit",t.limit.toString()),t?.offset!==void 0&&r.set("offset",t.offset.toString()),t?.sortColumn&&r.set("sortColumn",t.sortColumn),t?.sortOrder&&r.set("sortOrder",t.sortOrder),t?.search&&r.set("search",t.search);let n=r.toString(),i=n?`${e.url}/bucket?${n}`:`${e.url}/bucket`;return await Or(e.fetch,i,{headers:e.headers})})}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await $s(e.fetch,`${e.url}/bucket/${t}`,{},{headers:e.headers}))}from(t){var e=this;if(!sm(t))throw new Wn("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.");let r=new oc({baseUrl:this.url,catalogName:t,auth:{type:"custom",getHeaders:async()=>e.headers},fetch:this.fetch}),n=this.shouldThrowOnError;return new Proxy(r,{get(i,s){let o=i[s];return typeof o!="function"?o:async(...a)=>{try{return {data:await o.apply(i,a),error:null}}catch(l){if(n)throw l;return {data:null,error:l}}}}})}},wm=class extends Vt{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=E(E({},$r),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors");}async createIndex(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/CreateIndex`,t,{headers:e.headers})||{})}async getIndex(t,e){var r=this;return r.handleOperation(async()=>await re.post(r.fetch,`${r.url}/GetIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers}))}async listIndexes(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/ListIndexes`,t,{headers:e.headers}))}async deleteIndex(t,e){var r=this;return r.handleOperation(async()=>await re.post(r.fetch,`${r.url}/DeleteIndex`,{vectorBucketName:t,indexName:e},{headers:r.headers})||{})}},ym=class extends Vt{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=E(E({},$r),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors");}async putVectors(t){var e=this;if(t.vectors.length<1||t.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/PutVectors`,t,{headers:e.headers})||{})}async getVectors(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/GetVectors`,t,{headers:e.headers}))}async listVectors(t){var e=this;if(t.segmentCount!==void 0){if(t.segmentCount<1||t.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");if(t.segmentIndex!==void 0&&(t.segmentIndex<0||t.segmentIndex>=t.segmentCount))throw new Error(`segmentIndex must be between 0 and ${t.segmentCount-1}`)}return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/ListVectors`,t,{headers:e.headers}))}async queryVectors(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/QueryVectors`,t,{headers:e.headers}))}async deleteVectors(t){var e=this;if(t.keys.length<1||t.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/DeleteVectors`,t,{headers:e.headers})||{})}},km=class extends Vt{constructor(t,e={},r){let n=t.replace(/\/$/,""),i=E(E({},$r),{},{"Content-Type":"application/json"},e);super(n,i,r,"vectors");}async createBucket(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/CreateVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}async getBucket(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/GetVectorBucket`,{vectorBucketName:t},{headers:e.headers}))}async listBuckets(t={}){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/ListVectorBuckets`,t,{headers:e.headers}))}async deleteBucket(t){var e=this;return e.handleOperation(async()=>await re.post(e.fetch,`${e.url}/DeleteVectorBucket`,{vectorBucketName:t},{headers:e.headers})||{})}},bm=class extends km{constructor(t,e={}){super(t,e.headers||{},e.fetch);}from(t){return new vm(this.url,this.headers,t,this.fetch)}async createBucket(t){var e=()=>super.createBucket,r=this;return e().call(r,t)}async getBucket(t){var e=()=>super.getBucket,r=this;return e().call(r,t)}async listBuckets(t={}){var e=()=>super.listBuckets,r=this;return e().call(r,t)}async deleteBucket(t){var e=()=>super.deleteBucket,r=this;return e().call(r,t)}},vm=class extends wm{constructor(t,e,r,n){super(t,e,n),this.vectorBucketName=r;}async createIndex(t){var e=()=>super.createIndex,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName}))}async listIndexes(t={}){var e=()=>super.listIndexes,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName}))}async getIndex(t){var e=()=>super.getIndex,r=this;return e().call(r,r.vectorBucketName,t)}async deleteIndex(t){var e=()=>super.deleteIndex,r=this;return e().call(r,r.vectorBucketName,t)}index(t){return new Sm(this.url,this.headers,this.vectorBucketName,t,this.fetch)}},Sm=class extends ym{constructor(t,e,r,n,i){super(t,e,i),this.vectorBucketName=r,this.indexName=n;}async putVectors(t){var e=()=>super.putVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async getVectors(t){var e=()=>super.getVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async listVectors(t={}){var e=()=>super.listVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async queryVectors(t){var e=()=>super.queryVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}async deleteVectors(t){var e=()=>super.deleteVectors,r=this;return e().call(r,E(E({},t),{},{vectorBucketName:r.vectorBucketName,indexName:r.indexName}))}},fc=class extends mm{constructor(t,e={},r,n){super(t,e,r,n);}from(t){return new fm(this.url,this.headers,t,this.fetch)}get vectors(){return new bm(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new _m(this.url+"/iceberg",this.headers,this.fetch)}};});var Fn,Ns=R(()=>{Fn="2.103.2";});var ot,Hn,qn,mc,_c,wc,Nr,js,yc,kc,zn=R(()=>{Ns();ot=30*1e3,Hn=3,qn=Hn*ot,mc="http://localhost:9999",_c="supabase.auth.token",wc={"X-Client-Info":`gotrue-js/${Fn}`},Nr="X-Supabase-Api-Version",js={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},yc=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,kc=600*1e3;});function v(t){return typeof t=="object"&&t!==null&&"__isAuthError"in t}function bc(t){return v(t)&&t.name==="AuthApiError"}function Mr(t){return v(t)&&t.name==="AuthSessionMissingError"}function vc(t){return v(t)&&t.name==="AuthImplicitGrantRedirectError"}function Vn(t){return v(t)&&t.name==="AuthRetryableFetchError"}var qe,Jn,ue,me,J,Oe,at,lt,jr,Kn,Gt,Dr,ct,ut=R(()=>{qe=class extends Error{constructor(e,r,n){super(e),this.__isAuthError=true,this.name="AuthError",this.status=r,this.code=n;}toJSON(){return {name:this.name,message:this.message,status:this.status,code:this.code}}};Jn=class extends qe{constructor(e,r,n){super(e,r,n),this.name="AuthApiError",this.status=r,this.code=n;}};ue=class extends qe{constructor(e,r){super(e),this.name="AuthUnknownError",this.originalError=r;}},me=class extends qe{constructor(e,r,n,i){super(e,n,i),this.name=r,this.status=n;}},J=class extends me{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0);}};Oe=class extends me{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0);}},at=class extends me{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0);}},lt=class extends me{constructor(e,r=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=r;}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}};jr=class extends me{constructor(e,r=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=r;}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}},Kn=class extends me{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found");}},Gt=class extends me{constructor(e,r){super(e,"AuthRetryableFetchError",r,void 0);}};Dr=class extends me{constructor(e,r,n){super(e,"AuthWeakPasswordError",r,"weak_password"),this.reasons=n;}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}},ct=class extends me{constructor(e){super(e,"AuthInvalidJwtError",400,"invalid_jwt");}};});function Cc(t,e,r){if(t!==null)for(e.queue=e.queue<<8|t,e.queuedBits+=8;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(Gn[n]),e.queuedBits-=6;}else if(e.queuedBits>0)for(e.queue=e.queue<<6-e.queuedBits,e.queuedBits=6;e.queuedBits>=6;){let n=e.queue>>e.queuedBits-6&63;r(Gn[n]),e.queuedBits-=6;}}function Ec(t,e,r){let n=Cm[t];if(n>-1)for(e.queue=e.queue<<6|n,e.queuedBits+=6;e.queuedBits>=8;)r(e.queue>>e.queuedBits-8&255),e.queuedBits-=8;else {if(n===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(t)}"`)}}function Ds(t){let e=[],r=o=>{e.push(String.fromCodePoint(o));},n={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},s=o=>{xm(o,n,r);};for(let o=0;o<t.length;o+=1)Ec(t.charCodeAt(o),i,s);return e.join("")}function Em(t,e){if(t<=127){e(t);return}else if(t<=2047){e(192|t>>6),e(128|t&63);return}else if(t<=65535){e(224|t>>12),e(128|t>>6&63),e(128|t&63);return}else if(t<=1114111){e(240|t>>18),e(128|t>>12&63),e(128|t>>6&63),e(128|t&63);return}throw new Error(`Unrecognized Unicode codepoint: ${t.toString(16)}`)}function Rm(t,e){for(let r=0;r<t.length;r+=1){let n=t.charCodeAt(r);if(n>55295&&n<=56319){let i=(n-55296)*1024&65535;n=(t.charCodeAt(r+1)-56320&65535|i)+65536,r+=1;}Em(n,e);}}function xm(t,e,r){if(e.utf8seq===0){if(t<=127){r(t);return}for(let n=1;n<6;n+=1)if((t>>7-n&1)===0){e.utf8seq=n;break}if(e.utf8seq===2)e.codepoint=t&31;else if(e.utf8seq===3)e.codepoint=t&15;else if(e.utf8seq===4)e.codepoint=t&7;else throw new Error("Invalid UTF-8 sequence");e.utf8seq-=1;}else if(e.utf8seq>0){if(t<=127)throw new Error("Invalid UTF-8 sequence");e.codepoint=e.codepoint<<6|t&63,e.utf8seq-=1,e.utf8seq===0&&r(e.codepoint);}}function ze(t){let e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i);};for(let i=0;i<t.length;i+=1)Ec(t.charCodeAt(i),r,n);return new Uint8Array(e)}function Rc(t){let e=[];return Rm(t,r=>e.push(r)),new Uint8Array(e)}function $e(t){let e=[],r={queue:0,queuedBits:0},n=i=>{e.push(i);};return t.forEach(i=>Cc(i,r,n)),Cc(null,r,n),e.join("")}var Gn,Sc,Cm,Yn=R(()=>{Gn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Sc=`
|
|
31
|
+
\r=`.split(""),Cm=(()=>{let t=new Array(128);for(let e=0;e<t.length;e+=1)t[e]=-1;for(let e=0;e<Sc.length;e+=1)t[Sc[e].charCodeAt(0)]=-2;for(let e=0;e<Gn.length;e+=1)t[Gn[e].charCodeAt(0)]=e;return t})();});function xc(t){return Math.round(Date.now()/1e3)+t}function Pc(){return Symbol("auth-callback")}function Tc(t){let e={},r=new URL(t);if(r.hash&&r.hash[0]==="#")try{new URLSearchParams(r.hash.substring(1)).forEach((i,s)=>{e[s]=i;});}catch{}return r.searchParams.forEach((n,i)=>{e[i]=n;}),e}function Ur(t){let e=t.split(".");if(e.length!==3)throw new ct("Invalid JWT structure");for(let n=0;n<e.length;n++)if(!yc.test(e[n]))throw new ct("JWT not in base64url format");return {header:JSON.parse(Ds(e[0])),payload:JSON.parse(Ds(e[1])),signature:ze(e[2]),raw:{header:e[0],payload:e[1]}}}async function Ic(t){return await new Promise(e=>{setTimeout(()=>e(null),t);})}function Oc(t,e){return new Promise((n,i)=>{(async()=>{for(let s=0;s<1/0;s++)try{let o=await t(s);if(!e(s,null,o)){n(o);return}}catch(o){if(!e(s,o)){i(o);return}}})();})}function Pm(t){return ("0"+t.toString(16)).substr(-2)}function Tm(){let e=new Uint32Array(56);if(typeof crypto>"u"){let r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=r.length,i="";for(let s=0;s<56;s++)i+=r.charAt(Math.floor(Math.random()*n));return i}return crypto.getRandomValues(e),Array.from(e,Pm).join("")}async function Am(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r),i=new Uint8Array(n);return Array.from(i).map(s=>String.fromCharCode(s)).join("")}async function Im(t){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),t;let r=await Am(t);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function ht(t,e,r=false){let n=Tm(),i=n;r&&(i+="/PASSWORD_RECOVERY"),await pt(t,`${e}-code-verifier`,i);let s=await Im(n);return [s,n===s?"plain":"s256"]}function $c(t){let e=t.headers.get(Nr);if(!e||!e.match(Om))return null;try{return new Date(`${e}T00:00:00.0Z`)}catch{return null}}function Nc(t){if(!t)throw new Error("Missing exp claim");let e=Math.floor(Date.now()/1e3);if(t<=e)throw new Error("JWT has expired")}function jc(t){switch(t){case "RS256":return {name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case "ES256":return {name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}function ft(t){if(!$m.test(t))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function Qn(){let t={};return new Proxy(t,{get:(e,r)=>{if(r==="__isUserNotAvailableProxy")return true;if(typeof r=="symbol"){let n=r.toString();if(n==="Symbol(Symbol.toPrimitive)"||n==="Symbol(Symbol.toStringTag)"||n==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${r}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,r)=>{throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${r}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function Dc(t,e){return new Proxy(t,{get:(r,n,i)=>{if(n==="__isInsecureUserWarningProxy")return true;if(typeof n=="symbol"){let s=n.toString();if(s==="Symbol(Symbol.toPrimitive)"||s==="Symbol(Symbol.toStringTag)"||s==="Symbol(util.inspect.custom)"||s==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(r,n,i)}return !e.value&&typeof n=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),e.value=true),Reflect.get(r,n,i)}})}function Ms(t){return JSON.parse(JSON.stringify(t))}var q,dt,Xn,Zn,Ac,pt,Je,z,Lr,Om,$m,Yt=R(()=>{zn();ut();Yn();q=()=>typeof window<"u"&&typeof document<"u",dt={tested:false,writable:false},Xn=()=>{if(!q())return false;try{if(typeof globalThis.localStorage!="object")return !1}catch{return false}if(dt.tested)return dt.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),dt.tested=!0,dt.writable=!0;}catch{dt.tested=true,dt.writable=false;}return dt.writable};Zn=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),Ac=t=>typeof t=="object"&&t!==null&&"status"in t&&"ok"in t&&"json"in t&&typeof t.json=="function",pt=async(t,e,r)=>{await t.setItem(e,JSON.stringify(r));},Je=async(t,e)=>{let r=await t.getItem(e);if(!r)return null;try{return JSON.parse(r)}catch{return r}},z=async(t,e)=>{await t.removeItem(e);},Lr=class t{constructor(){this.promise=new t.promiseConstructor((e,r)=>{this.resolve=e,this.reject=r;});}};Lr.promiseConstructor=Promise;Om=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;$m=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;});async function Mc(t){var e;if(!Ac(t))throw new Gt(gt(t),0);if(Nm.includes(t.status))throw new Gt(gt(t),t.status);let r;try{r=await t.json();}catch(s){throw new ue(gt(s),s)}let n,i=$c(t);if(i&&i.getTime()>=js["2024-01-01"].timestamp&&typeof r=="object"&&r&&typeof r.code=="string"?n=r.code:typeof r=="object"&&r&&typeof r.error_code=="string"&&(n=r.error_code),n){if(n==="weak_password")throw new Dr(gt(r),t.status,((e=r.weak_password)===null||e===void 0?void 0:e.reasons)||[]);if(n==="session_not_found")throw new J}else if(typeof r=="object"&&r&&typeof r.weak_password=="object"&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((s,o)=>s&&typeof o=="string",true))throw new Dr(gt(r),t.status,r.weak_password.reasons);throw new Jn(gt(r),t.status||500,n)}async function S(t,e,r,n){var i;let s=Object.assign({},n?.headers);s[Nr]||(s[Nr]=js["2024-01-01"].name),n?.jwt&&(s.Authorization=`Bearer ${n.jwt}`);let o=(i=n?.query)!==null&&i!==void 0?i:{};n?.redirectTo&&(o.redirect_to=n.redirectTo);let a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await Dm(t,e,r+a,{headers:s,noResolveJson:n?.noResolveJson},{},n?.body);return n?.xform?n?.xform(l):{data:Object.assign({},l),error:null}}async function Dm(t,e,r,n,i,s){let o=jm(e,n,i,s),a;try{a=await t(r,Object.assign({},o));}catch(l){throw console.error(l),new Gt(gt(l),0)}if(a.ok||await Mc(a),n?.noResolveJson)return a;try{return await a.json()}catch(l){await Mc(l);}}function de(t){var e;let r=null;Mm(t)&&(r=Object.assign({},t),t.expires_at||(r.expires_at=xc(t.expires_in)));let n=(e=t.user)!==null&&e!==void 0?e:t;return {data:{session:r,user:n},error:null}}function Ls(t){let e=de(t);return !e.error&&t.weak_password&&typeof t.weak_password=="object"&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.message&&typeof t.weak_password.message=="string"&&t.weak_password.reasons.reduce((r,n)=>r&&typeof n=="string",true)&&(e.data.weak_password=t.weak_password),e}function Se(t){var e;return {data:{user:(e=t.user)!==null&&e!==void 0?e:t},error:null}}function Lc(t){return {data:t,error:null}}function Uc(t){let{action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:s}=t,o=it(t,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:r,hashed_token:n,redirect_to:i,verification_type:s},l=Object.assign({},o);return {data:{properties:a,user:l},error:null}}function Us(t){return t}function Mm(t){return t.access_token&&t.refresh_token&&t.expires_in}var gt,Nm,jm,Ws=R(()=>{mr();zn();Yt();ut();gt=t=>t.msg||t.message||t.error_description||t.error||JSON.stringify(t),Nm=[502,503,504,520,521,522,523,524,530];jm=(t,e,r,n)=>{let i={method:t,headers:e?.headers||{}};return t==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e?.headers),i.body=JSON.stringify(n),Object.assign(Object.assign({},i),r))};});var ei,Bs=R(()=>{ei=["global","local","others"];});var mt,ti=R(()=>{mr();Ws();Yt();Bs();ut();mt=class{constructor({url:e="",headers:r={},fetch:n}){this.url=e,this.headers=r,this.fetch=Zn(n),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)};}async signOut(e,r=ei[0]){if(ei.indexOf(r)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${ei.join(", ")}`);try{return await S(this.fetch,"POST",`${this.url}/logout?scope=${r}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(n){if(v(n))return {data:null,error:n};throw n}}async inviteUserByEmail(e,r={}){try{return await S(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:r.data},headers:this.headers,redirectTo:r.redirectTo,xform:Se})}catch(n){if(v(n))return {data:{user:null},error:n};throw n}}async generateLink(e){try{let{options:r}=e,n=it(e,["options"]),i=Object.assign(Object.assign({},n),r);return "newEmail"in n&&(i.new_email=n?.newEmail,delete i.newEmail),await S(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:Uc,redirectTo:r?.redirectTo})}catch(r){if(v(r))return {data:{properties:null,user:null},error:r};throw r}}async createUser(e){try{return await S(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Se})}catch(r){if(v(r))return {data:{user:null},error:r};throw r}}async listUsers(e){var r,n,i,s,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},u=await S(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(s=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:Us});if(u.error)throw u.error;let d=await u.json(),p=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,h=(l=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return h.length>0&&(h.forEach(f=>{let m=parseInt(f.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(f.split(";")[1].split("=")[1]);c[`${_}Page`]=m;}),c.total=parseInt(p)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(v(c))return {data:{users:[]},error:c};throw c}}async getUserById(e){ft(e);try{return await S(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Se})}catch(r){if(v(r))return {data:{user:null},error:r};throw r}}async updateUserById(e,r){ft(e);try{return await S(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:r,headers:this.headers,xform:Se})}catch(n){if(v(n))return {data:{user:null},error:n};throw n}}async deleteUser(e,r=false){ft(e);try{return await S(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:r},xform:Se})}catch(n){if(v(n))return {data:{user:null},error:n};throw n}}async _listFactors(e){ft(e.userId);try{let{data:r,error:n}=await S(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return {data:r,error:n}}catch(r){if(v(r))return {data:null,error:r};throw r}}async _deleteFactor(e){ft(e.userId),ft(e.id);try{return {data:await S(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(r){if(v(r))return {data:null,error:r};throw r}}async _listOAuthClients(e){var r,n,i,s,o,a,l;try{let c={nextPage:null,lastPage:0,total:0},u=await S(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(n=(r=e?.page)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:"",per_page:(s=(i=e?.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:Us});if(u.error)throw u.error;let d=await u.json(),p=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,h=(l=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return h.length>0&&(h.forEach(f=>{let m=parseInt(f.split(";")[0].split("=")[1].substring(0,1)),_=JSON.parse(f.split(";")[1].split("=")[1]);c[`${_}Page`]=m;}),c.total=parseInt(p)),{data:Object.assign(Object.assign({},d),c),error:null}}catch(c){if(v(c))return {data:{clients:[]},error:c};throw c}}async _createOAuthClient(e){try{return await S(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _getOAuthClient(e){try{return await S(this.fetch,"GET",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _updateOAuthClient(e,r){try{return await S(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${e}`,{body:r,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(v(n))return {data:null,error:n};throw n}}async _deleteOAuthClient(e){try{return await S(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(v(r))return {data:null,error:r};throw r}}async _regenerateOAuthClientSecret(e){try{return await S(this.fetch,"POST",`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _listCustomProviders(e){try{let r={};return e?.type&&(r.type=e.type),await S(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:r,xform:n=>{var i;return {data:{providers:(i=n?.providers)!==null&&i!==void 0?i:[]},error:null}}})}catch(r){if(v(r))return {data:{providers:[]},error:r};throw r}}async _createCustomProvider(e){try{return await S(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _getCustomProvider(e){try{return await S(this.fetch,"GET",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(v(r))return {data:null,error:r};throw r}}async _updateCustomProvider(e,r){try{return await S(this.fetch,"PUT",`${this.url}/admin/custom-providers/${e}`,{body:r,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(v(n))return {data:null,error:n};throw n}}async _deleteCustomProvider(e){try{return await S(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(r){if(v(r))return {data:null,error:r};throw r}}};});function Fs(t={}){return {getItem:e=>t[e]||null,setItem:(e,r)=>{t[e]=r;},removeItem:e=>{delete t[e];}}}var Wc=R(()=>{});async function Hs(t,e,r){_e.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",t,e);let n=new globalThis.AbortController,i;e>0&&(i=setTimeout(()=>{n.abort(),_e.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",t);},e)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,e===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async s=>{if(s){clearTimeout(i),_e.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",t,s.name);try{return await r()}finally{_e.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",t,s.name);}}else {if(e===0)throw _e.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",t),new Br(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);if(_e.debug)try{let o=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(o,null," "));}catch(o){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",o);}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),clearTimeout(i),await r()}})}catch(s){if(e>0&&clearTimeout(i),s?.name==="AbortError"&&e>0){if(n.signal.aborted)return _e.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${e}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,{mode:"exclusive",steal:true},async o=>{if(o){_e.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",t,o.name);try{return await r()}finally{_e.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",t,o.name);}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await r()}));throw _e.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",t),new Br(`Lock "${t}" was released because another request stole it`)}throw s}}var _e,Wr,Br,qs=R(()=>{Yt();_e={debug:!!(globalThis&&Xn()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},Wr=class extends Error{constructor(e){super(e),this.isAcquireTimeout=true;}},Br=class extends Wr{};});function Bc(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__;}catch{typeof self<"u"&&(self.globalThis=self);}}var Fc=R(()=>{});function zs(t){if(!/^0x[a-fA-F0-9]{40}$/.test(t))throw new Error(`@supabase/auth-js: Address "${t}" is invalid.`);return t.toLowerCase()}function Hc(t){return parseInt(t,16)}function qc(t){let e=new TextEncoder().encode(t);return "0x"+Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}function zc(t){var e;let{chainId:r,domain:n,expirationTime:i,issuedAt:s=new Date,nonce:o,notBefore:a,requestId:l,resources:c,scheme:u,uri:d,version:p}=t;{if(!Number.isInteger(r))throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${r}`);if(!n)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!d)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(p!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${p}`);if(!((e=t.statement)===null||e===void 0)&&e.includes(`
|
|
32
32
|
`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${t.statement}`)}let h=zs(t.address),f=u?`${u}://${n}`:n,m=t.statement?`${t.statement}
|
|
33
33
|
`:"",_=`${f} wants you to sign in with your Ethereum account:
|
|
34
34
|
${h}
|
|
@@ -43,40 +43,40 @@ Not Before: ${a.toISOString()}`),l&&(b+=`
|
|
|
43
43
|
Request ID: ${l}`),c){let w=`
|
|
44
44
|
Resources:`;for(let y of c){if(!y||typeof y!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${y}`);w+=`
|
|
45
45
|
- ${y}`;}b+=w;}return `${_}
|
|
46
|
-
${b}`}var Jc=R(()=>{});function Kc({error:t,options:e}){var r,n,i;let{publicKey:s}=e;if(!s)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new L({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=s.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===true)return new L({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((n=s.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new L({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((i=s.authenticatorSelection)===null||i===void 0?void 0:i.userVerification)==="required")return new L({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 L({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new L({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return s.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new L({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new L({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if(Js(o)){if(s.rp.id!==o)return new L({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new L({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new L({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 L({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 L({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Vc({error:t,options:e}){let{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new L({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else {if(t.name==="NotAllowedError")return new L({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let n=window.location.hostname;if(Js(n)){if(r.rpId!==n)return new L({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new L({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new L({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 L({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var L,_t,Gc=R(()=>{Ks();L=class extends Error{constructor({message:e,code:r,cause:n,name:i}){var s;super(e,{cause:n}),this.__isWebAuthnError=true,this.name=(s=i??(n instanceof Error?n.name:void 0))!==null&&s!==void 0?s:"Unknown Error",this.code=r;}},_t=class extends L{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r;}};});function Xc(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);let{challenge:e,user:r,excludeCredentials:n}=t,i=it(t,["challenge","user","excludeCredentials"]),s=ze(e).buffer,o=Object.assign(Object.assign({},r),{id:ze(r.id).buffer}),a=Object.assign(Object.assign({},i),{challenge:s,user:o});if(n&&n.length>0){a.excludeCredentials=new Array(n.length);for(let l=0;l<n.length;l++){let c=n[l];a.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:ze(c.id).buffer,type:c.type||"public-key",transports:c.transports});}}return a}function Zc(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);let{challenge:e,allowCredentials:r}=t,n=it(t,["challenge","allowCredentials"]),i=ze(e).buffer,s=Object.assign(Object.assign({},n),{challenge:i});if(r&&r.length>0){s.allowCredentials=new Array(r.length);for(let o=0;o<r.length;o++){let a=r[o];s.allowCredentials[o]=Object.assign(Object.assign({},a),{id:ze(a.id).buffer,type:a.type||"public-key",transports:a.transports});}}return s}function Qc(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t;return {id:t.id,rawId:t.id,response:{attestationObject:$e(new Uint8Array(t.response.attestationObject)),clientDataJSON:$e(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function eu(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,n=t.getClientExtensionResults(),i=t.response;return {id:t.id,rawId:t.id,response:{authenticatorData:$e(new Uint8Array(i.authenticatorData)),clientDataJSON:$e(new Uint8Array(i.clientDataJSON)),signature:$e(new Uint8Array(i.signature)),userHandle:i.userHandle?$e(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Js(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Yc(){var t,e;return !!(q()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function Um(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new _t("Browser returned unexpected credential type",e)}:{data:null,error:new _t("Empty credential response",e)}}catch(e){return {data:null,error:Kc({error:e,options:t})}}}async function Wm(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new _t("Browser returned unexpected credential type",e)}:{data:null,error:new _t("Empty credential response",e)}}catch(e){return {data:null,error:Vc({error:e,options:t})}}}function ti(...t){let e=i=>i!==null&&typeof i=="object"&&!Array.isArray(i),r=i=>i instanceof ArrayBuffer||ArrayBuffer.isView(i),n={};for(let i of t)if(i)for(let s in i){let o=i[s];if(o!==void 0)if(Array.isArray(o))n[s]=o;else if(r(o))n[s]=o;else if(e(o)){let a=n[s];e(a)?n[s]=ti(a,o):n[s]=ti(o);}else n[s]=o;}return n}function Hm(t,e){return ti(Bm,t,e||{})}function qm(t,e){return ti(Fm,t,e||{})}var Vs,Lm,Bm,Fm,ri,Ks=R(()=>{mr();Gn();ut();Yt();Gc();Vs=class{createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r);}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0;}}},Lm=new Vs;Bm={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:false,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Fm={userVerification:"preferred",hints:["security-key"],attestation:"direct"};ri=class{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:n,signal:i},s){var o;try{let{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return {data:null,error:l};let c=i??Lm.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:u}=a.webauthn.credential_options.publicKey;if(!u.name){let d=n;if(d)u.name=`${u.id}:${d}`;else {let h=(await this.client.getUser()).data.user,f=((o=h?.user_metadata)===null||o===void 0?void 0:o.name)||h?.email||h?.id||"User";u.name=`${u.id}:${f}`;}}u.displayName||(u.displayName=u.name);}switch(a.webauthn.type){case "create":{let u=Hm(a.webauthn.credential_options.publicKey,s?.create),{data:d,error:p}=await Um({publicKey:u,signal:c});return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:p}}case "request":{let u=qm(a.webauthn.credential_options.publicKey,s?.request),{data:d,error:p}=await Wm(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:u,signal:c}));return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:p}}}}catch(a){return v(a)?{data:null,error:a}:{data:null,error:new ue("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:n}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},s){if(!r)return {data:null,error:new qe("rpId is required for WebAuthn authentication")};try{if(!Yc())return {data:null,error:new ue("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:n},signal:i},{request:s});if(!o)return {data:null,error:a};let{webauthn:l}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:n,credential_response:l.credential_response}})}catch(o){return v(o)?{data:null,error:o}:{data:null,error:new ue("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},s){if(!r)return {data:null,error:new qe("rpId is required for WebAuthn registration")};try{if(!Yc())return {data:null,error:new ue("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(u=>{var d;return (d=u.data)===null||d===void 0?void 0:d.all.find(p=>p.factor_type==="webauthn"&&p.friendly_name===e&&p.status!=="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u?.id}):void 0),{data:null,error:a};let{data:l,error:c}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:n},signal:i},{create:s});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:n,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(o){return v(o)?{data:null,error:o}:{data:null,error:new ue("Unexpected error in register",o)}}}};});async function tu(t,e,r){return await r()}var zm,Xt,ni,Gs,Ys=R(()=>{ei();qn();ut();Ws();Yt();Wc();qs();Fc();Ns();Gn();Jc();Ks();Bc();zm={url:mc,storageKey:_c,autoRefreshToken:true,persistSession:true,detectSessionInUrl:true,headers:wc,flowType:"implicit",debug:false,hasCustomAuthorizationHeader:false,throwOnError:false,lockAcquireTimeout:5e3,skipAutoInitialize:false};Xt={},ni=class t{get jwks(){var e,r;return (r=(e=Xt[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Xt[this.storageKey]=Object.assign(Object.assign({},Xt[this.storageKey]),{jwks:e});}get jwks_cached_at(){var e,r;return (r=(e=Xt[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Xt[this.storageKey]=Object.assign(Object.assign({},Xt[this.storageKey]),{cachedAt:e});}constructor(e){var r,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=true,this.hasCustomAuthorizationHeader=false,this.suppressGetSessionWarning=false,this.lockAcquired=false,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let s=Object.assign(Object.assign({},zm),e);if(this.storageKey=s.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.instanceID>0&&q()){let o=`${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(o),this.logDebugMessages&&console.trace(o);}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.admin=new mt({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=Xn(s.fetch),this.lock=s.lock||tu,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock?this.lock=s.lock:this.persistSession&&q()&&(!((n=globalThis?.navigator)===null||n===void 0)&&n.locks)?this.lock=Hs:this.lock=tu,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 ri(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.persistSession?(s.storage?this.storage=s.storage:Yn()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Fs(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=Fs(this.memoryStorage)),q()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey);}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o);}(i=this.broadcastChannel)===null||i===void 0||i.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1);}catch(a){this._debug("#broadcastChannel","error",a);}});}s.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o);});}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return `GoTrueClient@${this.storageKey}:${this.instanceID} (${Bn}) ${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={},n="none";if(q()&&(r=Tc(window.location.href),this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce")),q()&&this.detectSessionInUrl&&n!=="none"){let{data:i,error:s}=await this._getSessionFromURL(r,n);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),vc(s)){let l=(e=s.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:s}}return {error:s}}let{session:o,redirectType:a}=i;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 v(r)?this._returnResult({error:r}):this._returnResult({error:new ue("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end");}}async signInAnonymously(e){var r,n,i;try{let s=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:de}),{data:o,error:a}=s;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});let 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(s){if(v(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signUp(e){var r,n,i;try{let s;if("email"in e){let{email:u,password:d,options:p}=e,h=null,f=null;this.flowType==="pkce"&&([h,f]=await ht(this.storage,this.storageKey)),s=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:p?.emailRedirectTo,body:{email:u,password:d,data:(r=p?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:h,code_challenge_method:f},xform:de});}else if("phone"in e){let{phone:u,password:d,options:p}=e;s=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:d,data:(n=p?.data)!==null&&n!==void 0?n:{},channel:(i=p?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:de});}else throw new at("You must provide either an email or phone number and a password");let{data:o,error:a}=s;if(a||!o)return await z(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let 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(s){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithPassword(e){try{let r;if("email"in e){let{email:s,password:o,options:a}=e;r=await S(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ls});}else if("phone"in e){let{phone:s,password:o,options:a}=e;r=await S(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ls});}else throw new at("You must provide either an email or phone number and a password");let{data:n,error:i}=r;if(i)return this._returnResult({data:{user:null,session:null},error:i});if(!n||!n.session||!n.user){let s=new Oe;return this._returnResult({data:{user:null,session:null},error:s})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:i})}catch(r){if(v(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,n,i,s;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(s=e.options)===null||s===void 0?void 0:s.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{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,n,i,s,o,a,l,c,u,d,p;let h,f;if("message"in e)h=e.message,f=e.signature;else {let{chain:m,wallet:_,statement:b,options:w}=e,y;if(q())if(typeof _=="object")y=_;else {let le=window;if("ethereum"in le&&typeof le.ethereum=="object"&&"request"in le.ethereum&&typeof le.ethereum.request=="function")y=le.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 _!="object"||!w?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");y=_;}let I=new URL((r=w?.url)!==null&&r!==void 0?r:window.location.href),Z=await y.request({method:"eth_requestAccounts"}).then(le=>le).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!Z||Z.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let T=zs(Z[0]),$=(n=w?.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!$){let le=await y.request({method:"eth_chainId"});$=Hc(le);}let Te={domain:I.host,address:T,statement:b,uri:I.href,version:"1",chainId:$,nonce:(i=w?.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(o=(s=w?.signInWithEthereum)===null||s===void 0?void 0:s.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=w?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=w?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=w?.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(u=w?.signInWithEthereum)===null||u===void 0?void 0:u.resources};h=zc(Te),f=await y.request({method:"personal_sign",params:[qc(h),T]});}try{let{data:m,error:_}=await S(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:h,signature:f},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:de});if(_)throw _;if(!m||!m.session||!m.user){let b=new Oe;return this._returnResult({data:{user:null,session:null},error:b})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:Object.assign({},m),error:_})}catch(m){if(v(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async signInWithSolana(e){var r,n,i,s,o,a,l,c,u,d,p,h;let f,m;if("message"in e)f=e.message,m=e.signature;else {let{chain:_,wallet:b,statement:w,options:y}=e,I;if(q())if(typeof b=="object")I=b;else {let T=window;if("solana"in T&&typeof T.solana=="object"&&("signIn"in T.solana&&typeof T.solana.signIn=="function"||"signMessage"in T.solana&&typeof T.solana.signMessage=="function"))I=T.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 b!="object"||!y?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");I=b;}let Z=new URL((r=y?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in I&&I.signIn){let T=await I.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},y?.signInWithSolana),{version:"1",domain:Z.host,uri:Z.href}),w?{statement:w}:null)),$;if(Array.isArray(T)&&T[0]&&typeof T[0]=="object")$=T[0];else if(T&&typeof T=="object"&&"signedMessage"in T&&"signature"in T)$=T;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in $&&"signature"in $&&(typeof $.signedMessage=="string"||$.signedMessage instanceof Uint8Array)&&$.signature instanceof Uint8Array)f=typeof $.signedMessage=="string"?$.signedMessage:new TextDecoder().decode($.signedMessage),m=$.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else {if(!("signMessage"in I)||typeof I.signMessage!="function"||!("publicKey"in I)||typeof I!="object"||!I.publicKey||!("toBase58"in I.publicKey)||typeof I.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");f=[`${Z.host} wants you to sign in with your Solana account:`,I.publicKey.toBase58(),...w?["",w,""]:[""],"Version: 1",`URI: ${Z.href}`,`Issued At: ${(i=(n=y?.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((s=y?.signInWithSolana)===null||s===void 0)&&s.notBefore?[`Not Before: ${y.signInWithSolana.notBefore}`]:[],...!((o=y?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${y.signInWithSolana.expirationTime}`]:[],...!((a=y?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${y.signInWithSolana.chainId}`]:[],...!((l=y?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${y.signInWithSolana.nonce}`]:[],...!((c=y?.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${y.signInWithSolana.requestId}`]:[],...!((d=(u=y?.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||d===void 0)&&d.length?["Resources",...y.signInWithSolana.resources.map($=>`- ${$}`)]:[]].join(`
|
|
47
|
-
`);let T=await I.signMessage(new TextEncoder().encode(f),"utf8");if(!T||!(T instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");m=T;}}try{let{data:_,error:b}=await S(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:f,signature:$e(m)},!((p=e.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(h=e.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:de});if(b)throw b;if(!_||!_.session||!_.user){let w=new Oe;return this._returnResult({data:{user:null,session:null},error:w})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:b})}catch(_){if(v(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async _exchangeCodeForSession(e){let r=await Je(this.storage,`${this.storageKey}-code-verifier`),[n,i]=(r??"").split("/");try{if(!n&&this.flowType==="pkce")throw new Jn;let{data:s,error:o}=await S(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:de});if(await z(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!s||!s.session||!s.user){let a=new Oe;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign(Object.assign({},s),{redirectType:i??null}),error:o})}catch(s){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(s))return this._returnResult({data:{user:null,session:null,redirectType:null},error:s});throw s}}async signInWithIdToken(e){try{let{options:r,provider:n,token:i,access_token:s,nonce:o}=e,a=await S(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:i,access_token:s,nonce:o,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:de}),{data:l,error:c}=a;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l||!l.session||!l.user){let u=new Oe;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(v(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,n,i,s,o;try{if("email"in e){let{email:a,options:l}=e,c=null,u=null;this.flowType==="pkce"&&([c,u]=await ht(this.storage,this.storageKey));let{error:d}=await S(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){let{phone:a,options:l}=e,{data:c,error:u}=await S(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=l?.data)!==null&&i!==void 0?i:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c?.message_id},error:u})}throw new at("You must provide either an email or phone number.")}catch(a){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,n;try{let i,s;"options"in e&&(i=(r=e.options)===null||r===void 0?void 0:r.redirectTo,s=(n=e.options)===null||n===void 0?void 0:n.captchaToken);let{data:o,error:a}=await S(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:s}}),redirectTo:i,xform:de});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,c=o.user;return 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(i){if(v(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithSSO(e){var r,n,i,s,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await ht(this.storage,this.storageKey));let c=await S(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:(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((i=e?.options)===null||i===void 0)&&i.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:Lc});return !((s=c.data)===null||s===void 0)&&s.url&&q()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(a){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(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=>{let{data:{session:r},error:n}=e;if(n)throw n;if(!r)throw new J;let{error:i}=await S(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:i})})}catch(e){if(v(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let r=`${this.url}/resend`;if("email"in e){let{email:n,type:i,options:s}=e,{error:o}=await S(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:s?.captchaToken}},redirectTo:s?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){let{phone:n,type:i,options:s}=e,{data:o,error:a}=await S(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:s?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:a})}throw new at("You must provide either an email or phone number and a type")}catch(r){if(v(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){let n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await i;}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let n=r();for(this.pendingInLock.push((async()=>{try{await n;}catch{}})()),await n;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length);}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1;}})}finally{this._debug("#_acquireLock","end");}}async _useSession(e){this._debug("#_useSession","begin");try{let 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,r=await Je(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};let n=e.expires_at?e.expires_at*1e3-Date.now()<Hn:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){let o=await Je(this.userStorage,this.storageKey+"-user");o?.user?e.user=o.user:e.user=Zn();}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let o={value:this.suppressGetSessionWarning};e.user=Dc(e.user,o),o.value&&(this.suppressGetSessionWarning=!0);}return {data:{session:e},error:null}}let{data:i,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{session:null},error:s}):this._returnResult({data:{session:i},error:null})}finally{this._debug("#__loadSession()","end");}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=true),r}async _getUser(e){try{return e?await S(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:ve}):await this._useSession(async r=>{var n,i,s;let{data:o,error:a}=r;if(a)throw a;return !(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new J}:await S(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&s!==void 0?s:void 0,xform:ve})})}catch(r){if(v(r))return Mr(r)&&(await this._removeSession(),await z(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 n=>{let{data:i,error:s}=n;if(s)throw s;if(!i.session)throw new J;let o=i.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await ht(this.storage,this.storageKey));let{data:c,error:u}=await S(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:ve});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(n){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(n))return this._returnResult({data:{user:null},error:n});throw n}}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 J;let r=Date.now()/1e3,n=r,i=!0,s=null,{payload:o}=Ur(e.access_token);if(o.exp&&(n=o.exp,i=n<=r),i){let{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};s=a;}else {let{data:a,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});s={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s);}return this._returnResult({data:{user:s.user,session:s},error:null})}catch(r){if(v(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 n;if(!e){let{data:o,error:a}=r;if(a)throw a;e=(n=o.session)!==null&&n!==void 0?n:void 0;}if(!e?.refresh_token)throw new J;let{data:i,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):i?this._returnResult({data:{user:i.user,session:i},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(v(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!q())throw new lt("No browser detected.");if(e.error||e.error_description||e.error_code)throw new lt(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 jr("Not a valid PKCE flow url.");break;case "pkce":if(this.flowType==="implicit")throw new lt("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 jr("No code detected.");let{data:w,error:y}=await this._exchangeCodeForSession(e.code);if(y)throw y;let I=new URL(window.location.href);return I.searchParams.delete("code"),window.history.replaceState(window.history.state,"",I.toString()),{data:{session:w.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:i,access_token:s,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!s||!a||!o||!c)throw new lt("No session defined in URL");let u=Math.round(Date.now()/1e3),d=parseInt(a),p=u+d;l&&(p=parseInt(l));let h=p-u;h*1e3<=ot&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${h}s, should have been closer to ${d}s`);let f=p-d;u-f>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",f,p,u):u-f<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",f,p,u);let{data:m,error:_}=await this._getUser(s);if(_)throw _;let b={provider_token:n,provider_refresh_token:i,access_token:s,expires_in:d,expires_at:p,refresh_token:o,token_type:c,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:b,redirectType:e.type},error:null})}catch(n){if(v(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){let r=await Je(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 n;let{data:i,error:s}=r;if(s&&!Mr(s))return this._returnResult({error:s});let o=(n=i.session)===null||n===void 0?void 0:n.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(bc(a)&&(a.status===404||a.status===401||a.status===403)||Mr(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await z(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=Pc(),n={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,n),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r);})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,i;try{let{data:{session:s},error:o}=r;if(o)throw o;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s);}catch(s){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",s),Mr(s)?console.warn(s):console.error(s);}})}async resetPasswordForEmail(e,r={}){let n=null,i=null;this.flowType==="pkce"&&([n,i]=await ht(this.storage,this.storageKey,true));try{return await S(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:i,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(s){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(s))return this._returnResult({data:null,error:s});throw s}}async getUserIdentities(){var e;try{let{data:r,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(v(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{let{data:n,error:i}=await this._useSession(async s=>{var o,a,l,c,u;let{data:d,error:p}=s;if(p)throw p;let h=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 S(this.fetch,"GET",h,{headers:this.headers,jwt:(u=(c=d.session)===null||c===void 0?void 0:c.access_token)!==null&&u!==void 0?u:void 0})});if(i)throw i;return q()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n?.url),this._returnResult({data:{provider:e.provider,url:n?.url},error:null})}catch(n){if(v(n))return this._returnResult({data:{provider:e.provider,url:null},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var n;try{let{error:i,data:{session:s}}=r;if(i)throw i;let{options:o,provider:a,token:l,access_token:c,nonce:u}=e,d=await S(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=s?.access_token)!==null&&n!==void 0?n:void 0,body:{provider:a,id_token:l,access_token:c,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:de}),{data:p,error:h}=d;return h?this._returnResult({data:{user:null,session:null},error:h}):!p||!p.session||!p.user?this._returnResult({data:{user:null,session:null},error:new Oe}):(p.session&&(await this._saveSession(p.session),await this._notifyAllSubscribers("USER_UPDATED",p.session)),this._returnResult({data:p,error:h}))}catch(i){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,i;let{data:s,error:o}=r;if(o)throw o;return await S(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(n=s.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){let r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{let n=Date.now();return await Oc(async i=>(i>0&&await Ic(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await S(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:de})),(i,s)=>{let o=200*Math.pow(2,i);return s&&Kn(s)&&Date.now()+o-n<ot})}catch(n){if(this._debug(r,"error",n),v(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}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){let n=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",n),q()&&!r.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,r;let n="#_recoverAndRefresh()";this._debug(n,"begin");try{let i=await Je(this.storage,this.storageKey);if(i&&this.userStorage){let o=await Je(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:i.user},await pt(this.userStorage,this.storageKey+"-user",o)),i.user=(e=o?.user)!==null&&e!==void 0?e:Zn();}else if(i&&!i.user&&!i.user){let o=await Je(this.storage,this.storageKey+"-user");o&&o?.user?(i.user=o.user,await z(this.storage,this.storageKey+"-user"),await pt(this.storage,this.storageKey,i)):i.user=Zn();}if(this._debug(n,"session from storage",i),!this._isValidSession(i)){this._debug(n,"session is not valid"),i!==null&&await this._removeSession();return}let s=((r=i.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<Hn;if(this._debug(n,`session has${s?"":" not"} expired with margin of ${Hn}s`),s){if(this.autoRefreshToken&&i.refresh_token){let{error:o}=await this._callRefreshToken(i.refresh_token);o&&(console.error(o),Kn(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()));}}else if(i.user&&i.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:a}=await this._getUser(i.access_token);!a&&o?.user?(i.user=o.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(n,"could not get user data, skipping SIGNED_IN notification");}catch(o){console.error("Error getting user data:",o),this._debug(n,"error getting user data, skipping SIGNED_IN notification",o);}else await this._notifyAllSubscribers("SIGNED_IN",i);}catch(i){this._debug(n,"error",i),console.error(i);return}finally{this._debug(n,"end");}}async _callRefreshToken(e){var r,n;if(!e)throw new J;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Lr;let{data:s,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!s.session)throw new J;await this._saveSession(s.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",s.session);let a={data:s.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(s){if(this._debug(i,"error",s),v(s)){let o={data:null,error:s};return Kn(s)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw (n=this.refreshingDeferred)===null||n===void 0||n.reject(s),s}finally{this.refreshingDeferred=null,this._debug(i,"end");}}async _notifyAllSubscribers(e,r,n=true){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",r,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:r});let s=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r);}catch(l){s.push(l);}});if(await Promise.all(o),s.length>0){for(let a=0;a<s.length;a+=1)console.error(s[a]);throw s[0]}}finally{this._debug(i,"end");}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=true,await z(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),n=r.user&&r.user.__isUserNotAvailableProxy===true;if(this.userStorage){!n&&r.user&&await pt(this.userStorage,this.storageKey+"-user",{user:r.user});let i=Object.assign({},r);delete i.user;let s=Ms(i);await pt(this.storage,this.storageKey,s);}else {let i=Ms(r);await pt(this.storage,this.storageKey,i);}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=false,await z(this.storage,this.storageKey),await z(this.storage,this.storageKey+"-code-verifier"),await z(this.storage,this.storageKey+"-user"),this.userStorage&&await z(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null);}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&q()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e);}catch(r){console.error("removing visibilitychange callback failed",r);}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),ot);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let 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()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let 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{let e=Date.now();try{return await this._useSession(async r=>{let{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((n.expires_at*1e3-e)/ot);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${ot}ms, refresh threshold is ${Fn} ticks`),i<=Fn&&await this._callRefreshToken(n.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.isAcquireTimeout||e instanceof Wr)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!q()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),false;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1);}catch(e){this._debug("#visibilityChangedCallback","error",e);}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0);}catch(e){console.error("_handleVisibilityChange",e);}}async _onVisibilityChanged(e){let 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,n){let i=[`provider=${encodeURIComponent(r)}`];if(n?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n?.scopes&&i.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){let[s,o]=await ht(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString());}if(n?.queryParams){let s=new URLSearchParams(n.queryParams);i.push(s.toString());}return n?.skipBrowserRedirect&&i.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var n;let{data:i,error:s}=r;return s?this._returnResult({data:null,error:s}):await S(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,i;let{data:s,error:o}=r;if(o)return this._returnResult({data:null,error:o});let 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 S(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((i=l?.totp)===null||i===void 0)&&i.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(v(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 n;let{data:i,error:s}=r;if(s)return this._returnResult({data:null,error:s});let o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Qc(e.webauthn.credential_response):eu(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await S(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.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(v(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 n;let{data:i,error:s}=r;if(s)return this._returnResult({data:null,error:s});let o=await S(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;let{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:Xc(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:Zc(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:n}=await this.getUser();if(n)return {data:null,error:n};let i={all:[],phone:[],totp:[],webauthn:[]};for(let s of (e=r?.factors)!==null&&e!==void 0?e:[])i.all.push(s),s.status==="verified"&&i[s.factor_type].push(s);return {data:i,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,n,i,s;if(e)try{let{payload:h}=Ur(e),f=null;h.aal&&(f=h.aal);let m=f,{data:{user:_},error:b}=await this.getUser(e);if(b)return this._returnResult({data:null,error:b});((n=(r=_?.factors)===null||r===void 0?void 0:r.filter(I=>I.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(m="aal2");let y=h.amr||[];return {data:{currentLevel:f,nextLevel:m,currentAuthenticationMethods:y},error:null}}catch(h){if(v(h))return this._returnResult({data:null,error:h});throw h}let{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};let{payload:l}=Ur(o.access_token),c=null;l.aal&&(c=l.aal);let u=c;((s=(i=o.user.factors)===null||i===void 0?void 0:i.filter(h=>h.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(u="aal2");let p=l.amr||[];return {data:{currentLevel:c,nextLevel:u,currentAuthenticationMethods:p},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?await S(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new J})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:i},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!i)return this._returnResult({data:null,error:new J});let o=await S(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&q()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if(v(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:i},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!i)return this._returnResult({data:null,error:new J});let o=await S(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&q()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if(v(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;return n?this._returnResult({data:null,error:n}):r?await S(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new J})})}catch(e){if(v(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?(await S(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new J})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(a=>a.kid===e);if(n)return n;let i=Date.now();if(n=this.jwks.keys.find(a=>a.kid===e),n&&this.jwks_cached_at+kc>i)return n;let{data:s,error:o}=await S(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return !s.keys||s.keys.length===0||(this.jwks=s,this.jwks_cached_at=i,n=s.keys.find(a=>a.kid===e),!n)?null:n}async getClaims(e,r={}){try{let n=e;if(!n){let{data:h,error:f}=await this.getSession();if(f||!h.session)return this._returnResult({data:null,error:f});n=h.session.access_token;}let{header:i,payload:s,signature:o,raw:{header:a,payload:l}}=Ur(n);r?.allowExpired||Nc(s.exp);let c=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!c){let{error:h}=await this.getUser(n);if(h)throw h;return {data:{claims:s,header:i,signature:o},error:null}}let u=jc(i.alg),d=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,d,o,Rc(`${a}.${l}`)))throw new ct("Invalid JWT signature");return {data:{claims:s,header:i,signature:o},error:null}}catch(n){if(v(n))return this._returnResult({data:null,error:n});throw n}}};ni.nextInstanceID={};Gs=ni;});var ru=R(()=>{ei();});var Jm,Xs,nu=R(()=>{Ys();Jm=Gs,Xs=Jm;});var Zs=R(()=>{ei();Ys();ru();nu();Bs();ut();qs();});function Hr(t){"@babel/helpers - typeof";return Hr=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},Hr(t)}function Qm(t,e){if(Hr(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(Hr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(t)}function e_(t){var e=Qm(t,"string");return Hr(e)=="symbol"?e:e+""}function t_(t,e,r){return (e=e_(e))in t?Object.defineProperty(t,e,{value:r,enumerable:true,configurable:true,writable:true}):t[e]=r,t}function iu(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n);}return r}function W(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?iu(Object(r),true).forEach(function(n){t_(t,n,r[n]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):iu(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n));});}return t}function s_(t){return t.endsWith("/")?t:t+"/"}function o_(t,e){var r,n;let{db:i,auth:s,realtime:o,global:a}=t,{db:l,auth:c,realtime:u,global:d}=e,p={db:W(W({},l),i),auth:W(W({},c),s),realtime:W(W({},u),o),storage:{},global:W(W(W({},d),a),{},{headers:W(W({},(r=d?.headers)!==null&&r!==void 0?r:{}),(n=a?.headers)!==null&&n!==void 0?n:{})}),accessToken:async()=>""};return t.accessToken?p.accessToken=t.accessToken:delete p.accessToken,p}function a_(t){let e=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(s_(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}function u_(){if(typeof window<"u")return false;let t=globalThis.process;if(!t)return false;let e=t.version;if(e==null)return false;let r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:false}var Km,Fr,Vm,Gm,Ym,Xm,Zm,r_,n_,i_,l_,c_,Zt,ii=R(()=>{$l();Fl();As();gc();Zs();As();Zs();Km="2.103.2",Fr="";typeof Deno<"u"?Fr="deno":typeof document<"u"?Fr="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Fr="react-native":Fr="node";Vm={"X-Client-Info":`supabase-js-${Fr}/${Km}`},Gm={headers:Vm},Ym={schema:"public"},Xm={autoRefreshToken:true,persistSession:true,detectSessionInUrl:true,flowType:"implicit"},Zm={};r_=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),n_=()=>Headers,i_=(t,e,r)=>{let n=r_(r),i=n_();return async(s,o)=>{var a;let l=(a=await e())!==null&&a!==void 0?a:t,c=new i(o?.headers);return c.has("apikey")||c.set("apikey",t),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),n(s,W(W({},o),{},{headers:c}))}};l_=class extends Xs{constructor(t){super(t);}},c_=class{constructor(t,e,r){var n,i;this.supabaseUrl=t,this.supabaseKey=e;let s=a_(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",s),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",s),this.storageUrl=new URL("storage/v1",s),this.functionsUrl=new URL("functions/v1",s);let o=`sb-${s.hostname.split(".")[0]}-auth-token`,a={db:Ym,realtime:Zm,auth:W(W({},Xm),{},{storageKey:o}),global:Gm},l=o_(r??{},a);if(this.storageKey=(n=l.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=l.global.headers)!==null&&i!==void 0?i:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(u,d)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} 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=i_(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(W({headers:this.headers,accessToken:this._getAccessToken.bind(this)},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 Wl(new URL("rest/v1",s).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new fc(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents();}get functions(){return new yr(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:false,get:false,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();let{data:n}=await t.auth.getSession();return (e=(r=n.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:n,userStorage:i,storageKey:s,flowType:o,lock:a,debug:l,throwOnError:c},u,d){let p={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new l_({url:this.authUrl.href,headers:W(W({},p),u),storageKey:s,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,flowType:o,lock:a,debug:l,throwOnError:c,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(h=>h.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Jt(this.realtimeUrl.href,W(W({},t),{},{params:W(W({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",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);}},Zt=(t,e,r)=>new c_(t,e,r);u_()&&console.warn("\u26A0\uFE0F 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");});function Se(t){let e=t.SUPABASE_URL??t.VITE_SUPABASE_URL??"https://xygyyikpgykarmqujajf.supabase.co",r=t.SUPABASE_ANON_KEY??t.VITE_SUPABASE_ANON_KEY??"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inh5Z3l5aWtwZ3lrYXJtcXVqYWpmIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzYyMjIyOTcsImV4cCI6MjA5MTc5ODI5N30.y_SPm1eJeofb4zYgPCogTJUPr4e7-z92BzcRzqQiK9g";if(!e||!r)throw new Qs("missing_supabase_config","Missing Supabase client configuration for CLI login.");return {supabaseUrl:e,supabaseAnonKey:r}}var Qs,si=R(()=>{Qs=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="CliAuthConfigError";}code};});async function au(t){let e=Se(t.env),r=f_(),n=Zt(e.supabaseUrl,e.supabaseAnonKey,{auth:{persistSession:true,detectSessionInUrl:false,flowType:"pkce",storage:r}}),i=await g_({timeoutMs:t.timeoutMs??300*1e3}),s=i.redirectUri;try{let{data:o,error:a}=await n.auth.signInWithOAuth({provider:"github",options:{redirectTo:s,skipBrowserRedirect:!0}});if(a||!o.url)throw new G("oauth_start_failed",a?.message??"Supabase did not return an OAuth URL.");t.onOpen?.({url:o.url,redirectUri:s}),await t.openUrl(o.url);let l=await i.waitForCode(),{data:c,error:u}=await n.auth.exchangeCodeForSession(l);if(u||!c.session?.access_token||!c.session.refresh_token)throw new G("oauth_exchange_failed",u?.message??"Supabase did not return a complete session.");let d=await p_(n,c.session,t.promptMfaCode),p=lu(e.supabaseUrl);return await nt(t.env).set(p,JSON.stringify(d)),{session:d,account:p}}finally{await i.close();}}async function p_(t,e,r){let{data:n,error:i}=await t.auth.mfa.getAuthenticatorAssuranceLevel();if(i)throw new G("mfa_check_failed",i.message);if(n.currentLevel===n.nextLevel||n.nextLevel!=="aal2")return h_(e);let{data:s,error:o}=await t.auth.mfa.listFactors();if(o)throw new G("mfa_factor_lookup_failed",o.message);let a=s.totp.find(d=>d.status==="verified");if(!a)throw new G("mfa_factor_missing","Two-factor authentication is enabled, but no verified TOTP factor was returned.");if(!r)throw new G("mfa_required","Two-factor authentication is required for this account.");let l=(await r("Authenticator code: ")).trim(),{data:c,error:u}=await t.auth.mfa.challengeAndVerify({factorId:a.id,code:l});if(u||!c)throw new G("mfa_verify_failed",u?.message??"Two-factor authentication failed.");return {access_token:c.access_token,refresh_token:c.refresh_token,expires_at:Math.floor(Date.now()/1e3)+c.expires_in,expires_in:c.expires_in,token_type:c.token_type,user:{id:c.user.id,email:c.user.email??void 0}}}function h_(t){return {access_token:t.access_token,refresh_token:t.refresh_token,expires_at:t.expires_at??Math.floor(Date.now()/1e3)+(t.expires_in??3600),expires_in:t.expires_in??void 0,token_type:t.token_type,user:{id:t.user.id,email:t.user.email??void 0}}}async function eo(t){let e=Se(t.env),r=await su(t.fetch,e,"auth-device-start",{});t.onPending?.({userCode:r.user_code,verificationUri:r.verification_uri,interval:r.interval});let n=Date.now()+r.expires_in*1e3,i=r.interval;for(;Date.now()<=n;){await t.sleep(i*1e3);let s=await su(t.fetch,e,"auth-device-token",{device_code:r.device_code},{acceptError:true});if("access_token"in s){let o=lu(e.supabaseUrl);return await nt(t.env).set(o,JSON.stringify(s)),{session:s,account:o}}switch(s.error){case "authorization_pending":i=s.interval??i;break;case "slow_down":i=s.interval??Math.min(i+5,30);break;case "expired_token":throw new Ne("expired_token","The device login code expired.");case "access_denied":throw new Ne("access_denied","The device login request was denied.");default:throw new Ne(s.error,`Device login failed: ${s.error}`)}}throw new Ne("expired_token","The device login code expired.")}function lu(t){let e=new URL(t).hostname;return `sb-${e.endsWith(".supabase.co")?e.slice(0,-12):e}-auth-token`}async function su(t,e,r,n,i={}){let s=await t(`${e.supabaseUrl}/functions/v1/${r}`,{method:"POST",headers:{"content-type":"application/json",apikey:e.supabaseAnonKey},body:JSON.stringify(n)}),o=await s.json().catch(()=>({}));if(!s.ok&&!i.acceptError)throw new Ne(o.error??"request_failed");return o}function f_(){let t=new Map;return {getItem:e=>t.get(e)??null,setItem:(e,r)=>{t.set(e,r);},removeItem:e=>{t.delete(e);}}}async function g_(t){let e=null,r=null,n=false,i=new Promise((l,c)=>{e=l,r=c;}),s=createServer((l,c)=>{m_(l,c,(u,d)=>{n||(n=true,u?r?.(u):e?.(d));});});await new Promise((l,c)=>{s.once("error",c),s.listen(0,"127.0.0.1",()=>{s.off("error",c),l();});});let o=s.address();if(!o||typeof o=="string")throw await ou(s),new G("callback_server_failed");let a=setTimeout(()=>{n||(n=true,r?.(new G("oauth_timeout","Browser login timed out.")));},t.timeoutMs);return {redirectUri:`http://127.0.0.1:${o.port}/auth/callback`,waitForCode:()=>i,close:async()=>{clearTimeout(a),await ou(s);}}}function m_(t,e,r){let n=t.headers.host??"127.0.0.1",i=new URL(t.url??"/",`http://${n}`);if(i.pathname!=="/auth/callback"){e.writeHead(404,{"content-type":"text/plain"}),e.end("Not found");return}let s=i.searchParams.get("error")??i.searchParams.get("error_description"),o=i.searchParams.get("code");if(s){e.writeHead(400,{"content-type":"text/plain"}),e.end("Pathrule login failed. You can close this window."),r(new G("oauth_denied",s),"");return}if(!o){e.writeHead(400,{"content-type":"text/plain"}),e.end("Pathrule login could not verify this browser response."),r(new G("oauth_invalid_callback"),"");return}e.writeHead(200,{"content-type":"text/html; charset=utf-8"}),e.end("<!doctype html><title>Pathrule CLI</title><p>Pathrule CLI is signed in. You can close this window.</p>"),r(null,o);}async function ou(t){t.listening&&await new Promise(e=>t.close(()=>e()));}var Ne,G,oi=R(()=>{ms();ii();si();si();Ne=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="DeviceLoginError";}code},G=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="BrowserLoginError";}code};});async function S_(t){await new Promise(e=>setTimeout(e,t));}async function C_(t){try{await mkdir(dirname(t),{recursive:!0,mode:448}),await chmod(dirname(t),448).catch(()=>{});let e=await open(t,"wx",384);await e.writeFile(`${process.pid}:${Date.now()}
|
|
48
|
-
`,"utf8"),await e.close();let r=!1;return async()=>{r||(r=!0,await rm$1(t,{force:!0}).catch(()=>{}));}}catch(e){if(e.code==="EEXIST")return null;throw e}}async function E_(t,e){try{let{stat:r}=await import('fs/promises'),n=await r(t);Date.now()-n.mtimeMs>e&&await rm$1(t,{force:!0});}catch{}}async function du(t,e={}){let r=e.timeoutMs??k_,n=e.staleMs??b_,i=e.lockFile??A(e.env).tokenLockFile,s=Date.now()+r;for(;Date.now()<=s;){let o=await C_(i);if(o)try{return await t()}finally{await o();}await E_(i,n),await S_(v_);}throw new to}var k_,b_,v_,to,pu=R(()=>{K();k_=15e3,b_=45e3,v_=100,to=class extends Error{constructor(){super("token_refresh_lock_timeout"),this.name="TokenRefreshLockTimeoutError";}};});async function ne(t,e=process.env){let r=rt(t,0,e);try{let n=await readFile(r.userConfigFile,"utf8"),i=JSON.parse(n);if(i&&typeof i=="object"&&i.schema_version===1)return i}catch(n){if(n.code!=="ENOENT")throw n}return {schema_version:1}}async function ai(t,e,r=process.env){let n=rt(t,0,r);await mu(n.userConfigFile,{...e,schema_version:1});}async function ie(t,e,r=process.env){let i={...await ne(t,r),...e,schema_version:1};return await ai(t,i,r),i}async function fu(t,e=process.env){let r=A(e),n={user_id:t,updated_at:new Date().toISOString()};await mu(r.activeUserFile,n);}async function gu(t=process.env){await rm$1(A(t).activeUserFile,{force:true});}async function mu(t,e){let r=dirname(t);await mkdir(r,{recursive:true,mode:D}),await chmod(r,D).catch(()=>{});let n=`${t}.tmp`;await writeFile(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:O}),await chmod(n,O).catch(()=>{}),await rename(n,t);}var Ke=R(()=>{K();});function _u(t){return t.startsWith($_)&&t.endsWith(N_)}async function Ce(t=process.env){let e=await wu(t);return !e||!yu(e.session)?e:D_(e,t)}async function wu(t=process.env){let r=await nt(t).findAll();for(let n of r)if(_u(n.account))try{let i=JSON.parse(n.value);if(!i.access_token||!i.refresh_token||!i.user?.id)continue;return {account:n.account,session:i}}catch{}return null}function yu(t){return t.expires_at<=Math.floor(Date.now()/1e3)+j_}async function D_(t,e){return du(async()=>{let r=await wu(e);if(r&&!yu(r.session))return r;let n=Se(e),i=Zt(n.supabaseUrl,n.supabaseAnonKey,{auth:{persistSession:!1}}),{data:s,error:o}=await i.auth.refreshSession({refresh_token:t.session.refresh_token});if(o)throw new li("refresh_failed",o.message);if(!s.session?.access_token||!s.session.refresh_token||!s.session.user?.id)throw new li("refresh_failed","Supabase did not return a complete session.");let a={access_token:s.session.access_token,refresh_token:s.session.refresh_token,expires_at:s.session.expires_at??Math.floor(Date.now()/1e3)+(s.session.expires_in??3600),user:{id:s.session.user.id,email:s.session.user.email??void 0}};return await nt(e).set(t.account,JSON.stringify(a)),{account:t.account,session:a}},{env:e})}async function ro(t=process.env){let e=nt(t),r=await e.findAll(),n=new Set,i=0;for(let o of r)if(_u(o.account)){try{let a=JSON.parse(o.value);a.user?.id&&n.add(a.user.id);}catch{}await e.delete(o.account)&&(i+=1);}let s=0;for(let o of n)await rm$1(rt(o,0,t).userCacheDir,{recursive:true,force:true}),s+=1;return await gu(t),{removed_sessions:i,purged_user_caches:s}}var $_,N_,j_,li,qr=R(()=>{pu();Ke();ms();K();ii();si();$_="sb-",N_="-auth-token",j_=60,li=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="CliSessionError";}code};});async function C(t=process.env){let e=await Ce(t);if(!e)throw new Qt("not_authenticated","Pathrule CLI is not signed in.");let r=Se(t);return {session:e.session,supabase:Zt(r.supabaseUrl,r.supabaseAnonKey,{auth:{persistSession:false},global:{headers:{Authorization:`Bearer ${e.session.access_token}`}}})}}var Qt,F=R(()=>{ii();oi();qr();Qt=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="CliAuthError";}code};});var Nu={};sf(Nu,{cliOrgWebUrl:()=>ee,currentCliOrg:()=>j,listCliOrgs:()=>_e,useCliOrg:()=>di});async function _e(t){let{session:e,supabase:r}=await C(t),{data:n,error:i}=await r.from("organization_members").select("role, organization:organizations ( id, name, slug, plan, subscription_status, trial_status, trial_ends_at, seat_count, paid_extra_seats, trial_seat_cap, beta_referral_credit_cents, beta_referral_activated_count, beta_referral_founder )").eq("user_id",e.user.id);if(i)throw i;let s=await ne(e.user.id,t),o=[],a=new Set;for(let l of n??[]){let c=l.organization,u=Array.isArray(c)?c[0]:c;if(!u||a.has(u.id))continue;a.add(u.id);let d=u.subscription_status?String(u.subscription_status):null,p=u.trial_status?String(u.trial_status):null,h=u.trial_ends_at?String(u.trial_ends_at):null,f=Q_(d,p,h);o.push({id:u.id,name:u.name,slug:u.slug,plan:u.plan,subscription_status:d,trial_status:p,trial_ends_at:h,seat_count:Ve(u.seat_count),paid_extra_seats:Ve(u.paid_extra_seats),trial_seat_cap:Ve(u.trial_seat_cap),beta_referral_credit_cents:Ve(u.beta_referral_credit_cents)??0,beta_referral_activated_count:Ve(u.beta_referral_activated_count)??0,beta_referral_founder:u.beta_referral_founder===true,role:l.role,current:s.current_org_id===u.id,billing:{status:d,freeze_kind:f.kind,freeze_reason:f.reason,seats:{active:Ve(u.seat_count),trial_cap:Ve(u.trial_seat_cap),paid_extra:Ve(u.paid_extra_seats)}}});}if(!s.current_org_id&&o.length===1){let l=o[0];l&&(o[0]={...l,current:true});}return o}async function j(t){let e=await _e(t);return e.find(r=>r.current)??e[0]??null}async function di(t,e){let{session:r}=await C(e),i=(await _e(e)).find(s=>s.id===t||s.slug===t);if(!i)throw new Error("org_not_found");return await ie(r.user.id,{current_org_id:i.id},e),await fu(r.user.id,e),{...i,current:true}}function ee(t,e,r="home"){let i=`${(e.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"")}/org/${encodeURIComponent(t.slug)}`;return r==="home"?i:r==="billing"?`${i}/billing`:`${i}/settings${r==="members"?"/members":""}`}function Ve(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function Q_(t,e,r){return t==="unpaid"||t==="past_due"?{kind:"subscription",reason:"unpaid"}:t==="canceled"?e==="expired"||r&&new Date(r).getTime()<Date.now()?{kind:"subscription",reason:"trial_expired"}:{kind:"subscription",reason:"canceled"}:{kind:"none",reason:null}}var Ee=R(()=>{Ke();F();});af(Ma());function La(t,e,r){return `${e}/.claude.json`}var fr="pathrule";function Xi(t){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new Error("Claude config root must be a JSON object");let e=t;if(e.mcpServers!==void 0&&(typeof e.mcpServers!="object"||e.mcpServers===null||Array.isArray(e.mcpServers)))throw new Error("Claude config `mcpServers` must be an object");return e}function Ua(t,e){let r=Xi(t),n={...r.mcpServers??{}},i=!(fr in n);return n[fr]=e,{config:{...r,mcpServers:n},wasNew:i}}function Wa(t){let e=Xi(t);if(!e.mcpServers||!(fr in e.mcpServers))return {config:e,wasPresent:false};let{[fr]:r,...n}=e.mcpServers;return {config:{...e,mcpServers:n},wasPresent:true}}function Ba(t){try{return Xi(t).mcpServers?.[fr]??null}catch{return null}}function B(t){return t.code==="PGRST116"?{code:"not_found",message:t.message}:t.code==="42501"?{code:"permission_denied",message:t.message}:{code:"upstream_error",message:t.message}}async function Nt(t,e){let{data:r,error:n}=await t.rpc("pathrule_check_content_dedup",{p_workspace_id:e.workspaceId,p_kind:e.kind,p_node_id:e.kind==="memory"?e.nodeId??null:null,p_candidate:e.candidate,p_threshold:e.threshold??.65,p_max_similar:e.maxSimilar??5,p_exclude_id:e.excludeId??null});if(n)return {ok:false,error:n.message};let i=r??{duplicate:null,similar:[]};return {ok:true,data:{duplicate:i.duplicate,similar:(i.similar??[]).map(s=>({id:s.id,title:s.title,similarity:typeof s.similarity=="string"?Number(s.similarity):s.similarity}))}}}function Fa(t){return t.code!=="23505"?false:!!t.message?.includes("skills_workspace_slug_unique")}async function Zi(t,e,r){let{data:n,error:i}=await t.from("nodes").select("id, workspace_id, parent_id, name, type, relative_path").eq("workspace_id",e).eq("relative_path","/").is("parent_id",null).maybeSingle();if(i)return {error:i.message};if(n)return n;let{data:s,error:o}=await t.from("nodes").insert({workspace_id:e,parent_id:null,name:r,type:"folder",relative_path:"/",order_index:0,status:"active"}).select("id, workspace_id, parent_id, name, type, relative_path").single();if(o||!s){if(o?.code==="23505"){let{data:a}=await t.from("nodes").select("id, workspace_id, parent_id, name, type, relative_path").eq("workspace_id",e).eq("relative_path","/").is("parent_id",null).maybeSingle();if(a)return a}return {error:o?.message??"Root node insert failed"}}return s}function Ha(t){let e=t.trim();if(e===""||e==="/")return "/";let n=(e.startsWith("/")?e:"/"+e).replace(/\/+/g,"/");return n==="/"?"/":n.replace(/\/$/,"")}function cf(t,e){return (t==="/"?"":t)+"/"+e.trim()}function uf(t){let e=t.split("/").filter(n=>n.length>0),r=e[e.length-1]??"";return /\.[A-Za-z0-9]{1,8}$/.test(r)?"file":"folder"}async function jt(t,e,r){let{data:n,error:i}=await t.from("nodes").select("id, workspace_id, parent_id, name, type, relative_path").eq("workspace_id",e).eq("relative_path",r).maybeSingle();return i?{error:i.message}:n??null}async function df(t,e,r,n){let i=Ha(r);if(i==="/"){let d=await jt(t,e,"/");return d&&!("error"in d)?d:{error:"Workspace root node missing \u2014 call ensureWorkspaceRootNode first."}}let s=await jt(t,e,i);if(s&&!("error"in s)||s&&"error"in s)return s;let o=await jt(t,e,"/");if(!o)return {error:"Workspace root node missing \u2014 call ensureWorkspaceRootNode first."};if("error"in o)return o;let a=i.split("/").filter(d=>d.length>0),l=uf(i),c=o,u="";for(let d=0;d<a.length;d+=1){let p=a[d];u+="/"+p;let f=d===a.length-1?l:"folder",m=await jt(t,e,u);if(m&&"error"in m)return m;if(m){c=m;continue}let{count:_}=await t.from("nodes").select("*",{count:"exact",head:true}).eq("workspace_id",e).eq("parent_id",c.id),{data:b,error:w}=await t.from("nodes").insert({workspace_id:e,parent_id:c.id,name:p,type:f,relative_path:cf(c.relative_path,p),order_index:_??0,status:"active"}).select("id, workspace_id, parent_id, name, type, relative_path").single();if(w||!b){if(w?.code==="23505"){let y=await jt(t,e,u);if(y&&!("error"in y)){c=y;continue}}return {error:w?.message??`Insert failed at ${u}`}}c=b;}return c}async function Dt(t,e,r,n){let i=Ha(r),s=await jt(t,e,"/");if(s&&"error"in s)return s;if(!s){let{data:o,error:a}=await t.from("workspaces").select("name").eq("id",e).maybeSingle();if(a)return {error:a.message};let l=o?.name??"Workspace",c=await Zi(t,e,l);if("error"in c)return c}return df(t,e,i)}function qa(t){return {id:t.id,workspaceId:t.workspace_id,nodeId:t.node_id,title:t.title,content:t.content,source:t.source,semanticTags:t.semantic_tags??[],versionId:t.version_id,versionNumber:t.version_number,createdBy:t.created_by,lastEditedBy:t.last_edited_by,lastEditedAt:t.last_edited_at,createdAt:t.created_at,updatedAt:t.updated_at}}function pf(t){return t.length===0?null:{code:"similar_titles",message:`Found ${t.length} memory/rule(s) with a similar title.`,detail:{similar:t}}}async function za(t,e){if(!t.workspaceId)return {ok:false,error:{code:"invalid_args",message:"ctx.workspaceId is required for path-based writes"}};let r=await Dt(t.supabase,t.workspaceId,e.node_path);if("error"in r)return {ok:false,error:{code:"upstream_error",message:r.error}};let n=e.title.trim(),i=await Nt(t.supabase,{workspaceId:r.workspace_id,kind:"memory",nodeId:r.id,candidate:n});if(i.ok&&i.data.duplicate&&!e.allow_duplicate)return {ok:false,error:{code:"duplicate",message:`A memory titled "${i.data.duplicate.title}" already exists at ${e.node_path}. Use update_memory, pick a different title, or pass allow_duplicate: true to insert anyway.`,detail:{existing_id:i.data.duplicate.id,existing_title:i.data.duplicate.title,similar:i.ok?i.data.similar:[]}}};let{data:s,error:o}=await t.supabase.from("memories").insert({workspace_id:r.workspace_id,node_id:r.id,title:n,content:e.content,source:e.source??"claude",created_by:t.userId,last_edited_by:t.userId}).select("*").single();if(o||!s)return {ok:false,error:B(o??{message:"insert failed"})};let a=i.ok?pf(i.data.similar):null;return a?{ok:true,data:qa(s),warnings:[a]}:{ok:true,data:qa(s)}}function hf(t){return t.length===0?null:{code:"similar_titles",message:`Found ${t.length} rule(s) with a similar name.`,detail:{similar:t}}}function ff(t){return {id:t.id,workspaceId:t.workspace_id,name:t.name,content:t.content,scopeType:t.scope_type,priority:t.priority,semanticTags:t.semantic_tags??[],versionId:t.version_id,versionNumber:t.version_number,createdBy:t.created_by,lastEditedBy:t.last_edited_by,lastEditedAt:t.last_edited_at,createdAt:t.created_at,updatedAt:t.updated_at}}async function Ja(t,e){if(!t.workspaceId)return {ok:false,error:{code:"invalid_args",message:"ctx.workspaceId is required for path-based writes"}};let r=await Dt(t.supabase,t.workspaceId,e.node_path);if("error"in r)return {ok:false,error:{code:"upstream_error",message:r.error}};let n=e.name.trim(),i=await Nt(t.supabase,{workspaceId:r.workspace_id,kind:"rule",candidate:n});if(i.ok&&i.data.duplicate&&!e.allow_duplicate)return {ok:false,error:{code:"duplicate",message:`A rule named "${i.data.duplicate.title}" already exists in this workspace. Use update_rule, pick a different name, or pass allow_duplicate: true.`,detail:{existing_id:i.data.duplicate.id,existing_name:i.data.duplicate.title,similar:i.ok?i.data.similar:[]}}};let{data:s,error:o}=await t.supabase.from("rules").insert({workspace_id:r.workspace_id,name:n,content:e.content,scope_type:e.scope_type,priority:e.priority,created_by:t.userId,last_edited_by:t.userId}).select("*").single();if(o||!s)return {ok:false,error:B(o??{message:"insert failed"})};let a=ff(s),{error:l}=await t.supabase.from("node_rules").insert({node_id:r.id,rule_id:a.id});if(l)return await t.supabase.from("rules").delete().eq("id",a.id),{ok:false,error:{code:"upstream_error",message:`attach failed: ${l.message}`}};let c=i.ok?hf(i.data.similar):null;return c?{ok:true,data:a,warnings:[c]}:{ok:true,data:a}}function gf(t){return {id:t.id,workspaceId:t.workspace_id,name:t.name,description:t.description,content:t.content,source:t.source,githubUrl:t.github_url,version:t.version,tags:t.tags,semanticTags:t.semantic_tags??[],versionId:t.version_id,versionNumber:t.version_number,createdBy:t.created_by,lastEditedBy:t.last_edited_by,lastEditedAt:t.last_edited_at,createdAt:t.created_at,updatedAt:t.updated_at,contentFetchedAt:t.content_fetched_at}}async function Ka(t,e){if(!t.workspaceId)return {ok:false,error:{code:"invalid_args",message:"ctx.workspaceId is required for path-based writes"}};let r=await Dt(t.supabase,t.workspaceId,e.node_path);if("error"in r)return {ok:false,error:{code:"upstream_error",message:r.error}};let n=e.name.trim(),i=await Nt(t.supabase,{workspaceId:r.workspace_id,kind:"skill",candidate:n,maxSimilar:0});if(i.ok&&i.data.duplicate)return {ok:false,error:{code:"duplicate",message:`A skill with this name already exists in this workspace: "${i.data.duplicate.title}". Use update_skill or pick a different name.`,detail:{existing_id:i.data.duplicate.id,existing_name:i.data.duplicate.title}}};let s=e.source??"manual",{data:o,error:a}=await t.supabase.from("skills").insert({workspace_id:r.workspace_id,name:n,description:e.description,content:e.content,source:s,github_url:e.github_url??null,tags:e.tags??[],created_by:t.userId,last_edited_by:t.userId,content_fetched_at:s==="github_ref"?new Date().toISOString():null}).select("*").single();if(a||!o)return Fa(a??{})?{ok:false,error:{code:"duplicate",message:"A skill with this name already exists in this workspace. Use update_skill or pick a different name."}}:{ok:false,error:B(a??{message:"insert failed"})};let l=gf(o),{error:c}=await t.supabase.from("node_skills").insert({node_id:r.id,skill_id:l.id,is_active:true});return c?(await t.supabase.from("skills").delete().eq("id",l.id),{ok:false,error:{code:"upstream_error",message:`attach failed: ${c.message}`}}):{ok:true,data:l}}var mf=/^[A-Za-z0-9_-]+/,_f=/[\s([{'"`]/;function es(t){return t.trim().toLowerCase()}function Va(t){let e=yf(t),r=[];for(let n=0;n<e.length-2;n+=1){if(e[n]!==":"||e[n+1]!==":")continue;let i=n===0?"":e[n-1]??"";if(i&&!_f.test(i))continue;let s=e.slice(n+2).match(mf);if(!s?.[0])continue;let o=s[0];r.push({raw:o,name:es(o),start:n,end:n+2+o.length}),n+=1+o.length;}return wf(r)}function wf(t){let e=new Set,r=[];for(let n of t)e.has(n.name)||(e.add(n.name),r.push(n));return r}function yf(t){let e="",r=0,n=false,i=false;for(;r<t.length;){if(t.startsWith("```",r)){n=!n,e+=" ",r+=3;continue}let s=t[r]??"";if(!n&&s==="`"){i=!i,e+=" ",r+=1;continue}e+=n||i?s===`
|
|
46
|
+
${b}`}var Jc=R(()=>{});function Kc({error:t,options:e}){var r,n,i;let{publicKey:s}=e;if(!s)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new L({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if(t.name==="ConstraintError"){if(((r=s.authenticatorSelection)===null||r===void 0?void 0:r.requireResidentKey)===true)return new L({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if(e.mediation==="conditional"&&((n=s.authenticatorSelection)===null||n===void 0?void 0:n.userVerification)==="required")return new L({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:t});if(((i=s.authenticatorSelection)===null||i===void 0?void 0:i.userVerification)==="required")return new L({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 L({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if(t.name==="NotAllowedError")return new L({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="NotSupportedError")return s.pubKeyCredParams.filter(a=>a.type==="public-key").length===0?new L({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new L({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if(t.name==="SecurityError"){let o=window.location.hostname;if(Js(o)){if(s.rp.id!==o)return new L({message:`The RP ID "${s.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new L({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="TypeError"){if(s.user.id.byteLength<1||s.user.id.byteLength>64)return new L({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 L({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 L({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}function Vc({error:t,options:e}){let{publicKey:r}=e;if(!r)throw Error("options was missing required publicKey property");if(t.name==="AbortError"){if(e.signal instanceof AbortSignal)return new L({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else {if(t.name==="NotAllowedError")return new L({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if(t.name==="SecurityError"){let n=window.location.hostname;if(Js(n)){if(r.rpId!==n)return new L({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else return new L({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t})}else if(t.name==="UnknownError")return new L({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 L({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t})}var L,_t,Gc=R(()=>{Ks();L=class extends Error{constructor({message:e,code:r,cause:n,name:i}){var s;super(e,{cause:n}),this.__isWebAuthnError=true,this.name=(s=i??(n instanceof Error?n.name:void 0))!==null&&s!==void 0?s:"Unknown Error",this.code=r;}},_t=class extends L{constructor(e,r){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:r,message:e}),this.name="WebAuthnUnknownError",this.originalError=r;}};});function Xc(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);let{challenge:e,user:r,excludeCredentials:n}=t,i=it(t,["challenge","user","excludeCredentials"]),s=ze(e).buffer,o=Object.assign(Object.assign({},r),{id:ze(r.id).buffer}),a=Object.assign(Object.assign({},i),{challenge:s,user:o});if(n&&n.length>0){a.excludeCredentials=new Array(n.length);for(let l=0;l<n.length;l++){let c=n[l];a.excludeCredentials[l]=Object.assign(Object.assign({},c),{id:ze(c.id).buffer,type:c.type||"public-key",transports:c.transports});}}return a}function Zc(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);let{challenge:e,allowCredentials:r}=t,n=it(t,["challenge","allowCredentials"]),i=ze(e).buffer,s=Object.assign(Object.assign({},n),{challenge:i});if(r&&r.length>0){s.allowCredentials=new Array(r.length);for(let o=0;o<r.length;o++){let a=r[o];s.allowCredentials[o]=Object.assign(Object.assign({},a),{id:ze(a.id).buffer,type:a.type||"public-key",transports:a.transports});}}return s}function Qc(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t;return {id:t.id,rawId:t.id,response:{attestationObject:$e(new Uint8Array(t.response.attestationObject)),clientDataJSON:$e(new Uint8Array(t.response.clientDataJSON))},type:"public-key",clientExtensionResults:t.getClientExtensionResults(),authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function eu(t){var e;if("toJSON"in t&&typeof t.toJSON=="function")return t.toJSON();let r=t,n=t.getClientExtensionResults(),i=t.response;return {id:t.id,rawId:t.id,response:{authenticatorData:$e(new Uint8Array(i.authenticatorData)),clientDataJSON:$e(new Uint8Array(i.clientDataJSON)),signature:$e(new Uint8Array(i.signature)),userHandle:i.userHandle?$e(new Uint8Array(i.userHandle)):void 0},type:"public-key",clientExtensionResults:n,authenticatorAttachment:(e=r.authenticatorAttachment)!==null&&e!==void 0?e:void 0}}function Js(t){return t==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}function Yc(){var t,e;return !!(q()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.create)=="function"&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.get)=="function")}async function Um(t){try{let e=await navigator.credentials.create(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new _t("Browser returned unexpected credential type",e)}:{data:null,error:new _t("Empty credential response",e)}}catch(e){return {data:null,error:Kc({error:e,options:t})}}}async function Wm(t){try{let e=await navigator.credentials.get(t);return e?e instanceof PublicKeyCredential?{data:e,error:null}:{data:null,error:new _t("Browser returned unexpected credential type",e)}:{data:null,error:new _t("Empty credential response",e)}}catch(e){return {data:null,error:Vc({error:e,options:t})}}}function ri(...t){let e=i=>i!==null&&typeof i=="object"&&!Array.isArray(i),r=i=>i instanceof ArrayBuffer||ArrayBuffer.isView(i),n={};for(let i of t)if(i)for(let s in i){let o=i[s];if(o!==void 0)if(Array.isArray(o))n[s]=o;else if(r(o))n[s]=o;else if(e(o)){let a=n[s];e(a)?n[s]=ri(a,o):n[s]=ri(o);}else n[s]=o;}return n}function Hm(t,e){return ri(Bm,t,e||{})}function qm(t,e){return ri(Fm,t,e||{})}var Vs,Lm,Bm,Fm,ni,Ks=R(()=>{mr();Yn();ut();Yt();Gc();Vs=class{createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r);}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=new Error("Manually cancelling existing WebAuthn API call");e.name="AbortError",this.controller.abort(e),this.controller=void 0;}}},Lm=new Vs;Bm={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:false,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Fm={userVerification:"preferred",hints:["security-key"],attestation:"direct"};ni=class{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:n,signal:i},s){var o;try{let{data:a,error:l}=await this.client.mfa.challenge({factorId:e,webauthn:r});if(!a)return {data:null,error:l};let c=i??Lm.createNewAbortSignal();if(a.webauthn.type==="create"){let{user:u}=a.webauthn.credential_options.publicKey;if(!u.name){let d=n;if(d)u.name=`${u.id}:${d}`;else {let h=(await this.client.getUser()).data.user,f=((o=h?.user_metadata)===null||o===void 0?void 0:o.name)||h?.email||h?.id||"User";u.name=`${u.id}:${f}`;}}u.displayName||(u.displayName=u.name);}switch(a.webauthn.type){case "create":{let u=Hm(a.webauthn.credential_options.publicKey,s?.create),{data:d,error:p}=await Um({publicKey:u,signal:c});return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:p}}case "request":{let u=qm(a.webauthn.credential_options.publicKey,s?.request),{data:d,error:p}=await Wm(Object.assign(Object.assign({},a.webauthn.credential_options),{publicKey:u,signal:c}));return d?{data:{factorId:e,challengeId:a.id,webauthn:{type:a.webauthn.type,credential_response:d}},error:null}:{data:null,error:p}}}}catch(a){return v(a)?{data:null,error:a}:{data:null,error:new ue("Unexpected error in challenge",a)}}}async _verify({challengeId:e,factorId:r,webauthn:n}){return this.client.mfa.verify({factorId:r,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},s){if(!r)return {data:null,error:new qe("rpId is required for WebAuthn authentication")};try{if(!Yc())return {data:null,error:new ue("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this.challenge({factorId:e,webauthn:{rpId:r,rpOrigins:n},signal:i},{request:s});if(!o)return {data:null,error:a};let{webauthn:l}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:l.type,rpId:r,rpOrigins:n,credential_response:l.credential_response}})}catch(o){return v(o)?{data:null,error:o}:{data:null,error:new ue("Unexpected error in authenticate",o)}}}async _register({friendlyName:e,webauthn:{rpId:r=typeof window<"u"?window.location.hostname:void 0,rpOrigins:n=typeof window<"u"?[window.location.origin]:void 0,signal:i}={}},s){if(!r)return {data:null,error:new qe("rpId is required for WebAuthn registration")};try{if(!Yc())return {data:null,error:new ue("Browser does not support WebAuthn",null)};let{data:o,error:a}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(u=>{var d;return (d=u.data)===null||d===void 0?void 0:d.all.find(p=>p.factor_type==="webauthn"&&p.friendly_name===e&&p.status!=="unverified")}).then(u=>u?this.client.mfa.unenroll({factorId:u?.id}):void 0),{data:null,error:a};let{data:l,error:c}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:r,rpOrigins:n},signal:i},{create:s});return l?this._verify({factorId:o.id,challengeId:l.challengeId,webauthn:{rpId:r,rpOrigins:n,type:l.webauthn.type,credential_response:l.webauthn.credential_response}}):{data:null,error:c}}catch(o){return v(o)?{data:null,error:o}:{data:null,error:new ue("Unexpected error in register",o)}}}};});async function tu(t,e,r){return await r()}var zm,Xt,ii,Gs,Ys=R(()=>{ti();zn();ut();Ws();Yt();Wc();qs();Fc();Ns();Yn();Jc();Ks();Bc();zm={url:mc,storageKey:_c,autoRefreshToken:true,persistSession:true,detectSessionInUrl:true,headers:wc,flowType:"implicit",debug:false,hasCustomAuthorizationHeader:false,throwOnError:false,lockAcquireTimeout:5e3,skipAutoInitialize:false};Xt={},ii=class t{get jwks(){var e,r;return (r=(e=Xt[this.storageKey])===null||e===void 0?void 0:e.jwks)!==null&&r!==void 0?r:{keys:[]}}set jwks(e){Xt[this.storageKey]=Object.assign(Object.assign({},Xt[this.storageKey]),{jwks:e});}get jwks_cached_at(){var e,r;return (r=(e=Xt[this.storageKey])===null||e===void 0?void 0:e.cachedAt)!==null&&r!==void 0?r:Number.MIN_SAFE_INTEGER}set jwks_cached_at(e){Xt[this.storageKey]=Object.assign(Object.assign({},Xt[this.storageKey]),{cachedAt:e});}constructor(e){var r,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=true,this.hasCustomAuthorizationHeader=false,this.suppressGetSessionWarning=false,this.lockAcquired=false,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let s=Object.assign(Object.assign({},zm),e);if(this.storageKey=s.storageKey,this.instanceID=(r=t.nextInstanceID[this.storageKey])!==null&&r!==void 0?r:0,t.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!s.debug,typeof s.debug=="function"&&(this.logger=s.debug),this.instanceID>0&&q()){let o=`${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(o),this.logDebugMessages&&console.trace(o);}if(this.persistSession=s.persistSession,this.autoRefreshToken=s.autoRefreshToken,this.admin=new mt({url:s.url,headers:s.headers,fetch:s.fetch}),this.url=s.url,this.headers=s.headers,this.fetch=Zn(s.fetch),this.lock=s.lock||tu,this.detectSessionInUrl=s.detectSessionInUrl,this.flowType=s.flowType,this.hasCustomAuthorizationHeader=s.hasCustomAuthorizationHeader,this.throwOnError=s.throwOnError,this.lockAcquireTimeout=s.lockAcquireTimeout,s.lock?this.lock=s.lock:this.persistSession&&q()&&(!((n=globalThis?.navigator)===null||n===void 0)&&n.locks)?this.lock=Hs:this.lock=tu,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 ni(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.persistSession?(s.storage?this.storage=s.storage:Xn()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=Fs(this.memoryStorage)),s.userStorage&&(this.userStorage=s.userStorage)):(this.memoryStorage={},this.storage=Fs(this.memoryStorage)),q()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey);}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o);}(i=this.broadcastChannel)===null||i===void 0||i.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1);}catch(a){this._debug("#broadcastChannel","error",a);}});}s.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o);});}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return `GoTrueClient@${this.storageKey}:${this.instanceID} (${Fn}) ${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={},n="none";if(q()&&(r=Tc(window.location.href),this._isImplicitGrantCallback(r)?n="implicit":await this._isPKCECallback(r)&&(n="pkce")),q()&&this.detectSessionInUrl&&n!=="none"){let{data:i,error:s}=await this._getSessionFromURL(r,n);if(s){if(this._debug("#_initialize()","error detecting session from URL",s),vc(s)){let l=(e=s.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:s}}return {error:s}}let{session:o,redirectType:a}=i;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 v(r)?this._returnResult({error:r}):this._returnResult({error:new ue("Unexpected error during initialization",r)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end");}}async signInAnonymously(e){var r,n,i;try{let s=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(n=(r=e?.options)===null||r===void 0?void 0:r.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:(i=e?.options)===null||i===void 0?void 0:i.captchaToken}},xform:de}),{data:o,error:a}=s;if(a||!o)return this._returnResult({data:{user:null,session:null},error:a});let 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(s){if(v(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signUp(e){var r,n,i;try{let s;if("email"in e){let{email:u,password:d,options:p}=e,h=null,f=null;this.flowType==="pkce"&&([h,f]=await ht(this.storage,this.storageKey)),s=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:p?.emailRedirectTo,body:{email:u,password:d,data:(r=p?.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:p?.captchaToken},code_challenge:h,code_challenge_method:f},xform:de});}else if("phone"in e){let{phone:u,password:d,options:p}=e;s=await S(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:d,data:(n=p?.data)!==null&&n!==void 0?n:{},channel:(i=p?.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:p?.captchaToken}},xform:de});}else throw new at("You must provide either an email or phone number and a password");let{data:o,error:a}=s;if(a||!o)return await z(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:a});let 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(s){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithPassword(e){try{let r;if("email"in e){let{email:s,password:o,options:a}=e;r=await S(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ls});}else if("phone"in e){let{phone:s,password:o,options:a}=e;r=await S(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:o,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:Ls});}else throw new at("You must provide either an email or phone number and a password");let{data:n,error:i}=r;if(i)return this._returnResult({data:{user:null,session:null},error:i});if(!n||!n.session||!n.user){let s=new Oe;return this._returnResult({data:{user:null,session:null},error:s})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:i})}catch(r){if(v(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOAuth(e){var r,n,i,s;return await this._handleProviderSignIn(e.provider,{redirectTo:(r=e.options)===null||r===void 0?void 0:r.redirectTo,scopes:(n=e.options)===null||n===void 0?void 0:n.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(s=e.options)===null||s===void 0?void 0:s.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e))}async signInWithWeb3(e){let{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,n,i,s,o,a,l,c,u,d,p;let h,f;if("message"in e)h=e.message,f=e.signature;else {let{chain:m,wallet:_,statement:b,options:w}=e,y;if(q())if(typeof _=="object")y=_;else {let le=window;if("ethereum"in le&&typeof le.ethereum=="object"&&"request"in le.ethereum&&typeof le.ethereum.request=="function")y=le.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 _!="object"||!w?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");y=_;}let I=new URL((r=w?.url)!==null&&r!==void 0?r:window.location.href),Z=await y.request({method:"eth_requestAccounts"}).then(le=>le).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!Z||Z.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let T=zs(Z[0]),$=(n=w?.signInWithEthereum)===null||n===void 0?void 0:n.chainId;if(!$){let le=await y.request({method:"eth_chainId"});$=Hc(le);}let Te={domain:I.host,address:T,statement:b,uri:I.href,version:"1",chainId:$,nonce:(i=w?.signInWithEthereum)===null||i===void 0?void 0:i.nonce,issuedAt:(o=(s=w?.signInWithEthereum)===null||s===void 0?void 0:s.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(a=w?.signInWithEthereum)===null||a===void 0?void 0:a.expirationTime,notBefore:(l=w?.signInWithEthereum)===null||l===void 0?void 0:l.notBefore,requestId:(c=w?.signInWithEthereum)===null||c===void 0?void 0:c.requestId,resources:(u=w?.signInWithEthereum)===null||u===void 0?void 0:u.resources};h=zc(Te),f=await y.request({method:"personal_sign",params:[qc(h),T]});}try{let{data:m,error:_}=await S(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:h,signature:f},!((d=e.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(p=e.options)===null||p===void 0?void 0:p.captchaToken}}:null),xform:de});if(_)throw _;if(!m||!m.session||!m.user){let b=new Oe;return this._returnResult({data:{user:null,session:null},error:b})}return m.session&&(await this._saveSession(m.session),await this._notifyAllSubscribers("SIGNED_IN",m.session)),this._returnResult({data:Object.assign({},m),error:_})}catch(m){if(v(m))return this._returnResult({data:{user:null,session:null},error:m});throw m}}async signInWithSolana(e){var r,n,i,s,o,a,l,c,u,d,p,h;let f,m;if("message"in e)f=e.message,m=e.signature;else {let{chain:_,wallet:b,statement:w,options:y}=e,I;if(q())if(typeof b=="object")I=b;else {let T=window;if("solana"in T&&typeof T.solana=="object"&&("signIn"in T.solana&&typeof T.solana.signIn=="function"||"signMessage"in T.solana&&typeof T.solana.signMessage=="function"))I=T.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 b!="object"||!y?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");I=b;}let Z=new URL((r=y?.url)!==null&&r!==void 0?r:window.location.href);if("signIn"in I&&I.signIn){let T=await I.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},y?.signInWithSolana),{version:"1",domain:Z.host,uri:Z.href}),w?{statement:w}:null)),$;if(Array.isArray(T)&&T[0]&&typeof T[0]=="object")$=T[0];else if(T&&typeof T=="object"&&"signedMessage"in T&&"signature"in T)$=T;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in $&&"signature"in $&&(typeof $.signedMessage=="string"||$.signedMessage instanceof Uint8Array)&&$.signature instanceof Uint8Array)f=typeof $.signedMessage=="string"?$.signedMessage:new TextDecoder().decode($.signedMessage),m=$.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else {if(!("signMessage"in I)||typeof I.signMessage!="function"||!("publicKey"in I)||typeof I!="object"||!I.publicKey||!("toBase58"in I.publicKey)||typeof I.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");f=[`${Z.host} wants you to sign in with your Solana account:`,I.publicKey.toBase58(),...w?["",w,""]:[""],"Version: 1",`URI: ${Z.href}`,`Issued At: ${(i=(n=y?.signInWithSolana)===null||n===void 0?void 0:n.issuedAt)!==null&&i!==void 0?i:new Date().toISOString()}`,...!((s=y?.signInWithSolana)===null||s===void 0)&&s.notBefore?[`Not Before: ${y.signInWithSolana.notBefore}`]:[],...!((o=y?.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${y.signInWithSolana.expirationTime}`]:[],...!((a=y?.signInWithSolana)===null||a===void 0)&&a.chainId?[`Chain ID: ${y.signInWithSolana.chainId}`]:[],...!((l=y?.signInWithSolana)===null||l===void 0)&&l.nonce?[`Nonce: ${y.signInWithSolana.nonce}`]:[],...!((c=y?.signInWithSolana)===null||c===void 0)&&c.requestId?[`Request ID: ${y.signInWithSolana.requestId}`]:[],...!((d=(u=y?.signInWithSolana)===null||u===void 0?void 0:u.resources)===null||d===void 0)&&d.length?["Resources",...y.signInWithSolana.resources.map($=>`- ${$}`)]:[]].join(`
|
|
47
|
+
`);let T=await I.signMessage(new TextEncoder().encode(f),"utf8");if(!T||!(T instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");m=T;}}try{let{data:_,error:b}=await S(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:f,signature:$e(m)},!((p=e.options)===null||p===void 0)&&p.captchaToken?{gotrue_meta_security:{captcha_token:(h=e.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:de});if(b)throw b;if(!_||!_.session||!_.user){let w=new Oe;return this._returnResult({data:{user:null,session:null},error:w})}return _.session&&(await this._saveSession(_.session),await this._notifyAllSubscribers("SIGNED_IN",_.session)),this._returnResult({data:Object.assign({},_),error:b})}catch(_){if(v(_))return this._returnResult({data:{user:null,session:null},error:_});throw _}}async _exchangeCodeForSession(e){let r=await Je(this.storage,`${this.storageKey}-code-verifier`),[n,i]=(r??"").split("/");try{if(!n&&this.flowType==="pkce")throw new Kn;let{data:s,error:o}=await S(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:n},xform:de});if(await z(this.storage,`${this.storageKey}-code-verifier`),o)throw o;if(!s||!s.session||!s.user){let a=new Oe;return this._returnResult({data:{user:null,session:null,redirectType:null},error:a})}return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),this._returnResult({data:Object.assign(Object.assign({},s),{redirectType:i??null}),error:o})}catch(s){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(s))return this._returnResult({data:{user:null,session:null,redirectType:null},error:s});throw s}}async signInWithIdToken(e){try{let{options:r,provider:n,token:i,access_token:s,nonce:o}=e,a=await S(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:i,access_token:s,nonce:o,gotrue_meta_security:{captcha_token:r?.captchaToken}},xform:de}),{data:l,error:c}=a;if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l||!l.session||!l.user){let u=new Oe;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(v(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async signInWithOtp(e){var r,n,i,s,o;try{if("email"in e){let{email:a,options:l}=e,c=null,u=null;this.flowType==="pkce"&&([c,u]=await ht(this.storage,this.storageKey));let{error:d}=await S(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(r=l?.data)!==null&&r!==void 0?r:{},create_user:(n=l?.shouldCreateUser)!==null&&n!==void 0?n:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:d})}if("phone"in e){let{phone:a,options:l}=e,{data:c,error:u}=await S(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=l?.data)!==null&&i!==void 0?i:{},create_user:(s=l?.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l?.captchaToken},channel:(o=l?.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:c?.message_id},error:u})}throw new at("You must provide either an email or phone number.")}catch(a){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async verifyOtp(e){var r,n;try{let i,s;"options"in e&&(i=(r=e.options)===null||r===void 0?void 0:r.redirectTo,s=(n=e.options)===null||n===void 0?void 0:n.captchaToken);let{data:o,error:a}=await S(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:s}}),redirectTo:i,xform:de});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");let l=o.session,c=o.user;return 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(i){if(v(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signInWithSSO(e){var r,n,i,s,o;try{let a=null,l=null;this.flowType==="pkce"&&([a,l]=await ht(this.storage,this.storageKey));let c=await S(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:(n=(r=e.options)===null||r===void 0?void 0:r.redirectTo)!==null&&n!==void 0?n:void 0}),!((i=e?.options)===null||i===void 0)&&i.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:Lc});return !((s=c.data)===null||s===void 0)&&s.url&&q()&&!(!((o=e.options)===null||o===void 0)&&o.skipBrowserRedirect)&&window.location.assign(c.data.url),this._returnResult(c)}catch(a){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(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=>{let{data:{session:r},error:n}=e;if(n)throw n;if(!r)throw new J;let{error:i}=await S(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:r.access_token});return this._returnResult({data:{user:null,session:null},error:i})})}catch(e){if(v(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){try{let r=`${this.url}/resend`;if("email"in e){let{email:n,type:i,options:s}=e,{error:o}=await S(this.fetch,"POST",r,{headers:this.headers,body:{email:n,type:i,gotrue_meta_security:{captcha_token:s?.captchaToken}},redirectTo:s?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:o})}else if("phone"in e){let{phone:n,type:i,options:s}=e,{data:o,error:a}=await S(this.fetch,"POST",r,{headers:this.headers,body:{phone:n,type:i,gotrue_meta_security:{captcha_token:s?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:a})}throw new at("You must provide either an email or phone number and a type")}catch(r){if(v(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){let n=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await n,await r()))();return this.pendingInLock.push((async()=>{try{await i;}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let n=r();for(this.pendingInLock.push((async()=>{try{await n;}catch{}})()),await n;this.pendingInLock.length;){let i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.length);}return await n}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1;}})}finally{this._debug("#_acquireLock","end");}}async _useSession(e){this._debug("#_useSession","begin");try{let 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,r=await Je(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};let n=e.expires_at?e.expires_at*1e3-Date.now()<qn:!1;if(this._debug("#__loadSession()",`session has${n?"":" not"} expired`,"expires_at",e.expires_at),!n){if(this.userStorage){let o=await Je(this.userStorage,this.storageKey+"-user");o?.user?e.user=o.user:e.user=Qn();}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let o={value:this.suppressGetSessionWarning};e.user=Dc(e.user,o),o.value&&(this.suppressGetSessionWarning=!0);}return {data:{session:e},error:null}}let{data:i,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{session:null},error:s}):this._returnResult({data:{session:i},error:null})}finally{this._debug("#__loadSession()","end");}}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let r=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return r.data.user&&(this.suppressGetSessionWarning=true),r}async _getUser(e){try{return e?await S(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Se}):await this._useSession(async r=>{var n,i,s;let{data:o,error:a}=r;if(a)throw a;return !(!((n=o.session)===null||n===void 0)&&n.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new J}:await S(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(s=(i=o.session)===null||i===void 0?void 0:i.access_token)!==null&&s!==void 0?s:void 0,xform:Se})})}catch(r){if(v(r))return Mr(r)&&(await this._removeSession(),await z(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 n=>{let{data:i,error:s}=n;if(s)throw s;if(!i.session)throw new J;let o=i.session,a=null,l=null;this.flowType==="pkce"&&e.email!=null&&([a,l]=await ht(this.storage,this.storageKey));let{data:c,error:u}=await S(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:r?.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:a,code_challenge_method:l}),jwt:o.access_token,xform:Se});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(n){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(n))return this._returnResult({data:{user:null},error:n});throw n}}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 J;let r=Date.now()/1e3,n=r,i=!0,s=null,{payload:o}=Ur(e.access_token);if(o.exp&&(n=o.exp,i=n<=r),i){let{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};s=a;}else {let{data:a,error:l}=await this._getUser(e.access_token);if(l)return this._returnResult({data:{user:null,session:null},error:l});s={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:n-r,expires_at:n},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s);}return this._returnResult({data:{user:s.user,session:s},error:null})}catch(r){if(v(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 n;if(!e){let{data:o,error:a}=r;if(a)throw a;e=(n=o.session)!==null&&n!==void 0?n:void 0;}if(!e?.refresh_token)throw new J;let{data:i,error:s}=await this._callRefreshToken(e.refresh_token);return s?this._returnResult({data:{user:null,session:null},error:s}):i?this._returnResult({data:{user:i.user,session:i},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(r){if(v(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async _getSessionFromURL(e,r){try{if(!q())throw new lt("No browser detected.");if(e.error||e.error_description||e.error_code)throw new lt(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 jr("Not a valid PKCE flow url.");break;case "pkce":if(this.flowType==="implicit")throw new lt("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 jr("No code detected.");let{data:w,error:y}=await this._exchangeCodeForSession(e.code);if(y)throw y;let I=new URL(window.location.href);return I.searchParams.delete("code"),window.history.replaceState(window.history.state,"",I.toString()),{data:{session:w.session,redirectType:null},error:null}}let{provider_token:n,provider_refresh_token:i,access_token:s,refresh_token:o,expires_in:a,expires_at:l,token_type:c}=e;if(!s||!a||!o||!c)throw new lt("No session defined in URL");let u=Math.round(Date.now()/1e3),d=parseInt(a),p=u+d;l&&(p=parseInt(l));let h=p-u;h*1e3<=ot&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${h}s, should have been closer to ${d}s`);let f=p-d;u-f>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",f,p,u):u-f<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",f,p,u);let{data:m,error:_}=await this._getUser(s);if(_)throw _;let b={provider_token:n,provider_refresh_token:i,access_token:s,expires_in:d,expires_at:p,refresh_token:o,token_type:c,user:m.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:b,redirectType:e.type},error:null})}catch(n){if(v(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){let r=await Je(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 n;let{data:i,error:s}=r;if(s&&!Mr(s))return this._returnResult({error:s});let o=(n=i.session)===null||n===void 0?void 0:n.access_token;if(o){let{error:a}=await this.admin.signOut(o,e);if(a&&!(bc(a)&&(a.status===404||a.status===401||a.status===403)||Mr(a)))return this._returnResult({error:a})}return e!=="others"&&(await this._removeSession(),await z(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange(e){let r=Pc(),n={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,n),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(r);})))(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async r=>{var n,i;try{let{data:{session:s},error:o}=r;if(o)throw o;await((n=this.stateChangeEmitters.get(e))===null||n===void 0?void 0:n.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s);}catch(s){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",s),Mr(s)?console.warn(s):console.error(s);}})}async resetPasswordForEmail(e,r={}){let n=null,i=null;this.flowType==="pkce"&&([n,i]=await ht(this.storage,this.storageKey,true));try{return await S(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:i,gotrue_meta_security:{captcha_token:r.captchaToken}},headers:this.headers,redirectTo:r.redirectTo})}catch(s){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(s))return this._returnResult({data:null,error:s});throw s}}async getUserIdentities(){var e;try{let{data:r,error:n}=await this.getUser();if(n)throw n;return this._returnResult({data:{identities:(e=r.user.identities)!==null&&e!==void 0?e:[]},error:null})}catch(r){if(v(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{let{data:n,error:i}=await this._useSession(async s=>{var o,a,l,c,u;let{data:d,error:p}=s;if(p)throw p;let h=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 S(this.fetch,"GET",h,{headers:this.headers,jwt:(u=(c=d.session)===null||c===void 0?void 0:c.access_token)!==null&&u!==void 0?u:void 0})});if(i)throw i;return q()&&!(!((r=e.options)===null||r===void 0)&&r.skipBrowserRedirect)&&window.location.assign(n?.url),this._returnResult({data:{provider:e.provider,url:n?.url},error:null})}catch(n){if(v(n))return this._returnResult({data:{provider:e.provider,url:null},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async r=>{var n;try{let{error:i,data:{session:s}}=r;if(i)throw i;let{options:o,provider:a,token:l,access_token:c,nonce:u}=e,d=await S(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(n=s?.access_token)!==null&&n!==void 0?n:void 0,body:{provider:a,id_token:l,access_token:c,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:de}),{data:p,error:h}=d;return h?this._returnResult({data:{user:null,session:null},error:h}):!p||!p.session||!p.user?this._returnResult({data:{user:null,session:null},error:new Oe}):(p.session&&(await this._saveSession(p.session),await this._notifyAllSubscribers("USER_UPDATED",p.session)),this._returnResult({data:p,error:h}))}catch(i){if(await z(this.storage,`${this.storageKey}-code-verifier`),v(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}})}async unlinkIdentity(e){try{return await this._useSession(async r=>{var n,i;let{data:s,error:o}=r;if(o)throw o;return await S(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:(i=(n=s.session)===null||n===void 0?void 0:n.access_token)!==null&&i!==void 0?i:void 0})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _refreshAccessToken(e){let r=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(r,"begin");try{let n=Date.now();return await Oc(async i=>(i>0&&await Ic(200*Math.pow(2,i-1)),this._debug(r,"refreshing attempt",i),await S(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:de})),(i,s)=>{let o=200*Math.pow(2,i);return s&&Vn(s)&&Date.now()+o-n<ot})}catch(n){if(this._debug(r,"error",n),v(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}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){let n=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",n),q()&&!r.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n},error:null}}async _recoverAndRefresh(){var e,r;let n="#_recoverAndRefresh()";this._debug(n,"begin");try{let i=await Je(this.storage,this.storageKey);if(i&&this.userStorage){let o=await Je(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:i.user},await pt(this.userStorage,this.storageKey+"-user",o)),i.user=(e=o?.user)!==null&&e!==void 0?e:Qn();}else if(i&&!i.user&&!i.user){let o=await Je(this.storage,this.storageKey+"-user");o&&o?.user?(i.user=o.user,await z(this.storage,this.storageKey+"-user"),await pt(this.storage,this.storageKey,i)):i.user=Qn();}if(this._debug(n,"session from storage",i),!this._isValidSession(i)){this._debug(n,"session is not valid"),i!==null&&await this._removeSession();return}let s=((r=i.expires_at)!==null&&r!==void 0?r:1/0)*1e3-Date.now()<qn;if(this._debug(n,`session has${s?"":" not"} expired with margin of ${qn}s`),s){if(this.autoRefreshToken&&i.refresh_token){let{error:o}=await this._callRefreshToken(i.refresh_token);o&&(console.error(o),Vn(o)||(this._debug(n,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()));}}else if(i.user&&i.user.__isUserNotAvailableProxy===!0)try{let{data:o,error:a}=await this._getUser(i.access_token);!a&&o?.user?(i.user=o.user,await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)):this._debug(n,"could not get user data, skipping SIGNED_IN notification");}catch(o){console.error("Error getting user data:",o),this._debug(n,"error getting user data, skipping SIGNED_IN notification",o);}else await this._notifyAllSubscribers("SIGNED_IN",i);}catch(i){this._debug(n,"error",i),console.error(i);return}finally{this._debug(n,"end");}}async _callRefreshToken(e){var r,n;if(!e)throw new J;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Lr;let{data:s,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!s.session)throw new J;await this._saveSession(s.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",s.session);let a={data:s.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(s){if(this._debug(i,"error",s),v(s)){let o={data:null,error:s};return Vn(s)||await this._removeSession(),(r=this.refreshingDeferred)===null||r===void 0||r.resolve(o),o}throw (n=this.refreshingDeferred)===null||n===void 0||n.reject(s),s}finally{this.refreshingDeferred=null,this._debug(i,"end");}}async _notifyAllSubscribers(e,r,n=true){let i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",r,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:r});let s=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,r);}catch(l){s.push(l);}});if(await Promise.all(o),s.length>0){for(let a=0;a<s.length;a+=1)console.error(s[a]);throw s[0]}}finally{this._debug(i,"end");}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=true,await z(this.storage,`${this.storageKey}-code-verifier`);let r=Object.assign({},e),n=r.user&&r.user.__isUserNotAvailableProxy===true;if(this.userStorage){!n&&r.user&&await pt(this.userStorage,this.storageKey+"-user",{user:r.user});let i=Object.assign({},r);delete i.user;let s=Ms(i);await pt(this.storage,this.storageKey,s);}else {let i=Ms(r);await pt(this.storage,this.storageKey,i);}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=false,await z(this.storage,this.storageKey),await z(this.storage,this.storageKey+"-code-verifier"),await z(this.storage,this.storageKey+"-user"),this.userStorage&&await z(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null);}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&q()&&window?.removeEventListener&&window.removeEventListener("visibilitychange",e);}catch(r){console.error("removing visibilitychange callback failed",r);}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),ot);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e);let 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()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let 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{let e=Date.now();try{return await this._useSession(async r=>{let{data:{session:n}}=r;if(!n||!n.refresh_token||!n.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let i=Math.floor((n.expires_at*1e3-e)/ot);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${ot}ms, refresh threshold is ${Hn} ticks`),i<=Hn&&await this._callRefreshToken(n.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.isAcquireTimeout||e instanceof Wr)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!q()||!window?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),false;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1);}catch(e){this._debug("#visibilityChangedCallback","error",e);}},window?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0);}catch(e){console.error("_handleVisibilityChange",e);}}async _onVisibilityChanged(e){let 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,n){let i=[`provider=${encodeURIComponent(r)}`];if(n?.redirectTo&&i.push(`redirect_to=${encodeURIComponent(n.redirectTo)}`),n?.scopes&&i.push(`scopes=${encodeURIComponent(n.scopes)}`),this.flowType==="pkce"){let[s,o]=await ht(this.storage,this.storageKey),a=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(o)}`});i.push(a.toString());}if(n?.queryParams){let s=new URLSearchParams(n.queryParams);i.push(s.toString());}return n?.skipBrowserRedirect&&i.push(`skip_http_redirect=${n.skipBrowserRedirect}`),`${e}?${i.join("&")}`}async _unenroll(e){try{return await this._useSession(async r=>{var n;let{data:i,error:s}=r;return s?this._returnResult({data:null,error:s}):await S(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _enroll(e){try{return await this._useSession(async r=>{var n,i;let{data:s,error:o}=r;if(o)return this._returnResult({data:null,error:o});let 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 S(this.fetch,"POST",`${this.url}/factors`,{body:a,headers:this.headers,jwt:(n=s?.session)===null||n===void 0?void 0:n.access_token});return c?this._returnResult({data:null,error:c}):(e.factorType==="totp"&&l.type==="totp"&&(!((i=l?.totp)===null||i===void 0)&&i.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(v(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 n;let{data:i,error:s}=r;if(s)return this._returnResult({data:null,error:s});let o=Object.assign({challenge_id:e.challengeId},"webauthn"in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type==="create"?Qc(e.webauthn.credential_response):eu(e.webauthn.credential_response)})}:{code:e.code}),{data:a,error:l}=await S(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:o,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.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(v(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 n;let{data:i,error:s}=r;if(s)return this._returnResult({data:null,error:s});let o=await S(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:(n=i?.session)===null||n===void 0?void 0:n.access_token});if(o.error)return o;let{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:Xc(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:Zc(a.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}})}async _challengeAndVerify(e){let{data:r,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:r.id,code:e.code})}async _listFactors(){var e;let{data:{user:r},error:n}=await this.getUser();if(n)return {data:null,error:n};let i={all:[],phone:[],totp:[],webauthn:[]};for(let s of (e=r?.factors)!==null&&e!==void 0?e:[])i.all.push(s),s.status==="verified"&&i[s.factor_type].push(s);return {data:i,error:null}}async _getAuthenticatorAssuranceLevel(e){var r,n,i,s;if(e)try{let{payload:h}=Ur(e),f=null;h.aal&&(f=h.aal);let m=f,{data:{user:_},error:b}=await this.getUser(e);if(b)return this._returnResult({data:null,error:b});((n=(r=_?.factors)===null||r===void 0?void 0:r.filter(I=>I.status==="verified"))!==null&&n!==void 0?n:[]).length>0&&(m="aal2");let y=h.amr||[];return {data:{currentLevel:f,nextLevel:m,currentAuthenticationMethods:y},error:null}}catch(h){if(v(h))return this._returnResult({data:null,error:h});throw h}let{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};let{payload:l}=Ur(o.access_token),c=null;l.aal&&(c=l.aal);let u=c;((s=(i=o.user.factors)===null||i===void 0?void 0:i.filter(h=>h.status==="verified"))!==null&&s!==void 0?s:[]).length>0&&(u="aal2");let p=l.amr||[];return {data:{currentLevel:c,nextLevel:u,currentAuthenticationMethods:p},error:null}}async _getAuthorizationDetails(e){try{return await this._useSession(async r=>{let{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?await S(this.fetch,"GET",`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new J})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async _approveAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:i},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!i)return this._returnResult({data:null,error:new J});let o=await S(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"approve"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&q()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if(v(n))return this._returnResult({data:null,error:n});throw n}}async _denyAuthorization(e,r){try{return await this._useSession(async n=>{let{data:{session:i},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!i)return this._returnResult({data:null,error:new J});let o=await S(this.fetch,"POST",`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:i.access_token,body:{action:"deny"},xform:a=>({data:a,error:null})});return o.data&&o.data.redirect_url&&q()&&!r?.skipBrowserRedirect&&window.location.assign(o.data.redirect_url),o})}catch(n){if(v(n))return this._returnResult({data:null,error:n});throw n}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:r},error:n}=e;return n?this._returnResult({data:null,error:n}):r?await S(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new J})})}catch(e){if(v(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async r=>{let{data:{session:n},error:i}=r;return i?this._returnResult({data:null,error:i}):n?(await S(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new J})})}catch(r){if(v(r))return this._returnResult({data:null,error:r});throw r}}async fetchJwk(e,r={keys:[]}){let n=r.keys.find(a=>a.kid===e);if(n)return n;let i=Date.now();if(n=this.jwks.keys.find(a=>a.kid===e),n&&this.jwks_cached_at+kc>i)return n;let{data:s,error:o}=await S(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return !s.keys||s.keys.length===0||(this.jwks=s,this.jwks_cached_at=i,n=s.keys.find(a=>a.kid===e),!n)?null:n}async getClaims(e,r={}){try{let n=e;if(!n){let{data:h,error:f}=await this.getSession();if(f||!h.session)return this._returnResult({data:null,error:f});n=h.session.access_token;}let{header:i,payload:s,signature:o,raw:{header:a,payload:l}}=Ur(n);r?.allowExpired||Nc(s.exp);let c=!i.alg||i.alg.startsWith("HS")||!i.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(i.kid,r?.keys?{keys:r.keys}:r?.jwks);if(!c){let{error:h}=await this.getUser(n);if(h)throw h;return {data:{claims:s,header:i,signature:o},error:null}}let u=jc(i.alg),d=await crypto.subtle.importKey("jwk",c,u,!0,["verify"]);if(!await crypto.subtle.verify(u,d,o,Rc(`${a}.${l}`)))throw new ct("Invalid JWT signature");return {data:{claims:s,header:i,signature:o},error:null}}catch(n){if(v(n))return this._returnResult({data:null,error:n});throw n}}};ii.nextInstanceID={};Gs=ii;});var ru=R(()=>{ti();});var Jm,Xs,nu=R(()=>{Ys();Jm=Gs,Xs=Jm;});var Zs=R(()=>{ti();Ys();ru();nu();Bs();ut();qs();});function Hr(t){"@babel/helpers - typeof";return Hr=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},Hr(t)}function Qm(t,e){if(Hr(t)!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var n=r.call(t,e);if(Hr(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return (e==="string"?String:Number)(t)}function e_(t){var e=Qm(t,"string");return Hr(e)=="symbol"?e:e+""}function t_(t,e,r){return (e=e_(e))in t?Object.defineProperty(t,e,{value:r,enumerable:true,configurable:true,writable:true}):t[e]=r,t}function iu(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n);}return r}function W(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?iu(Object(r),true).forEach(function(n){t_(t,n,r[n]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):iu(Object(r)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(r,n));});}return t}function s_(t){return t.endsWith("/")?t:t+"/"}function o_(t,e){var r,n;let{db:i,auth:s,realtime:o,global:a}=t,{db:l,auth:c,realtime:u,global:d}=e,p={db:W(W({},l),i),auth:W(W({},c),s),realtime:W(W({},u),o),storage:{},global:W(W(W({},d),a),{},{headers:W(W({},(r=d?.headers)!==null&&r!==void 0?r:{}),(n=a?.headers)!==null&&n!==void 0?n:{})}),accessToken:async()=>""};return t.accessToken?p.accessToken=t.accessToken:delete p.accessToken,p}function a_(t){let e=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(s_(e))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}function u_(){if(typeof window<"u")return false;let t=globalThis.process;if(!t)return false;let e=t.version;if(e==null)return false;let r=e.match(/^v(\d+)\./);return r?parseInt(r[1],10)<=18:false}var Km,Fr,Vm,Gm,Ym,Xm,Zm,r_,n_,i_,l_,c_,Zt,si=R(()=>{$l();Fl();As();gc();Zs();As();Zs();Km="2.103.2",Fr="";typeof Deno<"u"?Fr="deno":typeof document<"u"?Fr="web":typeof navigator<"u"&&navigator.product==="ReactNative"?Fr="react-native":Fr="node";Vm={"X-Client-Info":`supabase-js-${Fr}/${Km}`},Gm={headers:Vm},Ym={schema:"public"},Xm={autoRefreshToken:true,persistSession:true,detectSessionInUrl:true,flowType:"implicit"},Zm={};r_=t=>t?(...e)=>t(...e):(...e)=>fetch(...e),n_=()=>Headers,i_=(t,e,r)=>{let n=r_(r),i=n_();return async(s,o)=>{var a;let l=(a=await e())!==null&&a!==void 0?a:t,c=new i(o?.headers);return c.has("apikey")||c.set("apikey",t),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),n(s,W(W({},o),{},{headers:c}))}};l_=class extends Xs{constructor(t){super(t);}},c_=class{constructor(t,e,r){var n,i;this.supabaseUrl=t,this.supabaseKey=e;let s=a_(t);if(!e)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",s),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",s),this.storageUrl=new URL("storage/v1",s),this.functionsUrl=new URL("functions/v1",s);let o=`sb-${s.hostname.split(".")[0]}-auth-token`,a={db:Ym,realtime:Zm,auth:W(W({},Xm),{},{storageKey:o}),global:Gm},l=o_(r??{},a);if(this.storageKey=(n=l.auth.storageKey)!==null&&n!==void 0?n:"",this.headers=(i=l.global.headers)!==null&&i!==void 0?i:{},l.accessToken)this.accessToken=l.accessToken,this.auth=new Proxy({},{get:(u,d)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(d)} 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=i_(e,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(W({headers:this.headers,accessToken:this._getAccessToken.bind(this)},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 Wl(new URL("rest/v1",s).href,{headers:this.headers,schema:l.db.schema,fetch:this.fetch,timeout:l.db.timeout,urlLengthLimit:l.db.urlLengthLimit}),this.storage=new fc(this.storageUrl.href,this.headers,this.fetch,r?.storage),l.accessToken||this._listenForAuthEvents();}get functions(){return new yr(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:false,get:false,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();let{data:n}=await t.auth.getSession();return (e=(r=n.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:n,userStorage:i,storageKey:s,flowType:o,lock:a,debug:l,throwOnError:c},u,d){let p={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new l_({url:this.authUrl.href,headers:W(W({},p),u),storageKey:s,autoRefreshToken:t,persistSession:e,detectSessionInUrl:r,storage:n,userStorage:i,flowType:o,lock:a,debug:l,throwOnError:c,fetch:d,hasCustomAuthorizationHeader:Object.keys(this.headers).some(h=>h.toLowerCase()==="authorization")})}_initRealtimeClient(t){return new Jt(this.realtimeUrl.href,W(W({},t),{},{params:W(W({},{apikey:this.supabaseKey}),t?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((t,e)=>{this._handleTokenChanged(t,"CLIENT",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);}},Zt=(t,e,r)=>new c_(t,e,r);u_()&&console.warn("\u26A0\uFE0F 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");});function pe(t){let e=t.SUPABASE_URL??t.VITE_SUPABASE_URL??"https://xygyyikpgykarmqujajf.supabase.co",r=t.SUPABASE_ANON_KEY??t.VITE_SUPABASE_ANON_KEY??"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Inh5Z3l5aWtwZ3lrYXJtcXVqYWpmIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzYyMjIyOTcsImV4cCI6MjA5MTc5ODI5N30.y_SPm1eJeofb4zYgPCogTJUPr4e7-z92BzcRzqQiK9g";if(!e||!r)throw new Qs("missing_supabase_config","Missing Supabase client configuration for CLI login.");return {supabaseUrl:e,supabaseAnonKey:r}}var Qs,qr=R(()=>{Qs=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="CliAuthConfigError";}code};});async function au(t){let e=pe(t.env),r=f_(),n=Zt(e.supabaseUrl,e.supabaseAnonKey,{auth:{persistSession:true,detectSessionInUrl:false,flowType:"pkce",storage:r}}),i=await g_({timeoutMs:t.timeoutMs??300*1e3}),s=i.redirectUri;try{let{data:o,error:a}=await n.auth.signInWithOAuth({provider:"github",options:{redirectTo:s,skipBrowserRedirect:!0}});if(a||!o.url)throw new G("oauth_start_failed",a?.message??"Supabase did not return an OAuth URL.");t.onOpen?.({url:o.url,redirectUri:s}),await t.openUrl(o.url);let l=await i.waitForCode(),{data:c,error:u}=await n.auth.exchangeCodeForSession(l);if(u||!c.session?.access_token||!c.session.refresh_token)throw new G("oauth_exchange_failed",u?.message??"Supabase did not return a complete session.");let d=await p_(n,c.session,t.promptMfaCode),p=lu(e.supabaseUrl);return await nt(t.env).set(p,JSON.stringify(d)),{session:d,account:p}}finally{await i.close();}}async function p_(t,e,r){let{data:n,error:i}=await t.auth.mfa.getAuthenticatorAssuranceLevel();if(i)throw new G("mfa_check_failed",i.message);if(n.currentLevel===n.nextLevel||n.nextLevel!=="aal2")return h_(e);let{data:s,error:o}=await t.auth.mfa.listFactors();if(o)throw new G("mfa_factor_lookup_failed",o.message);let a=s.totp.find(d=>d.status==="verified");if(!a)throw new G("mfa_factor_missing","Two-factor authentication is enabled, but no verified TOTP factor was returned.");if(!r)throw new G("mfa_required","Two-factor authentication is required for this account.");let l=(await r("Authenticator code: ")).trim(),{data:c,error:u}=await t.auth.mfa.challengeAndVerify({factorId:a.id,code:l});if(u||!c)throw new G("mfa_verify_failed",u?.message??"Two-factor authentication failed.");return {access_token:c.access_token,refresh_token:c.refresh_token,expires_at:Math.floor(Date.now()/1e3)+c.expires_in,expires_in:c.expires_in,token_type:c.token_type,user:{id:c.user.id,email:c.user.email??void 0}}}function h_(t){return {access_token:t.access_token,refresh_token:t.refresh_token,expires_at:t.expires_at??Math.floor(Date.now()/1e3)+(t.expires_in??3600),expires_in:t.expires_in??void 0,token_type:t.token_type,user:{id:t.user.id,email:t.user.email??void 0}}}async function eo(t){let e=pe(t.env),r=await su(t.fetch,e,"auth-device-start",{});t.onPending?.({userCode:r.user_code,verificationUri:r.verification_uri,interval:r.interval});let n=Date.now()+r.expires_in*1e3,i=r.interval;for(;Date.now()<=n;){await t.sleep(i*1e3);let s=await su(t.fetch,e,"auth-device-token",{device_code:r.device_code},{acceptError:true});if("access_token"in s){let o=lu(e.supabaseUrl);return await nt(t.env).set(o,JSON.stringify(s)),{session:s,account:o}}switch(s.error){case "authorization_pending":i=s.interval??i;break;case "slow_down":i=s.interval??Math.min(i+5,30);break;case "expired_token":throw new Ne("expired_token","The device login code expired.");case "access_denied":throw new Ne("access_denied","The device login request was denied.");default:throw new Ne(s.error,`Device login failed: ${s.error}`)}}throw new Ne("expired_token","The device login code expired.")}function lu(t){let e=new URL(t).hostname;return `sb-${e.endsWith(".supabase.co")?e.slice(0,-12):e}-auth-token`}async function su(t,e,r,n,i={}){let s=await t(`${e.supabaseUrl}/functions/v1/${r}`,{method:"POST",headers:{"content-type":"application/json",apikey:e.supabaseAnonKey},body:JSON.stringify(n)}),o=await s.json().catch(()=>({}));if(!s.ok&&!i.acceptError)throw new Ne(o.error??"request_failed");return o}function f_(){let t=new Map;return {getItem:e=>t.get(e)??null,setItem:(e,r)=>{t.set(e,r);},removeItem:e=>{t.delete(e);}}}async function g_(t){let e=null,r=null,n=false,i=new Promise((l,c)=>{e=l,r=c;}),s=createServer((l,c)=>{m_(l,c,(u,d)=>{n||(n=true,u?r?.(u):e?.(d));});});await new Promise((l,c)=>{s.once("error",c),s.listen(0,"127.0.0.1",()=>{s.off("error",c),l();});});let o=s.address();if(!o||typeof o=="string")throw await ou(s),new G("callback_server_failed");let a=setTimeout(()=>{n||(n=true,r?.(new G("oauth_timeout","Browser login timed out.")));},t.timeoutMs);return {redirectUri:`http://127.0.0.1:${o.port}/auth/callback`,waitForCode:()=>i,close:async()=>{clearTimeout(a),await ou(s);}}}function m_(t,e,r){let n=t.headers.host??"127.0.0.1",i=new URL(t.url??"/",`http://${n}`);if(i.pathname!=="/auth/callback"){e.writeHead(404,{"content-type":"text/plain"}),e.end("Not found");return}let s=i.searchParams.get("error")??i.searchParams.get("error_description"),o=i.searchParams.get("code");if(s){e.writeHead(400,{"content-type":"text/plain"}),e.end("Pathrule login failed. You can close this window."),r(new G("oauth_denied",s),"");return}if(!o){e.writeHead(400,{"content-type":"text/plain"}),e.end("Pathrule login could not verify this browser response."),r(new G("oauth_invalid_callback"),"");return}e.writeHead(200,{"content-type":"text/html; charset=utf-8"}),e.end("<!doctype html><title>Pathrule CLI</title><p>Pathrule CLI is signed in. You can close this window.</p>"),r(null,o);}async function ou(t){t.listening&&await new Promise(e=>t.close(()=>e()));}var Ne,G,oi=R(()=>{ms();si();qr();qr();Ne=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="DeviceLoginError";}code},G=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="BrowserLoginError";}code};});async function S_(t){await new Promise(e=>setTimeout(e,t));}async function C_(t){try{await mkdir(dirname(t),{recursive:!0,mode:448}),await chmod(dirname(t),448).catch(()=>{});let e=await open(t,"wx",384);await e.writeFile(`${process.pid}:${Date.now()}
|
|
48
|
+
`,"utf8"),await e.close();let r=!1;return async()=>{r||(r=!0,await rm$1(t,{force:!0}).catch(()=>{}));}}catch(e){if(e.code==="EEXIST")return null;throw e}}async function E_(t,e){try{let{stat:r}=await import('fs/promises'),n=await r(t);Date.now()-n.mtimeMs>e&&await rm$1(t,{force:!0});}catch{}}async function du(t,e={}){let r=e.timeoutMs??k_,n=e.staleMs??b_,i=e.lockFile??A(e.env).tokenLockFile,s=Date.now()+r;for(;Date.now()<=s;){let o=await C_(i);if(o)try{return await t()}finally{await o();}await E_(i,n),await S_(v_);}throw new to}var k_,b_,v_,to,pu=R(()=>{K();k_=15e3,b_=45e3,v_=100,to=class extends Error{constructor(){super("token_refresh_lock_timeout"),this.name="TokenRefreshLockTimeoutError";}};});async function ne(t,e=process.env){let r=rt(t,0,e);try{let n=await readFile(r.userConfigFile,"utf8"),i=JSON.parse(n);if(i&&typeof i=="object"&&i.schema_version===1)return i}catch(n){if(n.code!=="ENOENT")throw n}return {schema_version:1}}async function ai(t,e,r=process.env){let n=rt(t,0,r);await mu(n.userConfigFile,{...e,schema_version:1});}async function ie(t,e,r=process.env){let i={...await ne(t,r),...e,schema_version:1};return await ai(t,i,r),i}async function fu(t,e=process.env){let r=A(e),n={user_id:t,updated_at:new Date().toISOString()};await mu(r.activeUserFile,n);}async function gu(t=process.env){await rm$1(A(t).activeUserFile,{force:true});}async function mu(t,e){let r=dirname(t);await mkdir(r,{recursive:true,mode:D}),await chmod(r,D).catch(()=>{});let n=`${t}.tmp`;await writeFile(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:O}),await chmod(n,O).catch(()=>{}),await rename(n,t);}var Ke=R(()=>{K();});function _u(t){return t.startsWith($_)&&t.endsWith(N_)}async function Ce(t=process.env){let e=await wu(t);return !e||!yu(e.session)?e:D_(e,t)}async function wu(t=process.env){let r=await nt(t).findAll();for(let n of r)if(_u(n.account))try{let i=JSON.parse(n.value);if(!i.access_token||!i.refresh_token||!i.user?.id)continue;return {account:n.account,session:i}}catch{}return null}function yu(t){return t.expires_at<=Math.floor(Date.now()/1e3)+j_}async function D_(t,e){return du(async()=>{let r=await wu(e);if(r&&!yu(r.session))return r;let n=pe(e),i=Zt(n.supabaseUrl,n.supabaseAnonKey,{auth:{persistSession:!1}}),{data:s,error:o}=await i.auth.refreshSession({refresh_token:t.session.refresh_token});if(o)throw new li("refresh_failed",o.message);if(!s.session?.access_token||!s.session.refresh_token||!s.session.user?.id)throw new li("refresh_failed","Supabase did not return a complete session.");let a={access_token:s.session.access_token,refresh_token:s.session.refresh_token,expires_at:s.session.expires_at??Math.floor(Date.now()/1e3)+(s.session.expires_in??3600),user:{id:s.session.user.id,email:s.session.user.email??void 0}};return await nt(e).set(t.account,JSON.stringify(a)),{account:t.account,session:a}},{env:e})}async function ro(t=process.env){let e=nt(t),r=await e.findAll(),n=new Set,i=0;for(let o of r)if(_u(o.account)){try{let a=JSON.parse(o.value);a.user?.id&&n.add(a.user.id);}catch{}await e.delete(o.account)&&(i+=1);}let s=0;for(let o of n)await rm$1(rt(o,0,t).userCacheDir,{recursive:true,force:true}),s+=1;return await gu(t),{removed_sessions:i,purged_user_caches:s}}var $_,N_,j_,li,zr=R(()=>{pu();Ke();ms();K();si();qr();$_="sb-",N_="-auth-token",j_=60,li=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="CliSessionError";}code};});async function C(t=process.env){let e=await Ce(t);if(!e)throw new Qt("not_authenticated","Pathrule CLI is not signed in.");let r=pe(t);return {session:e.session,supabase:Zt(r.supabaseUrl,r.supabaseAnonKey,{auth:{persistSession:false},global:{headers:{Authorization:`Bearer ${e.session.access_token}`}}})}}var Qt,F=R(()=>{si();oi();zr();Qt=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="CliAuthError";}code};});var Nu={};sf(Nu,{cliOrgWebUrl:()=>ee,currentCliOrg:()=>j,listCliOrgs:()=>we,useCliOrg:()=>di});async function we(t){let{session:e,supabase:r}=await C(t),{data:n,error:i}=await r.from("organization_members").select("role, organization:organizations ( id, name, slug, plan, subscription_status, trial_status, trial_ends_at, seat_count, paid_extra_seats, trial_seat_cap, beta_referral_credit_cents, beta_referral_activated_count, beta_referral_founder )").eq("user_id",e.user.id);if(i)throw i;let s=await ne(e.user.id,t),o=[],a=new Set;for(let l of n??[]){let c=l.organization,u=Array.isArray(c)?c[0]:c;if(!u||a.has(u.id))continue;a.add(u.id);let d=u.subscription_status?String(u.subscription_status):null,p=u.trial_status?String(u.trial_status):null,h=u.trial_ends_at?String(u.trial_ends_at):null,f=Q_(d,p,h);o.push({id:u.id,name:u.name,slug:u.slug,plan:u.plan,subscription_status:d,trial_status:p,trial_ends_at:h,seat_count:Ve(u.seat_count),paid_extra_seats:Ve(u.paid_extra_seats),trial_seat_cap:Ve(u.trial_seat_cap),beta_referral_credit_cents:Ve(u.beta_referral_credit_cents)??0,beta_referral_activated_count:Ve(u.beta_referral_activated_count)??0,beta_referral_founder:u.beta_referral_founder===true,role:l.role,current:s.current_org_id===u.id,billing:{status:d,freeze_kind:f.kind,freeze_reason:f.reason,seats:{active:Ve(u.seat_count),trial_cap:Ve(u.trial_seat_cap),paid_extra:Ve(u.paid_extra_seats)}}});}if(!s.current_org_id&&o.length===1){let l=o[0];l&&(o[0]={...l,current:true});}return o}async function j(t){let e=await we(t);return e.find(r=>r.current)??e[0]??null}async function di(t,e){let{session:r}=await C(e),i=(await we(e)).find(s=>s.id===t||s.slug===t);if(!i)throw new Error("org_not_found");return await ie(r.user.id,{current_org_id:i.id},e),await fu(r.user.id,e),{...i,current:true}}function ee(t,e,r="home"){let i=`${(e.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"")}/org/${encodeURIComponent(t.slug)}`;return r==="home"?i:r==="billing"?`${i}/billing`:`${i}/settings${r==="members"?"/members":""}`}function Ve(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function Q_(t,e,r){return t==="unpaid"||t==="past_due"?{kind:"subscription",reason:"unpaid"}:t==="canceled"?e==="expired"||r&&new Date(r).getTime()<Date.now()?{kind:"subscription",reason:"trial_expired"}:{kind:"subscription",reason:"canceled"}:{kind:"none",reason:null}}var Ee=R(()=>{Ke();F();});af(Ma());function La(t,e,r){return `${e}/.claude.json`}var fr="pathrule";function Xi(t){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new Error("Claude config root must be a JSON object");let e=t;if(e.mcpServers!==void 0&&(typeof e.mcpServers!="object"||e.mcpServers===null||Array.isArray(e.mcpServers)))throw new Error("Claude config `mcpServers` must be an object");return e}function Ua(t,e){let r=Xi(t),n={...r.mcpServers??{}},i=!(fr in n);return n[fr]=e,{config:{...r,mcpServers:n},wasNew:i}}function Wa(t){let e=Xi(t);if(!e.mcpServers||!(fr in e.mcpServers))return {config:e,wasPresent:false};let{[fr]:r,...n}=e.mcpServers;return {config:{...e,mcpServers:n},wasPresent:true}}function Ba(t){try{return Xi(t).mcpServers?.[fr]??null}catch{return null}}function B(t){return t.code==="PGRST116"?{code:"not_found",message:t.message}:t.code==="42501"?{code:"permission_denied",message:t.message}:{code:"upstream_error",message:t.message}}async function Nt(t,e){let{data:r,error:n}=await t.rpc("pathrule_check_content_dedup",{p_workspace_id:e.workspaceId,p_kind:e.kind,p_node_id:e.kind==="memory"?e.nodeId??null:null,p_candidate:e.candidate,p_threshold:e.threshold??.65,p_max_similar:e.maxSimilar??5,p_exclude_id:e.excludeId??null});if(n)return {ok:false,error:n.message};let i=r??{duplicate:null,similar:[]};return {ok:true,data:{duplicate:i.duplicate,similar:(i.similar??[]).map(s=>({id:s.id,title:s.title,similarity:typeof s.similarity=="string"?Number(s.similarity):s.similarity}))}}}function Fa(t){return t.code!=="23505"?false:!!t.message?.includes("skills_workspace_slug_unique")}async function Zi(t,e,r){let{data:n,error:i}=await t.from("nodes").select("id, workspace_id, parent_id, name, type, relative_path").eq("workspace_id",e).eq("relative_path","/").is("parent_id",null).maybeSingle();if(i)return {error:i.message};if(n)return n;let{data:s,error:o}=await t.from("nodes").insert({workspace_id:e,parent_id:null,name:r,type:"folder",relative_path:"/",order_index:0,status:"active"}).select("id, workspace_id, parent_id, name, type, relative_path").single();if(o||!s){if(o?.code==="23505"){let{data:a}=await t.from("nodes").select("id, workspace_id, parent_id, name, type, relative_path").eq("workspace_id",e).eq("relative_path","/").is("parent_id",null).maybeSingle();if(a)return a}return {error:o?.message??"Root node insert failed"}}return s}function Ha(t){let e=t.trim();if(e===""||e==="/")return "/";let n=(e.startsWith("/")?e:"/"+e).replace(/\/+/g,"/");return n==="/"?"/":n.replace(/\/$/,"")}function cf(t,e){return (t==="/"?"":t)+"/"+e.trim()}function uf(t){let e=t.split("/").filter(n=>n.length>0),r=e[e.length-1]??"";return /\.[A-Za-z0-9]{1,8}$/.test(r)?"file":"folder"}async function jt(t,e,r){let{data:n,error:i}=await t.from("nodes").select("id, workspace_id, parent_id, name, type, relative_path").eq("workspace_id",e).eq("relative_path",r).maybeSingle();return i?{error:i.message}:n??null}async function df(t,e,r,n){let i=Ha(r);if(i==="/"){let d=await jt(t,e,"/");return d&&!("error"in d)?d:{error:"Workspace root node missing \u2014 call ensureWorkspaceRootNode first."}}let s=await jt(t,e,i);if(s&&!("error"in s)||s&&"error"in s)return s;let o=await jt(t,e,"/");if(!o)return {error:"Workspace root node missing \u2014 call ensureWorkspaceRootNode first."};if("error"in o)return o;let a=i.split("/").filter(d=>d.length>0),l=uf(i),c=o,u="";for(let d=0;d<a.length;d+=1){let p=a[d];u+="/"+p;let f=d===a.length-1?l:"folder",m=await jt(t,e,u);if(m&&"error"in m)return m;if(m){c=m;continue}let{count:_}=await t.from("nodes").select("*",{count:"exact",head:true}).eq("workspace_id",e).eq("parent_id",c.id),{data:b,error:w}=await t.from("nodes").insert({workspace_id:e,parent_id:c.id,name:p,type:f,relative_path:cf(c.relative_path,p),order_index:_??0,status:"active"}).select("id, workspace_id, parent_id, name, type, relative_path").single();if(w||!b){if(w?.code==="23505"){let y=await jt(t,e,u);if(y&&!("error"in y)){c=y;continue}}return {error:w?.message??`Insert failed at ${u}`}}c=b;}return c}async function Dt(t,e,r,n){let i=Ha(r),s=await jt(t,e,"/");if(s&&"error"in s)return s;if(!s){let{data:o,error:a}=await t.from("workspaces").select("name").eq("id",e).maybeSingle();if(a)return {error:a.message};let l=o?.name??"Workspace",c=await Zi(t,e,l);if("error"in c)return c}return df(t,e,i)}function qa(t){return {id:t.id,workspaceId:t.workspace_id,nodeId:t.node_id,title:t.title,content:t.content,source:t.source,semanticTags:t.semantic_tags??[],versionId:t.version_id,versionNumber:t.version_number,createdBy:t.created_by,lastEditedBy:t.last_edited_by,lastEditedAt:t.last_edited_at,createdAt:t.created_at,updatedAt:t.updated_at}}function pf(t){return t.length===0?null:{code:"similar_titles",message:`Found ${t.length} memory/rule(s) with a similar title.`,detail:{similar:t}}}async function za(t,e){if(!t.workspaceId)return {ok:false,error:{code:"invalid_args",message:"ctx.workspaceId is required for path-based writes"}};let r=await Dt(t.supabase,t.workspaceId,e.node_path);if("error"in r)return {ok:false,error:{code:"upstream_error",message:r.error}};let n=e.title.trim(),i=await Nt(t.supabase,{workspaceId:r.workspace_id,kind:"memory",nodeId:r.id,candidate:n});if(i.ok&&i.data.duplicate&&!e.allow_duplicate)return {ok:false,error:{code:"duplicate",message:`A memory titled "${i.data.duplicate.title}" already exists at ${e.node_path}. Use update_memory, pick a different title, or pass allow_duplicate: true to insert anyway.`,detail:{existing_id:i.data.duplicate.id,existing_title:i.data.duplicate.title,similar:i.ok?i.data.similar:[]}}};let{data:s,error:o}=await t.supabase.from("memories").insert({workspace_id:r.workspace_id,node_id:r.id,title:n,content:e.content,source:e.source??"claude",created_by:t.userId,last_edited_by:t.userId}).select("*").single();if(o||!s)return {ok:false,error:B(o??{message:"insert failed"})};let a=i.ok?pf(i.data.similar):null;return a?{ok:true,data:qa(s),warnings:[a]}:{ok:true,data:qa(s)}}function hf(t){return t.length===0?null:{code:"similar_titles",message:`Found ${t.length} rule(s) with a similar name.`,detail:{similar:t}}}function ff(t){return {id:t.id,workspaceId:t.workspace_id,name:t.name,content:t.content,scopeType:t.scope_type,priority:t.priority,semanticTags:t.semantic_tags??[],versionId:t.version_id,versionNumber:t.version_number,createdBy:t.created_by,lastEditedBy:t.last_edited_by,lastEditedAt:t.last_edited_at,createdAt:t.created_at,updatedAt:t.updated_at}}async function Ja(t,e){if(!t.workspaceId)return {ok:false,error:{code:"invalid_args",message:"ctx.workspaceId is required for path-based writes"}};let r=await Dt(t.supabase,t.workspaceId,e.node_path);if("error"in r)return {ok:false,error:{code:"upstream_error",message:r.error}};let n=e.name.trim(),i=await Nt(t.supabase,{workspaceId:r.workspace_id,kind:"rule",candidate:n});if(i.ok&&i.data.duplicate&&!e.allow_duplicate)return {ok:false,error:{code:"duplicate",message:`A rule named "${i.data.duplicate.title}" already exists in this workspace. Use update_rule, pick a different name, or pass allow_duplicate: true.`,detail:{existing_id:i.data.duplicate.id,existing_name:i.data.duplicate.title,similar:i.ok?i.data.similar:[]}}};let{data:s,error:o}=await t.supabase.from("rules").insert({workspace_id:r.workspace_id,name:n,content:e.content,scope_type:e.scope_type,priority:e.priority,created_by:t.userId,last_edited_by:t.userId}).select("*").single();if(o||!s)return {ok:false,error:B(o??{message:"insert failed"})};let a=ff(s),{error:l}=await t.supabase.from("node_rules").insert({node_id:r.id,rule_id:a.id});if(l)return await t.supabase.from("rules").delete().eq("id",a.id),{ok:false,error:{code:"upstream_error",message:`attach failed: ${l.message}`}};let c=i.ok?hf(i.data.similar):null;return c?{ok:true,data:a,warnings:[c]}:{ok:true,data:a}}function gf(t){return {id:t.id,workspaceId:t.workspace_id,name:t.name,description:t.description,content:t.content,source:t.source,githubUrl:t.github_url,version:t.version,tags:t.tags,semanticTags:t.semantic_tags??[],versionId:t.version_id,versionNumber:t.version_number,createdBy:t.created_by,lastEditedBy:t.last_edited_by,lastEditedAt:t.last_edited_at,createdAt:t.created_at,updatedAt:t.updated_at,contentFetchedAt:t.content_fetched_at}}async function Ka(t,e){if(!t.workspaceId)return {ok:false,error:{code:"invalid_args",message:"ctx.workspaceId is required for path-based writes"}};let r=await Dt(t.supabase,t.workspaceId,e.node_path);if("error"in r)return {ok:false,error:{code:"upstream_error",message:r.error}};let n=e.name.trim(),i=await Nt(t.supabase,{workspaceId:r.workspace_id,kind:"skill",candidate:n,maxSimilar:0});if(i.ok&&i.data.duplicate)return {ok:false,error:{code:"duplicate",message:`A skill with this name already exists in this workspace: "${i.data.duplicate.title}". Use update_skill or pick a different name.`,detail:{existing_id:i.data.duplicate.id,existing_name:i.data.duplicate.title}}};let s=e.source??"manual",{data:o,error:a}=await t.supabase.from("skills").insert({workspace_id:r.workspace_id,name:n,description:e.description,content:e.content,source:s,github_url:e.github_url??null,tags:e.tags??[],created_by:t.userId,last_edited_by:t.userId,content_fetched_at:s==="github_ref"?new Date().toISOString():null}).select("*").single();if(a||!o)return Fa(a??{})?{ok:false,error:{code:"duplicate",message:"A skill with this name already exists in this workspace. Use update_skill or pick a different name."}}:{ok:false,error:B(a??{message:"insert failed"})};let l=gf(o),{error:c}=await t.supabase.from("node_skills").insert({node_id:r.id,skill_id:l.id,is_active:true});return c?(await t.supabase.from("skills").delete().eq("id",l.id),{ok:false,error:{code:"upstream_error",message:`attach failed: ${c.message}`}}):{ok:true,data:l}}var mf=/^[A-Za-z0-9_-]+/,_f=/[\s([{'"`]/;function es(t){return t.trim().toLowerCase()}function Va(t){let e=yf(t),r=[];for(let n=0;n<e.length-2;n+=1){if(e[n]!==":"||e[n+1]!==":")continue;let i=n===0?"":e[n-1]??"";if(i&&!_f.test(i))continue;let s=e.slice(n+2).match(mf);if(!s?.[0])continue;let o=s[0];r.push({raw:o,name:es(o),start:n,end:n+2+o.length}),n+=1+o.length;}return wf(r)}function wf(t){let e=new Set,r=[];for(let n of t)e.has(n.name)||(e.add(n.name),r.push(n));return r}function yf(t){let e="",r=0,n=false,i=false;for(;r<t.length;){if(t.startsWith("```",r)){n=!n,e+=" ",r+=3;continue}let s=t[r]??"";if(!n&&s==="`"){i=!i,e+=" ",r+=1;continue}e+=n||i?s===`
|
|
49
49
|
`?`
|
|
50
|
-
`:" ":s,r+=1;}return e}var Ya=[{tag:"frontend",patterns:[/\/packages\/app\b/i,/\b(frontend|front-end|renderer|react|tsx|jsx|component|components|screen|page|view)\b/i]},{tag:"backend",patterns:[/\/packages\/mcp-server\b/i,/\b(backend|server|service|api|ipc|worker|queue)\b/i]},{tag:"database",patterns:[/\b(database|postgres|postgrest|db|sql|rpc|rls|schema)\b/i,/\/supabase\b/i]},{tag:"infra",patterns:[/\b(infra|deploy|deployment|cloudflare|r2|notarize|notarized|updater)\b/i]},{tag:"test",patterns:[/\b(test|tests|vitest|playwright|typecheck|lint|eslint|smoke)\b/i]},{tag:"docs",patterns:[/\b(docs|readme|claude\.md|agents\.md|llms\.txt|documentation)\b/i]},{tag:"config",patterns:[/\b(config|env|toml|yaml|yml|json|settings|preferences)\b/i]},{tag:"ui",patterns:[/\b(ui|ux|modal|popover|dialog|button|badge|tab|tree|layout|design|onboarding)\b/i,/\b(tasarim|tasarım|ekran|sayfa|gorunum|görünüm|yerlesim|yerleşim|rozet)\b/i]},{tag:"design-system",patterns:[/\b(design system|design-system|tokens?|theme|tailwind|shadcn|visual language)\b/i]},{tag:"i18n",patterns:[/\b(i18n|translation|translations|locale|localization|hardcoded)\b/i]},{tag:"electron",patterns:[/\b(electron|main process|renderer|tray|native menu)\b/i]},{tag:"mcp",patterns:[/\b(mcp|model context protocol|get_context|read_memory|tool surface)\b/i]},{tag:"hook",patterns:[/\b(hook|hooks|pretooluse|posttooluse|userpromptsubmit|sessionstart)\b/i]},{tag:"router",patterns:[/\b(router|routing|route|deterministic_route|ai-route)\b/i]},{tag:"performance",patterns:[/\b(performance|latency|timeout|telemetry|cache|optimize|hiz|hız)\b/i]},{tag:"supabase",patterns:[/\b(supabase|edge function|edge-function)\b/i,/\/supabase\b/i]},{tag:"edge-function",patterns:[/\b(edge function|edge-function|functions\/[a-z0-9_-]+)\b/i]},{tag:"rls",patterns:[/\b(rls|row level security|policy|policies)\b/i]},{tag:"auth",patterns:[/\b(auth|jwt|session|login|keychain|oauth)\b/i]},{tag:"billing",patterns:[/\b(billing|subscription|checkout|invoice|payment|usage limit)\b/i]},{tag:"stripe",patterns:[/\b(stripe|webhook|checkout session|paymentintent)\b/i]},{tag:"migration",patterns:[/\b(migration|migrations|schema change|alter table)\b/i]},{tag:"security",patterns:[/\b(security|secret|service role|rls|jwt|permission|access check)\b/i]},{tag:"release",patterns:[/\b(release|ship|publish|version bump|notarized|signed)\b/i]},{tag:"tree",patterns:[/\b(tree|collapse|expand|node tree|treetoolbar)\b/i]},{tag:"suggestions",patterns:[/\b(suggestion|suggestions|suggestionstab|refresh suggestion)\b/i]},{tag:"modal",patterns:[/\b(modal|dialog|popover|sheet)\b/i]},{tag:"skill-package",patterns:[/\b(skill package|skill-package|skillpackagetree|skillpackageviewer)\b/i]},{tag:"workspace",patterns:[/\b(workspace|project root|repo root|node path|root path)\b/i]},{tag:"activity",patterns:[/\b(activity|activities|recent activity|log_activity|activity log)\b/i]},{tag:"cache",patterns:[/\b(cache|cached|etag|warm|cold|ttl)\b/i]}],kf=new Set(Ya.map(t=>t.tag));function bf(t){let e=t.trim().toLowerCase().replace(/[_\s]+/g,"-").replace(/[^a-z0-9-]/g,"");return kf.has(e)?e:null}function Ga(t){let e=`${t.path??""} ${t.text??""}`,r=new Set;for(let n of t.existingTags??[]){let i=bf(n);i&&r.add(i);}for(let n of Ya)n.patterns.some(i=>i.test(e))&&r.add(n.tag);return Array.from(r).slice(0,t.limit??8)}function et(t,e){let r=Ga({existingTags:t?Array.from(t):[],limit:e.limit});return r.length>0?r:Ga(e)}function vf(t){let e=Array.isArray(t.skill_files)?t.skill_files:t.skill_files?[t.skill_files]:[];return (e.find(n=>n.path==="SKILL.md")??e.find(n=>n.role==="primary"))?.content??t.content??""}async function Mt(t,e){let[r,n,i,s]=await Promise.all([t.supabase.from("nodes").select("id, relative_path").eq("workspace_id",e.workspace_id).eq("status","active"),t.supabase.from("memories").select("id, title, node_id, semantic_tags").eq("workspace_id",e.workspace_id).eq("status","active").order("created_at",{ascending:true}),t.supabase.from("node_rules").select("node_id, rules(id, name, content, scope_type, priority, semantic_tags)"),t.supabase.from("node_skills").select("node_id, is_active, skills(id, name, description, source, tags, semantic_tags)").eq("is_active",true)]);if(r.error)return {ok:false,error:B(r.error)};if(n.error)return {ok:false,error:B(n.error)};if(i.error)return {ok:false,error:B(i.error)};if(s.error)return {ok:false,error:B(s.error)};let o=new Map;for(let u of r.data??[])o.set(u.id,u.relative_path);let a=new Map;function l(u){let d=a.get(u);return d||(d={memories:[],rules:[],skills:[]},a.set(u,d)),d}for(let u of n.data??[])l(u.node_id).memories.push({id:u.id,title:u.title,semantic_tags:et(u.semantic_tags,{text:u.title,path:o.get(u.node_id)})});for(let u of i.data??[]){let d=u.rules,p=Array.isArray(d)?d[0]:d;if(!p)continue;let h=p,f=u.node_id;l(f).rules.push({id:h.id,name:h.name,scope_type:h.scope_type,priority:h.priority,semantic_tags:et(h.semantic_tags,{text:`${h.name} ${h.content??""}`,path:o.get(f)})});}for(let u of s.data??[]){let d=u.skills,p=Array.isArray(d)?d[0]:d;if(!p)continue;let h=p,f=u.node_id;l(f).skills.push({id:h.id,name:h.name,source:h.source,semantic_tags:et(h.semantic_tags,{text:`${h.name} ${h.description??""}`,path:o.get(f),existingTags:h.tags})});}let c=[];for(let[u,d]of a.entries()){if(e.exclude_node_id&&u===e.exclude_node_id)continue;let p=o.get(u);p&&(d.memories.length===0&&d.rules.length===0&&d.skills.length===0||c.push({node_id:u,relative_path:p,memories:d.memories,rules:d.rules,skills:d.skills}));}return c.sort((u,d)=>u.relative_path.localeCompare(d.relative_path)),{ok:true,data:c}}function Sf(t,e=160){let r=t.replace(/`[^`]*`/g,"").replace(/#+\s*/g,"").replace(/[*_~]+/g,"").trim(),n=r.indexOf("."),i=n>0&&n<e?r.slice(0,n+1):r.slice(0,e);return i.length<r.length?`${i}\u2026`:i}async function Cf(t,e,r){let n=Va(r??"");if(n.length===0)return {invokedSkills:[],missingInvokedSkills:[]};let{data:i,error:s}=await t.from("skills").select("id, name, description, content, source, github_url, skill_files(path, content, role)").eq("workspace_id",e).is("deleted_at",null);if(s)throw new Error(`skill invocation lookup failed: ${s.message}`);let o=new Map;for(let c of i??[]){let u=c;if(!u.name)continue;let d=es(u.name);o.set(d,[...o.get(d)??[],c]);}let a=[],l=[];for(let c of n){let u=o.get(c.name)??[];if(u.length===0){l.push({name:c.name,reason:"not_found"});continue}if(u.length>1){l.push({name:c.name,reason:"duplicate"});continue}let d=u[0];a.push({id:d.id,name:d.name,description:d.description,content:vf(d),source:d.source,githubUrl:d.github_url,nodeRelativePath:null});}return {invokedSkills:a,missingInvokedSkills:l}}async function yn(t,e){let r=await Cf(t.supabase,e.workspace_id,e.user_intent),{data:n,error:i}=await t.supabase.from("nodes").select("id, name, relative_path").eq("workspace_id",e.workspace_id).eq("relative_path",e.relative_path).maybeSingle();if(i)return {ok:false,error:B(i)};if(!n){let h=await Mt(t,{workspace_id:e.workspace_id});return {ok:true,data:{resolved_workspace_path:e.relative_path||"/",node:null,memories:[],rules:[],skills:[],workspace_overview:h.ok?h.data:[],invoked_skills:r.invokedSkills.length>0?r.invokedSkills:void 0,missing_invoked_skills:r.missingInvokedSkills.length>0?r.missingInvokedSkills:void 0}}}let s=n.id,[o,a,l,c]=await Promise.all([t.supabase.from("memories").select("id, title, content, semantic_tags").eq("node_id",s).eq("status","active").order("created_at",{ascending:true}),t.supabase.from("node_rules").select("rules(id, name, content, scope_type, priority, semantic_tags)").eq("node_id",s),t.supabase.from("node_skills").select("skills(id, name, description, source, tags, semantic_tags)").eq("node_id",s).eq("is_active",true),Mt(t,{workspace_id:e.workspace_id,exclude_node_id:s})]);if(o.error)return {ok:false,error:B(o.error)};if(a.error)return {ok:false,error:B(a.error)};if(l.error)return {ok:false,error:B(l.error)};let u=(o.data??[]).map(h=>({id:h.id,title:h.title,preview:Sf(h.content??""),semantic_tags:et(h.semantic_tags,{text:`${h.title} ${(h.content??"").slice(0,1e3)}`,path:n.relative_path})})),d=[];for(let h of a.data??[]){let f=h.rules,m=Array.isArray(f)?f[0]:f;if(!m)continue;let _=m;d.push({id:_.id,name:_.name,scope_type:_.scope_type,priority:_.priority,semantic_tags:et(_.semantic_tags,{text:`${_.name} ${_.content??""}`,path:n.relative_path})});}let p=[];for(let h of l.data??[]){let f=h.skills,m=Array.isArray(f)?f[0]:f;if(!m)continue;let _=m;p.push({id:_.id,name:_.name,description:_.description,source:_.source,semantic_tags:et(_.semantic_tags,{text:`${_.name} ${_.description??""}`,path:n.relative_path,existingTags:_.tags})});}return {ok:true,data:{resolved_workspace_path:e.relative_path||n.relative_path,node:{id:s,name:n.name,relative_path:n.relative_path},memories:u,rules:d,skills:p,workspace_overview:c.ok?c.data:[],invoked_skills:r.invokedSkills.length>0?r.invokedSkills:void 0,missing_invoked_skills:r.missingInvokedSkills.length>0?r.missingInvokedSkills:void 0}}}async function Xa(t){if(t.recipientUserIds.length===0)return {ok:true,skipped:"empty_recipients"};let{error:e}=await t.supabase.rpc("emit_notification",{p_event_type:t.eventType,p_workspace_id:t.workspaceId,p_actor_user_id:t.actorUserId,p_payload:t.payload,p_recipient_user_ids:t.recipientUserIds});return e?(console.warn(`[notifications:emit] ${t.eventType} failed:`,e.message),{ok:false,error:e.message}):{ok:true}}async function Za(t,e,r=null){let{data:n}=await t.from("workspaces").select("organization_id").eq("id",e).maybeSingle();if(!n)return [];let{data:i,error:s}=await t.from("organization_members").select("user_id, role").eq("organization_id",n.organization_id).in("role",["owner","admin"]);if(s||!i)return [];let o=new Set;for(let a of i)r!=null&&a.user_id===r||o.add(a.user_id);return Array.from(o)}async function Ef(t,e,r){let n=e==="memory"?"memories":"rules",i=e==="memory"?"title":"name",{data:s}=await t.from(n).select(`created_by, ${i}`).eq("id",r).maybeSingle();return s?{creatorId:s.created_by??null,title:s[i]??""}:{creatorId:null,title:""}}function ts(t){return {id:t.id,workspaceId:t.workspace_id,suggestionId:t.suggestion_id,subjectType:t.subject_type,subjectId:t.subject_id,formulaId:t.formula_id,status:t.status,requestedByUserId:t.requested_by_user_id,claimedByAi:t.claimed_by_ai,claimedAt:t.claimed_at,resolvedAt:t.resolved_at,resolvedNote:t.resolved_note,createdAt:t.created_at,updatedAt:t.updated_at,brief:t.brief??{}}}async function Qa(t,e){let r=e.include_in_progress?["pending","in_progress"]:["pending"],{data:n,error:i}=await t.supabase.from("suggestion_refreshes").select("id, subject_type, subject_id, formula_id, status, created_at, brief").eq("workspace_id",e.workspace_id).in("status",r).order("created_at",{ascending:true});return i?{ok:false,error:B(i)}:{ok:true,data:(n??[]).map(a=>{let l=a.brief??{};return {id:a.id,subjectType:a.subject_type,subjectId:a.subject_id,subjectTitle:l.subject?.title??"(unknown)",nodePath:l.subject?.nodePath??"/",formulaId:a.formula_id,humanReason:l.signal?.humanReason??a.formula_id,status:a.status,createdAt:a.created_at,hasProposedPatch:!!l.proposedPatch?.newBody}})}}async function el(t,e){let{data:r,error:n}=await t.supabase.from("suggestion_refreshes").select("*").eq("id",e.refresh_id).maybeSingle();if(n)return {ok:false,error:B(n)};if(!r)return {ok:false,error:{code:"not_found",message:`Refresh ${e.refresh_id} not found`}};let i=ts(r);if(i.status==="pending"){let s=new Date().toISOString(),{data:o,error:a}=await t.supabase.from("suggestion_refreshes").update({status:"in_progress",claimed_at:s,claimed_by_ai:e.claimed_by??null}).eq("id",e.refresh_id).eq("status","pending").select("*").maybeSingle();if(a)return {ok:false,error:B(a)};if(o)return {ok:true,data:ts(o)}}return {ok:true,data:i}}async function tl(t,e){let r=new Date().toISOString(),{data:n,error:i}=await t.supabase.from("suggestion_refreshes").update({status:e.status,resolved_at:r,resolved_note:e.note??null,...e.claimed_by?{claimed_by_ai:e.claimed_by}:{}}).eq("id",e.refresh_id).select("*").maybeSingle();if(i)return {ok:false,error:B(i)};if(!n)return {ok:false,error:{code:"not_found",message:`Refresh ${e.refresh_id} not found`}};let s=n;s.suggestion_id&&await t.supabase.from("suggestions").update({resolved_at:r}).eq("id",s.suggestion_id).is("resolved_at",null);let o=e.status==="applied"?30:365,{data:a}=await t.supabase.auth.getUser(),l=a?.user?.id;if(l&&await t.supabase.from("suggestion_dismissals").insert({workspace_id:s.workspace_id,subject_type:s.subject_type,subject_id:s.subject_id,formula_id:s.formula_id,action:"keep",dismiss_count:1,next_recheck_at:new Date(Date.now()+o*864e5).toISOString(),user_id:l}),e.status==="applied"||e.status==="rejected")try{let c=e.status==="applied"?"suggestion.applied":"suggestion.rejected",u=s.subject_type,d=s.subject_id,p=s.workspace_id,{creatorId:h,title:f}=await Ef(t.supabase,u,d),m=await Za(t.supabase,p,t.userId),_=new Set;h&&h!==t.userId&&_.add(h);for(let y of m)_.add(y);let b={subject_type:u,subject_title:f};e.status==="rejected"&&e.note&&(b.reason=e.note);let w=await Xa({supabase:t.supabase,eventType:c,workspaceId:p,actorUserId:t.userId,payload:b,recipientUserIds:Array.from(_)});w.ok||console.warn(`[notifications:emit] suggestion resolution failed: ${w.error}`);}catch(c){console.warn("[notifications:emit] suggestion resolution threw:",c);}return {ok:true,data:ts(s)}}var Rf="<!-- managed by Pathrule \u2014 do not edit this file manually. Cloud state is authoritative. Local edits are overwritten. -->",xf=["# Pathrule Workspace","","Pathrule is this workspace's shared memory, rule, and skill layer for AI agents.","Use it as a smart reminder system, not a full-context dump.","","## Context Policy","","- Pathrule is the first knowledge layer for this workspace. Use hook context first: metadata, relevant rule titles, path reminders, and filename/skill matches.","- `::skill-name` is a hard gate: use the exact injected skill; if missing, stop and resolve it through Pathrule/MCP before file edits.",'- Do not reflexively call `pathrule_get_context` before every small known-path code task. For discovery, inventory, architecture, recent activity, or "list/show/find/where/which" prompts (Turkish: listele, g\xF6ster, bul, nerede, hangi, neler), call it before any grep/read/fallback when hook context is missing, ambiguous, or stale.',"- Hook silence on a topic does not mean Pathrule has no relevant memory/rule. For discovery/inventory/architecture questions, call `pathrule_get_context` first; fall back to files, git, or general knowledge only after Pathrule returns nothing relevant.","- When calling `pathrule_get_context`, pass `cwd`, `user_intent`, and `omit_protocol: true`; this file already contains the protocol.","- Read full bodies with `pathrule_read_memory`, `pathrule_read_rule`, or `pathrule_read_skill` when a surfaced title/id is relevant.","- Treat existing local edits as protected user/team work: inspect overlaps, never revert unrelated changes, and keep edits scoped.","- Obey every surfaced rule. If a user request conflicts with a Pathrule rule, warn before taking action.","","## Writes","","- Pathrule cloud is the source of truth. Do not create local memory files such as `MEMORY.md` or `~/.claude/memory/`.","- Use path-first writes for lasting project knowledge: `pathrule_write_memory`, `pathrule_write_rule`, and `pathrule_write_skill` take the most specific workspace-relative `node_path`.","- Do not edit materialized local Pathrule files as the source of truth. This includes `.codex/skills/**/SKILL.md`, `.claude/skills/**`, rendered companion files, and synced skill/memory/rule files. Read only for orientation; create/update cloud records with the Pathrule MCP write/update tools.","- After any file-modifying response, call `pathrule_log_activity` once with domain, action, scope, subjects, files_touched, and a concise task_summary.",""].join(`
|
|
50
|
+
`:" ":s,r+=1;}return e}var Ya=[{tag:"frontend",patterns:[/\/packages\/app\b/i,/\b(frontend|front-end|renderer|react|tsx|jsx|component|components|screen|page|view)\b/i]},{tag:"backend",patterns:[/\/packages\/mcp-server\b/i,/\b(backend|server|service|api|ipc|worker|queue)\b/i]},{tag:"database",patterns:[/\b(database|postgres|postgrest|db|sql|rpc|rls|schema)\b/i,/\/supabase\b/i]},{tag:"infra",patterns:[/\b(infra|deploy|deployment|cloudflare|r2|notarize|notarized|updater)\b/i]},{tag:"test",patterns:[/\b(test|tests|vitest|playwright|typecheck|lint|eslint|smoke)\b/i]},{tag:"docs",patterns:[/\b(docs|readme|claude\.md|agents\.md|llms\.txt|documentation)\b/i]},{tag:"config",patterns:[/\b(config|env|toml|yaml|yml|json|settings|preferences)\b/i]},{tag:"ui",patterns:[/\b(ui|ux|modal|popover|dialog|button|badge|tab|tree|layout|design|onboarding)\b/i,/\b(tasarim|tasarım|ekran|sayfa|gorunum|görünüm|yerlesim|yerleşim|rozet)\b/i]},{tag:"design-system",patterns:[/\b(design system|design-system|tokens?|theme|tailwind|shadcn|visual language)\b/i]},{tag:"i18n",patterns:[/\b(i18n|translation|translations|locale|localization|hardcoded)\b/i]},{tag:"electron",patterns:[/\b(electron|main process|renderer|tray|native menu)\b/i]},{tag:"mcp",patterns:[/\b(mcp|model context protocol|get_context|read_memory|tool surface)\b/i]},{tag:"hook",patterns:[/\b(hook|hooks|pretooluse|posttooluse|userpromptsubmit|sessionstart)\b/i]},{tag:"router",patterns:[/\b(router|routing|route|deterministic_route|ai-route)\b/i]},{tag:"performance",patterns:[/\b(performance|latency|timeout|telemetry|cache|optimize|hiz|hız)\b/i]},{tag:"supabase",patterns:[/\b(supabase|edge function|edge-function)\b/i,/\/supabase\b/i]},{tag:"edge-function",patterns:[/\b(edge function|edge-function|functions\/[a-z0-9_-]+)\b/i]},{tag:"rls",patterns:[/\b(rls|row level security|policy|policies)\b/i]},{tag:"auth",patterns:[/\b(auth|jwt|session|login|keychain|oauth)\b/i]},{tag:"billing",patterns:[/\b(billing|subscription|checkout|invoice|payment|usage limit)\b/i]},{tag:"stripe",patterns:[/\b(stripe|webhook|checkout session|paymentintent)\b/i]},{tag:"migration",patterns:[/\b(migration|migrations|schema change|alter table)\b/i]},{tag:"security",patterns:[/\b(security|secret|service role|rls|jwt|permission|access check)\b/i]},{tag:"release",patterns:[/\b(release|ship|publish|version bump|notarized|signed)\b/i]},{tag:"tree",patterns:[/\b(tree|collapse|expand|node tree|treetoolbar)\b/i]},{tag:"suggestions",patterns:[/\b(suggestion|suggestions|suggestionstab|refresh suggestion)\b/i]},{tag:"modal",patterns:[/\b(modal|dialog|popover|sheet)\b/i]},{tag:"skill-package",patterns:[/\b(skill package|skill-package|skillpackagetree|skillpackageviewer)\b/i]},{tag:"workspace",patterns:[/\b(workspace|project root|repo root|node path|root path)\b/i]},{tag:"activity",patterns:[/\b(activity|activities|recent activity|log_activity|activity log)\b/i]},{tag:"cache",patterns:[/\b(cache|cached|etag|warm|cold|ttl)\b/i]}],kf=new Set(Ya.map(t=>t.tag));function bf(t){let e=t.trim().toLowerCase().replace(/[_\s]+/g,"-").replace(/[^a-z0-9-]/g,"");return kf.has(e)?e:null}function Ga(t){let e=`${t.path??""} ${t.text??""}`,r=new Set;for(let n of t.existingTags??[]){let i=bf(n);i&&r.add(i);}for(let n of Ya)n.patterns.some(i=>i.test(e))&&r.add(n.tag);return Array.from(r).slice(0,t.limit??8)}function et(t,e){let r=Ga({existingTags:t?Array.from(t):[],limit:e.limit});return r.length>0?r:Ga(e)}function vf(t){let e=Array.isArray(t.skill_files)?t.skill_files:t.skill_files?[t.skill_files]:[];return (e.find(n=>n.path==="SKILL.md")??e.find(n=>n.role==="primary"))?.content??t.content??""}async function Mt(t,e){let[r,n,i,s]=await Promise.all([t.supabase.from("nodes").select("id, relative_path").eq("workspace_id",e.workspace_id).eq("status","active"),t.supabase.from("memories").select("id, title, node_id, semantic_tags").eq("workspace_id",e.workspace_id).eq("status","active").order("created_at",{ascending:true}),t.supabase.from("node_rules").select("node_id, rules(id, name, content, scope_type, priority, semantic_tags)"),t.supabase.from("node_skills").select("node_id, is_active, skills(id, name, description, source, tags, semantic_tags)").eq("is_active",true)]);if(r.error)return {ok:false,error:B(r.error)};if(n.error)return {ok:false,error:B(n.error)};if(i.error)return {ok:false,error:B(i.error)};if(s.error)return {ok:false,error:B(s.error)};let o=new Map;for(let u of r.data??[])o.set(u.id,u.relative_path);let a=new Map;function l(u){let d=a.get(u);return d||(d={memories:[],rules:[],skills:[]},a.set(u,d)),d}for(let u of n.data??[])l(u.node_id).memories.push({id:u.id,title:u.title,semantic_tags:et(u.semantic_tags,{text:u.title,path:o.get(u.node_id)})});for(let u of i.data??[]){let d=u.rules,p=Array.isArray(d)?d[0]:d;if(!p)continue;let h=p,f=u.node_id;l(f).rules.push({id:h.id,name:h.name,scope_type:h.scope_type,priority:h.priority,semantic_tags:et(h.semantic_tags,{text:`${h.name} ${h.content??""}`,path:o.get(f)})});}for(let u of s.data??[]){let d=u.skills,p=Array.isArray(d)?d[0]:d;if(!p)continue;let h=p,f=u.node_id;l(f).skills.push({id:h.id,name:h.name,source:h.source,semantic_tags:et(h.semantic_tags,{text:`${h.name} ${h.description??""}`,path:o.get(f),existingTags:h.tags})});}let c=[];for(let[u,d]of a.entries()){if(e.exclude_node_id&&u===e.exclude_node_id)continue;let p=o.get(u);p&&(d.memories.length===0&&d.rules.length===0&&d.skills.length===0||c.push({node_id:u,relative_path:p,memories:d.memories,rules:d.rules,skills:d.skills}));}return c.sort((u,d)=>u.relative_path.localeCompare(d.relative_path)),{ok:true,data:c}}function Sf(t,e=160){let r=t.replace(/`[^`]*`/g,"").replace(/#+\s*/g,"").replace(/[*_~]+/g,"").trim(),n=r.indexOf("."),i=n>0&&n<e?r.slice(0,n+1):r.slice(0,e);return i.length<r.length?`${i}\u2026`:i}async function Cf(t,e,r){let n=Va(r??"");if(n.length===0)return {invokedSkills:[],missingInvokedSkills:[]};let{data:i,error:s}=await t.from("skills").select("id, name, description, content, source, github_url, skill_files(path, content, role)").eq("workspace_id",e).is("deleted_at",null);if(s)throw new Error(`skill invocation lookup failed: ${s.message}`);let o=new Map;for(let c of i??[]){let u=c;if(!u.name)continue;let d=es(u.name);o.set(d,[...o.get(d)??[],c]);}let a=[],l=[];for(let c of n){let u=o.get(c.name)??[];if(u.length===0){l.push({name:c.name,reason:"not_found"});continue}if(u.length>1){l.push({name:c.name,reason:"duplicate"});continue}let d=u[0];a.push({id:d.id,name:d.name,description:d.description,content:vf(d),source:d.source,githubUrl:d.github_url,nodeRelativePath:null});}return {invokedSkills:a,missingInvokedSkills:l}}async function kn(t,e){let r=await Cf(t.supabase,e.workspace_id,e.user_intent),{data:n,error:i}=await t.supabase.from("nodes").select("id, name, relative_path").eq("workspace_id",e.workspace_id).eq("relative_path",e.relative_path).maybeSingle();if(i)return {ok:false,error:B(i)};if(!n){let h=await Mt(t,{workspace_id:e.workspace_id});return {ok:true,data:{resolved_workspace_path:e.relative_path||"/",node:null,memories:[],rules:[],skills:[],workspace_overview:h.ok?h.data:[],invoked_skills:r.invokedSkills.length>0?r.invokedSkills:void 0,missing_invoked_skills:r.missingInvokedSkills.length>0?r.missingInvokedSkills:void 0}}}let s=n.id,[o,a,l,c]=await Promise.all([t.supabase.from("memories").select("id, title, content, semantic_tags").eq("node_id",s).eq("status","active").order("created_at",{ascending:true}),t.supabase.from("node_rules").select("rules(id, name, content, scope_type, priority, semantic_tags)").eq("node_id",s),t.supabase.from("node_skills").select("skills(id, name, description, source, tags, semantic_tags)").eq("node_id",s).eq("is_active",true),Mt(t,{workspace_id:e.workspace_id,exclude_node_id:s})]);if(o.error)return {ok:false,error:B(o.error)};if(a.error)return {ok:false,error:B(a.error)};if(l.error)return {ok:false,error:B(l.error)};let u=(o.data??[]).map(h=>({id:h.id,title:h.title,preview:Sf(h.content??""),semantic_tags:et(h.semantic_tags,{text:`${h.title} ${(h.content??"").slice(0,1e3)}`,path:n.relative_path})})),d=[];for(let h of a.data??[]){let f=h.rules,m=Array.isArray(f)?f[0]:f;if(!m)continue;let _=m;d.push({id:_.id,name:_.name,scope_type:_.scope_type,priority:_.priority,semantic_tags:et(_.semantic_tags,{text:`${_.name} ${_.content??""}`,path:n.relative_path})});}let p=[];for(let h of l.data??[]){let f=h.skills,m=Array.isArray(f)?f[0]:f;if(!m)continue;let _=m;p.push({id:_.id,name:_.name,description:_.description,source:_.source,semantic_tags:et(_.semantic_tags,{text:`${_.name} ${_.description??""}`,path:n.relative_path,existingTags:_.tags})});}return {ok:true,data:{resolved_workspace_path:e.relative_path||n.relative_path,node:{id:s,name:n.name,relative_path:n.relative_path},memories:u,rules:d,skills:p,workspace_overview:c.ok?c.data:[],invoked_skills:r.invokedSkills.length>0?r.invokedSkills:void 0,missing_invoked_skills:r.missingInvokedSkills.length>0?r.missingInvokedSkills:void 0}}}async function Xa(t){if(t.recipientUserIds.length===0)return {ok:true,skipped:"empty_recipients"};let{error:e}=await t.supabase.rpc("emit_notification",{p_event_type:t.eventType,p_workspace_id:t.workspaceId,p_actor_user_id:t.actorUserId,p_payload:t.payload,p_recipient_user_ids:t.recipientUserIds});return e?(console.warn(`[notifications:emit] ${t.eventType} failed:`,e.message),{ok:false,error:e.message}):{ok:true}}async function Za(t,e,r=null){let{data:n}=await t.from("workspaces").select("organization_id").eq("id",e).maybeSingle();if(!n)return [];let{data:i,error:s}=await t.from("organization_members").select("user_id, role").eq("organization_id",n.organization_id).in("role",["owner","admin"]);if(s||!i)return [];let o=new Set;for(let a of i)r!=null&&a.user_id===r||o.add(a.user_id);return Array.from(o)}async function Ef(t,e,r){let n=e==="memory"?"memories":"rules",i=e==="memory"?"title":"name",{data:s}=await t.from(n).select(`created_by, ${i}`).eq("id",r).maybeSingle();return s?{creatorId:s.created_by??null,title:s[i]??""}:{creatorId:null,title:""}}function ts(t){return {id:t.id,workspaceId:t.workspace_id,suggestionId:t.suggestion_id,subjectType:t.subject_type,subjectId:t.subject_id,formulaId:t.formula_id,status:t.status,requestedByUserId:t.requested_by_user_id,claimedByAi:t.claimed_by_ai,claimedAt:t.claimed_at,resolvedAt:t.resolved_at,resolvedNote:t.resolved_note,createdAt:t.created_at,updatedAt:t.updated_at,brief:t.brief??{}}}async function Qa(t,e){let r=e.include_in_progress?["pending","in_progress"]:["pending"],{data:n,error:i}=await t.supabase.from("suggestion_refreshes").select("id, subject_type, subject_id, formula_id, status, created_at, brief").eq("workspace_id",e.workspace_id).in("status",r).order("created_at",{ascending:true});return i?{ok:false,error:B(i)}:{ok:true,data:(n??[]).map(a=>{let l=a.brief??{};return {id:a.id,subjectType:a.subject_type,subjectId:a.subject_id,subjectTitle:l.subject?.title??"(unknown)",nodePath:l.subject?.nodePath??"/",formulaId:a.formula_id,humanReason:l.signal?.humanReason??a.formula_id,status:a.status,createdAt:a.created_at,hasProposedPatch:!!l.proposedPatch?.newBody}})}}async function el(t,e){let{data:r,error:n}=await t.supabase.from("suggestion_refreshes").select("*").eq("id",e.refresh_id).maybeSingle();if(n)return {ok:false,error:B(n)};if(!r)return {ok:false,error:{code:"not_found",message:`Refresh ${e.refresh_id} not found`}};let i=ts(r);if(i.status==="pending"){let s=new Date().toISOString(),{data:o,error:a}=await t.supabase.from("suggestion_refreshes").update({status:"in_progress",claimed_at:s,claimed_by_ai:e.claimed_by??null}).eq("id",e.refresh_id).eq("status","pending").select("*").maybeSingle();if(a)return {ok:false,error:B(a)};if(o)return {ok:true,data:ts(o)}}return {ok:true,data:i}}async function tl(t,e){let r=new Date().toISOString(),{data:n,error:i}=await t.supabase.from("suggestion_refreshes").update({status:e.status,resolved_at:r,resolved_note:e.note??null,...e.claimed_by?{claimed_by_ai:e.claimed_by}:{}}).eq("id",e.refresh_id).select("*").maybeSingle();if(i)return {ok:false,error:B(i)};if(!n)return {ok:false,error:{code:"not_found",message:`Refresh ${e.refresh_id} not found`}};let s=n;s.suggestion_id&&await t.supabase.from("suggestions").update({resolved_at:r}).eq("id",s.suggestion_id).is("resolved_at",null);let o=e.status==="applied"?30:365,{data:a}=await t.supabase.auth.getUser(),l=a?.user?.id;if(l&&await t.supabase.from("suggestion_dismissals").insert({workspace_id:s.workspace_id,subject_type:s.subject_type,subject_id:s.subject_id,formula_id:s.formula_id,action:"keep",dismiss_count:1,next_recheck_at:new Date(Date.now()+o*864e5).toISOString(),user_id:l}),e.status==="applied"||e.status==="rejected")try{let c=e.status==="applied"?"suggestion.applied":"suggestion.rejected",u=s.subject_type,d=s.subject_id,p=s.workspace_id,{creatorId:h,title:f}=await Ef(t.supabase,u,d),m=await Za(t.supabase,p,t.userId),_=new Set;h&&h!==t.userId&&_.add(h);for(let y of m)_.add(y);let b={subject_type:u,subject_title:f};e.status==="rejected"&&e.note&&(b.reason=e.note);let w=await Xa({supabase:t.supabase,eventType:c,workspaceId:p,actorUserId:t.userId,payload:b,recipientUserIds:Array.from(_)});w.ok||console.warn(`[notifications:emit] suggestion resolution failed: ${w.error}`);}catch(c){console.warn("[notifications:emit] suggestion resolution threw:",c);}return {ok:true,data:ts(s)}}var Rf="<!-- managed by Pathrule \u2014 do not edit this file manually. Cloud state is authoritative. Local edits are overwritten. -->",xf=["# Pathrule Workspace","","Pathrule is this workspace's shared memory, rule, and skill layer for AI agents.","Use it as a smart reminder system, not a full-context dump.","","## Context Policy","","- Pathrule is the first knowledge layer for this workspace. Use hook context first: metadata, relevant rule titles, path reminders, and filename/skill matches.","- `::skill-name` is a hard gate: use the exact injected skill; if missing, stop and resolve it through Pathrule/MCP before file edits.",'- Do not reflexively call `pathrule_get_context` before every small known-path code task. For discovery, inventory, architecture, recent activity, or "list/show/find/where/which" prompts (Turkish: listele, g\xF6ster, bul, nerede, hangi, neler), call it before any grep/read/fallback when hook context is missing, ambiguous, or stale.',"- Hook silence on a topic does not mean Pathrule has no relevant memory/rule. For discovery/inventory/architecture questions, call `pathrule_get_context` first; fall back to files, git, or general knowledge only after Pathrule returns nothing relevant.","- When calling `pathrule_get_context`, pass `cwd`, `user_intent`, and `omit_protocol: true`; this file already contains the protocol.","- Read full bodies with `pathrule_read_memory`, `pathrule_read_rule`, or `pathrule_read_skill` when a surfaced title/id is relevant.","- Treat existing local edits as protected user/team work: inspect overlaps, never revert unrelated changes, and keep edits scoped.","- Obey every surfaced rule. If a user request conflicts with a Pathrule rule, warn before taking action.","","## Writes","","- Pathrule cloud is the source of truth. Do not create local memory files such as `MEMORY.md` or `~/.claude/memory/`.","- Use path-first writes for lasting project knowledge: `pathrule_write_memory`, `pathrule_write_rule`, and `pathrule_write_skill` take the most specific workspace-relative `node_path`.","- Do not edit materialized local Pathrule files as the source of truth. This includes `.codex/skills/**/SKILL.md`, `.claude/skills/**`, rendered companion files, and synced skill/memory/rule files. Read only for orientation; create/update cloud records with the Pathrule MCP write/update tools.","- After any file-modifying response, call `pathrule_log_activity` once with domain, action, scope, subjects, files_touched, and a concise task_summary.",""].join(`
|
|
51
51
|
`);function rl(t){let e=[Rf,"",xf].join(`
|
|
52
52
|
`).replace(/\n{3,}/g,`
|
|
53
53
|
|
|
54
54
|
`);return e.endsWith(`
|
|
55
55
|
`)?e:`${e}
|
|
56
|
-
`}async function Pf(t,e){let{data:r,error:n}=await t.from("workspaces").select("name").eq("id",e).maybeSingle();if(n)throw new Error(`workspaces lookup failed: ${n.message}`);if(!r)throw new Error(`workspace ${e} not found (RLS or deleted)`);return r.name}async function nl(t){await Pf(t.supabase,t.workspaceId);let r={supabase:t.supabase},[n,i]=await Promise.all([
|
|
56
|
+
`}async function Pf(t,e){let{data:r,error:n}=await t.from("workspaces").select("name").eq("id",e).maybeSingle();if(n)throw new Error(`workspaces lookup failed: ${n.message}`);if(!r)throw new Error(`workspace ${e} not found (RLS or deleted)`);return r.name}async function nl(t){await Pf(t.supabase,t.workspaceId);let r={supabase:t.supabase},[n,i]=await Promise.all([kn(r,{workspace_id:t.workspaceId,relative_path:"/"}),Mt(r,{workspace_id:t.workspaceId})]);if(!n.ok)throw new Error(`getContext failed: ${n.error.message}`);if(!i.ok)throw new Error(`getWorkspaceOverview failed: ${i.error.message}`);let s=[];try{let l=new Date(Date.now()-12096e5).toISOString(),{data:c}=await t.supabase.from("activity_logs").select("domain, action, task_summary, created_at").eq("workspace_id",t.workspaceId).eq("status","active").gte("created_at",l).order("created_at",{ascending:!1}).limit(8);c&&(s=c);}catch{}let o=rl({rootContext:{memories:n.data.memories.map(l=>({id:l.id,title:l.title,preview:l.preview})),rules:n.data.rules,skills:n.data.skills.map(l=>({id:l.id,name:l.name,description:l.description,source:l.source}))},overview:i.data,recentActivities:s.length>0?s:void 0}),a=true;try{let{data:l,error:c}=await t.supabase.from("claude_md_snapshots").select("body").eq("workspace_id",t.workspaceId).maybeSingle();if(c)console.warn("[claude-md] snapshot read skipped:",c.message);else if(a=!l||l.body!==o,a){let{error:u}=await t.supabase.from("claude_md_snapshots").upsert({workspace_id:t.workspaceId,body:o,rendered_by:t.userId,rendered_at:new Date().toISOString()});u&&console.warn("[claude-md] snapshot upsert skipped:",u.message);}}catch{}return {body:o,snapshotChanged:a}}function il(t){let e=rs(t),r=2166136261;for(let n=0;n<e.length;n++)r^=e.charCodeAt(n),r=Math.imul(r,16777619);return (r>>>0).toString(16).padStart(8,"0")}function rs(t){return t===null?"null":Array.isArray(t)?"["+t.map(rs).join(",")+"]":typeof t=="object"?"{"+Object.keys(t).sort().map(n=>JSON.stringify(n)+":"+rs(t[n])).join(",")+"}":JSON.stringify(t)}var sl={PreToolUse:"preToolUse",PostToolUse:"postToolUse",UserPromptSubmit:"beforeSubmitPrompt",SessionStart:"sessionStart",SessionEnd:"sessionEnd",Stop:"stop",SubagentStop:"subagentStop",Notification:null,PreCompact:null,PostCompact:null};var ol={Edit:"Write",Bash:"Shell"},al={PreToolUse:"PreToolUse",PostToolUse:"PostToolUse",UserPromptSubmit:"UserPromptSubmit",SessionStart:"SessionStart",SessionEnd:null,Stop:"Stop",SubagentStop:null,Notification:null,PreCompact:null,PostCompact:null},ll={Edit:"apply_patch",Write:"apply_patch"};var ns=null;function Tf(t){return !!(t.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\"))}function is(t){if(typeof t!="string"||t.length===0)throw new Error("setHookCommand requires a non-empty string");if(t.startsWith("~"))throw new Error(`setHookCommand requires an absolute path; got ${t}. Tilde paths are not expanded by Codex's hook spawn (no shell), so they ENOENT silently. Resolve homedir() in the caller.`);if(!Tf(t))throw new Error(`setHookCommand requires an absolute path; got ${t}. Relative paths (e.g. bin/pathrule-hook.js) resolve against the AI client's working directory at hook spawn time, which is not stable.`);ns=t;}function ss(){if(ns===null)throw new Error("Pathrule hook command not configured. Each Node entry point (electron main, mcp-server, build scripts) must call setHookCommand(absolutePath) at startup before invoking any merger (ensureClaudeSettingsHook, ensureCodexHooks, etc.).");return ns}var Af=new Set(["Read","Write","Grep","Delete","Task","Shell"]),If=new Set(["SessionStart","PreToolUse","PostToolUse","Stop","SubagentStop","SessionEnd"]);function os(t){return t.map(e=>({matcher:e.matcher,hooks:e.hooks.map(r=>({...r}))}))}function Of(t){if(!t.matcher)return t;let e=new Set,r=[];for(let n of t.matcher.split("|")){let i=ol[n]??n;Af.has(i)&&(e.has(i)||(e.add(i),r.push(i)));}return r.length===0?null:{...t,matcher:r.join("|")}}function Be(t){let e=ss();return {hooks:{SessionStart:[{hooks:[{type:"command",command:e}]}],PreToolUse:[{matcher:"Read|Edit|Write|Grep|Glob|Bash",hooks:[{type:"command",command:e}]}],PostToolUse:[{matcher:"Read|Edit|Write|Bash",hooks:[{type:"command",command:e}]}],UserPromptSubmit:[{hooks:[{type:"command",command:e}]}],Stop:[{hooks:[{type:"command",command:e}]}],SubagentStop:[{hooks:[{type:"command",command:e}]}],SessionEnd:[{hooks:[{type:"command",command:e}]}]}}}function as(t){let e={};for(let[r,n]of Object.entries(t.hooks)){let i=r;if(!If.has(i))continue;let s=sl[i];if(!s||!n||n.length===0)continue;let o=os(n).map(Of).filter(a=>a!==null);o.length!==0&&(e[s]=o);}return e}function cl(t){return `${JSON.stringify({version:1,hooks:as(t)},null,2)}
|
|
57
57
|
`}var $f=new Set(["Bash","apply_patch"]),Nf=new Set(["SessionStart","PreToolUse","PostToolUse","UserPromptSubmit","Stop"]);function jf(t){if(!t.matcher)return t;let e=new Set,r=[];for(let n of t.matcher.split("|")){let i=ll[n]??n;$f.has(i)&&(e.has(i)||(e.add(i),r.push(i)));}return r.length===0?null:{...t,matcher:r.join("|")}}function ls(t){let e={};for(let[r,n]of Object.entries(t.hooks)){let i=r;if(!Nf.has(i))continue;let s=al[i];if(!s||!n||n.length===0)continue;let o=os(n).map(jf).filter(a=>a!==null);if(o.length===0&&n.some(a=>!a.matcher)){e[s]=os(n).filter(a=>!a.matcher);continue}o.length!==0&&(e[s]=o);}return e}function ul(t){return `${JSON.stringify({hooks:ls(t)},null,2)}
|
|
58
|
-
`}var
|
|
59
|
-
`)}var Df=["pathrule-hook.js","pathrule_log_activity"];function Mf(){return Be().hooks}function Lf(){return as(Be())}function Uf(){return ls(Be())}function
|
|
58
|
+
`}var bn={before:["Pathrule is the first knowledge layer for this workspace. Hooks auto-inject path-scoped memory/rule titles + session digest on every tool call and user prompt (M12). Trust that context before falling back to files, git, or general knowledge.","`::skill-name` is a hard gate: use the exact injected skill; if missing, stop and resolve it through Pathrule/MCP before file edits.","Do NOT reflexively call pathrule_get_context before every small known-path code task. DO call pathrule_get_context(cwd, user_intent, omit_protocol: true) before any grep/read/fallback when hook context is missing, ambiguous, stale, or the user asks for discovery, inventory, architecture, recent activity, or list/show/find/where/which style questions (including Turkish: listele, g\xF6ster, bul, nerede, hangi, neler).","Hook silence on a topic does not mean Pathrule has no relevant memory/rule. For discovery/inventory/architecture questions, call pathrule_get_context first; fall back to files, git, or general knowledge only after Pathrule returns nothing relevant. It's a single unified tool (M13): the router classifies intent and returns a depth-appropriate response - minimal for ui_tweak/new_feature on a known path, focused for bug_fix/refactor, deep for debug/discovery.","For discovery/inventory questions, treat `subtree_memory_index`, `discovery_signal`, and `semantic_candidates` as Pathrule evidence before filesystem fallback. Semantic candidates are not answers or rules: call pathrule_read_memory(id) and inspect the body before citing or following one.","The response tells you `next_required_action.primary_files` when the router is confident \u2014 edit those directly. For full memory/rule bodies: pathrule_read_memory(id) / pathrule_read_rule(id).","Obey every rule the hooks surface (advisory + strict). Apply every memory whose title looks relevant \u2014 fetch the body only when you want to cite or follow it.","Treat existing local edits as protected user/team work: inspect before touching overlapping files, never revert unrelated changes, and keep edits scoped to the user's request."],during:["Path-first writes: write_memory / write_rule / write_skill take a node_path string (e.g. '/apps/mobile'). Target the most specific path; missing nodes auto-create.","Never use local file-based memory (~/.claude/memory/, MEMORY.md). Pathrule is the single source of truth for all persistent knowledge.","After every write, summarise what you did in natural language \u2014 don't paste raw tool JSON."],after:["Log EVERY file-modifying response with pathrule_log_activity. Trigger: did you modify files? \u2192 log it. Required fields: domain, action, scope, subjects (\u22645 keywords), files_touched, task_summary."]},pl=il(bn);function hl(){let t=["# Pathrule Protocol","","This workspace uses Pathrule MCP. Follow this protocol on EVERY task.","","## BEFORE \u2014 mandatory first steps",""],e=1;for(let r of bn.before)t.push(`${e}. ${r}`),e++;t.push("","## DURING \u2014 constraints while coding","");for(let r of bn.during)t.push(`${e}. ${r}`),e++;t.push("","## AFTER \u2014 mandatory after every file modification","");for(let r of bn.after)t.push(`${e}. ${r}`),e++;return t.push(""),t.join(`
|
|
59
|
+
`)}var Df=["pathrule-hook.js","pathrule_log_activity"];function Mf(){return Be().hooks}function Lf(){return as(Be())}function Uf(){return ls(Be())}function vn(t){return t?Df.some(e=>t.includes(e)):false}function gr(t){let e=[];for(let r of t){let n=(r.hooks??[]).filter(i=>!vn(i.command));n.length!==0&&e.push({...r,hooks:n});}return e}function Sn(t){let e={};if(t&&t.trim().length>0)try{e=JSON.parse(t);}catch{e={_backup:t};}e.hooks||(e.hooks={});let r=false;for(let[n,i]of Object.entries(Mf())){let s=e.hooks[n],o=Array.isArray(s)?s:[],a=o.filter(u=>(u.hooks??[]).some(d=>vn(d.command))),l=gr(o);a.length===i.length&&a.every((u,d)=>{let p=i[d];if(!p)return false;let h=u.hooks,f=p.hooks;return (u.matcher??"")===(p.matcher??"")&&h.length===f.length&&h.every((m,_)=>m.command===f[_]?.command)})||(e.hooks[n]=[...l,...i],r=true);}return {body:JSON.stringify(e,null,2)+`
|
|
60
60
|
`,changed:r}}function fl(t,e){let r={version:1};if(t&&t.trim().length>0)try{r=JSON.parse(t);}catch{r={version:1,_backup:t};}typeof r.version!="number"&&(r.version=1),(!r.hooks||typeof r.hooks!="object")&&(r.hooks={});let n=e?.uninstall===true,i=false;if(n){for(let a of Object.keys(r.hooks)){let l=r.hooks[a];if(!Array.isArray(l))continue;let c=gr(l);c.length!==l.length&&(c.length===0?delete r.hooks[a]:r.hooks[a]=c,i=true);}let s=Object.keys(r).filter(a=>a!=="version"&&a!=="hooks"),o=Object.keys(r.hooks);return s.length===0&&o.length===0?{body:"",changed:true}:{body:JSON.stringify(r,null,2)+`
|
|
61
|
-
`,changed:i}}for(let[s,o]of Object.entries(Lf())){let a=r.hooks[s],l=Array.isArray(a)?a:[],c=l.filter(p=>(p.hooks??[]).some(h=>
|
|
61
|
+
`,changed:i}}for(let[s,o]of Object.entries(Lf())){let a=r.hooks[s],l=Array.isArray(a)?a:[],c=l.filter(p=>(p.hooks??[]).some(h=>vn(h.command))),u=gr(l);c.length===o.length&&c.every((p,h)=>{let f=o[h];return f?(p.matcher??"")===(f.matcher??"")&&p.hooks.length===f.hooks.length&&p.hooks.every((m,_)=>m.command===f.hooks[_]?.command):false})&&u.length===l.length-c.length||(r.hooks[s]=[...u,...o],i=true);}return {body:JSON.stringify(r,null,2)+`
|
|
62
62
|
`,changed:i}}function gl(t,e){let r={};if(t&&t.trim().length>0)try{r=JSON.parse(t);}catch{r={_backup:t};}(!r.hooks||typeof r.hooks!="object")&&(r.hooks={});let n=e?.uninstall===true,i=false;if(n){for(let a of Object.keys(r.hooks)){let l=r.hooks[a];if(!Array.isArray(l))continue;let c=gr(l);c.length!==l.length&&(c.length===0?delete r.hooks[a]:r.hooks[a]=c,i=true);}let s=Object.keys(r).filter(a=>a!=="hooks"),o=Object.keys(r.hooks);return s.length===0&&o.length===0?{body:"",changed:true}:{body:JSON.stringify(r,null,2)+`
|
|
63
|
-
`,changed:i}}for(let[s,o]of Object.entries(Uf())){let a=r.hooks[s],l=Array.isArray(a)?a:[],c=l.filter(p=>(p.hooks??[]).some(h=>
|
|
63
|
+
`,changed:i}}for(let[s,o]of Object.entries(Uf())){let a=r.hooks[s],l=Array.isArray(a)?a:[],c=l.filter(p=>(p.hooks??[]).some(h=>vn(h.command))),u=gr(l);c.length===o.length&&c.every((p,h)=>{let f=o[h];return f?(p.matcher??"")===(f.matcher??"")&&p.hooks.length===f.hooks.length&&p.hooks.every((m,_)=>m.command===f.hooks[_]?.command):false})&&u.length===l.length-c.length||(r.hooks[s]=[...u,...o],i=true);}return {body:JSON.stringify(r,null,2)+`
|
|
64
64
|
`,changed:i}}var ml="# >>> Pathrule managed (codex hook activation) >>>",cs="# <<< Pathrule managed <<<",dl=[ml,"[features]","codex_hooks = true",cs,""].join(`
|
|
65
|
-
`);function
|
|
65
|
+
`);function Cn(t,e){let r=(t??"").replace(/\r\n/g,`
|
|
66
66
|
`),n=r.indexOf(ml),i=r.indexOf(cs),s=r;if(n>=0&&i>n){let a=r.slice(i+cs.length).replace(/^\n+/,"");s=(r.slice(0,n).trimEnd()+(a?`
|
|
67
67
|
|
|
68
68
|
${a}`:"")).trimEnd();}else s=r.trimEnd();if(e?.uninstall===true){let a=s.length>0?`${s}
|
|
69
69
|
`:"";return {body:a,changed:a!==r}}let o=s.length>0?`${s}
|
|
70
70
|
|
|
71
|
-
${dl}`:dl;return r===o?{body:r,changed:false}:{body:o,changed:true}}var Wf={profile:80,organization:100,workspace:120},Bf=new Set(["pathrule","pathrule admin","pathrule support","pathrule security"]),Ff=new Set(["admin","administrator","security","support","system"]),_l=/[\u0000-\u001f\u007f-\u009f]/,Hf=/[\u0000-\u001f\u007f-\u009f]/g,qf=/<\/?[a-z][^>]*>/i,zf=/(^|\s)(https?:\/\/|javascript:|data:|mailto:)/i,Jf=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/i;function Kf(t){return t.replace(/\s+/g," ").trim()}function us(t,e){if(_l.test(t))return {ok:false,reason:"control_chars"};let r=Kf(t);if(r.length===0)return {ok:false,reason:"empty"};if(Array.from(r).length>Wf[e])return {ok:false,reason:"too_long"};if(qf.test(r))return {ok:false,reason:"html_like"};if(zf.test(r))return {ok:false,reason:"url_like"};if(e==="profile"&&Jf.test(r))return {ok:false,reason:"url_like"};let n=r.toLocaleLowerCase("en-US");return e!=="workspace"&&Bf.has(n)?{ok:false,reason:"reserved"}:e==="profile"&&Ff.has(n)?{ok:false,reason:"reserved"}:{ok:true,value:r}}function wl(t,e){if(typeof t!="string")return null;let r=us(t,e);return r.ok?r.value??null:null}function yl(t,e=2048){if(typeof t!="string")return null;let r=t.trim();if(!r||r.length>e||_l.test(r))return null;try{let n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?null:n.toString()}catch{return null}}function
|
|
71
|
+
${dl}`:dl;return r===o?{body:r,changed:false}:{body:o,changed:true}}var Wf={profile:80,organization:100,workspace:120},Bf=new Set(["pathrule","pathrule admin","pathrule support","pathrule security"]),Ff=new Set(["admin","administrator","security","support","system"]),_l=/[\u0000-\u001f\u007f-\u009f]/,Hf=/[\u0000-\u001f\u007f-\u009f]/g,qf=/<\/?[a-z][^>]*>/i,zf=/(^|\s)(https?:\/\/|javascript:|data:|mailto:)/i,Jf=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/i;function Kf(t){return t.replace(/\s+/g," ").trim()}function us(t,e){if(_l.test(t))return {ok:false,reason:"control_chars"};let r=Kf(t);if(r.length===0)return {ok:false,reason:"empty"};if(Array.from(r).length>Wf[e])return {ok:false,reason:"too_long"};if(qf.test(r))return {ok:false,reason:"html_like"};if(zf.test(r))return {ok:false,reason:"url_like"};if(e==="profile"&&Jf.test(r))return {ok:false,reason:"url_like"};let n=r.toLocaleLowerCase("en-US");return e!=="workspace"&&Bf.has(n)?{ok:false,reason:"reserved"}:e==="profile"&&Ff.has(n)?{ok:false,reason:"reserved"}:{ok:true,value:r}}function wl(t,e){if(typeof t!="string")return null;let r=us(t,e);return r.ok?r.value??null:null}function yl(t,e=2048){if(typeof t!="string")return null;let r=t.trim();if(!r||r.length>e||_l.test(r))return null;try{let n=new URL(r);return n.protocol!=="http:"&&n.protocol!=="https:"?null:n.toString()}catch{return null}}function En(t){return t.replace(Hf,e=>e===`
|
|
72
72
|
`?"\\n":e==="\r"?"\\r":e===" "?"\\t":`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`)}var H={web:"Pathrule Web",desktop:"Pathrule Desktop",cli:"Pathrule CLI"},tt={web:"Pathrule in your browser. Manage cloud content from anywhere.",desktop:"The complete Pathrule app for macOS, Windows, and Linux.",cli:"Pathrule from your terminal. Headless, scriptable, fast."};var Vf=["event_name","schema_version","occurred_at","surface","host_kind","app_version","os_family","country_iso","pseudonymous_install_id","session_local_id","duration_ms","result","blocking_reason","feature_tag"];function kl(t){let e=new Set(Vf);for(let r of Object.keys(t))if(!e.has(r))throw new Error(`telemetry_field_not_allowed:${r}`)}var Gf=[{match:t=>t.some(e=>/^next\.config\.(js|mjs|ts)$/.test(ce(e))),title:"Next.js project",content:"This workspace uses Next.js as its React framework."},{match:t=>t.some(e=>/^nuxt\.config\.(js|ts)$/.test(ce(e))),title:"Nuxt project",content:"This workspace uses Nuxt as its Vue framework."},{match:t=>t.some(e=>/^tailwind\.config\.(js|mjs|ts|cjs)$/.test(ce(e))),title:"Uses Tailwind CSS",content:"This workspace uses Tailwind CSS for styling."},{match:t=>t.some(e=>/^vite\.config\.(js|ts|mjs)$/.test(ce(e))),title:"Vite build tool",content:"This workspace uses Vite as the build tool / dev server."},{match:t=>{let e=t.filter(n=>n.endsWith("/package.json")||n==="package.json"),r=t.some(n=>n.startsWith("packages/")||n.startsWith("apps/"));return e.length>2&&r},title:"Monorepo structure",content:"This workspace is a monorepo with multiple packages/apps, each with its own package.json."},{match:t=>t.some(e=>ce(e)==="Podfile"||e.endsWith(".xcodeproj")),title:"iOS/macOS native project",content:"This workspace contains iOS/macOS native code (Xcode project or CocoaPods)."},{match:t=>t.some(e=>ce(e)==="pubspec.yaml"),title:"Flutter project",content:"This workspace is a Flutter/Dart project."},{match:t=>t.some(e=>ce(e)==="Cargo.toml"),title:"Rust project",content:"This workspace contains Rust code (Cargo-managed)."},{match:t=>t.some(e=>ce(e)==="go.mod"),title:"Go project",content:"This workspace is a Go module."},{match:t=>t.some(e=>/^tsconfig(\.\w+)?\.json$/.test(ce(e))),title:"TypeScript project",content:"This workspace uses TypeScript."},{match:t=>t.some(e=>ce(e)==="docker-compose.yml"||ce(e)==="docker-compose.yaml"||ce(e)==="Dockerfile"),title:"Docker containerization",content:"This workspace uses Docker for containerization."},{match:t=>t.some(e=>e.startsWith(".github/workflows/")),title:"GitHub Actions CI/CD",content:"This workspace uses GitHub Actions for CI/CD."}];function ce(t){let e=t.split("/");return e[e.length-1]??t}function ds(t){return Gf.filter(e=>e.match(t)).map(e=>({title:e.title,content:e.content}))}function ps(t){let e=new Map,r=0,n=t.split("---").filter(i=>i.trim().length>0);for(let i of n){if(r>=1e4)break;r++;let s=i.split(`
|
|
73
|
-
`).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("commit ")&&!o.startsWith("Author:"));if(!(s.length>20||s.length<2))for(let o=0;o<s.length;o++)for(let a=o+1;a<s.length;a++){let l=s[o],c=s[a],[u,d]=l<c?[l,c]:[c,l],p=`${u}\0${d}`;e.set(p,(e.get(p)??0)+1);}}return [...e.entries()].map(([i,s])=>{let[o,a]=i.split("\0");return {path_a:o,path_b:a,weight:s}}).sort((i,s)=>s.weight-i.weight).slice(0,1e4)}var U={"claude-code":{id:"claude-code",label:"Claude Code",skillsDir:".claude/skills",detectFile:".claude",supported:true},cursor:{id:"cursor",label:"Cursor",skillsDir:".cursor/skills",detectFile:".cursor",supported:true},windsurf:{id:"windsurf",label:"Windsurf",skillsDir:".windsurf/skills",detectFile:".windsurf",supported:true},codex:{id:"codex",label:"Codex",skillsDir:".codex/skills",detectFile:".codex",supported:true}},
|
|
74
|
-
`,{encoding:"utf8",mode:O}),await chmod(s,O).catch(()=>{}),await K_(t).catch(()=>{}),{recorded:true}}async function io(t,e){try{let r=q_(e.command,e.exitCode),n=e.exitCode===0?"ok":e.exitCode===64?"blocked":"failed";r&&await
|
|
73
|
+
`).map(o=>o.trim()).filter(o=>o.length>0&&!o.startsWith("commit ")&&!o.startsWith("Author:"));if(!(s.length>20||s.length<2))for(let o=0;o<s.length;o++)for(let a=o+1;a<s.length;a++){let l=s[o],c=s[a],[u,d]=l<c?[l,c]:[c,l],p=`${u}\0${d}`;e.set(p,(e.get(p)??0)+1);}}return [...e.entries()].map(([i,s])=>{let[o,a]=i.split("\0");return {path_a:o,path_b:a,weight:s}}).sort((i,s)=>s.weight-i.weight).slice(0,1e4)}var U={"claude-code":{id:"claude-code",label:"Claude Code",skillsDir:".claude/skills",detectFile:".claude",supported:true},cursor:{id:"cursor",label:"Cursor",skillsDir:".cursor/skills",detectFile:".cursor",supported:true},windsurf:{id:"windsurf",label:"Windsurf",skillsDir:".windsurf/skills",detectFile:".windsurf",supported:true},codex:{id:"codex",label:"Codex",skillsDir:".codex/skills",detectFile:".codex",supported:true}},Rn=["claude-code"];function hs(t){return U[t]??null}function bl(t){let e=[];for(let r of t){let n=hs(r);n&&n.supported&&e.push(n);}return e}var Yf="skill";function xn(t){let e=(t||"").toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return e?e.slice(0,80):Yf}function vl(t,e){let r=xn(t),n=e.replace(/-/g,"").slice(0,8);return `${r}-${n}`}var Sl="[redacted]",Xf="[redacted-email]",fs="[redacted-path]",Zf=/(authorization|password|secret|token|api[_-]?key|access[_-]?token|refresh[_-]?token|pair[_-]?token|session|cookie|env|environment|cache|content|body|file[_-]?content)/i,Qf=/(^|[_-])(path|paths|cwd|directory|root|repo|local_root|workspace_root)([_-]|$)/i,eg=/\b(?:Bearer\s+)?[A-Za-z0-9._~+/=-]{24,}\b/g,tg=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,rg=/(?:~|\/Users\/[^/\s]+|\/home\/[^/\s]+|\/var\/folders\/[^\s"']+|\/tmp\/[^\s"']+)/g,ng=/[A-Za-z]:\\(?:[^\\\s"']+\\?)+/g;function gs(t,e=""){return t&&(sg(e)?fs:ig(e)?Sl:t.replace(tg,Xf).replace(rg,fs).replace(ng,fs).replace(eg,Sl))}function Cl(t){let e=JSON.stringify(t),r=[/Bearer\s+[A-Za-z0-9._~+/=-]+/i,/access[_-]?token["':\s]+[A-Za-z0-9._~+/=-]{8,}/i,/refresh[_-]?token["':\s]+[A-Za-z0-9._~+/=-]{8,}/i,/pair[_-]?token["':\s]+[A-Za-z0-9._~+/=-]{8,}/i,/\/Users\/[^/"']+/,/\/home\/[^/"']+/,/[A-Za-z]:\\[^"']+/];for(let n of r)if(n.test(e))throw new Error(`support bundle contains sensitive material matching ${n}`)}function ig(t){return Zf.test(t)}function sg(t){return Qf.test(t)}var Fe={free:{workspaces:1,memories:50,rules:50,seatsExtra:0,basePriceMonthly:0,basePriceYearly:0,perSeatMonthly:0},starter:{workspaces:3,memories:2500,rules:2500,seatsExtra:-1,basePriceMonthly:12,basePriceYearly:10,perSeatMonthly:6},pro:{workspaces:-1,memories:1e4,rules:1e4,seatsExtra:-1,basePriceMonthly:24,basePriceYearly:20,perSeatMonthly:6},business:{workspaces:-1,memories:5e4,rules:5e4,seatsExtra:-1,basePriceMonthly:48,basePriceYearly:40,perSeatMonthly:6},enterprise:{workspaces:-1,memories:-1,rules:-1,seatsExtra:-1,basePriceMonthly:0,basePriceYearly:0,perSeatMonthly:0}};function El(t,e){if(!t)return {failure:{error:"organization_not_found"},billingImpact:Pn(),billingRequirement:null};if(t.plan==="free")return {failure:{error:"free_plan_invites_disabled"},billingImpact:Pn(),billingRequirement:null};if(["past_due","unpaid","canceled"].includes(t.subscription_status??""))return {failure:{error:"subscription_not_invitable"},billingImpact:Pn(),billingRequirement:null};if(t.trial_status==="active"&&t.trial_seat_cap){let r=e+1,n=t.paid_extra_seats??0,i=t.trial_seat_cap+n,s=r>t.trial_seat_cap,o=Math.max(0,r-t.trial_seat_cap),a={seat_effect:s?r>i?"paid_extra_required":"paid_extra_available":"included",may_use_paid_extra_seat:s,active_seats_before:e,target_active_seats:r,included_seat_cap:t.trial_seat_cap,current_paid_extra_seats:n,required_paid_extra_seats:o};return r>i?{failure:null,billingImpact:a,billingRequirement:{targetSeats:r,requiredPaidExtraSeats:o,giftSeatCap:t.trial_seat_cap,currentPaidExtraSeats:n}}:{failure:null,billingImpact:a,billingRequirement:null}}return {failure:null,billingImpact:Pn(),billingRequirement:null}}function Pn(){return {seat_effect:"not_applicable",may_use_paid_extra_seat:false}}K();var pg={"claude-code":["CLAUDE.md",".claude/rules/pathrule-protocol.md",".claude/settings.json"],cursor:[".cursorrules",".cursor/rules/pathrule-protocol.mdc",".cursor/hooks.json"],codex:["codex.md","AGENTS.md",".codex/hooks.json",".codex/config.toml"],windsurf:[".windsurfrules",".windsurf/rules/pathrule-protocol.md"]};async function hg(t){try{return await access(t,constants.F_OK),!0}catch{return false}}async function He(t){let e=Object.keys(U);return (await Promise.all(e.map(async n=>{for(let i of pg[n])if(await hg(join(t,i)))return n;return null}))).filter(n=>n!==null)}function Tn(t){let e=new Set(Object.keys(U)),r=(t.selected??[]).filter(n=>typeof n=="string"&&e.has(n));return r.length>0?r:t.detected.length>0?[...t.detected]:[...t.fallback]}oi();zr();F();var M_=new Map([["-h","--help"],["-v","--version"]]);function ku(t,e=process.env){let r=[],n={json:false,yes:false,noOpen:false,deviceCode:false,browserCallback:false,help:false,version:false,color:e.NO_COLOR!=="1"&&e.NO_COLOR!=="true",interactive:e.CI!=="true"};for(let o of t)switch(M_.get(o)??o){case "--json":n.json=true,n.color=false,n.interactive=false;break;case "--yes":n.yes=true;break;case "--no-open":n.noOpen=true;break;case "--device-code":n.deviceCode=true;break;case "--browser-callback":n.browserCallback=true;break;case "--help":n.help=true;break;case "--version":n.version=true;break;case "--no-color":n.color=false;break;default:r.push(o);break}let i=L_(r);return {command:i[0]??"help",positional:i,flags:n}}function L_(t){let e=t[0],r=t[1];return !e?.startsWith("/")||!r||!["memory","rule","skill","search"].includes(r)?t:[r,...t.slice(2),e]}Ke();F();K();var B_=randomUUID(),F_=20,H_=1500;function Eu(t){return t==="telemetry.enabled"||t==="telemetry.id"}async function Ru(t,e){if(t==="telemetry.enabled")return so(e,await oo(e));let r=await ui(e);return {key:t,value:r.pseudonymous_install_id,source:"config",configurable:true}}async function xu(t,e){let r=G_(t);if(r===null)throw new Error("invalid_telemetry_enabled");let n=await ui(e);return await ao({...n,telemetry_enabled:r},e),so(e,{...n,telemetry_enabled:r})}async function Pu(t){let r={...await ui(t),pseudonymous_install_id:randomUUID()};return await ao(r,t),{key:"telemetry.id",value:r.pseudonymous_install_id,source:"config",configurable:true}}async function Kr(t,e){let r=so(t,await oo(t));if(!r.value)return {recorded:false,reason:r.source};let n=await ui(t),i={event_name:e.eventName,schema_version:1,occurred_at:new Date().toISOString(),surface:"cli",host_kind:"cli-bridge",app_version:e.appVersion,os_family:process.platform,pseudonymous_install_id:n.pseudonymous_install_id,session_local_id:B_,result:e.result,...typeof e.durationMs=="number"?{duration_ms:e.durationMs}:{},...e.blockingReason?{blocking_reason:e.blockingReason}:{},...e.featureTag?{feature_tag:e.featureTag}:{}};kl(i),Y_(i);let s=Au(t);return await mkdir(dirname(s),{recursive:true,mode:D}),await chmod(dirname(s),D).catch(()=>{}),await appendFile(s,`${JSON.stringify(i)}
|
|
74
|
+
`,{encoding:"utf8",mode:O}),await chmod(s,O).catch(()=>{}),await K_(t).catch(()=>{}),{recorded:true}}async function io(t,e){try{let r=q_(e.command,e.exitCode),n=e.exitCode===0?"ok":e.exitCode===64?"blocked":"failed";r&&await Kr(t,{eventName:r,result:n,appVersion:e.appVersion,durationMs:e.durationMs,featureTag:z_(e.command),blockingReason:e.exitCode===64?"usage_or_preflight_blocked":void 0});let i=J_(e.command,e.exitCode);i&&await Kr(t,{eventName:"dead_end_seen",result:"blocked",appVersion:e.appVersion,durationMs:e.durationMs,featureTag:i.featureTag,blockingReason:i.blockingReason});}catch{}}function q_(t,e){switch(t){case "help":case "version":case "status":return "surface_viewed";case "setup":return e===0?"cli_setup_completed":"cli_setup_started";case "doctor":return e===0?null:"cli_doctor_failed";case "bridge":return e===0?"cli_bridge_pair_succeeded":"cli_bridge_pair_started";case "sync":return e===0?"agent_sync_succeeded":null;case "billing":case "team":case "upgrade":case "reactivate":case "open":return "web_admin_route_opened_from_cli";case "preflight":return e===0?null:"cli_preflight_blocked";default:return null}}function z_(t){return t==="bridge"?"cli_bridge":t==="setup"?"cli_setup":t==="doctor"?"cli_doctor":t==="sync"?"agent_sync":["billing","team","upgrade","reactivate","open"].includes(t)?"web_route":t==="preflight"?"preflight":"surface"}function J_(t,e){return e===0?null:t==="doctor"?{featureTag:"cli_doctor",blockingReason:"doctor_cannot_repair"}:t==="preflight"?{featureTag:"preflight",blockingReason:"preflight_blocked"}:t==="setup"?{featureTag:"cli_setup",blockingReason:"cli_setup_incomplete"}:t==="bridge"?{featureTag:"cli_bridge",blockingReason:"bridge_pair_failed"}:["billing","team","upgrade","reactivate","open"].includes(t)?{featureTag:"web_route",blockingReason:"web_route_not_opened"}:null}function so(t,e){return t.CI==="true"?{key:"telemetry.enabled",value:false,source:"ci",configurable:false}:t.NO_TELEMETRY==="1"?{key:"telemetry.enabled",value:false,source:"env",configurable:false}:typeof e?.telemetry_enabled=="boolean"?{key:"telemetry.enabled",value:e.telemetry_enabled,source:"config",configurable:true}:{key:"telemetry.enabled",value:true,source:"default",configurable:true}}async function ui(t){let e=await oo(t);if(e)return e;let r={schema_version:1,pseudonymous_install_id:randomUUID()};return await ao(r,t),r}async function oo(t){try{let e=JSON.parse(await readFile(Tu(t),"utf8"));if(e&&typeof e=="object"&&e.schema_version===1&&typeof e.pseudonymous_install_id=="string")return e}catch(e){if(e.code!=="ENOENT")throw e}return null}async function ao(t,e){let r=Tu(e);await mkdir(dirname(r),{recursive:true,mode:D}),await chmod(dirname(r),D).catch(()=>{});let n=`${r}.tmp`;await writeFile(n,JSON.stringify(t,null,2),{encoding:"utf8",mode:O}),await chmod(n,O).catch(()=>{}),await rename(n,r);}function Tu(t){return join(A(t).home,"telemetry.json")}function Au(t){return join(A(t).logsDir,"telemetry-events.jsonl")}async function K_(t){let e=V_(t);if(!e)return;let r=Au(t),n;try{n=(await readFile(r,"utf8")).split(`
|
|
75
75
|
`).filter(Boolean);}catch(a){if(a.code==="ENOENT")return;throw a}if(n.length===0)return;let i=n.slice(0,F_).map(a=>JSON.parse(a)),s=new AbortController,o=setTimeout(()=>s.abort(),H_);try{let a=await fetch(e.url,{method:"POST",headers:{"Content-Type":"application/json",apikey:e.anonKey,Authorization:`Bearer ${e.anonKey}`},body:JSON.stringify({events:i}),signal:s.signal});if(!a.ok)return;let l=await a.json().catch(()=>null),c=typeof l?.accepted=="number"?l.accepted:i.length,u=Math.max(0,Math.min(c,i.length)),d=n.slice(u).join(`
|
|
76
76
|
`);await writeFile(r,d?`${d}
|
|
77
|
-
`:"",{encoding:"utf8",mode:O}),await chmod(r,O).catch(()=>{});}finally{clearTimeout(o);}}function V_(t){let e=t.SUPABASE_URL??t.VITE_SUPABASE_URL,r=t.SUPABASE_ANON_KEY??t.VITE_SUPABASE_ANON_KEY;return !e||!r?null:{url:`${e.replace(/\/$/,"")}/functions/v1/telemetry-ingest`,anonKey:r}}function G_(t){if(!t)return null;let e=t.toLowerCase().trim();return e==="true"?true:e==="false"?false:null}function Y_(t){let e=JSON.stringify(t),r=[/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i,/(?:^|["\s])\/Users\/[^"\s]+/,/(?:^|["\s])\/home\/[^"\s]+/,/[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/,/ghp_[A-Za-z0-9_]{20,}/];for(let n of r)if(n.test(e))throw new Error(`telemetry_payload_contains_sensitive_material:${n}`)}var X_=new Set(["manual","notify","auto"]);function Ou(t,e){if(t.CI==="true"||t.NO_UPDATE_CHECK==="1")return {key:"update.policy",value:"manual",source:"ci",configurable:false};let r=lo(t.PATHRULE_UPDATE_POLICY);if(r)return {key:"update.policy",value:r,source:"env",configurable:false};let n=lo(e);return n?{key:"update.policy",value:n,source:"config",configurable:true}:{key:"update.policy",value:"notify",source:"default",configurable:true}}function $u(t){return typeof t=="boolean"?{key:"suggestions.desktop",value:t,source:"config",configurable:true}:{key:"suggestions.desktop",value:true,source:"default",configurable:true}}async function wt(t,e){if(Eu(t))return Ru(t,e);if(t!=="update.policy"&&t!=="suggestions.desktop")throw new Error("unsupported_config_key");try{let{session:r}=await C(e),n=await ne(r.user.id,e);return Iu(t,e,n)}catch{return Iu(t,e)}}async function co(t,e,r){if(t==="telemetry.enabled")return xu(e,r);if(t==="telemetry.id")throw new Error("use_config_reset_telemetry_id");if(t!=="update.policy"&&t!=="suggestions.desktop")throw new Error("unsupported_config_key");let{session:n}=await C(r);if(t==="update.policy"){let s=lo(e);if(!s)throw new Error("invalid_update_policy");return await ie(n.user.id,{update_policy:s},r),Ou(r,s)}let i=Z_(e);if(i===null)throw new Error("invalid_desktop_suggestions");return await ie(n.user.id,{desktop_suggestions:i},r),$u(i)}async function uo(t,e){if(t==="telemetry-id"||t==="telemetry.id")return Pu(e);throw new Error("unsupported_config_reset_key")}function lo(t){if(!t)return null;let e=t.toLowerCase().trim();return X_.has(e)?e:null}function Z_(t){if(!t)return null;let e=t.toLowerCase().trim();return e==="true"?true:e==="false"?false:null}function Iu(t,e,r){return t==="update.policy"?Ou(e,r?.update_policy):$u(r?.desktop_suggestions)}Ke();F();Ee();async function Re(t){let{session:e,supabase:r}=await C(t),n=await j(t);if(!n)return [];let{data:i,error:s}=await r.from("workspaces").select("id, organization_id, name, access_mode, git_remote_url, git_owner, git_repo, user_workspace_paths!left(local_root_path, user_id)").eq("organization_id",n.id).is("archived_at",null);if(s)throw s;let o=await ne(e.user.id,t),a=[];for(let l of i??[]){let u=(l.user_workspace_paths??[]).find(d=>d.user_id===e.user.id)??null;a.push({id:l.id,organization_id:l.organization_id,name:l.name,access_mode:l.access_mode,git_remote_url:l.git_remote_url,git_owner:l.git_owner,git_repo:l.git_repo,local_root_path:u?.local_root_path??null,current:o.current_workspace_id===l.id});}if(a.sort((l,c)=>l.name.localeCompare(c.name)),!o.current_workspace_id&&a.length===1){let l=a[0];l&&(a[0]={...l,current:true});}return a}async function M(t){let e=await Re(t),r=e.find(n=>n.current);return r||(e.length===1?e[0]??null:null)}async function Kr(t,e){let{session:r}=await C(e),i=(await Re(e)).find(s=>s.id===t||s.name===t);if(!i)throw new Error("workspace_not_found");return await ie(r.user.id,{current_workspace_id:i.id},e),{...i,current:true}}async function yt(t,e,r){let{session:n,supabase:i}=await C(r),s=await j(r);if(!s)throw new Error("org_required");let o=us(t,"workspace");if(!o.ok||!o.value)throw new Error(`unsafe_workspace_name:${o.reason??"invalid"}`);let{data:a,error:l}=await i.from("workspaces").insert({organization_id:s.id,name:o.value,access_mode:"organization",git_remote_url:null,git_provider:null,git_owner:null,git_repo:null,detected_at:null}).select("id, organization_id, name, access_mode").single();if(l||!a)throw new Error(l?.message??"workspace_create_failed");let{error:c}=await i.from("user_workspace_paths").insert({user_id:n.user.id,workspace_id:a.id,local_root_path:e,watcher_enabled:true});if(c)throw new Error(c.message);let u=await Zi(i,a.id,o.value);return await ie(n.user.id,{current_org_id:s.id,current_workspace_id:a.id},r),{workspace:{id:a.id,organization_id:a.organization_id,name:a.name,access_mode:a.access_mode,local_root_path:e,current:true},local_root_path:e,root_node_created:!("error"in u)}}async function xe(t,e,r){let{session:n,supabase:i}=await C(r),s=t?await ju(t,r):await M(r);if(!s)throw new Error("workspace_required");let{error:o}=await i.from("user_workspace_paths").upsert({user_id:n.user.id,workspace_id:s.id,local_root_path:e,watcher_enabled:true},{onConflict:"user_id,workspace_id"});if(o)throw o;return await ie(n.user.id,{current_org_id:s.organization_id,current_workspace_id:s.id},r),{workspace:{...s,local_root_path:e,current:true},local_root_path:e,previous_local_root_path:s.local_root_path}}async function Vr(t,e){let{session:r,supabase:n}=await C(e),i=t?await ju(t,e):await M(e);if(!i)throw new Error("workspace_required");let{error:s}=await n.from("user_workspace_paths").delete().eq("user_id",r.user.id).eq("workspace_id",i.id);if(s)throw s;return {...i,local_root_path:null}}async function ju(t,e){let n=(await Re(e)).find(i=>i.id===t||i.name===t);if(!n)throw new Error("workspace_not_found");return n}F();function Du(t,e=false){return e?true:t.length<=1200&&t.split(/\r?\n/).length<=24}function Mu(t,e={}){if(e.forceWeb)return {...t.open_targets.find(r=>r.kind==="web"),reason:"forced"};if(e.preferDesktopApp){let r=t.open_targets.find(n=>n.kind==="desktop-app");return r||{...t.open_targets.find(n=>n.kind==="web"),reason:"fallback"}}return t.open_targets[0]??{kind:"web",url:t.url,label:`Open ${t.kind} in Pathrule Web`,reason:"preferred"}}async function Gr(t,e,r={}){let n=await tw(e),{supabase:i}=await C(e),s=fo(r.limit),o=ow(r.path);if(t==="memory"){let{data:c,error:u}=await i.from("memories").select("id, title, content, updated_at, nodes(id, relative_path)").eq("workspace_id",n.id).eq("status","active").order("updated_at",{ascending:false}).limit(s*3);if(u)throw u;return (c??[]).map(d=>po("memory",n.id,d,e)).filter(d=>ho(d.path,o)).slice(0,s)}if(t==="rule"){let{data:c,error:u}=await i.from("rules").select("id, name, content, updated_at, node_rules(nodes(id, relative_path))").eq("workspace_id",n.id).order("updated_at",{ascending:false}).limit(s*3);if(u)throw u;return (c??[]).map(d=>po("rule",n.id,d,e)).filter(d=>ho(d.path,o)).slice(0,s)}let{data:a,error:l}=await i.from("skills").select("id, name, description, content, updated_at, node_skills(nodes!node_skills_node_id_fkey(id, relative_path))").eq("workspace_id",n.id).order("updated_at",{ascending:false}).limit(s*3);if(l)throw l;return (a??[]).map(c=>po("skill",n.id,c,e)).filter(c=>ho(c.path,o)).slice(0,s)}async function go(t,e,r={}){let n=t.trim().toLowerCase();if(!n)throw new Error("search_query_required");let i=r.types?.length?r.types:["memory","rule","skill"];return (await Promise.all(i.map(o=>Gr(o,e,{path:r.path,limit:Math.max(fo(r.limit),50)})))).flat().map(o=>({item:o,score:aw(o,n)})).filter(o=>o.score>0).sort((o,a)=>a.score-o.score||(a.item.updated_at??"").localeCompare(o.item.updated_at??"")).slice(0,fo(r.limit)).map(o=>o.item)}async function mo(t,e,r){let n=await Gr(t,r,{limit:100}),i=e.toLowerCase(),s=n.find(d=>d.id===e||d.title.toLowerCase()===i);if(!s)throw new Error(`${t}_not_found`);let{supabase:o}=await C(r),a=t==="memory"?"memories":t==="rule"?"rules":"skills",{data:l,error:c}=await o.from(a).select("content").eq("id",s.id).maybeSingle();if(c)throw c;let u=typeof l?.content=="string"?l.content:"";return {...s,content:u}}function kt(t,e,r,n,i){let s=(n.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"");return i?`${s}/workspace/${encodeURIComponent(t)}/node/${encodeURIComponent(i)}/${e}/${encodeURIComponent(r)}`:`${s}/workspace/${encodeURIComponent(t)}/${e}/${encodeURIComponent(r)}`}function ew(t,e,r,n){let i=n?`/node/${encodeURIComponent(n)}`:"";return `pathrule://workspace/${encodeURIComponent(t)}${i}/${e}/${encodeURIComponent(r)}`}async function tw(t){let e=await M(t);if(!e)throw new Error("workspace_required");return e}function po(t,e,r,n){let i=typeof r.title=="string"?r.title:typeof r.name=="string"?r.name:String(r.id),s=typeof r.content=="string"?r.content:typeof r.description=="string"?r.description:"",o=iw(t,r),a=sw(t,r),l=kt(e,t,String(r.id),n,a);return {id:String(r.id),kind:t,title:i,path:o,node_id:a,preview:lw(s),updated_at:typeof r.updated_at=="string"?r.updated_at:null,url:l,open_targets:[rw(e,t,String(r.id),n,a),nw(e,t,String(r.id),a)]}}function rw(t,e,r,n,i){return {kind:"web",url:kt(t,e,r,n,i),label:`Open ${e} in Pathrule Web`,reason:"preferred"}}function nw(t,e,r,n){return {kind:"desktop-app",url:ew(t,e,r,n),label:`Open ${e} in Pathrule Desktop`,reason:"fallback"}}function iw(t,e){if(t==="memory"){let s=e.nodes;return typeof s?.relative_path=="string"?s.relative_path:null}let i=e[t==="rule"?"node_rules":"node_skills"]?.[0]?.nodes?.relative_path;return typeof i=="string"?i:null}function sw(t,e){if(t==="memory"){let s=e.nodes;return typeof s?.id=="string"?s.id:null}let i=e[t==="rule"?"node_rules":"node_skills"]?.[0]?.nodes?.id;return typeof i=="string"?i:null}function ow(t){if(!t)return null;let e=t.trim();return e?e.startsWith("/")?e:`/${e}`:null}function ho(t,e){return e?t?t===e||t.startsWith(`${e}/`):false:true}function aw(t,e){let r=t.title.toLowerCase(),n=t.preview.toLowerCase(),i=t.path?.toLowerCase()??"",s=0;return r===e&&(s+=100),r.includes(e)&&(s+=30),i.includes(e)&&(s+=15),n.includes(e)&&(s+=10),s}function lw(t){return t.replace(/\s+/g," ").trim().slice(0,160)}function fo(t){return !t||!Number.isFinite(t)?20:Math.min(Math.max(Math.trunc(t),1),100)}F();async function ko(t,e,r){let{session:n,supabase:i}=await C(r),s=await M(r);if(!s)throw new Error("workspace_required");let o={supabase:i,userId:n.user.id,workspaceId:s.id};if(t==="memory"){let c=e,u=await za(o,{node_path:er(c.path),title:_o(c.title,"memory_title_required"),content:wo(c.body),source:"manual",allow_duplicate:c.allowDuplicate});if(!u.ok)throw new Error(u.error.message);return {item:{id:u.data.id,kind:t,title:u.data.title,path:er(c.path),url:kt(s.id,t,u.data.id,r),open_targets:[yo(s.id,t,u.data.id,r)],content_length:u.data.content.length,source:u.data.source},warnings:u.warnings??[]}}if(t==="rule"){let c=e,u=await Ja(o,{node_path:er(c.path),name:_o(c.name,"rule_name_required"),content:wo(c.body),priority:c.priority,scope_type:c.scopeType,allow_duplicate:c.allowDuplicate});if(!u.ok)throw new Error(u.error.message);return {item:{id:u.data.id,kind:t,title:u.data.name,path:er(c.path),url:kt(s.id,t,u.data.id,r),open_targets:[yo(s.id,t,u.data.id,r)],content_length:u.data.content.length,priority:u.data.priority,scope_type:u.data.scopeType},warnings:u.warnings??[]}}let a=e,l=await Ka(o,{node_path:er(a.path),name:_o(a.name,"skill_name_required"),description:Uu(a.description),content:wo(a.body),source:"manual"});if(!l.ok)throw new Error(l.error.message);return {item:{id:l.data.id,kind:t,title:l.data.name,path:er(a.path),url:kt(s.id,t,l.data.id,r),open_targets:[yo(s.id,t,l.data.id,r)],content_length:l.data.content.length,description:l.data.description,source:l.data.source},warnings:l.warnings??[]}}function Lu(t,e){if(t!=="skill")return "";let r=e,n=Uu(r.description)??"Describe when to use this skill.";return ["---",`name: ${r.name.trim()}`,`description: ${n}`,"---","","# Overview","","Explain when this skill should be used.","","## Instructions","","- Add the steps, constraints, and guardrails this skill should enforce.",""].join(`
|
|
77
|
+
`:"",{encoding:"utf8",mode:O}),await chmod(r,O).catch(()=>{});}finally{clearTimeout(o);}}function V_(t){let e=t.SUPABASE_URL??t.VITE_SUPABASE_URL,r=t.SUPABASE_ANON_KEY??t.VITE_SUPABASE_ANON_KEY;return !e||!r?null:{url:`${e.replace(/\/$/,"")}/functions/v1/telemetry-ingest`,anonKey:r}}function G_(t){if(!t)return null;let e=t.toLowerCase().trim();return e==="true"?true:e==="false"?false:null}function Y_(t){let e=JSON.stringify(t),r=[/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i,/(?:^|["\s])\/Users\/[^"\s]+/,/(?:^|["\s])\/home\/[^"\s]+/,/[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/,/ghp_[A-Za-z0-9_]{20,}/];for(let n of r)if(n.test(e))throw new Error(`telemetry_payload_contains_sensitive_material:${n}`)}var X_=new Set(["manual","notify","auto"]);function Ou(t,e){if(t.CI==="true"||t.NO_UPDATE_CHECK==="1")return {key:"update.policy",value:"manual",source:"ci",configurable:false};let r=lo(t.PATHRULE_UPDATE_POLICY);if(r)return {key:"update.policy",value:r,source:"env",configurable:false};let n=lo(e);return n?{key:"update.policy",value:n,source:"config",configurable:true}:{key:"update.policy",value:"notify",source:"default",configurable:true}}function $u(t){return typeof t=="boolean"?{key:"suggestions.desktop",value:t,source:"config",configurable:true}:{key:"suggestions.desktop",value:true,source:"default",configurable:true}}async function wt(t,e){if(Eu(t))return Ru(t,e);if(t!=="update.policy"&&t!=="suggestions.desktop")throw new Error("unsupported_config_key");try{let{session:r}=await C(e),n=await ne(r.user.id,e);return Iu(t,e,n)}catch{return Iu(t,e)}}async function co(t,e,r){if(t==="telemetry.enabled")return xu(e,r);if(t==="telemetry.id")throw new Error("use_config_reset_telemetry_id");if(t!=="update.policy"&&t!=="suggestions.desktop")throw new Error("unsupported_config_key");let{session:n}=await C(r);if(t==="update.policy"){let s=lo(e);if(!s)throw new Error("invalid_update_policy");return await ie(n.user.id,{update_policy:s},r),Ou(r,s)}let i=Z_(e);if(i===null)throw new Error("invalid_desktop_suggestions");return await ie(n.user.id,{desktop_suggestions:i},r),$u(i)}async function uo(t,e){if(t==="telemetry-id"||t==="telemetry.id")return Pu(e);throw new Error("unsupported_config_reset_key")}function lo(t){if(!t)return null;let e=t.toLowerCase().trim();return X_.has(e)?e:null}function Z_(t){if(!t)return null;let e=t.toLowerCase().trim();return e==="true"?true:e==="false"?false:null}function Iu(t,e,r){return t==="update.policy"?Ou(e,r?.update_policy):$u(r?.desktop_suggestions)}Ke();F();Ee();async function Re(t){let{session:e,supabase:r}=await C(t),n=await j(t);if(!n)return [];let{data:i,error:s}=await r.from("workspaces").select("id, organization_id, name, access_mode, git_remote_url, git_owner, git_repo, user_workspace_paths!left(local_root_path, user_id)").eq("organization_id",n.id).is("archived_at",null);if(s)throw s;let o=await ne(e.user.id,t),a=[];for(let l of i??[]){let u=(l.user_workspace_paths??[]).find(d=>d.user_id===e.user.id)??null;a.push({id:l.id,organization_id:l.organization_id,name:l.name,access_mode:l.access_mode,git_remote_url:l.git_remote_url,git_owner:l.git_owner,git_repo:l.git_repo,local_root_path:u?.local_root_path??null,current:o.current_workspace_id===l.id});}if(a.sort((l,c)=>l.name.localeCompare(c.name)),!o.current_workspace_id&&a.length===1){let l=a[0];l&&(a[0]={...l,current:true});}return a}async function M(t){let e=await Re(t),r=e.find(n=>n.current);return r||(e.length===1?e[0]??null:null)}async function Vr(t,e){let{session:r}=await C(e),i=(await Re(e)).find(s=>s.id===t||s.name===t);if(!i)throw new Error("workspace_not_found");return await ie(r.user.id,{current_workspace_id:i.id},e),{...i,current:true}}async function yt(t,e,r){let{session:n,supabase:i}=await C(r),s=await j(r);if(!s)throw new Error("org_required");let o=us(t,"workspace");if(!o.ok||!o.value)throw new Error(`unsafe_workspace_name:${o.reason??"invalid"}`);let{data:a,error:l}=await i.from("workspaces").insert({organization_id:s.id,name:o.value,access_mode:"organization",git_remote_url:null,git_provider:null,git_owner:null,git_repo:null,detected_at:null}).select("id, organization_id, name, access_mode").single();if(l||!a)throw new Error(l?.message??"workspace_create_failed");let{error:c}=await i.from("user_workspace_paths").insert({user_id:n.user.id,workspace_id:a.id,local_root_path:e,watcher_enabled:true});if(c)throw new Error(c.message);let u=await Zi(i,a.id,o.value);return await ie(n.user.id,{current_org_id:s.id,current_workspace_id:a.id},r),{workspace:{id:a.id,organization_id:a.organization_id,name:a.name,access_mode:a.access_mode,local_root_path:e,current:true},local_root_path:e,root_node_created:!("error"in u)}}async function xe(t,e,r){let{session:n,supabase:i}=await C(r),s=t?await ju(t,r):await M(r);if(!s)throw new Error("workspace_required");let{error:o}=await i.from("user_workspace_paths").upsert({user_id:n.user.id,workspace_id:s.id,local_root_path:e,watcher_enabled:true},{onConflict:"user_id,workspace_id"});if(o)throw o;return await ie(n.user.id,{current_org_id:s.organization_id,current_workspace_id:s.id},r),{workspace:{...s,local_root_path:e,current:true},local_root_path:e,previous_local_root_path:s.local_root_path}}async function Gr(t,e){let{session:r,supabase:n}=await C(e),i=t?await ju(t,e):await M(e);if(!i)throw new Error("workspace_required");let{error:s}=await n.from("user_workspace_paths").delete().eq("user_id",r.user.id).eq("workspace_id",i.id);if(s)throw s;return {...i,local_root_path:null}}async function ju(t,e){let n=(await Re(e)).find(i=>i.id===t||i.name===t);if(!n)throw new Error("workspace_not_found");return n}F();function Du(t,e=false){return e?true:t.length<=1200&&t.split(/\r?\n/).length<=24}function Mu(t,e={}){if(e.forceWeb)return {...t.open_targets.find(r=>r.kind==="web"),reason:"forced"};if(e.preferDesktopApp){let r=t.open_targets.find(n=>n.kind==="desktop-app");return r||{...t.open_targets.find(n=>n.kind==="web"),reason:"fallback"}}return t.open_targets[0]??{kind:"web",url:t.url,label:`Open ${t.kind} in Pathrule Web`,reason:"preferred"}}async function Yr(t,e,r={}){let n=await tw(e),{supabase:i}=await C(e),s=fo(r.limit),o=ow(r.path);if(t==="memory"){let{data:c,error:u}=await i.from("memories").select("id, title, content, updated_at, nodes(id, relative_path)").eq("workspace_id",n.id).eq("status","active").order("updated_at",{ascending:false}).limit(s*3);if(u)throw u;return (c??[]).map(d=>po("memory",n.id,d,e)).filter(d=>ho(d.path,o)).slice(0,s)}if(t==="rule"){let{data:c,error:u}=await i.from("rules").select("id, name, content, updated_at, node_rules(nodes(id, relative_path))").eq("workspace_id",n.id).order("updated_at",{ascending:false}).limit(s*3);if(u)throw u;return (c??[]).map(d=>po("rule",n.id,d,e)).filter(d=>ho(d.path,o)).slice(0,s)}let{data:a,error:l}=await i.from("skills").select("id, name, description, content, updated_at, node_skills(nodes!node_skills_node_id_fkey(id, relative_path))").eq("workspace_id",n.id).order("updated_at",{ascending:false}).limit(s*3);if(l)throw l;return (a??[]).map(c=>po("skill",n.id,c,e)).filter(c=>ho(c.path,o)).slice(0,s)}async function go(t,e,r={}){let n=t.trim().toLowerCase();if(!n)throw new Error("search_query_required");let i=r.types?.length?r.types:["memory","rule","skill"];return (await Promise.all(i.map(o=>Yr(o,e,{path:r.path,limit:Math.max(fo(r.limit),50)})))).flat().map(o=>({item:o,score:aw(o,n)})).filter(o=>o.score>0).sort((o,a)=>a.score-o.score||(a.item.updated_at??"").localeCompare(o.item.updated_at??"")).slice(0,fo(r.limit)).map(o=>o.item)}async function mo(t,e,r){let n=await Yr(t,r,{limit:100}),i=e.toLowerCase(),s=n.find(d=>d.id===e||d.title.toLowerCase()===i);if(!s)throw new Error(`${t}_not_found`);let{supabase:o}=await C(r),a=t==="memory"?"memories":t==="rule"?"rules":"skills",{data:l,error:c}=await o.from(a).select("content").eq("id",s.id).maybeSingle();if(c)throw c;let u=typeof l?.content=="string"?l.content:"";return {...s,content:u}}function kt(t,e,r,n,i){let s=(n.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"");return i?`${s}/workspace/${encodeURIComponent(t)}/node/${encodeURIComponent(i)}/${e}/${encodeURIComponent(r)}`:`${s}/workspace/${encodeURIComponent(t)}/${e}/${encodeURIComponent(r)}`}function ew(t,e,r,n){let i=n?`/node/${encodeURIComponent(n)}`:"";return `pathrule://workspace/${encodeURIComponent(t)}${i}/${e}/${encodeURIComponent(r)}`}async function tw(t){let e=await M(t);if(!e)throw new Error("workspace_required");return e}function po(t,e,r,n){let i=typeof r.title=="string"?r.title:typeof r.name=="string"?r.name:String(r.id),s=typeof r.content=="string"?r.content:typeof r.description=="string"?r.description:"",o=iw(t,r),a=sw(t,r),l=kt(e,t,String(r.id),n,a);return {id:String(r.id),kind:t,title:i,path:o,node_id:a,preview:lw(s),updated_at:typeof r.updated_at=="string"?r.updated_at:null,url:l,open_targets:[rw(e,t,String(r.id),n,a),nw(e,t,String(r.id),a)]}}function rw(t,e,r,n,i){return {kind:"web",url:kt(t,e,r,n,i),label:`Open ${e} in Pathrule Web`,reason:"preferred"}}function nw(t,e,r,n){return {kind:"desktop-app",url:ew(t,e,r,n),label:`Open ${e} in Pathrule Desktop`,reason:"fallback"}}function iw(t,e){if(t==="memory"){let s=e.nodes;return typeof s?.relative_path=="string"?s.relative_path:null}let i=e[t==="rule"?"node_rules":"node_skills"]?.[0]?.nodes?.relative_path;return typeof i=="string"?i:null}function sw(t,e){if(t==="memory"){let s=e.nodes;return typeof s?.id=="string"?s.id:null}let i=e[t==="rule"?"node_rules":"node_skills"]?.[0]?.nodes?.id;return typeof i=="string"?i:null}function ow(t){if(!t)return null;let e=t.trim();return e?e.startsWith("/")?e:`/${e}`:null}function ho(t,e){return e?t?t===e||t.startsWith(`${e}/`):false:true}function aw(t,e){let r=t.title.toLowerCase(),n=t.preview.toLowerCase(),i=t.path?.toLowerCase()??"",s=0;return r===e&&(s+=100),r.includes(e)&&(s+=30),i.includes(e)&&(s+=15),n.includes(e)&&(s+=10),s}function lw(t){return t.replace(/\s+/g," ").trim().slice(0,160)}function fo(t){return !t||!Number.isFinite(t)?20:Math.min(Math.max(Math.trunc(t),1),100)}F();async function ko(t,e,r){let{session:n,supabase:i}=await C(r),s=await M(r);if(!s)throw new Error("workspace_required");let o={supabase:i,userId:n.user.id,workspaceId:s.id};if(t==="memory"){let c=e,u=await za(o,{node_path:er(c.path),title:_o(c.title,"memory_title_required"),content:wo(c.body),source:"manual",allow_duplicate:c.allowDuplicate});if(!u.ok)throw new Error(u.error.message);return {item:{id:u.data.id,kind:t,title:u.data.title,path:er(c.path),url:kt(s.id,t,u.data.id,r),open_targets:[yo(s.id,t,u.data.id,r)],content_length:u.data.content.length,source:u.data.source},warnings:u.warnings??[]}}if(t==="rule"){let c=e,u=await Ja(o,{node_path:er(c.path),name:_o(c.name,"rule_name_required"),content:wo(c.body),priority:c.priority,scope_type:c.scopeType,allow_duplicate:c.allowDuplicate});if(!u.ok)throw new Error(u.error.message);return {item:{id:u.data.id,kind:t,title:u.data.name,path:er(c.path),url:kt(s.id,t,u.data.id,r),open_targets:[yo(s.id,t,u.data.id,r)],content_length:u.data.content.length,priority:u.data.priority,scope_type:u.data.scopeType},warnings:u.warnings??[]}}let a=e,l=await Ka(o,{node_path:er(a.path),name:_o(a.name,"skill_name_required"),description:Uu(a.description),content:wo(a.body),source:"manual"});if(!l.ok)throw new Error(l.error.message);return {item:{id:l.data.id,kind:t,title:l.data.name,path:er(a.path),url:kt(s.id,t,l.data.id,r),open_targets:[yo(s.id,t,l.data.id,r)],content_length:l.data.content.length,description:l.data.description,source:l.data.source},warnings:l.warnings??[]}}function Lu(t,e){if(t!=="skill")return "";let r=e,n=Uu(r.description)??"Describe when to use this skill.";return ["---",`name: ${r.name.trim()}`,`description: ${n}`,"---","","# Overview","","Explain when this skill should be used.","","## Instructions","","- Add the steps, constraints, and guardrails this skill should enforce.",""].join(`
|
|
78
78
|
`)}function er(t){let e=t.trim();if(!e)throw new Error("content_path_required");return e.startsWith("/")?e:`/${e}`}function _o(t,e){let r=t.trim();if(!r)throw new Error(e);return r}function wo(t){let e=t.replace(/\r\n/g,`
|
|
79
|
-
`);if(!e.trim())throw new Error("content_body_required");return e}function Uu(t){let e=t?.trim();return e||null}function yo(t,e,r,n){return {kind:"web",url:kt(t,e,r,n),label:`Open ${e} in Pathrule Web`,reason:"preferred"}}var Wu="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",dw=16;function Bu(t=dw){if(t<12)throw new Error("bridge_pair_code_too_short");let e=randomBytes(t),r="";for(let n of e)r+=Wu[n%Wu.length];return r.match(/.{1,4}/g)?.join("-")??r}function Fu(t){let e=pw(t);return createHash("sha256").update("pathrule-bridge-pair-v1","utf8").update("\0","utf8").update(bo(t.pairCode),"utf8").update("\0","utf8").update(t.pairVerifier,"utf8").update("\0","utf8").update(e,"utf8").digest("base64url")}function pw(t){return JSON.stringify({daemon_session_id:
|
|
79
|
+
`);if(!e.trim())throw new Error("content_body_required");return e}function Uu(t){let e=t?.trim();return e||null}function yo(t,e,r,n){return {kind:"web",url:kt(t,e,r,n),label:`Open ${e} in Pathrule Web`,reason:"preferred"}}var Wu="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",dw=16;function Bu(t=dw){if(t<12)throw new Error("bridge_pair_code_too_short");let e=randomBytes(t),r="";for(let n of e)r+=Wu[n%Wu.length];return r.match(/.{1,4}/g)?.join("-")??r}function Fu(t){let e=pw(t);return createHash("sha256").update("pathrule-bridge-pair-v1","utf8").update("\0","utf8").update(bo(t.pairCode),"utf8").update("\0","utf8").update(t.pairVerifier,"utf8").update("\0","utf8").update(e,"utf8").digest("base64url")}function pw(t){return JSON.stringify({daemon_session_id:Xr(t.daemonSessionId,"daemon_session_id"),browser_profile_id:Xr(t.browserProfileId,"browser_profile_id"),origin:hw(t.origin),user_id:Xr(t.userId,"user_id")})}function bo(t){return Xr(t,"pair_secret").replace(/[\s-]+/g,"").toUpperCase()}function hw(t){let e=Xr(t,"origin"),r=new URL(e);if(r.protocol!=="https:"&&r.hostname!=="localhost")throw new Error("bridge_pair_origin_not_allowed");return r.pathname="",r.search="",r.hash="",r.toString().replace(/\/$/,"")}function Xr(t,e){if(typeof t!="string"||t.trim()==="")throw new Error(`bridge_pair_${e}_required`);return t.trim()}K();F();var bw=300*1e3,Y=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="BridgePairError";}code};async function So(t){let e=t.user??await pi(t.env,t.verifyReauth!==false),r=Bu(),n=new Date(Date.now()+bw).toISOString(),i={schema_version:1,pair_code_hash:qu(r),user_id:e.user_id,user_email:e.user_email,daemon_session_id:t.daemonSessionId,created_at:new Date().toISOString(),expires_at:n};return await vw(t.env,i),{pair_code:r,expires_at:n,url:`${Cw(t.env)}/connect`,daemon_session_id:t.daemonSessionId}}async function Hu(t){let e=await Sw(t.env);if(!e)throw new Y("pair_code_missing");if(e.daemon_session_id!==t.daemonSessionId)throw await vo(t.env),new Y("pair_code_stale");if(Date.parse(e.expires_at)<=Date.now())throw await vo(t.env),new Y("pair_code_expired");if(e.pair_code_hash!==qu(t.pairCode))throw new Y("pair_code_invalid");let r=Fu({daemonSessionId:t.daemonSessionId,browserProfileId:t.browserProfileId,origin:t.origin,userId:e.user_id,pairCode:t.pairCode,pairVerifier:t.pairVerifier});return await vo(t.env),{pair_token:r,daemon_session_id:t.daemonSessionId,user_id:e.user_id}}async function pi(t,e=true){let{session:r,supabase:n}=await C(t);if(e){let{data:i,error:s}=await n.rpc("verify_sensitive_action_grant",{p_action:"bridge_pair"});if(s)throw new Y("bridge_pair_reauth_check_failed",s.message);if(i!==true)throw new Y("bridge_pair_reauth_required","Run sensitive-action reauth for bridge_pair before pairing this browser.")}return {user_id:r.user.id,user_email:r.user.email}}async function vw(t,e){let r=A(t).bridgePairFile;await mkdir(dirname(r),{recursive:true,mode:D});let n=`${r}.tmp`;await writeFile(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:O}),await rename(n,r);}async function Sw(t){try{return JSON.parse(await readFile(A(t).bridgePairFile,"utf8"))}catch{return null}}async function vo(t){await unlink(A(t).bridgePairFile).catch(()=>{});}function qu(t){return createHash("sha256").update("pathrule-bridge-pair-code-v1","utf8").update("\0","utf8").update(bo(t),"utf8").digest("base64url")}function Cw(t){return (t.PATHRULE_WEB_URL||t.VITE_PATHRULE_WEB_URL||"https://app.pathrule.io").replace(/\/+$/,"")}var hi="x-pathrule-pair-token",zu="x-pathrule-browser-profile-id";function bt(t){let e=Ew(t.headers,t.allowedOrigins);if(e)return e;let r=Co(t.headers,"content-type");return !r||!/^application\/json(?:\s*;|$)/i.test(r)?{statusCode:415,reason:"json_content_type_required"}:t.requirePairToken!==false&&!Co(t.headers,hi)?{statusCode:401,reason:"pair_token_required"}:null}function Eo(t,e){return !t||!fi(t,e)?null:{"Access-Control-Allow-Origin":t,"Access-Control-Allow-Headers":"Authorization, X-Pathrule-Pair-Token, X-Pathrule-Browser-Profile-Id, Content-Type","Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Credentials":"false"}}function Ew(t,e){let r=Co(t,"origin");return r?fi(r,e)?null:{statusCode:400,reason:"origin_not_allowed"}:{statusCode:400,reason:"origin_required"}}function fi(t,e){return e.some(r=>r===t)}function Ju(t){return {daemon_present:true,protocol_version:t}}function Ku(t){let e=t.windowMs??6e4,r=Math.floor((t.nowMs??Date.now())/e);return `${t.origin}\0${t.ip}\0${r}`}function Co(t,e){let r=t[e]??t[e.toLowerCase()],n=Array.isArray(r)?r[0]:r;return (typeof n=="string"?n.trim():"")||void 0}K();function Vu(t){return t==="modified"||t==="added"||t==="deleted"||t==="renamed"||t==="untracked"||t==="unknown"}function Gu(t){let e=t.nowMs??Date.now(),r=t.rows.filter(i=>t.currentUserId===null||i.user_id!==t.currentUserId).flatMap(i=>xw(i,t.displayNamesByUserId??{},e)).sort(Aw),n=Math.max(0,e-(t.startedAtMs??e));return r.length===0?{decision:"allow",conflicts:[],source:t.source,latency_ms:n}:{decision:"ask",conflicts:r,message:Pw(r[0],e),source:t.source,latency_ms:n}}function Yu(t=Date.now()){return {decision:"ask",conflicts:[],message:"Pathrule could not verify teammate local state in time. Continue?",source:"degraded",latency_ms:Math.max(0,Date.now()-t)}}function Xu(t){return Array.isArray(t)?t.flatMap(e=>{if(!e||typeof e!="object")return [];let r=e,n=typeof r.relative_path=="string"?r.relative_path:"",i=typeof r.user_id=="string"?r.user_id:"",s=typeof r.workspace_id=="string"?r.workspace_id:"";if(!n||!i||!s)return [];let o=Vu(r.git_status)?r.git_status:"unknown";return [{workspace_id:s,user_id:i,runtime_id:typeof r.runtime_id=="string"?r.runtime_id:"unknown",relative_path:n,is_active:r.is_active===true,is_dirty:r.is_dirty===true,git_status:o,last_heartbeat_at:typeof r.last_heartbeat_at=="string"?r.last_heartbeat_at:null,last_local_write_at:typeof r.last_local_write_at=="string"?r.last_local_write_at:null,last_git_scan_at:typeof r.last_git_scan_at=="string"?r.last_git_scan_at:new Date(0).toISOString()}]}):[]}function xw(t,e,r){let n=t.last_heartbeat_at?Date.parse(t.last_heartbeat_at):Number.NaN,i=t.is_active&&Number.isFinite(n)&&r-n<=3e4,s=t.is_dirty;return !i&&!s?[]:[{user_id:t.user_id,display_name:Zu(e[t.user_id]??"A teammate"),relative_path:t.relative_path,reason:i&&s?"active_dirty":i?"active":"dirty",git_status:t.git_status,last_heartbeat_at:t.last_heartbeat_at,last_local_write_at:t.last_local_write_at}]}function Pw(t,e){let r=Zu(t.display_name);if(t.reason==="active"||t.reason==="active_dirty")return `Pathrule caught a possible conflict. ${r} is actively working on this file. Continue?`;let n=Tw(t.last_local_write_at,e);return `Pathrule caught a possible conflict. ${r} changed this file ${n} and has not committed it yet. Continue?`}function Tw(t,e){let r=t?Date.parse(t):Number.NaN;if(!Number.isFinite(r))return "recently";let n=Math.max(0,e-r),s=60*6e4,o=24*s;if(n<s)return "recently";if(n<o){let l=Math.max(1,Math.floor(n/s));return `${l} ${l===1?"hour":"hours"} ago`}let a=Math.max(1,Math.floor(n/o));return `${a} ${a===1?"day":"days"} ago`}function Aw(t,e){let r=i=>i.reason==="active"||i.reason==="active_dirty"?0:1,n=r(t)-r(e);return n!==0?n:t.relative_path.localeCompare(e.relative_path)}function Zu(t){let e=t.replace(/[\x00-\x1F\x7F]/g,"").trim();return !e||e.includes("@")||/^https?:\/\//i.test(e)?"A teammate":e.slice(0,80)}F();K();var Lw=".pathrule/managed-files.json";function ed(t){return join(t,Lw)}function xo(t){let e=normalize(t).replace(/\\/g,"/").replace(/^\/+/,"");if(e==="."||e.length===0||e.startsWith("../")||e.includes("/../"))throw new Error(`Invalid managed file path: ${t}`);return e}async function gi(t){try{let e=await readFile(ed(t),"utf8"),r=JSON.parse(e);if(r.schema_version!==1||!Array.isArray(r.files))return Ro();let n=r.files.flatMap(i=>{if(!i||typeof i!="object")return [];let s=i;if(typeof s.path!="string"||!Bw(s.owner)||typeof s.owner_version!="string"||typeof s.updated_at!="string")return [];try{return [{path:xo(s.path),owner:s.owner,owner_version:s.owner_version,updated_at:s.updated_at}]}catch{return []}});return {schema_version:1,files:id(Fw(n))}}catch(e){if(e.code==="ENOENT"||e instanceof SyntaxError)return Ro();throw e}}async function mi(t){if(t.paths.length===0)return;let e=await gi(t.workspaceRoot),r=(t.now??new Date).toISOString(),n=new Map(e.files.map(i=>[i.path,i]));for(let i of t.paths){let s=xo(i);n.set(s,{path:s,owner:t.owner,owner_version:t.ownerVersion,updated_at:r});}await nd(t.workspaceRoot,{schema_version:1,files:id(Array.from(n.values()))});}async function td(t){if(t.paths.length===0)return;let e=await gi(t.workspaceRoot),r=new Set(t.paths.map(xo));await nd(t.workspaceRoot,{schema_version:1,files:e.files.filter(n=>!r.has(n.path))});}function rd(t,e,r){return t.files.map(n=>({...n,status:Ww(n,e,r)}))}function Uw(t,e){let r=Qu(t),n=Qu(e),i=Math.max(r.length,n.length);for(let s=0;s<i;s+=1){let o=(r[s]??0)-(n[s]??0);if(o!==0)return o>0?1:-1}return 0}function Ww(t,e,r){if(t.owner!==e)return "other_owner";let n=Uw(t.owner_version,r);return n>0?"newer_version":n<0?"older_version":"current"}async function nd(t,e){let r=ed(t);await mkdir(dirname(r),{recursive:true});let n=`${r}.tmp`;await writeFile(n,`${JSON.stringify(e,null,2)}
|
|
80
80
|
`,"utf8"),await rename(n,r);}function Ro(){return {schema_version:1,files:[]}}function Bw(t){return t==="desktop"||t==="cli"||t==="mcp"}function Qu(t){let e=t.match(/\d+(?:\.\d+)*/);return e?e[0].split(".").map(r=>Number.parseInt(r,10)):[0]}function Fw(t){return Array.from(new Map(t.map(e=>[e.path,e])).values())}function id(t){return t.sort((e,r)=>e.path.localeCompare(r.path))}function Po(t){if(!(!t||t.trim().length===0))try{return JSON.parse(t)}catch(e){throw new Error(`Claude config is not valid JSON: ${e.message}`)}}function sd(t){return JSON.stringify(t,null,2)+`
|
|
81
81
|
`}var od={id:"claude-code",homeConfigPath(t,e){return La(e,t)},inject(t,e){let r=Po(t),{config:n,wasNew:i}=Ua(r??{},e);return {body:sd(n),wasNew:i}},remove(t){if(t===null)return {body:null,wasPresent:false};let e=Po(t),{config:r,wasPresent:n}=Wa(e);return n?{body:sd(r),wasPresent:true}:{body:t,wasPresent:false}},read(t){try{let e=Po(t);return Ba(e)}catch{return null}}};function Hw(t,e){let r=t.slice(0,e).split(/\r\n|\n|\r/g);return [r.length,r.pop().length+1]}function qw(t,e,r){let n=t.split(/\r\n|\n|\r/g),i="",s=(Math.log10(e+1)|0)+1;for(let o=e-1;o<=e+1;o++){let a=n[o-1];a&&(i+=o.toString().padEnd(s," "),i+=": ",i+=a,i+=`
|
|
82
82
|
`,o===e&&(i+=" ".repeat(s+r+2),i+=`^
|
|
@@ -89,37 +89,37 @@ ${s}`,r),this.line=n,this.column=i,this.codeblock=s;}};function zw(t,e){let r=0;
|
|
|
89
89
|
`||i==="\r"&&t[e+1]===`
|
|
90
90
|
`);)e++;if(n||i!=="#")break;e=tr(t,e);}return e}function ad(t,e,r,n,i=false){if(!n)return e=_i(t,e),e<0?t.length:e;for(let s=e;s<t.length;s++){let o=t[s];if(o==="#")s=_i(t,s);else {if(o===r)return s+1;if(o===n||i&&(o===`
|
|
91
91
|
`||o==="\r"&&t[s+1]===`
|
|
92
|
-
`))return s}}throw new P("cannot find end of structure",{toml:t,ptr:e})}function wi(t,e){let r=t[e],n=r===t[e+1]&&t[e+1]===t[e+2]?t.slice(e,e+3):r;e+=n.length-1;do e=t.indexOf(n,++e);while(e>-1&&r!=="'"&&zw(t,e));return e>-1&&(e+=n.length,n.length>1&&(t[e]===r&&e++,t[e]===r&&e++)),e}var Jw=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,
|
|
92
|
+
`))return s}}throw new P("cannot find end of structure",{toml:t,ptr:e})}function wi(t,e){let r=t[e],n=r===t[e+1]&&t[e+1]===t[e+2]?t.slice(e,e+3):r;e+=n.length-1;do e=t.indexOf(n,++e);while(e>-1&&r!=="'"&&zw(t,e));return e>-1&&(e+=n.length,n.length>1&&(t[e]===r&&e++,t[e]===r&&e++)),e}var Jw=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,Zr=class t extends Date{#t=false;#r=false;#e=null;constructor(e){let r=true,n=true,i="Z";if(typeof e=="string"){let s=e.match(Jw);s?(s[1]||(r=false,e=`0000-01-01T${e}`),n=!!s[2],n&&e[10]===" "&&(e=e.replace(" ","T")),s[2]&&+s[2]>23?e="":(i=s[3]||null,e=e.toUpperCase(),!i&&n&&(e+="Z"))):e="";}super(e),isNaN(this.getTime())||(this.#t=r,this.#r=n,this.#e=i);}isDateTime(){return this.#t&&this.#r}isLocal(){return !this.#t||!this.#r||!this.#e}isDate(){return this.#t&&!this.#r}isTime(){return this.#r&&!this.#t}isValid(){return this.#t||this.#r}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#e===null)return e.slice(0,-1);if(this.#e==="Z")return e;let r=+this.#e.slice(1,3)*60+ +this.#e.slice(4,6);return r=this.#e[0]==="-"?r:-r,new Date(this.getTime()-r*6e4).toISOString().slice(0,-1)+this.#e}static wrapAsOffsetDateTime(e,r="Z"){let n=new t(e);return n.#e=r,n}static wrapAsLocalDateTime(e){let r=new t(e);return r.#e=null,r}static wrapAsLocalDate(e){let r=new t(e);return r.#r=false,r.#e=null,r}static wrapAsLocalTime(e){let r=new t(e);return r.#t=false,r.#e=null,r}};var Kw=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Vw=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,Gw=/^[+-]?0[0-9_]/,Yw=/^[0-9a-f]{2,8}$/i,ld={b:"\b",t:" ",n:`
|
|
93
93
|
`,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};function yi(t,e=0,r=t.length){let n=t[e]==="'",i=t[e++]===t[e]&&t[e]===t[e+1];i&&(r-=2,t[e+=2]==="\r"&&e++,t[e]===`
|
|
94
94
|
`&&e++);let s=0,o,a="",l=e;for(;e<r-1;){let c=t[e++];if(c===`
|
|
95
95
|
`||c==="\r"&&t[e]===`
|
|
96
96
|
`){if(!i)throw new P("newlines are not allowed in strings",{toml:t,ptr:e-1})}else if(c<" "&&c!==" "||c==="\x7F")throw new P("control characters are not allowed in strings",{toml:t,ptr:e-1});if(o){if(o=false,c==="x"||c==="u"||c==="U"){let u=t.slice(e,e+=c==="x"?2:c==="u"?4:8);if(!Yw.test(u))throw new P("invalid unicode escape",{toml:t,ptr:s});try{a+=String.fromCodePoint(parseInt(u,16));}catch{throw new P("invalid unicode escape",{toml:t,ptr:s})}}else if(i&&(c===`
|
|
97
97
|
`||c===" "||c===" "||c==="\r")){if(e=se(t,e-1,true),t[e]!==`
|
|
98
|
-
`&&t[e]!=="\r")throw new P("invalid escape: only line-ending whitespace may be escaped",{toml:t,ptr:s});e=se(t,e);}else if(c in ld)a+=ld[c];else throw new P("unrecognized escape sequence",{toml:t,ptr:s});l=e;}else !n&&c==="\\"&&(s=e-1,o=true,a+=t.slice(l,s));}return a+t.slice(l,r-1)}function cd(t,e,r,n){if(t==="true")return true;if(t==="false")return false;if(t==="-inf")return -1/0;if(t==="inf"||t==="+inf")return 1/0;if(t==="nan"||t==="+nan"||t==="-nan")return NaN;if(t==="-0")return n?0n:0;let i=Kw.test(t);if(i||Vw.test(t)){if(Gw.test(t))throw new P("leading zeroes are not allowed",{toml:e,ptr:r});t=t.replace(/_/g,"");let o=+t;if(isNaN(o))throw new P("invalid number",{toml:e,ptr:r});if(i){if((i=!Number.isSafeInteger(o))&&!n)throw new P("integer value cannot be represented losslessly",{toml:e,ptr:r});(i||n===true)&&(o=BigInt(t));}return o}let s=new
|
|
98
|
+
`&&t[e]!=="\r")throw new P("invalid escape: only line-ending whitespace may be escaped",{toml:t,ptr:s});e=se(t,e);}else if(c in ld)a+=ld[c];else throw new P("unrecognized escape sequence",{toml:t,ptr:s});l=e;}else !n&&c==="\\"&&(s=e-1,o=true,a+=t.slice(l,s));}return a+t.slice(l,r-1)}function cd(t,e,r,n){if(t==="true")return true;if(t==="false")return false;if(t==="-inf")return -1/0;if(t==="inf"||t==="+inf")return 1/0;if(t==="nan"||t==="+nan"||t==="-nan")return NaN;if(t==="-0")return n?0n:0;let i=Kw.test(t);if(i||Vw.test(t)){if(Gw.test(t))throw new P("leading zeroes are not allowed",{toml:e,ptr:r});t=t.replace(/_/g,"");let o=+t;if(isNaN(o))throw new P("invalid number",{toml:e,ptr:r});if(i){if((i=!Number.isSafeInteger(o))&&!n)throw new P("integer value cannot be represented losslessly",{toml:e,ptr:r});(i||n===true)&&(o=BigInt(t));}return o}let s=new Zr(t);if(!s.isValid())throw new P("invalid value",{toml:e,ptr:r});return s}function Xw(t,e,r){let n=t.slice(e,r),i=n.indexOf("#");return i>-1&&(tr(t,i),n=n.slice(0,i)),[n.trimEnd(),i]}function Qr(t,e,r,n,i){if(n===0)throw new P("document contains excessively nested structures. aborting.",{toml:t,ptr:e});let s=t[e];if(s==="["||s==="{"){let[l,c]=s==="["?dd(t,e,n,i):ud(t,e,n,i);if(r){if(c=se(t,c),t[c]===",")c++;else if(t[c]!==r)throw new P("expected comma or end of structure",{toml:t,ptr:c})}return [l,c]}let o;if(s==='"'||s==="'"){o=wi(t,e);let l=yi(t,e,o);if(r){if(o=se(t,o),t[o]&&t[o]!==","&&t[o]!==r&&t[o]!==`
|
|
99
99
|
`&&t[o]!=="\r")throw new P("unexpected character encountered",{toml:t,ptr:o});o+=+(t[o]===",");}return [l,o]}o=ad(t,e,",",r);let a=Xw(t,e,o-+(t[o-1]===","));if(!a[0])throw new P("incomplete key-value declaration: no value specified",{toml:t,ptr:e});return r&&a[1]>-1&&(o=se(t,e+a[1]),o+=+(t[o]===",")),[cd(a[0],t,e,i),o]}var Zw=/^[a-zA-Z0-9-_]+[ \t]*$/;function ki(t,e,r="="){let n=e-1,i=[],s=t.indexOf(r,e);if(s<0)throw new P("incomplete key-value: cannot find end of key",{toml:t,ptr:e});do{let o=t[e=++n];if(o!==" "&&o!==" ")if(o==='"'||o==="'"){if(o===t[e+1]&&o===t[e+2])throw new P("multiline strings are not allowed in keys",{toml:t,ptr:e});let a=wi(t,e);if(a<0)throw new P("unfinished string encountered",{toml:t,ptr:e});n=t.indexOf(".",a);let l=t.slice(a,n<0||n>s?s:n),c=_i(l);if(c>-1)throw new P("newlines are not allowed in keys",{toml:t,ptr:e+n+c});if(l.trimStart())throw new P("found extra tokens after the string part",{toml:t,ptr:a});if(s<a&&(s=t.indexOf(r,a),s<0))throw new P("incomplete key-value: cannot find end of key",{toml:t,ptr:e});i.push(yi(t,e,a));}else {n=t.indexOf(".",e);let a=t.slice(e,n<0||n>s?s:n);if(!Zw.test(a))throw new P("only letter, numbers, dashes and underscores are allowed in keys",{toml:t,ptr:e});i.push(a.trimEnd());}}while(n+1&&n<s);return [i,se(t,s+1,true,true)]}function ud(t,e,r,n){let i={},s=new Set,o;for(e++;(o=t[e++])!=="}"&&o;){if(o===",")throw new P("expected value, found comma",{toml:t,ptr:e-1});if(o==="#")e=tr(t,e);else if(o!==" "&&o!==" "&&o!==`
|
|
100
|
-
`&&o!=="\r"){let a,l=i,c=false,[u,d]=ki(t,e-1);for(let f=0;f<u.length;f++){if(f&&(l=c?l[a]:l[a]={}),a=u[f],(c=Object.hasOwn(l,a))&&(typeof l[a]!="object"||s.has(l[a])))throw new P("trying to redefine an already defined value",{toml:t,ptr:e});!c&&a==="__proto__"&&Object.defineProperty(l,a,{enumerable:true,configurable:true,writable:true});}if(c)throw new P("trying to redefine an already defined value",{toml:t,ptr:e});let[p,h]=
|
|
101
|
-
`&&s!=="\r"){let o=
|
|
102
|
-
`&&t[a]!=="\r")throw new P("each key-value declaration must be followed by an end-of-line",{toml:t,ptr:a});a=se(t,a);}return n}var hd=/^[a-z0-9-_]+$/i;function
|
|
100
|
+
`&&o!=="\r"){let a,l=i,c=false,[u,d]=ki(t,e-1);for(let f=0;f<u.length;f++){if(f&&(l=c?l[a]:l[a]={}),a=u[f],(c=Object.hasOwn(l,a))&&(typeof l[a]!="object"||s.has(l[a])))throw new P("trying to redefine an already defined value",{toml:t,ptr:e});!c&&a==="__proto__"&&Object.defineProperty(l,a,{enumerable:true,configurable:true,writable:true});}if(c)throw new P("trying to redefine an already defined value",{toml:t,ptr:e});let[p,h]=Qr(t,d,"}",r-1,n);s.add(p),l[a]=p,e=h;}}if(!o)throw new P("unfinished table encountered",{toml:t,ptr:e});return [i,e]}function dd(t,e,r,n){let i=[],s;for(e++;(s=t[e++])!=="]"&&s;){if(s===",")throw new P("expected value, found comma",{toml:t,ptr:e-1});if(s==="#")e=tr(t,e);else if(s!==" "&&s!==" "&&s!==`
|
|
101
|
+
`&&s!=="\r"){let o=Qr(t,e-1,"]",r-1,n);i.push(o[0]),e=o[1];}}if(!s)throw new P("unfinished array encountered",{toml:t,ptr:e});return [i,e]}function pd(t,e,r,n){let i=e,s=r,o,a=false,l;for(let c=0;c<t.length;c++){if(c){if(i=a?i[o]:i[o]={},s=(l=s[o]).c,n===0&&(l.t===1||l.t===2))return null;if(l.t===2){let u=i.length-1;i=i[u],s=s[u].c;}}if(o=t[c],(a=Object.hasOwn(i,o))&&s[o]?.t===0&&s[o]?.d)return null;a||(o==="__proto__"&&(Object.defineProperty(i,o,{enumerable:true,configurable:true,writable:true}),Object.defineProperty(s,o,{enumerable:true,configurable:true,writable:true})),s[o]={t:c<t.length-1&&n===2?3:n,d:false,i:0,c:{}});}if(l=s[o],l.t!==n&&!(n===1&&l.t===3)||(n===2&&(l.d||(l.d=true,i[o]=[]),i[o].push(i={}),l.c[l.i++]=l={t:1,d:false,i:0,c:{}}),l.d))return null;if(l.d=true,n===1)i=a?i[o]:i[o]={};else if(n===0&&a)return null;return [o,i,l.c]}function To(t,{maxDepth:e=1e3,integersAsBigInt:r}={}){let n={},i={},s=n,o=i;for(let a=se(t,0);a<t.length;){if(t[a]==="["){let l=t[++a]==="[",c=ki(t,a+=+l,"]");if(l){if(t[c[1]-1]!=="]")throw new P("expected end of table declaration",{toml:t,ptr:c[1]-1});c[1]++;}let u=pd(c[0],n,i,l?2:1);if(!u)throw new P("trying to redefine an already defined table or value",{toml:t,ptr:a});o=u[2],s=u[1],a=c[1];}else {let l=ki(t,a),c=pd(l[0],s,o,0);if(!c)throw new P("trying to redefine an already defined table or value",{toml:t,ptr:a});let u=Qr(t,l[1],void 0,e,r);c[1][c[0]]=u[0],a=u[1];}if(a=se(t,a,true),t[a]&&t[a]!==`
|
|
102
|
+
`&&t[a]!=="\r")throw new P("each key-value declaration must be followed by an end-of-line",{toml:t,ptr:a});a=se(t,a);}return n}var hd=/^[a-z0-9-_]+$/i;function en(t){let e=typeof t;if(e==="object"){if(Array.isArray(t))return "array";if(t instanceof Date)return "date"}return e}function Qw(t){for(let e=0;e<t.length;e++)if(en(t[e])!=="object")return false;return t.length!=0}function Ao(t){return JSON.stringify(t).replace(/\x7f/g,"\\u007f")}function Io(t,e,r,n){if(r===0)throw new Error("Could not stringify the object: maximum object depth exceeded");if(e==="number")return isNaN(t)?"nan":t===1/0?"inf":t===-1/0?"-inf":n&&Number.isInteger(t)?t.toFixed(1):t.toString();if(e==="bigint"||e==="boolean")return t.toString();if(e==="string")return Ao(t);if(e==="date"){if(isNaN(t.getTime()))throw new TypeError("cannot serialize invalid date");return t.toISOString()}if(e==="object")return ey(t,r,n);if(e==="array")return ty(t,r,n)}function ey(t,e,r){let n=Object.keys(t);if(n.length===0)return "{}";let i="{ ";for(let s=0;s<n.length;s++){let o=n[s];s&&(i+=", "),i+=hd.test(o)?o:Ao(o),i+=" = ",i+=Io(t[o],en(t[o]),e-1,r);}return i+" }"}function ty(t,e,r){if(t.length===0)return "[]";let n="[ ";for(let i=0;i<t.length;i++){if(i&&(n+=", "),t[i]===null||t[i]===void 0)throw new TypeError("arrays cannot contain null or undefined values");n+=Io(t[i],en(t[i]),e-1,r);}return n+" ]"}function ry(t,e,r,n){if(r===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let i="";for(let s=0;s<t.length;s++)i+=`${i&&`
|
|
103
103
|
`}[[${e}]]
|
|
104
|
-
`,i+=Oo(0,t[s],e,r,n);return i}function Oo(t,e,r,n,i){if(n===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let s="",o="",a=Object.keys(e);for(let l=0;l<a.length;l++){let c=a[l];if(e[c]!==null&&e[c]!==void 0){let u=
|
|
104
|
+
`,i+=Oo(0,t[s],e,r,n);return i}function Oo(t,e,r,n,i){if(n===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let s="",o="",a=Object.keys(e);for(let l=0;l<a.length;l++){let c=a[l];if(e[c]!==null&&e[c]!==void 0){let u=en(e[c]);if(u==="symbol"||u==="function")throw new TypeError(`cannot serialize values of type '${u}'`);let d=hd.test(c)?c:Ao(c);if(u==="array"&&Qw(e[c]))o+=(o&&`
|
|
105
105
|
`)+ry(e[c],r?`${r}.${d}`:d,n-1,i);else if(u==="object"){let p=r?`${r}.${d}`:d;o+=(o&&`
|
|
106
106
|
`)+Oo(p,e[c],p,n-1,i);}else s+=d,s+=" = ",s+=Io(e[c],u,n,i),s+=`
|
|
107
107
|
`;}}return t&&(s||!o)&&(s=s?`[${t}]
|
|
108
108
|
${s}`:`[${t}]`),s&&o?`${s}
|
|
109
|
-
${o}`:s||o}function bi(t,{maxDepth:e=1e3,numbersAsFloat:r=false}={}){if(
|
|
109
|
+
${o}`:s||o}function bi(t,{maxDepth:e=1e3,numbersAsFloat:r=false}={}){if(en(t)!=="object")throw new TypeError("stringify can only be called with an object");let n=Oo(0,t,"",e,r);return n[n.length-1]!==`
|
|
110
110
|
`?n+`
|
|
111
111
|
`:n}var oe="pathrule";function $o(t){if(!t||t.trim().length===0)return {};let e;try{e=To(t);}catch(r){throw new Error(`config.toml is not valid TOML: ${r.message}`)}if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("config.toml root must be a TOML table");return e}function ny(t){let e={command:t.command,args:t.args,enabled:true};return t.env&&Object.keys(t.env).length>0&&(e.env=t.env),e}function iy(t){return !t||typeof t.command!="string"?null:{type:"stdio",command:t.command,args:Array.isArray(t.args)?t.args.map(String):[],env:t.env&&typeof t.env=="object"&&!Array.isArray(t.env)?t.env:void 0}}var fd={id:"codex",homeConfigPath(t,e){return `${t}/.codex/config.toml`},inject(t,e){let r=$o(t),n={...r.mcp_servers??{}},i=!(oe in n);n[oe]=ny(e);let s={...r,mcp_servers:n};return {body:bi(s)+`
|
|
112
112
|
`,wasNew:i}},remove(t){let e=$o(t),r=e.mcp_servers??{};if(!(oe in r))return {body:t,wasPresent:false};let{[oe]:n,...i}=r,s={...e};return Object.keys(i).length===0?delete s.mcp_servers:s.mcp_servers=i,Object.keys(s).length===0?{body:null,wasPresent:true}:{body:bi(s)+`
|
|
113
113
|
`,wasPresent:true}},read(t){try{let e=$o(t);return iy(e.mcp_servers?.[oe])}catch{return null}}};function sy(t){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new Error("Config root must be a JSON object");let e=t;if(e.mcpServers!==void 0&&(typeof e.mcpServers!="object"||e.mcpServers===null||Array.isArray(e.mcpServers)))throw new Error("`mcpServers` must be an object");return e}function No(t){if(!t||t.trim().length===0)return {};let e;try{e=JSON.parse(t);}catch(r){throw new Error(`Config is not valid JSON: ${r.message}`)}return sy(e)}function gd(t){return JSON.stringify(t,null,2)+`
|
|
114
|
-
`}function vi(t){function e(r){if(t.includeTypeField)return r;let{type:n,...i}=r;return i}return {inject(r,n){let i=No(r),s={...i.mcpServers??{}},o=!(oe in s);s[oe]=e(n);let a={...i,mcpServers:s};return {body:gd(a),wasNew:o}},remove(r){let n=No(r),i=n.mcpServers??{};if(!(oe in i))return {body:r,wasPresent:false};let{[oe]:s,...o}=i,a={...n,mcpServers:o};return Object.keys(o).length===0&&Object.keys(a).length===1&&"mcpServers"in a?{body:null,wasPresent:true}:{body:gd(a),wasPresent:true}},read(r){try{return No(r).mcpServers?.[oe]??null}catch{return null}}}}var jo=vi({includeTypeField:true}),md={id:"cursor",homeConfigPath(t,e){return `${t}/.cursor/mcp.json`},inject:jo.inject,remove:jo.remove,read:jo.read};var Do=vi({includeTypeField:false}),_d={id:"windsurf",homeConfigPath(t,e){return `${t}/.codeium/windsurf/mcp_config.json`},inject:Do.inject,remove:Do.remove,read:Do.read};var oy={"claude-code":od,cursor:md,codex:fd,windsurf:_d};function vt(t){return oy[t]}
|
|
114
|
+
`}function vi(t){function e(r){if(t.includeTypeField)return r;let{type:n,...i}=r;return i}return {inject(r,n){let i=No(r),s={...i.mcpServers??{}},o=!(oe in s);s[oe]=e(n);let a={...i,mcpServers:s};return {body:gd(a),wasNew:o}},remove(r){let n=No(r),i=n.mcpServers??{};if(!(oe in i))return {body:r,wasPresent:false};let{[oe]:s,...o}=i,a={...n,mcpServers:o};return Object.keys(o).length===0&&Object.keys(a).length===1&&"mcpServers"in a?{body:null,wasPresent:true}:{body:gd(a),wasPresent:true}},read(r){try{return No(r).mcpServers?.[oe]??null}catch{return null}}}}var jo=vi({includeTypeField:true}),md={id:"cursor",homeConfigPath(t,e){return `${t}/.cursor/mcp.json`},inject:jo.inject,remove:jo.remove,read:jo.read};var Do=vi({includeTypeField:false}),_d={id:"windsurf",homeConfigPath(t,e){return `${t}/.codeium/windsurf/mcp_config.json`},inject:Do.inject,remove:Do.remove,read:Do.read};var oy={"claude-code":od,cursor:md,codex:fd,windsurf:_d};function vt(t){return oy[t]}zr();F();Ee();var hy=createRequire(import.meta.url),fy=hy("../package.json"),gy=fy.version,my=["claude-code","cursor","codex","windsurf"];async function je(t,e){let r=[],n=await Ce(t);r.push({name:"auth",status:n?"pass":"fail",detail:n?n.session.user.email??n.session.user.id:"not_authenticated"});let i=null;if(n){try{let u=await j(t);r.push({name:"organization",status:u?"pass":"warn",detail:u?.slug??"no organization selected"});}catch(u){r.push({name:"organization",status:"fail",detail:u instanceof Error?u.message:String(u)});}try{let u=await M(t);i=u?.local_root_path??null,r.push({name:"workspace",status:u?"pass":"warn",detail:u?.name??"no workspace selected"});}catch(u){r.push({name:"workspace",status:"fail",detail:u instanceof Error?u.message:String(u)});}}r.push({name:"cwd_attach",status:i===e?"pass":"warn",detail:i===e?"current folder is attached":i??"workspace not attached"});let s=await Promise.all(my.map(vy)),o=rd(await gi(e),"cli",gy),a=o.filter(u=>u.status==="other_owner").length,l=o.filter(u=>u.status==="newer_version").length;return a>0||l>0?r.push({name:"managed_files",status:"warn",detail:wy(a,l)}):o.length>0?r.push({name:"managed_files",status:"pass",detail:`${o.length} Pathrule-managed file${o.length===1?"":"s"} tracked`}):r.push({name:"managed_files",status:"pass",detail:"no Pathrule-managed files tracked yet"}),{ok:!r.some(u=>u.status==="fail"),checks:r,mcp:s,managed_files:o}}async function Lo(t,e){await ky(t);let r=await je(t,e),n=A(t);await mkdir(n.supportDir,{recursive:true,mode:D}),await chmod(n.supportDir,D).catch(()=>{});let i=join(n.supportDir,`${new Date().toISOString().replace(/[:.]/g,"-")}-doctor.json`),s={schema_version:1,produced_at:new Date().toISOString(),cwd_hash:by(e),platform:process.platform,node_version:process.version,env_keys:Object.keys(t).filter(o=>o.startsWith("PATHRULE_")||o==="CI"||o==="NO_COLOR").sort(),report:_y(r)};return Cl(s),await writeFile(i,JSON.stringify(s,null,2),{encoding:"utf8",mode:O}),await chmod(i,O).catch(()=>{}),{ok:r.ok,path:i,report:r}}function _y(t){return {ok:t.ok,checks:t.checks.map(e=>({...e,detail:Mo(e.detail)})),mcp:t.mcp.map(e=>({...e,config_path:yy(e.config_path),error:Mo(e.error)})),managed_files:t.managed_files.map(e=>({...e,path:Mo(e.path)??e.path}))}}function wy(t,e){let r=[];return t>0&&r.push(`${t} file${t===1?"":"s"} last written by another surface`),e>0&&r.push(`${e} file${e===1?"":"s"} last written by a newer CLI`),r.join("; ")}function Mo(t){return t&&gs(t)}function yy(t){return gs(t,"path")}async function ky(t){let{supabase:e}=await C(t),{data:r,error:n}=await e.rpc("consume_sensitive_action_grant",{p_action:"token_export"});if(n)throw new Error(`token_export_reauth_check_failed: ${n.message}`);if(r!==true)throw new Error("token_export_reauth_required")}function by(t){let e=2166136261;for(let r=0;r<t.length;r+=1)e^=t.charCodeAt(r),e=Math.imul(e,16777619);return (e>>>0).toString(16).padStart(8,"0")}async function vy(t){let e=vt(t),r=e.homeConfigPath(homedir(),process.platform);try{let n=await readFile(r,"utf8");return {client:t,config_path:r,readable:!0,installed:e.read(n)!==null}}catch(n){return n.code==="ENOENT"?{client:t,config_path:r,readable:false,installed:false}:{client:t,config_path:r,readable:false,installed:false,error:n instanceof Error?n.message:String(n)}}}var St=class extends Error{constructor(e){super(e),this.name="WorkspacePathSafetyError";}};async function kd(t,e){let r=await realpath(t),n=Cy(e),i=Ge.resolve(r,n||"."),s=await realpath(i);if(!vd(r,s))throw new St(`Refused: ${e||"/"} escapes the workspace root`);return {rootRealPath:r,absolutePath:s,relativePath:n===""?"/":`/${Ey(n)}`}}async function bd(t,e){try{let r=await realpath(e);return vd(t,r)?(await stat(r)).isDirectory():!1}catch{return false}}function Cy(t){if(typeof t!="string")throw new St("Refused: workspace path must be a string");if(t.includes("\0"))throw new St("Refused: workspace path contains a null byte");let e=t.trim();if(e===""||e==="/"||e===".")return "";if(/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\"))throw new St("Refused: absolute workspace path is not allowed");let r=e.replace(/^[/\\]+/,""),i=Ge.normalize(r).split(/[\\/]+/).filter(Boolean);if(i.includes(".."))throw new St(`Refused: ${t} escapes the workspace root`);return i.join(Ge.sep)}function vd(t,e){let r=yd(Ge.resolve(t)),n=yd(Ge.resolve(e)),i=r.endsWith(Ge.sep)?r:r+Ge.sep;return n===r||n.startsWith(i)}function yd(t){return process.platform==="win32"||process.platform==="darwin"?t.toLowerCase():t}function Ey(t){return t.split(Ge.sep).join("/")}var Py=new Set([".git","node_modules",".next","dist","build",".turbo",".cache","coverage","target","__pycache__",".venv","venv",".DS_Store",".idea",".vscode"]);async function Wo(t,e){let r=await kd(t,e),n=await promises.readdir(r.absolutePath,{withFileTypes:true,encoding:"utf8"}),i=[];for(let s of n){if(Py.has(s.name))continue;let o=Ge.join(r.absolutePath,s.name),a=s.isDirectory()||s.isSymbolicLink()&&await bd(r.rootRealPath,o);i.push({absPath:o,relativePath:Ty(e,s.name),name:s.name,isDir:a});}return i.sort((s,o)=>s.isDir!==o.isDir?s.isDir?-1:1:s.name.localeCompare(o.name)),i}function Ty(t,e){return t==="/"||t===""?"/"+e:t+"/"+e}K();async function Si(t){let e=Cd(t.env,t.workspaceId),r=false;if(t.refreshEpisodes!==false){let{error:o}=await t.supabase.rpc("pathrule_refresh_work_episodes",{p_workspace_id:t.workspaceId});r=!o;}let{data:n,error:i}=await t.supabase.rpc("pathrule_build_hook_index_payload",{p_workspace_id:t.workspaceId});if(i)return {ok:false,path:e,refreshed_episodes:r,schema_version:null,error:i.message};if(!n||typeof n!="object")return {ok:false,path:e,refreshed_episodes:r,schema_version:null,error:"empty_hook_index_payload"};let s={...n,workspace_root:t.workspaceRoot};return await Ny(t.env,s),{ok:true,path:e,refreshed_episodes:r,schema_version:s.schema_version}}function Cd(t,e){return join(A(t).home,"cache",e,"hook-index.json")}async function Ny(t,e){let r=Cd(t,e.workspace_id);await mkdir(join(A(t).home,"cache",e.workspace_id),{recursive:true});let n=`${r}.tmp`;await writeFile(n,JSON.stringify(e,null,2),"utf8"),await chmod(n,384),await rename(n,r);}K();F();Ke();function Ct(t,e){let r=[];r.push("<!-- Pathrule managed \u2014 do not edit; cloud state is authoritative. -->",""),r.push("# Pathrule integration",""),r.push("Pathrule is this workspace's shared memory, rule, and skill layer for AI agents.",`${e.toolLabel} should use it as a smart reminder system, not a full-context dump.`,""),r.push("## Context Policy",""),r.push("- Pathrule is the first knowledge layer for this workspace. Use hook context first: metadata, relevant rule titles, path reminders, and filename/skill matches.","- `::skill-name` is a hard gate: use the exact injected skill; if missing, stop and resolve it through Pathrule/MCP before file edits.",'- Do not reflexively call `pathrule_get_context` before every small known-path code task. For discovery, inventory, architecture, recent activity, or "list/show/find/where/which" prompts (Turkish: listele, g\xF6ster, bul, nerede, hangi, neler), call it before any grep/read/fallback when hook context is missing, ambiguous, or stale.',"- Hook silence on a topic does not mean Pathrule has no relevant memory/rule. For discovery/inventory/architecture questions, call `pathrule_get_context` first; fall back to files, git, or general knowledge only after Pathrule returns nothing relevant.","- When calling `pathrule_get_context`, pass `cwd`, `user_intent`, and `omit_protocol: true`; the companion file already contains the protocol.","- Read full bodies with `pathrule_read_memory`, `pathrule_read_rule`, or `pathrule_read_skill` when a surfaced title/id is relevant.","- Treat existing local edits as protected user/team work: inspect overlaps, never revert unrelated changes, and keep edits scoped.","- Obey every surfaced rule. If a user request conflicts with a Pathrule rule, warn before taking action.",""),r.push("## Writes",""),r.push("- Pathrule cloud is the source of truth. Do not create local memory files such as `MEMORY.md` or `~/.claude/memory/`.","- Use path-first writes for lasting project knowledge: `pathrule_write_memory`, `pathrule_write_rule`, and `pathrule_write_skill` take the most specific workspace-relative `node_path`.","- Do not edit materialized local Pathrule files as the source of truth. This includes `.codex/skills/**/SKILL.md`, `.claude/skills/**`, rendered companion files, and synced skill/memory/rule files. Read only for orientation; create/update cloud records with the Pathrule MCP write/update tools.","- After any file-modifying response, call `pathrule_log_activity` once with domain, action, scope, subjects, files_touched, and a concise task_summary.","");let n=r.join(`
|
|
115
115
|
`).replace(/\n{3,}/g,`
|
|
116
116
|
|
|
117
117
|
`);return n.endsWith(`
|
|
118
118
|
`)?n:`${n}
|
|
119
|
-
`}var Ed="AGENTS.md",Rd=".codex/hooks.json",xd=".codex/config.toml";function jy(t){let e=Ct(t,{toolLabel:"Codex"}),r=ul(Be()),n=
|
|
119
|
+
`}var Ed="AGENTS.md",Rd=".codex/hooks.json",xd=".codex/config.toml";function jy(t){let e=Ct(t,{toolLabel:"Codex"}),r=ul(Be()),n=Cn(null).body;return [{path:Ed,body:e},{path:Rd,body:r},{path:xd,body:n}]}function Dy(t){return [Ed,"codex.md",Rd,xd]}var Pd={id:"codex",render:jy,ownedPaths:Dy};var Td=".cursor/rules/pathrule-protocol.mdc",Ad=".cursorrules",Id=".cursor/hooks.json";function My(){return ["## Cursor-specific guardrail","","- If you call `pathrule_get_context`, include BOTH `cwd` and `user_intent`.","- `cwd` MUST be the absolute path of the active workspace root.","- Never call `pathrule_get_context` with empty args. If `cwd` is unknown, resolve it first.","","Example:","","```json",`{ "cwd": "/absolute/path/to/workspace", "user_intent": "<user's last message>", "omit_protocol": true }`,"```",""].join(`
|
|
120
120
|
`)}function Ly(){return ["---",'description: "Pathrule integration \u2014 workspace-shared memories, rules, and skills"',"alwaysApply: true","---",""].join(`
|
|
121
121
|
`)}function Uy(t){let e=Ct(t,{toolLabel:"Cursor"})+`
|
|
122
|
-
`+My(),r=cl(Be());return [{path:Td,body:Ly()+e},{path:Ad,body:e},{path:Id,body:r}]}function Wy(t){return [Td,Ad,Id]}var Od={id:"cursor",render:Uy,ownedPaths:Wy};var $d=".windsurf/rules/pathrule-protocol.md",Nd=".windsurfrules";function By(t){let e=Ct(t,{toolLabel:"Windsurf"});return [{path:$d,body:e},{path:Nd,body:e}]}function Fy(t){return [$d,Nd]}var jd={id:"windsurf",render:By,ownedPaths:Fy};var Hy={cursor:Od,codex:Pd,windsurf:jd};function Dd(t){return Hy[t]??null}async function qy(t,e){let{data:r,error:n}=await t.from("workspaces").select("name").eq("id",e).maybeSingle();if(n)throw new Error(`workspaces lookup failed: ${n.message}`);if(!r)throw new Error(`workspace ${e} not found (RLS or deleted)`);return r.name}async function zy(t,e){try{let r=new Date(Date.now()-12096e5).toISOString(),{data:n}=await t.from("activity_logs").select("domain, action, task_summary, created_at").eq("workspace_id",e).eq("status","active").gte("created_at",r).order("created_at",{ascending:!1}).limit(8);return n??[]}catch{return []}}async function Md(t){let e={supabase:t.supabase},[r,n,i,s]=await Promise.all([qy(t.supabase,t.workspaceId),
|
|
122
|
+
`+My(),r=cl(Be());return [{path:Td,body:Ly()+e},{path:Ad,body:e},{path:Id,body:r}]}function Wy(t){return [Td,Ad,Id]}var Od={id:"cursor",render:Uy,ownedPaths:Wy};var $d=".windsurf/rules/pathrule-protocol.md",Nd=".windsurfrules";function By(t){let e=Ct(t,{toolLabel:"Windsurf"});return [{path:$d,body:e},{path:Nd,body:e}]}function Fy(t){return [$d,Nd]}var jd={id:"windsurf",render:By,ownedPaths:Fy};var Hy={cursor:Od,codex:Pd,windsurf:jd};function Dd(t){return Hy[t]??null}async function qy(t,e){let{data:r,error:n}=await t.from("workspaces").select("name").eq("id",e).maybeSingle();if(n)throw new Error(`workspaces lookup failed: ${n.message}`);if(!r)throw new Error(`workspace ${e} not found (RLS or deleted)`);return r.name}async function zy(t,e){try{let r=new Date(Date.now()-12096e5).toISOString(),{data:n}=await t.from("activity_logs").select("domain, action, task_summary, created_at").eq("workspace_id",e).eq("status","active").gte("created_at",r).order("created_at",{ascending:!1}).limit(8);return n??[]}catch{return []}}async function Md(t){let e={supabase:t.supabase},[r,n,i,s]=await Promise.all([qy(t.supabase,t.workspaceId),kn(e,{workspace_id:t.workspaceId,relative_path:"/"}),Mt(e,{workspace_id:t.workspaceId}),zy(t.supabase,t.workspaceId)]);if(!n.ok)throw new Error(`getContext failed: ${n.error.message}`);if(!i.ok)throw new Error(`getWorkspaceOverview failed: ${i.error.message}`);return {workspaceName:r,rootContext:{memories:n.data.memories.map(o=>({id:o.id,title:o.title,preview:o.preview})),rules:n.data.rules,skills:n.data.skills.map(o=>({id:o.id,name:o.name,description:o.description,source:o.source}))},overview:i.data,recentActivities:s.length>0?s:void 0}}function Ld(t,e){let r=[];for(let n of e){let i=Dd(n);i&&r.push({client:n,files:i.render(t),ownedPaths:i.ownedPaths(t)});}return r}var Bo="<!-- Pathrule managed",Xy="<!-- managed by Pathrule";var Zy={".cursor/rules/pathrule-protocol.mdc":{kind:"overwrite"},".cursorrules":{kind:"backup-on-first-write",markerSubstring:Bo},".cursor/hooks.json":{kind:"merge",merger:fl},".claude/rules/pathrule-protocol.md":{kind:"overwrite"},".claude/settings.json":{kind:"merge",merger:Sn},"CLAUDE.md":{kind:"backup-on-first-write",markerSubstring:Xy},"AGENTS.md":{kind:"backup-on-first-write",markerSubstring:Bo},".codex/hooks.json":{kind:"merge",merger:gl},".codex/config.toml":{kind:"merge",merger:Cn},".windsurf/rules/pathrule-protocol.md":{kind:"overwrite"},".windsurfrules":{kind:"backup-on-first-write",markerSubstring:Bo}};async function Wd(t){try{return await access(t,constants.F_OK),!0}catch{return false}}async function Qy(t){if(!await Wd(t))return t;for(let e=1;e<1e3;e+=1){let r=`${t}.${e}`;if(!await Wd(r))return r}throw new Error(`Could not find a free backup name near ${t}`)}async function Ci(t){let e=Zy[t.relativePath]??{kind:"overwrite"},r=join(t.workspaceRoot,t.relativePath);switch(e.kind){case "overwrite":return t.existingBody===t.renderedBody?{finalBody:null,backupPath:null}:{finalBody:t.renderedBody,backupPath:null};case "backup-on-first-write":{let n=t.existingBody!==null&&!t.existingBody.includes(e.markerSubstring)&&t.existingBody!==t.renderedBody,i=null;if(n){let s=await Qy(join(dirname(r),`backup.${basename(r)}`));await rename(r,s),i=s;}return t.existingBody===t.renderedBody?{finalBody:null,backupPath:null}:{finalBody:t.renderedBody,backupPath:i}}case "merge":{let{body:n,changed:i}=e.merger(t.existingBody);return !i&&t.existingBody===n?{finalBody:null,backupPath:null}:{finalBody:n,backupPath:null}}}}async function lk(t){try{return await access(t,constants.F_OK),!0}catch{return false}}async function ck(t,e){await mkdir(dirname(t),{recursive:true});let r=`${t}.tmp`;await writeFile(r,e,"utf8"),await rename(r,t);}async function uk(t){try{return await readFile(t,"utf8")}catch(e){if(e.code==="ENOENT")return null;throw e}}async function dk(t){try{return await unlink(t),!0}catch(e){return e.code==="ENOENT",false}}async function Fd(t){let e={written:0,skipped:0,removed:0,backedUp:[],errors:[]},r=new Set,n=new Set;for(let i of t.results){let s=new Set(i.files.map(o=>o.path));for(let o of i.files){let a=join(t.workspaceRoot,o.path);try{let l=await uk(a),c=await Ci({workspaceRoot:t.workspaceRoot,relativePath:o.path,renderedBody:o.body,existingBody:l});if(c.backupPath&&e.backedUp.push(c.backupPath),c.finalBody===null){e.skipped+=1,r.add(o.path);continue}await ck(a,c.finalBody),e.written+=1,r.add(o.path);}catch(l){e.errors.push({path:o.path,message:l instanceof Error?l.message:String(l)});}}for(let o of i.ownedPaths){if(s.has(o))continue;let a=join(t.workspaceRoot,o);if(!await lk(a))continue;await dk(a)&&(e.removed+=1,n.add(o));}}if(t.runtimeOwner&&t.runtimeVersion)try{await mi({workspaceRoot:t.workspaceRoot,paths:Array.from(r),owner:t.runtimeOwner,ownerVersion:t.runtimeVersion}),await td({workspaceRoot:t.workspaceRoot,paths:Array.from(n)});}catch(i){e.errors.push({path:".pathrule/managed-files.json",message:i instanceof Error?i.message:String(i)});}return e}var pk=["cursor","codex","windsurf"];async function hk(t,e,r){let{data:n}=await t.from("user_workspace_paths").select("selected_ai_clients").eq("workspace_id",r).eq("user_id",e).maybeSingle();return n?.selected_ai_clients??null}async function Hd(t){let e={written:0,skipped:0,removed:0,backedUp:[],errors:[]};try{let[r,n]=await Promise.all([hk(t.supabase,t.userId,t.workspaceId),He(t.workspaceRoot)]),i=Tn({selected:r,detected:n,fallback:Rn}),s=i.filter(c=>pk.includes(c));if(s.length===0)return {ok:!0,enabled:i,results:[],disk:e};let o=await Md({supabase:t.supabase,workspaceId:t.workspaceId,userId:t.userId}),a=Ld(o,s),l=await Fd({workspaceRoot:t.workspaceRoot,results:a,sweepFor:s,runtimeOwner:t.runtimeOwner,runtimeVersion:t.runtimeVersion});return {ok:!0,enabled:i,results:a,disk:l}}catch(r){return {ok:false,enabled:[],results:[],disk:e,error:r instanceof Error?r.message:String(r)}}}K();var bk=".pathrule-skills-manifest.json",rr=2;function tn(){return {version:rr,skills:{}}}function rn(t){return createHash("sha256").update(t,"utf8").digest("hex")}function qd(t){return join(t,".claude",bk)}function vk(t){if(!t||typeof t!="object")return false;let e=t;return typeof e.slug=="string"&&typeof e.hash=="string"&&typeof e.source=="string"&&(e.fetchedAt===null||typeof e.fetchedAt=="string")&&Array.isArray(e.targets)&&e.targets.every(r=>typeof r=="string")}function Sk(t){if(!t||typeof t!="object")return false;let e=t;return typeof e.path=="string"&&typeof e.hash=="string"}function Ck(t,e){if(!t||typeof t!="object"||Array.isArray(t))return null;let r={};for(let[n,i]of Object.entries(t)){if(!vk(i)||e===rr&&i.files!==void 0&&!Array.isArray(i.files)||e===rr&&i.files?.some(s=>!Sk(s)))return null;r[n]={slug:i.slug,hash:i.hash,source:i.source,fetchedAt:i.fetchedAt,targets:i.targets,...e===rr&&i.files?{files:i.files}:{}};}return r}async function zd(t){try{let e=await readFile(qd(t),"utf8"),r=JSON.parse(e);if(!r||typeof r!="object"||r.version!==rr&&r.version!==1)return tn();let n=Ck(r.skills??{},r.version);return n?{version:rr,skills:n}:tn()}catch{return tn()}}async function Jd(t,e){let r=qd(t);await mkdir(dirname(r),{recursive:true});let n=`${r}.tmp`;await writeFile(n,JSON.stringify(e,null,2),"utf8"),await rename(n,r);}async function nr(t){try{return await access(t,constants.F_OK),!0}catch{return false}}async function Dk(t,e){await mkdir(dirname(t),{recursive:true});let r=`${t}.tmp`;await writeFile(r,e,"utf8"),await rename(r,t);}function Mk(t){let e=t.content??"";if(e.trim().startsWith("---"))return e.endsWith(`
|
|
123
123
|
`)?e:`${e}
|
|
124
124
|
`;let r=t.name.replace(/"/g,"'"),n=(t.description??"").replace(/"/g,"'").replace(/\r?\n/g," ").trim();return `${`---
|
|
125
125
|
name: "${r}"
|
|
@@ -128,8 +128,8 @@ name: "${r}"
|
|
|
128
128
|
|
|
129
129
|
`}${e}${e.endsWith(`
|
|
130
130
|
`)?"":`
|
|
131
|
-
`}`}function Lk(t,e,r){let n=e.skills[t.id]?.slug;if(n&&!r.has(n))return n;let i=
|
|
132
|
-
`))}function qo(t){return t.files?.length?t.files:[{path:"SKILL.md",hash:t.hash}]}function Kd(t,e){return t!==e&&(t.startsWith(`${e}/`)||e.startsWith(`${t}/`))}async function Bk(t,e,r,n){let i=posix.dirname(n);for(;i&&i!==".";){try{await rmdir(join(t,e.skillsDir,r,i));}catch{return}i=posix.dirname(i);}}async function Fk(t,e,r,n,i){if(!n)return 0;let s=0;for(let o of qo(n)){let a;try{a=Ho(o.path);}catch{continue}if(!Array.from(i).some(u=>Kd(a,u)))continue;let c=join(t,e.skillsDir,r,a);await nr(c)&&(await rm$1(c,{force:true}),s+=1,await Bk(t,e,r,a));}return s}async function Hk(t,e,r,n,i){if(!n)return 0;let s=0;for(let o of qo(n)){let a;try{a=Ho(o.path);}catch{continue}if(i.has(a))continue;let l=join(t,e.skillsDir,r,a);await nr(l)&&(await rm$1(l,{force:true}),s+=1);}return s}async function qk(t,e){let r=join(t,e.skillsDir);if(!await nr(r))return [];try{return (await readdir(r,{withFileTypes:!0})).filter(i=>i.isDirectory()).map(i=>i.name)}catch{return []}}function zk(t){let e=new Map;for(let r of t){let n=
|
|
131
|
+
`}`}function Lk(t,e,r){let n=e.skills[t.id]?.slug;if(n&&!r.has(n))return n;let i=xn(t.name);return i&&!r.has(i)?i:vl(t.name,t.id)}async function Ei(t,e,r){let n=join(t,e.skillsDir,r);await nr(n)&&await rm$1(n,{recursive:true,force:true});}function Ho(t){let e=t.trim();if(!e)throw new Error("Package file path is empty");if(e.includes("\\"))throw new Error(`Unsafe package file path: ${t}`);if(e.includes("//"))throw new Error(`Unsafe package file path: ${t}`);if(posix.isAbsolute(e)||win32.isAbsolute(e))throw new Error(`Unsafe package file path: ${t}`);if(e.split("/").some(i=>!i||i===".."))throw new Error(`Unsafe package file path: ${t}`);let r=posix.normalize(e);if(!r||r==="."||r.startsWith("../"))throw new Error(`Unsafe package file path: ${t}`);if(r.split("/").some(i=>!i||i===".."))throw new Error(`Unsafe package file path: ${t}`);return r}function Uk(t){if(!t.files?.length){let n=Mk(t);return [{path:"SKILL.md",content:n,hash:rn(n)}]}let e=new Set,r=t.files.map(n=>{let i=Ho(n.path);if(e.has(i))throw new Error(`Duplicate package file path: ${i}`);return e.add(i),{path:i,content:n.content,hash:n.sha256||rn(n.content)}}).sort((n,i)=>n.path.localeCompare(i.path));for(let n=1;n<r.length;n+=1){let i=r[n-1],s=r[n];if(Kd(i.path,s.path))throw new Error(`Conflicting package file paths: ${i.path}, ${s.path}`)}return r}function Wk(t){return rn(t.map(e=>`${e.path}\0${e.hash}`).join(`
|
|
132
|
+
`))}function qo(t){return t.files?.length?t.files:[{path:"SKILL.md",hash:t.hash}]}function Kd(t,e){return t!==e&&(t.startsWith(`${e}/`)||e.startsWith(`${t}/`))}async function Bk(t,e,r,n){let i=posix.dirname(n);for(;i&&i!==".";){try{await rmdir(join(t,e.skillsDir,r,i));}catch{return}i=posix.dirname(i);}}async function Fk(t,e,r,n,i){if(!n)return 0;let s=0;for(let o of qo(n)){let a;try{a=Ho(o.path);}catch{continue}if(!Array.from(i).some(u=>Kd(a,u)))continue;let c=join(t,e.skillsDir,r,a);await nr(c)&&(await rm$1(c,{force:true}),s+=1,await Bk(t,e,r,a));}return s}async function Hk(t,e,r,n,i){if(!n)return 0;let s=0;for(let o of qo(n)){let a;try{a=Ho(o.path);}catch{continue}if(i.has(a))continue;let l=join(t,e.skillsDir,r,a);await nr(l)&&(await rm$1(l,{force:true}),s+=1);}return s}async function qk(t,e){let r=join(t,e.skillsDir);if(!await nr(r))return [];try{return (await readdir(r,{withFileTypes:!0})).filter(i=>i.isDirectory()).map(i=>i.name)}catch{return []}}function zk(t){let e=new Map;for(let r of t){let n=xn(r.name),i=e.get(n);if(!i){e.set(n,r);continue}let s=i.updatedAt?Date.parse(i.updatedAt):0;(r.updatedAt?Date.parse(r.updatedAt):0)>s&&e.set(n,r);}return Array.from(e.values())}async function Vd(t){let{workspaceRoot:e,activeTargets:r}=t,n=zk(t.skills),i={written:0,skipped:0,removed:0,errors:[]},s=bl(r),o=await zd(e),a=new Set,l={};for(let p of n)try{let h=Lk(p,o,a);a.add(h);let f=Uk(p),m=f.map(T=>({path:T.path,hash:T.hash})),_=!!p.files?.length,b=_?Wk(m):m[0]?.hash??rn(""),w=o.skills[p.id],y=new Map((w?qo(w):[]).map(T=>[T.path,T.hash])),I=new Set(f.map(T=>T.path)),Z=[];for(let T of s){let $=w&&w.slug!==h;$&&w&&await Ei(e,T,w.slug),i.removed+=await Fk(e,T,h,$?void 0:w,I);for(let Te of f){let le=join(e,T.skillsDir,h,Te.path),Yh=y.get(Te.path)!==Te.hash,Xh=!await nr(le);Yh||Xh||$?(await Dk(le,Te.content),i.written+=1):i.skipped+=1;}i.removed+=await Hk(e,T,h,$?void 0:w,I),Z.push(T.id);}if(w){let T=w.targets.filter($=>!Z.includes($));for(let $ of T){let Te=U[$];Te&&(await Ei(e,Te,w.slug),i.removed+=1);}}l[p.id]={slug:h,hash:b,source:p.source,fetchedAt:p.source==="github_ref"?p.contentFetchedAt:null,targets:Z,..._?{files:m}:{}};}catch(h){let f=o.skills[p.id];f&&(l[p.id]=f),i.errors.push({skillId:p.id,message:h instanceof Error?h.message:String(h)});}let c=new Set(n.map(p=>p.id));for(let[p,h]of Object.entries(o.skills))if(!c.has(p))for(let f of h.targets){let m=U[f];m&&(await Ei(e,m,h.slug),i.removed+=1);}let u=new Set;for(let p of Object.values(l))u.add(p.slug);for(let p of Object.values(o.skills))u.add(p.slug);for(let p of s){let h=await qk(e,p);for(let f of h)Object.values(l).some(_=>_.slug===f)||u.has(f)&&(await Ei(e,p,f),i.removed+=1);}let d={version:o.version,skills:l};return await Jd(e,d),Object.keys(l).length>0&&await Kk(e).catch(()=>{}),i}var Gd="# Pathrule-managed skills (M18) \u2014",Jk=`
|
|
133
133
|
${Gd} cloud is the source of truth.
|
|
134
134
|
# Delete the lines below to opt in to committing your materialized skills.
|
|
135
135
|
.claude/skills/
|
|
@@ -139,12 +139,12 @@ ${Gd} cloud is the source of truth.
|
|
|
139
139
|
.claude/.pathrule-skills-manifest.json
|
|
140
140
|
`;async function Kk(t){let e=join(t,".gitignore");if(!await nr(e))return;let r=await readFile(e,"utf8");if(r.includes(Gd))return;let n=r.length>0&&!r.endsWith(`
|
|
141
141
|
`);await appendFile(e,(n?`
|
|
142
|
-
`:"")+Jk,"utf8");}F();F();Ee();var Vk=new Set(["write_memory","write_rule","write_skill","sync_agents","materialize_skills"]);async function ae(t,e){let{supabase:r}=await C(e),n=await j(e),i=(e.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"");if(!n)return ir(t,"org_required",{web_url:`${i}/settings`,suggested_command_after_resolution:"pathrule org use <slug-or-id>"});let{data:s,error:o}=await r.from("organizations").select("id, slug, plan, seat_count, subscription_status").eq("id",n.id).single();if(o)throw o;let a=String(s.plan??n.plan),l=n.role,c=`${i}/org/${n.slug}/billing`;if(t==="create_workspace"){if(!Zk(l))return ir(t,"permission_denied",{role:l,plan:a,organization_id:n.id,web_url:`${i}/org/${n.slug}/settings/members`});let p=await zo(r,"workspaces","organization_id",n.id,{archived_at:null}),h=Jo(a,"workspaces");return Yd(p,h)?ir(t,"capacity_full",{role:l,plan:a,organization_id:n.id,usage:{dimension:"workspaces",used:p,limit:h},web_url:c,suggested_command_after_resolution:"pathrule init"}):Xd(t,{role:l,plan:a,organization_id:n.id})}let u=await M(e);if(!u)return ir(t,"workspace_required",{role:l,plan:a,organization_id:n.id,web_url:`${i}/org/${n.slug}`,suggested_command_after_resolution:"pathrule workspace use <name-or-id>"});if(Vk.has(t)&&!Qk(l))return ir(t,"permission_denied",{role:l,plan:a,organization_id:n.id,workspace_id:u.id,web_url:`${i}/org/${n.slug}/settings/members`});let d=await Xk(t,a,u.id,r);return d&&Yd(d.used,d.limit)?ir(t,"capacity_full",{role:l,plan:a,organization_id:n.id,workspace_id:u.id,usage:d,web_url:c,suggested_command_after_resolution:"pathrule status"}):Xd(t,{role:l,plan:a,organization_id:n.id,workspace_id:u.id,usage:d})}function Ko(t){return ["create_workspace","write_memory","write_rule","write_skill","sync_agents","materialize_skills"].includes(t)}function sr(t){return t.allowed?{summary:`${t.action} is allowed.`,details:[],url:null,suggested_command_after_resolution:null}:t.blocking_reason==="capacity_full"&&t.usage?{summary:`${Gk(t.usage.dimension)} limit reached on the ${t.plan??"current"} plan (${t.usage.used} / ${Yk(t.usage.limit)}).`,details:["Open Pathrule Web to upgrade or clean up usage."],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution}:t.blocking_reason==="permission_denied"?{summary:`Your current role (${t.role??"unknown"}) cannot run ${t.action}.`,details:["Ask an organization admin to update your role or run the action from an admin account."],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution}:t.blocking_reason==="workspace_required"?{summary:"No current workspace is selected for this folder.",details:["Run setup or choose a workspace before retrying."],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution??"pathrule setup --json"}:t.blocking_reason==="org_required"?{summary:"No organization is selected.",details:["Choose an organization before retrying."],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution??"pathrule org use <slug-or-id>"}:{summary:`${t.action} blocked: ${t.blocking_reason??"preflight_blocked"}.`,details:[],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution}}function Gk(t){return t.charAt(0).toLocaleUpperCase("en-US")+t.slice(1)}function Yk(t){return t===-1?"unlimited":String(t)}async function Xk(t,e,r,n){return t==="write_memory"?{dimension:"memories",used:await zo(n,"memories","workspace_id",r),limit:Jo(e,"memories")}:t==="write_rule"?{dimension:"rules",used:await zo(n,"rules","workspace_id",r),limit:Jo(e,"rules")}:null}async function zo(t,e,r,n,i={}){let s=t.from(e).select("id",{count:"exact",head:true}).eq(r,n);for(let l of Object.keys(i))s=s.is(l,null);let{count:o,error:a}=await s;if(a)throw a;return o??0}function Zk(t){return t==="owner"||t==="admin"||t==="member"}function Qk(t){return t==="owner"||t==="admin"||t==="member"}function Jo(t,e){return Fe[t]?.[e]??Fe.free[e]}function Yd(t,e){return e!==-1&&t>=e}function Xd(t,e={}){return {action:t,allowed:true,blocking_reason:null,role:null,plan:null,organization_id:null,workspace_id:null,usage:null,web_url:null,suggested_command_after_resolution:null,...e}}function ir(t,e,r={}){return {action:t,allowed:false,blocking_reason:e,role:null,plan:null,organization_id:null,workspace_id:null,usage:null,web_url:null,suggested_command_after_resolution:null,...r}}var ob=createRequire(import.meta.url),ab=ob("../package.json"),Qd="cli",ep=ab.version;async function De(t,e,r={}){let{session:n,supabase:i}=await C(t),s=await M(t);if(!s)throw new Error("workspace_required");if(!s.local_root_path)throw new Error("workspace_not_attached");if(s.local_root_path!==e)throw new Error("workspace_cwd_mismatch");is(join(A(t).home,"bin","pathrule-hook.js"));let o=await ae(r.skillsOnly?"materialize_skills":"sync_agents",t);if(!o.allowed)return {ok:false,workspace_id:s.id,workspace_root:s.local_root_path,preflight:o,error:o.blocking_reason??"preflight_blocked"};if(r.skillsOnly){let u=await cb({supabase:i,userId:n.user.id,workspaceId:s.id,workspaceRoot:s.local_root_path});return {ok:u.errors.length===0,workspace_id:s.id,workspace_root:s.local_root_path,preflight:o,skills:{ok:u.errors.length===0,enabled:u.enabled,written:u.written,skipped:u.skipped,removed:u.removed,errors:u.errors},error:u.errors.length===0?void 0:"skill_sync_failed"}}let a=await Hd({supabase:i,userId:n.user.id,workspaceId:s.id,workspaceRoot:s.local_root_path,runtimeOwner:Qd,runtimeVersion:ep}),l=await lb({supabase:i,userId:n.user.id,workspaceId:s.id,workspaceRoot:s.local_root_path}),c=await Si({supabase:i,workspaceId:s.id,workspaceRoot:s.local_root_path,env:t});return {ok:a.ok&&l.errors.length===0&&c.ok,workspace_id:s.id,workspace_root:s.local_root_path,preflight:o,companion:{ok:a.ok,enabled:a.enabled,written:a.disk.written,skipped:a.disk.skipped,removed:a.disk.removed,errors:a.disk.errors,error:a.error},claude:{ok:l.errors.length===0,written:l.written,skipped:l.skipped,backed_up:l.backedUp,errors:l.errors,snapshot_changed:l.snapshotChanged},hook_index:c,error:a.error??(l.errors.length>0?"claude_sync_failed":c.ok?void 0:"hook_index_sync_failed")}}async function rn(t,e,r,n={}){let{session:i}=await C(t),s=await ne(i.user.id,t);await ai(i.user.id,{...s,current_workspace_id:e,schema_version:1},t);try{return await De(t,r,n)}finally{await ai(i.user.id,s,t);}}async function lb(t){let e={written:0,skipped:0,backedUp:[],errors:[],snapshotChanged:false},r=new Set,{body:n,snapshotChanged:i}=await nl({supabase:t.supabase,workspaceId:t.workspaceId,userId:t.userId});e.snapshotChanged=i,await Zd(e,t.workspaceRoot,"CLAUDE.md",n)&&r.add("CLAUDE.md"),await Zd(e,t.workspaceRoot,".claude/rules/pathrule-protocol.md",hl())&&r.add(".claude/rules/pathrule-protocol.md");let s=".claude/settings.json";try{let o=join(t.workspaceRoot,s),a=await rp(o),{body:l,changed:c}=vn(a);c?(await tp(o,l),e.written+=1):e.skipped+=1,r.add(s);}catch(o){e.errors.push({path:s,message:o instanceof Error?o.message:String(o)});}try{await mi({workspaceRoot:t.workspaceRoot,paths:Array.from(r),owner:Qd,ownerVersion:ep});}catch(o){e.errors.push({path:".pathrule/managed-files.json",message:o instanceof Error?o.message:String(o)});}return e}async function Zd(t,e,r,n){let i=join(e,r);try{let s=await rp(i),o=await Ci({workspaceRoot:e,relativePath:r,renderedBody:n,existingBody:s});return o.backupPath&&t.backedUp.push(o.backupPath),o.finalBody===null?(t.skipped+=1,!0):(await tp(i,o.finalBody),t.written+=1,!0)}catch(s){return t.errors.push({path:r,message:s instanceof Error?s.message:String(s)}),false}}async function tp(t,e){await mkdir(dirname(t),{recursive:true});let r=`${t}.tmp`;await writeFile(r,e,"utf8"),await rename(r,t);}async function rp(t){try{return await readFile(t,"utf8")}catch(e){if(e.code==="ENOENT")return null;throw e}}async function cb(t){let[e,r]=await Promise.all([ub(t.supabase,t.userId,t.workspaceId,t.workspaceRoot),db(t.supabase,t.workspaceId)]),n=await Vd({workspaceRoot:t.workspaceRoot,activeTargets:e,skills:r});return {enabled:e,written:n.written,skipped:n.skipped,removed:n.removed,errors:n.errors}}async function ub(t,e,r,n){let[{data:i},s]=await Promise.all([t.from("user_workspace_paths").select("selected_ai_clients").eq("workspace_id",r).eq("user_id",e).maybeSingle(),He(n)]),o=i?.selected_ai_clients??null;return Pn({selected:o,detected:s,fallback:En})}async function db(t,e){let{data:r,error:n}=await t.from("skills").select("id, name, description, content, source, github_url, content_fetched_at, updated_at, skill_files(path, content, sha256)").eq("workspace_id",e);if(n)throw new Error(`skill_catalogue_read_failed: ${n.message}`);return (r??[]).map(i=>({id:i.id,name:i.name,description:i.description,content:i.content,source:i.source,githubUrl:i.github_url,contentFetchedAt:i.content_fetched_at,updatedAt:i.updated_at,files:(i.skill_files??[]).map(s=>({path:s.path,content:s.content,sha256:s.sha256}))}))}async function nn(t,e){let r=await je(t,e);try{let n=await De(t,e),i=await je(t,e);return {ok:n.ok&&i.ok,doctor_before:r,sync:n,doctor_after:i,error:n.ok&&i.ok?void 0:n.error??"repair_incomplete"}}catch(n){return {ok:false,doctor_before:r,error:n instanceof Error?n.message:String(n)}}}function ip(t){let e=np(t.doctor_before.checks),r=t.doctor_after??t.doctor_before,n=np(r.checks),i=t.sync?.preflight,s=r.mcp.filter(p=>!p.installed),o=_b(e,n),a=wb(e,n),l=yb(r.mcp),c=kb(t),u=bb(t),d=vb(i);return {ok:t.ok,headline:t.ok?"Local runtime repaired":"Repair incomplete",next_command:Sb(t,n,s.length),sections:[o,a,l,c,u,d]}}async function Go(t,e={}){let{session:r,supabase:n}=await C(t),{data:i,error:s}=await n.from("user_security_state").select("security_epoch").eq("user_id",r.user.id).maybeSingle();if(s)throw s;let o=typeof i?.security_epoch=="number"?i.security_epoch:0,a=rt(r.user.id,o,t),l=[];for(let c=0;c<o;c+=1){let u=join(a.userCacheDir,`epoch-${c}`),d=await mb(u);if(d===0)continue;let p=e.dryRun!==false?false:await gb(u);l.push({path:u,epoch:c,removed:p,bytes:d});}return {ok:true,dry_run:e.dryRun!==false,current_epoch:o,candidates:l,reclaimed_bytes:l.filter(c=>c.removed).reduce((c,u)=>c+u.bytes,0)}}async function gb(t){return await rm$1(t,{recursive:true,force:true}),true}async function mb(t){try{let e=await stat(t);return e.isFile()?e.size:e.isDirectory()?1:0}catch{return 0}}function np(t){return new Map(t.map(e=>[e.name,e]))}function _b(t,e){let r=t.get("auth"),n=e.get("auth"),i=t.get("organization"),s=e.get("organization"),o=[xi(r,n,{pass:(a,l)=>l?`Signed in again as ${a??"the current account"}.`:`Signed in as ${a??"the current account"}.`,warn:a=>`Authentication still needs attention${a?`: ${a}`:""}.`,fail:a=>`Authentication is still blocked${a?`: ${a}`:""}.`}),xi(i,s,{pass:(a,l)=>l?`Organization context restored: ${a??"selected"}.`:`Organization context: ${a??"selected"}.`,warn:a=>`Organization selection is still missing${a&&a!=="no organization selected"?`: ${a}`:""}.`,fail:a=>`Organization lookup failed${a?`: ${a}`:""}.`})];return {title:"Account",status:sp(n?.status,s?.status),lines:o}}function wb(t,e){let r=t.get("workspace"),n=e.get("workspace"),i=t.get("cwd_attach"),s=e.get("cwd_attach"),o=[xi(r,n,{pass:(a,l)=>l?`Workspace selection recovered: ${a??"current workspace"}.`:`Workspace selection: ${a??"current workspace"}.`,warn:a=>`Workspace selection is still incomplete${a&&a!=="no workspace selected"?`: ${a}`:""}.`,fail:a=>`Workspace lookup failed${a?`: ${a}`:""}.`}),xi(i,s,{pass:(a,l)=>l?"Current folder is attached again.":"Current folder is attached.",warn:a=>a==="workspace not attached"?"Current folder is still not attached.":`Current folder still points to ${a??"another workspace root"}.`,fail:a=>`Current folder attachment check failed${a?`: ${a}`:""}.`})];return {title:"Workspace",status:sp(n?.status,s?.status),lines:o}}function yb(t){let e=t.filter(s=>s.installed).length,r=t.filter(s=>!s.installed).map(s=>s.client),n=t.filter(s=>s.error).map(s=>`${s.client}: ${s.error}`),i=[`MCP configs ready for ${e}/${t.length} supported clients.`,r.length>0?`Still missing: ${r.join(", ")}.`:"All supported MCP client configs are present."];return n.length>0&&i.push(`Agent config read errors: ${n.join("; ")}.`),{title:"Agents",status:n.length>0?"fail":r.length>0?"warn":"pass",lines:i}}function kb(t){let e=t.sync?.hook_index;return t.sync?e?{title:"Hooks",status:e.ok?"pass":"fail",lines:[e.ok?`Hook index refreshed${e.schema_version?` (schema ${e.schema_version})`:""}.`:`Hook index refresh failed: ${e.error??"unknown error"}.`,e.refreshed_episodes?"Hook work episodes were refreshed before rebuilding the index.":"Hook work episodes were left unchanged."]}:{title:"Hooks",status:"warn",lines:["Repair did not produce a hook index update."]}:{title:"Hooks",status:"warn",lines:["Repair stopped before hook files could be refreshed."]}}function bb(t){if(!t.sync)return {title:"Files",status:"warn",lines:["Repair stopped before local files could be rewritten."]};let e=[],r="pass";return t.sync.companion&&(e.push(`Companion files: ${t.sync.companion.written} written, ${t.sync.companion.skipped} unchanged, ${t.sync.companion.removed} removed.`),(t.sync.companion.errors.length>0||!t.sync.companion.ok)&&(r="fail",e.push(`Companion errors: ${t.sync.companion.errors.map(n=>n.message).join("; ")||t.sync.companion.error||"unknown error"}.`))),t.sync.claude&&(e.push(`Claude files: ${t.sync.claude.written} written, ${t.sync.claude.skipped} unchanged, ${t.sync.claude.backed_up.length} backed up.`),t.sync.claude.errors.length>0&&(r="fail",e.push(`Claude sync errors: ${t.sync.claude.errors.map(n=>n.message).join("; ")}.`))),t.sync.skills&&(e.push(`Skills: ${t.sync.skills.written} written, ${t.sync.skills.skipped} unchanged, ${t.sync.skills.removed} removed.`),t.sync.skills.errors.length>0&&(r="fail",e.push(`Skill materialization errors: ${t.sync.skills.errors.map(n=>n.message).join("; ")}.`))),e.length===0&&e.push("No local file rewrites were needed."),{title:"Files",status:r,lines:e}}function vb(t){return t?t.allowed?{title:"Capacity",status:"pass",lines:["No plan limit blocked this repair."]}:t.blocking_reason==="capacity_full"&&t.usage?{title:"Capacity",status:"fail",lines:[`${Cb(t.usage.dimension)} limit reached (${t.usage.used} / ${Eb(t.usage.limit)}).`,"Open billing or clean up usage before retrying the repair."]}:{title:"Capacity",status:"warn",lines:["Capacity is not the blocking issue for this repair."]}:{title:"Capacity",status:"warn",lines:["Capacity checks did not run because repair stopped early."]}}function xi(t,e,r){let n=e??t;if(!n)return "No status available.";let i=t!=null&&t.status!=="pass"&&n.status==="pass";return n.status==="pass"?r.pass(n.detail,i):n.status==="warn"?r.warn(n.detail,i):r.fail(n.detail,i)}function sp(...t){return t.includes("fail")?"fail":t.includes("warn")?"warn":"pass"}function Sb(t,e,r){if(e.get("auth")?.status!=="pass")return "pathrule login";if(e.get("organization")?.status!=="pass")return "pathrule org use <slug-or-id>";if(e.get("workspace")?.status!=="pass")return "pathrule workspace use <name-or-id>";if(e.get("cwd_attach")?.status!=="pass")return "pathrule attach <workspace>";let a=t.sync?.preflight;if(a&&!a.allowed&&a.suggested_command_after_resolution)return a.suggested_command_after_resolution;if(r>0)return "pathrule install";let l=!t.sync?.companion?.ok||!!t.sync?.companion?.errors.length||!!t.sync?.claude?.errors.length||!!t.sync?.skills?.errors.length||t.sync?.hook_index?.ok===false;return !t.ok||l?"pathrule sync":"pathrule doctor"}function Cb(t){return t.charAt(0).toLocaleUpperCase("en-US")+t.slice(1)}function Eb(t){return t===-1?"unlimited":String(t)}F();var Nb={all:"all",claude:"claude-code","claude-code":"claude-code",cursor:"cursor",codex:"codex",windsurf:"windsurf"},jb=["claude-code","cursor","codex","windsurf"];function ap(t){let e=Nb[(t??"all").toLowerCase()];if(!e)throw new Error("invalid_install_target");return e==="all"?jb:[e]}async function Ye(t,e){let r=ap(t),n=Db(e);return Promise.all(r.map(async i=>{let s=vt(i),o=s.homeConfigPath(homedir(),process.platform);try{let a=await lp(o),l=s.inject(a,n);return await cp(o,l.body),{client:i,ok:!0,status:"installed",config_path:o,was_new:l.wasNew}}catch(a){return {client:i,ok:false,status:"error",config_path:o,error:a instanceof Error?a.message:String(a)}}}))}async function Yo(t){return Promise.all(ap(t).map(async e=>{let r=vt(e),n=r.homeConfigPath(homedir(),process.platform);try{let i=await lp(n),s=r.remove(i);return s.wasPresent?(s.body===null?await rm$1(n,{force:!0}):await cp(n,s.body),{client:e,ok:!0,status:"removed",config_path:n}):{client:e,ok:!0,status:"not_present",config_path:n}}catch(i){return {client:e,ok:false,status:"error",config_path:n,error:i instanceof Error?i.message:String(i)}}}))}function Db(t){let e=t.SUPABASE_URL??t.VITE_SUPABASE_URL,r=t.SUPABASE_ANON_KEY??t.VITE_SUPABASE_ANON_KEY;if(!e||!r)throw new Error("missing_supabase_config");return {type:"stdio",command:Mb(),args:[fileURLToPath(new URL("../../mcp-server/dist/index.js",import.meta.url))],env:{SUPABASE_URL:e,SUPABASE_ANON_KEY:r}}}function Mb(){try{return execFileSync("which",["node"],{encoding:"utf8"}).trim()||process.execPath}catch{return process.execPath}}async function lp(t){try{return await readFile(t,"utf8")}catch(e){if(e.code==="ENOENT")return null;throw e}}async function cp(t,e){await mkdir(dirname(t),{recursive:true});let r=`${t}.tmp`;await writeFile(r,e,"utf8"),await rename(r,t);}async function Rt(t,e,r,n){let{session:i,supabase:s}=await C(t);if(i.user.id!==e)throw new Error("session_user_mismatch");let[{data:o},a]=await Promise.all([s.from("user_workspace_paths").select("selected_ai_clients").eq("user_id",e).eq("workspace_id",r).maybeSingle(),n?He(n):Promise.resolve([])]),l=new Set(o?.selected_ai_clients??[]),c=new Set(a),u=Object.keys(U);return Promise.all(u.map(async d=>{let p=await qb(d);return {client:d,active:l.has(d)||c.has(d),selected:l.has(d),markers:c.has(d)?["workspace_marker_detected"]:[],machineInstalled:p.installed,machineConfigPath:p.configPath,machineConfigExists:p.configExists}}))}async function hp(t,e,r,n,i,s,o="restore-backup"){let a=zb(i),{session:l,supabase:c}=await C(t);if(l.user.id!==e)throw new Error("session_user_mismatch");let{data:u,error:d}=await c.from("user_workspace_paths").select("selected_ai_clients").eq("user_id",e).eq("workspace_id",r).eq("local_root_path",n).maybeSingle();if(d)throw new Error(`workspace_client_selection_read_failed: ${d.message}`);if(!u)throw new Error("workspace_root_not_attached");let p=[],h=new Set((u.selected_ai_clients??[]).filter(fp)),f=Array.from(h);s?h.add(a):h.delete(a);let m=Array.from(h);if(!Jb(f,m)){let{error:w}=await c.from("user_workspace_paths").update({selected_ai_clients:m}).eq("user_id",e).eq("workspace_id",r).eq("local_root_path",n);if(w)throw new Error(`workspace_client_selection_update_failed: ${w.message}`)}if(s){let w=await Ye(a,t);for(let y of w)y.ok||p.push(`${y.client}: ${y.error??y.status}`);}else await dp(n,a);let _=await rn(t,r,n);return _.ok||p.push(_.error??"workspace_sync_failed"),s||await dp(n,a),{ok:true,statuses:await Rt(t,e,r,n),warnings:p}}async function qb(t){let e=vt(t),r=e.homeConfigPath(homedir(),process.platform);try{let n=await readFile(r,"utf8");return {configPath:r,configExists:!0,installed:e.read(n)!==null}}catch(n){return n.code!=="ENOENT"?{configPath:r,configExists:false,installed:false}:{configPath:r,configExists:false,installed:false}}}function zb(t){if(fp(t))return t;throw new Error("invalid_agent_target")}function fp(t){return hs(t)!==null}function Jb(t,e){if(t.length!==e.length)return false;let r=new Set(t);return e.every(n=>r.has(n))}async function dp(t,e,r){let n=U[e]?.skillsDir;if(!n)return;let i=join(t,n);await rm$1(i,{recursive:true,force:true}),await Kb(dirname(i),t);}async function Kb(t,e){let r=resolve(e),n=resolve(t);for(;n!==r&&n.startsWith(`${r}${sep}`);){try{await rmdir(n);}catch{return}n=dirname(n);}}Ke();var Yb=promisify(execFile),Xb=2e3;function Xo(t){if(t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t))return null;let e=t.replace(/\\/g,"/").replace(/\/+/g,"/");return e.length===0||e==="."||e.startsWith("../")||e.includes("/../")||e.startsWith(".git/")||/[\x00-\x1F]/.test(e)?null:e}function Zb(t){let r=(Buffer.isBuffer(t)?t.toString("utf8"):t).split("\0").filter(i=>i.length>0),n=[];for(let i=0;i<r.length;i+=1){let s=r[i];if(!s||s.length<4)continue;let o=s.slice(0,2),a=s.slice(3),l=Qb(o);if(o.includes("R")||o.includes("C")){let u=Xo(a);u&&n.push({relativePath:u,gitStatus:"renamed"});let d=Xo(r[i+1]??"");d&&n.push({relativePath:d,gitStatus:"renamed"}),i+=1;continue}let c=Xo(a);c&&n.push({relativePath:c,gitStatus:l});}return ev(n)}async function gp(t,e={}){try{let{stdout:r}=await Yb("git",["status","--porcelain=v1","-z"],{cwd:t,encoding:"buffer",maxBuffer:5242880,timeout:e.timeoutMs??Xb});return {entries:Zb(r),degraded:!1}}catch{return {entries:[],degraded:true}}}function Qb(t){return t==="??"?"untracked":t.includes("A")?"added":t.includes("D")?"deleted":t.includes("R")||t.includes("C")?"renamed":t.includes("M")||t.includes("T")||t.includes("U")?"modified":"unknown"}function ev(t){let e=new Map;for(let r of t)e.set(r.relativePath,r);return Array.from(e.values()).sort((r,n)=>r.relativePath.localeCompare(n.relativePath))}var rv=800,nv=6e4,Pi=500,sn=class{constructor(e){this.options=e;}options;dirty=new Map;pendingTimer=null;intervalTimer=null;stopped=false;degraded=false;lastScanAt=null;start(){this.intervalTimer||(this.reconcile(),this.intervalTimer=setInterval(()=>{this.reconcile();},this.options.scanIntervalMs??nv),this.intervalTimer.unref?.());}stop(){this.stopped=true,this.pendingTimer&&clearTimeout(this.pendingTimer),this.intervalTimer&&clearInterval(this.intervalTimer),this.pendingTimer=null,this.intervalTimer=null;}markActivePath(e){if(this.stopped||!iv(e))return;let r=this.isoNow();this.publishRows([{relative_path:e,is_active:true,is_dirty:this.dirty.has(e),git_status:this.dirty.get(e)?.gitStatus??"unknown",last_heartbeat_at:r,last_git_scan_at:r}],[]),this.scheduleReconcile();}scheduleReconcile(){this.stopped||(this.pendingTimer&&clearTimeout(this.pendingTimer),this.pendingTimer=setTimeout(()=>{this.pendingTimer=null,this.reconcile();},this.options.debounceMs??rv),this.pendingTimer.unref?.());}async reconcile(){if(this.stopped)return this.status();let e=this.isoNow(),r=await gp(this.options.workspaceRoot);if(this.degraded=r.degraded,r.degraded)return this.status();let n=new Map;for(let o of r.entries){let a=this.dirty.get(o.relativePath);n.set(o.relativePath,{gitStatus:o.gitStatus,firstSeenAt:a?.firstSeenAt??e});}let i=Array.from(this.dirty.keys()).filter(o=>!n.has(o));this.dirty.clear();for(let[o,a]of n)this.dirty.set(o,a);this.lastScanAt=e;let s=Array.from(n.entries()).map(([o,a])=>({relative_path:o,is_active:false,is_dirty:true,git_status:a.gitStatus,last_local_write_at:a.firstSeenAt,last_git_scan_at:e}));return await this.publishChunked(s,i),this.status()}status(){return {healthy:!this.degraded,degraded:this.degraded,lastScanAt:this.lastScanAt,dirtyPathCount:this.dirty.size}}async publishChunked(e,r){for(let n=0;n<e.length;n+=Pi)await this.publishRows(e.slice(n,n+Pi),[]);for(let n=0;n<r.length;n+=Pi)await this.publishRows([],r.slice(n,n+Pi));}async publishRows(e,r){if(e.length===0&&r.length===0)return;let{error:n}=await this.options.supabase.rpc("pathrule_upsert_file_work_state",{p_workspace_id:this.options.workspaceId,p_runtime_id:this.options.runtimeId,p_rows:e,p_clear_paths:r});n&&(this.degraded=true);}isoNow(){return (this.options.now?.()??new Date).toISOString()}};async function Zo(t,e=process.env){let r=await ne(t,e);if(r.work_state_runtime_id)return r.work_state_runtime_id;let n=`runtime:${randomUUID()}`;return await ie(t,{work_state_runtime_id:n},e),n}function iv(t){return t.length>0&&!t.startsWith("/")&&!t.startsWith("../")&&!t.includes("/../")&&!t.startsWith(".git/")&&!/[\x00-\x1F]/.test(t)}F();var xt=new Map;async function mp(t=process.env){let{session:e,supabase:r}=await C(t),{data:n,error:i}=await r.from("user_workspace_paths").select("workspace_id, local_root_path, watcher_enabled").eq("user_id",e.user.id).eq("watcher_enabled",true);if(i)throw i;let s=await Zo(e.user.id,t);for(let o of n??[]){if(!o.workspace_id||!o.local_root_path||xt.has(o.workspace_id))continue;let a=new sn({workspaceId:o.workspace_id,workspaceRoot:o.local_root_path,userId:e.user.id,runtimeId:s,supabase:r});xt.set(o.workspace_id,{tracker:a,workspaceRoot:o.local_root_path}),a.start();}}async function Qo(t,e,r=process.env){if(xt.has(t))return;let{session:n,supabase:i}=await C(r),s=await Zo(n.user.id,r),o=new sn({workspaceId:t,workspaceRoot:e,userId:n.user.id,runtimeId:s,supabase:i});xt.set(t,{tracker:o,workspaceRoot:e}),o.start();}async function ea(t){return xt.get(t)?.tracker.reconcile()??null}function _p(){for(let t of xt.values())t.tracker.stop();xt.clear();}var ta="1.0",$i=37913,on="127.0.0.1",mv=60,_v=createRequire(import.meta.url),wv=_v("../package.json"),he=promisify(execFile),cn="io.pathrule.cli-daemon",Ai="pathrule-daemon.service",yv=60;async function un(t){let e=await Le(t);if(e.running)return e;let r=process.argv[1];if(!r)throw new Error("daemon_entrypoint_missing");spawn(process.execPath,[r,"daemon","run"],{detached:true,stdio:"ignore",env:{...process.env,...t}}).unref();let i=Date.now()+3e3;for(;Date.now()<i;){let s=await Le(t);if(s.running)return s;await Wv(100);}throw new Error("daemon_start_timeout")}async function dn(t){let e=await Le(t);if(e.state?.pid&&e.state.pid!==process.pid)try{process.kill(e.state.pid,"SIGTERM");}catch{}return await unlink(A(t).daemonFile).catch(()=>{}),Le(t)}async function Ni(t=process.env){let e=xp(t);if(!e.supported)return e;if(e.method==="task-scheduler"){let r=await Ev();return {...e,enabled:r}}return {...e,enabled:e.path?await oa(e.path):false}}async function Xe(t,e){let r=xp(t);if(!r.supported)return r;if(e){let n=kv(t);if(r.method==="launchd"){if(!r.path)throw new Error("daemon_autostart_path_missing");return await bv(r.path,n,t),t.PATHRULE_SKIP_AUTOSTART_ACTIVATE!=="1"&&await Sv(r.path),{...r,enabled:true}}if(r.method==="systemd"){if(!r.path)throw new Error("daemon_autostart_path_missing");return await vv(r.path,n,t),t.PATHRULE_SKIP_AUTOSTART_ACTIVATE!=="1"&&(await he("systemctl",["--user","daemon-reload"]),await he("systemctl",["--user","enable","--now",Ai])),{...r,enabled:true}}return await Rv(n,t),{...r,enabled:true}}return r.method==="launchd"?(t.PATHRULE_SKIP_AUTOSTART_ACTIVATE!=="1"&&r.path&&await Cv(r.path),r.path&&await unlink(r.path).catch(()=>{}),{...r,enabled:false}):r.method==="systemd"?(t.PATHRULE_SKIP_AUTOSTART_ACTIVATE!=="1"&&(await he("systemctl",["--user","disable","--now",Ai]).catch(()=>{}),await he("systemctl",["--user","daemon-reload"]).catch(()=>{})),r.path&&await unlink(r.path).catch(()=>{}),{...r,enabled:false}):(await xv(),{...r,enabled:false})}async function Le(t){let e=A(t).daemonFile,r;try{r=JSON.parse(await readFile(e,"utf8"));}catch(i){return {running:false,state:null,state_path:e,reason:i.code==="ENOENT"?"missing":"unreadable"}}let n=Uv(r.pid);return {running:n,state:r,state_path:e,reason:n?void 0:"stale"}}function xp(t){let e=t.PATHRULE_TEST_PLATFORM??process.platform,r=t.PATHRULE_AUTOSTART_DIR;return e==="darwin"?{supported:true,enabled:false,method:"launchd",path:r?join(r,`${cn}.plist`):join(homedir(),"Library","LaunchAgents",`${cn}.plist`)}:e==="linux"?{supported:true,enabled:false,method:"systemd",path:r?join(r,Ai):join(homedir(),".config","systemd","user",Ai)}:e==="win32"?{supported:false,enabled:false,method:"task-scheduler",path:null,reason:"Windows daemon autostart requires installer support."}:{supported:false,enabled:false,method:"unsupported",path:null,reason:`Unsupported platform: ${e}`}}function kv(t){let e=t.PATHRULE_CLI_ENTRYPOINT?.trim()||process.argv[1];if(!e)throw new Error("daemon_entrypoint_missing");return {command:process.execPath,args:[e,"daemon","run"]}}function sa(t){let e={PATHRULE_DAEMON_PORT:t.PATHRULE_DAEMON_PORT?.trim()||String($i)};for(let r of ["PATH","PATHRULE_HOME","PATHRULE_WEB_URL"]){let n=t[r];n&&n.trim()!==""&&(e[r]=n);}return e}async function bv(t,e,r){let n=`<?xml version="1.0" encoding="UTF-8"?>
|
|
142
|
+
`:"")+Jk,"utf8");}F();F();Ee();var Vk=new Set(["write_memory","write_rule","write_skill","sync_agents","materialize_skills"]);async function ae(t,e){let{supabase:r}=await C(e),n=await j(e),i=(e.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"");if(!n)return ir(t,"org_required",{web_url:`${i}/settings`,suggested_command_after_resolution:"pathrule org use <slug-or-id>"});let{data:s,error:o}=await r.from("organizations").select("id, slug, plan, seat_count, subscription_status").eq("id",n.id).single();if(o)throw o;let a=String(s.plan??n.plan),l=n.role,c=`${i}/org/${n.slug}/billing`;if(t==="create_workspace"){if(!Zk(l))return ir(t,"permission_denied",{role:l,plan:a,organization_id:n.id,web_url:`${i}/org/${n.slug}/settings/members`});let p=await zo(r,"workspaces","organization_id",n.id,{archived_at:null}),h=Jo(a,"workspaces");return Yd(p,h)?ir(t,"capacity_full",{role:l,plan:a,organization_id:n.id,usage:{dimension:"workspaces",used:p,limit:h},web_url:c,suggested_command_after_resolution:"pathrule init"}):Xd(t,{role:l,plan:a,organization_id:n.id})}let u=await M(e);if(!u)return ir(t,"workspace_required",{role:l,plan:a,organization_id:n.id,web_url:`${i}/org/${n.slug}`,suggested_command_after_resolution:"pathrule workspace use <name-or-id>"});if(Vk.has(t)&&!Qk(l))return ir(t,"permission_denied",{role:l,plan:a,organization_id:n.id,workspace_id:u.id,web_url:`${i}/org/${n.slug}/settings/members`});let d=await Xk(t,a,u.id,r);return d&&Yd(d.used,d.limit)?ir(t,"capacity_full",{role:l,plan:a,organization_id:n.id,workspace_id:u.id,usage:d,web_url:c,suggested_command_after_resolution:"pathrule status"}):Xd(t,{role:l,plan:a,organization_id:n.id,workspace_id:u.id,usage:d})}function Ko(t){return ["create_workspace","write_memory","write_rule","write_skill","sync_agents","materialize_skills"].includes(t)}function sr(t){return t.allowed?{summary:`${t.action} is allowed.`,details:[],url:null,suggested_command_after_resolution:null}:t.blocking_reason==="capacity_full"&&t.usage?{summary:`${Gk(t.usage.dimension)} limit reached on the ${t.plan??"current"} plan (${t.usage.used} / ${Yk(t.usage.limit)}).`,details:["Open Pathrule Web to upgrade or clean up usage."],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution}:t.blocking_reason==="permission_denied"?{summary:`Your current role (${t.role??"unknown"}) cannot run ${t.action}.`,details:["Ask an organization admin to update your role or run the action from an admin account."],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution}:t.blocking_reason==="workspace_required"?{summary:"No current workspace is selected for this folder.",details:["Run setup or choose a workspace before retrying."],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution??"pathrule setup --json"}:t.blocking_reason==="org_required"?{summary:"No organization is selected.",details:["Choose an organization before retrying."],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution??"pathrule org use <slug-or-id>"}:{summary:`${t.action} blocked: ${t.blocking_reason??"preflight_blocked"}.`,details:[],url:t.web_url,suggested_command_after_resolution:t.suggested_command_after_resolution}}function Gk(t){return t.charAt(0).toLocaleUpperCase("en-US")+t.slice(1)}function Yk(t){return t===-1?"unlimited":String(t)}async function Xk(t,e,r,n){return t==="write_memory"?{dimension:"memories",used:await zo(n,"memories","workspace_id",r),limit:Jo(e,"memories")}:t==="write_rule"?{dimension:"rules",used:await zo(n,"rules","workspace_id",r),limit:Jo(e,"rules")}:null}async function zo(t,e,r,n,i={}){let s=t.from(e).select("id",{count:"exact",head:true}).eq(r,n);for(let l of Object.keys(i))s=s.is(l,null);let{count:o,error:a}=await s;if(a)throw a;return o??0}function Zk(t){return t==="owner"||t==="admin"||t==="member"}function Qk(t){return t==="owner"||t==="admin"||t==="member"}function Jo(t,e){return Fe[t]?.[e]??Fe.free[e]}function Yd(t,e){return e!==-1&&t>=e}function Xd(t,e={}){return {action:t,allowed:true,blocking_reason:null,role:null,plan:null,organization_id:null,workspace_id:null,usage:null,web_url:null,suggested_command_after_resolution:null,...e}}function ir(t,e,r={}){return {action:t,allowed:false,blocking_reason:e,role:null,plan:null,organization_id:null,workspace_id:null,usage:null,web_url:null,suggested_command_after_resolution:null,...r}}var ob=createRequire(import.meta.url),ab=ob("../package.json"),Qd="cli",ep=ab.version;async function De(t,e,r={}){let{session:n,supabase:i}=await C(t),s=await M(t);if(!s)throw new Error("workspace_required");if(!s.local_root_path)throw new Error("workspace_not_attached");if(s.local_root_path!==e)throw new Error("workspace_cwd_mismatch");is(join(A(t).home,"bin","pathrule-hook.js"));let o=await ae(r.skillsOnly?"materialize_skills":"sync_agents",t);if(!o.allowed)return {ok:false,workspace_id:s.id,workspace_root:s.local_root_path,preflight:o,error:o.blocking_reason??"preflight_blocked"};if(r.skillsOnly){let u=await cb({supabase:i,userId:n.user.id,workspaceId:s.id,workspaceRoot:s.local_root_path});return {ok:u.errors.length===0,workspace_id:s.id,workspace_root:s.local_root_path,preflight:o,skills:{ok:u.errors.length===0,enabled:u.enabled,written:u.written,skipped:u.skipped,removed:u.removed,errors:u.errors},error:u.errors.length===0?void 0:"skill_sync_failed"}}let a=await Hd({supabase:i,userId:n.user.id,workspaceId:s.id,workspaceRoot:s.local_root_path,runtimeOwner:Qd,runtimeVersion:ep}),l=await lb({supabase:i,userId:n.user.id,workspaceId:s.id,workspaceRoot:s.local_root_path}),c=await Si({supabase:i,workspaceId:s.id,workspaceRoot:s.local_root_path,env:t});return {ok:a.ok&&l.errors.length===0&&c.ok,workspace_id:s.id,workspace_root:s.local_root_path,preflight:o,companion:{ok:a.ok,enabled:a.enabled,written:a.disk.written,skipped:a.disk.skipped,removed:a.disk.removed,errors:a.disk.errors,error:a.error},claude:{ok:l.errors.length===0,written:l.written,skipped:l.skipped,backed_up:l.backedUp,errors:l.errors,snapshot_changed:l.snapshotChanged},hook_index:c,error:a.error??(l.errors.length>0?"claude_sync_failed":c.ok?void 0:"hook_index_sync_failed")}}async function nn(t,e,r,n={}){let{session:i}=await C(t),s=await ne(i.user.id,t);await ai(i.user.id,{...s,current_workspace_id:e,schema_version:1},t);try{return await De(t,r,n)}finally{await ai(i.user.id,s,t);}}async function lb(t){let e={written:0,skipped:0,backedUp:[],errors:[],snapshotChanged:false},r=new Set,{body:n,snapshotChanged:i}=await nl({supabase:t.supabase,workspaceId:t.workspaceId,userId:t.userId});e.snapshotChanged=i,await Zd(e,t.workspaceRoot,"CLAUDE.md",n)&&r.add("CLAUDE.md"),await Zd(e,t.workspaceRoot,".claude/rules/pathrule-protocol.md",hl())&&r.add(".claude/rules/pathrule-protocol.md");let s=".claude/settings.json";try{let o=join(t.workspaceRoot,s),a=await rp(o),{body:l,changed:c}=Sn(a);c?(await tp(o,l),e.written+=1):e.skipped+=1,r.add(s);}catch(o){e.errors.push({path:s,message:o instanceof Error?o.message:String(o)});}try{await mi({workspaceRoot:t.workspaceRoot,paths:Array.from(r),owner:Qd,ownerVersion:ep});}catch(o){e.errors.push({path:".pathrule/managed-files.json",message:o instanceof Error?o.message:String(o)});}return e}async function Zd(t,e,r,n){let i=join(e,r);try{let s=await rp(i),o=await Ci({workspaceRoot:e,relativePath:r,renderedBody:n,existingBody:s});return o.backupPath&&t.backedUp.push(o.backupPath),o.finalBody===null?(t.skipped+=1,!0):(await tp(i,o.finalBody),t.written+=1,!0)}catch(s){return t.errors.push({path:r,message:s instanceof Error?s.message:String(s)}),false}}async function tp(t,e){await mkdir(dirname(t),{recursive:true});let r=`${t}.tmp`;await writeFile(r,e,"utf8"),await rename(r,t);}async function rp(t){try{return await readFile(t,"utf8")}catch(e){if(e.code==="ENOENT")return null;throw e}}async function cb(t){let[e,r]=await Promise.all([ub(t.supabase,t.userId,t.workspaceId,t.workspaceRoot),db(t.supabase,t.workspaceId)]),n=await Vd({workspaceRoot:t.workspaceRoot,activeTargets:e,skills:r});return {enabled:e,written:n.written,skipped:n.skipped,removed:n.removed,errors:n.errors}}async function ub(t,e,r,n){let[{data:i},s]=await Promise.all([t.from("user_workspace_paths").select("selected_ai_clients").eq("workspace_id",r).eq("user_id",e).maybeSingle(),He(n)]),o=i?.selected_ai_clients??null;return Tn({selected:o,detected:s,fallback:Rn})}async function db(t,e){let{data:r,error:n}=await t.from("skills").select("id, name, description, content, source, github_url, content_fetched_at, updated_at, skill_files(path, content, sha256)").eq("workspace_id",e);if(n)throw new Error(`skill_catalogue_read_failed: ${n.message}`);return (r??[]).map(i=>({id:i.id,name:i.name,description:i.description,content:i.content,source:i.source,githubUrl:i.github_url,contentFetchedAt:i.content_fetched_at,updatedAt:i.updated_at,files:(i.skill_files??[]).map(s=>({path:s.path,content:s.content,sha256:s.sha256}))}))}async function sn(t,e){let r=await je(t,e);try{let n=await De(t,e),i=await je(t,e);return {ok:n.ok&&i.ok,doctor_before:r,sync:n,doctor_after:i,error:n.ok&&i.ok?void 0:n.error??"repair_incomplete"}}catch(n){return {ok:false,doctor_before:r,error:n instanceof Error?n.message:String(n)}}}function ip(t){let e=np(t.doctor_before.checks),r=t.doctor_after??t.doctor_before,n=np(r.checks),i=t.sync?.preflight,s=r.mcp.filter(p=>!p.installed),o=_b(e,n),a=wb(e,n),l=yb(r.mcp),c=kb(t),u=bb(t),d=vb(i);return {ok:t.ok,headline:t.ok?"Local runtime repaired":"Repair incomplete",next_command:Sb(t,n,s.length),sections:[o,a,l,c,u,d]}}async function Go(t,e={}){let{session:r,supabase:n}=await C(t),{data:i,error:s}=await n.from("user_security_state").select("security_epoch").eq("user_id",r.user.id).maybeSingle();if(s)throw s;let o=typeof i?.security_epoch=="number"?i.security_epoch:0,a=rt(r.user.id,o,t),l=[];for(let c=0;c<o;c+=1){let u=join(a.userCacheDir,`epoch-${c}`),d=await mb(u);if(d===0)continue;let p=e.dryRun!==false?false:await gb(u);l.push({path:u,epoch:c,removed:p,bytes:d});}return {ok:true,dry_run:e.dryRun!==false,current_epoch:o,candidates:l,reclaimed_bytes:l.filter(c=>c.removed).reduce((c,u)=>c+u.bytes,0)}}async function gb(t){return await rm$1(t,{recursive:true,force:true}),true}async function mb(t){try{let e=await stat(t);return e.isFile()?e.size:e.isDirectory()?1:0}catch{return 0}}function np(t){return new Map(t.map(e=>[e.name,e]))}function _b(t,e){let r=t.get("auth"),n=e.get("auth"),i=t.get("organization"),s=e.get("organization"),o=[xi(r,n,{pass:(a,l)=>l?`Signed in again as ${a??"the current account"}.`:`Signed in as ${a??"the current account"}.`,warn:a=>`Authentication still needs attention${a?`: ${a}`:""}.`,fail:a=>`Authentication is still blocked${a?`: ${a}`:""}.`}),xi(i,s,{pass:(a,l)=>l?`Organization context restored: ${a??"selected"}.`:`Organization context: ${a??"selected"}.`,warn:a=>`Organization selection is still missing${a&&a!=="no organization selected"?`: ${a}`:""}.`,fail:a=>`Organization lookup failed${a?`: ${a}`:""}.`})];return {title:"Account",status:sp(n?.status,s?.status),lines:o}}function wb(t,e){let r=t.get("workspace"),n=e.get("workspace"),i=t.get("cwd_attach"),s=e.get("cwd_attach"),o=[xi(r,n,{pass:(a,l)=>l?`Workspace selection recovered: ${a??"current workspace"}.`:`Workspace selection: ${a??"current workspace"}.`,warn:a=>`Workspace selection is still incomplete${a&&a!=="no workspace selected"?`: ${a}`:""}.`,fail:a=>`Workspace lookup failed${a?`: ${a}`:""}.`}),xi(i,s,{pass:(a,l)=>l?"Current folder is attached again.":"Current folder is attached.",warn:a=>a==="workspace not attached"?"Current folder is still not attached.":`Current folder still points to ${a??"another workspace root"}.`,fail:a=>`Current folder attachment check failed${a?`: ${a}`:""}.`})];return {title:"Workspace",status:sp(n?.status,s?.status),lines:o}}function yb(t){let e=t.filter(s=>s.installed).length,r=t.filter(s=>!s.installed).map(s=>s.client),n=t.filter(s=>s.error).map(s=>`${s.client}: ${s.error}`),i=[`MCP configs ready for ${e}/${t.length} supported clients.`,r.length>0?`Still missing: ${r.join(", ")}.`:"All supported MCP client configs are present."];return n.length>0&&i.push(`Agent config read errors: ${n.join("; ")}.`),{title:"Agents",status:n.length>0?"fail":r.length>0?"warn":"pass",lines:i}}function kb(t){let e=t.sync?.hook_index;return t.sync?e?{title:"Hooks",status:e.ok?"pass":"fail",lines:[e.ok?`Hook index refreshed${e.schema_version?` (schema ${e.schema_version})`:""}.`:`Hook index refresh failed: ${e.error??"unknown error"}.`,e.refreshed_episodes?"Hook work episodes were refreshed before rebuilding the index.":"Hook work episodes were left unchanged."]}:{title:"Hooks",status:"warn",lines:["Repair did not produce a hook index update."]}:{title:"Hooks",status:"warn",lines:["Repair stopped before hook files could be refreshed."]}}function bb(t){if(!t.sync)return {title:"Files",status:"warn",lines:["Repair stopped before local files could be rewritten."]};let e=[],r="pass";return t.sync.companion&&(e.push(`Companion files: ${t.sync.companion.written} written, ${t.sync.companion.skipped} unchanged, ${t.sync.companion.removed} removed.`),(t.sync.companion.errors.length>0||!t.sync.companion.ok)&&(r="fail",e.push(`Companion errors: ${t.sync.companion.errors.map(n=>n.message).join("; ")||t.sync.companion.error||"unknown error"}.`))),t.sync.claude&&(e.push(`Claude files: ${t.sync.claude.written} written, ${t.sync.claude.skipped} unchanged, ${t.sync.claude.backed_up.length} backed up.`),t.sync.claude.errors.length>0&&(r="fail",e.push(`Claude sync errors: ${t.sync.claude.errors.map(n=>n.message).join("; ")}.`))),t.sync.skills&&(e.push(`Skills: ${t.sync.skills.written} written, ${t.sync.skills.skipped} unchanged, ${t.sync.skills.removed} removed.`),t.sync.skills.errors.length>0&&(r="fail",e.push(`Skill materialization errors: ${t.sync.skills.errors.map(n=>n.message).join("; ")}.`))),e.length===0&&e.push("No local file rewrites were needed."),{title:"Files",status:r,lines:e}}function vb(t){return t?t.allowed?{title:"Capacity",status:"pass",lines:["No plan limit blocked this repair."]}:t.blocking_reason==="capacity_full"&&t.usage?{title:"Capacity",status:"fail",lines:[`${Cb(t.usage.dimension)} limit reached (${t.usage.used} / ${Eb(t.usage.limit)}).`,"Open billing or clean up usage before retrying the repair."]}:{title:"Capacity",status:"warn",lines:["Capacity is not the blocking issue for this repair."]}:{title:"Capacity",status:"warn",lines:["Capacity checks did not run because repair stopped early."]}}function xi(t,e,r){let n=e??t;if(!n)return "No status available.";let i=t!=null&&t.status!=="pass"&&n.status==="pass";return n.status==="pass"?r.pass(n.detail,i):n.status==="warn"?r.warn(n.detail,i):r.fail(n.detail,i)}function sp(...t){return t.includes("fail")?"fail":t.includes("warn")?"warn":"pass"}function Sb(t,e,r){if(e.get("auth")?.status!=="pass")return "pathrule login";if(e.get("organization")?.status!=="pass")return "pathrule org use <slug-or-id>";if(e.get("workspace")?.status!=="pass")return "pathrule workspace use <name-or-id>";if(e.get("cwd_attach")?.status!=="pass")return "pathrule attach <workspace>";let a=t.sync?.preflight;if(a&&!a.allowed&&a.suggested_command_after_resolution)return a.suggested_command_after_resolution;if(r>0)return "pathrule install";let l=!t.sync?.companion?.ok||!!t.sync?.companion?.errors.length||!!t.sync?.claude?.errors.length||!!t.sync?.skills?.errors.length||t.sync?.hook_index?.ok===false;return !t.ok||l?"pathrule sync":"pathrule doctor"}function Cb(t){return t.charAt(0).toLocaleUpperCase("en-US")+t.slice(1)}function Eb(t){return t===-1?"unlimited":String(t)}F();qr();var Nb={all:"all",claude:"claude-code","claude-code":"claude-code",cursor:"cursor",codex:"codex",windsurf:"windsurf"},jb=["claude-code","cursor","codex","windsurf"];function ap(t){let e=Nb[(t??"all").toLowerCase()];if(!e)throw new Error("invalid_install_target");return e==="all"?jb:[e]}async function Ye(t,e){let r=ap(t),n=Db(e);return Promise.all(r.map(async i=>{let s=vt(i),o=s.homeConfigPath(homedir(),process.platform);try{let a=await lp(o),l=s.inject(a,n);return await cp(o,l.body),{client:i,ok:!0,status:"installed",config_path:o,was_new:l.wasNew}}catch(a){return {client:i,ok:false,status:"error",config_path:o,error:a instanceof Error?a.message:String(a)}}}))}async function Yo(t){return Promise.all(ap(t).map(async e=>{let r=vt(e),n=r.homeConfigPath(homedir(),process.platform);try{let i=await lp(n),s=r.remove(i);return s.wasPresent?(s.body===null?await rm$1(n,{force:!0}):await cp(n,s.body),{client:e,ok:!0,status:"removed",config_path:n}):{client:e,ok:!0,status:"not_present",config_path:n}}catch(i){return {client:e,ok:false,status:"error",config_path:n,error:i instanceof Error?i.message:String(i)}}}))}function Db(t){let{supabaseUrl:e,supabaseAnonKey:r}=pe(t);return {type:"stdio",command:Mb(),args:[fileURLToPath(new URL("../../mcp-server/dist/index.js",import.meta.url))],env:{SUPABASE_URL:e,SUPABASE_ANON_KEY:r}}}function Mb(){try{return execFileSync("which",["node"],{encoding:"utf8"}).trim()||process.execPath}catch{return process.execPath}}async function lp(t){try{return await readFile(t,"utf8")}catch(e){if(e.code==="ENOENT")return null;throw e}}async function cp(t,e){await mkdir(dirname(t),{recursive:true});let r=`${t}.tmp`;await writeFile(r,e,"utf8"),await rename(r,t);}async function Rt(t,e,r,n){let{session:i,supabase:s}=await C(t);if(i.user.id!==e)throw new Error("session_user_mismatch");let[{data:o},a]=await Promise.all([s.from("user_workspace_paths").select("selected_ai_clients").eq("user_id",e).eq("workspace_id",r).maybeSingle(),n?He(n):Promise.resolve([])]),l=new Set(o?.selected_ai_clients??[]),c=new Set(a),u=Object.keys(U);return Promise.all(u.map(async d=>{let p=await qb(d);return {client:d,active:l.has(d)||c.has(d),selected:l.has(d),markers:c.has(d)?["workspace_marker_detected"]:[],machineInstalled:p.installed,machineConfigPath:p.configPath,machineConfigExists:p.configExists}}))}async function hp(t,e,r,n,i,s,o="restore-backup"){let a=zb(i),{session:l,supabase:c}=await C(t);if(l.user.id!==e)throw new Error("session_user_mismatch");let{data:u,error:d}=await c.from("user_workspace_paths").select("selected_ai_clients").eq("user_id",e).eq("workspace_id",r).eq("local_root_path",n).maybeSingle();if(d)throw new Error(`workspace_client_selection_read_failed: ${d.message}`);if(!u)throw new Error("workspace_root_not_attached");let p=[],h=new Set((u.selected_ai_clients??[]).filter(fp)),f=Array.from(h);s?h.add(a):h.delete(a);let m=Array.from(h);if(!Jb(f,m)){let{error:w}=await c.from("user_workspace_paths").update({selected_ai_clients:m}).eq("user_id",e).eq("workspace_id",r).eq("local_root_path",n);if(w)throw new Error(`workspace_client_selection_update_failed: ${w.message}`)}if(s){let w=await Ye(a,t);for(let y of w)y.ok||p.push(`${y.client}: ${y.error??y.status}`);}else await dp(n,a);let _=await nn(t,r,n);return _.ok||p.push(_.error??"workspace_sync_failed"),s||await dp(n,a),{ok:true,statuses:await Rt(t,e,r,n),warnings:p}}async function qb(t){let e=vt(t),r=e.homeConfigPath(homedir(),process.platform);try{let n=await readFile(r,"utf8");return {configPath:r,configExists:!0,installed:e.read(n)!==null}}catch(n){return n.code!=="ENOENT"?{configPath:r,configExists:false,installed:false}:{configPath:r,configExists:false,installed:false}}}function zb(t){if(fp(t))return t;throw new Error("invalid_agent_target")}function fp(t){return hs(t)!==null}function Jb(t,e){if(t.length!==e.length)return false;let r=new Set(t);return e.every(n=>r.has(n))}async function dp(t,e,r){let n=U[e]?.skillsDir;if(!n)return;let i=join(t,n);await rm$1(i,{recursive:true,force:true}),await Kb(dirname(i),t);}async function Kb(t,e){let r=resolve(e),n=resolve(t);for(;n!==r&&n.startsWith(`${r}${sep}`);){try{await rmdir(n);}catch{return}n=dirname(n);}}Ke();var Yb=promisify(execFile),Xb=2e3;function Xo(t){if(t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t))return null;let e=t.replace(/\\/g,"/").replace(/\/+/g,"/");return e.length===0||e==="."||e.startsWith("../")||e.includes("/../")||e.startsWith(".git/")||/[\x00-\x1F]/.test(e)?null:e}function Zb(t){let r=(Buffer.isBuffer(t)?t.toString("utf8"):t).split("\0").filter(i=>i.length>0),n=[];for(let i=0;i<r.length;i+=1){let s=r[i];if(!s||s.length<4)continue;let o=s.slice(0,2),a=s.slice(3),l=Qb(o);if(o.includes("R")||o.includes("C")){let u=Xo(a);u&&n.push({relativePath:u,gitStatus:"renamed"});let d=Xo(r[i+1]??"");d&&n.push({relativePath:d,gitStatus:"renamed"}),i+=1;continue}let c=Xo(a);c&&n.push({relativePath:c,gitStatus:l});}return ev(n)}async function gp(t,e={}){try{let{stdout:r}=await Yb("git",["status","--porcelain=v1","-z"],{cwd:t,encoding:"buffer",maxBuffer:5242880,timeout:e.timeoutMs??Xb});return {entries:Zb(r),degraded:!1}}catch{return {entries:[],degraded:true}}}function Qb(t){return t==="??"?"untracked":t.includes("A")?"added":t.includes("D")?"deleted":t.includes("R")||t.includes("C")?"renamed":t.includes("M")||t.includes("T")||t.includes("U")?"modified":"unknown"}function ev(t){let e=new Map;for(let r of t)e.set(r.relativePath,r);return Array.from(e.values()).sort((r,n)=>r.relativePath.localeCompare(n.relativePath))}var rv=800,nv=6e4,Pi=500,on=class{constructor(e){this.options=e;}options;dirty=new Map;pendingTimer=null;intervalTimer=null;stopped=false;degraded=false;lastScanAt=null;start(){this.intervalTimer||(this.reconcile(),this.intervalTimer=setInterval(()=>{this.reconcile();},this.options.scanIntervalMs??nv),this.intervalTimer.unref?.());}stop(){this.stopped=true,this.pendingTimer&&clearTimeout(this.pendingTimer),this.intervalTimer&&clearInterval(this.intervalTimer),this.pendingTimer=null,this.intervalTimer=null;}markActivePath(e){if(this.stopped||!iv(e))return;let r=this.isoNow();this.publishRows([{relative_path:e,is_active:true,is_dirty:this.dirty.has(e),git_status:this.dirty.get(e)?.gitStatus??"unknown",last_heartbeat_at:r,last_git_scan_at:r}],[]),this.scheduleReconcile();}scheduleReconcile(){this.stopped||(this.pendingTimer&&clearTimeout(this.pendingTimer),this.pendingTimer=setTimeout(()=>{this.pendingTimer=null,this.reconcile();},this.options.debounceMs??rv),this.pendingTimer.unref?.());}async reconcile(){if(this.stopped)return this.status();let e=this.isoNow(),r=await gp(this.options.workspaceRoot);if(this.degraded=r.degraded,r.degraded)return this.status();let n=new Map;for(let o of r.entries){let a=this.dirty.get(o.relativePath);n.set(o.relativePath,{gitStatus:o.gitStatus,firstSeenAt:a?.firstSeenAt??e});}let i=Array.from(this.dirty.keys()).filter(o=>!n.has(o));this.dirty.clear();for(let[o,a]of n)this.dirty.set(o,a);this.lastScanAt=e;let s=Array.from(n.entries()).map(([o,a])=>({relative_path:o,is_active:false,is_dirty:true,git_status:a.gitStatus,last_local_write_at:a.firstSeenAt,last_git_scan_at:e}));return await this.publishChunked(s,i),this.status()}status(){return {healthy:!this.degraded,degraded:this.degraded,lastScanAt:this.lastScanAt,dirtyPathCount:this.dirty.size}}async publishChunked(e,r){for(let n=0;n<e.length;n+=Pi)await this.publishRows(e.slice(n,n+Pi),[]);for(let n=0;n<r.length;n+=Pi)await this.publishRows([],r.slice(n,n+Pi));}async publishRows(e,r){if(e.length===0&&r.length===0)return;let{error:n}=await this.options.supabase.rpc("pathrule_upsert_file_work_state",{p_workspace_id:this.options.workspaceId,p_runtime_id:this.options.runtimeId,p_rows:e,p_clear_paths:r});n&&(this.degraded=true);}isoNow(){return (this.options.now?.()??new Date).toISOString()}};async function Zo(t,e=process.env){let r=await ne(t,e);if(r.work_state_runtime_id)return r.work_state_runtime_id;let n=`runtime:${randomUUID()}`;return await ie(t,{work_state_runtime_id:n},e),n}function iv(t){return t.length>0&&!t.startsWith("/")&&!t.startsWith("../")&&!t.includes("/../")&&!t.startsWith(".git/")&&!/[\x00-\x1F]/.test(t)}F();var xt=new Map;async function mp(t=process.env){let{session:e,supabase:r}=await C(t),{data:n,error:i}=await r.from("user_workspace_paths").select("workspace_id, local_root_path, watcher_enabled").eq("user_id",e.user.id).eq("watcher_enabled",true);if(i)throw i;let s=await Zo(e.user.id,t);for(let o of n??[]){if(!o.workspace_id||!o.local_root_path||xt.has(o.workspace_id))continue;let a=new on({workspaceId:o.workspace_id,workspaceRoot:o.local_root_path,userId:e.user.id,runtimeId:s,supabase:r});xt.set(o.workspace_id,{tracker:a,workspaceRoot:o.local_root_path}),a.start();}}async function Qo(t,e,r=process.env){if(xt.has(t))return;let{session:n,supabase:i}=await C(r),s=await Zo(n.user.id,r),o=new on({workspaceId:t,workspaceRoot:e,userId:n.user.id,runtimeId:s,supabase:i});xt.set(t,{tracker:o,workspaceRoot:e}),o.start();}async function ea(t){return xt.get(t)?.tracker.reconcile()??null}function _p(){for(let t of xt.values())t.tracker.stop();xt.clear();}var ta="1.0",$i=37913,an="127.0.0.1",mv=60,_v=createRequire(import.meta.url),wv=_v("../package.json"),fe=promisify(execFile),un="io.pathrule.cli-daemon",Ai="pathrule-daemon.service",yv=60;async function dn(t){let e=await Le(t);if(e.running)return e;let r=process.argv[1];if(!r)throw new Error("daemon_entrypoint_missing");spawn(process.execPath,[r,"daemon","run"],{detached:true,stdio:"ignore",env:{...process.env,...t}}).unref();let i=Date.now()+3e3;for(;Date.now()<i;){let s=await Le(t);if(s.running)return s;await Wv(100);}throw new Error("daemon_start_timeout")}async function pn(t){let e=await Le(t);if(e.state?.pid&&e.state.pid!==process.pid)try{process.kill(e.state.pid,"SIGTERM");}catch{}return await unlink(A(t).daemonFile).catch(()=>{}),Le(t)}async function Ni(t=process.env){let e=xp(t);if(!e.supported)return e;if(e.method==="task-scheduler"){let r=await Ev();return {...e,enabled:r}}return {...e,enabled:e.path?await oa(e.path):false}}async function Xe(t,e){let r=xp(t);if(!r.supported)return r;if(e){let n=kv(t);if(r.method==="launchd"){if(!r.path)throw new Error("daemon_autostart_path_missing");return await bv(r.path,n,t),t.PATHRULE_SKIP_AUTOSTART_ACTIVATE!=="1"&&await Sv(r.path),{...r,enabled:true}}if(r.method==="systemd"){if(!r.path)throw new Error("daemon_autostart_path_missing");return await vv(r.path,n,t),t.PATHRULE_SKIP_AUTOSTART_ACTIVATE!=="1"&&(await fe("systemctl",["--user","daemon-reload"]),await fe("systemctl",["--user","enable","--now",Ai])),{...r,enabled:true}}return await Rv(n,t),{...r,enabled:true}}return r.method==="launchd"?(t.PATHRULE_SKIP_AUTOSTART_ACTIVATE!=="1"&&r.path&&await Cv(r.path),r.path&&await unlink(r.path).catch(()=>{}),{...r,enabled:false}):r.method==="systemd"?(t.PATHRULE_SKIP_AUTOSTART_ACTIVATE!=="1"&&(await fe("systemctl",["--user","disable","--now",Ai]).catch(()=>{}),await fe("systemctl",["--user","daemon-reload"]).catch(()=>{})),r.path&&await unlink(r.path).catch(()=>{}),{...r,enabled:false}):(await xv(),{...r,enabled:false})}async function Le(t){let e=A(t).daemonFile,r;try{r=JSON.parse(await readFile(e,"utf8"));}catch(i){return {running:false,state:null,state_path:e,reason:i.code==="ENOENT"?"missing":"unreadable"}}let n=Uv(r.pid);return {running:n,state:r,state_path:e,reason:n?void 0:"stale"}}function xp(t){let e=t.PATHRULE_TEST_PLATFORM??process.platform,r=t.PATHRULE_AUTOSTART_DIR;return e==="darwin"?{supported:true,enabled:false,method:"launchd",path:r?join(r,`${un}.plist`):join(homedir(),"Library","LaunchAgents",`${un}.plist`)}:e==="linux"?{supported:true,enabled:false,method:"systemd",path:r?join(r,Ai):join(homedir(),".config","systemd","user",Ai)}:e==="win32"?{supported:false,enabled:false,method:"task-scheduler",path:null,reason:"Windows daemon autostart requires installer support."}:{supported:false,enabled:false,method:"unsupported",path:null,reason:`Unsupported platform: ${e}`}}function kv(t){let e=t.PATHRULE_CLI_ENTRYPOINT?.trim()||process.argv[1];if(!e)throw new Error("daemon_entrypoint_missing");return {command:process.execPath,args:[e,"daemon","run"]}}function sa(t){let e={PATHRULE_DAEMON_PORT:t.PATHRULE_DAEMON_PORT?.trim()||String($i)};for(let r of ["PATH","PATHRULE_HOME","PATHRULE_WEB_URL"]){let n=t[r];n&&n.trim()!==""&&(e[r]=n);}return e}async function bv(t,e,r){let n=`<?xml version="1.0" encoding="UTF-8"?>
|
|
143
143
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
144
144
|
<plist version="1.0">
|
|
145
145
|
<dict>
|
|
146
146
|
<key>Label</key>
|
|
147
|
-
<string>${or(
|
|
147
|
+
<string>${or(un)}</string>
|
|
148
148
|
<key>ProgramArguments</key>
|
|
149
149
|
<array>
|
|
150
150
|
${[e.command,...e.args].map(i=>` <string>${or(i)}</string>`).join(`
|
|
@@ -179,12 +179,12 @@ RestartSec=5
|
|
|
179
179
|
|
|
180
180
|
[Install]
|
|
181
181
|
WantedBy=default.target
|
|
182
|
-
`;await mkdir(dirname(t),{recursive:true,mode:D}),await writeFile(t,i,{encoding:"utf8",mode:O}),await chmod(t,O).catch(()=>{});}async function Sv(t){let e=Pp();await he("launchctl",["bootout",e,t]).catch(()=>{}),await he("launchctl",["bootstrap",e,t]),await he("launchctl",["enable",`${e}/${cn}`]).catch(()=>{}),await he("launchctl",["kickstart","-k",`${e}/${cn}`]).catch(()=>{});}async function Cv(t){await he("launchctl",["bootout",Pp(),t]).catch(()=>{});}function Pp(){return `gui/${typeof process.getuid=="function"?process.getuid():0}`}async function Ev(){try{return await he("schtasks.exe",["/Query","/TN","Pathrule CLI Daemon"]),!0}catch{return false}}async function Rv(t,e){let r=sa(e),n=Object.entries(r).map(([o,a])=>`set ${ra(o)}=${ra(a)}`).join("&&"),i=[t.command,...t.args].map(Pv).join(" "),s=n?`cmd.exe /d /c "${n}&&${i}"`:i;await he("schtasks.exe",["/Create","/TN","Pathrule CLI Daemon","/TR",s,"/SC","ONLOGON","/F"]);}async function xv(){await he("schtasks.exe",["/Delete","/TN","Pathrule CLI Daemon","/F"]).catch(()=>{});}function or(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function yp(t){return `"${t.replace(/(["\\$`])/g,"\\$1")}"`}function Pv(t){return `"${ra(t)}"`}function ra(t){return t.replace(/(["^&|<>%])/g,"^$1")}async function Tp(t,e={}){let r=null,n=new Map,i=new Map,s=createServer((l,c)=>{Iv(l,c,t,r,n,i);}),o=Tv(t);await new Promise((l,c)=>{s.once("error",c),s.listen(o.port,o.host,()=>{s.off("error",c),l();});});let a=s.address();if(!a||typeof a=="string")throw new Error("daemon_bind_failed");r={schema_version:1,pid:process.pid,host:on,port:a.port,protocol_version:ta,daemon_session_id:randomUUID(),started_at:new Date().toISOString()},await $v(t,r),await an(t,`listening ${on}:${a.port}`),mp(t).catch(l=>{an(t,`work_state_trackers_start_failed error=${l instanceof Error?l.message:"unknown"}`);}),await new Promise(l=>{let c=false,u=()=>{c||(c=true,process.off("SIGTERM",u),process.off("SIGINT",u),e.shutdownSignal?.removeEventListener("abort",u),_p(),s.close(()=>l()));};process.once("SIGTERM",u),process.once("SIGINT",u),e.shutdownSignal?.addEventListener("abort",u,{once:true});}),await unlink(A(t).daemonFile).catch(()=>{}),await an(t,"stopped");}function Tv(t){let e=t.PATHRULE_DAEMON_HOST?.trim();if(e&&e!==on&&e!=="localhost")throw new Error("daemon_host_must_be_loopback");let r=t.PATHRULE_DAEMON_PORT?.trim();if(!r)return {host:on,port:0};let n=Number(r);if(!Number.isInteger(n)||n<0||n>65535)throw new Error("daemon_port_invalid");return {host:on,port:n}}function Av(t,e,r,n=Date.now()){let i=Ku({origin:e,ip:r,nowMs:n}),s=(t.get(i)??0)+1;return t.set(i,s),s<=mv}async function Iv(t,e,r,n,i,s){let o=new URL(t.url??"/","http://127.0.0.1"),a=Ii(t.headers,"origin"),l=jv();if(t.method==="OPTIONS"){let d=Eo(a,l);if(!d){x(e,400,{ok:false,error:a?"origin_not_allowed":"origin_required"});return}e.writeHead(204,d),e.end();return}if(a&&!fi(a,l)){x(e,400,{ok:false,error:"origin_not_allowed"});return}if(a&&!Av(s,a,Dv(t))){x(e,429,{ok:false,error:"rate_limited"});return}let c=a?Eo(a,l)??void 0:void 0;if(t.method==="POST"&&o.pathname==="/hook/work-conflicts"&&!a)try{let d=await ar(t,8192),p=await kp(r,{workspaceId:Me(d,"workspace_id"),relativePaths:Cp(d,"relative_paths")});x(e,200,p);return}catch(d){x(e,400,{ok:false,error:d instanceof Error?d.message:String(d)});return}if(t.method==="GET"&&o.pathname==="/v1/status"){let d=Pt(t,a,i);if(d&&n){let p=await Ip(r);x(e,200,{daemon_present:true,paired:true,daemon_version:wv.version,protocol_version:ta,daemon_session_id:d.daemonSessionId,user_id:d.userId,paired_at:d.pairedAt,desktop_runtime_detected:p},c);return}x(e,200,Ju(ta),c);return}if(t.method==="POST"&&o.pathname==="/v1/pair"){let d=bt({headers:t.headers,allowedOrigins:l,requirePairToken:false});if(d){x(e,d.statusCode,{ok:false,error:d.reason},c);return}if(!n){x(e,503,{ok:false,error:"daemon_not_ready"},c);return}try{let p=await ar(t),h=Me(p,"browser_profile_id"),f=await Hu({env:r,daemonSessionId:n.daemon_session_id,origin:a??"",pairCode:Me(p,"pair_code"),pairVerifier:Me(p,"pair_verifier"),browserProfileId:h});i.set(f.pair_token,{daemonSessionId:f.daemon_session_id,browserProfileId:h,origin:a??"",userId:f.user_id,pairedAt:new Date().toISOString()}),await an(r,vp("bridge_paired",{origin:a??"",userId:f.user_id,browserProfileId:h})),x(e,200,f,c);return}catch(p){let h=p instanceof Y?p.code:"pair_failed",f=h==="pair_code_missing"||h==="pair_code_invalid"?401:h==="pair_code_expired"||h==="pair_code_stale"?410:h.endsWith("_required")?400:500;x(e,f,{ok:false,error:h},c);return}}if(t.method==="POST"&&o.pathname==="/v1/fs/read-dir"){let d=Pt(t,a,i),p=bt({headers:t.headers,allowedOrigins:l});if(p){x(e,p.statusCode,{ok:false,error:p.reason},c);return}if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{let h=await ar(t),f=Me(h,"workspace_root"),m=Me(h,"relative_dir");await pe(r,d.userId,f);let _=await Wo(f,m);x(e,200,{entries:_},c);return}catch(h){x(e,400,{error:h instanceof Error?h.message:String(h)},c);return}}if(t.method==="POST"&&o.pathname==="/v1/fs/path-exists"){let d=Pt(t,a,i),p=bt({headers:t.headers,allowedOrigins:l});if(p){x(e,p.statusCode,{ok:false,error:p.reason},c);return}if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{let h=await ar(t),f=Me(h,"path");await pe(r,d.userId,f);let m=await oa(f),_=m?await Ap(f):!1;x(e,200,{exists:m,isDirectory:_},c);return}catch(h){x(e,400,{error:h instanceof Error?h.message:String(h)},c);return}}if(t.method==="POST"&&o.pathname==="/v1/doctor"){let d=Pt(t,a,i),p=bt({headers:t.headers,allowedOrigins:l});if(p){x(e,p.statusCode,{ok:false,error:p.reason},c);return}if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{await na(r,d.userId);let h=await ar(t),f=Sp(h,"workspace_root")??process.cwd(),m=await je(r,f);x(e,200,{ok:m.ok,report:m},c);return}catch(h){x(e,400,{ok:false,error:h instanceof Error?h.message:String(h)},c);return}}let u=Ov(o.pathname);if(t.method==="GET"&&u){let d=Pt(t,a,i);if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{let p=o.searchParams.get("workspace_root")?.trim()??"";if(!p)throw new Error("workspace_root_required");if(u.action==="local-status"){await bp(e,r,d.userId,u.workspaceId,p,c);return}if(u.action==="agents-status"){await pe(r,d.userId,p,u.workspaceId);let h=await Rt(r,d.userId,u.workspaceId,p);x(e,200,{ok:!0,statuses:h,ai_clients:h},c);return}if(u.action==="fs-read"){await pe(r,d.userId,p,u.workspaceId);let h=await Wo(p,o.searchParams.get("dir")??"/");x(e,200,{ok:!0,entries:h},c);return}}catch(p){x(e,400,{ok:false,error:p instanceof Error?p.message:String(p)},c);return}}if(t.method==="POST"&&u){let d=Pt(t,a,i),p=bt({headers:t.headers,allowedOrigins:l});if(p){x(e,p.statusCode,{ok:false,error:p.reason},c);return}if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{let h=await ar(t),f=Me(h,"workspace_root");if(u.action==="local-status"){await bp(e,r,d.userId,u.workspaceId,f,c);return}if(u.action==="attach"){await na(r,d.userId);let m=await xe(u.workspaceId,f,r);x(e,200,{ok:!0,...m},c);return}if(u.action==="sync"){await pe(r,d.userId,f,u.workspaceId);let m=await rn(r,u.workspaceId,f);await Qo(u.workspaceId,f,r),await ea(u.workspaceId),x(e,m.ok?200:409,m,c);return}if(u.action==="repair"){await pe(r,d.userId,f,u.workspaceId);let m=await nn(r,f);x(e,m.ok?200:409,m,c);return}if(u.action==="agents-status"){await pe(r,d.userId,f,u.workspaceId);let m=await Rt(r,d.userId,u.workspaceId,f);x(e,200,{ok:!0,statuses:m,ai_clients:m},c);return}if(u.action==="agents-install"||u.action==="agents-uninstall"||u.action==="agents-set-enabled"){await pe(r,d.userId,f,u.workspaceId);let m=u.action==="agents-set-enabled"?Mv(h,"enabled"):u.action==="agents-install",_=await hp(r,d.userId,u.workspaceId,f,Me(h,"client"),m,Lv(Sp(h,"disable_mode")));x(e,_.ok?200:409,_,c);return}if(u.action==="hooks-sync"||u.action==="hook-index-rebuild"){await pe(r,d.userId,f,u.workspaceId);let{supabase:m}=await C(r),_=await Si({supabase:m,workspaceId:u.workspaceId,workspaceRoot:f,env:r});await Qo(u.workspaceId,f,r),await ea(u.workspaceId),x(e,_.ok?200:409,_,c);return}if(u.action==="work-conflicts"){await pe(r,d.userId,f,u.workspaceId);let m=await kp(r,{workspaceId:u.workspaceId,relativePaths:Cp(h,"relative_paths")});x(e,200,{ok:!0,decision:m},c);return}if(u.action==="skills-materialize"){await pe(r,d.userId,f,u.workspaceId);let m=await rn(r,u.workspaceId,f,{skillsOnly:!0});x(e,m.ok?200:409,m,c);return}}catch(h){x(e,400,{ok:false,error:h instanceof Error?h.message:String(h)},c);return}}if(t.method==="POST"&&o.pathname==="/v1/unpair"){let d=bt({headers:t.headers,allowedOrigins:l});if(d){x(e,d.statusCode,{ok:false,error:d.reason},c);return}let p=Ii(t.headers,hi),h=Pt(t,a,i);if(!p||!h){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}i.delete(p),await an(r,vp("bridge_unpaired",{origin:a??"",userId:h.userId,browserProfileId:h.browserProfileId})),x(e,200,{ok:true},c);return}x(e,404,{ok:false,error:"not_found"},c);}function Pt(t,e,r){let n=Ii(t.headers,hi);if(!n||!e)return null;let i=r.get(n);return !i||i.origin!==e||i.browserProfileId!==Ii(t.headers,zu)?null:i}async function pe(t,e,r,n){await na(t,e);let{session:i,supabase:s}=await C(t),o=s.from("user_workspace_paths").select("workspace_id").eq("user_id",e).eq("local_root_path",r).limit(1);n&&(o=o.eq("workspace_id",n));let{data:a,error:l}=await o;if(l)throw l;if(!a||a.length===0)throw new Error("workspace_root_not_attached")}async function na(t,e){let{session:r}=await C(t);if(r.user.id!==e)throw new Error("session_user_mismatch")}function Ov(t){let e=/^\/v1\/workspaces\/([^/]+)\/(.+)$/.exec(t);if(!e)return null;let r=decodeURIComponent(e[1]??""),n=e[2]??"";return r?n==="local-status"?{workspaceId:r,action:"local-status"}:n==="fs"?{workspaceId:r,action:"fs-read"}:n==="attach"?{workspaceId:r,action:"attach"}:n==="sync"?{workspaceId:r,action:"sync"}:n==="repair"?{workspaceId:r,action:"repair"}:n==="agents/status"?{workspaceId:r,action:"agents-status"}:n==="agents/install"?{workspaceId:r,action:"agents-install"}:n==="agents/uninstall"?{workspaceId:r,action:"agents-uninstall"}:n==="agents/set-enabled"?{workspaceId:r,action:"agents-set-enabled"}:n==="hooks/sync"?{workspaceId:r,action:"hooks-sync"}:n==="hook-index/rebuild"?{workspaceId:r,action:"hook-index-rebuild"}:n==="skills/materialize"?{workspaceId:r,action:"skills-materialize"}:n==="work-conflicts"?{workspaceId:r,action:"work-conflicts"}:null:null}async function kp(t,e){let r=Date.now(),{session:n,supabase:i}=await C(t),s=i.rpc("pathrule_check_file_work_conflicts",{p_workspace_id:e.workspaceId,p_relative_paths:e.relativePaths}),o=await Bv(s,yv);if(!o||o.error)return Yu(r);let a=Array.isArray(o.data)?o.data:[],l={};for(let c of a){if(!c||typeof c!="object")continue;let u=c;typeof u.user_id=="string"&&typeof u.display_name=="string"&&(l[u.user_id]=u.display_name);}return Gu({workspaceId:e.workspaceId,relativePaths:e.relativePaths,currentUserId:n.user.id,rows:Xu(a),displayNamesByUserId:l,source:"cloud_rpc",startedAtMs:r})}async function bp(t,e,r,n,i,s){await pe(e,r,i,n);let o=await oa(i),a=o?await Ap(i):false,l=await Ip(e),c=await Rt(e,r,n,i);x(t,200,{ok:true,workspace_id:n,local_root_path:i,root_exists:o,root_is_directory:a,desktop_runtime_detected:l,local_runtime_state:o?a?l?"cli_attached_desktop_also_detected":"cli_attached":"root_not_directory":"root_missing",ai_clients:c},s);}async function oa(t){try{return await access(t,constants.F_OK),!0}catch{return false}}async function Ap(t){try{return (await stat(t)).isDirectory()}catch{return false}}async function $v(t,e){let r=A(t).daemonFile;await mkdir(dirname(r),{recursive:true,mode:D});let n=`${r}.tmp`;await writeFile(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:O}),await rename(n,r);}async function an(t,e){let r=A(t).logsDir;await mkdir(r,{recursive:true,mode:D});let n=new Date().toISOString().slice(0,10),i=`${new Date().toISOString()} ${Nv(e)}
|
|
182
|
+
`;await mkdir(dirname(t),{recursive:true,mode:D}),await writeFile(t,i,{encoding:"utf8",mode:O}),await chmod(t,O).catch(()=>{});}async function Sv(t){let e=Pp();await fe("launchctl",["bootout",e,t]).catch(()=>{}),await fe("launchctl",["bootstrap",e,t]),await fe("launchctl",["enable",`${e}/${un}`]).catch(()=>{}),await fe("launchctl",["kickstart","-k",`${e}/${un}`]).catch(()=>{});}async function Cv(t){await fe("launchctl",["bootout",Pp(),t]).catch(()=>{});}function Pp(){return `gui/${typeof process.getuid=="function"?process.getuid():0}`}async function Ev(){try{return await fe("schtasks.exe",["/Query","/TN","Pathrule CLI Daemon"]),!0}catch{return false}}async function Rv(t,e){let r=sa(e),n=Object.entries(r).map(([o,a])=>`set ${ra(o)}=${ra(a)}`).join("&&"),i=[t.command,...t.args].map(Pv).join(" "),s=n?`cmd.exe /d /c "${n}&&${i}"`:i;await fe("schtasks.exe",["/Create","/TN","Pathrule CLI Daemon","/TR",s,"/SC","ONLOGON","/F"]);}async function xv(){await fe("schtasks.exe",["/Delete","/TN","Pathrule CLI Daemon","/F"]).catch(()=>{});}function or(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function yp(t){return `"${t.replace(/(["\\$`])/g,"\\$1")}"`}function Pv(t){return `"${ra(t)}"`}function ra(t){return t.replace(/(["^&|<>%])/g,"^$1")}async function Tp(t,e={}){let r=null,n=new Map,i=new Map,s=createServer((l,c)=>{Iv(l,c,t,r,n,i);}),o=Tv(t);await new Promise((l,c)=>{s.once("error",c),s.listen(o.port,o.host,()=>{s.off("error",c),l();});});let a=s.address();if(!a||typeof a=="string")throw new Error("daemon_bind_failed");r={schema_version:1,pid:process.pid,host:an,port:a.port,protocol_version:ta,daemon_session_id:randomUUID(),started_at:new Date().toISOString()},await $v(t,r),await ln(t,`listening ${an}:${a.port}`),mp(t).catch(l=>{ln(t,`work_state_trackers_start_failed error=${l instanceof Error?l.message:"unknown"}`);}),await new Promise(l=>{let c=false,u=()=>{c||(c=true,process.off("SIGTERM",u),process.off("SIGINT",u),e.shutdownSignal?.removeEventListener("abort",u),_p(),s.close(()=>l()));};process.once("SIGTERM",u),process.once("SIGINT",u),e.shutdownSignal?.addEventListener("abort",u,{once:true});}),await unlink(A(t).daemonFile).catch(()=>{}),await ln(t,"stopped");}function Tv(t){let e=t.PATHRULE_DAEMON_HOST?.trim();if(e&&e!==an&&e!=="localhost")throw new Error("daemon_host_must_be_loopback");let r=t.PATHRULE_DAEMON_PORT?.trim();if(!r)return {host:an,port:0};let n=Number(r);if(!Number.isInteger(n)||n<0||n>65535)throw new Error("daemon_port_invalid");return {host:an,port:n}}function Av(t,e,r,n=Date.now()){let i=Ku({origin:e,ip:r,nowMs:n}),s=(t.get(i)??0)+1;return t.set(i,s),s<=mv}async function Iv(t,e,r,n,i,s){let o=new URL(t.url??"/","http://127.0.0.1"),a=Ii(t.headers,"origin"),l=jv();if(t.method==="OPTIONS"){let d=Eo(a,l);if(!d){x(e,400,{ok:false,error:a?"origin_not_allowed":"origin_required"});return}e.writeHead(204,d),e.end();return}if(a&&!fi(a,l)){x(e,400,{ok:false,error:"origin_not_allowed"});return}if(a&&!Av(s,a,Dv(t))){x(e,429,{ok:false,error:"rate_limited"});return}let c=a?Eo(a,l)??void 0:void 0;if(t.method==="POST"&&o.pathname==="/hook/work-conflicts"&&!a)try{let d=await ar(t,8192),p=await kp(r,{workspaceId:Me(d,"workspace_id"),relativePaths:Cp(d,"relative_paths")});x(e,200,p);return}catch(d){x(e,400,{ok:false,error:d instanceof Error?d.message:String(d)});return}if(t.method==="GET"&&o.pathname==="/v1/status"){let d=Pt(t,a,i);if(d&&n){let p=await Ip(r);x(e,200,{daemon_present:true,paired:true,daemon_version:wv.version,protocol_version:ta,daemon_session_id:d.daemonSessionId,user_id:d.userId,paired_at:d.pairedAt,desktop_runtime_detected:p},c);return}x(e,200,Ju(ta),c);return}if(t.method==="POST"&&o.pathname==="/v1/pair"){let d=bt({headers:t.headers,allowedOrigins:l,requirePairToken:false});if(d){x(e,d.statusCode,{ok:false,error:d.reason},c);return}if(!n){x(e,503,{ok:false,error:"daemon_not_ready"},c);return}try{let p=await ar(t),h=Me(p,"browser_profile_id"),f=await Hu({env:r,daemonSessionId:n.daemon_session_id,origin:a??"",pairCode:Me(p,"pair_code"),pairVerifier:Me(p,"pair_verifier"),browserProfileId:h});i.set(f.pair_token,{daemonSessionId:f.daemon_session_id,browserProfileId:h,origin:a??"",userId:f.user_id,pairedAt:new Date().toISOString()}),await ln(r,vp("bridge_paired",{origin:a??"",userId:f.user_id,browserProfileId:h})),x(e,200,f,c);return}catch(p){let h=p instanceof Y?p.code:"pair_failed",f=h==="pair_code_missing"||h==="pair_code_invalid"?401:h==="pair_code_expired"||h==="pair_code_stale"?410:h.endsWith("_required")?400:500;x(e,f,{ok:false,error:h},c);return}}if(t.method==="POST"&&o.pathname==="/v1/fs/read-dir"){let d=Pt(t,a,i),p=bt({headers:t.headers,allowedOrigins:l});if(p){x(e,p.statusCode,{ok:false,error:p.reason},c);return}if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{let h=await ar(t),f=Me(h,"workspace_root"),m=Me(h,"relative_dir");await he(r,d.userId,f);let _=await Wo(f,m);x(e,200,{entries:_},c);return}catch(h){x(e,400,{error:h instanceof Error?h.message:String(h)},c);return}}if(t.method==="POST"&&o.pathname==="/v1/fs/path-exists"){let d=Pt(t,a,i),p=bt({headers:t.headers,allowedOrigins:l});if(p){x(e,p.statusCode,{ok:false,error:p.reason},c);return}if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{let h=await ar(t),f=Me(h,"path");await he(r,d.userId,f);let m=await oa(f),_=m?await Ap(f):!1;x(e,200,{exists:m,isDirectory:_},c);return}catch(h){x(e,400,{error:h instanceof Error?h.message:String(h)},c);return}}if(t.method==="POST"&&o.pathname==="/v1/doctor"){let d=Pt(t,a,i),p=bt({headers:t.headers,allowedOrigins:l});if(p){x(e,p.statusCode,{ok:false,error:p.reason},c);return}if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{await na(r,d.userId);let h=await ar(t),f=Sp(h,"workspace_root")??process.cwd(),m=await je(r,f);x(e,200,{ok:m.ok,report:m},c);return}catch(h){x(e,400,{ok:false,error:h instanceof Error?h.message:String(h)},c);return}}let u=Ov(o.pathname);if(t.method==="GET"&&u){let d=Pt(t,a,i);if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{let p=o.searchParams.get("workspace_root")?.trim()??"";if(!p)throw new Error("workspace_root_required");if(u.action==="local-status"){await bp(e,r,d.userId,u.workspaceId,p,c);return}if(u.action==="agents-status"){await he(r,d.userId,p,u.workspaceId);let h=await Rt(r,d.userId,u.workspaceId,p);x(e,200,{ok:!0,statuses:h,ai_clients:h},c);return}if(u.action==="fs-read"){await he(r,d.userId,p,u.workspaceId);let h=await Wo(p,o.searchParams.get("dir")??"/");x(e,200,{ok:!0,entries:h},c);return}}catch(p){x(e,400,{ok:false,error:p instanceof Error?p.message:String(p)},c);return}}if(t.method==="POST"&&u){let d=Pt(t,a,i),p=bt({headers:t.headers,allowedOrigins:l});if(p){x(e,p.statusCode,{ok:false,error:p.reason},c);return}if(!d){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}try{let h=await ar(t),f=Me(h,"workspace_root");if(u.action==="local-status"){await bp(e,r,d.userId,u.workspaceId,f,c);return}if(u.action==="attach"){await na(r,d.userId);let m=await xe(u.workspaceId,f,r);x(e,200,{ok:!0,...m},c);return}if(u.action==="sync"){await he(r,d.userId,f,u.workspaceId);let m=await nn(r,u.workspaceId,f);await Qo(u.workspaceId,f,r),await ea(u.workspaceId),x(e,m.ok?200:409,m,c);return}if(u.action==="repair"){await he(r,d.userId,f,u.workspaceId);let m=await sn(r,f);x(e,m.ok?200:409,m,c);return}if(u.action==="agents-status"){await he(r,d.userId,f,u.workspaceId);let m=await Rt(r,d.userId,u.workspaceId,f);x(e,200,{ok:!0,statuses:m,ai_clients:m},c);return}if(u.action==="agents-install"||u.action==="agents-uninstall"||u.action==="agents-set-enabled"){await he(r,d.userId,f,u.workspaceId);let m=u.action==="agents-set-enabled"?Mv(h,"enabled"):u.action==="agents-install",_=await hp(r,d.userId,u.workspaceId,f,Me(h,"client"),m,Lv(Sp(h,"disable_mode")));x(e,_.ok?200:409,_,c);return}if(u.action==="hooks-sync"||u.action==="hook-index-rebuild"){await he(r,d.userId,f,u.workspaceId);let{supabase:m}=await C(r),_=await Si({supabase:m,workspaceId:u.workspaceId,workspaceRoot:f,env:r});await Qo(u.workspaceId,f,r),await ea(u.workspaceId),x(e,_.ok?200:409,_,c);return}if(u.action==="work-conflicts"){await he(r,d.userId,f,u.workspaceId);let m=await kp(r,{workspaceId:u.workspaceId,relativePaths:Cp(h,"relative_paths")});x(e,200,{ok:!0,decision:m},c);return}if(u.action==="skills-materialize"){await he(r,d.userId,f,u.workspaceId);let m=await nn(r,u.workspaceId,f,{skillsOnly:!0});x(e,m.ok?200:409,m,c);return}}catch(h){x(e,400,{ok:false,error:h instanceof Error?h.message:String(h)},c);return}}if(t.method==="POST"&&o.pathname==="/v1/unpair"){let d=bt({headers:t.headers,allowedOrigins:l});if(d){x(e,d.statusCode,{ok:false,error:d.reason},c);return}let p=Ii(t.headers,hi),h=Pt(t,a,i);if(!p||!h){x(e,401,{ok:false,error:"pair_token_invalid"},c);return}i.delete(p),await ln(r,vp("bridge_unpaired",{origin:a??"",userId:h.userId,browserProfileId:h.browserProfileId})),x(e,200,{ok:true},c);return}x(e,404,{ok:false,error:"not_found"},c);}function Pt(t,e,r){let n=Ii(t.headers,hi);if(!n||!e)return null;let i=r.get(n);return !i||i.origin!==e||i.browserProfileId!==Ii(t.headers,zu)?null:i}async function he(t,e,r,n){await na(t,e);let{session:i,supabase:s}=await C(t),o=s.from("user_workspace_paths").select("workspace_id").eq("user_id",e).eq("local_root_path",r).limit(1);n&&(o=o.eq("workspace_id",n));let{data:a,error:l}=await o;if(l)throw l;if(!a||a.length===0)throw new Error("workspace_root_not_attached")}async function na(t,e){let{session:r}=await C(t);if(r.user.id!==e)throw new Error("session_user_mismatch")}function Ov(t){let e=/^\/v1\/workspaces\/([^/]+)\/(.+)$/.exec(t);if(!e)return null;let r=decodeURIComponent(e[1]??""),n=e[2]??"";return r?n==="local-status"?{workspaceId:r,action:"local-status"}:n==="fs"?{workspaceId:r,action:"fs-read"}:n==="attach"?{workspaceId:r,action:"attach"}:n==="sync"?{workspaceId:r,action:"sync"}:n==="repair"?{workspaceId:r,action:"repair"}:n==="agents/status"?{workspaceId:r,action:"agents-status"}:n==="agents/install"?{workspaceId:r,action:"agents-install"}:n==="agents/uninstall"?{workspaceId:r,action:"agents-uninstall"}:n==="agents/set-enabled"?{workspaceId:r,action:"agents-set-enabled"}:n==="hooks/sync"?{workspaceId:r,action:"hooks-sync"}:n==="hook-index/rebuild"?{workspaceId:r,action:"hook-index-rebuild"}:n==="skills/materialize"?{workspaceId:r,action:"skills-materialize"}:n==="work-conflicts"?{workspaceId:r,action:"work-conflicts"}:null:null}async function kp(t,e){let r=Date.now(),{session:n,supabase:i}=await C(t),s=i.rpc("pathrule_check_file_work_conflicts",{p_workspace_id:e.workspaceId,p_relative_paths:e.relativePaths}),o=await Bv(s,yv);if(!o||o.error)return Yu(r);let a=Array.isArray(o.data)?o.data:[],l={};for(let c of a){if(!c||typeof c!="object")continue;let u=c;typeof u.user_id=="string"&&typeof u.display_name=="string"&&(l[u.user_id]=u.display_name);}return Gu({workspaceId:e.workspaceId,relativePaths:e.relativePaths,currentUserId:n.user.id,rows:Xu(a),displayNamesByUserId:l,source:"cloud_rpc",startedAtMs:r})}async function bp(t,e,r,n,i,s){await he(e,r,i,n);let o=await oa(i),a=o?await Ap(i):false,l=await Ip(e),c=await Rt(e,r,n,i);x(t,200,{ok:true,workspace_id:n,local_root_path:i,root_exists:o,root_is_directory:a,desktop_runtime_detected:l,local_runtime_state:o?a?l?"cli_attached_desktop_also_detected":"cli_attached":"root_not_directory":"root_missing",ai_clients:c},s);}async function oa(t){try{return await access(t,constants.F_OK),!0}catch{return false}}async function Ap(t){try{return (await stat(t)).isDirectory()}catch{return false}}async function $v(t,e){let r=A(t).daemonFile;await mkdir(dirname(r),{recursive:true,mode:D});let n=`${r}.tmp`;await writeFile(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:O}),await rename(n,r);}async function ln(t,e){let r=A(t).logsDir;await mkdir(r,{recursive:true,mode:D});let n=new Date().toISOString().slice(0,10),i=`${new Date().toISOString()} ${Nv(e)}
|
|
183
183
|
`;await writeFile(join(r,`daemon-${n}.log`),i,{flag:"a",encoding:"utf8",mode:O});}function Nv(t){return t.replace(/(authorization|token|secret|password)=\S+/gi,"$1=[redacted]")}function vp(t,e){let r=createHash("sha256").update("pathrule-bridge-profile-v1","utf8").update("\0","utf8").update(e.browserProfileId,"utf8").digest("base64url").slice(0,16);return `${t} origin=${e.origin||"unknown"} user_id=${e.userId} browser_profile_hash=${r}`}async function Ip(t,e=Date.now()){let r=t.PATHRULE_DESKTOP_HEALTH?.trim().toLowerCase();if(r==="healthy"||r==="1"||r==="true")return true;if(r==="unhealthy"||r==="0"||r==="false")return false;let n;try{n=JSON.parse(await readFile(A(t).desktopFile,"utf8"));}catch{return false}if(n.healthy!==true||!n.updated_at)return false;let i=Date.parse(n.updated_at);return Number.isFinite(i)&&e-i<=600*1e3}function jv(){let t=process.env.PATHRULE_BRIDGE_ORIGINS;return t?t.split(",").map(e=>e.trim()).filter(Boolean):["https://app.pathrule.io","http://localhost:5173"]}function Ii(t,e){let r=t[e]??t[e.toLowerCase()],n=Array.isArray(r)?r[0]:r;return (typeof n=="string"?n.trim():"")||void 0}function Dv(t){return t.socket.remoteAddress??"unknown"}async function ar(t,e=4096){let r="";for await(let i of t)if(r+=i,Buffer.byteLength(r,"utf8")>e)throw new Error("request_body_too_large");let n=JSON.parse(r||"{}");if(!n||typeof n!="object"||Array.isArray(n))throw new Error("invalid_json_body");return n}function Me(t,e){let r=t[e];if(typeof r!="string"||r.trim()==="")throw new Y(`${e}_required`);return r.trim()}function Sp(t,e){let r=t[e];return typeof r!="string"||r.trim()===""?null:r.trim()}function Mv(t,e){let r=t[e];if(typeof r!="boolean")throw new Y(`${e}_required`);return r}function Cp(t,e){let r=t[e];if(!Array.isArray(r))throw new Y(`${e}_required`);return Array.from(new Set(r.filter(n=>typeof n=="string"))).filter(n=>n.trim()!=="").slice(0,100)}function Lv(t){return t==="full-remove"?"full-remove":"restore-backup"}function x(t,e,r,n){t.writeHead(e,{"content-type":"application/json",...n}),t.end(JSON.stringify(r));}function Uv(t){if(!Number.isInteger(t)||t<=0)return false;try{return process.kill(t,0),!0}catch{return false}}function Wv(t){return new Promise(e=>setTimeout(e,t))}async function Bv(t,e){let r=null;try{return await Promise.race([t,new Promise(n=>{r=setTimeout(()=>n(null),e),r.unref?.();})])}finally{r&&clearTimeout(r);}}F();function k(t){return {schema_version:1,ok:t.ok,command:t.command,cwd:t.cwd,...t.data===void 0?{}:{data:t.data},...t.error===void 0?{}:{error:t.error},...t.next_steps===void 0?{}:{next_steps:t.next_steps}}}function Op(t){return `${JSON.stringify(t,null,2)}
|
|
184
|
-
`}function g(t,e){let r={ok:"[ok]",warn:"[warn]",error:"[error]",info:"[info]"};return e.color?`${{ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[36m"}[t]}${r[t]}\x1B[0m`:r[t]}Ee();var Hv=/^[^\s@]+@[^\s@]+\.[^\s@]+$/i,Pe=class extends Error{constructor(r,n){super(n);this.code=r;this.name="CliInviteUsageError";}code};function aa(t){let e=[],r="editor",n,i;for(let o=0;o<t.length;o+=1){let a=t[o];if(a){if(a==="--role"){r=Zv(t[++o]);continue}if(a==="--org"){n=$p(t[++o],"--org requires a value","invite_org_required");continue}if(a==="--workspace"){i=$p(t[++o],"--workspace requires a value","invite_workspace_required");continue}if(a.startsWith("--"))throw new Pe("unknown_invite_option",`Unknown invite option "${a}".`);e.push(a);}}let s=e[0];if(!s)throw new Pe("invite_email_required","Usage: pathrule invite <email> [--role admin|editor|viewer] [--org <slug-or-id>] [--workspace <name-or-id>]");if(e.length>1)throw new Pe("unexpected_invite_argument",`Unexpected extra argument "${e[1]}".`);return {email:s,role:r,orgSelector:n,workspaceSelector:i}}async function la(t,e){let r=t.email.trim().toLowerCase();if(!Hv.test(r))return At("invalid_email",null,null,e,r);let{session:n,supabase:i}=await C(e),s=await qv(t.orgSelector,e);if(!s)return At("org_required",null,null,e,r);if(s.role!=="admin"&&s.role!=="owner")return At("forbidden",s,null,e,r);let o=await zv(i,n.user.id,s.id,t.workspaceSelector,e);if(!o&&t.workspaceSelector)return At("workspace_not_found",s,null,e,r);let a=await Qv(i,s.id);if(a.failure)return At(a.failure.error,s,o,e,r,a.failure.details);let l=await Yv(i,s.id,a,e);if(!l.ok)return At(l.error,s,o,e,r,l.details);let{data:c,error:u}=await i.rpc("create_org_invite",{p_org_id:s.id,p_email:r,p_role:t.role}),d=c,p=d&&d.ok===false?d.error:void 0;if(u||!d||d.ok!==true)return At(u?.message??p??"invite_failed",s,o,e,r);let h=true;try{let{error:m}=await i.functions.invoke("send-org-invite-email",{body:{invite_id:d.invite_id}});m&&(h=!1);}catch{h=false;}let f={kind:"web",url:ee(s,e,"members"),label:"Open team in Pathrule Web",reason:"preferred"};return {ok:true,invite_id:d.invite_id,email:d.email,role:d.role,email_sent:h,billing_impact:a.billingImpact,billing_adjustment:l.adjustment,organization:Np(s),workspace:jp(o),open_target:f,next_steps:[{label:"Open team in Pathrule Web",url:f.url},...h?[]:[{label:"Retry invite email from Pathrule Web",url:f.url}]]}}function Np(t){return t?{id:t.id,name:t.name,slug:t.slug,role:t.role}:null}function jp(t){return t?{id:t.id,name:t.name}:null}async function qv(t,e){return t?(await _e(e)).find(n=>n.id===t||n.slug===t)??null:j(e)}async function zv(t,e,r,n,i){if(!n){let a=await M(i);return a?.organization_id===r?a:null}let{data:s,error:o}=await t.from("workspaces").select("id, organization_id, name, access_mode, git_remote_url, git_owner, git_repo, user_workspace_paths!left(local_root_path, user_id)").eq("organization_id",r).is("archived_at",null);if(o)throw o;for(let a of s??[]){let c=(a.user_workspace_paths??[]).find(d=>d.user_id===e)??null,u={id:a.id,organization_id:a.organization_id,name:a.name,access_mode:a.access_mode,git_remote_url:a.git_remote_url,git_owner:a.git_owner,git_repo:a.git_repo,local_root_path:c?.local_root_path??null,current:false};if(u.id===n||u.name===n)return u}return null}function At(t,e,r,n,i,s){let o=Jv(t,e,n),a=Kv(t,i);return {ok:false,error:t,message:Gv(t),...a?{email_hash:a}:{},organization:Np(e),workspace:jp(r),open_target:o,next_steps:Vv(t,o),...s}}function Jv(t,e,r){if(e){if(t==="free_plan_invites_disabled"||t==="invite_blocked_billing"||t==="billing_update_failed")return {kind:"web",url:ee(e,r,"billing"),label:"Open billing in Pathrule Web",reason:"fallback"};if(t==="subscription_not_invitable"||t==="subscription_frozen")return {kind:"web",url:`${ee(e,r,"billing")}/reactivate`,label:"Open billing reactivation in Pathrule Web",reason:"fallback"};if(t==="paid_seats_required"||t==="seat_limit_reached")return {kind:"web",url:ee(e,r,"billing"),label:"Open billing in Pathrule Web",reason:"fallback"};if(t==="forbidden"||t==="permission_denied"||t==="already_member"||t==="email_already_member"||t==="invite_pending")return {kind:"web",url:ee(e,r,"members"),label:"Open team in Pathrule Web",reason:"fallback"}}}function Kv(t,e){if(e&&!(t!=="rate_limited"&&t!=="invite_resent_cooldown_hit"&&t!=="invite_declined_cooldown"))return createHash("sha256").update(e.trim().toLowerCase()).digest("hex")}function Vv(t,e){if(t==="not_authenticated"||t==="session_expired_security_epoch")return [{label:"Sign in again",command:"pathrule login"}];if(t==="org_required")return [{label:"Choose an organization",command:"pathrule org use <slug-or-id>"}];if(t==="workspace_not_found")return [{label:"List workspaces",command:"pathrule workspace list"}];if(t==="rate_limited"||t==="invite_resent_cooldown_hit"||t==="invite_declined_cooldown")return [{label:"Retry later"}];if(e)return [{label:e.label,url:e.url}]}function Gv(t){switch(t){case "invalid_email":return "Enter a valid email address.";case "invalid_role":return "Role must be admin, editor, or viewer.";case "not_authenticated":return "Pathrule CLI is not signed in.";case "session_expired_security_epoch":return "Your session is stale after a security change. Sign in again.";case "org_required":return "No organization is selected.";case "workspace_not_found":return "Workspace context not found for that organization.";case "forbidden":case "permission_denied":return "Your current role cannot invite teammates to this organization.";case "free_plan_invites_disabled":return "Invites require a paid Pathrule organization plan.";case "subscription_not_invitable":case "subscription_frozen":return "Invites are blocked until billing is reactivated.";case "paid_seats_required":case "seat_limit_reached":return "Pathrule could not automatically add paid seat coverage for this invite.";case "billing_update_failed":return "Billing could not be updated for this invite. Review billing before sending it.";case "rate_limited":return "Rate limit reached, try again later.";case "invite_resent_cooldown_hit":case "invite_declined_cooldown":return "Please wait before inviting this email again.";case "already_member":case "email_already_member":return "That email is already a member of this organization.";case "invite_pending":return "There is already a pending invite for this email.";case "organization_not_found":return "Organization not found.";default:return t.replace(/_/g," ")}}async function Yv(t,e,r,n){if(!r.billingRequirement)return {ok:true,adjustment:{status:r.billingImpact.seat_effect==="paid_extra_available"?"already_covered":"not_needed",target_seats:r.billingImpact.target_active_seats,required_paid_extra_seats:r.billingImpact.required_paid_extra_seats,paid_extra_seats_after:r.billingImpact.current_paid_extra_seats}};let i=r.billingRequirement,s={target_seats:i.targetSeats,required_paid_extra_seats:i.requiredPaidExtraSeats,gift_seat_cap:i.giftSeatCap,current_paid_extra_seats:i.currentPaidExtraSeats},o=null;try{let{data:a,error:l}=await t.functions.invoke("start-paid-seat-checkout",{body:{org_id:e,target_seats:i.targetSeats,return_url_origin:Xv(n)}});if(l)return {ok:!1,error:"billing_update_failed",details:s};o=a;}catch{return {ok:false,error:"billing_update_failed",details:s}}return o?.ok?o.url?{ok:false,error:"paid_seats_required",details:s}:{ok:true,adjustment:{status:o.updated?"updated":"already_covered",target_seats:i.targetSeats,required_paid_extra_seats:i.requiredPaidExtraSeats,paid_extra_seats_after:o.paid_extra_seats}}:{ok:false,error:o?.error??"billing_update_failed",details:s}}function Xv(t){return (t.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"")}function Zv(t){let e=t?.trim().toLowerCase();if(!e||e==="member")return "editor";if(e==="admin"||e==="editor"||e==="viewer")return e;throw new Pe("invalid_invite_role",`Invalid invite role "${t}".`)}function $p(t,e,r){if(!t)throw new Pe(r,e);return t}async function Qv(t,e){let[r,n]=await Promise.all([t.from("organizations").select("plan, subscription_status, trial_status, trial_seat_cap, paid_extra_seats").eq("id",e).maybeSingle(),t.from("organization_members").select("id",{count:"exact",head:true}).eq("organization_id",e)]);if(r.error)throw r.error;if(n.error)throw n.error;let i=El(r.data,n.count??0);return {failure:i.failure?{error:i.failure.error}:null,billingImpact:i.billingImpact,billingRequirement:i.billingRequirement}}Ee();F();var It=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="CliRefreshError";}code};async function pn(t,e={}){let r=await Di(t),n=await ha(t,r.id),i=await Qa(n,{workspace_id:r.id,include_in_progress:e.includeInProgress});if(!i.ok)throw fa(i.error);return i.data.slice(0,rS(e.limit)).map(s=>Dp(s,r.id,t))}async function ca(t,e,r={}){let n=await Di(t),i=e??await tS(t),s=await ha(t,n.id),o=await el(s,{refresh_id:i,claimed_by:r.claimedBy??"codex"});if(!o.ok)throw fa(o.error);return Mp(o.data,t)}async function ua(t,e,r,n={}){await Di(t);let i=await ha(t),s=await tl(i,{refresh_id:e,status:r,note:n.note,claimed_by:n.claimedBy??"codex"});if(!s.ok)throw fa(s.error);return Mp(s.data,t)}async function da(t,e){let r=await Di(t);if(!e){let l=(await pn(t,{includeInProgress:true,limit:1}))[0];if(!l)throw new It("refresh_not_found","No pending refresh tasks found.");return l}let{supabase:n}=await C(t),{data:i,error:s}=await n.from("suggestion_refreshes").select("id, workspace_id, subject_type, subject_id, formula_id, status, created_at, brief").eq("id",e).eq("workspace_id",r.id).maybeSingle();if(s)throw s;if(!i)throw new It("refresh_not_found",`Refresh ${e} not found.`);let o=i,a=o.brief??{};return Dp({id:o.id,subjectType:o.subject_type,subjectId:o.subject_id,subjectTitle:a.subject?.title??"(unknown)",nodePath:a.subject?.nodePath??"/",formulaId:o.formula_id,humanReason:a.signal?.humanReason??o.formula_id,status:o.status,createdAt:o.created_at,hasProposedPatch:!!a.proposedPatch?.newBody},r.id,t)}function ji(t,e={}){let r=t.open_targets.find(n=>n.kind==="web")??{kind:"web",url:t.url,label:"Open refresh task in Pathrule Web",reason:"preferred"};if(e.forceWeb)return {...r,reason:"forced"};if(e.preferDesktopApp){let n=t.open_targets.find(i=>i.kind==="desktop-app");return n||{...r,reason:"fallback"}}return t.open_targets[0]??r}function pa(t,e,r){return `${(r.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"")}/workspace/${encodeURIComponent(t)}?tab=suggestions&refresh=${encodeURIComponent(e)}`}function eS(t,e){return `pathrule://workspace/${encodeURIComponent(t)}/refresh/${encodeURIComponent(e)}`}async function tS(t){let e=(await pn(t,{limit:1}))[0];if(!e)throw new It("refresh_not_found","No pending refresh tasks found.");return e.id}async function Di(t){let e=await M(t);if(!e)throw new It("workspace_required","No current workspace. Run pathrule workspace use <name-or-id>.");return e}async function ha(t,e=null){let{session:r,supabase:n}=await C(t);return {supabase:n,userId:r.user.id,workspaceId:e,clientId:"codex"}}function Dp(t,e,r){let n=pa(e,t.id,r);return {...t,workspace_id:e,url:n,open_targets:[Lp(e,t.id,r),Up(e,t.id)]}}function Mp(t,e){return {...t,url:pa(t.workspaceId,t.id,e),open_targets:[Lp(t.workspaceId,t.id,e),Up(t.workspaceId,t.id)]}}function Lp(t,e,r){return {kind:"web",url:pa(t,e,r),label:"Open refresh task in Pathrule Web",reason:"preferred"}}function Up(t,e){return {kind:"desktop-app",url:eS(t,e),label:"Open refresh task in Pathrule Desktop",reason:"fallback"}}function rS(t){return !t||!Number.isFinite(t)?20:Math.min(Math.max(Math.trunc(t),1),100)}function fa(t){return new It(t.code,t.message)}K();K();var pS=promisify(execFile),hS=1440*60*1e3;function Wp(t,e=process.env){return join(A(e).home,"cache",t,"bootstrap-v2-brief.json")}async function Bp(t){let e=Wp(t.workspaceId,t.env),r=t.now??new Date;try{let[n,i,s]=await Promise.all([readFile(e,"utf8"),stat(e),Fp(t.localRootPath)]);if(r.getTime()-i.mtimeMs>hS)return {ok:!1,brief:null,cachePath:e,reason:"expired"};let o=JSON.parse(n);return o.schemaVersion!==1||o.workspaceId!==t.workspaceId||o.localRootPath!==t.localRootPath||o.brief.version!==2?{ok:!1,brief:null,cachePath:e,reason:"mismatch"}:o.gitHead!==s?{ok:!1,brief:null,cachePath:e,reason:"git_head_changed"}:{ok:!0,brief:o.brief,cachePath:e}}catch{return {ok:false,brief:null,cachePath:e,reason:"missing"}}}async function ga(t){let e=Wp(t.workspaceId,t.env),r={schemaVersion:1,workspaceId:t.workspaceId,localRootPath:t.localRootPath,gitHead:await Fp(t.localRootPath),cachedAt:new Date().toISOString(),brief:t.brief};await mkdir(dirname(e),{recursive:true});let n=`${e}.tmp`;return await writeFile(n,`${JSON.stringify(r,null,2)}
|
|
184
|
+
`}function g(t,e){let r={ok:"[ok]",warn:"[warn]",error:"[error]",info:"[info]"};return e.color?`${{ok:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[36m"}[t]}${r[t]}\x1B[0m`:r[t]}Ee();var Hv=/^[^\s@]+@[^\s@]+\.[^\s@]+$/i,Pe=class extends Error{constructor(r,n){super(n);this.code=r;this.name="CliInviteUsageError";}code};function aa(t){let e=[],r="editor",n,i;for(let o=0;o<t.length;o+=1){let a=t[o];if(a){if(a==="--role"){r=Zv(t[++o]);continue}if(a==="--org"){n=$p(t[++o],"--org requires a value","invite_org_required");continue}if(a==="--workspace"){i=$p(t[++o],"--workspace requires a value","invite_workspace_required");continue}if(a.startsWith("--"))throw new Pe("unknown_invite_option",`Unknown invite option "${a}".`);e.push(a);}}let s=e[0];if(!s)throw new Pe("invite_email_required","Usage: pathrule invite <email> [--role admin|editor|viewer] [--org <slug-or-id>] [--workspace <name-or-id>]");if(e.length>1)throw new Pe("unexpected_invite_argument",`Unexpected extra argument "${e[1]}".`);return {email:s,role:r,orgSelector:n,workspaceSelector:i}}async function la(t,e){let r=t.email.trim().toLowerCase();if(!Hv.test(r))return At("invalid_email",null,null,e,r);let{session:n,supabase:i}=await C(e),s=await qv(t.orgSelector,e);if(!s)return At("org_required",null,null,e,r);if(s.role!=="admin"&&s.role!=="owner")return At("forbidden",s,null,e,r);let o=await zv(i,n.user.id,s.id,t.workspaceSelector,e);if(!o&&t.workspaceSelector)return At("workspace_not_found",s,null,e,r);let a=await Qv(i,s.id);if(a.failure)return At(a.failure.error,s,o,e,r,a.failure.details);let l=await Yv(i,s.id,a,e);if(!l.ok)return At(l.error,s,o,e,r,l.details);let{data:c,error:u}=await i.rpc("create_org_invite",{p_org_id:s.id,p_email:r,p_role:t.role}),d=c,p=d&&d.ok===false?d.error:void 0;if(u||!d||d.ok!==true)return At(u?.message??p??"invite_failed",s,o,e,r);let h=true;try{let{error:m}=await i.functions.invoke("send-org-invite-email",{body:{invite_id:d.invite_id}});m&&(h=!1);}catch{h=false;}let f={kind:"web",url:ee(s,e,"members"),label:"Open team in Pathrule Web",reason:"preferred"};return {ok:true,invite_id:d.invite_id,email:d.email,role:d.role,email_sent:h,billing_impact:a.billingImpact,billing_adjustment:l.adjustment,organization:Np(s),workspace:jp(o),open_target:f,next_steps:[{label:"Open team in Pathrule Web",url:f.url},...h?[]:[{label:"Retry invite email from Pathrule Web",url:f.url}]]}}function Np(t){return t?{id:t.id,name:t.name,slug:t.slug,role:t.role}:null}function jp(t){return t?{id:t.id,name:t.name}:null}async function qv(t,e){return t?(await we(e)).find(n=>n.id===t||n.slug===t)??null:j(e)}async function zv(t,e,r,n,i){if(!n){let a=await M(i);return a?.organization_id===r?a:null}let{data:s,error:o}=await t.from("workspaces").select("id, organization_id, name, access_mode, git_remote_url, git_owner, git_repo, user_workspace_paths!left(local_root_path, user_id)").eq("organization_id",r).is("archived_at",null);if(o)throw o;for(let a of s??[]){let c=(a.user_workspace_paths??[]).find(d=>d.user_id===e)??null,u={id:a.id,organization_id:a.organization_id,name:a.name,access_mode:a.access_mode,git_remote_url:a.git_remote_url,git_owner:a.git_owner,git_repo:a.git_repo,local_root_path:c?.local_root_path??null,current:false};if(u.id===n||u.name===n)return u}return null}function At(t,e,r,n,i,s){let o=Jv(t,e,n),a=Kv(t,i);return {ok:false,error:t,message:Gv(t),...a?{email_hash:a}:{},organization:Np(e),workspace:jp(r),open_target:o,next_steps:Vv(t,o),...s}}function Jv(t,e,r){if(e){if(t==="free_plan_invites_disabled"||t==="invite_blocked_billing"||t==="billing_update_failed")return {kind:"web",url:ee(e,r,"billing"),label:"Open billing in Pathrule Web",reason:"fallback"};if(t==="subscription_not_invitable"||t==="subscription_frozen")return {kind:"web",url:`${ee(e,r,"billing")}/reactivate`,label:"Open billing reactivation in Pathrule Web",reason:"fallback"};if(t==="paid_seats_required"||t==="seat_limit_reached")return {kind:"web",url:ee(e,r,"billing"),label:"Open billing in Pathrule Web",reason:"fallback"};if(t==="forbidden"||t==="permission_denied"||t==="already_member"||t==="email_already_member"||t==="invite_pending")return {kind:"web",url:ee(e,r,"members"),label:"Open team in Pathrule Web",reason:"fallback"}}}function Kv(t,e){if(e&&!(t!=="rate_limited"&&t!=="invite_resent_cooldown_hit"&&t!=="invite_declined_cooldown"))return createHash("sha256").update(e.trim().toLowerCase()).digest("hex")}function Vv(t,e){if(t==="not_authenticated"||t==="session_expired_security_epoch")return [{label:"Sign in again",command:"pathrule login"}];if(t==="org_required")return [{label:"Choose an organization",command:"pathrule org use <slug-or-id>"}];if(t==="workspace_not_found")return [{label:"List workspaces",command:"pathrule workspace list"}];if(t==="rate_limited"||t==="invite_resent_cooldown_hit"||t==="invite_declined_cooldown")return [{label:"Retry later"}];if(e)return [{label:e.label,url:e.url}]}function Gv(t){switch(t){case "invalid_email":return "Enter a valid email address.";case "invalid_role":return "Role must be admin, editor, or viewer.";case "not_authenticated":return "Pathrule CLI is not signed in.";case "session_expired_security_epoch":return "Your session is stale after a security change. Sign in again.";case "org_required":return "No organization is selected.";case "workspace_not_found":return "Workspace context not found for that organization.";case "forbidden":case "permission_denied":return "Your current role cannot invite teammates to this organization.";case "free_plan_invites_disabled":return "Invites require a paid Pathrule organization plan.";case "subscription_not_invitable":case "subscription_frozen":return "Invites are blocked until billing is reactivated.";case "paid_seats_required":case "seat_limit_reached":return "Pathrule could not automatically add paid seat coverage for this invite.";case "billing_update_failed":return "Billing could not be updated for this invite. Review billing before sending it.";case "rate_limited":return "Rate limit reached, try again later.";case "invite_resent_cooldown_hit":case "invite_declined_cooldown":return "Please wait before inviting this email again.";case "already_member":case "email_already_member":return "That email is already a member of this organization.";case "invite_pending":return "There is already a pending invite for this email.";case "organization_not_found":return "Organization not found.";default:return t.replace(/_/g," ")}}async function Yv(t,e,r,n){if(!r.billingRequirement)return {ok:true,adjustment:{status:r.billingImpact.seat_effect==="paid_extra_available"?"already_covered":"not_needed",target_seats:r.billingImpact.target_active_seats,required_paid_extra_seats:r.billingImpact.required_paid_extra_seats,paid_extra_seats_after:r.billingImpact.current_paid_extra_seats}};let i=r.billingRequirement,s={target_seats:i.targetSeats,required_paid_extra_seats:i.requiredPaidExtraSeats,gift_seat_cap:i.giftSeatCap,current_paid_extra_seats:i.currentPaidExtraSeats},o=null;try{let{data:a,error:l}=await t.functions.invoke("start-paid-seat-checkout",{body:{org_id:e,target_seats:i.targetSeats,return_url_origin:Xv(n)}});if(l)return {ok:!1,error:"billing_update_failed",details:s};o=a;}catch{return {ok:false,error:"billing_update_failed",details:s}}return o?.ok?o.url?{ok:false,error:"paid_seats_required",details:s}:{ok:true,adjustment:{status:o.updated?"updated":"already_covered",target_seats:i.targetSeats,required_paid_extra_seats:i.requiredPaidExtraSeats,paid_extra_seats_after:o.paid_extra_seats}}:{ok:false,error:o?.error??"billing_update_failed",details:s}}function Xv(t){return (t.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"")}function Zv(t){let e=t?.trim().toLowerCase();if(!e||e==="member")return "editor";if(e==="admin"||e==="editor"||e==="viewer")return e;throw new Pe("invalid_invite_role",`Invalid invite role "${t}".`)}function $p(t,e,r){if(!t)throw new Pe(r,e);return t}async function Qv(t,e){let[r,n]=await Promise.all([t.from("organizations").select("plan, subscription_status, trial_status, trial_seat_cap, paid_extra_seats").eq("id",e).maybeSingle(),t.from("organization_members").select("id",{count:"exact",head:true}).eq("organization_id",e)]);if(r.error)throw r.error;if(n.error)throw n.error;let i=El(r.data,n.count??0);return {failure:i.failure?{error:i.failure.error}:null,billingImpact:i.billingImpact,billingRequirement:i.billingRequirement}}Ee();F();var It=class extends Error{constructor(r,n=r){super(n);this.code=r;this.name="CliRefreshError";}code};async function hn(t,e={}){let r=await Di(t),n=await ha(t,r.id),i=await Qa(n,{workspace_id:r.id,include_in_progress:e.includeInProgress});if(!i.ok)throw fa(i.error);return i.data.slice(0,rS(e.limit)).map(s=>Dp(s,r.id,t))}async function ca(t,e,r={}){let n=await Di(t),i=e??await tS(t),s=await ha(t,n.id),o=await el(s,{refresh_id:i,claimed_by:r.claimedBy??"codex"});if(!o.ok)throw fa(o.error);return Mp(o.data,t)}async function ua(t,e,r,n={}){await Di(t);let i=await ha(t),s=await tl(i,{refresh_id:e,status:r,note:n.note,claimed_by:n.claimedBy??"codex"});if(!s.ok)throw fa(s.error);return Mp(s.data,t)}async function da(t,e){let r=await Di(t);if(!e){let l=(await hn(t,{includeInProgress:true,limit:1}))[0];if(!l)throw new It("refresh_not_found","No pending refresh tasks found.");return l}let{supabase:n}=await C(t),{data:i,error:s}=await n.from("suggestion_refreshes").select("id, workspace_id, subject_type, subject_id, formula_id, status, created_at, brief").eq("id",e).eq("workspace_id",r.id).maybeSingle();if(s)throw s;if(!i)throw new It("refresh_not_found",`Refresh ${e} not found.`);let o=i,a=o.brief??{};return Dp({id:o.id,subjectType:o.subject_type,subjectId:o.subject_id,subjectTitle:a.subject?.title??"(unknown)",nodePath:a.subject?.nodePath??"/",formulaId:o.formula_id,humanReason:a.signal?.humanReason??o.formula_id,status:o.status,createdAt:o.created_at,hasProposedPatch:!!a.proposedPatch?.newBody},r.id,t)}function ji(t,e={}){let r=t.open_targets.find(n=>n.kind==="web")??{kind:"web",url:t.url,label:"Open refresh task in Pathrule Web",reason:"preferred"};if(e.forceWeb)return {...r,reason:"forced"};if(e.preferDesktopApp){let n=t.open_targets.find(i=>i.kind==="desktop-app");return n||{...r,reason:"fallback"}}return t.open_targets[0]??r}function pa(t,e,r){return `${(r.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"")}/workspace/${encodeURIComponent(t)}?tab=suggestions&refresh=${encodeURIComponent(e)}`}function eS(t,e){return `pathrule://workspace/${encodeURIComponent(t)}/refresh/${encodeURIComponent(e)}`}async function tS(t){let e=(await hn(t,{limit:1}))[0];if(!e)throw new It("refresh_not_found","No pending refresh tasks found.");return e.id}async function Di(t){let e=await M(t);if(!e)throw new It("workspace_required","No current workspace. Run pathrule workspace use <name-or-id>.");return e}async function ha(t,e=null){let{session:r,supabase:n}=await C(t);return {supabase:n,userId:r.user.id,workspaceId:e,clientId:"codex"}}function Dp(t,e,r){let n=pa(e,t.id,r);return {...t,workspace_id:e,url:n,open_targets:[Lp(e,t.id,r),Up(e,t.id)]}}function Mp(t,e){return {...t,url:pa(t.workspaceId,t.id,e),open_targets:[Lp(t.workspaceId,t.id,e),Up(t.workspaceId,t.id)]}}function Lp(t,e,r){return {kind:"web",url:pa(t,e,r),label:"Open refresh task in Pathrule Web",reason:"preferred"}}function Up(t,e){return {kind:"desktop-app",url:eS(t,e),label:"Open refresh task in Pathrule Desktop",reason:"fallback"}}function rS(t){return !t||!Number.isFinite(t)?20:Math.min(Math.max(Math.trunc(t),1),100)}function fa(t){return new It(t.code,t.message)}K();K();var pS=promisify(execFile),hS=1440*60*1e3;function Wp(t,e=process.env){return join(A(e).home,"cache",t,"bootstrap-v2-brief.json")}async function Bp(t){let e=Wp(t.workspaceId,t.env),r=t.now??new Date;try{let[n,i,s]=await Promise.all([readFile(e,"utf8"),stat(e),Fp(t.localRootPath)]);if(r.getTime()-i.mtimeMs>hS)return {ok:!1,brief:null,cachePath:e,reason:"expired"};let o=JSON.parse(n);return o.schemaVersion!==1||o.workspaceId!==t.workspaceId||o.localRootPath!==t.localRootPath||o.brief.version!==2?{ok:!1,brief:null,cachePath:e,reason:"mismatch"}:o.gitHead!==s?{ok:!1,brief:null,cachePath:e,reason:"git_head_changed"}:{ok:!0,brief:o.brief,cachePath:e}}catch{return {ok:false,brief:null,cachePath:e,reason:"missing"}}}async function ga(t){let e=Wp(t.workspaceId,t.env),r={schemaVersion:1,workspaceId:t.workspaceId,localRootPath:t.localRootPath,gitHead:await Fp(t.localRootPath),cachedAt:new Date().toISOString(),brief:t.brief};await mkdir(dirname(e),{recursive:true});let n=`${e}.tmp`;return await writeFile(n,`${JSON.stringify(r,null,2)}
|
|
185
185
|
`,{encoding:"utf8",mode:O}),await rename(n,e),{cachePath:e}}async function Fp(t){try{let{stdout:e}=await pS("git",["rev-parse","HEAD"],{cwd:t,timeout:1e3});return e.trim()||null}catch{return null}}var fS=/\b(?:packages|apps|src|docs|supabase|types|scripts|config|public|tests?)\/[A-Za-z0-9._/-]+/g;function Ot(t,e="/"){if(!t)return e;let r=t.trim().replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return !r||r==="."?e:`/${r}`}function lr(t){let e=Ot(t),r=e.replace(/^\/+/,"");return r.includes("/")?Ot(r.slice(0,r.lastIndexOf("/"))):e}function Hp(t){let e=new Set;for(let r of t.matchAll(fS)){let n=r[0].replace(/[),.;:]+$/,"");n.length>2&&e.add(n);}return [...e].slice(0,20)}function ma(t,e){let r=t.find(Boolean);return r?lr(r):e}function qp(t,e){let r=new Set,n=[];for(let i of t){let s=Ot(i);if(!r.has(s)&&(r.add(s),n.push(s),n.length>=e))break}return n}var _a=200,wS=1024*1024,yS=8*1024*1024,kS=new Set([".git","node_modules","dist","build","coverage","vendor","archive","archived",".next",".turbo"]),Vp=/\b(setup|development|architecture|testing|security|release|deploy|contributing|conventions?|workflow|migration)\b/i,bS=/\b(must|never|always|required|before merging|run|do not|don't|avoid|ensure)\b/gi,vS=/\b(pnpm|npm|bun|yarn|supabase|vercel|gh|electron-builder|vitest|tsx|tsc)\b/g;async function Gp(t){let e=[],r=await SS(t,e),n=[],i=0;for(let a of r){if(i>=yS){e.push("Documentation scan reached the 8 MB budget.");break}let l=await stat(join(t,a)).catch(()=>null);if(!l||l.size>wS)continue;i+=l.size;let c=await readFile(join(t,a),"utf8").catch(()=>"");if(c.trim())for(let u of ES(c)){let d=RS(a,u);d&&n.push(d);}}let s=n.sort((a,l)=>Jp(l)-Jp(a)).slice(0,40),o=new Set(s.flatMap(a=>a.pathMentions)).size;return {findings:s,candidateMemories:TS(s),candidateRules:AS(s),docsFilesScanned:r.length,filesMentionedByDocs:o,warnings:e}}async function SS(t,e){let r=[];return await n(t,""),r.sort((i,s)=>zp(i)-zp(s)).slice(0,_a);async function n(i,s){if(r.length>=_a)return;let o=await readdir(i,{withFileTypes:true}).catch(()=>[]);for(let a of o){if(r.length>=_a){e.push("Documentation scan reached the 200 file budget.");return}let l=s?`${s}/${a.name}`:a.name;if(a.isDirectory()){if(kS.has(a.name))continue;await n(join(i,a.name),l);continue}a.isFile()&&CS(l)&&r.push(l);}}}function CS(t){let e=basename(t).toLowerCase();return e==="readme.md"||/^readme\..+\.md$/.test(e)||e==="contributing.md"?true:t.startsWith("docs/")&&/\.(md|mdx)$/i.test(t)}function zp(t){let e=basename(t).toLowerCase();return e==="readme.md"?0:e==="contributing.md"?1:t.startsWith("docs/")?2:3}function ES(t){let e=t.split(/\r?\n/),r=[],n={body:""};for(let i of e){let s=i.match(/^(#{1,4})\s+(.+?)\s*#*\s*$/);s?(n.body.trim()&&r.push(n),n={heading:s[2],body:""}):n.body+=`${i}
|
|
186
186
|
`;}return n.body.trim()&&r.push(n),r}function RS(t,e){let r=`${e.heading??""}
|
|
187
|
-
${e.body}`.trim();if(xS(e.heading,r))return null;let n=[...r.matchAll(bS)].length,i=Hp(r),s=[...new Set([...r.matchAll(vS)].map(a=>a[0]))].slice(0,8);return !(e.heading?Vp.test(e.heading):false)&&n===0&&i.length===0&&s.length===0?null:{path:t,heading:e.heading,kind:PS(e.heading??r),summary:IS(r),pathMentions:i,commandMentions:s,imperativeScore:n,excerpt:OS(r)}}function xS(t,e){let r=`${t??""} ${e.slice(0,200)}`.toLowerCase();return /\b(changelog|release notes|history)\b/.test(r)&&/\b\d{4}-\d{2}-\d{2}\b/.test(r)}function PS(t){let e=t.toLowerCase();return e.includes("security")?"security":e.includes("test")?"testing":e.includes("release")||e.includes("deploy")?"release":e.includes("architecture")?"architecture":e.includes("setup")||e.includes("development")||e.includes("contributing")?"workflow":"convention"}function TS(t){return t.filter(e=>e.kind==="architecture"||e.kind==="workflow"||e.pathMentions.length>0).slice(0,18).map(e=>{let r=ma(e.pathMentions,lr(e.path));return {title:Yp("Project note",e),bodyGuidance:`Write a concise memory summarizing ${e.summary}. Include the relevant paths and commands, but do not paste the source document verbatim.`,nodePath:r,confidence:Zp(.55+e.pathMentions.length*.03+e.commandMentions.length*.02),evidence:[Xp(e)]}})}function AS(t){return t.filter(e=>e.imperativeScore>0||e.kind==="security"||e.kind==="testing").slice(0,12).map(e=>({title:Yp("Rule",e),bodyGuidance:`Write a rule from the documented requirement: ${e.summary}. Keep it imperative and scoped to the most specific path.`,nodePath:ma(e.pathMentions,Ot(e.kind==="security"?"/":lr(e.path))),confidence:Zp(.62+e.imperativeScore*.04),evidence:[Xp(e)]}))}function Yp(t,e){let r=e.heading||e.summary;return `${t}: ${r.replace(/[`*_#]/g,"").slice(0,80)}`}function Xp(t){return {kind:"doc",path:t.path,heading:t.heading,excerpt:t.excerpt}}function Jp(t){return t.imperativeScore*3+t.pathMentions.length*2+t.commandMentions.length+(t.heading&&Vp.test(t.heading)?8:0)}function IS(t){return t.replace(/\s+/g," ").replace(/[`*_#>-]/g,"").trim().slice(0,220)}function OS(t){return t.replace(/\s+/g," ").trim().slice(0,280)}function Zp(t){return Math.max(0,Math.min(1,Number(t.toFixed(2))))}var $S=/\b(fix|bug|regression|hotfix|breaking|break|migration|schema|refactor|rewrite|cleanup)\b/i,eh=/\b(breaking|break|migration|schema)\b/i,NS=/\b(fix|bug|regression|hotfix)\b/i,jS=/\b(refactor|rewrite|cleanup)\b/i;function th(t){let e=DS(t),r=new Map;for(let i of e){let s=eh.test(i.subject)?"breaking":NS.test(i.subject)?"fix":jS.test(i.subject)?"refactor":null;if(!s)continue;let o=new Set;for(let a of i.files){o.add(Ot(a)),o.add(lr(a));let l=MS(a);l&&o.add(l);}for(let a of o){let l=r.get(a)??{path:a,fix:0,breaking:0,refactor:0,commits:new Map};l.commits.set(i.hash,i),s==="fix"&&(l.fix+=1),s==="breaking"&&(l.breaking+=1),s==="refactor"&&(l.refactor+=1),r.set(a,l);}}return {findings:[...r.values()].filter(i=>i.commits.size>=3||i.breaking>=1).sort((i,s)=>Qp(s)-Qp(i)).slice(0,15).map(LS),commitsScanned:e.length}}function DS(t){let e=[];for(let r of t.split("")){let n=r.split(/\r?\n/).map(c=>c.trim()).filter(Boolean),i=n[0];if(!i)continue;let[s,o,a]=i.split("");if(!s||!o||!a||!$S.test(a)||/^merge\b/i.test(a))continue;let l=n.slice(1).filter(c=>!c.includes(" => "));l.length<1||l.length>30&&!eh.test(a)||e.push({hash:s,date:o,subject:a,files:l});}return e}function MS(t){let e=t.split("/");return (e[0]==="packages"||e[0]==="apps")&&e[1]?`/${e[0]}/${e[1]}`:e[0]==="supabase"&&e[1]?`/supabase/${e[1]}`:null}function Qp(t){return t.fix*3+t.breaking*5+t.refactor*2+t.commits.size}function LS(t){let e=[...t.commits.values()].sort((i,s)=>s.date.localeCompare(i.date)),r=e[0],n=e.slice(0,4).map(i=>({kind:"commit",commit:i.hash.slice(0,12),path:t.path,excerpt:`${i.date} ${i.subject}`}));return {path:t.path,summary:`${t.path} has ${t.fix} fix, ${t.breaking} breaking/schema, and ${t.refactor} refactor commits in recent history.`,fixCount:t.fix,breakingCount:t.breaking,refactorCount:t.refactor,uniqueCommits:t.commits.size,latestDate:r?.date,evidence:n}}var ih=promisify(execFile);async function sh(t){let e=t.now??new Date;if(!t.force){let r=await Bp({workspaceId:t.workspaceId,localRootPath:t.localRootPath,env:t.env,now:e});if(r.ok&&r.brief)return {ok:true,brief:r.brief,cachePath:r.cachePath,reusedCache:true}}try{let r=await YS(qS(t,e),t.timeoutMs??3e4),n=await ga({workspaceId:t.workspaceId,localRootPath:t.localRootPath,brief:r,env:t.env});return {ok:!0,brief:r,cachePath:n.cachePath,reusedCache:!1}}catch(r){let n=GS(t,e,r instanceof Error?r.message:String(r)),i=await ga({workspaceId:t.workspaceId,localRootPath:t.localRootPath,brief:n,env:t.env}).catch(()=>({cachePath:null}));return {ok:false,brief:n,cachePath:i.cachePath,reusedCache:false,error:n.warnings[0]}}}async function qS(t,e){let r=[],[n,i,s,o,a]=await Promise.all([zS(t.supabase,t.workspaceId),Gp(t.localRootPath),JS(t.localRootPath,r),VS(t.localRootPath,r),KS(t.localRootPath,r)]);r.push(...i.warnings);let l=th(s),c=a?ps(a):[],u=ds(o).map(w=>({title:w.title,summary:w.content})),d=u.map(w=>({title:w.title,bodyGuidance:`Write a short memory noting that ${w.summary.toLowerCase()}`,nodePath:"/",confidence:.72,evidence:[{kind:"stack",excerpt:w.summary}]})),p=l.findings.map(w=>({title:`Risk hotspot: ${w.path}`,bodyGuidance:`Write a memory explaining the risk pattern for ${w.path}: ${w.summary} Include the kinds of changes that should be reviewed together.`,nodePath:w.path,confidence:Math.min(.95,.6+w.uniqueCommits*.04+w.breakingCount*.08),evidence:w.evidence})),h=rh([...i.candidateMemories,...p,...d]),f=rh(i.candidateRules);h=nh(h,n.titles).slice(0,15),f=nh(f,n.titles).slice(0,8);let m=n.memoryCount+n.ruleCount>=8;m&&(h=[],f=[],r.push("Workspace already has meaningful setup content; Bootstrap v2 will avoid duplicate starter guidance."));let _=qp([...f.map(w=>w.nodePath),...h.map(w=>w.nodePath),...i.findings.flatMap(w=>[w.path,...w.pathMentions]),...l.findings.map(w=>w.path)],20),b=m?"Bootstrap v2 found existing Pathrule setup content. Use pathrule_get_context for task-specific context instead of writing duplicate starter memories or rules.":`Bootstrap v2 prepared ${h.length} memory candidates and ${f.length} rule candidates from ${i.docsFilesScanned} docs files and ${l.commitsScanned} risky commits.`;return {version:2,workspaceId:t.workspaceId,localRootPath:t.localRootPath,generatedAt:e.toISOString(),summary:b,stackSignals:u,documentationFindings:i.findings,commitWisdom:l.findings,candidateMemories:h,candidateRules:f,candidateSkills:[],suggestedOrder:_,coverage:{docsFilesScanned:i.docsFilesScanned,commitsScanned:l.commitsScanned,filesMentionedByDocs:i.filesMentionedByDocs,coChangePairsAvailable:c.length},warnings:r,alreadyBootstrapped:m}}async function zS(t,e){if(!t)return {memoryCount:0,ruleCount:0,skillCount:0,titles:new Set};let[r,n,i]=await Promise.all([t.from("memories").select("title",{count:"exact"}).eq("workspace_id",e).limit(200),t.from("rules").select("name",{count:"exact"}).eq("workspace_id",e).limit(200),t.from("skills").select("name",{count:"exact"}).eq("workspace_id",e).limit(50)]),s=new Set;for(let o of r.data??[])o.title&&s.add(hn(o.title));for(let o of n.data??[])o.name&&s.add(hn(o.name));for(let o of i.data??[])o.name&&s.add(hn(o.name));return {memoryCount:r.count??s.size,ruleCount:n.count??0,skillCount:i.count??0,titles:s}}async function JS(t,e){try{let{stdout:r}=await ih("git",["log","--date=short","--format=%x1e%H%x1f%ad%x1f%s","--name-only","-n","5000"],{cwd:t,maxBuffer:52428800,timeout:2e4});return r}catch{return e.push("Git commit wisdom skipped; repository history was unavailable."),""}}async function KS(t,e){try{let{stdout:r}=await ih("git",["log","--name-only","--pretty=format:---","-n","10000"],{cwd:t,maxBuffer:52428800,timeout:2e4});return r}catch{return e.push("Git co-change scan skipped; repository history was unavailable."),""}}async function VS(t,e){let r=[];async function n(i,s){if(s>4||r.length>5e3)return;let o=await readdir(i,{withFileTypes:true}).catch(()=>[]);for(let a of o){if(a.name===".git"||a.name==="node_modules"||a.name==="dist")continue;let l=join(i,a.name);a.isDirectory()?await n(l,s+1):a.isFile()&&r.push(relative(t,l).replace(/\\/g,"/"));}}return await n(t,0).catch(()=>e.push("Stack detection skipped; file tree was unavailable.")),r}function rh(t){let e=new Map;for(let r of t){let n=`${r.nodePath}:${hn(r.title)}`,i=e.get(n);(!i||r.confidence>i.confidence)&&e.set(n,r);}return [...e.values()].sort((r,n)=>n.confidence-r.confidence)}function nh(t,e){return t.filter(r=>!e.has(hn(r.title)))}function hn(t){return t.toLocaleLowerCase("en-US").replace(/[^a-z0-9]+/g," ").trim()}function GS(t,e,r){return {version:2,workspaceId:t.workspaceId,localRootPath:t.localRootPath,generatedAt:e.toISOString(),summary:"Bootstrap v2 could not complete the local scan. Use the fallback setup prompt.",stackSignals:[],documentationFindings:[],commitWisdom:[],candidateMemories:[],candidateRules:[],candidateSkills:[],suggestedOrder:[],coverage:{docsFilesScanned:0,commitsScanned:0,filesMentionedByDocs:0,coChangePairsAvailable:0},warnings:[r]}}function YS(t,e){return new Promise((r,n)=>{let i=setTimeout(()=>n(new Error("Bootstrap v2 scan timed out.")),e);t.then(s=>{clearTimeout(i),r(s);},s=>{clearTimeout(i),n(s);});})}F();K();oi();F();async function lh(t,e,r=fetch){if(!e.gitRemoteUrl)return {status:"skipped",error:"missing_git_remote"};try{let{session:n,supabase:i}=await C(t),{data:s,error:o}=await i.from("beta_platform_invites").select("id").eq("claimed_user_id",n.user.id).eq("status","claimed").order("claimed_at",{ascending:!1}).limit(1);if(o)return {status:"skipped",error:"invite_lookup_unavailable"};let a=(s??[])[0]??null;if(!a)return {status:"skipped",error:"no_claimed_beta_invite"};let l=Se(t),c=await iC(t),u=await r(`${l.supabaseUrl}/functions/v1/process-beta-activation`,{method:"POST",headers:{"content-type":"application/json",apikey:l.supabaseAnonKey,Authorization:`Bearer ${n.access_token}`},body:JSON.stringify({invite_id:a.id,workspace_id:e.workspaceId,git_remote_url:e.gitRemoteUrl,machine_id:c,runtime_source:e.runtimeSource})}),d=await u.json().catch(()=>null);return !u.ok||!d?.status?{status:"skipped",error:"activation_unavailable"}:{status:d.status,credit_cents:ah(d.credit_cents),founder_bonus_cents:ah(d.founder_bonus_cents)}}catch{return {status:"skipped",error:"activation_unavailable"}}}async function iC(t){let e=join(A(t).home,"machine-install.json");try{let n=JSON.parse(await readFile(e,"utf8"));if(typeof n.machine_id=="string"&&n.machine_id.length>=16)return n.machine_id}catch{}let r=`cli_${randomUUID()}`;return await sC(e,{schema_version:1,machine_id:r}),r}async function sC(t,e){let r=dirname(t);await mkdir(r,{recursive:true,mode:D}),await chmod(r,D).catch(()=>{});let n=`${t}.tmp`;await writeFile(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:O}),await chmod(n,O).catch(()=>{}),await rename(n,t);}function ah(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}Ee();var uC=promisify(execFile);async function Mi(t,e){let r=await j(e);if(!r)return {cwd:t,organization:null,candidates:[],recommended_action:"select_org"};let[n,i,s]=await Promise.all([Re(e),mh(t),gC(t,e)]),o=hC(t,r,n,i,s);return {cwd:t,organization:r,candidates:o,recommended_action:o.length===0?"create_workspace":o[0]?.confidence==="exact"||o[0]?.confidence==="high"?"attach_existing":"choose_workspace"}}async function cr(t,e,r,n={yes:false}){let i=pC(t);if(!i.shouldApply)return {plan:await Mi(e,r),applied:false,org_selected:null,workspace_action:"none",workspace:null,install:null,sync:null,beta_activation:null,bootstrap_v2:null};if(i.bootstrapRerun){let f=await M(r);if(!f?.id)throw new Error("workspace_required");let m=await dh(f.id,e,r,true);return {plan:await Mi(e,r),applied:true,org_selected:null,workspace_action:"none",workspace:f,install:null,sync:null,beta_activation:null,bootstrap_v2:m}}if(!n.yes)throw new Error("setup_requires_yes");let s=null;if(i.org){let{useCliOrg:f}=await Promise.resolve().then(()=>(Ee(),Nu));s=(await f(i.org,r)).id;}let o=await Mi(e,r),a="none",l=null;if(i.createWorkspace){let f=await ae("create_workspace",r);if(!f.allowed)throw new Error(f.blocking_reason??"preflight_blocked");l=await yt(i.workspaceName??basename(e),e,r),a="created";}else i.workspaceSelector?(l=await xe(i.workspaceSelector,e,r),a="attached"):o.recommended_action==="attach_existing"&&o.candidates[0]?(l=await xe(o.candidates[0].workspace_id,e,r),a="attached"):i.selectCurrentWorkspace&&(l=await Kr(i.selectCurrentWorkspace,r),a="selected");o=await Mi(e,r);let c=i.target?await Ye(i.target,r):null,u=a==="attached"||a==="created"?await De(r,e):null,d=dC(l),p=u?.ok&&d&&(a==="attached"||a==="created")?await dh(d,e,r,false):null,h=u?.ok&&(a==="attached"||a==="created")?await lh(r,{workspaceId:d,gitRemoteUrl:await mh(e),runtimeSource:"cli"}):null;return {plan:o,applied:true,org_selected:s,workspace_action:a,workspace:l,install:c,sync:u,beta_activation:h,bootstrap_v2:p}}async function dh(t,e,r,n){let{supabase:i}=await C(r),s=await sh({workspaceId:t,localRootPath:e,supabase:i,env:r,force:n});return {ok:s.ok,reused_cache:s.reusedCache,cache_path:s.cachePath,candidate_counts:{memories:s.brief.candidateMemories.length,rules:s.brief.candidateRules.length,skills:s.brief.candidateSkills.length},coverage:s.brief.coverage,summary:s.brief.summary,warnings:s.brief.warnings}}function dC(t){if(!t||typeof t!="object")return null;let e=t.id;if(typeof e=="string")return e;let r=t.workspace?.id;return typeof r=="string"?r:null}function pC(t){let e={org:null,workspaceSelector:null,workspaceName:null,createWorkspace:false,selectCurrentWorkspace:null,target:null,bootstrapRerun:false},r=false,n=false;for(let i=0;i<t.length;i+=1){let s=t[i],o=()=>{let a=t[i+1];if(!a||a.startsWith("--"))throw new Error(`missing_value:${s}`);return i+=1,a};if(s==="bootstrap"){if(r)throw new Error("unknown_setup_option:bootstrap");r=true;}else if(s==="--rerun"&&r)n=true;else if(s==="--org")e.org=o();else if(s==="--workspace"||s==="--workspace-id")e.workspaceSelector=o();else if(s==="--workspace-name")e.workspaceName=o();else if(s==="--create-workspace")e.createWorkspace=true;else if(s==="--select-workspace")e.selectCurrentWorkspace=o();else if(s==="--target")e.target=o();else throw new Error(`unknown_setup_option:${s}`)}if(r&&!n)throw new Error("missing_value:--rerun");return e.bootstrapRerun=r&&n,{...e,shouldApply:e.org!==null||e.workspaceSelector!==null||e.workspaceName!==null||e.createWorkspace||e.selectCurrentWorkspace!==null||e.target!==null||e.bootstrapRerun}}function hC(t,e,r,n,i){let s=fh(basename(t)),o=[],a=new Set,l=c=>{a.has(c.workspace_id)||(a.add(c.workspace_id),o.push(c));};for(let c of r){if(c.local_root_path===t){l(fn("cwd_mapping",c,e,"exact",false,"Exact local path mapping."));continue}if(n&&fC(c,n)){l(fn("git_remote",c,e,"high",true,"Git remote matches workspace metadata."));continue}if(i.has(c.id)){l(fn("hook_cache",c,e,"high",true,"Existing hook cache points at this folder."));continue}let u=fh(c.name);if(u===s){l(fn("name_match",c,e,"medium",true,"Folder name matches workspace name."));continue}mC(u,s)&&l(fn("name_match",c,e,"low",true,"Folder name is similar to workspace name."));}return o.sort((c,u)=>{let d=ph(u.confidence)-ph(c.confidence);return d!==0?d:hh(u.source)-hh(c.source)}),o.map((c,u)=>({...c,recommended:u===0}))}function fn(t,e,r,n,i,s){return {source:t,workspace_id:e.id,workspace_name:e.name,org_id:r.id,org_name:r.name,org_slug:r.slug,confidence:n,recommended:false,requires_confirmation:i,reason:s}}function ph(t){return {exact:4,high:3,medium:2,low:1}[t]}function hh(t){return {cwd_mapping:6,git_remote:5,hook_cache:4,companion_file:3,name_match:2,manual:1}[t]}function fC(t,e){let r=t;return r.git_remote_url&&ya(r.git_remote_url)===ya(e)?true:!r.git_owner||!r.git_repo?false:ya(e).endsWith(`/${r.git_owner}/${r.git_repo}`.toLocaleLowerCase("en-US"))}async function mh(t){try{let{stdout:e}=await uC("git",["config","--get","remote.origin.url"],{cwd:t,timeout:1e3});return e.trim()||null}catch{return null}}function ya(t){return t.trim().replace(/^git@([^:]+):/,"https://$1/").replace(/^https?:\/\//,"").replace(/\.git$/,"").toLocaleLowerCase("en-US")}async function gC(t,e){let r=new Set,n=join(A(e).home,"cache"),i;try{i=await readdir(n);}catch{return r}let s=resolve(t);return await Promise.all(i.map(async o=>{try{let a=await readFile(join(n,o,"hook-index.json"),"utf8"),l=JSON.parse(a);if(!l.workspace_id||!l.workspace_root)return;let c=resolve(l.workspace_root);(s===c||s.startsWith(`${c}/`))&&r.add(l.workspace_id);}catch{}})),r}function fh(t){return t.toLocaleLowerCase("en-US").replace(/[^a-z0-9]+/g," ").trim()}function mC(t,e){return !t||!e?false:t.includes(e)||e.includes(t)?true:_C(t,e)<=Math.max(2,Math.floor(Math.max(t.length,e.length)*.25))}function _C(t,e){let r=Array.from({length:e.length+1},(n,i)=>i);for(let n=1;n<=t.length;n+=1){let i=n,s=n-1;for(let o=1;o<=e.length;o+=1){let a=r[o]??0,l=t[n-1]===e[o-1]?0:1;r[o]=Math.min(a+1,i+1,s+l),i=r[o]??0,s=a;}r[0]=n;}return r[e.length]??0}F();Ee();async function ka(t,e){let r=await wC(t,e);if(!r)throw new Error("org_required");let{supabase:n}=await C(t),[i,s,o]=await Promise.all([n.from("organization_members").select("id, user_id, role, joined_at").eq("organization_id",r.id).order("joined_at",{ascending:true}),n.rpc("get_org_member_profiles",{p_org_id:r.id}),n.from("organization_invites").select("id, email, role, status, created_at, expires_at").eq("organization_id",r.id).eq("status","pending").order("created_at",{ascending:false})]);if(i.error)throw i.error;if(s.error)throw s.error;if(o.error)throw o.error;let a=new Map,l=s.data??[];for(let d of l)a.set(d.user_id,d);let c=(i.data??[]).map(d=>{let p=a.get(d.user_id);return {id:d.id,user_id:d.user_id,role:d.role,joined_at:d.joined_at,email:p?.email??null,full_name:wl(p?.full_name,"profile"),avatar_url:yl(p?.avatar_url),last_sign_in_at:p?.last_sign_in_at??null}}),u=(o.data??[]).map(d=>({id:d.id,email:d.email,role:d.role,status:d.status,created_at:d.created_at,expires_at:d.expires_at}));return {organization:{id:r.id,name:r.name,slug:r.slug,role:r.role},members:c,invites:u,open_target:{kind:"web",url:ee(r,t,"members"),label:"Open team in Pathrule Web",reason:"preferred"}}}async function wC(t,e){return e?(await _e(t)).find(n=>n.id===e||n.slug===e)??null:j(t)}Ke();qr();async function Li(t,e,r){let n=await wt("update.policy",e);if(n.key!=="update.policy")throw new Error("invalid_update_policy_state");let i=`${(e.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"")}/cli/versions.json`,s=e.PATHRULE_PROTOCOL_VERSION??pl;if(n.value==="manual")return {checked:false,policy:n.value,current_version:t,current_protocol_version:s,latest_version:null,min_supported_protocol_version:null,protocol_compatible:true,update_available:false,upgrade_command:null,reason:"manual_policy",url:i};try{let o=await r(i,{headers:{"user-agent":`pathrule-cli/${t}`}});if(!o.ok)throw new Error(`http_${o.status}`);let a=await o.json(),l=a.latest_version??a.latest??null,c=a.min_supported_protocol_version??null;return {checked:!0,policy:n.value,current_version:t,current_protocol_version:s,latest_version:l,min_supported_protocol_version:c,protocol_compatible:kC(s,c),update_available:l?l!==t:!1,upgrade_command:a.upgrade_command??yC(a.channels),url:i}}catch{return {checked:false,policy:n.value,current_version:t,current_protocol_version:s,latest_version:null,min_supported_protocol_version:null,protocol_compatible:true,update_available:false,upgrade_command:null,reason:"request_failed",url:i}}}async function wh(t,e,r){let n=await wt("update.policy",e);if(n.key!=="update.policy")throw new Error("invalid_update_policy_state");if(n.value==="manual")return null;let i=await Ce(e).catch(()=>null);if(!i)return null;let s=await ne(i.session.user.id,e);if(s.last_update_check_at){let l=new Date(s.last_update_check_at).getTime();if(Number.isFinite(l)&&Date.now()-l<1440*60*1e3)return null}await ie(i.session.user.id,{last_update_check_at:new Date().toISOString()},e);let o=await Li(t,e,r);if(!o.checked||!o.update_available)return null;let a=o.upgrade_command?` Run: ${o.upgrade_command}`:"";return `Pathrule CLI ${o.latest_version} is available.${a}`}function yC(t){return t?t.brew??t.npm??t.standalone??null:null}function kC(t,e){if(!e)return true;let r=_h(t),n=_h(e);return r&&n?bC(r,n)>=0:t===e}function _h(t){let e=t.match(/^v?(\d+)\.(\d+)\.(\d+)$/);return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function bC(t,e){for(let r=0;r<3;r+=1){let n=(t[r]??0)-(e[r]??0);if(n!==0)return n}return 0}F();Ee();async function ba(t){let{session:e,supabase:r}=await C(t.env),[n,i]=await Promise.all([j(t.env),M(t.env)]);if(!n)throw new Error("org_required");if(!i)throw new Error("workspace_required");let s=vC(n.plan),[o,a,l,c,u,d,p,h]=await Promise.all([SC(r,i.id),gn(r.from("nodes").select("id",{count:"exact",head:true}).eq("workspace_id",i.id)),gn(r.from("memories").select("id",{count:"exact",head:true}).eq("workspace_id",i.id)),gn(r.from("rules").select("id",{count:"exact",head:true}).eq("workspace_id",i.id)),gn(r.from("skills").select("id",{count:"exact",head:true}).eq("workspace_id",i.id)),gn(r.from("workspaces").select("id",{count:"exact",head:true}).eq("organization_id",n.id).is("archived_at",null)),CC(r,i.id),Rt(t.env,e.user.id,i.id,i.local_root_path)]);return {organization:{id:n.id,name:n.name,slug:n.slug,plan:s,role:n.role,subscription_status:n.subscription_status,trial_status:n.trial_status},workspace:i,local_status:{current_folder:t.cwd,attached_root:i.local_root_path,current_folder_attached:i.local_root_path===t.cwd,attached_elsewhere:i.local_root_path!==null&&i.local_root_path!==t.cwd},cloud_tree:{root_node_present:o,nodes:a,memories:l,rules:c,skills:u},capacity:{plan:s,workspaces:{used:d,limit:Fe[s].workspaces},memories:{used:l,limit:Fe[s].memories},rules:{used:c,limit:Fe[s].rules}},active_clients:h.map(f=>RC(f)),recent_activity:p}}function vC(t){return Object.hasOwn(Fe,t)?t:"free"}async function SC(t,e){let{data:r,error:n}=await t.from("nodes").select("id").eq("workspace_id",e).eq("relative_path","/").is("parent_id",null).maybeSingle();if(n)throw n;return !!r?.id}async function gn(t){let{count:e,error:r}=await t;if(r)throw new Error(r.message);return e??0}async function CC(t,e){let{data:r,error:n}=await t.from("activity_logs").select("created_at, domain, action, scope, node_path, task_summary, files_touched").eq("workspace_id",e).eq("status","active").order("created_at",{ascending:false}).limit(5);if(n)throw n;return (r??[]).map(i=>({created_at:String(i.created_at),domain:String(i.domain??"unknown"),action:String(i.action??"unknown"),scope:String(i.scope??"project"),node_path:String(i.node_path??"/"),task_summary:String(i.task_summary??""),files_touched_total:EC(i.files_touched)}))}function EC(t){if(!t||typeof t!="object")return 0;let e=t.total;return typeof e=="number"&&Number.isFinite(e)?e:0}function RC(t){let e=t.client;return {client:e,label:U[e]?.label??e,active:t.active,selected:t.selected,detected:t.markers.includes("workspace_marker_detected"),machine_installed:t.machineInstalled,machine_config_exists:t.machineConfigExists,machine_config_path:t.machineConfigPath}}var LC=createRequire(import.meta.url),Ue=LC("../package.json"),Bi=promisify(execFile),X=class extends Error{constructor(r,n){super(n);this.code=r;this.name="CliContentUsageError";}code},UC=`${H.cli}
|
|
187
|
+
${e.body}`.trim();if(xS(e.heading,r))return null;let n=[...r.matchAll(bS)].length,i=Hp(r),s=[...new Set([...r.matchAll(vS)].map(a=>a[0]))].slice(0,8);return !(e.heading?Vp.test(e.heading):false)&&n===0&&i.length===0&&s.length===0?null:{path:t,heading:e.heading,kind:PS(e.heading??r),summary:IS(r),pathMentions:i,commandMentions:s,imperativeScore:n,excerpt:OS(r)}}function xS(t,e){let r=`${t??""} ${e.slice(0,200)}`.toLowerCase();return /\b(changelog|release notes|history)\b/.test(r)&&/\b\d{4}-\d{2}-\d{2}\b/.test(r)}function PS(t){let e=t.toLowerCase();return e.includes("security")?"security":e.includes("test")?"testing":e.includes("release")||e.includes("deploy")?"release":e.includes("architecture")?"architecture":e.includes("setup")||e.includes("development")||e.includes("contributing")?"workflow":"convention"}function TS(t){return t.filter(e=>e.kind==="architecture"||e.kind==="workflow"||e.pathMentions.length>0).slice(0,18).map(e=>{let r=ma(e.pathMentions,lr(e.path));return {title:Yp("Project note",e),bodyGuidance:`Write a concise memory summarizing ${e.summary}. Include the relevant paths and commands, but do not paste the source document verbatim.`,nodePath:r,confidence:Zp(.55+e.pathMentions.length*.03+e.commandMentions.length*.02),evidence:[Xp(e)]}})}function AS(t){return t.filter(e=>e.imperativeScore>0||e.kind==="security"||e.kind==="testing").slice(0,12).map(e=>({title:Yp("Rule",e),bodyGuidance:`Write a rule from the documented requirement: ${e.summary}. Keep it imperative and scoped to the most specific path.`,nodePath:ma(e.pathMentions,Ot(e.kind==="security"?"/":lr(e.path))),confidence:Zp(.62+e.imperativeScore*.04),evidence:[Xp(e)]}))}function Yp(t,e){let r=e.heading||e.summary;return `${t}: ${r.replace(/[`*_#]/g,"").slice(0,80)}`}function Xp(t){return {kind:"doc",path:t.path,heading:t.heading,excerpt:t.excerpt}}function Jp(t){return t.imperativeScore*3+t.pathMentions.length*2+t.commandMentions.length+(t.heading&&Vp.test(t.heading)?8:0)}function IS(t){return t.replace(/\s+/g," ").replace(/[`*_#>-]/g,"").trim().slice(0,220)}function OS(t){return t.replace(/\s+/g," ").trim().slice(0,280)}function Zp(t){return Math.max(0,Math.min(1,Number(t.toFixed(2))))}var $S=/\b(fix|bug|regression|hotfix|breaking|break|migration|schema|refactor|rewrite|cleanup)\b/i,eh=/\b(breaking|break|migration|schema)\b/i,NS=/\b(fix|bug|regression|hotfix)\b/i,jS=/\b(refactor|rewrite|cleanup)\b/i;function th(t){let e=DS(t),r=new Map;for(let i of e){let s=eh.test(i.subject)?"breaking":NS.test(i.subject)?"fix":jS.test(i.subject)?"refactor":null;if(!s)continue;let o=new Set;for(let a of i.files){o.add(Ot(a)),o.add(lr(a));let l=MS(a);l&&o.add(l);}for(let a of o){let l=r.get(a)??{path:a,fix:0,breaking:0,refactor:0,commits:new Map};l.commits.set(i.hash,i),s==="fix"&&(l.fix+=1),s==="breaking"&&(l.breaking+=1),s==="refactor"&&(l.refactor+=1),r.set(a,l);}}return {findings:[...r.values()].filter(i=>i.commits.size>=3||i.breaking>=1).sort((i,s)=>Qp(s)-Qp(i)).slice(0,15).map(LS),commitsScanned:e.length}}function DS(t){let e=[];for(let r of t.split("")){let n=r.split(/\r?\n/).map(c=>c.trim()).filter(Boolean),i=n[0];if(!i)continue;let[s,o,a]=i.split("");if(!s||!o||!a||!$S.test(a)||/^merge\b/i.test(a))continue;let l=n.slice(1).filter(c=>!c.includes(" => "));l.length<1||l.length>30&&!eh.test(a)||e.push({hash:s,date:o,subject:a,files:l});}return e}function MS(t){let e=t.split("/");return (e[0]==="packages"||e[0]==="apps")&&e[1]?`/${e[0]}/${e[1]}`:e[0]==="supabase"&&e[1]?`/supabase/${e[1]}`:null}function Qp(t){return t.fix*3+t.breaking*5+t.refactor*2+t.commits.size}function LS(t){let e=[...t.commits.values()].sort((i,s)=>s.date.localeCompare(i.date)),r=e[0],n=e.slice(0,4).map(i=>({kind:"commit",commit:i.hash.slice(0,12),path:t.path,excerpt:`${i.date} ${i.subject}`}));return {path:t.path,summary:`${t.path} has ${t.fix} fix, ${t.breaking} breaking/schema, and ${t.refactor} refactor commits in recent history.`,fixCount:t.fix,breakingCount:t.breaking,refactorCount:t.refactor,uniqueCommits:t.commits.size,latestDate:r?.date,evidence:n}}var ih=promisify(execFile);async function sh(t){let e=t.now??new Date;if(!t.force){let r=await Bp({workspaceId:t.workspaceId,localRootPath:t.localRootPath,env:t.env,now:e});if(r.ok&&r.brief)return {ok:true,brief:r.brief,cachePath:r.cachePath,reusedCache:true}}try{let r=await YS(qS(t,e),t.timeoutMs??3e4),n=await ga({workspaceId:t.workspaceId,localRootPath:t.localRootPath,brief:r,env:t.env});return {ok:!0,brief:r,cachePath:n.cachePath,reusedCache:!1}}catch(r){let n=GS(t,e,r instanceof Error?r.message:String(r)),i=await ga({workspaceId:t.workspaceId,localRootPath:t.localRootPath,brief:n,env:t.env}).catch(()=>({cachePath:null}));return {ok:false,brief:n,cachePath:i.cachePath,reusedCache:false,error:n.warnings[0]}}}async function qS(t,e){let r=[],[n,i,s,o,a]=await Promise.all([zS(t.supabase,t.workspaceId),Gp(t.localRootPath),JS(t.localRootPath,r),VS(t.localRootPath,r),KS(t.localRootPath,r)]);r.push(...i.warnings);let l=th(s),c=a?ps(a):[],u=ds(o).map(w=>({title:w.title,summary:w.content})),d=u.map(w=>({title:w.title,bodyGuidance:`Write a short memory noting that ${w.summary.toLowerCase()}`,nodePath:"/",confidence:.72,evidence:[{kind:"stack",excerpt:w.summary}]})),p=l.findings.map(w=>({title:`Risk hotspot: ${w.path}`,bodyGuidance:`Write a memory explaining the risk pattern for ${w.path}: ${w.summary} Include the kinds of changes that should be reviewed together.`,nodePath:w.path,confidence:Math.min(.95,.6+w.uniqueCommits*.04+w.breakingCount*.08),evidence:w.evidence})),h=rh([...i.candidateMemories,...p,...d]),f=rh(i.candidateRules);h=nh(h,n.titles).slice(0,15),f=nh(f,n.titles).slice(0,8);let m=n.memoryCount+n.ruleCount>=8;m&&(h=[],f=[],r.push("Workspace already has meaningful setup content; Bootstrap v2 will avoid duplicate starter guidance."));let _=qp([...f.map(w=>w.nodePath),...h.map(w=>w.nodePath),...i.findings.flatMap(w=>[w.path,...w.pathMentions]),...l.findings.map(w=>w.path)],20),b=m?"Bootstrap v2 found existing Pathrule setup content. Use pathrule_get_context for task-specific context instead of writing duplicate starter memories or rules.":`Bootstrap v2 prepared ${h.length} memory candidates and ${f.length} rule candidates from ${i.docsFilesScanned} docs files and ${l.commitsScanned} risky commits.`;return {version:2,workspaceId:t.workspaceId,localRootPath:t.localRootPath,generatedAt:e.toISOString(),summary:b,stackSignals:u,documentationFindings:i.findings,commitWisdom:l.findings,candidateMemories:h,candidateRules:f,candidateSkills:[],suggestedOrder:_,coverage:{docsFilesScanned:i.docsFilesScanned,commitsScanned:l.commitsScanned,filesMentionedByDocs:i.filesMentionedByDocs,coChangePairsAvailable:c.length},warnings:r,alreadyBootstrapped:m}}async function zS(t,e){if(!t)return {memoryCount:0,ruleCount:0,skillCount:0,titles:new Set};let[r,n,i]=await Promise.all([t.from("memories").select("title",{count:"exact"}).eq("workspace_id",e).limit(200),t.from("rules").select("name",{count:"exact"}).eq("workspace_id",e).limit(200),t.from("skills").select("name",{count:"exact"}).eq("workspace_id",e).limit(50)]),s=new Set;for(let o of r.data??[])o.title&&s.add(fn(o.title));for(let o of n.data??[])o.name&&s.add(fn(o.name));for(let o of i.data??[])o.name&&s.add(fn(o.name));return {memoryCount:r.count??s.size,ruleCount:n.count??0,skillCount:i.count??0,titles:s}}async function JS(t,e){try{let{stdout:r}=await ih("git",["log","--date=short","--format=%x1e%H%x1f%ad%x1f%s","--name-only","-n","5000"],{cwd:t,maxBuffer:52428800,timeout:2e4});return r}catch{return e.push("Git commit wisdom skipped; repository history was unavailable."),""}}async function KS(t,e){try{let{stdout:r}=await ih("git",["log","--name-only","--pretty=format:---","-n","10000"],{cwd:t,maxBuffer:52428800,timeout:2e4});return r}catch{return e.push("Git co-change scan skipped; repository history was unavailable."),""}}async function VS(t,e){let r=[];async function n(i,s){if(s>4||r.length>5e3)return;let o=await readdir(i,{withFileTypes:true}).catch(()=>[]);for(let a of o){if(a.name===".git"||a.name==="node_modules"||a.name==="dist")continue;let l=join(i,a.name);a.isDirectory()?await n(l,s+1):a.isFile()&&r.push(relative(t,l).replace(/\\/g,"/"));}}return await n(t,0).catch(()=>e.push("Stack detection skipped; file tree was unavailable.")),r}function rh(t){let e=new Map;for(let r of t){let n=`${r.nodePath}:${fn(r.title)}`,i=e.get(n);(!i||r.confidence>i.confidence)&&e.set(n,r);}return [...e.values()].sort((r,n)=>n.confidence-r.confidence)}function nh(t,e){return t.filter(r=>!e.has(fn(r.title)))}function fn(t){return t.toLocaleLowerCase("en-US").replace(/[^a-z0-9]+/g," ").trim()}function GS(t,e,r){return {version:2,workspaceId:t.workspaceId,localRootPath:t.localRootPath,generatedAt:e.toISOString(),summary:"Bootstrap v2 could not complete the local scan. Use the fallback setup prompt.",stackSignals:[],documentationFindings:[],commitWisdom:[],candidateMemories:[],candidateRules:[],candidateSkills:[],suggestedOrder:[],coverage:{docsFilesScanned:0,commitsScanned:0,filesMentionedByDocs:0,coChangePairsAvailable:0},warnings:[r]}}function YS(t,e){return new Promise((r,n)=>{let i=setTimeout(()=>n(new Error("Bootstrap v2 scan timed out.")),e);t.then(s=>{clearTimeout(i),r(s);},s=>{clearTimeout(i),n(s);});})}F();K();oi();F();async function lh(t,e,r=fetch){if(!e.gitRemoteUrl)return {status:"skipped",error:"missing_git_remote"};try{let{session:n,supabase:i}=await C(t),{data:s,error:o}=await i.from("beta_platform_invites").select("id").eq("claimed_user_id",n.user.id).eq("status","claimed").order("claimed_at",{ascending:!1}).limit(1);if(o)return {status:"skipped",error:"invite_lookup_unavailable"};let a=(s??[])[0]??null;if(!a)return {status:"skipped",error:"no_claimed_beta_invite"};let l=pe(t),c=await iC(t),u=await r(`${l.supabaseUrl}/functions/v1/process-beta-activation`,{method:"POST",headers:{"content-type":"application/json",apikey:l.supabaseAnonKey,Authorization:`Bearer ${n.access_token}`},body:JSON.stringify({invite_id:a.id,workspace_id:e.workspaceId,git_remote_url:e.gitRemoteUrl,machine_id:c,runtime_source:e.runtimeSource})}),d=await u.json().catch(()=>null);return !u.ok||!d?.status?{status:"skipped",error:"activation_unavailable"}:{status:d.status,credit_cents:ah(d.credit_cents),founder_bonus_cents:ah(d.founder_bonus_cents)}}catch{return {status:"skipped",error:"activation_unavailable"}}}async function iC(t){let e=join(A(t).home,"machine-install.json");try{let n=JSON.parse(await readFile(e,"utf8"));if(typeof n.machine_id=="string"&&n.machine_id.length>=16)return n.machine_id}catch{}let r=`cli_${randomUUID()}`;return await sC(e,{schema_version:1,machine_id:r}),r}async function sC(t,e){let r=dirname(t);await mkdir(r,{recursive:true,mode:D}),await chmod(r,D).catch(()=>{});let n=`${t}.tmp`;await writeFile(n,JSON.stringify(e,null,2),{encoding:"utf8",mode:O}),await chmod(n,O).catch(()=>{}),await rename(n,t);}function ah(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}Ee();var uC=promisify(execFile);async function Mi(t,e){let r=await j(e);if(!r)return {cwd:t,organization:null,candidates:[],recommended_action:"select_org"};let[n,i,s]=await Promise.all([Re(e),mh(t),gC(t,e)]),o=hC(t,r,n,i,s);return {cwd:t,organization:r,candidates:o,recommended_action:o.length===0?"create_workspace":o[0]?.confidence==="exact"||o[0]?.confidence==="high"?"attach_existing":"choose_workspace"}}async function cr(t,e,r,n={yes:false}){let i=pC(t);if(!i.shouldApply)return {plan:await Mi(e,r),applied:false,org_selected:null,workspace_action:"none",workspace:null,install:null,sync:null,beta_activation:null,bootstrap_v2:null};if(i.bootstrapRerun){let f=await M(r);if(!f?.id)throw new Error("workspace_required");let m=await dh(f.id,e,r,true);return {plan:await Mi(e,r),applied:true,org_selected:null,workspace_action:"none",workspace:f,install:null,sync:null,beta_activation:null,bootstrap_v2:m}}if(!n.yes)throw new Error("setup_requires_yes");let s=null;if(i.org){let{useCliOrg:f}=await Promise.resolve().then(()=>(Ee(),Nu));s=(await f(i.org,r)).id;}let o=await Mi(e,r),a="none",l=null;if(i.createWorkspace){let f=await ae("create_workspace",r);if(!f.allowed)throw new Error(f.blocking_reason??"preflight_blocked");l=await yt(i.workspaceName??basename(e),e,r),a="created";}else i.workspaceSelector?(l=await xe(i.workspaceSelector,e,r),a="attached"):o.recommended_action==="attach_existing"&&o.candidates[0]?(l=await xe(o.candidates[0].workspace_id,e,r),a="attached"):i.selectCurrentWorkspace&&(l=await Vr(i.selectCurrentWorkspace,r),a="selected");o=await Mi(e,r);let c=i.target?await Ye(i.target,r):null,u=a==="attached"||a==="created"?await De(r,e):null,d=dC(l),p=u?.ok&&d&&(a==="attached"||a==="created")?await dh(d,e,r,false):null,h=u?.ok&&(a==="attached"||a==="created")?await lh(r,{workspaceId:d,gitRemoteUrl:await mh(e),runtimeSource:"cli"}):null;return {plan:o,applied:true,org_selected:s,workspace_action:a,workspace:l,install:c,sync:u,beta_activation:h,bootstrap_v2:p}}async function dh(t,e,r,n){let{supabase:i}=await C(r),s=await sh({workspaceId:t,localRootPath:e,supabase:i,env:r,force:n});return {ok:s.ok,reused_cache:s.reusedCache,cache_path:s.cachePath,candidate_counts:{memories:s.brief.candidateMemories.length,rules:s.brief.candidateRules.length,skills:s.brief.candidateSkills.length},coverage:s.brief.coverage,summary:s.brief.summary,warnings:s.brief.warnings}}function dC(t){if(!t||typeof t!="object")return null;let e=t.id;if(typeof e=="string")return e;let r=t.workspace?.id;return typeof r=="string"?r:null}function pC(t){let e={org:null,workspaceSelector:null,workspaceName:null,createWorkspace:false,selectCurrentWorkspace:null,target:null,bootstrapRerun:false},r=false,n=false;for(let i=0;i<t.length;i+=1){let s=t[i],o=()=>{let a=t[i+1];if(!a||a.startsWith("--"))throw new Error(`missing_value:${s}`);return i+=1,a};if(s==="bootstrap"){if(r)throw new Error("unknown_setup_option:bootstrap");r=true;}else if(s==="--rerun"&&r)n=true;else if(s==="--org")e.org=o();else if(s==="--workspace"||s==="--workspace-id")e.workspaceSelector=o();else if(s==="--workspace-name")e.workspaceName=o();else if(s==="--create-workspace")e.createWorkspace=true;else if(s==="--select-workspace")e.selectCurrentWorkspace=o();else if(s==="--target")e.target=o();else throw new Error(`unknown_setup_option:${s}`)}if(r&&!n)throw new Error("missing_value:--rerun");return e.bootstrapRerun=r&&n,{...e,shouldApply:e.org!==null||e.workspaceSelector!==null||e.workspaceName!==null||e.createWorkspace||e.selectCurrentWorkspace!==null||e.target!==null||e.bootstrapRerun}}function hC(t,e,r,n,i){let s=fh(basename(t)),o=[],a=new Set,l=c=>{a.has(c.workspace_id)||(a.add(c.workspace_id),o.push(c));};for(let c of r){if(c.local_root_path===t){l(gn("cwd_mapping",c,e,"exact",false,"Exact local path mapping."));continue}if(n&&fC(c,n)){l(gn("git_remote",c,e,"high",true,"Git remote matches workspace metadata."));continue}if(i.has(c.id)){l(gn("hook_cache",c,e,"high",true,"Existing hook cache points at this folder."));continue}let u=fh(c.name);if(u===s){l(gn("name_match",c,e,"medium",true,"Folder name matches workspace name."));continue}mC(u,s)&&l(gn("name_match",c,e,"low",true,"Folder name is similar to workspace name."));}return o.sort((c,u)=>{let d=ph(u.confidence)-ph(c.confidence);return d!==0?d:hh(u.source)-hh(c.source)}),o.map((c,u)=>({...c,recommended:u===0}))}function gn(t,e,r,n,i,s){return {source:t,workspace_id:e.id,workspace_name:e.name,org_id:r.id,org_name:r.name,org_slug:r.slug,confidence:n,recommended:false,requires_confirmation:i,reason:s}}function ph(t){return {exact:4,high:3,medium:2,low:1}[t]}function hh(t){return {cwd_mapping:6,git_remote:5,hook_cache:4,companion_file:3,name_match:2,manual:1}[t]}function fC(t,e){let r=t;return r.git_remote_url&&ya(r.git_remote_url)===ya(e)?true:!r.git_owner||!r.git_repo?false:ya(e).endsWith(`/${r.git_owner}/${r.git_repo}`.toLocaleLowerCase("en-US"))}async function mh(t){try{let{stdout:e}=await uC("git",["config","--get","remote.origin.url"],{cwd:t,timeout:1e3});return e.trim()||null}catch{return null}}function ya(t){return t.trim().replace(/^git@([^:]+):/,"https://$1/").replace(/^https?:\/\//,"").replace(/\.git$/,"").toLocaleLowerCase("en-US")}async function gC(t,e){let r=new Set,n=join(A(e).home,"cache"),i;try{i=await readdir(n);}catch{return r}let s=resolve(t);return await Promise.all(i.map(async o=>{try{let a=await readFile(join(n,o,"hook-index.json"),"utf8"),l=JSON.parse(a);if(!l.workspace_id||!l.workspace_root)return;let c=resolve(l.workspace_root);(s===c||s.startsWith(`${c}/`))&&r.add(l.workspace_id);}catch{}})),r}function fh(t){return t.toLocaleLowerCase("en-US").replace(/[^a-z0-9]+/g," ").trim()}function mC(t,e){return !t||!e?false:t.includes(e)||e.includes(t)?true:_C(t,e)<=Math.max(2,Math.floor(Math.max(t.length,e.length)*.25))}function _C(t,e){let r=Array.from({length:e.length+1},(n,i)=>i);for(let n=1;n<=t.length;n+=1){let i=n,s=n-1;for(let o=1;o<=e.length;o+=1){let a=r[o]??0,l=t[n-1]===e[o-1]?0:1;r[o]=Math.min(a+1,i+1,s+l),i=r[o]??0,s=a;}r[0]=n;}return r[e.length]??0}F();Ee();async function ka(t,e){let r=await wC(t,e);if(!r)throw new Error("org_required");let{supabase:n}=await C(t),[i,s,o]=await Promise.all([n.from("organization_members").select("id, user_id, role, joined_at").eq("organization_id",r.id).order("joined_at",{ascending:true}),n.rpc("get_org_member_profiles",{p_org_id:r.id}),n.from("organization_invites").select("id, email, role, status, created_at, expires_at").eq("organization_id",r.id).eq("status","pending").order("created_at",{ascending:false})]);if(i.error)throw i.error;if(s.error)throw s.error;if(o.error)throw o.error;let a=new Map,l=s.data??[];for(let d of l)a.set(d.user_id,d);let c=(i.data??[]).map(d=>{let p=a.get(d.user_id);return {id:d.id,user_id:d.user_id,role:d.role,joined_at:d.joined_at,email:p?.email??null,full_name:wl(p?.full_name,"profile"),avatar_url:yl(p?.avatar_url),last_sign_in_at:p?.last_sign_in_at??null}}),u=(o.data??[]).map(d=>({id:d.id,email:d.email,role:d.role,status:d.status,created_at:d.created_at,expires_at:d.expires_at}));return {organization:{id:r.id,name:r.name,slug:r.slug,role:r.role},members:c,invites:u,open_target:{kind:"web",url:ee(r,t,"members"),label:"Open team in Pathrule Web",reason:"preferred"}}}async function wC(t,e){return e?(await we(t)).find(n=>n.id===e||n.slug===e)??null:j(t)}Ke();zr();async function Li(t,e,r){let n=await wt("update.policy",e);if(n.key!=="update.policy")throw new Error("invalid_update_policy_state");let i=`${(e.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"")}/cli/versions.json`,s=e.PATHRULE_PROTOCOL_VERSION??pl;if(n.value==="manual")return {checked:false,policy:n.value,current_version:t,current_protocol_version:s,latest_version:null,min_supported_protocol_version:null,protocol_compatible:true,update_available:false,upgrade_command:null,reason:"manual_policy",url:i};try{let o=await r(i,{headers:{"user-agent":`pathrule-cli/${t}`}});if(!o.ok)throw new Error(`http_${o.status}`);let a=await o.json(),l=a.latest_version??a.latest??null,c=a.min_supported_protocol_version??null;return {checked:!0,policy:n.value,current_version:t,current_protocol_version:s,latest_version:l,min_supported_protocol_version:c,protocol_compatible:kC(s,c),update_available:l?l!==t:!1,upgrade_command:a.upgrade_command??yC(a.channels),url:i}}catch{return {checked:false,policy:n.value,current_version:t,current_protocol_version:s,latest_version:null,min_supported_protocol_version:null,protocol_compatible:true,update_available:false,upgrade_command:null,reason:"request_failed",url:i}}}async function wh(t,e,r){let n=await wt("update.policy",e);if(n.key!=="update.policy")throw new Error("invalid_update_policy_state");if(n.value==="manual")return null;let i=await Ce(e).catch(()=>null);if(!i)return null;let s=await ne(i.session.user.id,e);if(s.last_update_check_at){let l=new Date(s.last_update_check_at).getTime();if(Number.isFinite(l)&&Date.now()-l<1440*60*1e3)return null}await ie(i.session.user.id,{last_update_check_at:new Date().toISOString()},e);let o=await Li(t,e,r);if(!o.checked||!o.update_available)return null;let a=o.upgrade_command?` Run: ${o.upgrade_command}`:"";return `Pathrule CLI ${o.latest_version} is available.${a}`}function yC(t){return t?t.brew??t.npm??t.standalone??null:null}function kC(t,e){if(!e)return true;let r=_h(t),n=_h(e);return r&&n?bC(r,n)>=0:t===e}function _h(t){let e=t.match(/^v?(\d+)\.(\d+)\.(\d+)$/);return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function bC(t,e){for(let r=0;r<3;r+=1){let n=(t[r]??0)-(e[r]??0);if(n!==0)return n}return 0}F();Ee();async function ba(t){let{session:e,supabase:r}=await C(t.env),[n,i]=await Promise.all([j(t.env),M(t.env)]);if(!n)throw new Error("org_required");if(!i)throw new Error("workspace_required");let s=vC(n.plan),[o,a,l,c,u,d,p,h]=await Promise.all([SC(r,i.id),mn(r.from("nodes").select("id",{count:"exact",head:true}).eq("workspace_id",i.id)),mn(r.from("memories").select("id",{count:"exact",head:true}).eq("workspace_id",i.id)),mn(r.from("rules").select("id",{count:"exact",head:true}).eq("workspace_id",i.id)),mn(r.from("skills").select("id",{count:"exact",head:true}).eq("workspace_id",i.id)),mn(r.from("workspaces").select("id",{count:"exact",head:true}).eq("organization_id",n.id).is("archived_at",null)),CC(r,i.id),Rt(t.env,e.user.id,i.id,i.local_root_path)]);return {organization:{id:n.id,name:n.name,slug:n.slug,plan:s,role:n.role,subscription_status:n.subscription_status,trial_status:n.trial_status},workspace:i,local_status:{current_folder:t.cwd,attached_root:i.local_root_path,current_folder_attached:i.local_root_path===t.cwd,attached_elsewhere:i.local_root_path!==null&&i.local_root_path!==t.cwd},cloud_tree:{root_node_present:o,nodes:a,memories:l,rules:c,skills:u},capacity:{plan:s,workspaces:{used:d,limit:Fe[s].workspaces},memories:{used:l,limit:Fe[s].memories},rules:{used:c,limit:Fe[s].rules}},active_clients:h.map(f=>RC(f)),recent_activity:p}}function vC(t){return Object.hasOwn(Fe,t)?t:"free"}async function SC(t,e){let{data:r,error:n}=await t.from("nodes").select("id").eq("workspace_id",e).eq("relative_path","/").is("parent_id",null).maybeSingle();if(n)throw n;return !!r?.id}async function mn(t){let{count:e,error:r}=await t;if(r)throw new Error(r.message);return e??0}async function CC(t,e){let{data:r,error:n}=await t.from("activity_logs").select("created_at, domain, action, scope, node_path, task_summary, files_touched").eq("workspace_id",e).eq("status","active").order("created_at",{ascending:false}).limit(5);if(n)throw n;return (r??[]).map(i=>({created_at:String(i.created_at),domain:String(i.domain??"unknown"),action:String(i.action??"unknown"),scope:String(i.scope??"project"),node_path:String(i.node_path??"/"),task_summary:String(i.task_summary??""),files_touched_total:EC(i.files_touched)}))}function EC(t){if(!t||typeof t!="object")return 0;let e=t.total;return typeof e=="number"&&Number.isFinite(e)?e:0}function RC(t){let e=t.client;return {client:e,label:U[e]?.label??e,active:t.active,selected:t.selected,detected:t.markers.includes("workspace_marker_detected"),machine_installed:t.machineInstalled,machine_config_exists:t.machineConfigExists,machine_config_path:t.machineConfigPath}}var LC=createRequire(import.meta.url),Ue=LC("../package.json"),Bi=promisify(execFile),X=class extends Error{constructor(r,n){super(n);this.code=r;this.name="CliContentUsageError";}code},UC=`${H.cli}
|
|
188
188
|
|
|
189
189
|
Usage:
|
|
190
190
|
pathrule <command> [options]
|
|
@@ -310,10 +310,10 @@ Useful commands:
|
|
|
310
310
|
`}function Th(t){return t?WC(t)?{ok:true,text:BC(t),topic:t}:{ok:false,message:`Unknown help topic "${t}". Try: ${Pa.join(", ")}.`}:{ok:true,text:UC,topic:null}}async function Ah(t,e){let r=Date.now(),n=ku(t,e.env),i={json:n.flags.json,color:n.flags.color,interactive:n.flags.interactive,noOpen:n.flags.noOpen},s=n.flags.version?"version":n.flags.help?"help":n.command;if(i.json){let a=await FC(s,e,n.positional.slice(1),n.flags);return e.stdout.write(Op(a.envelope)),await io(e.env,{command:s,exitCode:a.exitCode,appVersion:Ue.version,durationMs:Date.now()-r}),a.exitCode}let o;switch(s){case "help":{let a=Th(n.positional[1]);if(!a.ok){e.stderr.write(`${g("error",i)} ${a.message}
|
|
311
311
|
`),o=64;break}e.stdout.write(a.text),o=0;break}case "version":e.stdout.write(`${Ue.version}
|
|
312
312
|
`),o=0;break;case "start":o=await U0(e,i);break;case "login":o=await Kh(e,i,n.flags.browserCallback);break;case "org":o=await wE(n.positional[1]??"list",n.positional.slice(2),e,i);break;case "workspace":o=await u0(n.positional[1]??"list",n.positional.slice(2),e,i);break;case "init":o=await d0(n.positional[1],e,i);break;case "setup":o=await p0(e,i,n.positional.slice(1),n.flags.yes);break;case "attach":o=await A0(n.positional[1],e,i);break;case "detach":o=await I0(n.positional[1],e,i);break;case "preflight":o=await O0(n.positional[1],e,i);break;case "install":o=await $0(n.positional[1],e,i);break;case "uninstall":o=await N0(n.positional[1],e,i);break;case "sync":o=await j0(n.positional.slice(1),e,i);break;case "config":o=await D0(n.positional[1],n.positional[2],n.positional[3],e,i);break;case "update":o=await M0(e,i);break;case "daemon":o=await W0(n.positional.slice(1),e,i);break;case "bridge":o=await F0(n.positional[1]??"pair",e,i);break;case "open":o=await Nh(n.positional.slice(1),e,i);break;case "search":o=await oE(n.positional.slice(1),e,i);break;case "memory":case "rule":case "skill":o=await sE(s,n.positional.slice(1),e,i);break;case "refresh":o=await aE(n.positional.slice(1),e,i);break;case "repair":o=await lE(e,i);break;case "cache":o=await cE(n.positional.slice(1),e,i,n.flags.yes);break;case "billing":case "team":case "invite":case "upgrade":case "reactivate":o=s==="invite"?await Y0(n.positional.slice(1),e,i):s==="team"?await X0(n.positional.slice(1),e,i):await G0(s,n.positional.slice(1),e,i);break;case "status":o=await J0(e,i);break;case "doctor":o=await z0(n.positional.slice(1),e,i);break;case "whoami":o=await V0(e,i);break;case "logout":o=await PE(e,i);break;default:e.stderr.write(`${g("error",i)} Unknown command "${s}". Run pathrule help.
|
|
313
|
-
`),o=64;}return s!=="update"&&s!=="login"&&s!=="logout"&&await L0(e,i),await io(e.env,{command:s,exitCode:o,appVersion:Ue.version,durationMs:Date.now()-r}),o}async function FC(t,e,r,n={yes:false}){if(t==="version")return {exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:{version:Ue.version}})};if(t==="help"){let i=Th(r[0]);return i.ok?{exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:{topic:i.topic,topics:[...Pa],text:i.text,commands:["help","version","start","login","status","doctor","whoami","logout","org","workspace","init","setup","attach","detach","preflight","install","uninstall","sync","config","update","daemon","bridge","open","search","memory","rule","skill","refresh","repair","cache","billing","team","invite","upgrade","reactivate"]}})}:{exitCode:64,envelope:k({command:t,cwd:e.cwd,ok:false,error:{code:"invalid_help_topic",message:i.message}})}}if(t==="login")try{let i=await eo({env:e.env,fetch:e.fetch??fetch,sleep:e.sleep??Vh});return {exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:!0,data:{user_id:i.session.user.id,email:i.session.user.email??null,expires_at:i.session.expires_at}})}}catch(i){let s=i instanceof Ne?i.code:"login_failed";return {exitCode:1,envelope:k({command:t,cwd:e.cwd,ok:false,error:{code:s,message:i instanceof Error?i.message:String(i)}})}}if(t==="daemon")return o0(e,r);if(t==="bridge")return a0(e,r[0]??"pair");if(t==="open")return jh(e,r);if(t==="search")return dE(e,r);if(t==="memory"||t==="rule"||t==="skill")return uE(t,e,r);if(t==="refresh")return pE(e,r);if(t==="repair")return hE(e);if(t==="cache")return fE(e,r,n.yes);if(t==="invite")return Q0(e,r);if(t==="team")return eE(e,r);if(t==="billing"||t==="upgrade"||t==="reactivate")return Z0(t,e,r);if(t==="whoami"){let i=await Ce(e.env);return i?{exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:{user_id:i.session.user.id,email:i.session.user.email??null,expires_at:i.session.expires_at,...await JC(e.env)}})}:{exitCode:1,envelope:k({command:t,cwd:e.cwd,ok:false,error:{code:"not_authenticated",message:"Pathrule CLI is not signed in.",remediation:[{label:"Sign in",command:"pathrule login"}]}})}}if(t==="logout"){let i=await ro(e.env);return {exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:i})}}return t==="org"?l0(e,r[0]??"list",r.slice(1)):t==="workspace"?GC(e,r[0]??"list",r.slice(1)):t==="init"?YC(e,r[0]):t==="setup"?XC(e,r,n.yes):t==="attach"?ZC(e,r[0]):t==="detach"?QC(e,r[0]):t==="preflight"?e0(e,r[0]):t==="install"?t0(e,r[0]):t==="uninstall"?r0(e,r[0]):t==="sync"?n0(e,r):t==="config"?i0(e,r[0],r[1],r[2]):t==="update"?s0(e):t==="status"?VC(e):t==="doctor"?HC(e,r):t==="__scaffold"?{exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:{status:"not_implemented",phase:"m31a_cli_foundation"},next_steps:zC(t)})}:{exitCode:64,envelope:k({command:t,cwd:e.cwd,ok:false,error:{code:"unknown_command",message:`Unknown command "${t}".`,remediation:[{label:"Show help",command:"pathrule help"}]}})}}async function HC(t,e){try{if(e.includes("--bundle")){let n=await Lo(t.env,t.cwd);return {exitCode:n.ok?0:1,envelope:k({command:"doctor --bundle",cwd:t.cwd,ok:n.ok,data:{path:n.path,report:n.report}})}}let r=await je(t.env,t.cwd);return await qC(t.env,r.managed_files),{exitCode:r.ok?0:1,envelope:k({command:"doctor",cwd:t.cwd,ok:r.ok,data:r})}}catch(r){return {exitCode:1,envelope:k({command:"doctor",cwd:t.cwd,ok:false,error:{code:V(r,"doctor_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function qC(t,e){e.some(r=>r.status==="other_owner"||r.status==="newer_version")&&(await Jr(t,{eventName:"managed_file_owner_conflict",result:"blocked",appVersion:Ue.version,featureTag:"managed_files",blockingReason:"managed_file_owner_conflict"}).catch(()=>{}),await Jr(t,{eventName:"dead_end_seen",result:"blocked",appVersion:Ue.version,featureTag:"managed_files",blockingReason:"managed_file_owner_conflict"}).catch(()=>{}));}function zC(t){if(t==="status"||t==="doctor"||t==="whoami")return [{label:"Continue M31a implementation",command:"pathrule login"}]}async function JC(t){try{let[e,r,n]=await Promise.all([_e(t),j(t),M(t)]);return {organizations:e,current_org:r,current_workspace:n}}catch(e){return {context_error:e instanceof Error?e.message:String(e)}}}async function KC(t){let e=await M(t);if(!e)throw new Error("workspace_required");return e}async function VC(t){try{let e=await Ih(t);return {exitCode:e.authenticated?0:1,envelope:k({command:"status",cwd:t.cwd,ok:e.authenticated,data:e,error:e.authenticated?void 0:{code:"not_authenticated",message:"Pathrule CLI is not signed in.",remediation:[{label:"Sign in",command:"pathrule login"}]}})}}catch(e){return {exitCode:1,envelope:k({command:"status",cwd:t.cwd,ok:false,error:{code:V(e,"status_failed"),message:e instanceof Error?e.message:String(e)}})}}}async function GC(t,e,r){try{if(e==="inspect"){let i=await ba(t);return {exitCode:0,envelope:k({command:"workspace inspect",cwd:t.cwd,ok:!0,data:i})}}if(e==="open"){let i=await ur(t);if(!i)throw new Error("workspace_required");let s=await qi(i.id,t.env,{preferDesktopApp:r.includes("--desktop-app"),forceWeb:r.includes("--web")});return {exitCode:0,envelope:k({command:"workspace open",cwd:t.cwd,ok:!0,data:s})}}if(e==="create"){let i=await ae("create_workspace",t.env);if(!i.allowed){let s=sr(i);return {exitCode:1,envelope:k({command:"workspace create",cwd:t.cwd,ok:!1,data:{preflight:i},error:{code:i.blocking_reason??"preflight_blocked",message:s.summary},next_steps:Ji(s)})}}}let n=e==="current"?await KC(t.env):e==="use"?await Kr(r[0]??"",t.env):e==="create"?await yt(r[0]??"",t.cwd,t.env):e==="attach"?await xe(r[0],t.cwd,t.env):e==="detach"?await Vr(r[0],t.env):await Re(t.env);return {exitCode:0,envelope:k({command:`workspace ${e}`,cwd:t.cwd,ok:!0,data:n})}}catch(n){return {exitCode:1,envelope:k({command:`workspace ${e}`,cwd:t.cwd,ok:false,error:{code:V(n,"workspace_command_failed"),message:n instanceof Error?n.message:String(n)}})}}}async function YC(t,e){try{let r=await ae("create_workspace",t.env);if(!r.allowed){let i=sr(r);return {exitCode:1,envelope:k({command:"init",cwd:t.cwd,ok:!1,data:{preflight:r},error:{code:r.blocking_reason??"preflight_blocked",message:i.summary},next_steps:Ji(i)})}}let n=await yt(e??Gh(t.cwd),t.cwd,t.env);return {exitCode:0,envelope:k({command:"init",cwd:t.cwd,ok:!0,data:n})}}catch(r){return {exitCode:1,envelope:k({command:"init",cwd:t.cwd,ok:false,error:{code:V(r,"init_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function XC(t,e,r){try{let n=await cr(e,t.cwd,t.env,{yes:r});return {exitCode:0,envelope:k({command:"setup",cwd:t.cwd,ok:!0,data:n})}}catch(n){let i=V(n,"setup_failed");return {exitCode:i.startsWith("unknown_setup_option")||i.startsWith("missing_value")||i==="setup_requires_yes"?64:1,envelope:k({command:"setup",cwd:t.cwd,ok:false,error:{code:i,message:n instanceof Error?n.message:String(n)}})}}}async function ZC(t,e){try{let r=await xe(e,t.cwd,t.env);return {exitCode:0,envelope:k({command:"attach",cwd:t.cwd,ok:!0,data:r})}}catch(r){return {exitCode:1,envelope:k({command:"attach",cwd:t.cwd,ok:false,error:{code:V(r,"attach_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function QC(t,e){try{let r=await Vr(e,t.env);return {exitCode:0,envelope:k({command:"detach",cwd:t.cwd,ok:!0,data:r})}}catch(r){return {exitCode:1,envelope:k({command:"detach",cwd:t.cwd,ok:false,error:{code:V(r,"detach_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function e0(t,e){if(!e||!Ko(e))return {exitCode:64,envelope:k({command:"preflight",cwd:t.cwd,ok:false,error:{code:"invalid_preflight_action",message:"Usage: pathrule preflight <create_workspace|write_memory|write_rule|write_skill|sync_agents|materialize_skills>"}})};try{let r=await ae(e,t.env),n=r.allowed?null:sr(r);return {exitCode:r.allowed?0:1,envelope:k({command:`preflight ${e}`,cwd:t.cwd,ok:r.allowed,data:r,error:r.allowed?void 0:{code:r.blocking_reason??"preflight_blocked",message:n?.summary??"Preflight blocked."},next_steps:n?Ji(n):void 0})}}catch(r){return {exitCode:1,envelope:k({command:`preflight ${e}`,cwd:t.cwd,ok:false,error:{code:V(r,"preflight_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function t0(t,e){try{let r=await Ye(e,t.env);return {exitCode:r.every(n=>n.ok)?0:1,envelope:k({command:"install",cwd:t.cwd,ok:r.every(n=>n.ok),data:r})}}catch(r){return {exitCode:r instanceof Error&&r.message==="invalid_install_target"?64:1,envelope:k({command:"install",cwd:t.cwd,ok:false,error:{code:r instanceof Error?r.message:"install_failed",message:r instanceof Error?r.message:String(r)}})}}}async function r0(t,e){try{let r=await Yo(e);return {exitCode:r.every(n=>n.ok)?0:1,envelope:k({command:"uninstall",cwd:t.cwd,ok:r.every(n=>n.ok),data:r})}}catch(r){return {exitCode:r instanceof Error&&r.message==="invalid_install_target"?64:1,envelope:k({command:"uninstall",cwd:t.cwd,ok:false,error:{code:r instanceof Error?r.message:"uninstall_failed",message:r instanceof Error?r.message:String(r)}})}}}async function n0(t,e){try{let r=await De(t.env,t.cwd,{skillsOnly:e.includes("--skills")});return {exitCode:r.ok?0:1,envelope:k({command:"sync",cwd:t.cwd,ok:r.ok,data:r,error:r.ok?void 0:{code:r.error??"sync_failed",message:r.error??"Pathrule sync failed."}})}}catch(r){return {exitCode:1,envelope:k({command:"sync",cwd:t.cwd,ok:false,error:{code:V(r,"sync_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function i0(t,e,r,n){try{if(e==="get"&&r){let i=await wt(r,t.env);return {exitCode:0,envelope:k({command:`config get ${r}`,cwd:t.cwd,ok:!0,data:i})}}if(e==="set"&&r&&n){let i=await co(r,n,t.env);return {exitCode:0,envelope:k({command:`config set ${r}`,cwd:t.cwd,ok:!0,data:i})}}if(e==="reset"&&r){let i=await uo(r,t.env);return {exitCode:0,envelope:k({command:`config reset ${r}`,cwd:t.cwd,ok:!0,data:i})}}return {exitCode:64,envelope:k({command:"config",cwd:t.cwd,ok:!1,error:{code:"invalid_config_command",message:"Usage: pathrule config get <update.policy|suggestions.desktop|telemetry.enabled|telemetry.id> OR pathrule config set update.policy manual|notify|auto OR pathrule config set suggestions.desktop true|false OR pathrule config set telemetry.enabled true|false OR pathrule config reset telemetry-id"}})}}catch(i){return {exitCode:i instanceof Error&&i.message.startsWith("invalid_")?64:1,envelope:k({command:"config",cwd:t.cwd,ok:false,error:{code:i instanceof Error?i.message:"config_failed",message:i instanceof Error?i.message:String(i)}})}}}async function s0(t){let e=await Li(Ue.version,t.env,t.fetch??fetch);return {exitCode:0,envelope:k({command:"update",cwd:t.cwd,ok:true,data:e})}}async function o0(t,e){let r=e[0]??"status";try{if(r==="run")throw new Error("daemon_run_not_available_in_json_mode");if(r==="autostart"||r==="toggle"){let i=r==="toggle"?"toggle":e[1]??"status",s=await Ni(t.env),o=i==="status"?s:i==="on"||i==="enable"?await Xe(t.env,!0):i==="off"||i==="disable"?await Xe(t.env,!1):i==="toggle"?await Xe(t.env,!s.enabled):null;if(!o)throw new Error("invalid_daemon_command");return {exitCode:o.supported?0:1,envelope:k({command:r==="toggle"?"daemon toggle":`daemon autostart ${i}`,cwd:t.cwd,ok:o.supported,data:o,error:o.supported?void 0:{code:"daemon_autostart_unsupported",message:o.reason??"Daemon autostart is not supported on this platform."}})}}let n=r==="start"?await un(pr(t.env)):r==="stop"?await dn(t.env):r==="status"?await Le(t.env):null;if(!n)throw new Error("invalid_daemon_command");return {exitCode:0,envelope:k({command:`daemon ${r}`,cwd:t.cwd,ok:!0,data:n})}}catch(n){let i=n instanceof Error?n.message:"daemon_failed";return {exitCode:i==="invalid_daemon_command"?64:1,envelope:k({command:`daemon ${r}`,cwd:t.cwd,ok:false,error:{code:i,message:n instanceof Error?n.message:String(n)}})}}}async function a0(t,e){try{if(e!=="pair")throw new Error("invalid_bridge_command");let r=pr(t.env),n=await pi(r),i=(await Ta(r)).status;if(!i.state?.daemon_session_id)throw new Error("daemon_session_missing");let s=await So({env:r,daemonSessionId:i.state.daemon_session_id,user:n,verifyReauth:!1});return {exitCode:0,envelope:k({command:"bridge pair",cwd:t.cwd,ok:!0,data:s})}}catch(r){let n=r instanceof Y||r instanceof Qt?r.code:r instanceof Error?r.message:"bridge_pair_failed";return {exitCode:n==="invalid_bridge_command"?64:1,envelope:k({command:`bridge ${e}`,cwd:t.cwd,ok:false,error:{code:n,message:r instanceof Error?r.message:String(r)}})}}}async function l0(t,e,r){try{let n=e==="current"?await j(t.env):e==="use"?await di(r[0]??"",t.env):e==="open"?await c0(t,r[0]):await _e(t.env);return {exitCode:0,envelope:k({command:`org ${e}`,cwd:t.cwd,ok:!0,data:n})}}catch(n){return {exitCode:1,envelope:k({command:`org ${e}`,cwd:t.cwd,ok:false,error:{code:V(n,"org_command_failed"),message:n instanceof Error?n.message:String(n)}})}}}async function c0(t,e){let r=await j(t.env);if(!r)throw new Error("org_required");let n=Hh(e);return {org_id:r.id,slug:r.slug,name:r.name,role:r.role,billing:r.billing,url:ee(r,t.env,n),opened:false}}async function Ih(t){let e=await Ce(t.env);if(!e)return {authenticated:false,user:null,organization:null,workspace:null,cwd_workspace_match:null};let r=await j(t.env),n=await M(t.env),i=await Re(t.env),s=Mh(i,t.cwd),o=s??n;return {authenticated:true,user:{id:e.session.user.id,email:e.session.user.email??null,expires_at:e.session.expires_at},organization:r,workspace:o,selected_workspace:n,cwd_workspace_match:s}}async function u0(t,e,r,n){try{if(t==="current"){let s=await M(r.env);return s?(r.stdout.write(`${g("ok",n)} ${s.name}
|
|
313
|
+
`),o=64;}return s!=="update"&&s!=="login"&&s!=="logout"&&await L0(e,i),await io(e.env,{command:s,exitCode:o,appVersion:Ue.version,durationMs:Date.now()-r}),o}async function FC(t,e,r,n={yes:false}){if(t==="version")return {exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:{version:Ue.version}})};if(t==="help"){let i=Th(r[0]);return i.ok?{exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:{topic:i.topic,topics:[...Pa],text:i.text,commands:["help","version","start","login","status","doctor","whoami","logout","org","workspace","init","setup","attach","detach","preflight","install","uninstall","sync","config","update","daemon","bridge","open","search","memory","rule","skill","refresh","repair","cache","billing","team","invite","upgrade","reactivate"]}})}:{exitCode:64,envelope:k({command:t,cwd:e.cwd,ok:false,error:{code:"invalid_help_topic",message:i.message}})}}if(t==="login")try{let i=await eo({env:e.env,fetch:e.fetch??fetch,sleep:e.sleep??Vh});return {exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:!0,data:{user_id:i.session.user.id,email:i.session.user.email??null,expires_at:i.session.expires_at}})}}catch(i){let s=i instanceof Ne?i.code:"login_failed";return {exitCode:1,envelope:k({command:t,cwd:e.cwd,ok:false,error:{code:s,message:i instanceof Error?i.message:String(i)}})}}if(t==="daemon")return o0(e,r);if(t==="bridge")return a0(e,r[0]??"pair");if(t==="open")return jh(e,r);if(t==="search")return dE(e,r);if(t==="memory"||t==="rule"||t==="skill")return uE(t,e,r);if(t==="refresh")return pE(e,r);if(t==="repair")return hE(e);if(t==="cache")return fE(e,r,n.yes);if(t==="invite")return Q0(e,r);if(t==="team")return eE(e,r);if(t==="billing"||t==="upgrade"||t==="reactivate")return Z0(t,e,r);if(t==="whoami"){let i=await Ce(e.env);return i?{exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:{user_id:i.session.user.id,email:i.session.user.email??null,expires_at:i.session.expires_at,...await JC(e.env)}})}:{exitCode:1,envelope:k({command:t,cwd:e.cwd,ok:false,error:{code:"not_authenticated",message:"Pathrule CLI is not signed in.",remediation:[{label:"Sign in",command:"pathrule login"}]}})}}if(t==="logout"){let i=await ro(e.env);return {exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:i})}}return t==="org"?l0(e,r[0]??"list",r.slice(1)):t==="workspace"?GC(e,r[0]??"list",r.slice(1)):t==="init"?YC(e,r[0]):t==="setup"?XC(e,r,n.yes):t==="attach"?ZC(e,r[0]):t==="detach"?QC(e,r[0]):t==="preflight"?e0(e,r[0]):t==="install"?t0(e,r[0]):t==="uninstall"?r0(e,r[0]):t==="sync"?n0(e,r):t==="config"?i0(e,r[0],r[1],r[2]):t==="update"?s0(e):t==="status"?VC(e):t==="doctor"?HC(e,r):t==="__scaffold"?{exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:true,data:{status:"not_implemented",phase:"m31a_cli_foundation"},next_steps:zC(t)})}:{exitCode:64,envelope:k({command:t,cwd:e.cwd,ok:false,error:{code:"unknown_command",message:`Unknown command "${t}".`,remediation:[{label:"Show help",command:"pathrule help"}]}})}}async function HC(t,e){try{if(e.includes("--bundle")){let n=await Lo(t.env,t.cwd);return {exitCode:n.ok?0:1,envelope:k({command:"doctor --bundle",cwd:t.cwd,ok:n.ok,data:{path:n.path,report:n.report}})}}let r=await je(t.env,t.cwd);return await qC(t.env,r.managed_files),{exitCode:r.ok?0:1,envelope:k({command:"doctor",cwd:t.cwd,ok:r.ok,data:r})}}catch(r){return {exitCode:1,envelope:k({command:"doctor",cwd:t.cwd,ok:false,error:{code:V(r,"doctor_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function qC(t,e){e.some(r=>r.status==="other_owner"||r.status==="newer_version")&&(await Kr(t,{eventName:"managed_file_owner_conflict",result:"blocked",appVersion:Ue.version,featureTag:"managed_files",blockingReason:"managed_file_owner_conflict"}).catch(()=>{}),await Kr(t,{eventName:"dead_end_seen",result:"blocked",appVersion:Ue.version,featureTag:"managed_files",blockingReason:"managed_file_owner_conflict"}).catch(()=>{}));}function zC(t){if(t==="status"||t==="doctor"||t==="whoami")return [{label:"Continue M31a implementation",command:"pathrule login"}]}async function JC(t){try{let[e,r,n]=await Promise.all([we(t),j(t),M(t)]);return {organizations:e,current_org:r,current_workspace:n}}catch(e){return {context_error:e instanceof Error?e.message:String(e)}}}async function KC(t){let e=await M(t);if(!e)throw new Error("workspace_required");return e}async function VC(t){try{let e=await Ih(t);return {exitCode:e.authenticated?0:1,envelope:k({command:"status",cwd:t.cwd,ok:e.authenticated,data:e,error:e.authenticated?void 0:{code:"not_authenticated",message:"Pathrule CLI is not signed in.",remediation:[{label:"Sign in",command:"pathrule login"}]}})}}catch(e){return {exitCode:1,envelope:k({command:"status",cwd:t.cwd,ok:false,error:{code:V(e,"status_failed"),message:e instanceof Error?e.message:String(e)}})}}}async function GC(t,e,r){try{if(e==="inspect"){let i=await ba(t);return {exitCode:0,envelope:k({command:"workspace inspect",cwd:t.cwd,ok:!0,data:i})}}if(e==="open"){let i=await ur(t);if(!i)throw new Error("workspace_required");let s=await qi(i.id,t.env,{preferDesktopApp:r.includes("--desktop-app"),forceWeb:r.includes("--web")});return {exitCode:0,envelope:k({command:"workspace open",cwd:t.cwd,ok:!0,data:s})}}if(e==="create"){let i=await ae("create_workspace",t.env);if(!i.allowed){let s=sr(i);return {exitCode:1,envelope:k({command:"workspace create",cwd:t.cwd,ok:!1,data:{preflight:i},error:{code:i.blocking_reason??"preflight_blocked",message:s.summary},next_steps:Ji(s)})}}}let n=e==="current"?await KC(t.env):e==="use"?await Vr(r[0]??"",t.env):e==="create"?await yt(r[0]??"",t.cwd,t.env):e==="attach"?await xe(r[0],t.cwd,t.env):e==="detach"?await Gr(r[0],t.env):await Re(t.env);return {exitCode:0,envelope:k({command:`workspace ${e}`,cwd:t.cwd,ok:!0,data:n})}}catch(n){return {exitCode:1,envelope:k({command:`workspace ${e}`,cwd:t.cwd,ok:false,error:{code:V(n,"workspace_command_failed"),message:n instanceof Error?n.message:String(n)}})}}}async function YC(t,e){try{let r=await ae("create_workspace",t.env);if(!r.allowed){let i=sr(r);return {exitCode:1,envelope:k({command:"init",cwd:t.cwd,ok:!1,data:{preflight:r},error:{code:r.blocking_reason??"preflight_blocked",message:i.summary},next_steps:Ji(i)})}}let n=await yt(e??Gh(t.cwd),t.cwd,t.env);return {exitCode:0,envelope:k({command:"init",cwd:t.cwd,ok:!0,data:n})}}catch(r){return {exitCode:1,envelope:k({command:"init",cwd:t.cwd,ok:false,error:{code:V(r,"init_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function XC(t,e,r){try{let n=await cr(e,t.cwd,t.env,{yes:r});return {exitCode:0,envelope:k({command:"setup",cwd:t.cwd,ok:!0,data:n})}}catch(n){let i=V(n,"setup_failed");return {exitCode:i.startsWith("unknown_setup_option")||i.startsWith("missing_value")||i==="setup_requires_yes"?64:1,envelope:k({command:"setup",cwd:t.cwd,ok:false,error:{code:i,message:n instanceof Error?n.message:String(n)}})}}}async function ZC(t,e){try{let r=await xe(e,t.cwd,t.env);return {exitCode:0,envelope:k({command:"attach",cwd:t.cwd,ok:!0,data:r})}}catch(r){return {exitCode:1,envelope:k({command:"attach",cwd:t.cwd,ok:false,error:{code:V(r,"attach_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function QC(t,e){try{let r=await Gr(e,t.env);return {exitCode:0,envelope:k({command:"detach",cwd:t.cwd,ok:!0,data:r})}}catch(r){return {exitCode:1,envelope:k({command:"detach",cwd:t.cwd,ok:false,error:{code:V(r,"detach_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function e0(t,e){if(!e||!Ko(e))return {exitCode:64,envelope:k({command:"preflight",cwd:t.cwd,ok:false,error:{code:"invalid_preflight_action",message:"Usage: pathrule preflight <create_workspace|write_memory|write_rule|write_skill|sync_agents|materialize_skills>"}})};try{let r=await ae(e,t.env),n=r.allowed?null:sr(r);return {exitCode:r.allowed?0:1,envelope:k({command:`preflight ${e}`,cwd:t.cwd,ok:r.allowed,data:r,error:r.allowed?void 0:{code:r.blocking_reason??"preflight_blocked",message:n?.summary??"Preflight blocked."},next_steps:n?Ji(n):void 0})}}catch(r){return {exitCode:1,envelope:k({command:`preflight ${e}`,cwd:t.cwd,ok:false,error:{code:V(r,"preflight_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function t0(t,e){try{let r=await Ye(e,t.env);return {exitCode:r.every(n=>n.ok)?0:1,envelope:k({command:"install",cwd:t.cwd,ok:r.every(n=>n.ok),data:r})}}catch(r){return {exitCode:r instanceof Error&&r.message==="invalid_install_target"?64:1,envelope:k({command:"install",cwd:t.cwd,ok:false,error:{code:r instanceof Error?r.message:"install_failed",message:r instanceof Error?r.message:String(r)}})}}}async function r0(t,e){try{let r=await Yo(e);return {exitCode:r.every(n=>n.ok)?0:1,envelope:k({command:"uninstall",cwd:t.cwd,ok:r.every(n=>n.ok),data:r})}}catch(r){return {exitCode:r instanceof Error&&r.message==="invalid_install_target"?64:1,envelope:k({command:"uninstall",cwd:t.cwd,ok:false,error:{code:r instanceof Error?r.message:"uninstall_failed",message:r instanceof Error?r.message:String(r)}})}}}async function n0(t,e){try{let r=await De(t.env,t.cwd,{skillsOnly:e.includes("--skills")});return {exitCode:r.ok?0:1,envelope:k({command:"sync",cwd:t.cwd,ok:r.ok,data:r,error:r.ok?void 0:{code:r.error??"sync_failed",message:r.error??"Pathrule sync failed."}})}}catch(r){return {exitCode:1,envelope:k({command:"sync",cwd:t.cwd,ok:false,error:{code:V(r,"sync_failed"),message:r instanceof Error?r.message:String(r)}})}}}async function i0(t,e,r,n){try{if(e==="get"&&r){let i=await wt(r,t.env);return {exitCode:0,envelope:k({command:`config get ${r}`,cwd:t.cwd,ok:!0,data:i})}}if(e==="set"&&r&&n){let i=await co(r,n,t.env);return {exitCode:0,envelope:k({command:`config set ${r}`,cwd:t.cwd,ok:!0,data:i})}}if(e==="reset"&&r){let i=await uo(r,t.env);return {exitCode:0,envelope:k({command:`config reset ${r}`,cwd:t.cwd,ok:!0,data:i})}}return {exitCode:64,envelope:k({command:"config",cwd:t.cwd,ok:!1,error:{code:"invalid_config_command",message:"Usage: pathrule config get <update.policy|suggestions.desktop|telemetry.enabled|telemetry.id> OR pathrule config set update.policy manual|notify|auto OR pathrule config set suggestions.desktop true|false OR pathrule config set telemetry.enabled true|false OR pathrule config reset telemetry-id"}})}}catch(i){return {exitCode:i instanceof Error&&i.message.startsWith("invalid_")?64:1,envelope:k({command:"config",cwd:t.cwd,ok:false,error:{code:i instanceof Error?i.message:"config_failed",message:i instanceof Error?i.message:String(i)}})}}}async function s0(t){let e=await Li(Ue.version,t.env,t.fetch??fetch);return {exitCode:0,envelope:k({command:"update",cwd:t.cwd,ok:true,data:e})}}async function o0(t,e){let r=e[0]??"status";try{if(r==="run")throw new Error("daemon_run_not_available_in_json_mode");if(r==="autostart"||r==="toggle"){let i=r==="toggle"?"toggle":e[1]??"status",s=await Ni(t.env),o=i==="status"?s:i==="on"||i==="enable"?await Xe(t.env,!0):i==="off"||i==="disable"?await Xe(t.env,!1):i==="toggle"?await Xe(t.env,!s.enabled):null;if(!o)throw new Error("invalid_daemon_command");return {exitCode:o.supported?0:1,envelope:k({command:r==="toggle"?"daemon toggle":`daemon autostart ${i}`,cwd:t.cwd,ok:o.supported,data:o,error:o.supported?void 0:{code:"daemon_autostart_unsupported",message:o.reason??"Daemon autostart is not supported on this platform."}})}}let n=r==="start"?await dn(pr(t.env)):r==="stop"?await pn(t.env):r==="status"?await Le(t.env):null;if(!n)throw new Error("invalid_daemon_command");return {exitCode:0,envelope:k({command:`daemon ${r}`,cwd:t.cwd,ok:!0,data:n})}}catch(n){let i=n instanceof Error?n.message:"daemon_failed";return {exitCode:i==="invalid_daemon_command"?64:1,envelope:k({command:`daemon ${r}`,cwd:t.cwd,ok:false,error:{code:i,message:n instanceof Error?n.message:String(n)}})}}}async function a0(t,e){try{if(e!=="pair")throw new Error("invalid_bridge_command");let r=pr(t.env),n=await pi(r),i=(await Ta(r)).status;if(!i.state?.daemon_session_id)throw new Error("daemon_session_missing");let s=await So({env:r,daemonSessionId:i.state.daemon_session_id,user:n,verifyReauth:!1});return {exitCode:0,envelope:k({command:"bridge pair",cwd:t.cwd,ok:!0,data:s})}}catch(r){let n=r instanceof Y||r instanceof Qt?r.code:r instanceof Error?r.message:"bridge_pair_failed";return {exitCode:n==="invalid_bridge_command"?64:1,envelope:k({command:`bridge ${e}`,cwd:t.cwd,ok:false,error:{code:n,message:r instanceof Error?r.message:String(r)}})}}}async function l0(t,e,r){try{let n=e==="current"?await j(t.env):e==="use"?await di(r[0]??"",t.env):e==="open"?await c0(t,r[0]):await we(t.env);return {exitCode:0,envelope:k({command:`org ${e}`,cwd:t.cwd,ok:!0,data:n})}}catch(n){return {exitCode:1,envelope:k({command:`org ${e}`,cwd:t.cwd,ok:false,error:{code:V(n,"org_command_failed"),message:n instanceof Error?n.message:String(n)}})}}}async function c0(t,e){let r=await j(t.env);if(!r)throw new Error("org_required");let n=Hh(e);return {org_id:r.id,slug:r.slug,name:r.name,role:r.role,billing:r.billing,url:ee(r,t.env,n),opened:false}}async function Ih(t){let e=await Ce(t.env);if(!e)return {authenticated:false,user:null,organization:null,workspace:null,cwd_workspace_match:null};let r=await j(t.env),n=await M(t.env),i=await Re(t.env),s=Mh(i,t.cwd),o=s??n;return {authenticated:true,user:{id:e.session.user.id,email:e.session.user.email??null,expires_at:e.session.expires_at},organization:r,workspace:o,selected_workspace:n,cwd_workspace_match:s}}async function u0(t,e,r,n){try{if(t==="current"){let s=await M(r.env);return s?(r.stdout.write(`${g("ok",n)} ${s.name}
|
|
314
314
|
`),0):(r.stdout.write(`${g("warn",n)} No current workspace selected. Run pathrule workspace use <name-or-id>.
|
|
315
315
|
`),1)}if(t==="use"){let s=e[0];if(!s)return r.stderr.write(`${g("error",n)} Usage: pathrule workspace use <name-or-id>
|
|
316
|
-
`),64;let o=await
|
|
316
|
+
`),64;let o=await Vr(s,r.env);return r.stdout.write(`${g("ok",n)} Current workspace: ${o.name}
|
|
317
317
|
`),0}if(t==="inspect"){let s=await ba(r);r.stdout.write(`${g("ok",n)} Workspace: ${s.workspace.name}
|
|
318
318
|
`),r.stdout.write(`${g("info",n)} Organization: ${s.organization.slug} (${s.organization.plan}, ${s.organization.role})
|
|
319
319
|
`),r.stdout.write(`${g("info",n)} Access mode: ${s.workspace.access_mode}
|
|
@@ -333,7 +333,7 @@ Useful commands:
|
|
|
333
333
|
`),0}if(t==="create"){let s=e[0];if(!s)return r.stderr.write(`${g("error",n)} Usage: pathrule workspace create <name>
|
|
334
334
|
`),64;let o=await ae("create_workspace",r.env);if(!o.allowed)return Ki(o,r.stderr,n),1;let a=await yt(s,r.cwd,r.env);return r.stdout.write(`${g("ok",n)} Created ${a.workspace.name} and attached it to ${a.local_root_path}
|
|
335
335
|
`),await dr(r,n),0}if(t==="attach"){let s=await xe(e[0],r.cwd,r.env);return r.stdout.write(`${g("ok",n)} Attached ${s.workspace.name} to ${s.local_root_path}
|
|
336
|
-
`),await dr(r,n),0}if(t==="detach"){let s=await
|
|
336
|
+
`),await dr(r,n),0}if(t==="detach"){let s=await Gr(e[0],r.env);return r.stdout.write(`${g("ok",n)} Detached ${s.name} from this machine.
|
|
337
337
|
`),0}if(t!=="list")return r.stderr.write(`${g("error",n)} Unknown workspace command "${t}".
|
|
338
338
|
`),64;let i=await Re(r.env);return i.length===0?(r.stdout.write(`${g("warn",n)} No workspaces found.
|
|
339
339
|
`),0):(r.stdout.write(i.map(s=>`${s.current?"*":" "} ${s.id} ${s.name}`).join(`
|
|
@@ -379,22 +379,22 @@ Useful commands:
|
|
|
379
379
|
`),1}}function f0(t){let e=["\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2588\u2588\u2588\u2557 ","\u2588\u2588\u2554\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2554\u2550\u2550\u255D ","\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],r=t.color?"\x1B[36m":"",n=t.color?"\x1B[2m":"",i=t.color?"\x1B[0m":"";return ["",...e.map(s=>`${r}${s}${i}`),`${n}setup${i}`,""].join(`
|
|
380
380
|
`)}function Oh(t,e,r){if(!t)return;let n=t.candidate_counts,i=t.ok?"ok":"warn";e.write(`${g(i,r)} Bootstrap v2 prepared: ${n.memories} memory candidates, ${n.rules} rule candidates from ${t.coverage.docsFilesScanned} docs files and ${t.coverage.commitsScanned} commits.
|
|
381
381
|
`);let s=t.warnings[0];s&&e.write(`${g("warn",r)} ${s}
|
|
382
|
-
`);}async function g0(t,e){try{return await cr([],t.cwd,t.env,{yes:!1})}catch(r){if(!(r instanceof Qt)||r.code!=="not_authenticated")throw r;return !await
|
|
382
|
+
`);}async function g0(t,e){try{return await cr([],t.cwd,t.env,{yes:!1})}catch(r){if(!(r instanceof Qt)||r.code!=="not_authenticated")throw r;return !await wn(t,"Pathrule CLI is not signed in. Sign in now?",true)||await Kh(t,e)!==0?null:cr([],t.cwd,t.env,{yes:false})}}async function m0(t,e,r){let n=t.candidates.slice(0,5);if(n.length===0){let a=basename(e.cwd)||"Workspace";return await wn(e,`Create a new workspace named "${a}" for this folder?`,true)?["--create-workspace"]:null}e.stdout.write(`Workspace candidates:
|
|
383
383
|
`),n.forEach((a,l)=>{e.stdout.write(`${l+1}. ${a.recommended?"[recommended] ":""}${a.workspace_name} (${a.confidence}) - ${a.reason}
|
|
384
|
-
`);});let i=n[0];if(i&&(i.confidence==="exact"||i.confidence==="high")&&await
|
|
384
|
+
`);});let i=n[0];if(i&&(i.confidence==="exact"||i.confidence==="high")&&await wn(e,`Attach "${i.workspace_name}" to this folder?`,true))return ["--workspace",i.workspace_id];let s=(await hr(e,`Choose workspace [1-${n.length}], c to create new, or q to cancel: `)).trim().toLowerCase();if(!s||s==="q")return null;if(s==="c"||s==="create")return ["--create-workspace"];let o=Number(s);return Number.isInteger(o)&&o>=1&&o<=n.length?["--workspace",n[o-1].workspace_id]:(e.stdout.write(`${g("warn",r)} Invalid selection; setup canceled.
|
|
385
385
|
`),null)}async function _0(t,e){let r=Object.values(U).filter(c=>c.supported),n=await He(t.cwd).catch(()=>[]),i=new Set(n),s=r.map(c=>c.id).filter(c=>i.has(c));if(Jh(t,e))return w0(r,s,i);t.stdout.write(`AI tools:
|
|
386
386
|
`),r.forEach((c,u)=>{t.stdout.write(`${u+1}. ${c.label}${i.has(c.id)?" [detected]":""}
|
|
387
387
|
`);});let o=s.length>0?`Enter for detected (${s.map(c=>U[c].label).join(", ")})`:"Enter to skip",a=(await hr(t,`Select AI tools by number, comma-separated, "all", or "none" (${o}): `)).trim().toLowerCase();if(!a)return s;if(a==="none"||a==="skip")return [];if(a==="all")return r.map(c=>c.id);let l=[];for(let c of a.split(/[,\s]+/).filter(Boolean)){let u=Number(c),d=Number.isInteger(u)?r[u-1]:r.find(p=>p.id===c||p.label.toLowerCase()===c);if(!d){t.stdout.write(`${g("warn",e)} Ignoring unknown AI tool: ${c}
|
|
388
388
|
`);continue}l.includes(d.id)||l.push(d.id);}return l}async function w0(t,e,r){let n=process.stdin,i=process.stdout,s=new Set(e),o=Math.max(0,t.findIndex(c=>s.has(c.id))),a=0,l=()=>{a>0&&i.write(`\x1B[${a}A\x1B[J`);let c=["AI tools","Use \u2191\u2193 to move, space to select, enter to confirm.","",...t.map((u,d)=>{let p=d===o?"\u203A":" ",h=s.has(u.id)?"\u25CF":"\u25CB",f=r.has(u.id)?" [detected]":"";return `${p} ${h} ${u.label}${f}`}),"",`Selected: ${s.size>0?Array.from(s).map(u=>U[u].label).join(", "):"none"}`];i.write(`${c.join(`
|
|
389
389
|
`)}
|
|
390
390
|
`),a=c.length;};emitKeypressEvents(n),n.isTTY&&n.setRawMode(true),n.resume(),i.write("\x1B[?25l"),l();try{return await new Promise((c,u)=>{let d=Date.now()+350,p=()=>{n.off("keypress",f),n.isTTY&&n.setRawMode(!1),n.pause(),i.write("\x1B[?25h");},h=m=>{p(),c(m);},f=(m,_)=>{if(_.ctrl&&_.name==="c"){p(),u(new Error("setup_canceled"));return}if(_.name==="up"){o=(o-1+t.length)%t.length,l();return}if(_.name==="down"){o=(o+1)%t.length,l();return}if(_.name==="space"){let b=t[o];s.has(b.id)?s.delete(b.id):s.add(b.id),l();return}if(_.name==="a"){s.size===t.length?s.clear():t.forEach(b=>s.add(b.id)),l();return}if(_.name==="return"||_.name==="enter"){if(Date.now()<d)return;h(t.map(b=>b.id).filter(b=>s.has(b)));}};n.on("keypress",f);})}finally{i.write(`
|
|
391
|
-
`);}}async function y0(t,e,r){if(r.length===0||!await
|
|
391
|
+
`);}}async function y0(t,e,r){if(r.length===0||!await wn(t,"Start the first project scan now?",true))return;let i=r.length===1?r[0]:await b0(t,e,r);if(!i)return;let s=await S0(t,i);if(s.ok){s.promptDelivered?t.stdout.write(`${g("ok",e)} Opened ${U[i].label} with the project setup prompt.
|
|
392
392
|
`):(t.stdout.write(`${g("ok",e)} Opened ${U[i].label}.
|
|
393
393
|
`),t.stdout.write(`Prompt to run in your AI tool: ${Hi}
|
|
394
394
|
`));return}t.stdout.write(`${g("warn",e)} ${s.error}
|
|
395
395
|
`),t.stdout.write(`Prompt to run in your AI tool: ${Hi}
|
|
396
396
|
`);}async function k0(t,e){let r=await Ni(t.env);if(!r.supported||r.enabled){t.stdout.write(`Manual start: pathrule start
|
|
397
|
-
`);return}if(!await
|
|
397
|
+
`);return}if(!await wn(t,"Start Pathrule automatically when you sign in?",true)){t.stdout.write(`Manual start: pathrule start
|
|
398
398
|
`);return}try{let i=await Xe(t.env,!0);i.supported&&i.enabled?t.stdout.write(`${g("ok",e)} Daemon autostart enabled.
|
|
399
399
|
`):t.stdout.write(`${g("warn",e)} Daemon autostart could not be enabled.
|
|
400
400
|
`);}catch(i){t.stdout.write(`${g("warn",e)} Daemon autostart could not be enabled. ${i instanceof Error?i.message:String(i)}
|
|
@@ -411,7 +411,7 @@ tell application "Terminal" to activate`;spawn("osascript",["-e",s],{detached:tr
|
|
|
411
411
|
|
|
412
412
|
${t}`}function bh(t){return `'${t.replace(/'/g,"'\\''")}'`}function x0(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}async function P0(t,e,r){let{session:n,supabase:i}=await C(t),{error:s}=await i.from("user_workspace_paths").update({selected_ai_clients:r}).eq("user_id",n.user.id).eq("workspace_id",e);if(s)throw new Error(`workspace_client_selection_update_failed: ${s.message}`)}function T0(t){if(!t||typeof t!="object")return null;let e=t;return typeof e.workspace?.id!="string"||typeof e.local_root_path!="string"?null:{workspaceId:e.workspace.id,localRootPath:e.local_root_path}}async function A0(t,e,r){try{let n=await xe(t,e.cwd,e.env);return e.stdout.write(`${g("ok",r)} Attached ${n.workspace.name} to ${n.local_root_path}
|
|
413
413
|
`),await Qe(e,r),await dr(e,r),0}catch(n){return e.stderr.write(`${g("error",r)} ${n instanceof Error?n.message:String(n)}
|
|
414
|
-
`),1}}async function I0(t,e,r){try{let n=await
|
|
414
|
+
`),1}}async function I0(t,e,r){try{let n=await Gr(t,e.env);return e.stdout.write(`${g("ok",r)} Detached ${n.name} from this machine.
|
|
415
415
|
`),0}catch(n){return e.stderr.write(`${g("error",r)} ${n instanceof Error?n.message:String(n)}
|
|
416
416
|
`),1}}async function O0(t,e,r){if(!t||!Ko(t))return e.stderr.write(`${g("error",r)} Usage: pathrule preflight <create_workspace|write_memory|write_rule|write_skill|sync_agents|materialize_skills>
|
|
417
417
|
`),64;try{let n=await ae(t,e.env);return n.allowed?(e.stdout.write(`${g("ok",r)} ${t} is allowed.
|
|
@@ -436,10 +436,10 @@ ${t}`}function bh(t){return `'${t.replace(/'/g,"'\\''")}'`}function x0(t){return
|
|
|
436
436
|
`),0):(t.stdout.write(`${g("info",e)} Update check skipped: ${r.reason}
|
|
437
437
|
`),0)}async function L0(t,e){if(!e.interactive)return;let r=await wh(Ue.version,t.env,t.fetch??fetch).catch(()=>null);r&&t.stderr.write(`${g("info",e)} ${r}
|
|
438
438
|
`);}async function U0(t,e){t.stdout.write(`Pathrule
|
|
439
|
-
`);let r=await
|
|
439
|
+
`);let r=await dn(pr(t.env));return r.running&&r.state?t.stdout.write(`${g("ok",e)} Local Web bridge is running on 127.0.0.1:${r.state.port}.
|
|
440
440
|
`):t.stdout.write(`${g("info",e)} Local Web bridge is not running.
|
|
441
441
|
`),t.stdout.write(`Next: pathrule bridge pair
|
|
442
|
-
`),0}async function W0(t,e,r){let n=t[0]??"status";try{if(n==="run")return await Tp(e.env),0;if(n==="autostart"||n==="toggle")return B0(n==="toggle"?"toggle":t[1]??"status",e,r);let i=n==="start"?await
|
|
442
|
+
`),0}async function W0(t,e,r){let n=t[0]??"status";try{if(n==="run")return await Tp(e.env),0;if(n==="autostart"||n==="toggle")return B0(n==="toggle"?"toggle":t[1]??"status",e,r);let i=n==="start"?await dn(pr(e.env)):n==="stop"?await pn(e.env):n==="status"?await Le(e.env):null;return i?(i.running&&i.state?e.stdout.write(`${g("ok",r)} Daemon running on 127.0.0.1:${i.state.port} (pid ${i.state.pid})
|
|
443
443
|
`):e.stdout.write(`${g("info",r)} Daemon not running (${i.reason??"unknown"}).
|
|
444
444
|
`),0):(e.stderr.write(`${g("error",r)} Usage: pathrule daemon start|stop|status|autostart on|autostart off|autostart status|toggle
|
|
445
445
|
`),64)}catch(i){return e.stderr.write(`${g("error",r)} ${i instanceof Error?i.message:String(i)}
|
|
@@ -453,9 +453,9 @@ ${t}`}function bh(t){return `'${t.replace(/'/g,"'\\''")}'`}function x0(t){return
|
|
|
453
453
|
`),e.stdout.write(`${g("info",r)} Open ${o.url} and paste the code.
|
|
454
454
|
`),e.stdout.write(`${g("info",r)} Expires at ${o.expires_at}
|
|
455
455
|
`),0}catch(n){return e.stderr.write(`${g("error",r)} ${n instanceof Error?n.message:String(n)}
|
|
456
|
-
`),1}}function pr(t){let e=t.PATHRULE_DAEMON_PORT?.trim();return {...t,PATHRULE_DAEMON_PORT:e&&e.length>0?e:String($i)}}async function Ta(t){let e=H0(t),r=await Le(t);return r.running&&(e===0||r.state?.port===e)?{status:r,changed:false}:(r.running&&r.state?.port!==e&&await
|
|
456
|
+
`),1}}function pr(t){let e=t.PATHRULE_DAEMON_PORT?.trim();return {...t,PATHRULE_DAEMON_PORT:e&&e.length>0?e:String($i)}}async function Ta(t){let e=H0(t),r=await Le(t);return r.running&&(e===0||r.state?.port===e)?{status:r,changed:false}:(r.running&&r.state?.port!==e&&await pn(t),{status:await dn(t),changed:true})}function H0(t){let e=t.PATHRULE_DAEMON_PORT?.trim()||String($i),r=Number(e);if(!Number.isInteger(r)||r<0||r>65535)throw new Error("daemon_port_invalid");return r}async function Qe(t,e,r={}){if(!e.interactive||t.env.PATHRULE_DAEMON_AUTOSTART==="0")return;let n=pr(t.env);try{let i=await Ta(n);i.changed&&i.status.running&&i.status.state&&t.stdout.write(`${g("info",e)} Local Web bridge ready on 127.0.0.1:${i.status.state.port}.
|
|
457
457
|
`);}catch(i){t.stderr.write(`${g("warn",e)} Local Web bridge could not start. ${r.manualHint??"Run pathrule start to start it manually."} (${i instanceof Error?i.message:String(i)})
|
|
458
|
-
`);}}async function q0(t,e){if(!(!e.interactive||t.env.PATHRULE_DAEMON_AUTOSTART==="0"))try{if(!(await Le(t.env)).running)return;await
|
|
458
|
+
`);}}async function q0(t,e){if(!(!e.interactive||t.env.PATHRULE_DAEMON_AUTOSTART==="0"))try{if(!(await Le(t.env)).running)return;await pn(t.env),t.stdout.write(`${g("info",e)} Local Web bridge stopped.
|
|
459
459
|
`);}catch(r){t.stderr.write(`${g("warn",e)} Local Web bridge could not stop. (${r instanceof Error?r.message:String(r)})
|
|
460
460
|
`);}}async function z0(t,e,r){try{if(t.includes("--bundle")){let o=await Lo(e.env,e.cwd);return e.stdout.write(`${g("ok",r)} Support bundle written: ${o.path}
|
|
461
461
|
`),o.ok?0:1}let n=await je(e.env,e.cwd);if(e.stdout.write(`Pathrule doctor
|
|
@@ -503,28 +503,28 @@ ${t}
|
|
|
503
503
|
`)):e.stderr.write(`${n.open_target.url}
|
|
504
504
|
`)),Rh(e.stderr,n.next_steps),1)}catch(n){return n instanceof Pe?(e.stderr.write(`${g("error",r)} ${n.message}
|
|
505
505
|
`),64):(e.stderr.write(`${g("error",r)} ${n instanceof Error?n.message:String(n)}
|
|
506
|
-
`),1)}}async function X0(t,e,r){try{let n=qh(t),i=await ka(e.env,n.orgSelector),s=await
|
|
506
|
+
`),1)}}async function X0(t,e,r){try{let n=qh(t),i=await ka(e.env,n.orgSelector),s=await _n(i.organization.slug,e.env,"members",{preferDesktopApp:n.preferDesktopApp,forceWeb:n.forceWeb});return n.open?(r.interactive&&!r.noOpen?(await We(e,s.url),e.stdout.write(`${g("ok",r)} Opened ${s.url}
|
|
507
507
|
`)):e.stdout.write(`${s.url}
|
|
508
|
-
`),0):(e.stdout.write([`${
|
|
508
|
+
`),0):(e.stdout.write([`${En(i.organization.name)} (${i.organization.slug})`,`${g("info",r)} Your role: ${i.organization.role}`,"","Members",...i.members.map(o=>`- ${En(o.email??o.user_id)} \xB7 ${o.role}${o.full_name?` \xB7 ${En(o.full_name)}`:""}`),"","Pending invites",...i.invites.length?i.invites.map(o=>`- ${o.email} \xB7 ${o.role} \xB7 expires ${o.expires_at}`):["- none"],"",`${s.label}: ${s.url}`,""].join(`
|
|
509
509
|
`)),0)}catch(n){return e.stderr.write(`${g("error",r)} ${n instanceof Error?n.message:String(n)}
|
|
510
|
-
`),1}}async function jh(t,e){try{let r=await Dh(e,t);return {exitCode:0,envelope:k({command:"open",cwd:t.cwd,ok:!0,data:r})}}catch(r){return {exitCode:1,envelope:k({command:"open",cwd:t.cwd,ok:false,error:{code:"open_target_failed",message:r instanceof Error?r.message:String(r)}})}}}async function Z0(t,e,r){let n=await jh(e,[Lh(t),...r]);return {...n,envelope:{...n.envelope,command:t}}}async function Q0(t,e){try{let r=await la(aa(e),t.env);return {exitCode:r.ok?0:1,envelope:k({command:"invite",cwd:t.cwd,ok:r.ok,data:r,error:r.ok?void 0:{code:r.error,message:r.message},next_steps:r.next_steps})}}catch(r){let n=V(r,"invite_failed");return {exitCode:r instanceof Pe?64:1,envelope:k({command:"invite",cwd:t.cwd,ok:false,error:{code:n,message:r instanceof Error?r.message:String(r)}})}}}async function eE(t,e){try{let r=qh(e),n=await ka(t.env,r.orgSelector),i=await
|
|
510
|
+
`),1}}async function jh(t,e){try{let r=await Dh(e,t);return {exitCode:0,envelope:k({command:"open",cwd:t.cwd,ok:!0,data:r})}}catch(r){return {exitCode:1,envelope:k({command:"open",cwd:t.cwd,ok:false,error:{code:"open_target_failed",message:r instanceof Error?r.message:String(r)}})}}}async function Z0(t,e,r){let n=await jh(e,[Lh(t),...r]);return {...n,envelope:{...n.envelope,command:t}}}async function Q0(t,e){try{let r=await la(aa(e),t.env);return {exitCode:r.ok?0:1,envelope:k({command:"invite",cwd:t.cwd,ok:r.ok,data:r,error:r.ok?void 0:{code:r.error,message:r.message},next_steps:r.next_steps})}}catch(r){let n=V(r,"invite_failed");return {exitCode:r instanceof Pe?64:1,envelope:k({command:"invite",cwd:t.cwd,ok:false,error:{code:n,message:r instanceof Error?r.message:String(r)}})}}}async function eE(t,e){try{let r=qh(e),n=await ka(t.env,r.orgSelector),i=await _n(n.organization.slug,t.env,"members",{preferDesktopApp:r.preferDesktopApp,forceWeb:r.forceWeb});return {exitCode:0,envelope:k({command:"team",cwd:t.cwd,ok:!0,data:r.open?i:{...n,open_target:i}})}}catch(r){let n=V(r,"team_failed");return {exitCode:n.startsWith("unknown_team_option")?64:1,envelope:k({command:"team",cwd:t.cwd,ok:false,error:{code:n,message:r instanceof Error?r.message:String(r)}})}}}async function Dh(t,e){let r=t.find(s=>s&&!["--web","--desktop-app","--no-open"].includes(s)),n=t.includes("--web"),i=t.includes("--desktop-app")&&!n;if(!r){let s=await ur(e);return s?qi(s.id,e.env,{preferDesktopApp:i,forceWeb:n}):nE(e.env)}if(r==="workspace"||r==="--workspace"){let s=await ur(e);if(!s)throw new Error("workspace_required");return qi(s.id,e.env,{preferDesktopApp:i,forceWeb:n})}if(r==="workspace-settings"||r==="--workspace-settings"){let s=await ur(e);if(!s)throw new Error("workspace_required");return vh(s.id,e.env,"settings",n)}if(r==="agent-setup"||r==="agents"||r==="ai-tools"||r==="--agent-setup"){let s=await ur(e);if(!s)throw new Error("workspace_required");return vh(s.id,e.env,"ai-tools",n)}if(r==="org"||r==="--org"){let s=await j(e.env);if(!s)throw new Error("org_required");return _n(s.slug,e.env,"home",{preferDesktopApp:i,forceWeb:n})}if(r==="team"||r==="--team")return Sa(e.env,"members",n,i);if(r==="billing"||r==="--billing"||r==="upgrade"||r==="--upgrade")return Sa(e.env,"billing",n,i);if(r==="settings"||r==="--settings")return Sa(e.env,"settings",n,i);if(r==="reactivate"||r==="--reactivate"){let s=await j(e.env);if(!s)throw new Error("org_required");return _n(s.slug,e.env,"reactivate",{preferDesktopApp:i,forceWeb:n})}throw new Error("invalid_open_target")}async function ur(t){let e=await Re(t.env);return Mh(e,t.cwd)??tE(e)}function tE(t){let e=t.find(r=>r.current);return e||(t.length===1?t[0]??null:null)}function Mh(t,e){let r=t.filter(n=>n.local_root_path?rE(n.local_root_path,e):false);return r.sort((n,i)=>(i.local_root_path?.length??0)-(n.local_root_path?.length??0)),r[0]??null}function rE(t,e){let r=resolve(t),n=resolve(e),i=relative(r,n);return i===""||!i.startsWith("..")&&!isAbsolute(i)}function nE(t){return {kind:"web",url:(t.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,""),label:"Open Pathrule Web",reason:"preferred"}}async function Sa(t,e,r,n){let i=await j(t);if(!i)throw new Error("org_required");return _n(i.slug,t,e,{preferDesktopApp:n,forceWeb:r})}function Lh(t){return t==="team"?"team":t==="upgrade"?"upgrade":t==="reactivate"?"reactivate":"billing"}function Aa(t,e){return `${(e.PATHRULE_WEB_URL??"https://app.pathrule.io").replace(/\/$/,"")}/workspace/${encodeURIComponent(t)}`}function iE(t,e,r){let n=`${Aa(t,e)}/settings`;return r==="ai-tools"?`${n}/ai-tools`:n}function vh(t,e,r,n=false){return {kind:"web",url:iE(t,e,r),label:r==="ai-tools"?"Open AI tools in Pathrule Web":"Open workspace settings in Pathrule Web",reason:n?"forced":"preferred"}}async function qi(t,e,r={}){return r.preferDesktopApp&&!r.forceWeb?{kind:"desktop-app",url:`pathrule://workspace/${encodeURIComponent(t)}`,label:"Open workspace in Pathrule Desktop",reason:"forced"}:!r.forceWeb&&await Ia(e,"workspace")?{kind:"desktop-app",url:`pathrule://workspace/${encodeURIComponent(t)}`,label:"Open workspace in Pathrule Desktop",reason:"preferred"}:{kind:"web",url:Aa(t,e),label:"Open workspace in Pathrule Web",reason:r.forceWeb?"forced":"preferred"}}async function _n(t,e,r,n={}){let i=r==="reactivate"?"billing":r,s={slug:t},o=r==="reactivate"?`${ee(s,e,"billing")}/reactivate`:ee(s,e,i),a=r==="billing"?"Open billing in Pathrule Web":r==="members"?"Open team in Pathrule Web":r==="settings"?"Open settings in Pathrule Web":r==="reactivate"?"Open billing reactivation in Pathrule Web":"Open organization in Pathrule Web";if(n.preferDesktopApp&&!n.forceWeb){let c=r==="members"?"team":r;return {kind:"desktop-app",url:`pathrule://org/${encodeURIComponent(t)}/${c}`,label:a.replace("Pathrule Web","Pathrule Desktop"),reason:"forced"}}let l=r==="members"?"team":r;return !n.forceWeb&&await Ia(e,`org:${l}`)?{kind:"desktop-app",url:`pathrule://org/${encodeURIComponent(t)}/${l}`,label:a.replace("Pathrule Web","Pathrule Desktop"),reason:"preferred"}:{kind:"web",url:o,label:a,reason:n.forceWeb?"forced":"preferred"}}async function Ia(t,e,r=Date.now()){let n=t.PATHRULE_DESKTOP_HEALTH?.trim().toLowerCase();if(n==="healthy"||n==="1"||n==="true")return true;if(n==="unhealthy"||n==="0"||n==="false")return false;let i;try{i=JSON.parse(await readFile(A(t).desktopFile,"utf8"));}catch{return false}if(i.healthy!==true||!i.updated_at)return false;let s=Date.parse(i.updated_at);return !(!Number.isFinite(s)||r-s>600*1e3||i.routes&&!i.routes.includes(e)&&!i.routes.includes("*"))}function Ca(t,e){return `${t} / ${e===-1?"unlimited":e}`}async function sE(t,e,r,n){try{let i=e[0]??"list";if(i==="add"){let a=Wh(t,e.slice(1)),l=await ae(Fh(t),r.env);if(!l.allowed)return Ki(l,r.stderr,n),1;let c=await Bh(t,a,r),u=await ko(t,c,r.env);r.stdout.write(`${g("ok",n)} Created ${t}: ${u.item.title}
|
|
511
511
|
`),r.stdout.write(`${g("info",n)} Path: ${u.item.path}
|
|
512
512
|
`),a.open?await Fi({kind:t,title:u.item.title,totalResults:1,target:u.item.open_targets[0],runtime:r,mode:n}):r.stdout.write(`${g("info",n)} URL: ${u.item.url}
|
|
513
513
|
`);for(let d of u.warnings)r.stdout.write(`${g("warn",n)} ${d.message??d.code}
|
|
514
514
|
`);return 0}let s=zi(e.slice(1));if(i==="read"){let a=s.positionals[0];if(!a)return r.stderr.write(`${g("error",n)} Usage: pathrule ${t} read <id-or-title>
|
|
515
515
|
`),64;let l=await mo(t,a,r.env);return s.open||!Du(l.content,s.print)?(await Fi({kind:t,title:l.title,totalResults:1,target:await xa(l,s,r.env),runtime:r,mode:n,reason:s.open?void 0:"Content is long, so Pathrule CLI is pointing you to Pathrule Web by default. Pass --print to view it in the terminal."}),0):(r.stdout.write([`${l.kind}: ${l.title}`,`Path: ${l.path??"/"}`,`URL: ${l.url}`,"",l.content,""].join(`
|
|
516
516
|
`)),0)}if(i!=="list")return r.stderr.write(`${g("error",n)} Usage: pathrule ${t} list|read|add
|
|
517
|
-
`),64;let o=await
|
|
517
|
+
`),64;let o=await Yr(t,r.env,s);if(Uh(r.stdout,n,o),s.open&&o.length>0){let a=await zh(t,o,r,n);if(!a)return 0;await Fi({kind:t,title:a.item.title,totalResults:o.length,selectionIndex:a.index,target:await xa(a.item,s,r.env),runtime:r,mode:n});}return 0}catch(i){return i instanceof X?(r.stderr.write(`${g("error",n)} ${i.message}
|
|
518
518
|
`),64):(r.stderr.write(`${g("error",n)} ${i instanceof Error?i.message:String(i)}
|
|
519
519
|
`),1)}}async function oE(t,e,r){try{let n=zi(t),i=n.positionals.join(" ").trim();if(!i)return e.stderr.write(`${g("error",r)} Usage: pathrule search <query>
|
|
520
520
|
`),64;let s=await go(i,e.env,{...n,types:n.types});if(Uh(e.stdout,r,s),n.open&&s.length>0){let o=await zh("result",s,e,r);if(!o)return 0;await Fi({kind:o.item.kind,title:o.item.title,totalResults:s.length,selectionIndex:o.index,target:await xa(o.item,n,e.env),runtime:e,mode:r});}return 0}catch(n){return e.stderr.write(`${g("error",r)} ${n instanceof Error?n.message:String(n)}
|
|
521
|
-
`),1}}async function aE(t,e,r){let n=t[0]??"list";try{if(n==="list"){let i=Ze(t.slice(1)),s=await
|
|
521
|
+
`),1}}async function aE(t,e,r){let n=t[0]??"list";try{if(n==="list"){let i=Ze(t.slice(1)),s=await hn(e.env,{includeInProgress:i.includeInProgress,limit:i.limit});if(gE(e.stdout,r,s),i.open&&s.length>0){let o=s[0];if(!o)return 0;await Eh({target:ji(o,{forceWeb:i.forceWeb,preferDesktopApp:i.preferDesktopApp}),title:o.subjectTitle,totalResults:s.length,runtime:e,mode:r});}return 0}if(n==="claim"){let i=Ze(t.slice(1)),s=await ca(e.env,i.positionals[0]);return mE(e.stdout,r,s),0}if(n==="resolve"){let i=Ze(t.slice(1)),s=i.positionals[0];if(!s)return e.stderr.write(`${g("error",r)} Usage: pathrule refresh resolve <refresh-id> --status applied|rejected [--note "..."]
|
|
522
522
|
`),64;if(i.status!=="applied"&&i.status!=="rejected")return e.stderr.write(`${g("error",r)} Usage: pathrule refresh resolve <refresh-id> --status applied|rejected [--note "..."]
|
|
523
523
|
`),64;let o=await ua(e.env,s,i.status,{note:i.note});return e.stdout.write(`${g("ok",r)} Refresh task marked ${o.status}.
|
|
524
524
|
`),o.resolvedNote&&e.stdout.write(`${g("info",r)} Note: ${o.resolvedNote}
|
|
525
525
|
`),0}if(n==="open"){let i=Ze(t.slice(1)),s=await da(e.env,i.positionals[0]);return await Eh({target:ji(s,{forceWeb:i.forceWeb,preferDesktopApp:i.preferDesktopApp}),title:s.subjectTitle,totalResults:1,runtime:e,mode:r}),0}return e.stderr.write(`${g("error",r)} Usage: pathrule refresh list|claim|resolve|open
|
|
526
526
|
`),64}catch(i){return e.stderr.write(`${g("error",r)} ${i instanceof Error?i.message:String(i)}
|
|
527
|
-
`),V(i,"refresh_failed")==="workspace_required",1}}async function lE(t,e){let r=await
|
|
527
|
+
`),V(i,"refresh_failed")==="workspace_required",1}}async function lE(t,e){let r=await sn(t.env,t.cwd),n=ip(r);t.stdout.write(`Pathrule repair
|
|
528
528
|
`),t.stdout.write(`${g(n.ok?"ok":"error",e)} ${n.headline}${r.error?`: ${r.error}`:""}
|
|
529
529
|
`);for(let i of n.sections){t.stdout.write(`
|
|
530
530
|
${i.title}
|
|
@@ -535,7 +535,7 @@ Next: ${n.next_command}
|
|
|
535
535
|
`),64;let s=await Go(e.env,{dryRun:!n});return s.dry_run?(e.stdout.write(`${g("warn",r)} Dry run: ${s.candidates.length} stale epoch cache dirs found
|
|
536
536
|
`),e.stdout.write(`Run pathrule cache prune --yes to remove them.
|
|
537
537
|
`)):e.stdout.write(`${g("ok",r)} Removed ${s.candidates.filter(o=>o.removed).length} stale epoch cache dirs
|
|
538
|
-
`),0}async function uE(t,e,r){try{let n=r[0]??"list";if(n==="add"){let o=Wh(t,r.slice(1)),a=await ae(Fh(t),e.env);if(!a.allowed){let u=sr(a);return {exitCode:1,envelope:k({command:`${t} add`,cwd:e.cwd,ok:!1,error:{code:a.blocking_reason??"preflight_blocked",message:u.summary,remediation:Ji(u)}})}}let l=await Bh(t,o,e),c=await ko(t,l,e.env);return {exitCode:0,envelope:k({command:`${t} add`,cwd:e.cwd,ok:!0,data:{...c,open_target:c.item.open_targets[0]??null}})}}let i=zi(r.slice(1)),s=n==="read"?await mo(t,Oa(i.positionals[0],`${t}_selector_required`),e.env):await
|
|
538
|
+
`),0}async function uE(t,e,r){try{let n=r[0]??"list";if(n==="add"){let o=Wh(t,r.slice(1)),a=await ae(Fh(t),e.env);if(!a.allowed){let u=sr(a);return {exitCode:1,envelope:k({command:`${t} add`,cwd:e.cwd,ok:!1,error:{code:a.blocking_reason??"preflight_blocked",message:u.summary,remediation:Ji(u)}})}}let l=await Bh(t,o,e),c=await ko(t,l,e.env);return {exitCode:0,envelope:k({command:`${t} add`,cwd:e.cwd,ok:!0,data:{...c,open_target:c.item.open_targets[0]??null}})}}let i=zi(r.slice(1)),s=n==="read"?await mo(t,Oa(i.positionals[0],`${t}_selector_required`),e.env):await Yr(t,e.env,i);return {exitCode:0,envelope:k({command:t,cwd:e.cwd,ok:!0,data:s})}}catch(n){return {exitCode:n instanceof X?64:1,envelope:k({command:r[0]==="add"?`${t} add`:t,cwd:e.cwd,ok:false,error:{code:V(n,"content_command_failed"),message:n instanceof Error?n.message:String(n)}})}}}async function dE(t,e){try{let r=zi(e),n=Oa(r.positionals.join(" ").trim(),"search_query_required"),i=await go(n,t.env,r);return {exitCode:0,envelope:k({command:"search",cwd:t.cwd,ok:!0,data:i})}}catch(r){return {exitCode:1,envelope:k({command:"search",cwd:t.cwd,ok:false,error:{code:"search_failed",message:r instanceof Error?r.message:String(r)}})}}}async function pE(t,e){let r=e[0]??"list";try{if(r==="list"){let n=Ze(e.slice(1)),i=await hn(t.env,{includeInProgress:n.includeInProgress,limit:n.limit});return {exitCode:0,envelope:k({command:"refresh list",cwd:t.cwd,ok:!0,data:i})}}if(r==="claim"){let n=Ze(e.slice(1)),i=await ca(t.env,n.positionals[0]);return {exitCode:0,envelope:k({command:"refresh claim",cwd:t.cwd,ok:!0,data:i})}}if(r==="resolve"){let n=Ze(e.slice(1)),i=Oa(n.positionals[0],"refresh_id_required");if(n.status!=="applied"&&n.status!=="rejected")throw new Error("refresh_status_required");let s=await ua(t.env,i,n.status,{note:n.note});return {exitCode:0,envelope:k({command:"refresh resolve",cwd:t.cwd,ok:!0,data:s})}}if(r==="open"){let n=Ze(e.slice(1)),i=await da(t.env,n.positionals[0]),s={refresh:i,open_target:ji(i,{forceWeb:n.forceWeb,preferDesktopApp:n.preferDesktopApp})};return {exitCode:0,envelope:k({command:"refresh open",cwd:t.cwd,ok:!0,data:s})}}return {exitCode:64,envelope:k({command:"refresh",cwd:t.cwd,ok:!1,error:{code:"usage",message:"Usage: pathrule refresh list|claim|resolve|open"}})}}catch(n){let i=V(n,"refresh_failed");return {exitCode:i==="refresh_id_required"||i==="refresh_status_required"?64:1,envelope:k({command:r==="list"?"refresh list":`refresh ${r}`,cwd:t.cwd,ok:false,error:{code:i,message:n instanceof Error?n.message:String(n),remediation:i==="workspace_required"?[{label:"Select a workspace",command:"pathrule workspace use <name-or-id>"}]:void 0}})}}}async function hE(t){let e=await sn(t.env,t.cwd);return {exitCode:e.ok?0:1,envelope:k({command:"repair",cwd:t.cwd,ok:e.ok,data:e.ok?e:void 0,error:e.ok?void 0:{code:"repair_failed",message:e.error??"Repair incomplete"}})}}async function fE(t,e,r){if((e[0]??"prune")!=="prune")return {exitCode:64,envelope:k({command:"cache",cwd:t.cwd,ok:false,error:{code:"usage",message:"Usage: pathrule cache prune [--yes]"}})};let i=await Go(t.env,{dryRun:!r});return {exitCode:0,envelope:k({command:"cache",cwd:t.cwd,ok:true,data:i})}}function Uh(t,e,r){if(r.length===0){t.write(`${g("warn",e)} No content found.
|
|
539
539
|
`);return}for(let n of r)t.write([`${n.kind.padEnd(6)} ${n.title}`,` ${n.path??"/"} ${n.updated_at??""}`,n.preview?` ${n.preview}`:"",` ${n.url}`].filter(Boolean).join(`
|
|
540
540
|
`)+`
|
|
541
541
|
`);}function gE(t,e,r){if(r.length===0){t.write(`${g("warn",e)} No pending refresh tasks.
|
|
@@ -554,12 +554,12 @@ Proposed patch: ${r.brief.proposedPatch.reasoning} (confidence ${r.brief.propose
|
|
|
554
554
|
`),1;let o=Hh(e[0]),a=ee(s,r.env,o);return n.interactive&&!n.noOpen?(await We(r,a),r.stdout.write(`${g("ok",n)} Opened ${a}
|
|
555
555
|
`)):r.stdout.write(`${a}
|
|
556
556
|
`),0}if(t!=="list")return r.stderr.write(`${g("error",n)} Unknown org command "${t}".
|
|
557
|
-
`),64;let i=await
|
|
557
|
+
`),64;let i=await we(r.env);return i.length===0?(r.stdout.write(`${g("warn",n)} No organizations found.
|
|
558
558
|
`),0):(r.stdout.write(i.map(s=>`${s.current?"*":" "} ${s.slug} ${s.role} ${s.name}`).join(`
|
|
559
559
|
`)+`
|
|
560
560
|
`),0)}catch(i){return r.stderr.write(`${g("error",n)} ${i instanceof Error?i.message:String(i)}
|
|
561
561
|
`),1}}function Hh(t){if(!t||t==="home")return "home";if(t==="billing"||t==="settings"||t==="members")return t;throw new Error("invalid_org_open_target")}function qh(t){let e=false,r,n=false,i=false;for(let s=0;s<t.length;s+=1){let o=t[s];if(o){if(o==="open"||o==="--open"){e=true;continue}if(o==="--org"){r=t[++s];continue}if(o==="--desktop-app"){n=true;continue}if(o==="--web"){i=true;continue}throw new Error(`unknown_team_option:${o}`)}}return {open:e,orgSelector:r,preferDesktopApp:n,forceWeb:i}}async function yE(t){if(process.platform==="darwin"){await Bi("open",[t]);return}if(process.platform==="win32"){await Bi("cmd",["/c","start","",t]);return}await Bi("xdg-open",[t]);}async function We(t,e){if(t.openUrl){await t.openUrl(e);return}await yE(e);}async function kE(){return new Promise((t,e)=>{let r="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{r+=n;}),process.stdin.on("end",()=>t(r)),process.stdin.on("error",e);})}async function bE(t,e,r){let n=t.env.VISUAL?.trim()||t.env.EDITOR?.trim();if(!n)throw new X("editor_required","Set $EDITOR or pass --body / stdin for this command.");let i=await mkdtemp(join(tmpdir(),"pathrule-cli-edit-")),s=join(i,r);await writeFile(s,e,"utf8");try{return await vE(n,s,t.env),await readFile(s,"utf8")}finally{await rm$1(i,{recursive:true,force:true});}}async function vE(t,e,r){let n=`${t} ${JSON.stringify(e)}`;await new Promise((i,s)=>{let o=spawn(n,{env:r,shell:true,stdio:"inherit"});o.once("error",s),o.once("exit",a=>{if(a===0){i();return}s(new Error(`editor_exit_${a??"signal"}`));});});}async function xa(t,e,r){return Mu(t,{forceWeb:e.forceWeb,preferDesktopApp:e.preferDesktopApp||!e.forceWeb&&await Ia(r,"workspace")})}async function zh(t,e,r,n){let i=e[0];if(!i)return null;if(e.length===1||!SE(r,n))return {item:i,index:1};let s=(await hr(r,`Select ${t} to open [1-${e.length}] (Enter for 1): `)).trim();if(!s)return {item:i,index:1};let o=Number(s);return !Number.isInteger(o)||o<1||o>e.length?(r.stdout.write(`${g("warn",n)} Invalid selection; opening the top match.
|
|
562
|
-
`),{item:i,index:1}):{item:e[o-1],index:o}}function SE(t,e){return !e.interactive||e.noOpen?false:t.promptLine?true:process.env.NODE_ENV==="test"?false:!!(process.stdin.isTTY&&process.stdout.isTTY)}function CE(t,e){return !e.interactive||e.json?false:t.promptLine?true:process.env.NODE_ENV==="test"?false:!!(process.stdin.isTTY&&process.stdout.isTTY)}function Jh(t,e){return !e.interactive||e.json||t.promptLine||process.env.NODE_ENV==="test"?false:!!(process.stdin.isTTY&&process.stdout.isTTY)}async function
|
|
562
|
+
`),{item:i,index:1}):{item:e[o-1],index:o}}function SE(t,e){return !e.interactive||e.noOpen?false:t.promptLine?true:process.env.NODE_ENV==="test"?false:!!(process.stdin.isTTY&&process.stdout.isTTY)}function CE(t,e){return !e.interactive||e.json?false:t.promptLine?true:process.env.NODE_ENV==="test"?false:!!(process.stdin.isTTY&&process.stdout.isTTY)}function Jh(t,e){return !e.interactive||e.json||t.promptLine||process.env.NODE_ENV==="test"?false:!!(process.stdin.isTTY&&process.stdout.isTTY)}async function wn(t,e,r){let n=" [Y/n]: ";if(!t.promptLine&&process.stdin.isTTY&&process.stdout.isTTY)return EE(e,n,r);let i=(await hr(t,`${e}${n}`)).trim().toLowerCase();return i?i==="y"||i==="yes":r}async function EE(t,e,r){let n=process.stdin,i=process.stdout,s=n.isPaused();i.write(`${t}${e}`),n.isTTY&&n.setRawMode(true),n.resume();try{return await new Promise((o,a)=>{let l=!1,c=()=>{n.off("data",d),n.isTTY&&n.setRawMode(!1),n.pause();},u=(p,h)=>{l||(l=!0,i.write(`${h}
|
|
563
563
|
`),c(),o(p));},d=p=>{let h=p.toString("utf8");if(h.includes("")){if(l)return;l=!0,c(),i.write(`
|
|
564
564
|
`),a(new Error("setup_canceled"));return}if(h.includes("\r")||h.includes(`
|
|
565
565
|
`)){u(r,r?"Y":"N");return}if(/[yY]/.test(h)){u(!0,"Y");return}/[nN]/.test(h)&&u(!1,"N");};n.on("data",d);})}finally{n.isTTY&&n.setRawMode(false),(s||!n.isPaused())&&n.pause();}}async function hr(t,e){if(t.promptLine)return t.promptLine(e);let r=createInterface({input:process.stdin,output:process.stdout});try{return await r.question(e)}finally{r.close();}}async function Fi(t){let{runtime:e,mode:r,target:n,title:i,totalResults:s,kind:o,reason:a,selectionIndex:l}=t;if(a&&e.stdout.write(`${g("info",r)} ${a}
|