@supabase/lite 0.6.1-next.3 → 0.6.1-next.5
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/STATUS.md +2 -0
- package/dist/cli/index.js +111 -108
- package/dist/cli/lib.js +38 -35
- package/dist/index.d.ts +6 -0
- package/dist/index.js +38 -38
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
2
|
+
import Bn,{statSync,readFileSync}from'node:fs';import*as pe from'node:fs/promises';import pe__default,{stat,constants}from'node:fs/promises';import*as ze from'node:path';import ze__default,{join}from'node:path';import {fileURLToPath}from'node:url';import {createConnection}from'@supabase/lite/sqlite';import Cw from'node:os';import {createClient}from'@supabase/supabase-js';import m_,{createHash}from'node:crypto';import {parse}from'dotenv';import {DataLossError,isEqual,measureTime,splitSqlStatements,ensureVar,App,cloud}from'@supabase/lite';import {createRequire}from'module';import bf,{posix,sep,basename,dirname,resolve,normalize,relative}from'path';import*as or from'fs';import or__default from'fs';import {fileURLToPath as fileURLToPath$1}from'url';import {Deparser,QuoteUtils}from'pgsql-deparser';import bE from'chokidar';import {styleText,promisify}from'node:util';import We,{stdout,stdin}from'node:process';import*as wt from'node:readline';import wt__default from'node:readline';import {ReadStream}from'node:tty';import {DeparserContext}from'pgsql-deparser/visitors/base.js';import {SqlFormatter}from'pgsql-deparser/utils/sql-formatter.js';import {Buffer as Buffer$1}from'node:buffer';import Z0 from'node:net';import {Command as Command$1}from'@commander-js/extra-typings';import M_,{execFile}from'node:child_process';import {Command}from'commander';try {
|
|
3
3
|
/**
|
|
4
4
|
* Adding this to avoid warnings from node:sqlite being experimental
|
|
5
5
|
*/
|
|
@@ -10,39 +10,39 @@ import Fn,{statSync,readFileSync}from'node:fs';import*as pe from'node:fs/promise
|
|
|
10
10
|
};
|
|
11
11
|
} catch {}
|
|
12
12
|
|
|
13
|
-
var
|
|
13
|
+
var eg=Object.create;var Li=Object.defineProperty;var tg=Object.getOwnPropertyDescriptor;var rg=Object.getOwnPropertyNames;var ng=Object.getPrototypeOf,sg=Object.prototype.hasOwnProperty;var w=(e,t)=>()=>(e&&(t=e(e=0)),t);var ot=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),de=(e,t)=>{for(var r in t)Li(e,r,{get:t[r],enumerable:true});},ig=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of rg(t))!sg.call(e,s)&&s!==r&&Li(e,s,{get:()=>t[s],enumerable:!(n=tg(t,s))||n.enumerable});return e};var ee=(e,t,r)=>(r=e!=null?eg(ng(e)):{},ig(Li(r,"default",{value:e,enumerable:true}),e));var ie=ot((_$,Di)=>{var Mn=process||{},nc=Mn.argv||[],Fn=Mn.env||{},og=!(Fn.NO_COLOR||nc.includes("--no-color"))&&(!!Fn.FORCE_COLOR||nc.includes("--color")||Mn.platform==="win32"||(Mn.stdout||{}).isTTY&&Fn.TERM!=="dumb"||!!Fn.CI),ag=(e,t,r=e)=>n=>{let s=""+n,i=s.indexOf(t,e.length);return ~i?e+lg(s,t,r,i)+t:e+s+t},lg=(e,t,r,n)=>{let s="",i=0;do s+=e.substring(i,n)+r,i=n+t.length,n=e.indexOf(t,i);while(~n);return s+e.substring(i)},sc=(e=og)=>{let t=e?ag:()=>String;return {isColorSupported:e,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};Di.exports=sc();Di.exports.createColors=sc;});function ug(e){let t=typeof process<"u"&&process.env||void 0;return t?t.NODE_ENV==="test"?true:t[cg[e]]==="1":false}function ac(e){return oc[e]}function ji(){return ic.filter(e=>oc[e])}function Un(){let e=ji();if(e.length===0)return null;let t=e.includes("storage")?" Cloud sync (lite cloud deploy) is disabled.":"";return `EXPERIMENTAL FEATURES ENABLED: ${e.join(", ")} - not supported, do not use in production.${t}`}var cg,ic,oc,zt=w(()=>{cg={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},ic=["storage","cloud"],oc=Object.fromEntries(ic.map(e=>[e,ug(e)]));});function ke(e,t){Bn.existsSync(e)||(Bn.mkdirSync(e,{recursive:true}),t?.());}function Et(e,t,r){Bn.existsSync(e)||(Bn.writeFileSync(e,t),r?.());}var xt=w(()=>{});function fg(e,t){let r=e.slice(0,t).split(/\r\n|\n|\r/g);return [r.length,r.pop().length+1]}function mg(e,t,r){let n=e.split(/\r\n|\n|\r/g),s="",i=(Math.log10(t+1)|0)+1;for(let o=t-1;o<=t+1;o++){let a=n[o-1];a&&(s+=o.toString().padEnd(i," "),s+=": ",s+=a,s+=`
|
|
14
14
|
`,o===t&&(s+=" ".repeat(i+r+2),s+=`^
|
|
15
|
-
`));}return s}var H,
|
|
15
|
+
`));}return s}var H,_t=w(()=>{H=class extends Error{line;column;codeblock;constructor(t,r){let[n,s]=fg(r.toml,r.ptr),i=mg(r.toml,n,s);super(`Invalid TOML document: ${t}
|
|
16
16
|
|
|
17
|
-
${i}`,r),this.line=n,this.column=s,this.codeblock=i;}};});function
|
|
18
|
-
`,t);return e[n-1]==="\r"&&n--,n<=r?n:-1}function
|
|
17
|
+
${i}`,r),this.line=n,this.column=s,this.codeblock=i;}};});function dg(e,t){let r=0;for(;e[t-++r]==="\\";);return --r&&r%2}function qn(e,t=0,r=e.length){let n=e.indexOf(`
|
|
18
|
+
`,t);return e[n-1]==="\r"&&n--,n<=r?n:-1}function Vt(e,t){for(let r=t;r<e.length;r++){let n=e[r];if(n===`
|
|
19
19
|
`)return r;if(n==="\r"&&e[r+1]===`
|
|
20
20
|
`)return r+1;if(n<" "&&n!==" "||n==="\x7F")throw new H("control characters are not allowed in comments",{toml:e,ptr:t})}return e.length}function Pe(e,t,r,n){let s;for(;(s=e[t])===" "||s===" "||!r&&(s===`
|
|
21
21
|
`||s==="\r"&&e[t+1]===`
|
|
22
|
-
`);)t++;return n||s!=="#"?t:Pe(e,
|
|
22
|
+
`);)t++;return n||s!=="#"?t:Pe(e,Vt(e,t),r)}function cc(e,t,r,n,s=false){if(!n)return t=qn(e,t),t<0?e.length:t;for(let i=t;i<e.length;i++){let o=e[i];if(o==="#")i=qn(e,i);else {if(o===r)return i+1;if(o===n||s&&(o===`
|
|
23
23
|
`||o==="\r"&&e[i+1]===`
|
|
24
|
-
`))return i}}throw new H("cannot find end of structure",{toml:e,ptr:t})}function
|
|
24
|
+
`))return i}}throw new H("cannot find end of structure",{toml:e,ptr:t})}function Hn(e,t){let r=e[t],n=r===e[t+1]&&e[t+1]===e[t+2]?e.slice(t,t+3):r;t+=n.length-1;do t=e.indexOf(n,++t);while(t>-1&&r!=="'"&&dg(e,t));return t>-1&&(t+=n.length,n.length>1&&(e[t]===r&&t++,e[t]===r&&t++)),t}var xr=w(()=>{_t();});var hg,_r,Fi=w(()=>{hg=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,_r=class e extends Date{#e=false;#t=false;#r=null;constructor(t){let r=true,n=true,s="Z";if(typeof t=="string"){let i=t.match(hg);i?(i[1]||(r=false,t=`0000-01-01T${t}`),n=!!i[2],n&&t[10]===" "&&(t=t.replace(" ","T")),i[2]&&+i[2]>23?t="":(s=i[3]||null,t=t.toUpperCase(),!s&&n&&(t+="Z"))):t="";}super(t),isNaN(this.getTime())||(this.#e=r,this.#t=n,this.#r=s);}isDateTime(){return this.#e&&this.#t}isLocal(){return !this.#e||!this.#t||!this.#r}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let t=super.toISOString();if(this.isDate())return t.slice(0,10);if(this.isTime())return t.slice(11,23);if(this.#r===null)return t.slice(0,-1);if(this.#r==="Z")return t;let r=+this.#r.slice(1,3)*60+ +this.#r.slice(4,6);return r=this.#r[0]==="-"?r:-r,new Date(this.getTime()-r*6e4).toISOString().slice(0,-1)+this.#r}static wrapAsOffsetDateTime(t,r="Z"){let n=new e(t);return n.#r=r,n}static wrapAsLocalDateTime(t){let r=new e(t);return r.#r=null,r}static wrapAsLocalDate(t){let r=new e(t);return r.#t=false,r.#r=null,r}static wrapAsLocalTime(t){let r=new e(t);return r.#e=false,r.#r=null,r}};});function Wn(e,t=0,r=e.length){let n=e[t]==="'",s=e[t++]===e[t]&&e[t]===e[t+1];s&&(r-=2,e[t+=2]==="\r"&&t++,e[t]===`
|
|
25
25
|
`&&t++);let i=0,o,a="",l=t;for(;t<r-1;){let c=e[t++];if(c===`
|
|
26
26
|
`||c==="\r"&&e[t]===`
|
|
27
|
-
`){if(!s)throw new H("newlines are not allowed in strings",{toml:e,ptr:t-1})}else if(c<" "&&c!==" "||c==="\x7F")throw new H("control characters are not allowed in strings",{toml:e,ptr:t-1});if(o){if(o=false,c==="x"||c==="u"||c==="U"){let u=e.slice(t,t+=c==="x"?2:c==="u"?4:8);if(!
|
|
27
|
+
`){if(!s)throw new H("newlines are not allowed in strings",{toml:e,ptr:t-1})}else if(c<" "&&c!==" "||c==="\x7F")throw new H("control characters are not allowed in strings",{toml:e,ptr:t-1});if(o){if(o=false,c==="x"||c==="u"||c==="U"){let u=e.slice(t,t+=c==="x"?2:c==="u"?4:8);if(!bg.test(u))throw new H("invalid unicode escape",{toml:e,ptr:i});try{a+=String.fromCodePoint(parseInt(u,16));}catch{throw new H("invalid unicode escape",{toml:e,ptr:i})}}else if(s&&(c===`
|
|
28
28
|
`||c===" "||c===" "||c==="\r")){if(t=Pe(e,t-1,true),e[t]!==`
|
|
29
|
-
`&&e[t]!=="\r")throw new H("invalid escape: only line-ending whitespace may be escaped",{toml:e,ptr:i});t=Pe(e,t);}else if(c in
|
|
30
|
-
`,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};});function
|
|
31
|
-
`&&e[o]!=="\r")throw new H("unexpected character encountered",{toml:e,ptr:o});o+=+(e[o]===",");}return [l,o]}o=
|
|
32
|
-
`&&o!=="\r"){let a,l=s,c=false,[u,p]=
|
|
33
|
-
`&&i!=="\r"){let o
|
|
34
|
-
`&&e[a]!=="\r")throw new H("each key-value declaration must be followed by an end-of-line",{toml:e,ptr:a});a=Pe(e,a);}return n}var
|
|
29
|
+
`&&e[t]!=="\r")throw new H("invalid escape: only line-ending whitespace may be escaped",{toml:e,ptr:i});t=Pe(e,t);}else if(c in uc)a+=uc[c];else throw new H("unrecognized escape sequence",{toml:e,ptr:i});l=t;}else !n&&c==="\\"&&(i=t-1,o=true,a+=e.slice(l,i));}return a+e.slice(l,r-1)}function pc(e,t,r,n){if(e==="true")return true;if(e==="false")return false;if(e==="-inf")return -1/0;if(e==="inf"||e==="+inf")return 1/0;if(e==="nan"||e==="+nan"||e==="-nan")return NaN;if(e==="-0")return n?0n:0;let s=gg.test(e);if(s||yg.test(e)){if(wg.test(e))throw new H("leading zeroes are not allowed",{toml:t,ptr:r});e=e.replace(/_/g,"");let o=+e;if(isNaN(o))throw new H("invalid number",{toml:t,ptr:r});if(s){if((s=!Number.isSafeInteger(o))&&!n)throw new H("integer value cannot be represented losslessly",{toml:t,ptr:r});(s||n===true)&&(o=BigInt(e));}return o}let i=new _r(e);if(!i.isValid())throw new H("invalid value",{toml:t,ptr:r});return i}var gg,yg,wg,bg,uc,Mi=w(()=>{xr();Fi();_t();gg=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,yg=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,wg=/^[+-]?0[0-9_]/,bg=/^[0-9a-f]{2,8}$/i,uc={b:"\b",t:" ",n:`
|
|
30
|
+
`,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};});function Sg(e,t,r){let n=e.slice(t,r),s=n.indexOf("#");return s>-1&&(Vt(e,s),n=n.slice(0,s)),[n.trimEnd(),s]}function $r(e,t,r,n,s){if(n===0)throw new H("document contains excessively nested structures. aborting.",{toml:e,ptr:t});let i=e[t];if(i==="["||i==="{"){let[l,c]=i==="["?mc(e,t,n,s):fc(e,t,n,s);if(r){if(c=Pe(e,c),e[c]===",")c++;else if(e[c]!==r)throw new H("expected comma or end of structure",{toml:e,ptr:c})}return [l,c]}let o;if(i==='"'||i==="'"){o=Hn(e,t);let l=Wn(e,t,o);if(r){if(o=Pe(e,o),e[o]&&e[o]!==","&&e[o]!==r&&e[o]!==`
|
|
31
|
+
`&&e[o]!=="\r")throw new H("unexpected character encountered",{toml:e,ptr:o});o+=+(e[o]===",");}return [l,o]}o=cc(e,t,",",r);let a=Sg(e,t,o-+(e[o-1]===","));if(!a[0])throw new H("incomplete key-value declaration: no value specified",{toml:e,ptr:t});return r&&a[1]>-1&&(o=Pe(e,t+a[1]),o+=+(e[o]===",")),[pc(a[0],e,t,s),o]}var Ui=w(()=>{Mi();Bi();xr();_t();});function Gn(e,t,r="="){let n=t-1,s=[],i=e.indexOf(r,t);if(i<0)throw new H("incomplete key-value: cannot find end of key",{toml:e,ptr:t});do{let o=e[t=++n];if(o!==" "&&o!==" ")if(o==='"'||o==="'"){if(o===e[t+1]&&o===e[t+2])throw new H("multiline strings are not allowed in keys",{toml:e,ptr:t});let a=Hn(e,t);if(a<0)throw new H("unfinished string encountered",{toml:e,ptr:t});n=e.indexOf(".",a);let l=e.slice(a,n<0||n>i?i:n),c=qn(l);if(c>-1)throw new H("newlines are not allowed in keys",{toml:e,ptr:t+n+c});if(l.trimStart())throw new H("found extra tokens after the string part",{toml:e,ptr:a});if(i<a&&(i=e.indexOf(r,a),i<0))throw new H("incomplete key-value: cannot find end of key",{toml:e,ptr:t});s.push(Wn(e,t,a));}else {n=e.indexOf(".",t);let a=e.slice(t,n<0||n>i?i:n);if(!Eg.test(a))throw new H("only letter, numbers, dashes and underscores are allowed in keys",{toml:e,ptr:t});s.push(a.trimEnd());}}while(n+1&&n<i);return [s,Pe(e,i+1,true,true)]}function fc(e,t,r,n){let s={},i=new Set,o;for(t++;(o=e[t++])!=="}"&&o;){if(o===",")throw new H("expected value, found comma",{toml:e,ptr:t-1});if(o==="#")t=Vt(e,t);else if(o!==" "&&o!==" "&&o!==`
|
|
32
|
+
`&&o!=="\r"){let a,l=s,c=false,[u,p]=Gn(e,t-1);for(let d=0;d<u.length;d++){if(d&&(l=c?l[a]:l[a]={}),a=u[d],(c=Object.hasOwn(l,a))&&(typeof l[a]!="object"||i.has(l[a])))throw new H("trying to redefine an already defined value",{toml:e,ptr:t});!c&&a==="__proto__"&&Object.defineProperty(l,a,{enumerable:true,configurable:true,writable:true});}if(c)throw new H("trying to redefine an already defined value",{toml:e,ptr:t});let[f,g]=$r(e,p,"}",r-1,n);i.add(f),l[a]=f,t=g;}}if(!o)throw new H("unfinished table encountered",{toml:e,ptr:t});return [s,t]}function mc(e,t,r,n){let s=[],i;for(t++;(i=e[t++])!=="]"&&i;){if(i===",")throw new H("expected value, found comma",{toml:e,ptr:t-1});if(i==="#")t=Vt(e,t);else if(i!==" "&&i!==" "&&i!==`
|
|
33
|
+
`&&i!=="\r"){let o=$r(e,t-1,"]",r-1,n);s.push(o[0]),t=o[1];}}if(!i)throw new H("unfinished array encountered",{toml:e,ptr:t});return [s,t]}var Eg,Bi=w(()=>{Mi();Ui();xr();_t();Eg=/^[a-zA-Z0-9-_]+[ \t]*$/;});function dc(e,t,r,n){let s=t,i=r,o,a=false,l;for(let c=0;c<e.length;c++){if(c){if(s=a?s[o]:s[o]={},i=(l=i[o]).c,n===0&&(l.t===1||l.t===2))return null;if(l.t===2){let u=s.length-1;s=s[u],i=i[u].c;}}if(o=e[c],(a=Object.hasOwn(s,o))&&i[o]?.t===0&&i[o]?.d)return null;a||(o==="__proto__"&&(Object.defineProperty(s,o,{enumerable:true,configurable:true,writable:true}),Object.defineProperty(i,o,{enumerable:true,configurable:true,writable:true})),i[o]={t:c<e.length-1&&n===2?3:n,d:false,i:0,c:{}});}if(l=i[o],l.t!==n&&!(n===1&&l.t===3)||(n===2&&(l.d||(l.d=true,s[o]=[]),s[o].push(s={}),l.c[l.i++]=l={t:1,d:false,i:0,c:{}}),l.d))return null;if(l.d=true,n===1)s=a?s[o]:s[o]={};else if(n===0&&a)return null;return [o,s,l.c]}function $t(e,{maxDepth:t=1e3,integersAsBigInt:r}={}){let n={},s={},i=n,o=s;for(let a=Pe(e,0);a<e.length;){if(e[a]==="["){let l=e[++a]==="[",c=Gn(e,a+=+l,"]");if(l){if(e[c[1]-1]!=="]")throw new H("expected end of table declaration",{toml:e,ptr:c[1]-1});c[1]++;}let u=dc(c[0],n,s,l?2:1);if(!u)throw new H("trying to redefine an already defined table or value",{toml:e,ptr:a});o=u[2],i=u[1],a=c[1];}else {let l=Gn(e,a),c=dc(l[0],i,o,0);if(!c)throw new H("trying to redefine an already defined table or value",{toml:e,ptr:a});let u=$r(e,l[1],void 0,t,r);c[1][c[0]]=u[0],a=u[1];}if(a=Pe(e,a,true),e[a]&&e[a]!==`
|
|
34
|
+
`&&e[a]!=="\r")throw new H("each key-value declaration must be followed by an end-of-line",{toml:e,ptr:a});a=Pe(e,a);}return n}var hc=w(()=>{Bi();Ui();xr();_t();});function vr(e){let t=typeof e;if(t==="object"){if(Array.isArray(e))return "array";if(e instanceof Date)return "date"}return t}function xg(e){for(let t=0;t<e.length;t++)if(vr(e[t])!=="object")return false;return e.length!=0}function qi(e){return JSON.stringify(e).replace(/\x7f/g,"\\u007f")}function Hi(e,t,r,n){if(r===0)throw new Error("Could not stringify the object: maximum object depth exceeded");if(t==="number")return isNaN(e)?"nan":e===1/0?"inf":e===-1/0?"-inf":n&&Number.isInteger(e)?e.toFixed(1):e.toString();if(t==="bigint"||t==="boolean")return e.toString();if(t==="string")return qi(e);if(t==="date"){if(isNaN(e.getTime()))throw new TypeError("cannot serialize invalid date");return e.toISOString()}if(t==="object")return _g(e,r,n);if(t==="array")return $g(e,r,n)}function _g(e,t,r){let n=Object.keys(e);if(n.length===0)return "{}";let s="{ ";for(let i=0;i<n.length;i++){let o=n[i];i&&(s+=", "),s+=gc.test(o)?o:qi(o),s+=" = ",s+=Hi(e[o],vr(e[o]),t-1,r);}return s+" }"}function $g(e,t,r){if(e.length===0)return "[]";let n="[ ";for(let s=0;s<e.length;s++){if(s&&(n+=", "),e[s]===null||e[s]===void 0)throw new TypeError("arrays cannot contain null or undefined values");n+=Hi(e[s],vr(e[s]),t-1,r);}return n+" ]"}function vg(e,t,r,n){if(r===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let s="";for(let i=0;i<e.length;i++)s+=`${s&&`
|
|
35
35
|
`}[[${t}]]
|
|
36
|
-
`,s+=
|
|
37
|
-
`)+
|
|
38
|
-
`)+
|
|
36
|
+
`,s+=Wi(0,e[i],t,r,n);return s}function Wi(e,t,r,n,s){if(n===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let i="",o="",a=Object.keys(t);for(let l=0;l<a.length;l++){let c=a[l];if(t[c]!==null&&t[c]!==void 0){let u=vr(t[c]);if(u==="symbol"||u==="function")throw new TypeError(`cannot serialize values of type '${u}'`);let p=gc.test(c)?c:qi(c);if(u==="array"&&xg(t[c]))o+=(o&&`
|
|
37
|
+
`)+vg(t[c],r?`${r}.${p}`:p,n-1,s);else if(u==="object"){let f=r?`${r}.${p}`:p;o+=(o&&`
|
|
38
|
+
`)+Wi(f,t[c],f,n-1,s);}else i+=p,i+=" = ",i+=Hi(t[c],u,n,s),i+=`
|
|
39
39
|
`;}}return e&&(i||!o)&&(i=i?`[${e}]
|
|
40
40
|
${i}`:`[${e}]`),i&&o?`${i}
|
|
41
|
-
${o}`:i||o}function
|
|
41
|
+
${o}`:i||o}function Gi(e,{maxDepth:t=1e3,numbersAsFloat:r=false}={}){if(vr(e)!=="object")throw new TypeError("stringify can only be called with an object");let n=Wi(0,e,"",t,r);return n[n.length-1]!==`
|
|
42
42
|
`?n+`
|
|
43
|
-
`:n}var
|
|
44
|
-
`);}),
|
|
45
|
-
`);}var
|
|
43
|
+
`:n}var gc,yc=w(()=>{gc=/^[a-z0-9-_]+$/i;});var Tr=w(()=>{hc();yc();Fi();_t();});var ve,Kt=w(()=>{ve={config_dir:"supabase",default_api_port:54321,default_config_format:"toml",default_config_path:"config.toml",default_db_url:"file:supabase/.temp/data.db",default_db_dir:"supabase/.temp/data"};});async function Ag(e=""){try{let t=ze__default.resolve(Xn(),ze__default.join(e,"package.json")),r=await pe__default.readFile(t,"utf-8");if(r)return JSON.parse(r)}catch{}return {}}async function Kn(e=""){let t=await Ag(e);return t?{name:t.name,version:t.version??"unknown"}:{name:"unknown",version:"unknown"}}function Xn(){let e=ze__default.dirname(fileURLToPath(import.meta.url));return ze__default.resolve(e,process.env.LOCAL?"../../../":"../../")}function zi(){return ze__default.resolve(Xn(),"dist")}function Jn(){return ze__default.relative(process.cwd(),zi())}async function Ar(e){let t=ze__default.relative(process.cwd(),ve.config_dir);if(!e)for(let r of Cg){let n=ze__default.join(t,`config.${r}`);if(await pe__default.access(n).then(()=>true).catch(()=>false)){e=n;break}}return e}async function Y(e){await Ar(e)||(console.error(Vn.default.red("No project found. Run `lite init` first.")),process.exit(1));}async function wc(e){let t=await Ar(e);if(!t)return {};switch(console.log(Vn.default.dim(`Using config file: ${Vn.default.cyan(`./${t}`)}`)),t.split(".").pop()){case "toml":return $t(await pe__default.readFile(t,"utf-8"));case "json":return JSON.parse(await pe__default.readFile(t,"utf-8"));case "ts":case "mts":case "js":case "mjs":case "cjs":try{return (await import(ze__default.join(process.cwd(),t))).default}catch(n){throw console.error("Failed to import config file",n),n}default:throw new Error(`Unsupported config file type: ${t}`)}}function bc(e){if(!e||e===":memory:")return;let t=e;if(t.startsWith("file://")?t=t.slice(7):t.startsWith("file:")&&(t=t.slice(5)),!(!t||t===":memory:"))return ze__default.resolve(process.cwd(),t)}var Vn,Cg,xe=w(()=>{Tr();Kt();Vn=ee(ie());Cg=["toml","json","ts","mts","js","mjs","cjs"];});async function Yn(e={}){let t=process.cwd();if(e.recreate){console.log(Ki.default.dim("Recreating database..."));try{let n=await Ar();if(n&&!/\.(ts|mts|js|mjs|cjs)$/.test(n)){let i=(await wc(n))?.db?.url,o=i?bc(i):void 0;o&&Bn.existsSync(o)&&(Bn.rmSync(o,{recursive:!0,force:!0}),console.log(Ki.default.dim(` \u279C removed ${ze__default.relative(t,o)}`)));}}catch{}try{Bn.rmSync(ze__default.join(t,"supabase",".temp"),{recursive:!0,force:!0});}catch{}}if(ke(ze__default.join(t,"supabase")),!await Ar()){let n={api:{port:54321},db:{driver:"sqlite-postgres",url:"file:./supabase/.temp/data.db",migrations:{schema_paths:["./schemas/schema.sql"]},seed:{sql_paths:["./seed.sql"]}},auth:{enabled:true,jwt_secret:"dev-secret-change-me",jwt_expiry:3600,enable_signup:true,email:{enable_confirmations:false}}};e.driver==="pglite"&&(n.db.driver="pglite",n.db.url=ze__default.relative(process.cwd(),ze__default.join(t,"supabase",".temp","data")));let s=e.configFormat??"toml",i=ze__default.join(t,"supabase",`config.${s}`);s==="json"?Et(i,JSON.stringify(n)):Et(i,Gi(n));}ke(ze__default.join(t,"supabase",".temp")),ke(ze__default.join(t,"supabase","schemas"),()=>{Et(ze__default.join(t,"supabase","schemas","schema.sql"),e.template?Rg:`-- This is a schema file for the database
|
|
44
|
+
`);}),Et(ze__default.join(t,"supabase","seed.sql"),e.template?kg:`-- This is a seed file for the database
|
|
45
|
+
`);}var Ki,Rg,kg,Xi=w(()=>{xt();Ki=ee(ie());Tr();xe();Rg=`
|
|
46
46
|
create table todos (
|
|
47
47
|
id serial primary key,
|
|
48
48
|
title text not null,
|
|
@@ -55,14 +55,17 @@ create table todos (
|
|
|
55
55
|
create table test (
|
|
56
56
|
id serial primary key,
|
|
57
57
|
name text not null
|
|
58
|
-
)`,
|
|
58
|
+
)`,kg="insert into todos (`id`, `title`, `description`, `completed`) values (1, 'test', 'test', false);\ninsert into todos (`id`, `title`, `description`, `completed`) values (2, 'test2', 'test2', true);\ninsert into test (`id`, `name`) values (1, 'test');\n";});var Ec={};de(Ec,{init:()=>Pg});var Ji,Pg,xc=w(()=>{Ji=ee(ie());Xi();Pg=e=>{e.command("init").description("Initialize a new project").helpGroup("Local Development:").option("--pglite","Use pglite as database",false).option("--recreate","Recreate everything",false).option("--format","Format to use","toml").action(async t=>{await Yn({configFormat:t.format,recreate:t.recreate,driver:t.pglite?"pglite":void 0}),console.log(),console.log(Ji.default.green(" \u279C"),"Project initialized",Ji.default.cyan("./"+ze__default.relative(process.cwd(),ze__default.join(process.cwd(),"supabase"))));});};});var _c=w(()=>{});var $c=w(()=>{});function Yi(e,t,r=void 0){let n=typeof t=="string"?t.split(/[.[\]"]+/).filter(s=>s):t;if(n.length===0)return e;try{let[s,...i]=n;return !s||!(s in e)?r:Yi(e[s],i,r)}catch{if(typeof r<"u")return r;throw new Error(`Invalid path: ${n.join(".")}`)}}var vc=w(()=>{});var Tc=w(()=>{});function Qn(){try{return !Cr()&&global?.process?.release?.name==="node"}catch{return false}}function Cr(){try{return typeof Bun<"u"}catch{return false}}async function Zn(e,t){let r=performance.now();await e();let n=performance.now();t(n-r);}var Ac=w(()=>{});function Rc(e,t={}){return e.split(`
|
|
59
59
|
`).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>!r.startsWith(t.comments??"--")).join(`
|
|
60
|
-
`)}function
|
|
61
|
-
`;)r+=e[n],n++;continue}if(
|
|
62
|
-
`;)r++;continue}if(s==="/"&&i==="*"){for(r+=2;r<n&&!(e[r]==="*"&&e[r+1]==="/");)r++;r+=2;continue}t+=s,r++;}return t.trim()}function Vi(e){return (e??"").trim().toLowerCase()}function Ki(e){return (e??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase()}function Ji(e){if(e==null)return null;let t=e.trim();for(;t.startsWith("(")&&t.endsWith(")");)t=t.slice(1,-1).trim();return (t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),t}var $r=y(()=>{});function Sg(e,t,r=void 0){let n=typeof t=="string"?Ac(t):Qi(t);return es(e,n,r)}function es(e,t,r=void 0){let n=typeof t=="string"?t.split(/[.\[\]\"]+/).filter(s=>s):t;if(n.length===0)return e;try{let[s,...i]=n;return !s||!(s in e)?r:es(e[s],i,r)}catch{if(typeof r<"u")return r;throw new Error(`Invalid path: ${n.join(".")}`)}}function _g(e){return e===null}function he(e){return !Array.isArray(e)&&typeof e=="object"&&e!==null}function $g(e){return Object.prototype.toString.call(e)==="[object Object]"}function ze(e){return typeof e=="string"}function Ye(e){return typeof e=="number"}function vg(e){return typeof e=="number"&&Number.isInteger(e)}function to(e){return typeof e=="boolean"}function ot(e){return Array.isArray(e)}function Tg(e){return typeof e!="boolean"}function Ag(e){return e!==void 0&&Tg(e)&&"type"in e}function Ae(e){return e!==void 0&&he(e)&&Te in e}function Cg(e){return Ae(e)&&typeof e.toJSON()=="boolean"}function Rg(e,t,r){if(!e)throw new xg(t,r)}function Cc(e){return ze(e)?e.normalize("NFC"):e}function vr(e,t){let r=typeof e;if(r!==typeof t)return false;if(Array.isArray(e)){if(!Array.isArray(t))return false;let n=e.length;if(n!==t.length)return false;for(let s=0;s<n;s++)if(!vr(e[s],t[s]))return false;return true}if(r==="object"){if(!e||!t)return e===t;let n=Object.keys(e),s=Object.keys(t);if(n.length!==s.length)return false;for(let i of n)if(!vr(e[i],t[i]))return false;return true}return e===t}function kg(e,t){return t.reduce((r,n)=>(n in e&&(r[n]=e[n]),r),{})}function Rc(e){try{return structuredClone(e)}catch{return e}}function Pg(e,t,r={}){let n=t;try{n=structuredClone(t);}catch{n=JSON.parse(JSON.stringify(t));}let s={resolver:r.resolver||new ro(e),depth:r.depth||0,dropUnknown:r.dropUnknown??false};return s.resolver.hasRef(e,n)?s.resolver.resolve(e.$ref).coerce(n,{...s,depth:s.depth+1}):n}function ts(e,t,r={}){return e.map(n=>n.validate(t,Zn(r)).valid?n:void 0).filter(Boolean)}function uy(e,t,r={}){let n={keywordPath:r.keywordPath||[],instancePath:r.instancePath||[],coerce:r.coerce||false,errors:r.errors||[],shortCircuit:r.shortCircuit||false,ignoreUnsupported:r.ignoreUnsupported||false,resolver:r.resolver||e.getResolver?.()||new ro(e),depth:r.depth?r.depth+1:0,skipClone:r.skipClone||false},s;if(r?.coerce&&e.coerce){let i=e.coerce(t,{resolver:n.resolver,depth:n.depth});s=n.skipClone?i:structuredClone(i);}else s=n.skipClone?t:structuredClone(t);if(r.ignoreUnsupported!==true){let i=["$defs"];for(let o of i)if(e[o])throw new Error(`${o} not implemented`)}if(n.resolver.hasRef(e,s)){let i=n.resolver.resolve(e.$ref).validate(s,{...n,errors:[]});i.valid||n.errors.push(...i.errors);}else {let i={keywordPath:n.keywordPath,instancePath:n.instancePath,coerce:n.coerce,errors:[],shortCircuit:n.shortCircuit,ignoreUnsupported:n.ignoreUnsupported,resolver:n.resolver,depth:n.depth};for(let o in e)if(o==="type"&&e.type!==void 0){if(s!==void 0){let a=Xi[o];if(a){i.errors=[];let l=a(e,s,i);if(!l.valid){if(r.shortCircuit)return l;n.errors.push(...l.errors);}}}}else if(o in Xi&&e[o]!==void 0){if(s===void 0)continue;let a=Xi[o];if(a){i.errors=[];let l=a(e,s,i);if(!l.valid){if(r.shortCircuit)return l;n.errors.push(...l.errors);}}}}return {valid:n.errors.length===0,errors:n.errors}}function rs(e,t,r){return new class extends Qe{type=e}(t,r)}function Zi(e){return new py(e)}function vc(e,t){return Array.isArray(e)?e.map(t):e!==void 0?[t(e)]:[]}function Tc(e,t,r=n=>n){return Object.fromEntries(Object.entries(e).map(([n,s])=>[n,r(t(s,n),n)]))}function Gt(e){if(to(e))return Zi(e);let t=structuredClone(e);if(!he(t))throw new Eg("non-object schemas cannot be converted to a schema",t);"properties"in t&&t.properties&&(t.properties=Tc(t.properties,(i,o)=>{try{return Gt(i)}catch(a){throw new Error(`Couldn't schemaize property "${o}": ${String(a)}`)}},(i,o)=>"required"in t&&Array.isArray(t.required)&&t.required.includes(o)?i:i.optional()));let r=["patternProperties","dependentSchemas","$defs"];for(let i of r)i in t&&t[i]&&(t[i]=Tc(t[i],Gt));let n=["additionalProperties","items","prefixItems","propertyNames","contains","not","if","then","else"];for(let i of n)i in t&&typeof t[i]<"u"&&(ot(t[i])?t[i]=vc(t[i],Gt):t[i]=Gt(t[i]));let s=["anyOf","oneOf","allOf"];for(let i of s)if(i in t){let{[i]:o}=t;t[i]=vc(o,Gt);}if(Ag(t))switch(t.type){case "string":return Pc(t);case "number":return Oc(t);case "integer":return Ic(t);case "boolean":return Dc(t);case "object":{let{properties:i,...o}=t;return ns(i,o)}case "array":{let{items:i,...o}=t;return Lc(i,o)}}return kc(t)}function $y(){return {type(e){let t=e.map(r=>Array.isArray(r)?new Set(r):new Set([r])).reduce((r,n)=>r?new Set([...r].filter(s=>n.has(s))):new Set(n));if(!t.size)throw new Error('Incompatible "type" in allOf');return t.size===1?[...t][0]:[...t]},enum(e){let t=e.map(r=>new Set(r)).reduce((r,n)=>new Set([...r].filter(s=>n.has(s))));if(!t.size)throw new Error('Incompatible "enum" in allOf');return [...t]},required(e){return [...new Set(e.flat())]},properties(e,t,r){return e.reduce((n,s)=>r(n,s),{})},patternProperties(e,t,r){return e.reduce((n,s)=>r(n,s),{})},$defs(e,t,r){return e.reduce((n,s)=>r(n,s),{})},definitions(e,t,r){return e.reduce((n,s)=>r(n,s),{})},...Object.fromEntries(xy.map(e=>[e,t=>Math.min(...t)])),...Object.fromEntries(_y.map(e=>[e,t=>Math.max(...t)]))}}function vy(e){let t={...$y(),...e.resolvers};function r(n,s){if(Array.isArray(n)&&Array.isArray(s))return [...new Set([...n,...s])];if(eo(n)&&eo(s)){let i={...n};for(let[o,a]of Object.entries(s))if(o in i){let l=t[o];i[o]=l?l([i[o],a],o,r):Yi(a);}else i[o]=Yi(a);return i}return Yi(s)}return r}function Ay(e,t={}){let r=t.deep!==false,n=vy(t);function s(i){if(Array.isArray(i))return i.map(s);if(!eo(i))return i;if(Array.isArray(i.allOf)){let a=i.allOf.map(s);if(a.some(g=>g===false))return false;let l=a.filter(g=>g!==true);if(!l.length)return true;let c=l.reduce((g,d)=>n(g,d),{}),u=Ty(c);if(u!==null)return u;let p={...i};delete p.allOf;let f=n(c,r?s(p):p);return r?s(f):f}let o={};for(let[a,l]of Object.entries(i))o[a]=s(l);return o}return s(e)}var Qi,Ac,Q,L,zt,Zn,xt,Eg,xg,Te,ro,Ng,Og,Ig,Lg,Dg,jg,Fg,Mg,Ug,Bg,qg,Hg,Wg,Gg,zg,Vg,Kg,Jg,Xg,Yg,Qg,Zg,ey,ty,ry,ny,sy,iy,oy,ay,ly,$c,cy,Xi,Qe,Tr,py,kc,fy,my,ns,dy,hy,gy,yy,wy,Pc,Nc,Oc,Ic,by,Lc,Dc,Qn,jc,Sy,Ey,eo,Yi,xy,_y,Ty,Cy,Fc,Ry,ky,Py,Mc,Uc=y(()=>{Qi=(e=[],t="")=>"/"+[t,...e.map(r=>String(r).replace(/\./g,"/"))].filter(Boolean).join("/"),Ac=e=>e.split("/").slice(1);Q=(e={},t,r,n)=>({valid:false,errors:[...e.errors??[],{keywordLocation:Qi([...e.keywordPath??[],t]),instanceLocation:Qi(e.instancePath),error:typeof r=="string"?r:`Invalid value for ${t}`,data:n}]}),L=()=>({valid:true,errors:[]}),zt=(e,t,r)=>{let n=Array.isArray(t)?t:[t],s=r?Array.isArray(r)?r:[r]:[];return {...e,keywordPath:[...e.keywordPath??[],...n],instancePath:s?[...e.instancePath??[],...s]:e.instancePath}},Zn=(e={})=>({...e,errors:[]}),xt=class extends Error{constructor(e){super(`Expected ${e}`);}},Eg=class extends Error{constructor(e,t){super(`${e??"Invalid raw schema"}: ${JSON.stringify(t)}`),this.schema=t;}},xg=class extends Error{constructor(e,t){super(`${e}, got: 'type "${typeof t}": ${JSON.stringify(t)}'`),this.value=t;}},Te=Symbol.for("jsonv-ts:schema");ro=class{constructor(e){this.root=e,this.cache=new Map;}cache;hasRef(e,t){return t!==void 0&&"$ref"in e&&ze(e.$ref)}resolve(e){let t=this.cache.get(e);if(!t){if(t=Sg(this.root,e),!Ae(t))throw new Error(`ref not found: ${e}`);if("$ref"in t&&t.$ref===e)throw new Error(`ref loop: ${e}`);this.cache.set(e,t);}return t}};Ng=({type:e},t,r={})=>{if(e===void 0||t===void 0)return L();let n,s={string:ze,number:Ye,integer:vg,object:he,array:ot,boolean:to,null:_g};if(Array.isArray(e)){for(let i of e){if(!(i in s))throw new xt(`Unknown type: ${i}`);if(s[i](t))return L()}n=`Expected one of: ${e.join(", ")}`;}else {if(!(e in s))throw new xt(`Unknown type: ${e}`);s[e](t)||(n=`Expected ${e}`);}return n?Q(r,"type",n,t):L()},Og=({const:e},t,r={})=>vr(e,t)?L():Q(r,"const",`Expected const: ${e}`,t),Ig=({enum:e=[]},t,r={})=>e.some(n=>vr(n,t))?L():Q(r,"enum",`Expected enum: ${JSON.stringify(e)}`,t);Lg=({anyOf:e=[]},t,r={})=>ts(e,t,r).length>0?L():Q(r,"anyOf","Expected at least one to match",t),Dg=({oneOf:e=[]},t,r={})=>ts(e,t).length===1?L():Q(r,"oneOf","Expected exactly one to match",t),jg=({allOf:e=[]},t,r={})=>ts(e,t,r).length===e.length?L():Q(r,"allOf","Expected all to match",t),Fg=({not:e},t,r={})=>t===void 0?L():Ae(e)&&e.validate(t,r).valid?Q(r,"not","Expected not to match",t):L(),Mg=({if:e,then:t,else:r},n,s={})=>{if(e&&(t||r)){if(e.validate(n,Zn(s)).valid)return t?t.validate(n,Zn(s)):L();if(r)return r.validate(n,Zn(s))}return L()},Ug=({pattern:e=""},t,r={})=>{if(!ze(t))return L();if(e instanceof RegExp){if(e.test(t))return L()}else if(new RegExp(e,"u").test(t))return L();return Q(r,"pattern",`Expected string matching pattern ${e}`,t)},Bg=({minLength:e=0},t,r={})=>ze(t)?[...Cc(t)].length>=e?L():Q(r,"minLength",`Expected string with minimum length of ${e}`,t):L(),qg=({maxLength:e=0},t,r={})=>ze(t)?[...Cc(t)].length<=e?L():Q(r,"maxLength",`Expected string with maximum length of ${e}`,t):L(),Hg=({multipleOf:e=0},t,r={})=>{if(!Ye(t))return L();if(!(Number.isFinite(t)&&Number.isFinite(e))||e<=0)throw new xt("number");let n=t/e,s=Number.EPSILON*Math.max(1,Math.abs(n));return Math.abs(n-Math.round(n))<=s?L():Q(r,"multipleOf",`Expected number being a multiple of ${e}`,t)},Wg=({maximum:e=0},t,r={})=>!Ye(t)||t<=e?L():Q(r,"maximum",`Expected number less than or equal to ${e}`,t),Gg=({exclusiveMaximum:e=0},t,r={})=>!Ye(t)||t<e?L():Q(r,"exclusiveMaximum",`Expected number less than ${e}`,t),zg=({minimum:e=0},t,r={})=>!Ye(t)||t>=e?L():Q(r,"minimum",`Expected number greater than or equal to ${e}`,t),Vg=({exclusiveMinimum:e=0},t,r={})=>!Ye(t)||t>e?L():Q(r,"exclusiveMinimum",`Expected number greater than ${e}`,t),Kg=({properties:e={}},t,r={})=>{if(!he(t))return L();for(let[n,s]of Object.entries(t)){let i=e[n];if(!Ae(i))continue;let o=i.validate(s,zt(r,["properties",n],n));if(!o.valid)return o}return L()},Jg=({properties:e={},additionalProperties:t,patternProperties:r},n,s={})=>{if(!he(n))return L();if(!Ae(t))throw new xt("additionalProperties must be a boolean or a managed schema");let i=Object.keys(e),o=he(r)?Object.keys(n).filter(l=>Object.keys(r).some(c=>new RegExp(c).test(l))):[],a=Object.keys(n).filter(l=>!i.includes(l)&&!o.includes(l));if(a.length>0){if(Cg(t)){if(t.toJSON()===true)return L();let l=a.reduce((c,u)=>(c[u]=n[u],c),{});return Q(s,"additionalProperties","Additional properties are not allowed",l)}else if(Ae(t))for(let l of a){let c=t.validate(n[l],zt(s,["additionalProperties"],l));if(!c.valid)return c}}return L()},Xg=({dependentRequired:e},t,r={})=>{if(!he(t))return L();let n=Object.keys(t).filter(s=>typeof t[s]!="function");if(he(e)){for(let[s,i]of Object.entries(e))if(n.includes(s)){for(let o of i)if(!n.includes(o))return Q(r,"dependentRequired",`Expected dependent required property ${o}`,t)}}return L()},Yg=({required:e=[]},t,r={})=>{if(!he(t))return L();let n=Object.keys(t).filter(s=>typeof t[s]!="function");return e.every(s=>n.includes(s))?L():Q(r,"required",`Expected object with required properties ${e.join(", ")}`,t)},Qg=({dependentSchemas:e},t,r={})=>{if(!he(t))return L();let n=Object.keys(t).filter(s=>typeof t[s]!="function");if(he(e)){for(let[s,i]of Object.entries(e))if(n.includes(s)){let o=i.validate(t,r);if(!o.valid)return o}}return L()},Zg=({minProperties:e=0},t,r={})=>he(t)?Object.keys(t).length>=e?L():Q(r,"minProperties",`Expected object with at least ${e} properties`,t):L(),ey=({maxProperties:e=0},t,r={})=>!he(t)||Object.keys(t).length<=e?L():Q(r,"maxProperties",`Expected object with at most ${e} properties`,t),ty=({patternProperties:e={}},t,r={})=>{if(!he(t))return L();if(!he(e))throw new xt("patternProperties must be an object");for(let[n,s]of Object.entries(t))for(let[i,o]of Object.entries(e))if(new RegExp(i,"u").test(n)){let a=o.validate(s,zt(r,["patternProperties"],n));if(!a.valid)return a}return L()},ry=({propertyNames:e},t,r={})=>{if(!he(t)||e===void 0)return L();if(!Ae(e))throw new xt("propertyNames must be a managed schema");for(let n of Object.keys(t)){let s=e.validate(n,zt(r,["propertyNames"],n));if(!s.valid)return s}return L()},ny=({items:e,prefixItems:t=[]},r,n={})=>{if(!ot(r)||e===void 0)return L();if(!Ae(e))throw new xt("items must be a managed schema");for(let[s,i]of r.slice(t.length).entries()){let o=e.validate(i,zt(n,["items"],String(s)));if(!o.valid)return o}return L()},sy=({minItems:e=0},t,r={})=>!ot(t)||t.length>=e?L():Q(r,"minItems",`Expected array with at least ${e} items`,t),iy=({maxItems:e=0},t,r={})=>!ot(t)||t.length<=e?L():Q(r,"maxItems",`Expected array with at most ${e} items`,t),oy=({uniqueItems:e=false},t,r={})=>{if(!ot(t)||!e)return L();for(let n=0;n<t.length;n++){let s=t[n];for(let i=0;i<t.length;i++){if(n===i)continue;let o=t[i];if(vr(s,o))return Q(r,"uniqueItems",`Duplicated items at index ${n} and ${i}`,t)}}return L()},ay=({contains:e,minContains:t,maxContains:r},n,s={})=>{if(!Ae(e))throw new Error("contains must be a managed schema");if(!ot(n))return L();let i=n.filter(o=>e.validate(o).valid).length;return i<(t??1)?Q(s,t?"minContains":"contains",`Expected array to contain at least ${t??1}, but found ${i}`,n):r!==void 0&&i>r?Q(s,"maxContains",`Expected array to contain at most ${r}, but found ${i}`,n):L()},ly=({prefixItems:e=[]},t,r={})=>{if(!ot(t))return L();for(let n=0;n<t.length;n++){let s=e[n]?.validate(t[n],zt(r,String(n),String(n)));if(s&&s?.valid!==true)return s}return L()},$c={email:e=>{if(e.length>318)return false;if(/^[a-z0-9!#$%&'*+/=?^_`{|}~-]{1,20}(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]{1,21}){0,2}@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,60}[a-z0-9])?){0,3}$/i.test(e))return true;if(!e.includes("@")||/(^\.|^"|\.@|\.\.)/.test(e))return false;let[t,r,...n]=e.split("@");return !t||!r||n.length!==0||t.length>64||r.length>253||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?false:r.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},hostname:e=>e.length>(e.endsWith(".")?254:253)?false:/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.?$/i.test(e),date:e=>{if(e.length!==10)return false;if(e[5]==="0"&&e[6]==="2"){if(/^\d\d\d\d-02-(?:[012][1-8]|[12]0|[01]9)$/.test(e))return true;let t=e.match(/^(\d\d\d\d)-02-29$/);if(!t)return false;let r=Number(t[1]);return r%16===0||r%4===0&&r%25!==0}return e.endsWith("31")?/^\d\d\d\d-(?:0[13578]|1[02])-31$/.test(e):/^\d\d\d\d-(?:0[13-9]|1[012])-(?:[012][1-9]|[123]0)$/.test(e)},time:e=>{if(e.length>27||!/^(?:2[0-3]|[0-1]\d):[0-5]\d:(?:[0-5]\d|60)(?:\.\d+)?(?:z|[+-](?:2[0-3]|[0-1]\d)(?::?[0-5]\d)?)?$/i.test(e))return false;if(!/:60/.test(e))return true;let t=e.match(/([0-9.]+|[^0-9.])/g);if(!t)return false;let r=Number(t[0])*60+Number(t[2]);return t[5]==="+"?r+=1440-Number(t[6]||0)*60-Number(t[8]||0):t[5]==="-"&&(r+=Number(t[6]||0)*60+Number(t[8]||0)),r%1440===1439},"date-time":e=>{if(e.length>38)return false;let t=/^\d\d\d\d-(?:0[1-9]|1[0-2])-(?:[0-2]\d|3[01])[t\s](?:2[0-3]|[0-1]\d):[0-5]\d:(?:[0-5]\d|60)(?:\.\d+)?(?:z|[+-](?:2[0-3]|[0-1]\d)(?::?[0-5]\d)?)$/i,r=e[5]==="0"&&e[6]==="2";if(r&&e[8]==="3"||!t.test(e))return false;if(e[17]==="6"){let n=e.slice(11).match(/([0-9.]+|[^0-9.])/g);if(!n)return false;let s=Number(n[0])*60+Number(n[2]);if(n[5]==="+"?s+=1440-Number(n[6]||0)*60-Number(n[8]||0):n[5]==="-"&&(s+=Number(n[6]||0)*60+Number(n[8]||0)),s%1440!==1439)return false}if(r){if(/^\d\d\d\d-02-(?:[012][1-8]|[12]0|[01]9)/.test(e))return true;let n=e.match(/^(\d\d\d\d)-02-29/);if(!n)return false;let s=Number(n[1]??0);return s%16===0||s%4===0&&s%25!==0}return e[8]==="3"&&e[9]==="1"?/^\d\d\d\d-(?:0[13578]|1[02])-31/.test(e):/^\d\d\d\d-(?:0[13-9]|1[012])-(?:[012][1-9]|[123]0)/.test(e)},ipv4:e=>e.length<=15&&/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)$/.test(e),ipv6:e=>{if(e.length>45||e.length<2)return false;let t=0,r=0,n=0,s=false,i=false,o=0,a=true;for(let c=0;c<e.length;c++){let u=e.charCodeAt(c);if(c===1&&o===58&&u!==58)return false;if(u>=48&&u<=57){if(++n>4)return false}else if(u===46){if(t>6||r>=3||n===0||i)return false;r++,n=0;}else if(u===58){if(r>0||t>=7)return false;if(o===58){if(s)return false;s=true;}else c===0&&(a=false);t++,n=0,i=false;}else if(u>=97&&u<=102||u>=65&&u<=70){if(r>0||++n>4)return false;i=true;}else return false;o=u;}if(t<2||r>0&&(r!==3||n===0))return false;if(s&&e.length===2)return true;if(r>0&&!/(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/.test(e))return false;let l=r>0?6:7;return s?(a||n>0)&&t<l:t===l&&a&&n>0},uri:e=>/^[a-z][a-z0-9+\-.]*:(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/?(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i.test(e),"uri-reference":e=>/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/?(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)?(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i.test(e),"uri-template":e=>/^(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2}|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i.test(e),"json-pointer":e=>/^(?:|\/(?:[^~]|~0|~1)*)$/.test(e),"relative-json-pointer":e=>/^(?:0|[1-9][0-9]*)(?:|#|\/(?:[^~]|~0|~1)*)$/.test(e),uuid:e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),duration:e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),regex:e=>{if(/[^\\]\\Z/.test(e))return false;try{return new RegExp(e,"u"),!0}catch{return false}},binary:()=>true,password:()=>true},cy=({format:e},t,r={})=>!ze(t)||!e?L():$c[e]?$c[e](t)?L():Q(r,"format",`Expected format: ${e}`,t):L(),Xi={type:Ng,const:Og,enum:Ig,allOf:jg,anyOf:Lg,oneOf:Dg,not:Fg,minLength:Bg,maxLength:qg,pattern:Ug,format:cy,minimum:zg,exclusiveMinimum:Vg,maximum:Wg,exclusiveMaximum:Gg,multipleOf:Hg,required:Yg,dependentRequired:Xg,dependentSchemas:Qg,minProperties:Zg,maxProperties:ey,propertyNames:ry,properties:Kg,patternProperties:ty,additionalProperties:Jg,minItems:sy,maxItems:iy,uniqueItems:oy,contains:ay,prefixItems:ly,items:ny,if:Mg};Qe=class{"~standard";[Te];_resolver;type;$id;$ref;$schema;title;description;readOnly;writeOnly;$comment;examples;constructor(e,t){let{type:r,validate:n,coerce:s,template:i,...o}=e||{};Object.assign(this,{type:r},o),this[Te]={raw:e,optional:false,overrides:t},this["~standard"]={version:1,vendor:"jsonv-ts",validate:a=>{let l=this.validate(a);return l.valid?{value:a}:{issues:l.errors.map(c=>({message:c.error,path:Ac(c.instanceLocation)}))}}};}template(e,t){let r=this,n=e;if(r.const!==void 0?n=r.const:n===void 0&&(r.default!==void 0&&(n=r.default),t?.withExtendedOptional&&r.enum!==void 0&&(n=r.enum[0])),t?.withOptional!==true&&n===void 0&&this.isOptional())return n;if(this[Te].raw?.template){let i=this[Te].raw.template(n,t);i!==void 0&&(n=i);}let s=this[Te].overrides?.template?.(n,t);return s!==void 0&&(n=s),n}validate(e,t){let r={keywordPath:t?.keywordPath||[],instancePath:t?.instancePath||[],coerce:t?.coerce||false,errors:t?.errors||[],shortCircuit:t?.shortCircuit||false,ignoreUnsupported:t?.ignoreUnsupported||false,resolver:t?.resolver||this.getResolver(),depth:t?.depth?t.depth+1:0,skipClone:t?.skipClone??true},n=this[Te].raw?.validate;if(n!==void 0){let s=n(e,r);if(!s.valid)return s}return uy(this,e,r)}coerce(e,t){let r={...t,resolver:t?.resolver||this.getResolver(),depth:t?.depth?t.depth+1:0,dropUnknown:t?.dropUnknown??false},n=this[Te].raw?.coerce;if(n!==void 0)return n(e,r);let s=this[Te].overrides?.coerce?.(e,r)??e;return Pg(this,s,r)}optional(){return this[Te].optional=true,this}isOptional(){return this[Te].optional}getResolver(){return this._resolver||(this._resolver=new ro(this)),this._resolver}children(e){return []}*walk({instancePath:e=[],keywordPath:t=[],data:r,maxDepth:n=Number.POSITIVE_INFINITY,...s}={}){let i=e.length===0&&r?Rc(r):r;if(s.includeSelf!==false&&(yield new Tr(this,{instancePath:e,keywordPath:t,data:i,...s})),!(e.length>=n))for(let o of this.children(s)){let a=[...e,...o.instancePath];yield*o.schema.walk({...s,data:i,maxDepth:n,instancePath:a,keywordPath:[...t,...o.keywordPath]});}}*[Symbol.iterator](e){for(let t of this.walk(e))yield t;}toJSON(){let{toJSON:e,"~standard":t,_resolver:r,...n}=this;return JSON.parse(JSON.stringify(n))}},Tr=class{constructor(e,t={}){this.schema=e,this.instancePath=t.instancePath||[],this.keywordPath=t.keywordPath||[],this.depth=this.instancePath.length;try{if(t.data!==void 0){let r=es(t.data,this.instancePath);e.validate(r).valid&&(this.data=r);}}catch{}}instancePath;keywordPath;data;depth;appendInstancePath(e){return this.instancePath=[...this.instancePath,...e],this}appendKeywordPath(e){return this.keywordPath=[...this.keywordPath,...e],this}setData(e){return this.data=e,this}};py=class extends Qe{constructor(e){super(),this.bool=e;}toJSON(){return this.bool}validate(e,t){return this.bool?L():Q(t,"","Always fails",e)}};kc=e=>rs(e?.type,e),fy=(e,t)=>rs(void 0,{...t,const:e}),my=class extends Qe{type="object";properties;required;constructor(e,t){let r=[];for(let[s,i]of Object.entries(e||{}))Rg(Ae(i),"properties must be managed schemas",i),i[Te].optional||r.push(s);let n=t?.additionalProperties===false?Zi(false):t?.additionalProperties;r=r.length>0?r:void 0,super({...t,additionalProperties:n,properties:e,required:r},{template:(s,i)=>{let o=structuredClone(he(s)?s:{}),a={...o};if(this.properties)for(let[l,c]of Object.entries(this.properties)){let u=es(o,l);if(c.isOptional()&&i?.withOptional!==true&&u===void 0&&s===void 0)continue;let p=c.template(u,i);p!==void 0&&(a[l]=p);}if(!(Object.keys(a).length===0&&!i?.withExtendedOptional))return a},coerce:(s,i)=>{let o=Object.keys(this.properties),a=Rc(s),l=o.length>0&&Object.values(this.properties).every(u=>!u[Te].optional);if($g(a)&&(i?.dropUnknown===true||l)&&(a=kg(a,o)),typeof a=="string"&&a.match(/^\{/)&&(a=JSON.parse(a)),typeof a!="object"||a===null)return;if(this.properties)for(let[u,p]of Object.entries(this.properties)){let f=a[u];f!==void 0&&(a[u]=p.coerce(f,i));}let c=this.additionalProperties;if(i?.dropUnknown!==true&&(!c||c.validate(null).valid)){let u=he(s)?s:{},p=Object.keys(u).filter(f=>!o.includes(f));for(let f of p)a[f]=c?c.coerce(u[f],i):u[f];}return a}}),this.properties=e,this.required=r;}strict(){return this.additionalProperties=Zi(false),this[Te].raw.additionalProperties=false,this}partial(){for(let[,e]of Object.entries(this.properties))e[Te].optional=true;return this.required=void 0,this}children(e){let t=[];for(let[r,n]of Object.entries(this.properties)){let s=new Tr(n,e);s.appendInstancePath([r]),s.appendKeywordPath(["properties",r]),t.push(s);}return t}},ns=(e,t)=>new my(e,t),dy=(e,t)=>ns(e,t).strict(),hy=(e,t)=>ns(e,t).partial(),gy=class extends Qe{type="object";additionalProperties;constructor(e,t){super({...t,additionalProperties:e},{template:(r,n)=>n?.withExtendedOptional&&(r===void 0||!he(r))?{}:r}),this.additionalProperties=e;}children(e){let t=[],r=new Tr(this.additionalProperties,e);return r.appendKeywordPath(["additionalProperties"]),t.push(r),t}},yy=(e,t)=>new gy(e,t),wy=class extends Qe{type="string";constructor(e){super(e,{template:(t,r)=>r?.withExtendedOptional&&(t===void 0||!ze(t))?"":t,coerce:t=>Ye(t)?String(t):t});}toJSON(){let{pattern:e,"~standard":t,_resolver:r,...n}=this;return JSON.parse(JSON.stringify({...n,pattern:e instanceof RegExp?e.source:e}))}},Pc=e=>new wy(e),Nc=(e,t,r)=>rs(e,r,{template:(n,s)=>s?.withExtendedOptional&&(n===void 0||!Ye(n))?r?.minimum??0:n,coerce:n=>{if(ze(n)){let s=t.parseFn(n);if(!Number.isNaN(s))return s}return n}}),Oc=e=>Nc("number",{parseFn:Number},e),Ic=e=>Nc("integer",{parseFn:Number.parseInt},e),by=class extends Qe{constructor(e,t={}){super({...t,items:e},{template:r=>r===void 0||!Array.isArray(r)?[]:r,coerce:(r,n)=>{try{let s=typeof r=="string"?JSON.parse(r):r;if(!Array.isArray(s))return;if(Ae(this.items))for(let[i,o]of s.entries())s[i]=this.items.coerce(o,n);return s}catch{}return r}}),this.items=e,this.items=e;}type="array";children(e){let t=[];if(this.items){let r=new Tr(this.items,e);r.appendKeywordPath(["items"]),t.push(r);}return t}},Lc=(e,t)=>new by(e,t),Dc=e=>rs("boolean",e,{template:(t,r)=>r?.withExtendedOptional&&(t===void 0||!to(t))?false:t,coerce:t=>{if(ze(t)&&["true","false","1","0"].includes(t))return t==="true"||t==="1";if(Ye(t)){if(t===1)return true;if(t===0)return false}return t}}),Qn=Symbol.for("unionType"),jc=class extends Qe{[Qn];constructor(e,t,r){super({...r,[t]:e},{coerce:(n,s)=>{let i=r?.coerce;if(i!==void 0)return i.bind(this)(n,s);let o=ts(e,n,{ignoreUnsupported:true,resolver:s?.resolver,coerce:true});return o.length>0?o[0].coerce(n,s):n}}),this[Qn]=t;}get schemas(){return this[this[Qn]]}children(e){let t=[];for(let[r,n]of this.schemas.entries()){let s=new Tr(n,e);s.appendKeywordPath([this[Qn],r]),t.push(s);}return t}},Sy=(e,t)=>new jc(e,"anyOf",t),Ey=(e,t)=>new jc(e,"oneOf",t);eo=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Yi=e=>typeof globalThis.structuredClone=="function"?globalThis.structuredClone(e):JSON.parse(JSON.stringify(e)),xy=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],_y=["minimum","exclusiveMinimum","minLength","minItems","minProperties"];Ty=e=>e===true||e===false?e:null;Cy=(e,t)=>{let r=JSON.parse(JSON.stringify({...t,allOf:e}));return Gt(Ay(r))},Fc=class extends Qe{$ref;constructor(e,t){if(!t&&!Ae(e))throw new Error("Ref not set");if(Ae(e)&&!e.$id)throw new Error("Ref must have an $id");let r=t??e?.$id;super({$ref:r},{coerce:(n,s)=>{let i=s?.resolver?.resolve(this.$ref);if(!Ae(i))throw new Error(`Ref not found: ${this.$ref}`);return i.coerce(n,s)}}),this.$ref=r;}},Ry=(e,t)=>new Fc(e,t),ky=e=>new Fc(void 0,e),Py=e=>e(new Qe({$ref:"#",coerce:(t,r)=>{let n=r?.resolver?.resolve("#");if(!Ae(n))throw new Error("Ref not found: #");return n.coerce(t,r)}})),Mc={boolean:Dc,any:kc,literal:fy,object:ns,strictObject:dy,partialObject:hy,record:yy,string:Pc,number:Oc,integer:Ic,array:Lc,anyOf:Sy,oneOf:Ey,allOf:Cy,ref:Ry,refId:ky,recursive:Py};});function Bc(e,t){if(typeof e!="string"){throw new Error("Email must be a string");}if(!Mc.string({format:"email"}).validate(e).valid){throw new Error("Invalid email");}if(t?.domains?.length&&!t.domains.includes(e.split("@")[1])){throw new Error("Email domain not allowed");}return true}function qc(e,{panic:t=true,length:r=8,numbers:n=0,special:s=0}={}){try{if(typeof e!="string"){if(t)throw new Error("Password must be a string");return !1}if(e.length<r){if(t)throw new Error(`Password must be at least ${r} characters long`);return !1}if((e.match(/[0-9]/g)?.length??0)<n){if(t)throw new Error(`Password must contain at least ${n} numbers`);return !1}if((e.match(/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/g)?.length??0)<s){if(t)throw new Error(`Password must contain at least ${s} special characters`);return !1}return !0}catch(i){if(t)throw i;return false}}function U(e,t='"'){return `${t}${e}${t}`}function Hc(e,t,r){if(t instanceof RegExp)return t.test(e);if(typeof t=="string")switch(!r&&t.startsWith("/")&&(r="regex"),r){case "regex":return new RegExp(t).test(e);case "sql":return new RegExp(t.replace("%",".*").replace("_",".")).test(e);case "wildcard":return new RegExp(t.replace("*",".*")).test(e);default:return e.includes(t)}return false}var Ar=y(()=>{Uc();});function no(e){return typeof e=="number"?e:Number.parseInt(String(e),10)}var Wc=y(()=>{});var Gc=y(()=>{});var at=y(()=>{wc();bc();Sc();Ec();xc();$r();Ar();Wc();Gc();});var so,zc=y(()=>{so=(e,t,r)=>(n,s)=>{let i=-1;return o(0);async function o(a){if(a<=i)throw new Error("next() called multiple times");i=a;let l,c=false,u;if(e[a]?(u=e[a][0][0],n.req.routeIndex=a):u=a===e.length&&s||void 0,u)try{l=await u(n,()=>o(a+1));}catch(p){if(p instanceof Error&&t)n.error=p,l=await t(p,n),c=true;else throw p}else n.finalized===false&&r&&(l=await r(n));return l&&(n.finalized===false||c)&&(n.res=l),n}};});var Vc=y(()=>{});var Kc,Jc=y(()=>{Kc=Symbol();});async function Ny(e,t){let r=await e.formData();return r?Oy(r,t):{}}function Oy(e,t){let r=Object.create(null);return e.forEach((n,s)=>{t.all||s.endsWith("[]")?Iy(r,s,n):r[s]=n;}),t.dot&&Object.entries(r).forEach(([n,s])=>{n.includes(".")&&(Ly(r,n,s),delete r[n]);}),r}var Xc,Iy,Ly,Yc=y(()=>{io();Xc=async(e,t=Object.create(null))=>{let{all:r=false,dot:n=false}=t,i=(e instanceof ss?e.raw.headers:e.headers).get("Content-Type");return i?.startsWith("multipart/form-data")||i?.startsWith("application/x-www-form-urlencoded")?Ny(e,{all:r,dot:n}):{}};Iy=(e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r;},Ly=(e,t,r)=>{let n=e,s=t.split(".");s.forEach((i,o)=>{o===s.length-1?n[i]=r:((!n[i]||typeof n[i]!="object"||Array.isArray(n[i])||n[i]instanceof File)&&(n[i]=Object.create(null)),n=n[i]);});};});var ao,Qc,Dy,jy,is,Zc,os,Fy,lo,eu,_t,as,oo,tu,ru,nu,co,Vt=y(()=>{ao=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},Qc=e=>{let{groups:t,path:r}=Dy(e),n=ao(r);return jy(n,t)},Dy=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let s=`@${n}`;return t.push([s,r]),s}),{groups:t,path:e}},jy=(e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let s=e.length-1;s>=0;s--)if(e[s].includes(n)){e[s]=e[s].replace(n,t[r][1]);break}}return e},is={},Zc=(e,t)=>{if(e==="*")return "*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return is[n]||(r[2]?is[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:is[n]=[e,r[1],true]),is[n]}return null},os=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},Fy=e=>os(e,decodeURI),lo=e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let s=t.charCodeAt(n);if(s===37){let i=t.indexOf("?",n),o=t.indexOf("#",n),a=i===-1?o===-1?void 0:o:o===-1?i:Math.min(i,o),l=t.slice(r,a);return Fy(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(s===63||s===35)break}return t.slice(r,n)},eu=e=>{let t=lo(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},_t=(e,t,...r)=>(r.length&&(t=_t(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),as=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(s=>{if(s!==""&&!/\:/.test(s))n+="/"+s;else if(/\:/.test(s))if(/\?/.test(s)){r.length===0&&n===""?r.push("/"):r.push(n);let i=s.replace("?","");n+="/"+i,r.push(n);}else n+="/"+s;}),r.filter((s,i,o)=>o.indexOf(s)===i)},oo=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?os(e,co):e):e,tu=(e,t,r)=>{let n;if(!r&&t&&!/[%+]/.test(t)){let o=e.indexOf("?",8);if(o===-1)return;for(e.startsWith(t,o+1)||(o=e.indexOf(`&${t}`,o+1));o!==-1;){let a=e.charCodeAt(o+t.length+1);if(a===61){let l=o+t.length+2,c=e.indexOf("&",l);return oo(e.slice(l,c===-1?void 0:c))}else if(a==38||isNaN(a))return "";o=e.indexOf(`&${t}`,o+1);}if(n=/[%+]/.test(e),!n)return}let s={};n??=/[%+]/.test(e);let i=e.indexOf("?",8);for(;i!==-1;){let o=e.indexOf("&",i+1),a=e.indexOf("=",i);a>o&&o!==-1&&(a=-1);let l=e.slice(i+1,a===-1?o===-1?void 0:o:a);if(n&&(l=oo(l)),i=o,l==="")continue;let c;a===-1?c="":(c=e.slice(a+1,o===-1?void 0:o),n&&(c=oo(c))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(c)):s[l]??=c;}return t?s[t]:s},ru=tu,nu=(e,t)=>tu(e,t,true),co=decodeURIComponent;});var su,ss,io=y(()=>{Vc();Jc();Yc();Vt();su=e=>os(e,co),ss=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#t=r,this.#e={};}param(e){return e?this.#r(e):this.#i()}#r(e){let t=this.#t[0][this.routeIndex][1][e],r=this.#s(t);return r&&/\%/.test(r)?su(r):r}#i(){let e={},t=Object.keys(this.#t[0][this.routeIndex][1]);for(let r of t){let n=this.#s(this.#t[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=/\%/.test(n)?su(n):n);}return e}#s(e){return this.#t[1]?this.#t[1][e]:e}query(e){return ru(this.url,e)}queries(e){return nu(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((r,n)=>{t[n]=r;}),t}async parseBody(e){return this.bodyCache.parsedBody??=await Xc(this,e)}#n=e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;let s=Object.keys(t)[0];return s?t[s].then(i=>(s==="json"&&(i=JSON.stringify(i)),new Response(i)[e]())):t[e]=r[e]()};json(){return this.#n("text").then(e=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(e,t){this.#e[e]=t;}valid(e){return this.#e[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Kc](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}};});var iu,ou,uo,po=y(()=>{iu={Stringify:1,BeforeStream:2,Stream:3},ou=(e,t)=>{let r=new String(e);return r.isEscaped=true,r.callbacks=t,r},uo=async(e,t,r,n,s)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let i=e.callbacks;if(!i?.length)return Promise.resolve(e);s?s[0]+=e:s=[e];let o=Promise.all(i.map(a=>a({phase:t,buffer:s,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(l=>uo(l,t,false,n,s))).then(()=>s[0]));return r?ou(await o,i):o};});var My,fo,Cr,au,lu=y(()=>{io();po();My="text/plain; charset=UTF-8",fo=(e,t)=>({"Content-Type":e,...t}),Cr=(e,t)=>new Response(e,t),au=class{#e;#t;env={};#r;finalized=false;error;#i;#s;#n;#u;#l;#c;#a;#p;#f;constructor(e,t){this.#e=e,t&&(this.#s=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#f=t.path,this.#p=t.matchResult);}get req(){return this.#t??=new ss(this.#e,this.#f,this.#p),this.#t}get event(){if(this.#s&&"respondWith"in this.#s)return this.#s;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#s)return this.#s;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=Cr(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=Cr(e.body,e);for(let[t,r]of this.#n.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let s of n)e.headers.append("set-cookie",s);}else e.headers.set(t,r);}this.#n=e,this.finalized=true;}render=(...e)=>(this.#l??=t=>this.html(t),this.#l(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#l=e;};header=(e,t,r)=>{this.finalized&&(this.#n=Cr(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;t===void 0?n.delete(e):r?.append?n.append(e,t):n.set(e,t);};status=e=>{this.#i=e;};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t);};get=e=>this.#r?this.#r.get(e):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#o(e,t,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof t=="object"&&"headers"in t){let i=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[o,a]of i)o.toLowerCase()==="set-cookie"?n.append(o,a):n.set(o,a);}if(r)for(let[i,o]of Object.entries(r))if(typeof o=="string")n.set(i,o);else {n.delete(i);for(let a of o)n.append(i,a);}let s=typeof t=="number"?t:t?.status??this.#i;return Cr(e,{status:s,headers:n})}newResponse=(...e)=>this.#o(...e);body=(e,t,r)=>this.#o(e,t,r);text=(e,t,r)=>!this.#a&&!this.#i&&!t&&!r&&!this.finalized?new Response(e):this.#o(e,t,fo(My,r));json=(e,t,r)=>this.#o(JSON.stringify(e),t,fo("application/json",r));html=(e,t,r)=>{let n=s=>this.#o(s,t,fo("text/html; charset=UTF-8",r));return typeof e=="object"?uo(e,iu.Stringify,false,{}).then(n):n(e)};redirect=(e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>Cr(),this.#c(this))};});var te,cu,uu,ls,cs,lt=y(()=>{te="ALL",cu="all",uu=["get","post","put","delete","options","patch"],ls="Can not add a route since the matcher is already built.",cs=class extends Error{};});var Rr,mo=y(()=>{Rr="__COMPOSED_HANDLER";});var Uy,pu,fu,du=y(()=>{zc();lu();lt();mo();Vt();Uy=e=>e.text("404 Not Found",404),pu=(e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},fu=class mu{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...uu,cu].forEach(i=>{this[i]=(o,...a)=>(typeof o=="string"?this.#e=o:this.#i(i,this.#e,o),a.forEach(l=>{this.#i(i,this.#e,l);}),this);}),this.on=(i,o,...a)=>{for(let l of [o].flat()){this.#e=l;for(let c of [i].flat())a.map(u=>{this.#i(c.toUpperCase(),this.#e,u);});}return this},this.use=(i,...o)=>(typeof i=="string"?this.#e=i:(this.#e="*",o.unshift(i)),o.forEach(a=>{this.#i(te,this.#e,a);}),this);let{strict:n,...s}=t;Object.assign(this,s),this.getPath=n??true?t.getPath??lo:eu;}#t(){let t=new mu({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Uy;errorHandler=pu;route(t,r){let n=this.basePath(t);return r.routes.map(s=>{let i;r.errorHandler===pu?i=s.handler:(i=async(o,a)=>(await so([],r.errorHandler)(o,()=>s.handler(o,a))).res,i[Rr]=s.handler),n.#i(s.method,s.path,i);}),this}basePath(t){let r=this.#t();return r._basePath=_t(this._basePath,t),r}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,r,n){let s,i;n&&(typeof n=="function"?i=n:(i=n.optionHandler,n.replaceRequest===false?s=l=>l:s=n.replaceRequest));let o=i?l=>{let c=i(l);return Array.isArray(c)?c:[c]}:l=>{let c;try{c=l.executionCtx;}catch{}return [l.env,c]};s||=(()=>{let l=_t(this._basePath,t),c=l==="/"?0:l.length;return u=>{let p=new URL(u.url);return p.pathname=p.pathname.slice(c)||"/",new Request(p,u)}})();let a=async(l,c)=>{let u=await r(s(l.req.raw),...o(l));if(u)return u;await c();};return this.#i(te,_t(t,"*"),a),this}#i(t,r,n){t=t.toUpperCase(),r=_t(this._basePath,r);let s={basePath:this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s);}#s(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,n,s){if(s==="HEAD")return (async()=>new Response(null,await this.#n(t,r,n,"GET")))();let i=this.getPath(t,{env:n}),o=this.router.match(s,i),a=new au(t,{path:i,matchResult:o,env:n,executionCtx:r,notFoundHandler:this.#r});if(o[0].length===1){let c;try{c=o[0][0][0][0](a,async()=>{a.res=await this.#r(a);});}catch(u){return this.#s(u,a)}return c instanceof Promise?c.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#s(u,a)):c??this.#r(a)}let l=so(o[0],this.errorHandler,this.#r);return (async()=>{try{let c=await l(a);if(!c.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return c.res}catch(c){return this.#s(c,a)}})()}fetch=(t,...r)=>this.#n(t,r[1],r[0],t.method);request=(t,r,n,s)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,s):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${_t("/",t)}`,r),n,s));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method));});}};});function ho(e,t){let r=this.buildAllMatchers(),n=((s,i)=>{let o=r[s]||r[te],a=o[2][i];if(a)return a;let l=i.match(o[0]);if(!l)return [[],us];let c=l.indexOf("",1);return [o[1][c],l]});return this.match=n,n(e,t)}var us,go=y(()=>{lt();us=[];});function qy(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===kr||e===Pr?1:t===kr||t===Pr?-1:e===ps?1:t===ps?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var ps,kr,Pr,$t,By,hu,wo=y(()=>{ps="[^/]+",kr=".*",Pr="(?:|/.*)",$t=Symbol(),By=new Set(".\\+*[^]$()");hu=class yo{#e;#t;#r=Object.create(null);insert(t,r,n,s,i){if(t.length===0){if(this.#e!==void 0)throw $t;if(i)return;this.#e=r;return}let[o,...a]=t,l=o==="*"?a.length===0?["","",kr]:["","",ps]:o==="/*"?["","",Pr]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let u=l[1],p=l[2]||ps;if(u&&l[2]&&(p===".*"||(p=p.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(p))))throw $t;if(c=this.#r[p],!c){if(Object.keys(this.#r).some(f=>f!==kr&&f!==Pr))throw $t;if(i)return;c=this.#r[p]=new yo,u!==""&&(c.#t=s.varIndex++);}!i&&u!==""&&n.push([u,c.#t]);}else if(c=this.#r[o],!c){if(Object.keys(this.#r).some(u=>u.length>1&&u!==kr&&u!==Pr))throw $t;if(i)return;c=this.#r[o]=new yo;}c.insert(a,r,n,s,i);}buildRegExpStr(){let r=Object.keys(this.#r).sort(qy).map(n=>{let s=this.#r[n];return (typeof s.#t=="number"?`(${n})@${s.#t}`:By.has(n)?`\\${n}`:n)+s.buildRegExpStr()});return typeof this.#e=="number"&&r.unshift(`#${this.#e}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};});var gu,yu=y(()=>{wo();gu=class{#e={varIndex:0};#t=new hu;insert(e,t,r){let n=[],s=[];for(let o=0;;){let a=false;if(e=e.replace(/\{[^}]+\}/g,l=>{let c=`@\\${o}`;return s[o]=[c,l],o++,a=true,c}),!a)break}let i=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let o=s.length-1;o>=0;o--){let[a]=s[o];for(let l=i.length-1;l>=0;l--)if(i[l].indexOf(a)!==-1){i[l]=i[l].replace(a,s[o][1]);break}}return this.#t.insert(i,t,n,this.#e,r),n}buildRegExp(){let e=this.#t.buildRegExpStr();if(e==="")return [/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,i,o)=>i!==void 0?(r[++t]=Number(i),"$()"):(o!==void 0&&(n[Number(o)]=++t),"")),[new RegExp(`^${e}`),r,n]}};});function bu(e){return wu[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function Wy(){wu=Object.create(null);}function Gy(e){let t=new gu,r=[];if(e.length===0)return Hy;let n=e.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,u],[p,f])=>c?1:p?-1:u.length-f.length),s=Object.create(null);for(let c=0,u=-1,p=n.length;c<p;c++){let[f,g,d]=n[c];f?s[g]=[d.map(([w])=>[w,Object.create(null)]),us]:u++;let m;try{m=t.insert(g,u,f);}catch(w){throw w===$t?new cs(g):w}f||(r[u]=d.map(([w,h])=>{let S=Object.create(null);for(h-=1;h>=0;h--){let[T,$]=m[h];S[T]=$;}return [w,S]}));}let[i,o,a]=t.buildRegExp();for(let c=0,u=r.length;c<u;c++)for(let p=0,f=r[c].length;p<f;p++){let g=r[c][p]?.[1];if(!g)continue;let d=Object.keys(g);for(let m=0,w=d.length;m<w;m++)g[d[m]]=a[g[d[m]]];}let l=[];for(let c in o)l[c]=r[o[c]];return [i,l,s]}function Kt(e,t){if(e){for(let r of Object.keys(e).sort((n,s)=>s.length-n.length))if(bu(r).test(t))return [...e[r]]}}var Hy,wu,fs,bo=y(()=>{lt();Vt();go();wo();yu();Hy=[/^$/,[],Object.create(null)],wu=Object.create(null);fs=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[te]:Object.create(null)},this.#t={[te]:Object.create(null)};}add(e,t,r){let n=this.#e,s=this.#t;if(!n||!s)throw new Error(ls);n[e]||[n,s].forEach(a=>{a[e]=Object.create(null),Object.keys(a[te]).forEach(l=>{a[e][l]=[...a[te][l]];});}),t==="/*"&&(t="*");let i=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=bu(t);e===te?Object.keys(n).forEach(l=>{n[l][t]||=Kt(n[l],t)||Kt(n[te],t)||[];}):n[e][t]||=Kt(n[e],t)||Kt(n[te],t)||[],Object.keys(n).forEach(l=>{(e===te||e===l)&&Object.keys(n[l]).forEach(c=>{a.test(c)&&n[l][c].push([r,i]);});}),Object.keys(s).forEach(l=>{(e===te||e===l)&&Object.keys(s[l]).forEach(c=>a.test(c)&&s[l][c].push([r,i]));});return}let o=as(t)||[t];for(let a=0,l=o.length;a<l;a++){let c=o[a];Object.keys(s).forEach(u=>{(e===te||e===u)&&(s[u][c]||=[...Kt(n[u],c)||Kt(n[te],c)||[]],s[u][c].push([r,i-l+a+1]));});}}match=ho;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(t=>{e[t]||=this.#r(t);}),this.#e=this.#t=void 0,Wy(),e}#r(e){let t=[],r=e===te;return [this.#e,this.#t].forEach(n=>{let s=n[e]?Object.keys(n[e]).map(i=>[i,n[e][i]]):[];s.length!==0?(r||=true,t.push(...s)):e!==te&&t.push(...Object.keys(n[te]).map(i=>[i,n[te][i]]));}),r?Gy(t):null}};});var Su=y(()=>{lt();go();bo();});var Eu=y(()=>{bo();Su();});var So,xu=y(()=>{lt();So=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers;}add(e,t,r){if(!this.#t)throw new Error(ls);this.#t.push([e,t,r]);}match(e,t){if(!this.#t)throw new Error("Fatal error");let r=this.#e,n=this.#t,s=r.length,i=0,o;for(;i<s;i++){let a=r[i];try{for(let l=0,c=n.length;l<c;l++)a.add(...n[l]);o=a.match(e,t);}catch(l){if(l instanceof cs)continue;throw l}this.match=a.match.bind(a),this.#e=[a],this.#t=void 0;break}if(i===s)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#t||this.#e.length!==1)throw new Error("No active router has been determined yet.");return this.#e[0]}};});var _u=y(()=>{xu();});var Nr,zy,$u,Tu=y(()=>{lt();Vt();Nr=Object.create(null),zy=e=>{for(let t in e)return true;return false},$u=class vu{#e;#t;#r;#i=0;#s=Nr;constructor(t,r,n){if(this.#t=n||Object.create(null),this.#e=[],t&&r){let s=Object.create(null);s[t]={handler:r,possibleKeys:[],score:0},this.#e=[s];}this.#r=[];}insert(t,r,n){this.#i=++this.#i;let s=this,i=Qc(r),o=[];for(let a=0,l=i.length;a<l;a++){let c=i[a],u=i[a+1],p=Zc(c,u),f=Array.isArray(p)?p[0]:c;if(f in s.#t){s=s.#t[f],p&&o.push(p[1]);continue}s.#t[f]=new vu,p&&(s.#r.push(p),o.push(p[1])),s=s.#t[f];}return s.#e.push({[t]:{handler:n,possibleKeys:o.filter((a,l,c)=>c.indexOf(a)===l),score:this.#i}}),s}#n(t,r,n,s,i){for(let o=0,a=r.#e.length;o<a;o++){let l=r.#e[o],c=l[n]||l[te],u={};if(c!==void 0&&(c.params=Object.create(null),t.push(c),s!==Nr||i&&i!==Nr))for(let p=0,f=c.possibleKeys.length;p<f;p++){let g=c.possibleKeys[p],d=u[c.score];c.params[g]=i?.[g]&&!d?i[g]:s[g]??i?.[g],u[c.score]=true;}}}search(t,r){let n=[];this.#s=Nr;let i=[this],o=ao(r),a=[],l=o.length,c=null;for(let u=0;u<l;u++){let p=o[u],f=u===l-1,g=[];for(let m=0,w=i.length;m<w;m++){let h=i[m],S=h.#t[p];S&&(S.#s=h.#s,f?(S.#t["*"]&&this.#n(n,S.#t["*"],t,h.#s),this.#n(n,S,t,h.#s)):g.push(S));for(let T=0,$=h.#r.length;T<$;T++){let P=h.#r[T],N=h.#s===Nr?{}:{...h.#s};if(P==="*"){let D=h.#t["*"];D&&(this.#n(n,D,t,h.#s),D.#s=N,g.push(D));continue}let[v,_,I]=P;if(!p&&!(I instanceof RegExp))continue;let b=h.#t[v];if(I instanceof RegExp){if(c===null){c=new Array(l);let F=r[0]==="/"?1:0;for(let E=0;E<l;E++)c[E]=F,F+=o[E].length+1;}let D=r.substring(c[u]),R=I.exec(D);if(R){if(N[_]=R[0],this.#n(n,b,t,h.#s,N),zy(b.#t)){b.#s=N;let F=R[0].match(/\//)?.length??0;(a[F]||=[]).push(b);}continue}}(I===true||I.test(p))&&(N[_]=p,f?(this.#n(n,b,t,N,h.#s),b.#t["*"]&&this.#n(n,b.#t["*"],t,N,h.#s)):(b.#s=N,g.push(b)));}}let d=a.shift();i=d?g.concat(d):g;}return n.length>1&&n.sort((u,p)=>u.score-p.score),[n.map(({handler:u,params:p})=>[u,p])]}};});var Eo,Au=y(()=>{Vt();Tu();Eo=class{name="TrieRouter";#e;constructor(){this.#e=new $u;}add(e,t,r){let n=as(t);if(n){for(let s=0,i=n.length;s<i;s++)this.#e.insert(e,n[s],r);return}this.#e.insert(e,t,r);}match(e,t){return this.#e.search(e,t)}};});var Cu=y(()=>{Au();});var xo,Ru=y(()=>{du();Eu();_u();Cu();xo=class extends fu{constructor(e={}){super(e),this.router=e.router??new So({routers:[new fs,new Eo]});}};});var ku=y(()=>{Ru();});function _o(e){return !e||typeof e!="object"?false:e.code==="EADDRINUSE"}function Pu(e,t){return new Promise((r,n)=>{let s=o=>{e.off("listening",i),n(o);},i=()=>{e.off("error",s),r();};e.once("error",s),e.once("listening",i),e.listen(t);})}function $o(e){console.error(),console.error(Or.default.red(`Cannot start server: Port ${Or.default.bold(String(e))} is already in use.`)),console.error(Or.default.red(`Stop the process using that port, or set a different ${Or.default.bold("api.port")} in your config.`)),console.error(),process.exit(1);}var Or,Nu=y(()=>{Or=ee(ie());});var Ou,Iu=y(()=>{Ou=/^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;});var To,Lu,Vy,vo,Ao=y(()=>{To=(e,t=vo)=>{let r=/\.([a-zA-Z0-9]+?)$/,n=e.match(r);if(!n)return;let s=t[n[1]];return s&&s.startsWith("text")&&(s+="; charset=utf-8"),s},Lu=e=>{for(let t in vo)if(vo[t]===e)return t},Vy={aac:"audio/aac",avi:"video/x-msvideo",avif:"image/avif",av1:"video/av1",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css",csv:"text/csv",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",gz:"application/gzip",htm:"text/html",html:"text/html",ico:"image/x-icon",ics:"text/calendar",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",map:"application/json",mid:"audio/x-midi",midi:"audio/x-midi",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",pdf:"application/pdf",png:"image/png",rtf:"application/rtf",svg:"image/svg+xml",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",wasm:"application/wasm",webm:"video/webm",weba:"audio/webm",webmanifest:"application/manifest+json",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xml:"application/xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2",gltf:"model/gltf+json",glb:"model/gltf-binary"},vo=Vy;});var Du,ju=y(()=>{Du=(...e)=>{let t=e.filter(s=>s!=="").join("/");t=t.replace(/(?<=\/)\/+/g,"");let r=t.split("/"),n=[];for(let s of r)s===".."&&n.length>0&&n.at(-1)!==".."?n.pop():s!=="."&&n.push(s);return n.join("/")||"."};});var Fu,Ky,Jy,Mu,Uu=y(()=>{Iu();Ao();ju();Fu={br:".br",zstd:".zst",gzip:".gz"},Ky=Object.keys(Fu),Jy="index.html",Mu=e=>{let t=e.root??"./",r=e.path,n=e.join??Du;return async(s,i)=>{if(s.finalized)return i();let o;if(e.path)o=e.path;else try{if(o=decodeURIComponent(s.req.path),/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(o))throw new Error}catch{return await e.onNotFound?.(s.req.path,s),i()}let a=n(t,!r&&e.rewriteRequestPath?e.rewriteRequestPath(o):o);e.isDir&&await e.isDir(a)&&(a=n(a,Jy));let l=e.getContent,c=await l(a,s);if(c instanceof Response)return s.newResponse(c.body,c);if(c){let u=e.mimes&&To(a,e.mimes)||To(a);if(s.header("Content-Type",u||"application/octet-stream"),e.precompressed&&(!u||Ou.test(u))){let p=new Set(s.req.header("Accept-Encoding")?.split(",").map(f=>f.trim()));for(let f of Ky){if(!p.has(f))continue;let g=await l(a+Fu[f],s);if(g){c=g,s.header("Content-Encoding",f),s.header("Vary","Accept-Encoding",{append:true});break}}}return await e.onFound?.(a,s),s.body(c)}await e.onNotFound?.(a,s),await i();}};});var Bu,qu=y(()=>{Uu();Bu=e=>async function(r,n){return Mu({...e,getContent:async o=>{let a=Bun.file(o);return await a.exists()?a:null},join:join,isDir:async o=>{let a;try{a=(await stat(o)).isDirectory();}catch{}return a}})(r,n)};});var Hu=y(()=>{});var Wu,Gu=y(()=>{Hu();Wu=(e,t)=>{for(let[r,n]of Object.entries(t)){let s=new RegExp("/:"+r+"(?:{[^/]+})?\\??");e=e.replace(s,n?`/${n}`:"");}return e};});var Qy,zu,Vu=y(()=>{Qy=1024,zu=({concurrency:e,interval:t}={})=>{if(e||=Qy,e===1/0)return {run:async s=>s()};let r=new Set,n=async(s,i,o)=>{if(r.size>=e)return i||=new Promise(c=>o=c),setTimeout(()=>n(s,i,o)),i;let a={};r.add(a);let l=await s();return t?setTimeout(()=>r.delete(a),t):r.delete(a),o?(o(l),i):l};return {run:n}};});var Ku,Co,Ju=y(()=>{mo();Ku=e=>e.length>1,Co=e=>e[Rr]?Co(e[Rr]):e;});var Xu,Zy,ew,tw,rw,Ir,Yu,Ro,ko=y(()=>{lt();Ju();Xu=e=>e.split(/[\/\\]/).slice(0,-1).join("/"),Zy=e=>e.replace(/(\\)/g,"/").replace(/\/$/g,""),ew=(e,t)=>{e.length===0||t?e.push(".."):e.pop();},tw=(e,t)=>{e=e.replace(/^\.(?!.)/,""),e!==""&&t.push(e);},rw=(e,t)=>{let r=false;for(let n of e)n===".."?(ew(t,r),r=true):(tw(n,t),r=false);},Ir=(...e)=>{e=e.map(Zy);let t=[];return rw(e.join("/").split("/"),t),(e[0][0]==="/"?"/":"")+t.join("/")},Yu=e=>e.routes.reduce((t,{method:r,handler:n,path:s})=>{let i=Co(n);return ["GET",te].includes(r)&&!Ku(i)&&t.push({path:s}),t},[]),Ro=e=>e.split("/").some(t=>t.startsWith(":")||t.includes("*"));});var Qu,ms,Po=y(()=>{ko();Qu="HONO_SSG_CONTEXT",ms="x-hono-disable-ssg",(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[ms]:"true"}})}catch{return null}})();});var Zu=y(()=>{po();});var No,Oo=y(()=>{Zu();No=()=>({afterResponseHook:e=>e.status!==200?false:e});});var nw,sw,iw,ow,aw,lw,cw,uw,pw,fw,mw,ep,dw,tp,rp=y(()=>{Gu();Vu();Ao();Po();Oo();ko();nw=2,sw="text/plain",iw="./static",ow=(e,t,r,n)=>{let s=cw(r,n);return e.endsWith(`.${s}`)?Ir(t,e):e==="/"?Ir(t,`index.${s}`):e.endsWith("/")?Ir(t,e,`index.${s}`):Ir(t,`${e}.${s}`)},aw=async e=>{let t=e.headers.get("Content-Type");try{return t?.includes("text")||t?.includes("json")?await e.text():await e.arrayBuffer()}catch(r){throw new Error(`Error processing response: ${r instanceof Error?r.message:"Unknown error"}`)}},lw={"text/html":"html","text/xml":"xml","application/xml":"xml","application/yaml":"yaml"},cw=(e,t)=>{let r=t||lw;return e in r?r[e]:Lu(e)||"html"},uw=e=>Array.isArray(e)?async t=>{let r=t;for(let n of e){let s=await n(r);if(s===false)return false;s instanceof Request&&(r=s);}return r}:e,pw=e=>Array.isArray(e)?async t=>{let r=t;for(let n of e){let s=await n(r);if(s===false)return false;s instanceof Response&&(r=s);}return r}:e,fw=(e,t,r)=>Array.isArray(e)?async n=>{for(let s of e)await s(n,t,r);}:e,mw=function*(e,t,r,n){let s="http://localhost",i=zu({concurrency:n});for(let o of Yu(e)){let a=new URL(o.path,s).toString(),l=new Request(a);yield new Promise(async(c,u)=>{try{if(t){let f=await t(l);if(!f){c(void 0);return}l=f;}if(await i.run(()=>e.fetch(l)),!l.ssgParams){if(Ro(o.path)){c(void 0);return}l.ssgParams=[{}];}let p={method:l.method,headers:l.headers};c((function*(){for(let f of l.ssgParams)yield new Promise(async(g,d)=>{try{let m=Wu(o.path,f),w=await i.run(()=>e.request(m,p,{[Qu]:!0}));if(w.headers.get(ms)){g(void 0);return}if(r){let T=await r(w);if(!T){g(void 0);return}w=T;}let h=w.headers.get("Content-Type")?.split(";")[0]||sw,S=await aw(w);g({routePath:m,mimeType:h,content:S});}catch(m){d(m);}});})());}catch(p){u(p);}});}},ep=new Set,dw=async(e,t,r,n)=>{let s=await e;if(!s)return;let{routePath:i,content:o,mimeType:a}=s,l=ow(i,r,a,n),c=Xu(l);return ep.has(c)||(await t.mkdir(c,{recursive:true}),ep.add(c)),typeof o=="string"?await t.writeFile(l,o):o instanceof ArrayBuffer&&await t.writeFile(l,new Uint8Array(o)),l},tp=async(e,t,r)=>{let n,s=[],i=[],o=r?.plugins||[No()],a=[],l=[],c=[];r?.beforeRequestHook&&a.push(...Array.isArray(r.beforeRequestHook)?r.beforeRequestHook:[r.beforeRequestHook]),r?.afterResponseHook&&l.push(...Array.isArray(r.afterResponseHook)?r.afterResponseHook:[r.afterResponseHook]),r?.afterGenerateHook&&c.push(...Array.isArray(r.afterGenerateHook)?r.afterGenerateHook:[r.afterGenerateHook]);for(let u of o)u.beforeRequestHook&&a.push(...Array.isArray(u.beforeRequestHook)?u.beforeRequestHook:[u.beforeRequestHook]),u.afterResponseHook&&l.push(...Array.isArray(u.afterResponseHook)?u.afterResponseHook:[u.afterResponseHook]),u.afterGenerateHook&&c.push(...Array.isArray(u.afterGenerateHook)?u.afterGenerateHook:[u.afterGenerateHook]);try{let u=r?.dir??iw,p=r?.concurrency??nw,f=uw(a.length>0?a:[w=>w]),g=pw(l.length>0?l:[w=>w]),d=mw(e,f,g,p);for(let w of d)s.push(w.then(h=>{if(h)for(let S of h)i.push(dw(S,t,u,r?.extensionMap).catch(T=>T));}));await Promise.all(s);let m=[];for(let w of i){let h=await w;if(typeof h=="string")m.push(h);else if(h)throw h}n={success:!0,files:m};}catch(u){let p=u instanceof Error?u:new Error(String(u));n={success:false,files:[],error:p};}return c.length>0&&await fw(c,t,r)(n,t,r),n};});var np=y(()=>{rp();Po();Oo();});var hw,Io,sp,ip=y(()=>{np();(({write:hw}=Bun)),Io={writeFile:async(e,t)=>{await hw(e,t);},mkdir:async()=>{}},sp=async(e,t)=>tp(e,Io,t);});var op,ap,lp,cp=y(()=>{op=class{#e;constructor(e){this.#e=e,this.raw=e.raw,this.url=e.url?new URL(e.url):null,this.protocol=e.protocol??null;}send(e,t){this.#e.send(e,t??{});}raw;binaryType="arraybuffer";get readyState(){return this.#e.readyState}url;protocol;close(e,t){this.#e.close(e,t);}},ap=e=>new MessageEvent("message",{data:e}),lp=e=>((...t)=>{if(typeof t[0]=="function"){let[r,n]=t;return async function(i,o){let a=await r(i),l=await e(i,a,n);if(l)return l;await o();}}else {let[r,n,s]=t;return (async()=>{let i=await e(r,n,s);if(!i)throw new Error("Failed to upgrade WebSocket");return i})()}});});var Jt,ds=y(()=>{Jt=e=>"server"in e.env?e.env.server:e.env;});var Lo,Do,jo,up,pp=y(()=>{cp();ds();Lo=e=>new op({send:(t,r)=>{e.send(t,r?.compress);},raw:e,readyState:e.readyState,url:e.data.url,protocol:e.data.protocol,close(t,r){e.close(t,r);}}),Do=lp((e,t)=>{let r=Jt(e);if(!r)throw new TypeError("env has to include the 2nd argument of fetch.");if(r.upgrade(e.req.raw,{data:{events:t,url:new URL(e.req.url),protocol:e.req.url}}))return new Response(null)}),jo={open(e){let t=e.data.events;t.onOpen&&t.onOpen(new Event("open"),Lo(e));},close(e,t,r){let n=e.data.events;n.onClose&&n.onClose(new CloseEvent("close",{code:t,reason:r}),Lo(e));},message(e,t){let r=e.data.events;if(r.onMessage){let n=typeof t=="string"?t:t.buffer;r.onMessage(ap(n),Lo(e));}}},up=()=>({upgradeWebSocket:Do,websocket:jo});});var fp,mp=y(()=>{ds();fp=e=>{let t=Jt(e);if(!t)throw new TypeError("env has to include the 2nd argument of fetch.");if(typeof t.requestIP!="function")throw new TypeError("server.requestIP is not a function.");let r=t.requestIP(e.req.raw);return r?{remote:{address:r.address,addressType:r.family==="IPv6"||r.family==="IPv4"?r.family:void 0,port:r.port}}:{remote:{}}};});var dp={};de(dp,{bunFileSystemModule:()=>Io,createBunWebSocket:()=>up,getBunServer:()=>Jt,getConnInfo:()=>fp,serveStatic:()=>Bu,toSSG:()=>sp,upgradeWebSocket:()=>Do,websocket:()=>jo});var hp=y(()=>{qu();ip();pp();mp();ds();});async function hs(e,t={port:3e3}){let r=Vn(),n=t.port??3e3;if(_r()){let s=await Promise.resolve().then(()=>(hp(),dp)).then(o=>o.serveStatic),i;try{i=Bun.serve({fetch:yp(e,r,s).fetch,port:n});}catch(o){throw _o(o)&&$o(n),o}return async()=>{await i.stop();}}else {let{createAdaptorServer:s}=await import('@hono/node-server'),i=await import('@hono/node-server/serve-static').then(a=>a.serveStatic),o=s({fetch:yp(e,r,i).fetch});try{await Pu(o,n);}catch(a){throw _o(a)&&$o(n),a}return ()=>new Promise(a=>{o.close(()=>{a(void 0);});})}}function yp(e,t,r){return new xo().use("/favicon.ico",r({path:We__default.join(t,"static","favicon.ico")})).use("/fonts/*",r({root:We__default.join(t,"static"),onNotFound:n=>{console.log("fonts not found",n,process.cwd());}})).use("/static/*",r({root:t,onNotFound(n){console.log("not found",n,process.cwd());}})).all("*",async n=>e.fetch(n.req.raw))}var Fo=y(()=>{at();ku();Nu();Ee();});var et,Mo=y(()=>{bt();et=class e{root;constructor(t,r){let n=r??e.projectDir();this.root=We__default.join(n,t??"");}ensureRoot(){ke(this.root);}static homeDir(){return We__default.join(gw.homedir(),".lite")}static projectDir(){return We__default.join(process.cwd(),"supabase")}deleteAll(t=false){try{Fn.rmSync(this.root,{recursive:!0});}catch(r){if(!t)throw r}this.ensureRoot();}delete(t,r=false){try{Fn.unlinkSync(We__default.join(this.root,t));}catch(n){if(!r)throw n}}write(t,r,n=false){try{this.ensureRoot(),Fn.writeFileSync(We__default.join(this.root,t),r);}catch(s){if(!n)throw s}}read(t,r=false){try{return Fn.readFileSync(We__default.join(this.root,t),"utf8")}catch(n){if(!r)throw n}}relativePath(t){return t?We__default.relative(process.cwd(),We__default.join(this.root,t)):this.root}path(t){return t?We__default.join(this.root,t):this.root}};});var Lr,Uo=y(()=>{Lr=process.env.SUPALITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2000":"https://www.lite.dev");});var ws,wp=y(()=>{bt();ws=class{root;constructor(t){this.root=t??We__default.join(gw.homedir(),".lite","auth"),ke(this.root);}async getItem(t){try{return Fn.readFileSync(We__default.join(this.root,t+".json"),"utf8")}catch{return null}}async setItem(t,r){Fn.writeFileSync(We__default.join(this.root,t+".json"),r);}async removeItem(t){try{Fn.unlinkSync(We__default.join(this.root,t+".json"));}catch{return}}};});var Xt,qo=y(()=>{Uo();Mo();wp();Xt=class{constructor(t){this.config=t;this.tempFs=new et(".temp",this.config.root),this.projectFs=new et("supabase",this.config.root),this.schemaFs=new et("schemas",this.config.root),this.authStorage=this.config.authStorage??new ws(We__default.join(et.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??Lr,process.env.SUPALITE_CLOUD_ANON_KEY??"...",{auth:{storage:this.authStorage}}):void 0;}tempFs;projectFs;schemaFs;_client;authStorage;async fetch(t,r){if(!this.config.token)throw new Error("Not authenticated, sign in first.");let n=t instanceof URL?t:new URL(t,this.config.host??Lr);return await fetch(n,{...r,headers:{...r?.headers,Authorization:`Bearer ${this.config.token}`}})}};});var Yt,Ho=y(()=>{qo();Yt=class extends Xt{constructor(r){super(r);this.config=r;}get client(){if(!this._client)throw new Error("Supabase client not initialized");return this._client}projectRef(){return this.tempFs.read("project-ref",true)}projectUrl(r){let n=new URL(this.config.host),s=n.hostname==="localhost"?"supalite.local":n.hostname,i=s.split(".").filter(a=>a!=="www"),o=i.length>=2?i.slice(-2).join("."):s;return `${n.protocol}//${r}.${o}${n.port?`:${n.port}`:""}`}};});function Sw(e){let t=We.extname(e).toLowerCase();return {".html":"text/html",".css":"text/css",".js":"application/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".avif":"image/avif",".pdf":"application/pdf",".txt":"text/plain",".xml":"application/xml",".zip":"application/zip",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav",".woff":"font/woff",".woff2":"font/woff2"}[t]??"application/octet-stream"}var Ss,bp=y(()=>{at();Ss=class{driver=pe;basePath;constructor(t){this.basePath=We.resolve(t.basePath);}filePath(t,r){return We.join(this.basePath,t,r)}async ensureDir(t){await pe.mkdir(We.dirname(t),{recursive:true});}async getObject(t,r,n,s){let i=this.filePath(t,r),o=await pe.stat(i),a=`"${createHash("md5").update(`${i}:${o.mtimeMs}`).digest("hex")}"`;if(s?.ifNoneMatch===a)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,r)};if(s?.ifModifiedSince){let f=new Date(s.ifModifiedSince);if(o.mtime<=f)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,r)}}let l,c,u=o.size,p=200;if(s?.range){let f=s.range.match(/^bytes=(\d+)-(\d*)$/);if(f){let g=Number.parseInt(f[1],10),d=f[2]?Number.parseInt(f[2],10):o.size-1;u=d-g+1,c=`bytes ${g}-${d}/${o.size}`,p=206,l=(await pe.open(i,"r")).readableWebStream();}else l=(await pe.open(i,"r")).readableWebStream();}else l=(await pe.open(i,"r")).readableWebStream();return {httpStatusCode:p,metadata:{...this.buildMetadata(o,a,r),contentLength:u,contentRange:c},body:l}}async uploadObject(t,r,n,s,i,o){let a=this.filePath(t,r);await this.ensureDir(a);let l;if(s instanceof Uint8Array||Buffer.isBuffer(s))l=s;else {let p=[],f=s.getReader();for(;;){let{done:g,value:d}=await f.read();if(g)break;p.push(d);}l=Buffer.concat(p);}await pe.writeFile(a,l);let c=await pe.stat(a),u=`"${createHash("md5").update(l).digest("hex")}"`;return {cacheControl:o,contentLength:c.size,size:c.size,mimetype:i,lastModified:c.mtime,eTag:u}}async deleteObject(t,r,n){let s=this.filePath(t,r);await pe.unlink(s).catch(i=>{if(i.code!=="ENOENT")throw i});}async deleteObjects(t,r){for(let n of r)await this.deleteObject(t,n,void 0);}async copyObject(t,r,n,s,i){let o=this.filePath(t,r),a=this.filePath(t,s);await this.ensureDir(a),await pe.copyFile(o,a);let l=await pe.stat(a),c=await pe.readFile(a);return {httpStatusCode:200,eTag:`"${createHash("md5").update(c).digest("hex")}"`,lastModified:l.mtime}}async headObject(t,r,n){let s=this.filePath(t,r),i=await pe.stat(s),o=`"${createHash("md5").update(`${s}:${i.mtimeMs}`).digest("hex")}"`;return this.buildMetadata(i,o,r)}async privateAssetUrl(t,r,n){return `file://${this.filePath(t,r)}`}buildMetadata(t,r,n){return {cacheControl:"no-cache",contentLength:no(t.size),size:no(t.size),mimetype:Sw(n),lastModified:t.mtime,eTag:r}}};});async function Ue(e,t,r){try{return await Ew(e)}catch(n){throw n?.code==="ERR_MODULE_NOT_FOUND"||/Cannot find package/.test(String(n?.message))?new Error(`Driver '${t}' selected but '${r}' is not installed. Run: bun add ${r}`):n}}var Ew,Qt=y(()=>{Ew=new Function("spec","return import(spec)");});function Sp(e,t={}){let r=We__default.resolve(t.cwd??process.cwd()),n=t.env??process.env,s=process.env.SUPABASE_ENV||"development",i=[`.env.${s}.local`,s==="test"?null:".env.local",`.env.${s}`,".env"].filter(a=>a!==null),o=$w(We__default.resolve(e),r);for(let a of o)for(let l of i){let c=We__default.join(a,l),u;try{u=Fn.readFileSync(c,"utf-8");}catch{continue}let p;try{p=parse(u);}catch(f){throw new Error(`Failed to parse ${c}: ${f.message}`)}for(let[f,g]of Object.entries(p))n[f]===void 0&&(n[f]=g);}}function $w(e,t){let r=[],n=e,s=We__default.parse(n).root;for(;r.push(n),!(n===t||n===s);){let i=We__default.dirname(n);if(i===n)break;n=i;}return r}var Ep=y(()=>{});function xp(e,t=process.env){return Wo(e,t)}function Wo(e,t){if(typeof e=="string"){let r=e.match(vw);return r?t[r[1]]??"":e}if(Array.isArray(e))return e.map(r=>Wo(r,t));if(e&&typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return e;let n={};for(let[s,i]of Object.entries(e))n[s]=Wo(i,t);return n}return e}var vw,_p=y(()=>{vw=/^env\((\w+)\)$/;});var jr,Aw,Es,vp=y(()=>{Ho();Wt();jr=ee(ie());Er();qt();bp();Qt();Ep();_p();Aw=["toml","json","ts","mts","js","mjs","cjs"],Es=class extends Yt{ref(){return this.projectRef()}setRef(t){return this.tempFs.write("project-ref",t),this}link(t){return this.setRef(t.id),t}unlink(){return this.tempFs.delete("project-ref"),this}url(){let t=this.ref();if(!t)throw new Error("No project linked");return this.projectUrl(t)}async getConfigPath(t){let r=We__default.relative(process.cwd(),ve.config_dir);if(!t)for(let n of Aw){let s=We__default.join(r,`config.${n}`);if(await pe__default.access(s).then(()=>true).catch(()=>false)){t=s;break}}return t}async readConfig(t){let r=await this.getConfigPath(t);if(!r)return {};console.log(jr.default.dim(`Using config file: ${jr.default.cyan(`./${r}`)}`));let n=We__default.dirname(We__default.resolve(r));Sp(n);let s=r.split(".").pop(),i;switch(s){case "toml":i=Et(await pe__default.readFile(r,"utf-8"));break;case "json":i=JSON.parse(await pe__default.readFile(r,"utf-8"));break;case "ts":case "mts":case "js":case "mjs":case "cjs":try{i=(await import(We__default.join(process.cwd(),r))).default;break}catch(o){throw console.error("Failed to import config file",o),o}default:throw new Error(`Unsupported config file type: ${r}`)}return xp(i)}async createConnection(){throw new Error("Not implemented")}async getConfig(t){let r=await this.readConfig(t);if("connection"in r)return {...r,connection:await r.connection};let n,s;switch(r.db?.driver){case "sqlite":s=r.db?.url??ve.default_db_url,n=await createConnection({url:s,ddlDialect:"sqlite"});break;case "pglite":{s=r.db?.url??We__default.join(process.cwd(),ve.default_db_dir);let{createPgliteConnection:i}=await Ue("@supabase/lite/pglite","pglite","@electric-sql/pglite");n=await i({url:s});break}case "postgres":{s=r.db?.url??"";let{createPostgresConnection:i}=await Ue("@supabase/lite/postgres","postgres","postgres");n=await i({url:s});break}default:s=r.db?.url??ve.default_db_url,n=await createConnection({url:s,ddlDialect:"postgres"});break}if(!n)throw new Error("Failed to create connection");return console.log(jr.default.green(" \u279C"),"Database located at",jr.default.cyan(s??"in-memory")),{...r,connection:n}}async createApp(t){let r=await this.getConfig(t),n=new App(r);return n.config.storage?.enabled&&process.env.EXPERIMENTAL_STORAGE==="1"&&!n._storageAdapter&&(n._storageAdapter=new Ss({basePath:We__default.join(process.cwd(),ve.config_dir,".temp/storage")})),await n.init()}};});var xs,Tp=y(()=>{Ho();xs=class extends Yt{url(t){return this.projectUrl(t)}async ping(){return (await this.fetch("/v1/system/ping")).ok}async list(){let t=await this.fetch("/v1/projects");if(!t.ok)throw new Error("Failed to list projects");let r=await t.json();if(!r||!r.data)throw new Error("Failed to list projects");return r.data}async get(t){if(t=t??this.projectRef(),!t)throw new Error("No project ref found");let r=await this.fetch(`/v1/projects/${t}`);if(!r.ok)throw new Error(`Failed to get project: ${r.status} ${r.statusText}`);let n=await r.json();if(!n||!n.id)throw new Error("Failed to get project");return n}async create(t={}){let r=await this.fetch("/v1/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok)throw new Error(`Failed to create project: ${r.status} ${r.statusText}`);let n=await r.json();if(!n.data||!n.data.id)throw new Error("Failed to create project");return n.data}async getConfig(t){let r=await this.fetch(`/v1/projects/${t}/config`);if(!r.ok)throw new Error(`Failed to get project config: ${r.status} ${r.statusText}`);let n=await r.json();if(!n)throw new Error("Failed to get project config");return n}async setConfig(t,r){let n=await this.fetch(`/v1/projects/${t}/config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok)throw new Error(`Failed to set project config: ${n.status} ${n.statusText}`);return true}async createApp(t){if(!this.config.host)throw new Error("No host specified");let{data:r,error:n}=await this.client.auth.getSession();if(n)throw n;if(!r?.session?.access_token)throw new Error("Not authenticated, sign in first.");let s=await this.getConfig(t);return await new App({...s.config,connection:cloud({projectRef:t,token:r.session.access_token,host:this.config.host})}).init()}};});var _s,Ap=y(()=>{qo();vp();Tp();_s=class extends Xt{project;get client(){if(!this._client)throw new Error("Supabase client not initialized");return this._client}async getSession(){return await this.client.auth.getSession()}async getAccessToken(){let{data:t,error:r}=await this.getSession();if(r)throw r;return t?.session?.access_token}async requireSession(){let t=await this.getAccessToken();if(!t)throw new Error("Not authenticated, sign in first.");return t}async init(){let t={...this.config};return this.config.withSupabaseClient!==false&&(t.client=this.client,t.token=await this.getAccessToken()),this.project={local:new Es(t),remote:new xs(t)},this}};});async function z(e={}){return await new _s({host:Lr,root:et.projectDir(),...e}).init()}var Ce=y(()=>{Mo();Uo();Ap();});var Cp={};de(Cp,{start:()=>kw});var Fr,kw,Rp=y(()=>{Fo();at();Fr=ee(ie());Wt();Ce();Ee();qt();kw=e=>{e.command("start").option("--config <config>","Path to the config file").description("Start the development server").helpGroup("Local Development:").action(async t=>{await Y(t.config),await Xn(async()=>{let n=await(await z({withSupabaseClient:false})).project.local.createApp(t.config),s=n.config.api?.port??ve.default_api_port;await hs(n,{port:s});console.log(Fr.default.green(" \u279C"),"Server running on ",Fr.default.cyan(`http://localhost:${s}`));let o=jn();o&&console.log(Fr.default.yellow(` \u26A0 ${o}`)),await n.connection.ping();},r=>{console.log(),console.log(Fr.default.green(`Ready in ${r.toFixed(2)}ms`));});});};});function jw(e){let t=normalize(e);return t.length>1&&t[t.length-1]===sep&&(t=t.substring(0,t.length-1)),t}function Op(e,t){return e.replace(Fw,t)}function Uw(e){return e==="/"||Mw.test(e)}function zo(e,t){let{resolvePaths:r,normalizePath:n,pathSeparator:s}=t,i=process.platform==="win32"&&e.includes("/")||e.startsWith(".");if(r&&(e=resolve(e)),(n||i)&&(e=jw(e)),e===".")return "";let o=e[e.length-1]!==s;return Op(o?e+s:e,s)}function Ip(e,t){return t+e}function Bw(e,t){return function(r,n){return n.startsWith(e)?n.slice(e.length)+r:Op(relative(e,n),t.pathSeparator)+t.pathSeparator+r}}function qw(e){return e}function Hw(e,t,r){return t+e+r}function Ww(e,t){let{relativePaths:r,includeBasePath:n}=t;return r&&e?Bw(e,t):n?Ip:qw}function Gw(e){return function(t,r){r.push(t.substring(e.length)||".");}}function zw(e){return function(t,r,n){let s=t.substring(e.length)||".";n.every(i=>i(s,true))&&r.push(s);}}function Xw(e,t){let{includeDirs:r,filters:n,relativePaths:s}=t;return r?s?n&&n.length?zw(e):Gw(e):n&&n.length?Kw:Vw:Jw}function rb(e){let{excludeFiles:t,filters:r,onlyCounts:n}=e;return t?tb:r&&r.length?n?Yw:Qw:n?Zw:eb}function ib(e){return e.group?sb:nb}function lb(e){return e.group?ob:ab}function pb(e,t){return !e.resolveSymlinks||e.excludeSymlinks?null:t?ub:cb}function Lp(e,t,r){if(r.options.useRealPaths)return fb(t,r);let n=dirname(e),s=1;for(;n!==r.root&&s<2;){let i=r.symlinks.get(n);!!i&&(i===t||i.startsWith(t)||t.startsWith(i))?s++:n=dirname(n);}return r.symlinks.set(e,t),s>1}function fb(e,t){return t.visited.includes(e+t.options.pathSeparator)}function $s(e,t,r,n){t(e&&!n?e:null,r);}function Eb(e,t){let{onlyCounts:r,group:n,maxFiles:s}=e;return r?t?mb:yb:n?t?db:Sb:s?t?gb:bb:t?hb:wb}function $b(e){return e?_b:xb}function Cb(e,t){return new Promise((r,n)=>{Fp(e,t,(s,i)=>{if(s)return n(s);r(i);});})}function Fp(e,t,r){new jp(e,t,r).start();}function Rb(e,t){return new jp(e,t).start()}var kp,Fw,Mw,Vw,Kw,Jw,Yw,Qw,Zw,eb,tb,nb,sb,ob,ab,cb,ub,mb,db,hb,gb,yb,wb,bb,Sb,Dp,xb,_b,vb,Tb,Ab,jp,Pp,Mp,Up,Bp=y(()=>{kp=createRequire(import.meta.url);Fw=/[\\/]/g;Mw=/^[a-z]:[\\/]$/i;Vw=(e,t)=>{t.push(e||".");},Kw=(e,t,r)=>{let n=e||".";r.every(s=>s(n,true))&&t.push(n);},Jw=()=>{};Yw=(e,t,r,n)=>{n.every(s=>s(e,false))&&r.files++;},Qw=(e,t,r,n)=>{n.every(s=>s(e,false))&&t.push(e);},Zw=(e,t,r,n)=>{r.files++;},eb=(e,t)=>{t.push(e);},tb=()=>{};nb=e=>e,sb=()=>[""].slice(0,0);ob=(e,t,r)=>{e.push({directory:t,files:r,dir:t});},ab=()=>{};cb=function(e,t,r){let{queue:n,fs:s,options:{suppressErrors:i}}=t;n.enqueue(),s.realpath(e,(o,a)=>{if(o)return n.dequeue(i?null:o,t);s.stat(a,(l,c)=>{if(l)return n.dequeue(i?null:l,t);if(c.isDirectory()&&Lp(e,a,t))return n.dequeue(null,t);r(c,a),n.dequeue(null,t);});});},ub=function(e,t,r){let{queue:n,fs:s,options:{suppressErrors:i}}=t;n.enqueue();try{let o=s.realpathSync(e),a=s.statSync(o);if(a.isDirectory()&&Lp(e,o,t))return;r(a,o);}catch(o){if(!i)throw o}};mb=e=>e.counts,db=e=>e.groups,hb=e=>e.paths,gb=e=>e.paths.slice(0,e.options.maxFiles),yb=(e,t,r)=>($s(t,r,e.counts,e.options.suppressErrors),null),wb=(e,t,r)=>($s(t,r,e.paths,e.options.suppressErrors),null),bb=(e,t,r)=>($s(t,r,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),Sb=(e,t,r)=>($s(t,r,e.groups,e.options.suppressErrors),null);Dp={withFileTypes:true},xb=(e,t,r,n,s)=>{if(e.queue.enqueue(),n<0)return e.queue.dequeue(null,e);let{fs:i}=e;e.visited.push(t),e.counts.directories++,i.readdir(t||".",Dp,(o,a=[])=>{s(a,r,n),e.queue.dequeue(e.options.suppressErrors?null:o,e);});},_b=(e,t,r,n,s)=>{let{fs:i}=e;if(n<0)return;e.visited.push(t),e.counts.directories++;let o=[];try{o=i.readdirSync(t||".",Dp);}catch(a){if(!e.options.suppressErrors)throw a}s(o,r,n);};vb=class{count=0;constructor(e){this.onQueueEmpty=e;}enqueue(){return this.count++,this.count}dequeue(e,t){this.onQueueEmpty&&(--this.count<=0||e)&&(this.onQueueEmpty(e,t),e&&(t.controller.abort(),this.onQueueEmpty=void 0));}},Tb=class{_files=0;_directories=0;set files(e){this._files=e;}get files(){return this._files}set directories(e){this._directories=e;}get directories(){return this._directories}get dirs(){return this._directories}},Ab=class{aborted=false;abort(){this.aborted=true;}},jp=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(e,t,r){this.isSynchronous=!r,this.callbackInvoker=Eb(t,this.isSynchronous),this.root=zo(e,t),this.state={root:Uw(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new Tb,options:t,queue:new vb((n,s)=>this.callbackInvoker(s,n,r)),symlinks:new Map,visited:[""].slice(0,0),controller:new Ab,fs:t.fs||er},this.joinPath=Ww(this.root,t),this.pushDirectory=Xw(this.root,t),this.pushFile=rb(t),this.getArray=ib(t),this.groupFiles=lb(t),this.resolveSymlink=pb(t,this.isSynchronous),this.walkDirectory=$b(this.isSynchronous);}start(){return this.pushDirectory(this.root,this.state.paths,this.state.options.filters),this.walkDirectory(this.state,this.root,this.root,this.state.options.maxDepth,this.walk),this.isSynchronous?this.callbackInvoker(this.state,null):null}walk=(e,t,r)=>{let{paths:n,options:{filters:s,resolveSymlinks:i,excludeSymlinks:o,exclude:a,maxFiles:l,signal:c,useRealPaths:u,pathSeparator:p},controller:f}=this.state;if(f.aborted||c&&c.aborted||l&&n.length>l)return;let g=this.getArray(this.state.paths);for(let d=0;d<e.length;++d){let m=e[d];if(m.isFile()||m.isSymbolicLink()&&!i&&!o){let w=this.joinPath(m.name,t);this.pushFile(w,g,this.state.counts,s);}else if(m.isDirectory()){let w=Hw(m.name,t,this.state.options.pathSeparator);if(a&&a(m.name,w))continue;this.pushDirectory(w,n,s),this.walkDirectory(this.state,w,w,r-1,this.walk);}else if(this.resolveSymlink&&m.isSymbolicLink()){let w=Ip(m.name,t);this.resolveSymlink(w,this.state,(h,S)=>{if(h.isDirectory()){if(S=zo(S,this.state.options),a&&a(m.name,u?S:w+p))return;this.walkDirectory(this.state,S,u?S:w+p,r-1,this.walk);}else {S=u?S:w;let T=basename(S),$=zo(dirname(S),this.state.options);S=this.joinPath(T,$),this.pushFile(S,g,this.state.counts,s);}});}}this.groupFiles(this.state.groups,t,g);}};Pp=class{constructor(e,t){this.root=e,this.options=t;}withPromise(){return Cb(this.root,this.options)}withCallback(e){Fp(this.root,this.options,e);}sync(){return Rb(this.root,this.options)}},Mp=null;try{kp.resolve("picomatch"),Mp=kp("picomatch");}catch{}Up=class{globCache={};options={maxDepth:1/0,suppressErrors:true,pathSeparator:sep,filters:[]};globFunction;constructor(e){this.options={...this.options,...e},this.globFunction=this.options.globFunction;}group(){return this.options.group=true,this}withPathSeparator(e){return this.options.pathSeparator=e,this}withBasePath(){return this.options.includeBasePath=true,this}withRelativePaths(){return this.options.relativePaths=true,this}withDirs(){return this.options.includeDirs=true,this}withMaxDepth(e){return this.options.maxDepth=e,this}withMaxFiles(e){return this.options.maxFiles=e,this}withFullPaths(){return this.options.resolvePaths=true,this.options.includeBasePath=true,this}withErrors(){return this.options.suppressErrors=false,this}withSymlinks({resolvePaths:e=true}={}){return this.options.resolveSymlinks=true,this.options.useRealPaths=e,this.withFullPaths()}withAbortSignal(e){return this.options.signal=e,this}normalize(){return this.options.normalizePath=true,this}filter(e){return this.options.filters.push(e),this}onlyDirs(){return this.options.excludeFiles=true,this.options.includeDirs=true,this}exclude(e){return this.options.exclude=e,this}onlyCounts(){return this.options.onlyCounts=true,this}crawl(e){return new Pp(e||".",this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new Pp(e||".",this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:true})}globWithOptions(e,...t){let r=this.globFunction||Mp;if(!r)throw new Error("Please specify a glob function to use glob matching.");var n=this.globCache[e.join("\0")];return n||(n=r(e,...t),this.globCache[e.join("\0")]=n),this.options.filters.push(s=>n(s)),this}};});var Mr=it((kC,zp)=>{var qp="[^\\\\/]",kb="(?=.)",Hp="[^/]",Ko="(?:\\/|$)",Wp="(?:^|\\/)",Jo=`\\.{1,2}${Ko}`,Pb="(?!\\.)",Nb=`(?!${Wp}${Jo})`,Ob=`(?!\\.{0,1}${Ko})`,Ib=`(?!${Jo})`,Lb="[^.\\/]",Db=`${Hp}*?`,jb="/",Gp={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:kb,QMARK:Hp,END_ANCHOR:Ko,DOTS_SLASH:Jo,NO_DOT:Pb,NO_DOTS:Nb,NO_DOT_SLASH:Ob,NO_DOTS_SLASH:Ib,QMARK_NO_DOT:Lb,STAR:Db,START_ANCHOR:Wp,SEP:jb},Fb={...Gp,SLASH_LITERAL:"[\\\\/]",QMARK:qp,STAR:`${qp}*?`,DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},Mb={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};zp.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:Mb,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(e){return {"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===true?Fb:Gp}};});var Ur=it(Ne=>{var{REGEX_BACKSLASH:Ub,REGEX_REMOVE_BACKSLASH:Bb,REGEX_SPECIAL_CHARS:qb,REGEX_SPECIAL_CHARS_GLOBAL:Hb}=Mr();Ne.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);Ne.hasRegexChars=e=>qb.test(e);Ne.isRegexChar=e=>e.length===1&&Ne.hasRegexChars(e);Ne.escapeRegex=e=>e.replace(Hb,"\\$1");Ne.toPosixSlashes=e=>e.replace(Ub,"/");Ne.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let e=navigator.platform.toLowerCase();return e==="win32"||e==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":false};Ne.removeBackslashes=e=>e.replace(Bb,t=>t==="\\"?"":t);Ne.escapeLast=(e,t,r)=>{let n=e.lastIndexOf(t,r);return n===-1?e:e[n-1]==="\\"?Ne.escapeLast(e,t,n-1):`${e.slice(0,n)}\\${e.slice(n)}`};Ne.removePrefix=(e,t={})=>{let r=e;return r.startsWith("./")&&(r=r.slice(2),t.prefix="./"),r};Ne.wrapOutput=(e,t={},r={})=>{let n=r.contains?"":"^",s=r.contains?"":"$",i=`${n}(?:${e})${s}`;return t.negated===true&&(i=`(?:^(?!${i}).*$)`),i};Ne.basename=(e,{windows:t}={})=>{let r=e.split(t?/[\\/]/:"/"),n=r[r.length-1];return n===""?r[r.length-2]:n};});var ef=it((NC,Zp)=>{var Vp=Ur(),{CHAR_ASTERISK:Xo,CHAR_AT:Wb,CHAR_BACKWARD_SLASH:Br,CHAR_COMMA:Gb,CHAR_DOT:Yo,CHAR_EXCLAMATION_MARK:Qo,CHAR_FORWARD_SLASH:Qp,CHAR_LEFT_CURLY_BRACE:Zo,CHAR_LEFT_PARENTHESES:ea,CHAR_LEFT_SQUARE_BRACKET:zb,CHAR_PLUS:Vb,CHAR_QUESTION_MARK:Kp,CHAR_RIGHT_CURLY_BRACE:Kb,CHAR_RIGHT_PARENTHESES:Jp,CHAR_RIGHT_SQUARE_BRACKET:Jb}=Mr(),Xp=e=>e===Qp||e===Br,Yp=e=>{e.isPrefix!==true&&(e.depth=e.isGlobstar?1/0:1);},Xb=(e,t)=>{let r=t||{},n=e.length-1,s=r.parts===true||r.scanToEnd===true,i=[],o=[],a=[],l=e,c=-1,u=0,p=0,f=false,g=false,d=false,m=false,w=false,h=false,S=false,T=false,$=false,P=false,N=0,v,_,I={value:"",depth:0,isGlob:false},b=()=>c>=n,D=()=>l.charCodeAt(c+1),R=()=>(v=_,l.charCodeAt(++c));for(;c<n;){_=R();let q;if(_===Br){S=I.backslashes=true,_=R(),_===Zo&&(h=true);continue}if(h===true||_===Zo){for(N++;b()!==true&&(_=R());){if(_===Br){S=I.backslashes=true,R();continue}if(_===Zo){N++;continue}if(h!==true&&_===Yo&&(_=R())===Yo){if(f=I.isBrace=true,d=I.isGlob=true,P=true,s===true)continue;break}if(h!==true&&_===Gb){if(f=I.isBrace=true,d=I.isGlob=true,P=true,s===true)continue;break}if(_===Kb&&(N--,N===0)){h=false,f=I.isBrace=true,P=true;break}}if(s===true)continue;break}if(_===Qp){if(i.push(c),o.push(I),I={value:"",depth:0,isGlob:false},P===true)continue;if(v===Yo&&c===u+1){u+=2;continue}p=c+1;continue}if(r.noext!==true&&(_===Vb||_===Wb||_===Xo||_===Kp||_===Qo)===true&&D()===ea){if(d=I.isGlob=true,m=I.isExtglob=true,P=true,_===Qo&&c===u&&($=true),s===true){for(;b()!==true&&(_=R());){if(_===Br){S=I.backslashes=true,_=R();continue}if(_===Jp){d=I.isGlob=true,P=true;break}}continue}break}if(_===Xo){if(v===Xo&&(w=I.isGlobstar=true),d=I.isGlob=true,P=true,s===true)continue;break}if(_===Kp){if(d=I.isGlob=true,P=true,s===true)continue;break}if(_===zb){for(;b()!==true&&(q=R());){if(q===Br){S=I.backslashes=true,R();continue}if(q===Jb){g=I.isBracket=true,d=I.isGlob=true,P=true;break}}if(s===true)continue;break}if(r.nonegate!==true&&_===Qo&&c===u){T=I.negated=true,u++;continue}if(r.noparen!==true&&_===ea){if(d=I.isGlob=true,s===true){for(;b()!==true&&(_=R());){if(_===ea){S=I.backslashes=true,_=R();continue}if(_===Jp){P=true;break}}continue}break}if(d===true){if(P=true,s===true)continue;break}}r.noext===true&&(m=false,d=false);let F=l,E="",x="";u>0&&(E=l.slice(0,u),l=l.slice(u),p-=u),F&&d===true&&p>0?(F=l.slice(0,p),x=l.slice(p)):d===true?(F="",x=l):F=l,F&&F!==""&&F!=="/"&&F!==l&&Xp(F.charCodeAt(F.length-1))&&(F=F.slice(0,-1)),r.unescape===true&&(x&&(x=Vp.removeBackslashes(x)),F&&S===true&&(F=Vp.removeBackslashes(F)));let X={prefix:E,input:e,start:u,base:F,glob:x,isBrace:f,isBracket:g,isGlob:d,isExtglob:m,isGlobstar:w,negated:T,negatedExtglob:$};if(r.tokens===true&&(X.maxDepth=0,Xp(_)||o.push(I),X.tokens=o),r.parts===true||r.tokens===true){let q;for(let j=0;j<i.length;j++){let se=q?q+1:u,ce=i[j],st=e.slice(se,ce);r.tokens&&(j===0&&u!==0?(o[j].isPrefix=true,o[j].value=E):o[j].value=st,Yp(o[j]),X.maxDepth+=o[j].depth),(j!==0||st!=="")&&a.push(st),q=ce;}if(q&&q+1<e.length){let j=e.slice(q+1);a.push(j),r.tokens&&(o[o.length-1].value=j,Yp(o[o.length-1]),X.maxDepth+=o[o.length-1].depth);}X.slashes=i,X.parts=a;}return X};Zp.exports=Xb;});var nf=it((OC,rf)=>{var vs=Mr(),Ve=Ur(),{MAX_LENGTH:Ts,POSIX_REGEX_SOURCE:Yb,REGEX_NON_SPECIAL_CHARS:Qb,REGEX_SPECIAL_CHARS_BACKREF:Zb,REPLACEMENTS:tf}=vs,eS=(e,t)=>{if(typeof t.expandRange=="function")return t.expandRange(...e,t);e.sort();let r=`[${e.join("-")}]`;try{new RegExp(r);}catch{return e.map(s=>Ve.escapeRegex(s)).join("..")}return r},Zt=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,ta=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=tf[e]||e;let r={...t},n=typeof r.maxLength=="number"?Math.min(Ts,r.maxLength):Ts,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);let i={type:"bos",value:"",output:r.prepend||""},o=[i],a=r.capture?"":"?:",l=vs.globChars(r.windows),c=vs.extglobChars(l),{DOT_LITERAL:u,PLUS_LITERAL:p,SLASH_LITERAL:f,ONE_CHAR:g,DOTS_SLASH:d,NO_DOT:m,NO_DOT_SLASH:w,NO_DOTS_SLASH:h,QMARK:S,QMARK_NO_DOT:T,STAR:$,START_ANCHOR:P}=l,N=O=>`(${a}(?:(?!${P}${O.dot?d:u}).)*?)`,v=r.dot?"":m,_=r.dot?S:T,I=r.bash===true?N(r):$;r.capture&&(I=`(${I})`),typeof r.noext=="boolean"&&(r.noextglob=r.noext);let b={input:e,index:-1,start:0,dot:r.dot===true,consumed:"",output:"",prefix:"",backtrack:false,negated:false,brackets:0,braces:0,parens:0,quotes:0,globstar:false,tokens:o};e=Ve.removePrefix(e,b),s=e.length;let D=[],R=[],F=[],E=i,x,X=()=>b.index===s-1,q=b.peek=(O=1)=>e[b.index+O],j=b.advance=()=>e[++b.index]||"",se=()=>e.slice(b.index+1),ce=(O="",re=0)=>{b.consumed+=O,b.index+=re;},st=O=>{b.output+=O.output!=null?O.output:O.value,ce(O.value);},Mh=()=>{let O=1;for(;q()==="!"&&(q(2)!=="("||q(3)==="?");)j(),b.start++,O++;return O%2===0?false:(b.negated=true,b.start++,true)},Nn=O=>{b[O]++,F.push(O);},yt=O=>{b[O]--,F.pop();},G=O=>{if(E.type==="globstar"){let re=b.braces>0&&(O.type==="comma"||O.type==="brace"),A=O.extglob===true||D.length&&(O.type==="pipe"||O.type==="paren");O.type!=="slash"&&O.type!=="paren"&&!re&&!A&&(b.output=b.output.slice(0,-E.output.length),E.type="star",E.value="*",E.output=I,b.output+=E.output);}if(D.length&&O.type!=="paren"&&(D[D.length-1].inner+=O.value),(O.value||O.output)&&st(O),E&&E.type==="text"&&O.type==="text"){E.output=(E.output||E.value)+O.value,E.value+=O.value;return}O.prev=E,o.push(O),E=O;},On=(O,re)=>{let A={...c[re],conditions:1,inner:""};A.prev=E,A.parens=b.parens,A.output=b.output;let W=(r.capture?"(":"")+A.open;Nn("parens"),G({type:O,value:re,output:b.output?"":g}),G({type:"paren",extglob:true,value:j(),output:W}),D.push(A);},Uh=O=>{let re=O.close+(r.capture?")":""),A;if(O.type==="negate"){let W=I;if(O.inner&&O.inner.length>1&&O.inner.includes("/")&&(W=N(r)),(W!==I||X()||/^\)+$/.test(se()))&&(re=O.close=`)$))${W}`),O.inner.includes("*")&&(A=se())&&/^\.[^\\/.]+$/.test(A)){let le=ta(A,{...t,fastpaths:false}).output;re=O.close=`)${le})${W})`;}O.prev.type==="bos"&&(b.negatedExtglob=true);}G({type:"paren",extglob:true,value:x,output:re}),yt("parens");};if(r.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let O=false,re=e.replace(Zb,(A,W,le,$e,me,Ri)=>$e==="\\"?(O=true,A):$e==="?"?W?W+$e+(me?S.repeat(me.length):""):Ri===0?_+(me?S.repeat(me.length):""):S.repeat(le.length):$e==="."?u.repeat(le.length):$e==="*"?W?W+$e+(me?I:""):I:W?A:`\\${A}`);return O===true&&(r.unescape===true?re=re.replace(/\\/g,""):re=re.replace(/\\+/g,A=>A.length%2===0?"\\\\":A?"\\":"")),re===e&&r.contains===true?(b.output=e,b):(b.output=Ve.wrapOutput(re,b,t),b)}for(;!X();){if(x=j(),x==="\0")continue;if(x==="\\"){let A=q();if(A==="/"&&r.bash!==true||A==="."||A===";")continue;if(!A){x+="\\",G({type:"text",value:x});continue}let W=/^\\+/.exec(se()),le=0;if(W&&W[0].length>2&&(le=W[0].length,b.index+=le,le%2!==0&&(x+="\\")),r.unescape===true?x=j():x+=j(),b.brackets===0){G({type:"text",value:x});continue}}if(b.brackets>0&&(x!=="]"||E.value==="["||E.value==="[^")){if(r.posix!==false&&x===":"){let A=E.value.slice(1);if(A.includes("[")&&(E.posix=true,A.includes(":"))){let W=E.value.lastIndexOf("["),le=E.value.slice(0,W),$e=E.value.slice(W+2),me=Yb[$e];if(me){E.value=le+me,b.backtrack=true,j(),!i.output&&o.indexOf(E)===1&&(i.output=g);continue}}}(x==="["&&q()!==":"||x==="-"&&q()==="]")&&(x=`\\${x}`),x==="]"&&(E.value==="["||E.value==="[^")&&(x=`\\${x}`),r.posix===true&&x==="!"&&E.value==="["&&(x="^"),E.value+=x,st({value:x});continue}if(b.quotes===1&&x!=='"'){x=Ve.escapeRegex(x),E.value+=x,st({value:x});continue}if(x==='"'){b.quotes=b.quotes===1?0:1,r.keepQuotes===true&&G({type:"text",value:x});continue}if(x==="("){Nn("parens"),G({type:"paren",value:x});continue}if(x===")"){if(b.parens===0&&r.strictBrackets===true)throw new SyntaxError(Zt("opening","("));let A=D[D.length-1];if(A&&b.parens===A.parens+1){Uh(D.pop());continue}G({type:"paren",value:x,output:b.parens?")":"\\)"}),yt("parens");continue}if(x==="["){if(r.nobracket===true||!se().includes("]")){if(r.nobracket!==true&&r.strictBrackets===true)throw new SyntaxError(Zt("closing","]"));x=`\\${x}`;}else Nn("brackets");G({type:"bracket",value:x});continue}if(x==="]"){if(r.nobracket===true||E&&E.type==="bracket"&&E.value.length===1){G({type:"text",value:x,output:`\\${x}`});continue}if(b.brackets===0){if(r.strictBrackets===true)throw new SyntaxError(Zt("opening","["));G({type:"text",value:x,output:`\\${x}`});continue}yt("brackets");let A=E.value.slice(1);if(E.posix!==true&&A[0]==="^"&&!A.includes("/")&&(x=`/${x}`),E.value+=x,st({value:x}),r.literalBrackets===false||Ve.hasRegexChars(A))continue;let W=Ve.escapeRegex(E.value);if(b.output=b.output.slice(0,-E.value.length),r.literalBrackets===true){b.output+=W,E.value=W;continue}E.value=`(${a}${W}|${E.value})`,b.output+=E.value;continue}if(x==="{"&&r.nobrace!==true){Nn("braces");let A={type:"brace",value:x,output:"(",outputIndex:b.output.length,tokensIndex:b.tokens.length};R.push(A),G(A);continue}if(x==="}"){let A=R[R.length-1];if(r.nobrace===true||!A){G({type:"text",value:x,output:x});continue}let W=")";if(A.dots===true){let le=o.slice(),$e=[];for(let me=le.length-1;me>=0&&(o.pop(),le[me].type!=="brace");me--)le[me].type!=="dots"&&$e.unshift(le[me].value);W=eS($e,r),b.backtrack=true;}if(A.comma!==true&&A.dots!==true){let le=b.output.slice(0,A.outputIndex),$e=b.tokens.slice(A.tokensIndex);A.value=A.output="\\{",x=W="\\}",b.output=le;for(let me of $e)b.output+=me.output||me.value;}G({type:"brace",value:x,output:W}),yt("braces"),R.pop();continue}if(x==="|"){D.length>0&&D[D.length-1].conditions++,G({type:"text",value:x});continue}if(x===","){let A=x,W=R[R.length-1];W&&F[F.length-1]==="braces"&&(W.comma=true,A="|"),G({type:"comma",value:x,output:A});continue}if(x==="/"){if(E.type==="dot"&&b.index===b.start+1){b.start=b.index+1,b.consumed="",b.output="",o.pop(),E=i;continue}G({type:"slash",value:x,output:f});continue}if(x==="."){if(b.braces>0&&E.type==="dot"){E.value==="."&&(E.output=u);let A=R[R.length-1];E.type="dots",E.output+=x,E.value+=x,A.dots=true;continue}if(b.braces+b.parens===0&&E.type!=="bos"&&E.type!=="slash"){G({type:"text",value:x,output:u});continue}G({type:"dot",value:x,output:u});continue}if(x==="?"){if(!(E&&E.value==="(")&&r.noextglob!==true&&q()==="("&&q(2)!=="?"){On("qmark",x);continue}if(E&&E.type==="paren"){let W=q(),le=x;(E.value==="("&&!/[!=<:]/.test(W)||W==="<"&&!/<([!=]|\w+>)/.test(se()))&&(le=`\\${x}`),G({type:"text",value:x,output:le});continue}if(r.dot!==true&&(E.type==="slash"||E.type==="bos")){G({type:"qmark",value:x,output:T});continue}G({type:"qmark",value:x,output:S});continue}if(x==="!"){if(r.noextglob!==true&&q()==="("&&(q(2)!=="?"||!/[!=<:]/.test(q(3)))){On("negate",x);continue}if(r.nonegate!==true&&b.index===0){Mh();continue}}if(x==="+"){if(r.noextglob!==true&&q()==="("&&q(2)!=="?"){On("plus",x);continue}if(E&&E.value==="("||r.regex===false){G({type:"plus",value:x,output:p});continue}if(E&&(E.type==="bracket"||E.type==="paren"||E.type==="brace")||b.parens>0){G({type:"plus",value:x});continue}G({type:"plus",value:p});continue}if(x==="@"){if(r.noextglob!==true&&q()==="("&&q(2)!=="?"){G({type:"at",extglob:true,value:x,output:""});continue}G({type:"text",value:x});continue}if(x!=="*"){(x==="$"||x==="^")&&(x=`\\${x}`);let A=Qb.exec(se());A&&(x+=A[0],b.index+=A[0].length),G({type:"text",value:x});continue}if(E&&(E.type==="globstar"||E.star===true)){E.type="star",E.star=true,E.value+=x,E.output=I,b.backtrack=true,b.globstar=true,ce(x);continue}let O=se();if(r.noextglob!==true&&/^\([^?]/.test(O)){On("star",x);continue}if(E.type==="star"){if(r.noglobstar===true){ce(x);continue}let A=E.prev,W=A.prev,le=A.type==="slash"||A.type==="bos",$e=W&&(W.type==="star"||W.type==="globstar");if(r.bash===true&&(!le||O[0]&&O[0]!=="/")){G({type:"star",value:x,output:""});continue}let me=b.braces>0&&(A.type==="comma"||A.type==="brace"),Ri=D.length&&(A.type==="pipe"||A.type==="paren");if(!le&&A.type!=="paren"&&!me&&!Ri){G({type:"star",value:x,output:""});continue}for(;O.slice(0,3)==="/**";){let In=e[b.index+4];if(In&&In!=="/")break;O=O.slice(3),ce("/**",3);}if(A.type==="bos"&&X()){E.type="globstar",E.value+=x,E.output=N(r),b.output=E.output,b.globstar=true,ce(x);continue}if(A.type==="slash"&&A.prev.type!=="bos"&&!$e&&X()){b.output=b.output.slice(0,-(A.output+E.output).length),A.output=`(?:${A.output}`,E.type="globstar",E.output=N(r)+(r.strictSlashes?")":"|$)"),E.value+=x,b.globstar=true,b.output+=A.output+E.output,ce(x);continue}if(A.type==="slash"&&A.prev.type!=="bos"&&O[0]==="/"){let In=O[1]!==void 0?"|$":"";b.output=b.output.slice(0,-(A.output+E.output).length),A.output=`(?:${A.output}`,E.type="globstar",E.output=`${N(r)}${f}|${f}${In})`,E.value+=x,b.output+=A.output+E.output,b.globstar=true,ce(x+j()),G({type:"slash",value:"/",output:""});continue}if(A.type==="bos"&&O[0]==="/"){E.type="globstar",E.value+=x,E.output=`(?:^|${f}|${N(r)}${f})`,b.output=E.output,b.globstar=true,ce(x+j()),G({type:"slash",value:"/",output:""});continue}b.output=b.output.slice(0,-E.output.length),E.type="globstar",E.output=N(r),E.value+=x,b.output+=E.output,b.globstar=true,ce(x);continue}let re={type:"star",value:x,output:I};if(r.bash===true){re.output=".*?",(E.type==="bos"||E.type==="slash")&&(re.output=v+re.output),G(re);continue}if(E&&(E.type==="bracket"||E.type==="paren")&&r.regex===true){re.output=x,G(re);continue}(b.index===b.start||E.type==="slash"||E.type==="dot")&&(E.type==="dot"?(b.output+=w,E.output+=w):r.dot===true?(b.output+=h,E.output+=h):(b.output+=v,E.output+=v),q()!=="*"&&(b.output+=g,E.output+=g)),G(re);}for(;b.brackets>0;){if(r.strictBrackets===true)throw new SyntaxError(Zt("closing","]"));b.output=Ve.escapeLast(b.output,"["),yt("brackets");}for(;b.parens>0;){if(r.strictBrackets===true)throw new SyntaxError(Zt("closing",")"));b.output=Ve.escapeLast(b.output,"("),yt("parens");}for(;b.braces>0;){if(r.strictBrackets===true)throw new SyntaxError(Zt("closing","}"));b.output=Ve.escapeLast(b.output,"{"),yt("braces");}if(r.strictSlashes!==true&&(E.type==="star"||E.type==="bracket")&&G({type:"maybe_slash",value:"",output:`${f}?`}),b.backtrack===true){b.output="";for(let O of b.tokens)b.output+=O.output!=null?O.output:O.value,O.suffix&&(b.output+=O.suffix);}return b};ta.fastpaths=(e,t)=>{let r={...t},n=typeof r.maxLength=="number"?Math.min(Ts,r.maxLength):Ts,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);e=tf[e]||e;let{DOT_LITERAL:i,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:l,NO_DOT:c,NO_DOTS:u,NO_DOTS_SLASH:p,STAR:f,START_ANCHOR:g}=vs.globChars(r.windows),d=r.dot?u:c,m=r.dot?p:c,w=r.capture?"":"?:",h={negated:false,prefix:""},S=r.bash===true?".*?":f;r.capture&&(S=`(${S})`);let T=v=>v.noglobstar===true?S:`(${w}(?:(?!${g}${v.dot?l:i}).)*?)`,$=v=>{switch(v){case "*":return `${d}${a}${S}`;case ".*":return `${i}${a}${S}`;case "*.*":return `${d}${S}${i}${a}${S}`;case "*/*":return `${d}${S}${o}${a}${m}${S}`;case "**":return d+T(r);case "**/*":return `(?:${d}${T(r)}${o})?${m}${a}${S}`;case "**/*.*":return `(?:${d}${T(r)}${o})?${m}${S}${i}${a}${S}`;case "**/.*":return `(?:${d}${T(r)}${o})?${i}${a}${S}`;default:{let _=/^(.*?)\.(\w+)$/.exec(v);if(!_)return;let I=$(_[1]);return I?I+i+_[2]:void 0}}},P=Ve.removePrefix(e,h),N=$(P);return N&&r.strictSlashes!==true&&(N+=`${o}?`),N};rf.exports=ta;});var af=it((IC,of)=>{var tS=ef(),ra=nf(),sf=Ur(),rS=Mr(),nS=e=>e&&typeof e=="object"&&!Array.isArray(e),ue=(e,t,r=false)=>{if(Array.isArray(e)){let u=e.map(f=>ue(f,t,r));return f=>{for(let g of u){let d=g(f);if(d)return d}return false}}let n=nS(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let s=t||{},i=s.windows,o=n?ue.compileRe(e,t):ue.makeRe(e,t,false,true),a=o.state;delete o.state;let l=()=>false;if(s.ignore){let u={...t,ignore:null,onMatch:null,onResult:null};l=ue(s.ignore,u,r);}let c=(u,p=false)=>{let{isMatch:f,match:g,output:d}=ue.test(u,o,t,{glob:e,posix:i}),m={glob:e,state:a,regex:o,posix:i,input:u,output:d,match:g,isMatch:f};return typeof s.onResult=="function"&&s.onResult(m),f===false?(m.isMatch=false,p?m:false):l(u)?(typeof s.onIgnore=="function"&&s.onIgnore(m),m.isMatch=false,p?m:false):(typeof s.onMatch=="function"&&s.onMatch(m),p?m:true)};return r&&(c.state=a),c};ue.test=(e,t,r,{glob:n,posix:s}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return {isMatch:false,output:""};let i=r||{},o=i.format||(s?sf.toPosixSlashes:null),a=e===n,l=a&&o?o(e):e;return a===false&&(l=o?o(e):e,a=l===n),(a===false||i.capture===true)&&(i.matchBase===true||i.basename===true?a=ue.matchBase(e,t,r,s):a=t.exec(l)),{isMatch:!!a,match:a,output:l}};ue.matchBase=(e,t,r)=>(t instanceof RegExp?t:ue.makeRe(t,r)).test(sf.basename(e));ue.isMatch=(e,t,r)=>ue(t,r)(e);ue.parse=(e,t)=>Array.isArray(e)?e.map(r=>ue.parse(r,t)):ra(e,{...t,fastpaths:false});ue.scan=(e,t)=>tS(e,t);ue.compileRe=(e,t,r=false,n=false)=>{if(r===true)return e.output;let s=t||{},i=s.contains?"":"^",o=s.contains?"":"$",a=`${i}(?:${e.output})${o}`;e&&e.negated===true&&(a=`^(?!${a}).*$`);let l=ue.toRegex(a,t);return n===true&&(l.state=e),l};ue.makeRe=(e,t={},r=false,n=false)=>{if(!e||typeof e!="string")throw new TypeError("Expected a non-empty string");let s={negated:false,fastpaths:true};return t.fastpaths!==false&&(e[0]==="."||e[0]==="*")&&(s.output=ra.fastpaths(e,t)),s.output||(s=ra(e,t)),ue.compileRe(s,t,r,n)};ue.toRegex=(e,t)=>{try{let r=t||{};return new RegExp(e,r.flags||(r.nocase?"i":""))}catch(r){if(t&&t.debug===true)throw r;return /$^/}};ue.constants=rS;of.exports=ue;});var pf=it((LC,uf)=>{var lf=af(),sS=Ur();function cf(e,t,r=false){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:sS.isWindows()}),lf(e,t,r)}Object.assign(cf,lf);uf.exports=cf;});function lS(e,t={}){let r=e.length,n=Array(r),s=Array(r),i=!t.noglobstar;for(let o=0;o<r;o++){let a=hf(e[o]);n[o]=a;let l=a.length,c=Array(l);for(let u=0;u<l;u++)c[u]=(0, rr.default)(a[u],t);s[o]=c;}return o=>{let a=o.split("/");if(a[0]===".."&&aS.test(o))return true;for(let l=0;l<e.length;l++){let c=n[l],u=s[l],p=a.length,f=Math.min(p,c.length),g=0;for(;g<f;){let d=c[g];if(d.includes("/"))return true;if(!u[g](a[g]))break;if(i&&d==="**")return true;g++;}if(g===p)return true}return false}}function ff(e,t,r){if(e===t||t.startsWith(`${e}/`)){if(r){let s=uS(e)?e.length:e.length+1;return (i,o)=>i.slice(s,o?-1:void 0)||"."}let n=t.slice(e.length+1);return n?(s,i)=>{if(s===".")return n;let o=`${n}/${s}`;return i?o.slice(0,-1):o}:(s,i)=>i&&s!=="."?s.slice(0,-1):s}return r?n=>posix.relative(e,n)||".":n=>posix.relative(e,`${t}/${n}`)||"."}function pS(e,t){if(t.startsWith(`${e}/`)){let r=t.slice(e.length+1);return n=>`${r}/${n}`}return r=>{let n=posix.relative(e,`${t}/${r}`);return r.endsWith("/")&&n!==""?`${n}/`:n||"."}}function hf(e){var t;let r=rr.default.scan(e,fS);return !((t=r.parts)===null||t===void 0)&&t.length?r.parts:[e]}function wS(e,t){let r=rr.default.scan(e);return r.isGlob||r.negated}function tr(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...e);}function na(e,t,r,n,s){let i=e;e.endsWith("/")&&(i=e.slice(0,-1)),!i.endsWith("*")&&t&&(i+="/**");let o=yS(r);mf.isAbsolute(i.replace(SS,""))?i=posix.relative(o,i):i=posix.normalize(i);let a=bS.exec(i),l=hf(i);if(a?.[0]){let u=(a[0].length+1)/3,p=0,f=o.split("/");for(;p<u&&l[p+u]===f[f.length+p-u];)i=i.slice(0,(u-p-1)*3)+i.slice((u-p)*3+l[p+u].length+1)||".",p++;let g=posix.join(r,a[0].slice(p*3));!g.startsWith(".")&&n.root.length>g.length&&(n.root=g,n.depthOffset=-u+p);}if(!s&&n.depthOffset>=0){var c;(c=n.commonPath)!==null&&c!==void 0||(n.commonPath=l);let u=[],p=Math.min(n.commonPath.length,l.length);for(let f=0;f<p;f++){let g=l[f];if(g==="**"&&!l[f+1]){u.pop();break}if(g!==n.commonPath[f]||wS(g)||f===l.length-1)break;u.push(g);}n.depthOffset=u.length,n.commonPath=u,n.root=u.length>0?posix.join(r,...u):r;}return i}function ES({patterns:e=["**/*"],ignore:t=[],expandDirectories:r=true},n,s){typeof e=="string"&&(e=[e]),typeof t=="string"&&(t=[t]);let i=[],o=[];for(let a of t)a&&(a[0]!=="!"||a[1]==="(")&&o.push(na(a,r,n,s,true));for(let a of e)a&&(a[0]!=="!"||a[1]==="("?i.push(na(a,r,n,s,false)):(a[1]!=="!"||a[2]==="(")&&o.push(na(a.slice(1),r,n,s,true)));return {match:i,ignore:o}}function xS(e,t){for(let r=e.length-1;r>=0;r--){let n=e[r];e[r]=t(n);}return e}function _S(e){return e?e instanceof URL?fileURLToPath$1(e).replace(As,"/"):mf.resolve(e).replace(As,"/"):process.cwd().replace(As,"/")}function $S(e,t={}){let r=process.env.TINYGLOBBY_DEBUG?{...t,debug:true}:t,n=_S(r.cwd);if(r.debug&&tr("globbing with:",{patterns:e,options:r,cwd:n}),Array.isArray(e)&&e.length===0)return [{sync:()=>[],withPromise:async()=>[]},false];let s={root:n,commonPath:null,depthOffset:0},i=ES({...r,patterns:e},n,s);r.debug&&tr("internal processing patterns:",i);let o={dot:r.dot,nobrace:r.braceExpansion===false,nocase:r.caseSensitiveMatch===false,noextglob:r.extglob===false,noglobstar:r.globstar===false,posix:true},a=(0, rr.default)(i.match,{...o,ignore:i.ignore}),l=(0, rr.default)(i.ignore,o),c=lS(i.match,o),u=ff(n,s.root,r.absolute),p=r.absolute?u:ff(n,s.root,true),f={filters:[r.debug?(m,w)=>{let h=u(m,w),S=a(h);return S&&tr(`matched ${h}`),S}:(m,w)=>a(u(m,w))],exclude:r.debug?(m,w)=>{let h=p(w,true),S=h!=="."&&!c(h)||l(h);return tr(S?`skipped ${w}`:`crawling ${w}`),S}:(m,w)=>{let h=p(w,true);return h!=="."&&!c(h)||l(h)},fs:r.fs?{readdir:r.fs.readdir||er__default.readdir,readdirSync:r.fs.readdirSync||er__default.readdirSync,realpath:r.fs.realpath||er__default.realpath,realpathSync:r.fs.realpathSync||er__default.realpathSync,stat:r.fs.stat||er__default.stat,statSync:r.fs.statSync||er__default.statSync}:void 0,pathSeparator:"/",relativePaths:true,resolveSymlinks:true,signal:r.signal};r.deep!==void 0&&(f.maxDepth=Math.round(r.deep-s.depthOffset)),r.absolute&&(f.relativePaths=false,f.resolvePaths=true,f.includeBasePath=true),r.followSymbolicLinks===false&&(f.resolveSymlinks=false,f.excludeSymlinks=true),r.onlyDirectories?(f.excludeFiles=true,f.includeDirs=true):r.onlyFiles===false&&(f.includeDirs=true),s.root=s.root.replace(As,"");let g=s.root;r.debug&&tr("internal properties:",s);let d=n!==g&&!r.absolute&&pS(n,s.root);return [new Up(f).crawl(g),d]}async function qr(e,t){if(e&&t?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let r=oS(e)||typeof e=="string",n=r?t:e,s=r?e:e.patterns,[i,o]=$S(s,n);return o?xS(await i.withPromise(),o):i.withPromise()}var rr,oS,df,aS,cS,uS,fS,mS,dS,hS,gS,yS,bS,SS,As,sa=y(()=>{Bp();rr=ee(pf()),oS=Array.isArray,df=process.platform==="win32",aS=/^(\/?\.\.)+$/;cS=/^[A-Z]:\/$/i,uS=df?e=>cS.test(e):e=>e==="/";fS={parts:true};mS=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,dS=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,hS=e=>e.replace(mS,"\\$&"),gS=e=>e.replace(dS,"\\$&"),yS=df?gS:hS;bS=/^(\/?\.\.)+/,SS=/\\(?=[()[\]{}!*+?@|])/g,As=/\\/g;});function nr(e){return e.dialect==="postgres"?"pg":e.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function gf(e){return e==="sqlite"?{schema_migrations:"migrations",seed_files:null}:e==="pg-flat"?{schema_migrations:'"supabase_migrations.schema_migrations"',seed_files:'"supabase_migrations.seed_files"'}:{schema_migrations:"supabase_migrations.schema_migrations",seed_files:"supabase_migrations.seed_files"}}function ia(e){return `'${e.replace(/'/g,"''")}'`}function vS(e){return `'${`{${e.map(n=>`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function TS(e){return e==="sqlite"?[`CREATE TABLE IF NOT EXISTS migrations (
|
|
60
|
+
`)}function Xt(e){let t=[],r="",n=0,s=e.length,i=false,o=false,a=0,l=/^create(\s+or\s+replace)?(\s+temp(orary)?)?$/i,c=p=>{Cc(p).length>0&&t.push(p.trim());},u=()=>{i=false,o=false,a=0;};for(;n<s;){let p=e[n],f=e[n+1];if(p==="-"&&f==="-"){for(;n<s&&e[n]!==`
|
|
61
|
+
`;)r+=e[n],n++;continue}if(p==="/"&&f==="*"){for(r+="/*",n+=2;n<s&&!(e[n]==="*"&&e[n+1]==="/");)r+=e[n],n++;n<s&&(r+="*/",n+=2);continue}if(p==="'"){for(r+=p,n++;n<s;){if(e[n]==="'"&&e[n+1]==="'"){r+="''",n+=2;continue}if(r+=e[n],e[n]==="'"){n++;break}n++;}continue}if(p==='"'){for(r+=p,n++;n<s;){if(e[n]==='"'&&e[n+1]==='"'){r+='""',n+=2;continue}if(r+=e[n],e[n]==='"'){n++;break}n++;}continue}if(p==="$"){let g=e.indexOf("$",n+1);if(g!==-1){let d=e.slice(n,g+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(d)){r+=d,n=g+1;let y=e.indexOf(d,n);y===-1?(r+=e.slice(n),n=s):(r+=e.slice(n,y+d.length),n=y+d.length);continue}}}if(/[A-Za-z_]/.test(p)){let g=n;for(;g<s&&/[A-Za-z0-9_]/.test(e[g]);)g++;let d=e.slice(n,g),m=d.toLowerCase();if(m==="trigger"&&l.test(Cc(r))?i=true:i&&m==="begin"?(o=true,a++):i&&o&&m==="case"?a++:i&&o&&m==="end"&&a>0&&a--,r+=d,n=g,i&&o&&a===0){let y=n;for(;y<s&&/\s/.test(e[y]);)y++;e[y]===";"&&(n=y+1),c(r),r="",u();}continue}if(p===";"){if(i&&o&&a>0){r+=p,n++;continue}c(r),r="",u(),n++;continue}r+=p,n++;}return c(r),t}function Cc(e){let t="",r=0,n=e.length;for(;r<n;){let s=e[r],i=e[r+1];if(s==="-"&&i==="-"){for(;r<n&&e[r]!==`
|
|
62
|
+
`;)r++;continue}if(s==="/"&&i==="*"){for(r+=2;r<n&&!(e[r]==="*"&&e[r+1]==="/");)r++;r+=2;continue}t+=s,r++;}return t.trim()}function Qi(e){return (e??"").trim().toLowerCase()}function Zi(e){return (e??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase()}function eo(e){if(e==null)return null;let t=e.trim();for(;t.startsWith("(")&&t.endsWith(")");)t=t.slice(1,-1).trim();return (t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"'))&&(t=t.slice(1,-1)),t}var Jt=w(()=>{});function Ng(e,t,r=void 0){let n=typeof t=="string"?Oc(t):no(t);return rs(e,n,r)}function rs(e,t,r=void 0){let n=typeof t=="string"?t.split(/[.\[\]\"]+/).filter(s=>s):t;if(n.length===0)return e;try{let[s,...i]=n;return !s||!(s in e)?r:rs(e[s],i,r)}catch{if(typeof r<"u")return r;throw new Error(`Invalid path: ${n.join(".")}`)}}function Lg(e){return e===null}function he(e){return !Array.isArray(e)&&typeof e=="object"&&e!==null}function Dg(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ke(e){return typeof e=="string"}function Qe(e){return typeof e=="number"}function jg(e){return typeof e=="number"&&Number.isInteger(e)}function oo(e){return typeof e=="boolean"}function at(e){return Array.isArray(e)}function Fg(e){return typeof e!="boolean"}function Mg(e){return e!==void 0&&Fg(e)&&"type"in e}function Ae(e){return e!==void 0&&he(e)&&Te in e}function Ug(e){return Ae(e)&&typeof e.toJSON()=="boolean"}function Bg(e,t,r){if(!e)throw new Ig(t,r)}function Ic(e){return Ke(e)?e.normalize("NFC"):e}function Rr(e,t){let r=typeof e;if(r!==typeof t)return false;if(Array.isArray(e)){if(!Array.isArray(t))return false;let n=e.length;if(n!==t.length)return false;for(let s=0;s<n;s++)if(!Rr(e[s],t[s]))return false;return true}if(r==="object"){if(!e||!t)return e===t;let n=Object.keys(e),s=Object.keys(t);if(n.length!==s.length)return false;for(let i of n)if(!Rr(e[i],t[i]))return false;return true}return e===t}function qg(e,t){return t.reduce((r,n)=>(n in e&&(r[n]=e[n]),r),{})}function Lc(e){try{return structuredClone(e)}catch{return e}}function Hg(e,t,r={}){let n=t;try{n=structuredClone(t);}catch{n=JSON.parse(JSON.stringify(t));}let s={resolver:r.resolver||new ao(e),depth:r.depth||0,dropUnknown:r.dropUnknown??false};return s.resolver.hasRef(e,n)?s.resolver.resolve(e.$ref).coerce(n,{...s,depth:s.depth+1}):n}function ns(e,t,r={}){return e.map(n=>n.validate(t,ts(r)).valid?n:void 0).filter(Boolean)}function xy(e,t,r={}){let n={keywordPath:r.keywordPath||[],instancePath:r.instancePath||[],coerce:r.coerce||false,errors:r.errors||[],shortCircuit:r.shortCircuit||false,ignoreUnsupported:r.ignoreUnsupported||false,resolver:r.resolver||e.getResolver?.()||new ao(e),depth:r.depth?r.depth+1:0,skipClone:r.skipClone||false},s;if(r?.coerce&&e.coerce){let i=e.coerce(t,{resolver:n.resolver,depth:n.depth});s=n.skipClone?i:structuredClone(i);}else s=n.skipClone?t:structuredClone(t);if(r.ignoreUnsupported!==true){let i=["$defs"];for(let o of i)if(e[o])throw new Error(`${o} not implemented`)}if(n.resolver.hasRef(e,s)){let i=n.resolver.resolve(e.$ref).validate(s,{...n,errors:[]});i.valid||n.errors.push(...i.errors);}else {let i={keywordPath:n.keywordPath,instancePath:n.instancePath,coerce:n.coerce,errors:[],shortCircuit:n.shortCircuit,ignoreUnsupported:n.ignoreUnsupported,resolver:n.resolver,depth:n.depth};for(let o in e)if(o==="type"&&e.type!==void 0){if(s!==void 0){let a=to[o];if(a){i.errors=[];let l=a(e,s,i);if(!l.valid){if(r.shortCircuit)return l;n.errors.push(...l.errors);}}}}else if(o in to&&e[o]!==void 0){if(s===void 0)continue;let a=to[o];if(a){i.errors=[];let l=a(e,s,i);if(!l.valid){if(r.shortCircuit)return l;n.errors.push(...l.errors);}}}}return {valid:n.errors.length===0,errors:n.errors}}function ss(e,t,r){return new class extends Ze{type=e}(t,r)}function so(e){return new _y(e)}function Pc(e,t){return Array.isArray(e)?e.map(t):e!==void 0?[t(e)]:[]}function Nc(e,t,r=n=>n){return Object.fromEntries(Object.entries(e).map(([n,s])=>[n,r(t(s,n),n)]))}function Yt(e){if(oo(e))return so(e);let t=structuredClone(e);if(!he(t))throw new Og("non-object schemas cannot be converted to a schema",t);"properties"in t&&t.properties&&(t.properties=Nc(t.properties,(i,o)=>{try{return Yt(i)}catch(a){throw new Error(`Couldn't schemaize property "${o}": ${String(a)}`)}},(i,o)=>"required"in t&&Array.isArray(t.required)&&t.required.includes(o)?i:i.optional()));let r=["patternProperties","dependentSchemas","$defs"];for(let i of r)i in t&&t[i]&&(t[i]=Nc(t[i],Yt));let n=["additionalProperties","items","prefixItems","propertyNames","contains","not","if","then","else"];for(let i of n)i in t&&typeof t[i]<"u"&&(at(t[i])?t[i]=Pc(t[i],Yt):t[i]=Yt(t[i]));let s=["anyOf","oneOf","allOf"];for(let i of s)if(i in t){let{[i]:o}=t;t[i]=Pc(o,Yt);}if(Mg(t))switch(t.type){case "string":return jc(t);case "number":return Mc(t);case "integer":return Uc(t);case "boolean":return qc(t);case "object":{let{properties:i,...o}=t;return is(i,o)}case "array":{let{items:i,...o}=t;return Bc(i,o)}}return Dc(t)}function Dy(){return {type(e){let t=e.map(r=>Array.isArray(r)?new Set(r):new Set([r])).reduce((r,n)=>r?new Set([...r].filter(s=>n.has(s))):new Set(n));if(!t.size)throw new Error('Incompatible "type" in allOf');return t.size===1?[...t][0]:[...t]},enum(e){let t=e.map(r=>new Set(r)).reduce((r,n)=>new Set([...r].filter(s=>n.has(s))));if(!t.size)throw new Error('Incompatible "enum" in allOf');return [...t]},required(e){return [...new Set(e.flat())]},properties(e,t,r){return e.reduce((n,s)=>r(n,s),{})},patternProperties(e,t,r){return e.reduce((n,s)=>r(n,s),{})},$defs(e,t,r){return e.reduce((n,s)=>r(n,s),{})},definitions(e,t,r){return e.reduce((n,s)=>r(n,s),{})},...Object.fromEntries(Iy.map(e=>[e,t=>Math.min(...t)])),...Object.fromEntries(Ly.map(e=>[e,t=>Math.max(...t)]))}}function jy(e){let t={...Dy(),...e.resolvers};function r(n,s){if(Array.isArray(n)&&Array.isArray(s))return [...new Set([...n,...s])];if(io(n)&&io(s)){let i={...n};for(let[o,a]of Object.entries(s))if(o in i){let l=t[o];i[o]=l?l([i[o],a],o,r):ro(a);}else i[o]=ro(a);return i}return ro(s)}return r}function My(e,t={}){let r=t.deep!==false,n=jy(t);function s(i){if(Array.isArray(i))return i.map(s);if(!io(i))return i;if(Array.isArray(i.allOf)){let a=i.allOf.map(s);if(a.some(g=>g===false))return false;let l=a.filter(g=>g!==true);if(!l.length)return true;let c=l.reduce((g,d)=>n(g,d),{}),u=Fy(c);if(u!==null)return u;let p={...i};delete p.allOf;let f=n(c,r?s(p):p);return r?s(f):f}let o={};for(let[a,l]of Object.entries(i))o[a]=s(l);return o}return s(e)}var no,Oc,Q,L,Qt,ts,vt,Og,Ig,Te,ao,Wg,Gg,zg,Vg,Kg,Xg,Jg,Yg,Qg,Zg,ey,ty,ry,ny,sy,iy,oy,ay,ly,cy,uy,py,fy,my,dy,hy,gy,yy,wy,by,Sy,kc,Ey,to,Ze,kr,_y,Dc,$y,vy,is,Ty,Ay,Cy,Ry,ky,jc,Fc,Mc,Uc,Py,Bc,qc,es,Hc,Ny,Oy,io,ro,Iy,Ly,Fy,Uy,Wc,By,qy,Hy,Gc,zc=w(()=>{no=(e=[],t="")=>"/"+[t,...e.map(r=>String(r).replace(/\./g,"/"))].filter(Boolean).join("/"),Oc=e=>e.split("/").slice(1);Q=(e={},t,r,n)=>({valid:false,errors:[...e.errors??[],{keywordLocation:no([...e.keywordPath??[],t]),instanceLocation:no(e.instancePath),error:typeof r=="string"?r:`Invalid value for ${t}`,data:n}]}),L=()=>({valid:true,errors:[]}),Qt=(e,t,r)=>{let n=Array.isArray(t)?t:[t],s=r?Array.isArray(r)?r:[r]:[];return {...e,keywordPath:[...e.keywordPath??[],...n],instancePath:s?[...e.instancePath??[],...s]:e.instancePath}},ts=(e={})=>({...e,errors:[]}),vt=class extends Error{constructor(e){super(`Expected ${e}`);}},Og=class extends Error{constructor(e,t){super(`${e??"Invalid raw schema"}: ${JSON.stringify(t)}`),this.schema=t;}},Ig=class extends Error{constructor(e,t){super(`${e}, got: 'type "${typeof t}": ${JSON.stringify(t)}'`),this.value=t;}},Te=Symbol.for("jsonv-ts:schema");ao=class{constructor(e){this.root=e,this.cache=new Map;}cache;hasRef(e,t){return t!==void 0&&"$ref"in e&&Ke(e.$ref)}resolve(e){let t=this.cache.get(e);if(!t){if(t=Ng(this.root,e),!Ae(t))throw new Error(`ref not found: ${e}`);if("$ref"in t&&t.$ref===e)throw new Error(`ref loop: ${e}`);this.cache.set(e,t);}return t}};Wg=({type:e},t,r={})=>{if(e===void 0||t===void 0)return L();let n,s={string:Ke,number:Qe,integer:jg,object:he,array:at,boolean:oo,null:Lg};if(Array.isArray(e)){for(let i of e){if(!(i in s))throw new vt(`Unknown type: ${i}`);if(s[i](t))return L()}n=`Expected one of: ${e.join(", ")}`;}else {if(!(e in s))throw new vt(`Unknown type: ${e}`);s[e](t)||(n=`Expected ${e}`);}return n?Q(r,"type",n,t):L()},Gg=({const:e},t,r={})=>Rr(e,t)?L():Q(r,"const",`Expected const: ${e}`,t),zg=({enum:e=[]},t,r={})=>e.some(n=>Rr(n,t))?L():Q(r,"enum",`Expected enum: ${JSON.stringify(e)}`,t);Vg=({anyOf:e=[]},t,r={})=>ns(e,t,r).length>0?L():Q(r,"anyOf","Expected at least one to match",t),Kg=({oneOf:e=[]},t,r={})=>ns(e,t).length===1?L():Q(r,"oneOf","Expected exactly one to match",t),Xg=({allOf:e=[]},t,r={})=>ns(e,t,r).length===e.length?L():Q(r,"allOf","Expected all to match",t),Jg=({not:e},t,r={})=>t===void 0?L():Ae(e)&&e.validate(t,r).valid?Q(r,"not","Expected not to match",t):L(),Yg=({if:e,then:t,else:r},n,s={})=>{if(e&&(t||r)){if(e.validate(n,ts(s)).valid)return t?t.validate(n,ts(s)):L();if(r)return r.validate(n,ts(s))}return L()},Qg=({pattern:e=""},t,r={})=>{if(!Ke(t))return L();if(e instanceof RegExp){if(e.test(t))return L()}else if(new RegExp(e,"u").test(t))return L();return Q(r,"pattern",`Expected string matching pattern ${e}`,t)},Zg=({minLength:e=0},t,r={})=>Ke(t)?[...Ic(t)].length>=e?L():Q(r,"minLength",`Expected string with minimum length of ${e}`,t):L(),ey=({maxLength:e=0},t,r={})=>Ke(t)?[...Ic(t)].length<=e?L():Q(r,"maxLength",`Expected string with maximum length of ${e}`,t):L(),ty=({multipleOf:e=0},t,r={})=>{if(!Qe(t))return L();if(!(Number.isFinite(t)&&Number.isFinite(e))||e<=0)throw new vt("number");let n=t/e,s=Number.EPSILON*Math.max(1,Math.abs(n));return Math.abs(n-Math.round(n))<=s?L():Q(r,"multipleOf",`Expected number being a multiple of ${e}`,t)},ry=({maximum:e=0},t,r={})=>!Qe(t)||t<=e?L():Q(r,"maximum",`Expected number less than or equal to ${e}`,t),ny=({exclusiveMaximum:e=0},t,r={})=>!Qe(t)||t<e?L():Q(r,"exclusiveMaximum",`Expected number less than ${e}`,t),sy=({minimum:e=0},t,r={})=>!Qe(t)||t>=e?L():Q(r,"minimum",`Expected number greater than or equal to ${e}`,t),iy=({exclusiveMinimum:e=0},t,r={})=>!Qe(t)||t>e?L():Q(r,"exclusiveMinimum",`Expected number greater than ${e}`,t),oy=({properties:e={}},t,r={})=>{if(!he(t))return L();for(let[n,s]of Object.entries(t)){let i=e[n];if(!Ae(i))continue;let o=i.validate(s,Qt(r,["properties",n],n));if(!o.valid)return o}return L()},ay=({properties:e={},additionalProperties:t,patternProperties:r},n,s={})=>{if(!he(n))return L();if(!Ae(t))throw new vt("additionalProperties must be a boolean or a managed schema");let i=Object.keys(e),o=he(r)?Object.keys(n).filter(l=>Object.keys(r).some(c=>new RegExp(c).test(l))):[],a=Object.keys(n).filter(l=>!i.includes(l)&&!o.includes(l));if(a.length>0){if(Ug(t)){if(t.toJSON()===true)return L();let l=a.reduce((c,u)=>(c[u]=n[u],c),{});return Q(s,"additionalProperties","Additional properties are not allowed",l)}else if(Ae(t))for(let l of a){let c=t.validate(n[l],Qt(s,["additionalProperties"],l));if(!c.valid)return c}}return L()},ly=({dependentRequired:e},t,r={})=>{if(!he(t))return L();let n=Object.keys(t).filter(s=>typeof t[s]!="function");if(he(e)){for(let[s,i]of Object.entries(e))if(n.includes(s)){for(let o of i)if(!n.includes(o))return Q(r,"dependentRequired",`Expected dependent required property ${o}`,t)}}return L()},cy=({required:e=[]},t,r={})=>{if(!he(t))return L();let n=Object.keys(t).filter(s=>typeof t[s]!="function");return e.every(s=>n.includes(s))?L():Q(r,"required",`Expected object with required properties ${e.join(", ")}`,t)},uy=({dependentSchemas:e},t,r={})=>{if(!he(t))return L();let n=Object.keys(t).filter(s=>typeof t[s]!="function");if(he(e)){for(let[s,i]of Object.entries(e))if(n.includes(s)){let o=i.validate(t,r);if(!o.valid)return o}}return L()},py=({minProperties:e=0},t,r={})=>he(t)?Object.keys(t).length>=e?L():Q(r,"minProperties",`Expected object with at least ${e} properties`,t):L(),fy=({maxProperties:e=0},t,r={})=>!he(t)||Object.keys(t).length<=e?L():Q(r,"maxProperties",`Expected object with at most ${e} properties`,t),my=({patternProperties:e={}},t,r={})=>{if(!he(t))return L();if(!he(e))throw new vt("patternProperties must be an object");for(let[n,s]of Object.entries(t))for(let[i,o]of Object.entries(e))if(new RegExp(i,"u").test(n)){let a=o.validate(s,Qt(r,["patternProperties"],n));if(!a.valid)return a}return L()},dy=({propertyNames:e},t,r={})=>{if(!he(t)||e===void 0)return L();if(!Ae(e))throw new vt("propertyNames must be a managed schema");for(let n of Object.keys(t)){let s=e.validate(n,Qt(r,["propertyNames"],n));if(!s.valid)return s}return L()},hy=({items:e,prefixItems:t=[]},r,n={})=>{if(!at(r)||e===void 0)return L();if(!Ae(e))throw new vt("items must be a managed schema");for(let[s,i]of r.slice(t.length).entries()){let o=e.validate(i,Qt(n,["items"],String(s)));if(!o.valid)return o}return L()},gy=({minItems:e=0},t,r={})=>!at(t)||t.length>=e?L():Q(r,"minItems",`Expected array with at least ${e} items`,t),yy=({maxItems:e=0},t,r={})=>!at(t)||t.length<=e?L():Q(r,"maxItems",`Expected array with at most ${e} items`,t),wy=({uniqueItems:e=false},t,r={})=>{if(!at(t)||!e)return L();for(let n=0;n<t.length;n++){let s=t[n];for(let i=0;i<t.length;i++){if(n===i)continue;let o=t[i];if(Rr(s,o))return Q(r,"uniqueItems",`Duplicated items at index ${n} and ${i}`,t)}}return L()},by=({contains:e,minContains:t,maxContains:r},n,s={})=>{if(!Ae(e))throw new Error("contains must be a managed schema");if(!at(n))return L();let i=n.filter(o=>e.validate(o).valid).length;return i<(t??1)?Q(s,t?"minContains":"contains",`Expected array to contain at least ${t??1}, but found ${i}`,n):r!==void 0&&i>r?Q(s,"maxContains",`Expected array to contain at most ${r}, but found ${i}`,n):L()},Sy=({prefixItems:e=[]},t,r={})=>{if(!at(t))return L();for(let n=0;n<t.length;n++){let s=e[n]?.validate(t[n],Qt(r,String(n),String(n)));if(s&&s?.valid!==true)return s}return L()},kc={email:e=>{if(e.length>318)return false;if(/^[a-z0-9!#$%&'*+/=?^_`{|}~-]{1,20}(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]{1,21}){0,2}@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,60}[a-z0-9])?){0,3}$/i.test(e))return true;if(!e.includes("@")||/(^\.|^"|\.@|\.\.)/.test(e))return false;let[t,r,...n]=e.split("@");return !t||!r||n.length!==0||t.length>64||r.length>253||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?false:r.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},hostname:e=>e.length>(e.endsWith(".")?254:253)?false:/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\.?$/i.test(e),date:e=>{if(e.length!==10)return false;if(e[5]==="0"&&e[6]==="2"){if(/^\d\d\d\d-02-(?:[012][1-8]|[12]0|[01]9)$/.test(e))return true;let t=e.match(/^(\d\d\d\d)-02-29$/);if(!t)return false;let r=Number(t[1]);return r%16===0||r%4===0&&r%25!==0}return e.endsWith("31")?/^\d\d\d\d-(?:0[13578]|1[02])-31$/.test(e):/^\d\d\d\d-(?:0[13-9]|1[012])-(?:[012][1-9]|[123]0)$/.test(e)},time:e=>{if(e.length>27||!/^(?:2[0-3]|[0-1]\d):[0-5]\d:(?:[0-5]\d|60)(?:\.\d+)?(?:z|[+-](?:2[0-3]|[0-1]\d)(?::?[0-5]\d)?)?$/i.test(e))return false;if(!/:60/.test(e))return true;let t=e.match(/([0-9.]+|[^0-9.])/g);if(!t)return false;let r=Number(t[0])*60+Number(t[2]);return t[5]==="+"?r+=1440-Number(t[6]||0)*60-Number(t[8]||0):t[5]==="-"&&(r+=Number(t[6]||0)*60+Number(t[8]||0)),r%1440===1439},"date-time":e=>{if(e.length>38)return false;let t=/^\d\d\d\d-(?:0[1-9]|1[0-2])-(?:[0-2]\d|3[01])[t\s](?:2[0-3]|[0-1]\d):[0-5]\d:(?:[0-5]\d|60)(?:\.\d+)?(?:z|[+-](?:2[0-3]|[0-1]\d)(?::?[0-5]\d)?)$/i,r=e[5]==="0"&&e[6]==="2";if(r&&e[8]==="3"||!t.test(e))return false;if(e[17]==="6"){let n=e.slice(11).match(/([0-9.]+|[^0-9.])/g);if(!n)return false;let s=Number(n[0])*60+Number(n[2]);if(n[5]==="+"?s+=1440-Number(n[6]||0)*60-Number(n[8]||0):n[5]==="-"&&(s+=Number(n[6]||0)*60+Number(n[8]||0)),s%1440!==1439)return false}if(r){if(/^\d\d\d\d-02-(?:[012][1-8]|[12]0|[01]9)/.test(e))return true;let n=e.match(/^(\d\d\d\d)-02-29/);if(!n)return false;let s=Number(n[1]??0);return s%16===0||s%4===0&&s%25!==0}return e[8]==="3"&&e[9]==="1"?/^\d\d\d\d-(?:0[13578]|1[02])-31/.test(e):/^\d\d\d\d-(?:0[13-9]|1[012])-(?:[012][1-9]|[123]0)/.test(e)},ipv4:e=>e.length<=15&&/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)$/.test(e),ipv6:e=>{if(e.length>45||e.length<2)return false;let t=0,r=0,n=0,s=false,i=false,o=0,a=true;for(let c=0;c<e.length;c++){let u=e.charCodeAt(c);if(c===1&&o===58&&u!==58)return false;if(u>=48&&u<=57){if(++n>4)return false}else if(u===46){if(t>6||r>=3||n===0||i)return false;r++,n=0;}else if(u===58){if(r>0||t>=7)return false;if(o===58){if(s)return false;s=true;}else c===0&&(a=false);t++,n=0,i=false;}else if(u>=97&&u<=102||u>=65&&u<=70){if(r>0||++n>4)return false;i=true;}else return false;o=u;}if(t<2||r>0&&(r!==3||n===0))return false;if(s&&e.length===2)return true;if(r>0&&!/(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/.test(e))return false;let l=r>0?6:7;return s?(a||n>0)&&t<l:t===l&&a&&n>0},uri:e=>/^[a-z][a-z0-9+\-.]*:(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/?(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i.test(e),"uri-reference":e=>/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/?(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)?(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i.test(e),"uri-template":e=>/^(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2}|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i.test(e),"json-pointer":e=>/^(?:|\/(?:[^~]|~0|~1)*)$/.test(e),"relative-json-pointer":e=>/^(?:0|[1-9][0-9]*)(?:|#|\/(?:[^~]|~0|~1)*)$/.test(e),uuid:e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),duration:e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),regex:e=>{if(/[^\\]\\Z/.test(e))return false;try{return new RegExp(e,"u"),!0}catch{return false}},binary:()=>true,password:()=>true},Ey=({format:e},t,r={})=>!Ke(t)||!e?L():kc[e]?kc[e](t)?L():Q(r,"format",`Expected format: ${e}`,t):L(),to={type:Wg,const:Gg,enum:zg,allOf:Xg,anyOf:Vg,oneOf:Kg,not:Jg,minLength:Zg,maxLength:ey,pattern:Qg,format:Ey,minimum:sy,exclusiveMinimum:iy,maximum:ry,exclusiveMaximum:ny,multipleOf:ty,required:cy,dependentRequired:ly,dependentSchemas:uy,minProperties:py,maxProperties:fy,propertyNames:dy,properties:oy,patternProperties:my,additionalProperties:ay,minItems:gy,maxItems:yy,uniqueItems:wy,contains:by,prefixItems:Sy,items:hy,if:Yg};Ze=class{"~standard";[Te];_resolver;type;$id;$ref;$schema;title;description;readOnly;writeOnly;$comment;examples;constructor(e,t){let{type:r,validate:n,coerce:s,template:i,...o}=e||{};Object.assign(this,{type:r},o),this[Te]={raw:e,optional:false,overrides:t},this["~standard"]={version:1,vendor:"jsonv-ts",validate:a=>{let l=this.validate(a);return l.valid?{value:a}:{issues:l.errors.map(c=>({message:c.error,path:Oc(c.instanceLocation)}))}}};}template(e,t){let r=this,n=e;if(r.const!==void 0?n=r.const:n===void 0&&(r.default!==void 0&&(n=r.default),t?.withExtendedOptional&&r.enum!==void 0&&(n=r.enum[0])),t?.withOptional!==true&&n===void 0&&this.isOptional())return n;if(this[Te].raw?.template){let i=this[Te].raw.template(n,t);i!==void 0&&(n=i);}let s=this[Te].overrides?.template?.(n,t);return s!==void 0&&(n=s),n}validate(e,t){let r={keywordPath:t?.keywordPath||[],instancePath:t?.instancePath||[],coerce:t?.coerce||false,errors:t?.errors||[],shortCircuit:t?.shortCircuit||false,ignoreUnsupported:t?.ignoreUnsupported||false,resolver:t?.resolver||this.getResolver(),depth:t?.depth?t.depth+1:0,skipClone:t?.skipClone??true},n=this[Te].raw?.validate;if(n!==void 0){let s=n(e,r);if(!s.valid)return s}return xy(this,e,r)}coerce(e,t){let r={...t,resolver:t?.resolver||this.getResolver(),depth:t?.depth?t.depth+1:0,dropUnknown:t?.dropUnknown??false},n=this[Te].raw?.coerce;if(n!==void 0)return n(e,r);let s=this[Te].overrides?.coerce?.(e,r)??e;return Hg(this,s,r)}optional(){return this[Te].optional=true,this}isOptional(){return this[Te].optional}getResolver(){return this._resolver||(this._resolver=new ao(this)),this._resolver}children(e){return []}*walk({instancePath:e=[],keywordPath:t=[],data:r,maxDepth:n=Number.POSITIVE_INFINITY,...s}={}){let i=e.length===0&&r?Lc(r):r;if(s.includeSelf!==false&&(yield new kr(this,{instancePath:e,keywordPath:t,data:i,...s})),!(e.length>=n))for(let o of this.children(s)){let a=[...e,...o.instancePath];yield*o.schema.walk({...s,data:i,maxDepth:n,instancePath:a,keywordPath:[...t,...o.keywordPath]});}}*[Symbol.iterator](e){for(let t of this.walk(e))yield t;}toJSON(){let{toJSON:e,"~standard":t,_resolver:r,...n}=this;return JSON.parse(JSON.stringify(n))}},kr=class{constructor(e,t={}){this.schema=e,this.instancePath=t.instancePath||[],this.keywordPath=t.keywordPath||[],this.depth=this.instancePath.length;try{if(t.data!==void 0){let r=rs(t.data,this.instancePath);e.validate(r).valid&&(this.data=r);}}catch{}}instancePath;keywordPath;data;depth;appendInstancePath(e){return this.instancePath=[...this.instancePath,...e],this}appendKeywordPath(e){return this.keywordPath=[...this.keywordPath,...e],this}setData(e){return this.data=e,this}};_y=class extends Ze{constructor(e){super(),this.bool=e;}toJSON(){return this.bool}validate(e,t){return this.bool?L():Q(t,"","Always fails",e)}};Dc=e=>ss(e?.type,e),$y=(e,t)=>ss(void 0,{...t,const:e}),vy=class extends Ze{type="object";properties;required;constructor(e,t){let r=[];for(let[s,i]of Object.entries(e||{}))Bg(Ae(i),"properties must be managed schemas",i),i[Te].optional||r.push(s);let n=t?.additionalProperties===false?so(false):t?.additionalProperties;r=r.length>0?r:void 0,super({...t,additionalProperties:n,properties:e,required:r},{template:(s,i)=>{let o=structuredClone(he(s)?s:{}),a={...o};if(this.properties)for(let[l,c]of Object.entries(this.properties)){let u=rs(o,l);if(c.isOptional()&&i?.withOptional!==true&&u===void 0&&s===void 0)continue;let p=c.template(u,i);p!==void 0&&(a[l]=p);}if(!(Object.keys(a).length===0&&!i?.withExtendedOptional))return a},coerce:(s,i)=>{let o=Object.keys(this.properties),a=Lc(s),l=o.length>0&&Object.values(this.properties).every(u=>!u[Te].optional);if(Dg(a)&&(i?.dropUnknown===true||l)&&(a=qg(a,o)),typeof a=="string"&&a.match(/^\{/)&&(a=JSON.parse(a)),typeof a!="object"||a===null)return;if(this.properties)for(let[u,p]of Object.entries(this.properties)){let f=a[u];f!==void 0&&(a[u]=p.coerce(f,i));}let c=this.additionalProperties;if(i?.dropUnknown!==true&&(!c||c.validate(null).valid)){let u=he(s)?s:{},p=Object.keys(u).filter(f=>!o.includes(f));for(let f of p)a[f]=c?c.coerce(u[f],i):u[f];}return a}}),this.properties=e,this.required=r;}strict(){return this.additionalProperties=so(false),this[Te].raw.additionalProperties=false,this}partial(){for(let[,e]of Object.entries(this.properties))e[Te].optional=true;return this.required=void 0,this}children(e){let t=[];for(let[r,n]of Object.entries(this.properties)){let s=new kr(n,e);s.appendInstancePath([r]),s.appendKeywordPath(["properties",r]),t.push(s);}return t}},is=(e,t)=>new vy(e,t),Ty=(e,t)=>is(e,t).strict(),Ay=(e,t)=>is(e,t).partial(),Cy=class extends Ze{type="object";additionalProperties;constructor(e,t){super({...t,additionalProperties:e},{template:(r,n)=>n?.withExtendedOptional&&(r===void 0||!he(r))?{}:r}),this.additionalProperties=e;}children(e){let t=[],r=new kr(this.additionalProperties,e);return r.appendKeywordPath(["additionalProperties"]),t.push(r),t}},Ry=(e,t)=>new Cy(e,t),ky=class extends Ze{type="string";constructor(e){super(e,{template:(t,r)=>r?.withExtendedOptional&&(t===void 0||!Ke(t))?"":t,coerce:t=>Qe(t)?String(t):t});}toJSON(){let{pattern:e,"~standard":t,_resolver:r,...n}=this;return JSON.parse(JSON.stringify({...n,pattern:e instanceof RegExp?e.source:e}))}},jc=e=>new ky(e),Fc=(e,t,r)=>ss(e,r,{template:(n,s)=>s?.withExtendedOptional&&(n===void 0||!Qe(n))?r?.minimum??0:n,coerce:n=>{if(Ke(n)){let s=t.parseFn(n);if(!Number.isNaN(s))return s}return n}}),Mc=e=>Fc("number",{parseFn:Number},e),Uc=e=>Fc("integer",{parseFn:Number.parseInt},e),Py=class extends Ze{constructor(e,t={}){super({...t,items:e},{template:r=>r===void 0||!Array.isArray(r)?[]:r,coerce:(r,n)=>{try{let s=typeof r=="string"?JSON.parse(r):r;if(!Array.isArray(s))return;if(Ae(this.items))for(let[i,o]of s.entries())s[i]=this.items.coerce(o,n);return s}catch{}return r}}),this.items=e,this.items=e;}type="array";children(e){let t=[];if(this.items){let r=new kr(this.items,e);r.appendKeywordPath(["items"]),t.push(r);}return t}},Bc=(e,t)=>new Py(e,t),qc=e=>ss("boolean",e,{template:(t,r)=>r?.withExtendedOptional&&(t===void 0||!oo(t))?false:t,coerce:t=>{if(Ke(t)&&["true","false","1","0"].includes(t))return t==="true"||t==="1";if(Qe(t)){if(t===1)return true;if(t===0)return false}return t}}),es=Symbol.for("unionType"),Hc=class extends Ze{[es];constructor(e,t,r){super({...r,[t]:e},{coerce:(n,s)=>{let i=r?.coerce;if(i!==void 0)return i.bind(this)(n,s);let o=ns(e,n,{ignoreUnsupported:true,resolver:s?.resolver,coerce:true});return o.length>0?o[0].coerce(n,s):n}}),this[es]=t;}get schemas(){return this[this[es]]}children(e){let t=[];for(let[r,n]of this.schemas.entries()){let s=new kr(n,e);s.appendKeywordPath([this[es],r]),t.push(s);}return t}},Ny=(e,t)=>new Hc(e,"anyOf",t),Oy=(e,t)=>new Hc(e,"oneOf",t);io=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ro=e=>typeof globalThis.structuredClone=="function"?globalThis.structuredClone(e):JSON.parse(JSON.stringify(e)),Iy=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],Ly=["minimum","exclusiveMinimum","minLength","minItems","minProperties"];Fy=e=>e===true||e===false?e:null;Uy=(e,t)=>{let r=JSON.parse(JSON.stringify({...t,allOf:e}));return Yt(My(r))},Wc=class extends Ze{$ref;constructor(e,t){if(!t&&!Ae(e))throw new Error("Ref not set");if(Ae(e)&&!e.$id)throw new Error("Ref must have an $id");let r=t??e?.$id;super({$ref:r},{coerce:(n,s)=>{let i=s?.resolver?.resolve(this.$ref);if(!Ae(i))throw new Error(`Ref not found: ${this.$ref}`);return i.coerce(n,s)}}),this.$ref=r;}},By=(e,t)=>new Wc(e,t),qy=e=>new Wc(void 0,e),Hy=e=>e(new Ze({$ref:"#",coerce:(t,r)=>{let n=r?.resolver?.resolve("#");if(!Ae(n))throw new Error("Ref not found: #");return n.coerce(t,r)}})),Gc={boolean:qc,any:Dc,literal:$y,object:is,strictObject:Ty,partialObject:Ay,record:Ry,string:jc,number:Mc,integer:Uc,array:Bc,anyOf:Ny,oneOf:Oy,allOf:Uy,ref:By,refId:qy,recursive:Hy};});function Vc(e,t){if(typeof e!="string"){throw new Error("Email must be a string");}if(!Gc.string({format:"email"}).validate(e).valid){throw new Error("Invalid email");}if(t?.domains?.length&&!t.domains.includes(e.split("@")[1])){throw new Error("Email domain not allowed");}return true}function Kc(e,{panic:t=true,length:r=8,numbers:n=0,special:s=0}={}){try{if(typeof e!="string"){if(t)throw new Error("Password must be a string");return !1}if(e.length<r){if(t)throw new Error(`Password must be at least ${r} characters long`);return !1}if((e.match(/[0-9]/g)?.length??0)<n){if(t)throw new Error(`Password must contain at least ${n} numbers`);return !1}if((e.match(/[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/g)?.length??0)<s){if(t)throw new Error(`Password must contain at least ${s} special characters`);return !1}return !0}catch(i){if(t)throw i;return false}}function U(e,t='"'){return `${t}${e}${t}`}function Xc(e,t,r){if(t instanceof RegExp)return t.test(e);if(typeof t=="string")switch(!r&&t.startsWith("/")&&(r="regex"),r){case "regex":return new RegExp(t).test(e);case "sql":return new RegExp(t.replace("%",".*").replace("_",".")).test(e);case "wildcard":return new RegExp(t.replace("*",".*")).test(e);default:return e.includes(t)}return false}var Pr=w(()=>{zc();});function lo(e){return typeof e=="number"?e:Number.parseInt(String(e),10)}var Jc=w(()=>{});var Yc=w(()=>{});var lt=w(()=>{_c();$c();vc();Tc();Ac();Jt();Pr();Jc();Yc();});var co,Qc=w(()=>{co=(e,t,r)=>(n,s)=>{let i=-1;return o(0);async function o(a){if(a<=i)throw new Error("next() called multiple times");i=a;let l,c=false,u;if(e[a]?(u=e[a][0][0],n.req.routeIndex=a):u=a===e.length&&s||void 0,u)try{l=await u(n,()=>o(a+1));}catch(p){if(p instanceof Error&&t)n.error=p,l=await t(p,n),c=true;else throw p}else n.finalized===false&&r&&(l=await r(n));return l&&(n.finalized===false||c)&&(n.res=l),n}};});var Zc=w(()=>{});var eu,tu=w(()=>{eu=Symbol();});async function Wy(e,t){let r=await e.formData();return r?Gy(r,t):{}}function Gy(e,t){let r=Object.create(null);return e.forEach((n,s)=>{t.all||s.endsWith("[]")?zy(r,s,n):r[s]=n;}),t.dot&&Object.entries(r).forEach(([n,s])=>{n.includes(".")&&(Vy(r,n,s),delete r[n]);}),r}var ru,zy,Vy,nu=w(()=>{uo();ru=async(e,t=Object.create(null))=>{let{all:r=false,dot:n=false}=t,i=(e instanceof os?e.raw.headers:e.headers).get("Content-Type");return i?.startsWith("multipart/form-data")||i?.startsWith("application/x-www-form-urlencoded")?Wy(e,{all:r,dot:n}):{}};zy=(e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r;},Vy=(e,t,r)=>{let n=e,s=t.split(".");s.forEach((i,o)=>{o===s.length-1?n[i]=r:((!n[i]||typeof n[i]!="object"||Array.isArray(n[i])||n[i]instanceof File)&&(n[i]=Object.create(null)),n=n[i]);});};});var fo,su,Ky,Xy,as,iu,ls,Jy,mo,ou,Tt,cs,po,au,lu,cu,ho,Zt=w(()=>{fo=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},su=e=>{let{groups:t,path:r}=Ky(e),n=fo(r);return Xy(n,t)},Ky=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let s=`@${n}`;return t.push([s,r]),s}),{groups:t,path:e}},Xy=(e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let s=e.length-1;s>=0;s--)if(e[s].includes(n)){e[s]=e[s].replace(n,t[r][1]);break}}return e},as={},iu=(e,t)=>{if(e==="*")return "*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return as[n]||(r[2]?as[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:as[n]=[e,r[1],true]),as[n]}return null},ls=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},Jy=e=>ls(e,decodeURI),mo=e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let s=t.charCodeAt(n);if(s===37){let i=t.indexOf("?",n),o=t.indexOf("#",n),a=i===-1?o===-1?void 0:o:o===-1?i:Math.min(i,o),l=t.slice(r,a);return Jy(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(s===63||s===35)break}return t.slice(r,n)},ou=e=>{let t=mo(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},Tt=(e,t,...r)=>(r.length&&(t=Tt(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),cs=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(s=>{if(s!==""&&!/\:/.test(s))n+="/"+s;else if(/\:/.test(s))if(/\?/.test(s)){r.length===0&&n===""?r.push("/"):r.push(n);let i=s.replace("?","");n+="/"+i,r.push(n);}else n+="/"+s;}),r.filter((s,i,o)=>o.indexOf(s)===i)},po=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?ls(e,ho):e):e,au=(e,t,r)=>{let n;if(!r&&t&&!/[%+]/.test(t)){let o=e.indexOf("?",8);if(o===-1)return;for(e.startsWith(t,o+1)||(o=e.indexOf(`&${t}`,o+1));o!==-1;){let a=e.charCodeAt(o+t.length+1);if(a===61){let l=o+t.length+2,c=e.indexOf("&",l);return po(e.slice(l,c===-1?void 0:c))}else if(a==38||isNaN(a))return "";o=e.indexOf(`&${t}`,o+1);}if(n=/[%+]/.test(e),!n)return}let s={};n??=/[%+]/.test(e);let i=e.indexOf("?",8);for(;i!==-1;){let o=e.indexOf("&",i+1),a=e.indexOf("=",i);a>o&&o!==-1&&(a=-1);let l=e.slice(i+1,a===-1?o===-1?void 0:o:a);if(n&&(l=po(l)),i=o,l==="")continue;let c;a===-1?c="":(c=e.slice(a+1,o===-1?void 0:o),n&&(c=po(c))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(c)):s[l]??=c;}return t?s[t]:s},lu=au,cu=(e,t)=>au(e,t,true),ho=decodeURIComponent;});var uu,os,uo=w(()=>{Zc();tu();nu();Zt();uu=e=>ls(e,ho),os=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#t=r,this.#e={};}param(e){return e?this.#r(e):this.#i()}#r(e){let t=this.#t[0][this.routeIndex][1][e],r=this.#s(t);return r&&/\%/.test(r)?uu(r):r}#i(){let e={},t=Object.keys(this.#t[0][this.routeIndex][1]);for(let r of t){let n=this.#s(this.#t[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=/\%/.test(n)?uu(n):n);}return e}#s(e){return this.#t[1]?this.#t[1][e]:e}query(e){return lu(this.url,e)}queries(e){return cu(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((r,n)=>{t[n]=r;}),t}async parseBody(e){return this.bodyCache.parsedBody??=await ru(this,e)}#n=e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;let s=Object.keys(t)[0];return s?t[s].then(i=>(s==="json"&&(i=JSON.stringify(i)),new Response(i)[e]())):t[e]=r[e]()};json(){return this.#n("text").then(e=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(e,t){this.#e[e]=t;}valid(e){return this.#e[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[eu](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}};});var pu,fu,go,yo=w(()=>{pu={Stringify:1,BeforeStream:2,Stream:3},fu=(e,t)=>{let r=new String(e);return r.isEscaped=true,r.callbacks=t,r},go=async(e,t,r,n,s)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let i=e.callbacks;if(!i?.length)return Promise.resolve(e);s?s[0]+=e:s=[e];let o=Promise.all(i.map(a=>a({phase:t,buffer:s,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(l=>go(l,t,false,n,s))).then(()=>s[0]));return r?fu(await o,i):o};});var Yy,wo,Nr,mu,du=w(()=>{uo();yo();Yy="text/plain; charset=UTF-8",wo=(e,t)=>({"Content-Type":e,...t}),Nr=(e,t)=>new Response(e,t),mu=class{#e;#t;env={};#r;finalized=false;error;#i;#s;#n;#u;#l;#c;#a;#p;#f;constructor(e,t){this.#e=e,t&&(this.#s=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#f=t.path,this.#p=t.matchResult);}get req(){return this.#t??=new os(this.#e,this.#f,this.#p),this.#t}get event(){if(this.#s&&"respondWith"in this.#s)return this.#s;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#s)return this.#s;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=Nr(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=Nr(e.body,e);for(let[t,r]of this.#n.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let s of n)e.headers.append("set-cookie",s);}else e.headers.set(t,r);}this.#n=e,this.finalized=true;}render=(...e)=>(this.#l??=t=>this.html(t),this.#l(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#l=e;};header=(e,t,r)=>{this.finalized&&(this.#n=Nr(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;t===void 0?n.delete(e):r?.append?n.append(e,t):n.set(e,t);};status=e=>{this.#i=e;};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t);};get=e=>this.#r?this.#r.get(e):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#o(e,t,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof t=="object"&&"headers"in t){let i=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[o,a]of i)o.toLowerCase()==="set-cookie"?n.append(o,a):n.set(o,a);}if(r)for(let[i,o]of Object.entries(r))if(typeof o=="string")n.set(i,o);else {n.delete(i);for(let a of o)n.append(i,a);}let s=typeof t=="number"?t:t?.status??this.#i;return Nr(e,{status:s,headers:n})}newResponse=(...e)=>this.#o(...e);body=(e,t,r)=>this.#o(e,t,r);text=(e,t,r)=>!this.#a&&!this.#i&&!t&&!r&&!this.finalized?new Response(e):this.#o(e,t,wo(Yy,r));json=(e,t,r)=>this.#o(JSON.stringify(e),t,wo("application/json",r));html=(e,t,r)=>{let n=s=>this.#o(s,t,wo("text/html; charset=UTF-8",r));return typeof e=="object"?go(e,pu.Stringify,false,{}).then(n):n(e)};redirect=(e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>Nr(),this.#c(this))};});var te,hu,gu,us,ps,ct=w(()=>{te="ALL",hu="all",gu=["get","post","put","delete","options","patch"],us="Can not add a route since the matcher is already built.",ps=class extends Error{};});var Or,bo=w(()=>{Or="__COMPOSED_HANDLER";});var Qy,yu,wu,Su=w(()=>{Qc();du();ct();bo();Zt();Qy=e=>e.text("404 Not Found",404),yu=(e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},wu=class bu{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...gu,hu].forEach(i=>{this[i]=(o,...a)=>(typeof o=="string"?this.#e=o:this.#i(i,this.#e,o),a.forEach(l=>{this.#i(i,this.#e,l);}),this);}),this.on=(i,o,...a)=>{for(let l of [o].flat()){this.#e=l;for(let c of [i].flat())a.map(u=>{this.#i(c.toUpperCase(),this.#e,u);});}return this},this.use=(i,...o)=>(typeof i=="string"?this.#e=i:(this.#e="*",o.unshift(i)),o.forEach(a=>{this.#i(te,this.#e,a);}),this);let{strict:n,...s}=t;Object.assign(this,s),this.getPath=n??true?t.getPath??mo:ou;}#t(){let t=new bu({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Qy;errorHandler=yu;route(t,r){let n=this.basePath(t);return r.routes.map(s=>{let i;r.errorHandler===yu?i=s.handler:(i=async(o,a)=>(await co([],r.errorHandler)(o,()=>s.handler(o,a))).res,i[Or]=s.handler),n.#i(s.method,s.path,i);}),this}basePath(t){let r=this.#t();return r._basePath=Tt(this._basePath,t),r}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,r,n){let s,i;n&&(typeof n=="function"?i=n:(i=n.optionHandler,n.replaceRequest===false?s=l=>l:s=n.replaceRequest));let o=i?l=>{let c=i(l);return Array.isArray(c)?c:[c]}:l=>{let c;try{c=l.executionCtx;}catch{}return [l.env,c]};s||=(()=>{let l=Tt(this._basePath,t),c=l==="/"?0:l.length;return u=>{let p=new URL(u.url);return p.pathname=p.pathname.slice(c)||"/",new Request(p,u)}})();let a=async(l,c)=>{let u=await r(s(l.req.raw),...o(l));if(u)return u;await c();};return this.#i(te,Tt(t,"*"),a),this}#i(t,r,n){t=t.toUpperCase(),r=Tt(this._basePath,r);let s={basePath:this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s);}#s(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,n,s){if(s==="HEAD")return (async()=>new Response(null,await this.#n(t,r,n,"GET")))();let i=this.getPath(t,{env:n}),o=this.router.match(s,i),a=new mu(t,{path:i,matchResult:o,env:n,executionCtx:r,notFoundHandler:this.#r});if(o[0].length===1){let c;try{c=o[0][0][0][0](a,async()=>{a.res=await this.#r(a);});}catch(u){return this.#s(u,a)}return c instanceof Promise?c.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#s(u,a)):c??this.#r(a)}let l=co(o[0],this.errorHandler,this.#r);return (async()=>{try{let c=await l(a);if(!c.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return c.res}catch(c){return this.#s(c,a)}})()}fetch=(t,...r)=>this.#n(t,r[1],r[0],t.method);request=(t,r,n,s)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,s):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${Tt("/",t)}`,r),n,s));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method));});}};});function So(e,t){let r=this.buildAllMatchers(),n=((s,i)=>{let o=r[s]||r[te],a=o[2][i];if(a)return a;let l=i.match(o[0]);if(!l)return [[],fs];let c=l.indexOf("",1);return [o[1][c],l]});return this.match=n,n(e,t)}var fs,Eo=w(()=>{ct();fs=[];});function ew(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===Ir||e===Lr?1:t===Ir||t===Lr?-1:e===ms?1:t===ms?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var ms,Ir,Lr,At,Zy,Eu,_o=w(()=>{ms="[^/]+",Ir=".*",Lr="(?:|/.*)",At=Symbol(),Zy=new Set(".\\+*[^]$()");Eu=class xo{#e;#t;#r=Object.create(null);insert(t,r,n,s,i){if(t.length===0){if(this.#e!==void 0)throw At;if(i)return;this.#e=r;return}let[o,...a]=t,l=o==="*"?a.length===0?["","",Ir]:["","",ms]:o==="/*"?["","",Lr]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let u=l[1],p=l[2]||ms;if(u&&l[2]&&(p===".*"||(p=p.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(p))))throw At;if(c=this.#r[p],!c){if(Object.keys(this.#r).some(f=>f!==Ir&&f!==Lr))throw At;if(i)return;c=this.#r[p]=new xo,u!==""&&(c.#t=s.varIndex++);}!i&&u!==""&&n.push([u,c.#t]);}else if(c=this.#r[o],!c){if(Object.keys(this.#r).some(u=>u.length>1&&u!==Ir&&u!==Lr))throw At;if(i)return;c=this.#r[o]=new xo;}c.insert(a,r,n,s,i);}buildRegExpStr(){let r=Object.keys(this.#r).sort(ew).map(n=>{let s=this.#r[n];return (typeof s.#t=="number"?`(${n})@${s.#t}`:Zy.has(n)?`\\${n}`:n)+s.buildRegExpStr()});return typeof this.#e=="number"&&r.unshift(`#${this.#e}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};});var xu,_u=w(()=>{_o();xu=class{#e={varIndex:0};#t=new Eu;insert(e,t,r){let n=[],s=[];for(let o=0;;){let a=false;if(e=e.replace(/\{[^}]+\}/g,l=>{let c=`@\\${o}`;return s[o]=[c,l],o++,a=true,c}),!a)break}let i=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let o=s.length-1;o>=0;o--){let[a]=s[o];for(let l=i.length-1;l>=0;l--)if(i[l].indexOf(a)!==-1){i[l]=i[l].replace(a,s[o][1]);break}}return this.#t.insert(i,t,n,this.#e,r),n}buildRegExp(){let e=this.#t.buildRegExpStr();if(e==="")return [/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,i,o)=>i!==void 0?(r[++t]=Number(i),"$()"):(o!==void 0&&(n[Number(o)]=++t),"")),[new RegExp(`^${e}`),r,n]}};});function vu(e){return $u[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function rw(){$u=Object.create(null);}function nw(e){let t=new xu,r=[];if(e.length===0)return tw;let n=e.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,u],[p,f])=>c?1:p?-1:u.length-f.length),s=Object.create(null);for(let c=0,u=-1,p=n.length;c<p;c++){let[f,g,d]=n[c];f?s[g]=[d.map(([y])=>[y,Object.create(null)]),fs]:u++;let m;try{m=t.insert(g,u,f);}catch(y){throw y===At?new ps(g):y}f||(r[u]=d.map(([y,h])=>{let S=Object.create(null);for(h-=1;h>=0;h--){let[T,$]=m[h];S[T]=$;}return [y,S]}));}let[i,o,a]=t.buildRegExp();for(let c=0,u=r.length;c<u;c++)for(let p=0,f=r[c].length;p<f;p++){let g=r[c][p]?.[1];if(!g)continue;let d=Object.keys(g);for(let m=0,y=d.length;m<y;m++)g[d[m]]=a[g[d[m]]];}let l=[];for(let c in o)l[c]=r[o[c]];return [i,l,s]}function er(e,t){if(e){for(let r of Object.keys(e).sort((n,s)=>s.length-n.length))if(vu(r).test(t))return [...e[r]]}}var tw,$u,ds,$o=w(()=>{ct();Zt();Eo();_o();_u();tw=[/^$/,[],Object.create(null)],$u=Object.create(null);ds=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[te]:Object.create(null)},this.#t={[te]:Object.create(null)};}add(e,t,r){let n=this.#e,s=this.#t;if(!n||!s)throw new Error(us);n[e]||[n,s].forEach(a=>{a[e]=Object.create(null),Object.keys(a[te]).forEach(l=>{a[e][l]=[...a[te][l]];});}),t==="/*"&&(t="*");let i=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=vu(t);e===te?Object.keys(n).forEach(l=>{n[l][t]||=er(n[l],t)||er(n[te],t)||[];}):n[e][t]||=er(n[e],t)||er(n[te],t)||[],Object.keys(n).forEach(l=>{(e===te||e===l)&&Object.keys(n[l]).forEach(c=>{a.test(c)&&n[l][c].push([r,i]);});}),Object.keys(s).forEach(l=>{(e===te||e===l)&&Object.keys(s[l]).forEach(c=>a.test(c)&&s[l][c].push([r,i]));});return}let o=cs(t)||[t];for(let a=0,l=o.length;a<l;a++){let c=o[a];Object.keys(s).forEach(u=>{(e===te||e===u)&&(s[u][c]||=[...er(n[u],c)||er(n[te],c)||[]],s[u][c].push([r,i-l+a+1]));});}}match=So;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(t=>{e[t]||=this.#r(t);}),this.#e=this.#t=void 0,rw(),e}#r(e){let t=[],r=e===te;return [this.#e,this.#t].forEach(n=>{let s=n[e]?Object.keys(n[e]).map(i=>[i,n[e][i]]):[];s.length!==0?(r||=true,t.push(...s)):e!==te&&t.push(...Object.keys(n[te]).map(i=>[i,n[te][i]]));}),r?nw(t):null}};});var Tu=w(()=>{ct();Eo();$o();});var Au=w(()=>{$o();Tu();});var vo,Cu=w(()=>{ct();vo=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers;}add(e,t,r){if(!this.#t)throw new Error(us);this.#t.push([e,t,r]);}match(e,t){if(!this.#t)throw new Error("Fatal error");let r=this.#e,n=this.#t,s=r.length,i=0,o;for(;i<s;i++){let a=r[i];try{for(let l=0,c=n.length;l<c;l++)a.add(...n[l]);o=a.match(e,t);}catch(l){if(l instanceof ps)continue;throw l}this.match=a.match.bind(a),this.#e=[a],this.#t=void 0;break}if(i===s)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#t||this.#e.length!==1)throw new Error("No active router has been determined yet.");return this.#e[0]}};});var Ru=w(()=>{Cu();});var Dr,sw,ku,Nu=w(()=>{ct();Zt();Dr=Object.create(null),sw=e=>{for(let t in e)return true;return false},ku=class Pu{#e;#t;#r;#i=0;#s=Dr;constructor(t,r,n){if(this.#t=n||Object.create(null),this.#e=[],t&&r){let s=Object.create(null);s[t]={handler:r,possibleKeys:[],score:0},this.#e=[s];}this.#r=[];}insert(t,r,n){this.#i=++this.#i;let s=this,i=su(r),o=[];for(let a=0,l=i.length;a<l;a++){let c=i[a],u=i[a+1],p=iu(c,u),f=Array.isArray(p)?p[0]:c;if(f in s.#t){s=s.#t[f],p&&o.push(p[1]);continue}s.#t[f]=new Pu,p&&(s.#r.push(p),o.push(p[1])),s=s.#t[f];}return s.#e.push({[t]:{handler:n,possibleKeys:o.filter((a,l,c)=>c.indexOf(a)===l),score:this.#i}}),s}#n(t,r,n,s,i){for(let o=0,a=r.#e.length;o<a;o++){let l=r.#e[o],c=l[n]||l[te],u={};if(c!==void 0&&(c.params=Object.create(null),t.push(c),s!==Dr||i&&i!==Dr))for(let p=0,f=c.possibleKeys.length;p<f;p++){let g=c.possibleKeys[p],d=u[c.score];c.params[g]=i?.[g]&&!d?i[g]:s[g]??i?.[g],u[c.score]=true;}}}search(t,r){let n=[];this.#s=Dr;let i=[this],o=fo(r),a=[],l=o.length,c=null;for(let u=0;u<l;u++){let p=o[u],f=u===l-1,g=[];for(let m=0,y=i.length;m<y;m++){let h=i[m],S=h.#t[p];S&&(S.#s=h.#s,f?(S.#t["*"]&&this.#n(n,S.#t["*"],t,h.#s),this.#n(n,S,t,h.#s)):g.push(S));for(let T=0,$=h.#r.length;T<$;T++){let P=h.#r[T],N=h.#s===Dr?{}:{...h.#s};if(P==="*"){let D=h.#t["*"];D&&(this.#n(n,D,t,h.#s),D.#s=N,g.push(D));continue}let[v,_,I]=P;if(!p&&!(I instanceof RegExp))continue;let b=h.#t[v];if(I instanceof RegExp){if(c===null){c=new Array(l);let F=r[0]==="/"?1:0;for(let E=0;E<l;E++)c[E]=F,F+=o[E].length+1;}let D=r.substring(c[u]),R=I.exec(D);if(R){if(N[_]=R[0],this.#n(n,b,t,h.#s,N),sw(b.#t)){b.#s=N;let F=R[0].match(/\//)?.length??0;(a[F]||=[]).push(b);}continue}}(I===true||I.test(p))&&(N[_]=p,f?(this.#n(n,b,t,N,h.#s),b.#t["*"]&&this.#n(n,b.#t["*"],t,N,h.#s)):(b.#s=N,g.push(b)));}}let d=a.shift();i=d?g.concat(d):g;}return n.length>1&&n.sort((u,p)=>u.score-p.score),[n.map(({handler:u,params:p})=>[u,p])]}};});var To,Ou=w(()=>{Zt();Nu();To=class{name="TrieRouter";#e;constructor(){this.#e=new ku;}add(e,t,r){let n=cs(t);if(n){for(let s=0,i=n.length;s<i;s++)this.#e.insert(e,n[s],r);return}this.#e.insert(e,t,r);}match(e,t){return this.#e.search(e,t)}};});var Iu=w(()=>{Ou();});var Ao,Lu=w(()=>{Su();Au();Ru();Iu();Ao=class extends wu{constructor(e={}){super(e),this.router=e.router??new vo({routers:[new ds,new To]});}};});var Du=w(()=>{Lu();});function Co(e){return !e||typeof e!="object"?false:e.code==="EADDRINUSE"}function ju(e,t){return new Promise((r,n)=>{let s=o=>{e.off("listening",i),n(o);},i=()=>{e.off("error",s),r();};e.once("error",s),e.once("listening",i),e.listen(t);})}function Ro(e){console.error(),console.error(jr.default.red(`Cannot start server: Port ${jr.default.bold(String(e))} is already in use.`)),console.error(jr.default.red(`Stop the process using that port, or set a different ${jr.default.bold("api.port")} in your config.`)),console.error(),process.exit(1);}var jr,Fu=w(()=>{jr=ee(ie());});var Mu,Uu=w(()=>{Mu=/^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;});var Po,Bu,iw,ko,No=w(()=>{Po=(e,t=ko)=>{let r=/\.([a-zA-Z0-9]+?)$/,n=e.match(r);if(!n)return;let s=t[n[1]];return s&&s.startsWith("text")&&(s+="; charset=utf-8"),s},Bu=e=>{for(let t in ko)if(ko[t]===e)return t},iw={aac:"audio/aac",avi:"video/x-msvideo",avif:"image/avif",av1:"video/av1",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css",csv:"text/csv",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",gz:"application/gzip",htm:"text/html",html:"text/html",ico:"image/x-icon",ics:"text/calendar",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",map:"application/json",mid:"audio/x-midi",midi:"audio/x-midi",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",pdf:"application/pdf",png:"image/png",rtf:"application/rtf",svg:"image/svg+xml",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",wasm:"application/wasm",webm:"video/webm",weba:"audio/webm",webmanifest:"application/manifest+json",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xml:"application/xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2",gltf:"model/gltf+json",glb:"model/gltf-binary"},ko=iw;});var qu,Hu=w(()=>{qu=(...e)=>{let t=e.filter(s=>s!=="").join("/");t=t.replace(/(?<=\/)\/+/g,"");let r=t.split("/"),n=[];for(let s of r)s===".."&&n.length>0&&n.at(-1)!==".."?n.pop():s!=="."&&n.push(s);return n.join("/")||"."};});var Wu,ow,aw,Gu,zu=w(()=>{Uu();No();Hu();Wu={br:".br",zstd:".zst",gzip:".gz"},ow=Object.keys(Wu),aw="index.html",Gu=e=>{let t=e.root??"./",r=e.path,n=e.join??qu;return async(s,i)=>{if(s.finalized)return i();let o;if(e.path)o=e.path;else try{if(o=decodeURIComponent(s.req.path),/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(o))throw new Error}catch{return await e.onNotFound?.(s.req.path,s),i()}let a=n(t,!r&&e.rewriteRequestPath?e.rewriteRequestPath(o):o);e.isDir&&await e.isDir(a)&&(a=n(a,aw));let l=e.getContent,c=await l(a,s);if(c instanceof Response)return s.newResponse(c.body,c);if(c){let u=e.mimes&&Po(a,e.mimes)||Po(a);if(s.header("Content-Type",u||"application/octet-stream"),e.precompressed&&(!u||Mu.test(u))){let p=new Set(s.req.header("Accept-Encoding")?.split(",").map(f=>f.trim()));for(let f of ow){if(!p.has(f))continue;let g=await l(a+Wu[f],s);if(g){c=g,s.header("Content-Encoding",f),s.header("Vary","Accept-Encoding",{append:true});break}}}return await e.onFound?.(a,s),s.body(c)}await e.onNotFound?.(a,s),await i();}};});var Vu,Ku=w(()=>{zu();Vu=e=>async function(r,n){return Gu({...e,getContent:async o=>{let a=Bun.file(o);return await a.exists()?a:null},join:join,isDir:async o=>{let a;try{a=(await stat(o)).isDirectory();}catch{}return a}})(r,n)};});var Xu=w(()=>{});var Ju,Yu=w(()=>{Xu();Ju=(e,t)=>{for(let[r,n]of Object.entries(t)){let s=new RegExp("/:"+r+"(?:{[^/]+})?\\??");e=e.replace(s,n?`/${n}`:"");}return e};});var uw,Qu,Zu=w(()=>{uw=1024,Qu=({concurrency:e,interval:t}={})=>{if(e||=uw,e===1/0)return {run:async s=>s()};let r=new Set,n=async(s,i,o)=>{if(r.size>=e)return i||=new Promise(c=>o=c),setTimeout(()=>n(s,i,o)),i;let a={};r.add(a);let l=await s();return t?setTimeout(()=>r.delete(a),t):r.delete(a),o?(o(l),i):l};return {run:n}};});var ep,Oo,tp=w(()=>{bo();ep=e=>e.length>1,Oo=e=>e[Or]?Oo(e[Or]):e;});var rp,pw,fw,mw,dw,Fr,np,Io,Lo=w(()=>{ct();tp();rp=e=>e.split(/[\/\\]/).slice(0,-1).join("/"),pw=e=>e.replace(/(\\)/g,"/").replace(/\/$/g,""),fw=(e,t)=>{e.length===0||t?e.push(".."):e.pop();},mw=(e,t)=>{e=e.replace(/^\.(?!.)/,""),e!==""&&t.push(e);},dw=(e,t)=>{let r=false;for(let n of e)n===".."?(fw(t,r),r=true):(mw(n,t),r=false);},Fr=(...e)=>{e=e.map(pw);let t=[];return dw(e.join("/").split("/"),t),(e[0][0]==="/"?"/":"")+t.join("/")},np=e=>e.routes.reduce((t,{method:r,handler:n,path:s})=>{let i=Oo(n);return ["GET",te].includes(r)&&!ep(i)&&t.push({path:s}),t},[]),Io=e=>e.split("/").some(t=>t.startsWith(":")||t.includes("*"));});var sp,hs,Do=w(()=>{Lo();sp="HONO_SSG_CONTEXT",hs="x-hono-disable-ssg",(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[hs]:"true"}})}catch{return null}})();});var ip=w(()=>{yo();});var jo,Fo=w(()=>{ip();jo=()=>({afterResponseHook:e=>e.status!==200?false:e});});var hw,gw,yw,ww,bw,Sw,Ew,xw,_w,$w,vw,op,Tw,ap,lp=w(()=>{Yu();Zu();No();Do();Fo();Lo();hw=2,gw="text/plain",yw="./static",ww=(e,t,r,n)=>{let s=Ew(r,n);return e.endsWith(`.${s}`)?Fr(t,e):e==="/"?Fr(t,`index.${s}`):e.endsWith("/")?Fr(t,e,`index.${s}`):Fr(t,`${e}.${s}`)},bw=async e=>{let t=e.headers.get("Content-Type");try{return t?.includes("text")||t?.includes("json")?await e.text():await e.arrayBuffer()}catch(r){throw new Error(`Error processing response: ${r instanceof Error?r.message:"Unknown error"}`)}},Sw={"text/html":"html","text/xml":"xml","application/xml":"xml","application/yaml":"yaml"},Ew=(e,t)=>{let r=t||Sw;return e in r?r[e]:Bu(e)||"html"},xw=e=>Array.isArray(e)?async t=>{let r=t;for(let n of e){let s=await n(r);if(s===false)return false;s instanceof Request&&(r=s);}return r}:e,_w=e=>Array.isArray(e)?async t=>{let r=t;for(let n of e){let s=await n(r);if(s===false)return false;s instanceof Response&&(r=s);}return r}:e,$w=(e,t,r)=>Array.isArray(e)?async n=>{for(let s of e)await s(n,t,r);}:e,vw=function*(e,t,r,n){let s="http://localhost",i=Qu({concurrency:n});for(let o of np(e)){let a=new URL(o.path,s).toString(),l=new Request(a);yield new Promise(async(c,u)=>{try{if(t){let f=await t(l);if(!f){c(void 0);return}l=f;}if(await i.run(()=>e.fetch(l)),!l.ssgParams){if(Io(o.path)){c(void 0);return}l.ssgParams=[{}];}let p={method:l.method,headers:l.headers};c((function*(){for(let f of l.ssgParams)yield new Promise(async(g,d)=>{try{let m=Ju(o.path,f),y=await i.run(()=>e.request(m,p,{[sp]:!0}));if(y.headers.get(hs)){g(void 0);return}if(r){let T=await r(y);if(!T){g(void 0);return}y=T;}let h=y.headers.get("Content-Type")?.split(";")[0]||gw,S=await bw(y);g({routePath:m,mimeType:h,content:S});}catch(m){d(m);}});})());}catch(p){u(p);}});}},op=new Set,Tw=async(e,t,r,n)=>{let s=await e;if(!s)return;let{routePath:i,content:o,mimeType:a}=s,l=ww(i,r,a,n),c=rp(l);return op.has(c)||(await t.mkdir(c,{recursive:true}),op.add(c)),typeof o=="string"?await t.writeFile(l,o):o instanceof ArrayBuffer&&await t.writeFile(l,new Uint8Array(o)),l},ap=async(e,t,r)=>{let n,s=[],i=[],o=r?.plugins||[jo()],a=[],l=[],c=[];r?.beforeRequestHook&&a.push(...Array.isArray(r.beforeRequestHook)?r.beforeRequestHook:[r.beforeRequestHook]),r?.afterResponseHook&&l.push(...Array.isArray(r.afterResponseHook)?r.afterResponseHook:[r.afterResponseHook]),r?.afterGenerateHook&&c.push(...Array.isArray(r.afterGenerateHook)?r.afterGenerateHook:[r.afterGenerateHook]);for(let u of o)u.beforeRequestHook&&a.push(...Array.isArray(u.beforeRequestHook)?u.beforeRequestHook:[u.beforeRequestHook]),u.afterResponseHook&&l.push(...Array.isArray(u.afterResponseHook)?u.afterResponseHook:[u.afterResponseHook]),u.afterGenerateHook&&c.push(...Array.isArray(u.afterGenerateHook)?u.afterGenerateHook:[u.afterGenerateHook]);try{let u=r?.dir??yw,p=r?.concurrency??hw,f=xw(a.length>0?a:[y=>y]),g=_w(l.length>0?l:[y=>y]),d=vw(e,f,g,p);for(let y of d)s.push(y.then(h=>{if(h)for(let S of h)i.push(Tw(S,t,u,r?.extensionMap).catch(T=>T));}));await Promise.all(s);let m=[];for(let y of i){let h=await y;if(typeof h=="string")m.push(h);else if(h)throw h}n={success:!0,files:m};}catch(u){let p=u instanceof Error?u:new Error(String(u));n={success:false,files:[],error:p};}return c.length>0&&await $w(c,t,r)(n,t,r),n};});var cp=w(()=>{lp();Do();Fo();});var Aw,Mo,up,pp=w(()=>{cp();(({write:Aw}=Bun)),Mo={writeFile:async(e,t)=>{await Aw(e,t);},mkdir:async()=>{}},up=async(e,t)=>ap(e,Mo,t);});var fp,mp,dp,hp=w(()=>{fp=class{#e;constructor(e){this.#e=e,this.raw=e.raw,this.url=e.url?new URL(e.url):null,this.protocol=e.protocol??null;}send(e,t){this.#e.send(e,t??{});}raw;binaryType="arraybuffer";get readyState(){return this.#e.readyState}url;protocol;close(e,t){this.#e.close(e,t);}},mp=e=>new MessageEvent("message",{data:e}),dp=e=>((...t)=>{if(typeof t[0]=="function"){let[r,n]=t;return async function(i,o){let a=await r(i),l=await e(i,a,n);if(l)return l;await o();}}else {let[r,n,s]=t;return (async()=>{let i=await e(r,n,s);if(!i)throw new Error("Failed to upgrade WebSocket");return i})()}});});var tr,gs=w(()=>{tr=e=>"server"in e.env?e.env.server:e.env;});var Uo,Bo,qo,gp,yp=w(()=>{hp();gs();Uo=e=>new fp({send:(t,r)=>{e.send(t,r?.compress);},raw:e,readyState:e.readyState,url:e.data.url,protocol:e.data.protocol,close(t,r){e.close(t,r);}}),Bo=dp((e,t)=>{let r=tr(e);if(!r)throw new TypeError("env has to include the 2nd argument of fetch.");if(r.upgrade(e.req.raw,{data:{events:t,url:new URL(e.req.url),protocol:e.req.url}}))return new Response(null)}),qo={open(e){let t=e.data.events;t.onOpen&&t.onOpen(new Event("open"),Uo(e));},close(e,t,r){let n=e.data.events;n.onClose&&n.onClose(new CloseEvent("close",{code:t,reason:r}),Uo(e));},message(e,t){let r=e.data.events;if(r.onMessage){let n=typeof t=="string"?t:t.buffer;r.onMessage(mp(n),Uo(e));}}},gp=()=>({upgradeWebSocket:Bo,websocket:qo});});var wp,bp=w(()=>{gs();wp=e=>{let t=tr(e);if(!t)throw new TypeError("env has to include the 2nd argument of fetch.");if(typeof t.requestIP!="function")throw new TypeError("server.requestIP is not a function.");let r=t.requestIP(e.req.raw);return r?{remote:{address:r.address,addressType:r.family==="IPv6"||r.family==="IPv4"?r.family:void 0,port:r.port}}:{remote:{}}};});var Sp={};de(Sp,{bunFileSystemModule:()=>Mo,createBunWebSocket:()=>gp,getBunServer:()=>tr,getConnInfo:()=>wp,serveStatic:()=>Vu,toSSG:()=>up,upgradeWebSocket:()=>Bo,websocket:()=>qo});var Ep=w(()=>{Ku();pp();yp();bp();gs();});async function ys(e,t={port:3e3}){let r=Jn(),n=t.port??3e3;if(Cr()){let s=await Promise.resolve().then(()=>(Ep(),Sp)).then(o=>o.serveStatic),i;try{i=Bun.serve({fetch:_p(e,r,s).fetch,port:n});}catch(o){throw Co(o)&&Ro(n),o}return async()=>{await i.stop();}}else {let{createAdaptorServer:s}=await import('@hono/node-server'),i=await import('@hono/node-server/serve-static').then(a=>a.serveStatic),o=s({fetch:_p(e,r,i).fetch});try{await ju(o,n);}catch(a){throw Co(a)&&Ro(n),a}return ()=>new Promise(a=>{o.close(()=>{a(void 0);});})}}function _p(e,t,r){return new Ao().use("/favicon.ico",r({path:ze__default.join(t,"static","favicon.ico")})).use("/fonts/*",r({root:ze__default.join(t,"static"),onNotFound:n=>{console.log("fonts not found",n,process.cwd());}})).use("/static/*",r({root:t,onNotFound(n){console.log("not found",n,process.cwd());}})).all("*",async n=>e.fetch(n.req.raw))}var Ho=w(()=>{lt();Du();Fu();xe();});var tt,Wo=w(()=>{xt();tt=class e{root;constructor(t,r){let n=r??e.projectDir();this.root=ze__default.join(n,t??"");}ensureRoot(){ke(this.root);}static homeDir(){return ze__default.join(Cw.homedir(),".lite")}static projectDir(){return ze__default.join(process.cwd(),"supabase")}deleteAll(t=false){try{Bn.rmSync(this.root,{recursive:!0});}catch(r){if(!t)throw r}this.ensureRoot();}delete(t,r=false){try{Bn.unlinkSync(ze__default.join(this.root,t));}catch(n){if(!r)throw n}}write(t,r,n=false){try{this.ensureRoot(),Bn.writeFileSync(ze__default.join(this.root,t),r);}catch(s){if(!n)throw s}}read(t,r=false){try{return Bn.readFileSync(ze__default.join(this.root,t),"utf8")}catch(n){if(!r)throw n}}relativePath(t){return t?ze__default.relative(process.cwd(),ze__default.join(this.root,t)):this.root}path(t){return t?ze__default.join(this.root,t):this.root}};});var Mr,Go=w(()=>{Mr=process.env.SUPALITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2000":"https://www.lite.dev");});var Ss,$p=w(()=>{xt();Ss=class{root;constructor(t){this.root=t??ze__default.join(Cw.homedir(),".lite","auth"),ke(this.root);}async getItem(t){try{return Bn.readFileSync(ze__default.join(this.root,t+".json"),"utf8")}catch{return null}}async setItem(t,r){Bn.writeFileSync(ze__default.join(this.root,t+".json"),r);}async removeItem(t){try{Bn.unlinkSync(ze__default.join(this.root,t+".json"));}catch{return}}};});var rr,Vo=w(()=>{Go();Wo();$p();rr=class{constructor(t){this.config=t;this.tempFs=new tt(".temp",this.config.root),this.projectFs=new tt("supabase",this.config.root),this.schemaFs=new tt("schemas",this.config.root),this.authStorage=this.config.authStorage??new Ss(ze__default.join(tt.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??Mr,process.env.SUPALITE_CLOUD_ANON_KEY??"...",{auth:{storage:this.authStorage}}):void 0;}tempFs;projectFs;schemaFs;_client;authStorage;async fetch(t,r){if(!this.config.token)throw new Error("Not authenticated, sign in first.");let n=t instanceof URL?t:new URL(t,this.config.host??Mr);return await fetch(n,{...r,headers:{...r?.headers,Authorization:`Bearer ${this.config.token}`}})}};});var nr,Ko=w(()=>{Vo();nr=class extends rr{constructor(r){super(r);this.config=r;}get client(){if(!this._client)throw new Error("Supabase client not initialized");return this._client}projectRef(){return this.tempFs.read("project-ref",true)}projectUrl(r){let n=new URL(this.config.host),s=n.hostname==="localhost"?"supalite.local":n.hostname,i=s.split(".").filter(a=>a!=="www"),o=i.length>=2?i.slice(-2).join("."):s;return `${n.protocol}//${r}.${o}${n.port?`:${n.port}`:""}`}};});function Nw(e){let t=ze.extname(e).toLowerCase();return {".html":"text/html",".css":"text/css",".js":"application/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".avif":"image/avif",".pdf":"application/pdf",".txt":"text/plain",".xml":"application/xml",".zip":"application/zip",".mp4":"video/mp4",".webm":"video/webm",".mp3":"audio/mpeg",".wav":"audio/wav",".woff":"font/woff",".woff2":"font/woff2"}[t]??"application/octet-stream"}var xs,vp=w(()=>{lt();xs=class{driver=pe;basePath;constructor(t){this.basePath=ze.resolve(t.basePath);}filePath(t,r){return ze.join(this.basePath,t,r)}async ensureDir(t){await pe.mkdir(ze.dirname(t),{recursive:true});}async getObject(t,r,n,s){let i=this.filePath(t,r),o=await pe.stat(i),a=`"${createHash("md5").update(`${i}:${o.mtimeMs}`).digest("hex")}"`;if(s?.ifNoneMatch===a)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,r)};if(s?.ifModifiedSince){let f=new Date(s.ifModifiedSince);if(o.mtime<=f)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,r)}}let l,c,u=o.size,p=200;if(s?.range){let f=s.range.match(/^bytes=(\d+)-(\d*)$/);if(f){let g=Number.parseInt(f[1],10),d=f[2]?Number.parseInt(f[2],10):o.size-1;u=d-g+1,c=`bytes ${g}-${d}/${o.size}`,p=206,l=(await pe.open(i,"r")).readableWebStream();}else l=(await pe.open(i,"r")).readableWebStream();}else l=(await pe.open(i,"r")).readableWebStream();return {httpStatusCode:p,metadata:{...this.buildMetadata(o,a,r),contentLength:u,contentRange:c},body:l}}async uploadObject(t,r,n,s,i,o){let a=this.filePath(t,r);await this.ensureDir(a);let l;if(s instanceof Uint8Array||Buffer.isBuffer(s))l=s;else {let p=[],f=s.getReader();for(;;){let{done:g,value:d}=await f.read();if(g)break;p.push(d);}l=Buffer.concat(p);}await pe.writeFile(a,l);let c=await pe.stat(a),u=`"${createHash("md5").update(l).digest("hex")}"`;return {cacheControl:o,contentLength:c.size,size:c.size,mimetype:i,lastModified:c.mtime,eTag:u}}async deleteObject(t,r,n){let s=this.filePath(t,r);await pe.unlink(s).catch(i=>{if(i.code!=="ENOENT")throw i});}async deleteObjects(t,r){for(let n of r)await this.deleteObject(t,n,void 0);}async copyObject(t,r,n,s,i){let o=this.filePath(t,r),a=this.filePath(t,s);await this.ensureDir(a),await pe.copyFile(o,a);let l=await pe.stat(a),c=await pe.readFile(a);return {httpStatusCode:200,eTag:`"${createHash("md5").update(c).digest("hex")}"`,lastModified:l.mtime}}async headObject(t,r,n){let s=this.filePath(t,r),i=await pe.stat(s),o=`"${createHash("md5").update(`${s}:${i.mtimeMs}`).digest("hex")}"`;return this.buildMetadata(i,o,r)}async privateAssetUrl(t,r,n){return `file://${this.filePath(t,r)}`}buildMetadata(t,r,n){return {cacheControl:"no-cache",contentLength:lo(t.size),size:lo(t.size),mimetype:Nw(n),lastModified:t.mtime,eTag:r}}};});async function qe(e,t,r){try{return await Ow(e)}catch(n){throw n?.code==="ERR_MODULE_NOT_FOUND"||/Cannot find package/.test(String(n?.message))?new Error(`Driver '${t}' selected but '${r}' is not installed. Run: bun add ${r}`):n}}var Ow,sr=w(()=>{Ow=new Function("spec","return import(spec)");});function Tp(e,t={}){let r=ze__default.resolve(t.cwd??process.cwd()),n=t.env??process.env,s=process.env.SUPABASE_ENV||"development",i=[`.env.${s}.local`,s==="test"?null:".env.local",`.env.${s}`,".env"].filter(a=>a!==null),o=Dw(ze__default.resolve(e),r);for(let a of o)for(let l of i){let c=ze__default.join(a,l),u;try{u=Bn.readFileSync(c,"utf-8");}catch{continue}let p;try{p=parse(u);}catch(f){throw new Error(`Failed to parse ${c}: ${f.message}`)}for(let[f,g]of Object.entries(p))n[f]===void 0&&(n[f]=g);}}function Dw(e,t){let r=[],n=e,s=ze__default.parse(n).root;for(;r.push(n),!(n===t||n===s);){let i=ze__default.dirname(n);if(i===n)break;n=i;}return r}var Ap=w(()=>{});function Cp(e,t=process.env){return Xo(e,t)}function Xo(e,t){if(typeof e=="string"){let r=e.match(jw);return r?t[r[1]]??"":e}if(Array.isArray(e))return e.map(r=>Xo(r,t));if(e&&typeof e=="object"){let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return e;let n={};for(let[s,i]of Object.entries(e))n[s]=Xo(i,t);return n}return e}var jw,Rp=w(()=>{jw=/^env\((\w+)\)$/;});var Br,Mw,_s,Pp=w(()=>{Ko();Kt();Br=ee(ie());Tr();zt();vp();sr();Ap();Rp();Mw=["toml","json","ts","mts","js","mjs","cjs"],_s=class extends nr{ref(){return this.projectRef()}setRef(t){return this.tempFs.write("project-ref",t),this}link(t){return this.setRef(t.id),t}unlink(){return this.tempFs.delete("project-ref"),this}url(){let t=this.ref();if(!t)throw new Error("No project linked");return this.projectUrl(t)}async getConfigPath(t){let r=ze__default.relative(process.cwd(),ve.config_dir);if(!t)for(let n of Mw){let s=ze__default.join(r,`config.${n}`);if(await pe__default.access(s).then(()=>true).catch(()=>false)){t=s;break}}return t}async readConfig(t){let r=await this.getConfigPath(t);if(!r)return {};console.log(Br.default.dim(`Using config file: ${Br.default.cyan(`./${r}`)}`));let n=ze__default.dirname(ze__default.resolve(r));Tp(n);let s=r.split(".").pop(),i;switch(s){case "toml":i=$t(await pe__default.readFile(r,"utf-8"));break;case "json":i=JSON.parse(await pe__default.readFile(r,"utf-8"));break;case "ts":case "mts":case "js":case "mjs":case "cjs":try{i=(await import(ze__default.join(process.cwd(),r))).default;break}catch(o){throw console.error("Failed to import config file",o),o}default:throw new Error(`Unsupported config file type: ${r}`)}return Cp(i)}async createConnection(){throw new Error("Not implemented")}async getConfig(t){let r=await this.readConfig(t);if("connection"in r)return {...r,connection:await r.connection};let n,s;switch(r.db?.driver){case "sqlite":s=r.db?.url??ve.default_db_url,n=await createConnection({url:s,ddlDialect:"sqlite"});break;case "pglite":{s=r.db?.url??ze__default.join(process.cwd(),ve.default_db_dir);let{createPgliteConnection:i}=await qe("@supabase/lite/pglite","pglite","@electric-sql/pglite");n=await i({url:s});break}case "postgres":{s=r.db?.url??"";let{createPostgresConnection:i}=await qe("@supabase/lite/postgres","postgres","postgres");n=await i({url:s});break}default:s=r.db?.url??ve.default_db_url,n=await createConnection({url:s,ddlDialect:"postgres"});break}if(!n)throw new Error("Failed to create connection");return console.log(Br.default.green(" \u279C"),"Database located at",Br.default.cyan(s??"in-memory")),{...r,connection:n}}async createApp(t){let r=await this.getConfig(t),n=new App(r);return n.config.storage?.enabled&&process.env.EXPERIMENTAL_STORAGE==="1"&&!n._storageAdapter&&(n._storageAdapter=new xs({basePath:ze__default.join(process.cwd(),ve.config_dir,".temp/storage")})),await n.init()}};});var $s,Np=w(()=>{Ko();$s=class extends nr{url(t){return this.projectUrl(t)}async ping(){return (await this.fetch("/v1/system/ping")).ok}async list(){let t=await this.fetch("/v1/projects");if(!t.ok)throw new Error("Failed to list projects");let r=await t.json();if(!r||!r.data)throw new Error("Failed to list projects");return r.data}async get(t){if(t=t??this.projectRef(),!t)throw new Error("No project ref found");let r=await this.fetch(`/v1/projects/${t}`);if(!r.ok)throw new Error(`Failed to get project: ${r.status} ${r.statusText}`);let n=await r.json();if(!n||!n.id)throw new Error("Failed to get project");return n}async create(t={}){let r=await this.fetch("/v1/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok)throw new Error(`Failed to create project: ${r.status} ${r.statusText}`);let n=await r.json();if(!n.data||!n.data.id)throw new Error("Failed to create project");return n.data}async getConfig(t){let r=await this.fetch(`/v1/projects/${t}/config`);if(!r.ok)throw new Error(`Failed to get project config: ${r.status} ${r.statusText}`);let n=await r.json();if(!n)throw new Error("Failed to get project config");return n}async setConfig(t,r){let n=await this.fetch(`/v1/projects/${t}/config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok)throw new Error(`Failed to set project config: ${n.status} ${n.statusText}`);return true}async createApp(t){if(!this.config.host)throw new Error("No host specified");let{data:r,error:n}=await this.client.auth.getSession();if(n)throw n;if(!r?.session?.access_token)throw new Error("Not authenticated, sign in first.");let s=await this.getConfig(t);return await new App({...s.config,connection:cloud({projectRef:t,token:r.session.access_token,host:this.config.host})}).init()}};});var vs,Op=w(()=>{Vo();Pp();Np();vs=class extends rr{project;get client(){if(!this._client)throw new Error("Supabase client not initialized");return this._client}async getSession(){return await this.client.auth.getSession()}async getAccessToken(){let{data:t,error:r}=await this.getSession();if(r)throw r;return t?.session?.access_token}async requireSession(){let t=await this.getAccessToken();if(!t)throw new Error("Not authenticated, sign in first.");return t}async init(){let t={...this.config};return this.config.withSupabaseClient!==false&&(t.client=this.client,t.token=await this.getAccessToken()),this.project={local:new _s(t),remote:new $s(t)},this}};});async function z(e={}){return await new vs({host:Mr,root:tt.projectDir(),...e}).init()}var Ce=w(()=>{Wo();Go();Op();});var Ip={};de(Ip,{start:()=>qw});var qr,qw,Lp=w(()=>{Ho();lt();qr=ee(ie());Kt();Ce();xe();zt();qw=e=>{e.command("start").option("--config <config>","Path to the config file").description("Start the development server").helpGroup("Local Development:").action(async t=>{await Y(t.config),await Zn(async()=>{let n=await(await z({withSupabaseClient:false})).project.local.createApp(t.config),s=n.config.api?.port??ve.default_api_port;await ys(n,{port:s});console.log(qr.default.green(" \u279C"),"Server running on ",qr.default.cyan(`http://localhost:${s}`));let o=Un();o&&console.log(qr.default.yellow(` \u26A0 ${o}`)),await n.connection.ping();},r=>{console.log(),console.log(qr.default.green(`Ready in ${r.toFixed(2)}ms`));});});};});function Xw(e){let t=normalize(e);return t.length>1&&t[t.length-1]===sep&&(t=t.substring(0,t.length-1)),t}function Mp(e,t){return e.replace(Jw,t)}function Qw(e){return e==="/"||Yw.test(e)}function Yo(e,t){let{resolvePaths:r,normalizePath:n,pathSeparator:s}=t,i=process.platform==="win32"&&e.includes("/")||e.startsWith(".");if(r&&(e=resolve(e)),(n||i)&&(e=Xw(e)),e===".")return "";let o=e[e.length-1]!==s;return Mp(o?e+s:e,s)}function Up(e,t){return t+e}function Zw(e,t){return function(r,n){return n.startsWith(e)?n.slice(e.length)+r:Mp(relative(e,n),t.pathSeparator)+t.pathSeparator+r}}function eb(e){return e}function tb(e,t,r){return t+e+r}function rb(e,t){let{relativePaths:r,includeBasePath:n}=t;return r&&e?Zw(e,t):n?Up:eb}function nb(e){return function(t,r){r.push(t.substring(e.length)||".");}}function sb(e){return function(t,r,n){let s=t.substring(e.length)||".";n.every(i=>i(s,true))&&r.push(s);}}function lb(e,t){let{includeDirs:r,filters:n,relativePaths:s}=t;return r?s?n&&n.length?sb(e):nb(e):n&&n.length?ob:ib:ab}function db(e){let{excludeFiles:t,filters:r,onlyCounts:n}=e;return t?mb:r&&r.length?n?cb:ub:n?pb:fb}function yb(e){return e.group?gb:hb}function Sb(e){return e.group?wb:bb}function _b(e,t){return !e.resolveSymlinks||e.excludeSymlinks?null:t?xb:Eb}function Bp(e,t,r){if(r.options.useRealPaths)return $b(t,r);let n=dirname(e),s=1;for(;n!==r.root&&s<2;){let i=r.symlinks.get(n);!!i&&(i===t||i.startsWith(t)||t.startsWith(i))?s++:n=dirname(n);}return r.symlinks.set(e,t),s>1}function $b(e,t){return t.visited.includes(e+t.options.pathSeparator)}function Ts(e,t,r,n){t(e&&!n?e:null,r);}function Ob(e,t){let{onlyCounts:r,group:n,maxFiles:s}=e;return r?t?vb:Rb:n?t?Tb:Nb:s?t?Cb:Pb:t?Ab:kb}function Db(e){return e?Lb:Ib}function Ub(e,t){return new Promise((r,n)=>{Wp(e,t,(s,i)=>{if(s)return n(s);r(i);});})}function Wp(e,t,r){new Hp(e,t,r).start();}function Bb(e,t){return new Hp(e,t).start()}var Dp,Jw,Yw,ib,ob,ab,cb,ub,pb,fb,mb,hb,gb,wb,bb,Eb,xb,vb,Tb,Ab,Cb,Rb,kb,Pb,Nb,qp,Ib,Lb,jb,Fb,Mb,Hp,jp,Gp,zp,Vp=w(()=>{Dp=createRequire(import.meta.url);Jw=/[\\/]/g;Yw=/^[a-z]:[\\/]$/i;ib=(e,t)=>{t.push(e||".");},ob=(e,t,r)=>{let n=e||".";r.every(s=>s(n,true))&&t.push(n);},ab=()=>{};cb=(e,t,r,n)=>{n.every(s=>s(e,false))&&r.files++;},ub=(e,t,r,n)=>{n.every(s=>s(e,false))&&t.push(e);},pb=(e,t,r,n)=>{r.files++;},fb=(e,t)=>{t.push(e);},mb=()=>{};hb=e=>e,gb=()=>[""].slice(0,0);wb=(e,t,r)=>{e.push({directory:t,files:r,dir:t});},bb=()=>{};Eb=function(e,t,r){let{queue:n,fs:s,options:{suppressErrors:i}}=t;n.enqueue(),s.realpath(e,(o,a)=>{if(o)return n.dequeue(i?null:o,t);s.stat(a,(l,c)=>{if(l)return n.dequeue(i?null:l,t);if(c.isDirectory()&&Bp(e,a,t))return n.dequeue(null,t);r(c,a),n.dequeue(null,t);});});},xb=function(e,t,r){let{queue:n,fs:s,options:{suppressErrors:i}}=t;n.enqueue();try{let o=s.realpathSync(e),a=s.statSync(o);if(a.isDirectory()&&Bp(e,o,t))return;r(a,o);}catch(o){if(!i)throw o}};vb=e=>e.counts,Tb=e=>e.groups,Ab=e=>e.paths,Cb=e=>e.paths.slice(0,e.options.maxFiles),Rb=(e,t,r)=>(Ts(t,r,e.counts,e.options.suppressErrors),null),kb=(e,t,r)=>(Ts(t,r,e.paths,e.options.suppressErrors),null),Pb=(e,t,r)=>(Ts(t,r,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),Nb=(e,t,r)=>(Ts(t,r,e.groups,e.options.suppressErrors),null);qp={withFileTypes:true},Ib=(e,t,r,n,s)=>{if(e.queue.enqueue(),n<0)return e.queue.dequeue(null,e);let{fs:i}=e;e.visited.push(t),e.counts.directories++,i.readdir(t||".",qp,(o,a=[])=>{s(a,r,n),e.queue.dequeue(e.options.suppressErrors?null:o,e);});},Lb=(e,t,r,n,s)=>{let{fs:i}=e;if(n<0)return;e.visited.push(t),e.counts.directories++;let o=[];try{o=i.readdirSync(t||".",qp);}catch(a){if(!e.options.suppressErrors)throw a}s(o,r,n);};jb=class{count=0;constructor(e){this.onQueueEmpty=e;}enqueue(){return this.count++,this.count}dequeue(e,t){this.onQueueEmpty&&(--this.count<=0||e)&&(this.onQueueEmpty(e,t),e&&(t.controller.abort(),this.onQueueEmpty=void 0));}},Fb=class{_files=0;_directories=0;set files(e){this._files=e;}get files(){return this._files}set directories(e){this._directories=e;}get directories(){return this._directories}get dirs(){return this._directories}},Mb=class{aborted=false;abort(){this.aborted=true;}},Hp=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(e,t,r){this.isSynchronous=!r,this.callbackInvoker=Ob(t,this.isSynchronous),this.root=Yo(e,t),this.state={root:Qw(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new Fb,options:t,queue:new jb((n,s)=>this.callbackInvoker(s,n,r)),symlinks:new Map,visited:[""].slice(0,0),controller:new Mb,fs:t.fs||or},this.joinPath=rb(this.root,t),this.pushDirectory=lb(this.root,t),this.pushFile=db(t),this.getArray=yb(t),this.groupFiles=Sb(t),this.resolveSymlink=_b(t,this.isSynchronous),this.walkDirectory=Db(this.isSynchronous);}start(){return this.pushDirectory(this.root,this.state.paths,this.state.options.filters),this.walkDirectory(this.state,this.root,this.root,this.state.options.maxDepth,this.walk),this.isSynchronous?this.callbackInvoker(this.state,null):null}walk=(e,t,r)=>{let{paths:n,options:{filters:s,resolveSymlinks:i,excludeSymlinks:o,exclude:a,maxFiles:l,signal:c,useRealPaths:u,pathSeparator:p},controller:f}=this.state;if(f.aborted||c&&c.aborted||l&&n.length>l)return;let g=this.getArray(this.state.paths);for(let d=0;d<e.length;++d){let m=e[d];if(m.isFile()||m.isSymbolicLink()&&!i&&!o){let y=this.joinPath(m.name,t);this.pushFile(y,g,this.state.counts,s);}else if(m.isDirectory()){let y=tb(m.name,t,this.state.options.pathSeparator);if(a&&a(m.name,y))continue;this.pushDirectory(y,n,s),this.walkDirectory(this.state,y,y,r-1,this.walk);}else if(this.resolveSymlink&&m.isSymbolicLink()){let y=Up(m.name,t);this.resolveSymlink(y,this.state,(h,S)=>{if(h.isDirectory()){if(S=Yo(S,this.state.options),a&&a(m.name,u?S:y+p))return;this.walkDirectory(this.state,S,u?S:y+p,r-1,this.walk);}else {S=u?S:y;let T=basename(S),$=Yo(dirname(S),this.state.options);S=this.joinPath(T,$),this.pushFile(S,g,this.state.counts,s);}});}}this.groupFiles(this.state.groups,t,g);}};jp=class{constructor(e,t){this.root=e,this.options=t;}withPromise(){return Ub(this.root,this.options)}withCallback(e){Wp(this.root,this.options,e);}sync(){return Bb(this.root,this.options)}},Gp=null;try{Dp.resolve("picomatch"),Gp=Dp("picomatch");}catch{}zp=class{globCache={};options={maxDepth:1/0,suppressErrors:true,pathSeparator:sep,filters:[]};globFunction;constructor(e){this.options={...this.options,...e},this.globFunction=this.options.globFunction;}group(){return this.options.group=true,this}withPathSeparator(e){return this.options.pathSeparator=e,this}withBasePath(){return this.options.includeBasePath=true,this}withRelativePaths(){return this.options.relativePaths=true,this}withDirs(){return this.options.includeDirs=true,this}withMaxDepth(e){return this.options.maxDepth=e,this}withMaxFiles(e){return this.options.maxFiles=e,this}withFullPaths(){return this.options.resolvePaths=true,this.options.includeBasePath=true,this}withErrors(){return this.options.suppressErrors=false,this}withSymlinks({resolvePaths:e=true}={}){return this.options.resolveSymlinks=true,this.options.useRealPaths=e,this.withFullPaths()}withAbortSignal(e){return this.options.signal=e,this}normalize(){return this.options.normalizePath=true,this}filter(e){return this.options.filters.push(e),this}onlyDirs(){return this.options.excludeFiles=true,this.options.includeDirs=true,this}exclude(e){return this.options.exclude=e,this}onlyCounts(){return this.options.onlyCounts=true,this}crawl(e){return new jp(e||".",this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new jp(e||".",this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:true})}globWithOptions(e,...t){let r=this.globFunction||Gp;if(!r)throw new Error("Please specify a glob function to use glob matching.");var n=this.globCache[e.join("\0")];return n||(n=r(e,...t),this.globCache[e.join("\0")]=n),this.options.filters.push(s=>n(s)),this}};});var Hr=ot((XC,Qp)=>{var Kp="[^\\\\/]",qb="(?=.)",Xp="[^/]",Zo="(?:\\/|$)",Jp="(?:^|\\/)",ea=`\\.{1,2}${Zo}`,Hb="(?!\\.)",Wb=`(?!${Jp}${ea})`,Gb=`(?!\\.{0,1}${Zo})`,zb=`(?!${ea})`,Vb="[^.\\/]",Kb=`${Xp}*?`,Xb="/",Yp={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:qb,QMARK:Xp,END_ANCHOR:Zo,DOTS_SLASH:ea,NO_DOT:Hb,NO_DOTS:Wb,NO_DOT_SLASH:Gb,NO_DOTS_SLASH:zb,QMARK_NO_DOT:Vb,STAR:Kb,START_ANCHOR:Jp,SEP:Xb},Jb={...Yp,SLASH_LITERAL:"[\\\\/]",QMARK:Kp,STAR:`${Kp}*?`,DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},Yb={alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Qp.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:Yb,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(e){return {"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===true?Jb:Yp}};});var Wr=ot(Ne=>{var{REGEX_BACKSLASH:Qb,REGEX_REMOVE_BACKSLASH:Zb,REGEX_SPECIAL_CHARS:eS,REGEX_SPECIAL_CHARS_GLOBAL:tS}=Hr();Ne.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);Ne.hasRegexChars=e=>eS.test(e);Ne.isRegexChar=e=>e.length===1&&Ne.hasRegexChars(e);Ne.escapeRegex=e=>e.replace(tS,"\\$1");Ne.toPosixSlashes=e=>e.replace(Qb,"/");Ne.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let e=navigator.platform.toLowerCase();return e==="win32"||e==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":false};Ne.removeBackslashes=e=>e.replace(Zb,t=>t==="\\"?"":t);Ne.escapeLast=(e,t,r)=>{let n=e.lastIndexOf(t,r);return n===-1?e:e[n-1]==="\\"?Ne.escapeLast(e,t,n-1):`${e.slice(0,n)}\\${e.slice(n)}`};Ne.removePrefix=(e,t={})=>{let r=e;return r.startsWith("./")&&(r=r.slice(2),t.prefix="./"),r};Ne.wrapOutput=(e,t={},r={})=>{let n=r.contains?"":"^",s=r.contains?"":"$",i=`${n}(?:${e})${s}`;return t.negated===true&&(i=`(?:^(?!${i}).*$)`),i};Ne.basename=(e,{windows:t}={})=>{let r=e.split(t?/[\\/]/:"/"),n=r[r.length-1];return n===""?r[r.length-2]:n};});var af=ot((YC,of)=>{var Zp=Wr(),{CHAR_ASTERISK:ta,CHAR_AT:rS,CHAR_BACKWARD_SLASH:Gr,CHAR_COMMA:nS,CHAR_DOT:ra,CHAR_EXCLAMATION_MARK:na,CHAR_FORWARD_SLASH:sf,CHAR_LEFT_CURLY_BRACE:sa,CHAR_LEFT_PARENTHESES:ia,CHAR_LEFT_SQUARE_BRACKET:sS,CHAR_PLUS:iS,CHAR_QUESTION_MARK:ef,CHAR_RIGHT_CURLY_BRACE:oS,CHAR_RIGHT_PARENTHESES:tf,CHAR_RIGHT_SQUARE_BRACKET:aS}=Hr(),rf=e=>e===sf||e===Gr,nf=e=>{e.isPrefix!==true&&(e.depth=e.isGlobstar?1/0:1);},lS=(e,t)=>{let r=t||{},n=e.length-1,s=r.parts===true||r.scanToEnd===true,i=[],o=[],a=[],l=e,c=-1,u=0,p=0,f=false,g=false,d=false,m=false,y=false,h=false,S=false,T=false,$=false,P=false,N=0,v,_,I={value:"",depth:0,isGlob:false},b=()=>c>=n,D=()=>l.charCodeAt(c+1),R=()=>(v=_,l.charCodeAt(++c));for(;c<n;){_=R();let q;if(_===Gr){S=I.backslashes=true,_=R(),_===sa&&(h=true);continue}if(h===true||_===sa){for(N++;b()!==true&&(_=R());){if(_===Gr){S=I.backslashes=true,R();continue}if(_===sa){N++;continue}if(h!==true&&_===ra&&(_=R())===ra){if(f=I.isBrace=true,d=I.isGlob=true,P=true,s===true)continue;break}if(h!==true&&_===nS){if(f=I.isBrace=true,d=I.isGlob=true,P=true,s===true)continue;break}if(_===oS&&(N--,N===0)){h=false,f=I.isBrace=true,P=true;break}}if(s===true)continue;break}if(_===sf){if(i.push(c),o.push(I),I={value:"",depth:0,isGlob:false},P===true)continue;if(v===ra&&c===u+1){u+=2;continue}p=c+1;continue}if(r.noext!==true&&(_===iS||_===rS||_===ta||_===ef||_===na)===true&&D()===ia){if(d=I.isGlob=true,m=I.isExtglob=true,P=true,_===na&&c===u&&($=true),s===true){for(;b()!==true&&(_=R());){if(_===Gr){S=I.backslashes=true,_=R();continue}if(_===tf){d=I.isGlob=true,P=true;break}}continue}break}if(_===ta){if(v===ta&&(y=I.isGlobstar=true),d=I.isGlob=true,P=true,s===true)continue;break}if(_===ef){if(d=I.isGlob=true,P=true,s===true)continue;break}if(_===sS){for(;b()!==true&&(q=R());){if(q===Gr){S=I.backslashes=true,R();continue}if(q===aS){g=I.isBracket=true,d=I.isGlob=true,P=true;break}}if(s===true)continue;break}if(r.nonegate!==true&&_===na&&c===u){T=I.negated=true,u++;continue}if(r.noparen!==true&&_===ia){if(d=I.isGlob=true,s===true){for(;b()!==true&&(_=R());){if(_===ia){S=I.backslashes=true,_=R();continue}if(_===tf){P=true;break}}continue}break}if(d===true){if(P=true,s===true)continue;break}}r.noext===true&&(m=false,d=false);let F=l,E="",x="";u>0&&(E=l.slice(0,u),l=l.slice(u),p-=u),F&&d===true&&p>0?(F=l.slice(0,p),x=l.slice(p)):d===true?(F="",x=l):F=l,F&&F!==""&&F!=="/"&&F!==l&&rf(F.charCodeAt(F.length-1))&&(F=F.slice(0,-1)),r.unescape===true&&(x&&(x=Zp.removeBackslashes(x)),F&&S===true&&(F=Zp.removeBackslashes(F)));let J={prefix:E,input:e,start:u,base:F,glob:x,isBrace:f,isBracket:g,isGlob:d,isExtglob:m,isGlobstar:y,negated:T,negatedExtglob:$};if(r.tokens===true&&(J.maxDepth=0,rf(_)||o.push(I),J.tokens=o),r.parts===true||r.tokens===true){let q;for(let j=0;j<i.length;j++){let se=q?q+1:u,ce=i[j],it=e.slice(se,ce);r.tokens&&(j===0&&u!==0?(o[j].isPrefix=true,o[j].value=E):o[j].value=it,nf(o[j]),J.maxDepth+=o[j].depth),(j!==0||it!=="")&&a.push(it),q=ce;}if(q&&q+1<e.length){let j=e.slice(q+1);a.push(j),r.tokens&&(o[o.length-1].value=j,nf(o[o.length-1]),J.maxDepth+=o[o.length-1].depth);}J.slashes=i,J.parts=a;}return J};of.exports=lS;});var uf=ot((QC,cf)=>{var As=Hr(),Xe=Wr(),{MAX_LENGTH:Cs,POSIX_REGEX_SOURCE:cS,REGEX_NON_SPECIAL_CHARS:uS,REGEX_SPECIAL_CHARS_BACKREF:pS,REPLACEMENTS:lf}=As,fS=(e,t)=>{if(typeof t.expandRange=="function")return t.expandRange(...e,t);e.sort();let r=`[${e.join("-")}]`;try{new RegExp(r);}catch{return e.map(s=>Xe.escapeRegex(s)).join("..")}return r},ir=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,oa=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=lf[e]||e;let r={...t},n=typeof r.maxLength=="number"?Math.min(Cs,r.maxLength):Cs,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);let i={type:"bos",value:"",output:r.prepend||""},o=[i],a=r.capture?"":"?:",l=As.globChars(r.windows),c=As.extglobChars(l),{DOT_LITERAL:u,PLUS_LITERAL:p,SLASH_LITERAL:f,ONE_CHAR:g,DOTS_SLASH:d,NO_DOT:m,NO_DOT_SLASH:y,NO_DOTS_SLASH:h,QMARK:S,QMARK_NO_DOT:T,STAR:$,START_ANCHOR:P}=l,N=O=>`(${a}(?:(?!${P}${O.dot?d:u}).)*?)`,v=r.dot?"":m,_=r.dot?S:T,I=r.bash===true?N(r):$;r.capture&&(I=`(${I})`),typeof r.noext=="boolean"&&(r.noextglob=r.noext);let b={input:e,index:-1,start:0,dot:r.dot===true,consumed:"",output:"",prefix:"",backtrack:false,negated:false,brackets:0,braces:0,parens:0,quotes:0,globstar:false,tokens:o};e=Xe.removePrefix(e,b),s=e.length;let D=[],R=[],F=[],E=i,x,J=()=>b.index===s-1,q=b.peek=(O=1)=>e[b.index+O],j=b.advance=()=>e[++b.index]||"",se=()=>e.slice(b.index+1),ce=(O="",re=0)=>{b.consumed+=O,b.index+=re;},it=O=>{b.output+=O.output!=null?O.output:O.value,ce(O.value);},Qh=()=>{let O=1;for(;q()==="!"&&(q(2)!=="("||q(3)==="?");)j(),b.start++,O++;return O%2===0?false:(b.negated=true,b.start++,true)},Ln=O=>{b[O]++,F.push(O);},St=O=>{b[O]--,F.pop();},G=O=>{if(E.type==="globstar"){let re=b.braces>0&&(O.type==="comma"||O.type==="brace"),A=O.extglob===true||D.length&&(O.type==="pipe"||O.type==="paren");O.type!=="slash"&&O.type!=="paren"&&!re&&!A&&(b.output=b.output.slice(0,-E.output.length),E.type="star",E.value="*",E.output=I,b.output+=E.output);}if(D.length&&O.type!=="paren"&&(D[D.length-1].inner+=O.value),(O.value||O.output)&&it(O),E&&E.type==="text"&&O.type==="text"){E.output=(E.output||E.value)+O.value,E.value+=O.value;return}O.prev=E,o.push(O),E=O;},Dn=(O,re)=>{let A={...c[re],conditions:1,inner:""};A.prev=E,A.parens=b.parens,A.output=b.output;let W=(r.capture?"(":"")+A.open;Ln("parens"),G({type:O,value:re,output:b.output?"":g}),G({type:"paren",extglob:true,value:j(),output:W}),D.push(A);},Zh=O=>{let re=O.close+(r.capture?")":""),A;if(O.type==="negate"){let W=I;if(O.inner&&O.inner.length>1&&O.inner.includes("/")&&(W=N(r)),(W!==I||J()||/^\)+$/.test(se()))&&(re=O.close=`)$))${W}`),O.inner.includes("*")&&(A=se())&&/^\.[^\\/.]+$/.test(A)){let le=oa(A,{...t,fastpaths:false}).output;re=O.close=`)${le})${W})`;}O.prev.type==="bos"&&(b.negatedExtglob=true);}G({type:"paren",extglob:true,value:x,output:re}),St("parens");};if(r.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let O=false,re=e.replace(pS,(A,W,le,$e,me,Ii)=>$e==="\\"?(O=true,A):$e==="?"?W?W+$e+(me?S.repeat(me.length):""):Ii===0?_+(me?S.repeat(me.length):""):S.repeat(le.length):$e==="."?u.repeat(le.length):$e==="*"?W?W+$e+(me?I:""):I:W?A:`\\${A}`);return O===true&&(r.unescape===true?re=re.replace(/\\/g,""):re=re.replace(/\\+/g,A=>A.length%2===0?"\\\\":A?"\\":"")),re===e&&r.contains===true?(b.output=e,b):(b.output=Xe.wrapOutput(re,b,t),b)}for(;!J();){if(x=j(),x==="\0")continue;if(x==="\\"){let A=q();if(A==="/"&&r.bash!==true||A==="."||A===";")continue;if(!A){x+="\\",G({type:"text",value:x});continue}let W=/^\\+/.exec(se()),le=0;if(W&&W[0].length>2&&(le=W[0].length,b.index+=le,le%2!==0&&(x+="\\")),r.unescape===true?x=j():x+=j(),b.brackets===0){G({type:"text",value:x});continue}}if(b.brackets>0&&(x!=="]"||E.value==="["||E.value==="[^")){if(r.posix!==false&&x===":"){let A=E.value.slice(1);if(A.includes("[")&&(E.posix=true,A.includes(":"))){let W=E.value.lastIndexOf("["),le=E.value.slice(0,W),$e=E.value.slice(W+2),me=cS[$e];if(me){E.value=le+me,b.backtrack=true,j(),!i.output&&o.indexOf(E)===1&&(i.output=g);continue}}}(x==="["&&q()!==":"||x==="-"&&q()==="]")&&(x=`\\${x}`),x==="]"&&(E.value==="["||E.value==="[^")&&(x=`\\${x}`),r.posix===true&&x==="!"&&E.value==="["&&(x="^"),E.value+=x,it({value:x});continue}if(b.quotes===1&&x!=='"'){x=Xe.escapeRegex(x),E.value+=x,it({value:x});continue}if(x==='"'){b.quotes=b.quotes===1?0:1,r.keepQuotes===true&&G({type:"text",value:x});continue}if(x==="("){Ln("parens"),G({type:"paren",value:x});continue}if(x===")"){if(b.parens===0&&r.strictBrackets===true)throw new SyntaxError(ir("opening","("));let A=D[D.length-1];if(A&&b.parens===A.parens+1){Zh(D.pop());continue}G({type:"paren",value:x,output:b.parens?")":"\\)"}),St("parens");continue}if(x==="["){if(r.nobracket===true||!se().includes("]")){if(r.nobracket!==true&&r.strictBrackets===true)throw new SyntaxError(ir("closing","]"));x=`\\${x}`;}else Ln("brackets");G({type:"bracket",value:x});continue}if(x==="]"){if(r.nobracket===true||E&&E.type==="bracket"&&E.value.length===1){G({type:"text",value:x,output:`\\${x}`});continue}if(b.brackets===0){if(r.strictBrackets===true)throw new SyntaxError(ir("opening","["));G({type:"text",value:x,output:`\\${x}`});continue}St("brackets");let A=E.value.slice(1);if(E.posix!==true&&A[0]==="^"&&!A.includes("/")&&(x=`/${x}`),E.value+=x,it({value:x}),r.literalBrackets===false||Xe.hasRegexChars(A))continue;let W=Xe.escapeRegex(E.value);if(b.output=b.output.slice(0,-E.value.length),r.literalBrackets===true){b.output+=W,E.value=W;continue}E.value=`(${a}${W}|${E.value})`,b.output+=E.value;continue}if(x==="{"&&r.nobrace!==true){Ln("braces");let A={type:"brace",value:x,output:"(",outputIndex:b.output.length,tokensIndex:b.tokens.length};R.push(A),G(A);continue}if(x==="}"){let A=R[R.length-1];if(r.nobrace===true||!A){G({type:"text",value:x,output:x});continue}let W=")";if(A.dots===true){let le=o.slice(),$e=[];for(let me=le.length-1;me>=0&&(o.pop(),le[me].type!=="brace");me--)le[me].type!=="dots"&&$e.unshift(le[me].value);W=fS($e,r),b.backtrack=true;}if(A.comma!==true&&A.dots!==true){let le=b.output.slice(0,A.outputIndex),$e=b.tokens.slice(A.tokensIndex);A.value=A.output="\\{",x=W="\\}",b.output=le;for(let me of $e)b.output+=me.output||me.value;}G({type:"brace",value:x,output:W}),St("braces"),R.pop();continue}if(x==="|"){D.length>0&&D[D.length-1].conditions++,G({type:"text",value:x});continue}if(x===","){let A=x,W=R[R.length-1];W&&F[F.length-1]==="braces"&&(W.comma=true,A="|"),G({type:"comma",value:x,output:A});continue}if(x==="/"){if(E.type==="dot"&&b.index===b.start+1){b.start=b.index+1,b.consumed="",b.output="",o.pop(),E=i;continue}G({type:"slash",value:x,output:f});continue}if(x==="."){if(b.braces>0&&E.type==="dot"){E.value==="."&&(E.output=u);let A=R[R.length-1];E.type="dots",E.output+=x,E.value+=x,A.dots=true;continue}if(b.braces+b.parens===0&&E.type!=="bos"&&E.type!=="slash"){G({type:"text",value:x,output:u});continue}G({type:"dot",value:x,output:u});continue}if(x==="?"){if(!(E&&E.value==="(")&&r.noextglob!==true&&q()==="("&&q(2)!=="?"){Dn("qmark",x);continue}if(E&&E.type==="paren"){let W=q(),le=x;(E.value==="("&&!/[!=<:]/.test(W)||W==="<"&&!/<([!=]|\w+>)/.test(se()))&&(le=`\\${x}`),G({type:"text",value:x,output:le});continue}if(r.dot!==true&&(E.type==="slash"||E.type==="bos")){G({type:"qmark",value:x,output:T});continue}G({type:"qmark",value:x,output:S});continue}if(x==="!"){if(r.noextglob!==true&&q()==="("&&(q(2)!=="?"||!/[!=<:]/.test(q(3)))){Dn("negate",x);continue}if(r.nonegate!==true&&b.index===0){Qh();continue}}if(x==="+"){if(r.noextglob!==true&&q()==="("&&q(2)!=="?"){Dn("plus",x);continue}if(E&&E.value==="("||r.regex===false){G({type:"plus",value:x,output:p});continue}if(E&&(E.type==="bracket"||E.type==="paren"||E.type==="brace")||b.parens>0){G({type:"plus",value:x});continue}G({type:"plus",value:p});continue}if(x==="@"){if(r.noextglob!==true&&q()==="("&&q(2)!=="?"){G({type:"at",extglob:true,value:x,output:""});continue}G({type:"text",value:x});continue}if(x!=="*"){(x==="$"||x==="^")&&(x=`\\${x}`);let A=uS.exec(se());A&&(x+=A[0],b.index+=A[0].length),G({type:"text",value:x});continue}if(E&&(E.type==="globstar"||E.star===true)){E.type="star",E.star=true,E.value+=x,E.output=I,b.backtrack=true,b.globstar=true,ce(x);continue}let O=se();if(r.noextglob!==true&&/^\([^?]/.test(O)){Dn("star",x);continue}if(E.type==="star"){if(r.noglobstar===true){ce(x);continue}let A=E.prev,W=A.prev,le=A.type==="slash"||A.type==="bos",$e=W&&(W.type==="star"||W.type==="globstar");if(r.bash===true&&(!le||O[0]&&O[0]!=="/")){G({type:"star",value:x,output:""});continue}let me=b.braces>0&&(A.type==="comma"||A.type==="brace"),Ii=D.length&&(A.type==="pipe"||A.type==="paren");if(!le&&A.type!=="paren"&&!me&&!Ii){G({type:"star",value:x,output:""});continue}for(;O.slice(0,3)==="/**";){let jn=e[b.index+4];if(jn&&jn!=="/")break;O=O.slice(3),ce("/**",3);}if(A.type==="bos"&&J()){E.type="globstar",E.value+=x,E.output=N(r),b.output=E.output,b.globstar=true,ce(x);continue}if(A.type==="slash"&&A.prev.type!=="bos"&&!$e&&J()){b.output=b.output.slice(0,-(A.output+E.output).length),A.output=`(?:${A.output}`,E.type="globstar",E.output=N(r)+(r.strictSlashes?")":"|$)"),E.value+=x,b.globstar=true,b.output+=A.output+E.output,ce(x);continue}if(A.type==="slash"&&A.prev.type!=="bos"&&O[0]==="/"){let jn=O[1]!==void 0?"|$":"";b.output=b.output.slice(0,-(A.output+E.output).length),A.output=`(?:${A.output}`,E.type="globstar",E.output=`${N(r)}${f}|${f}${jn})`,E.value+=x,b.output+=A.output+E.output,b.globstar=true,ce(x+j()),G({type:"slash",value:"/",output:""});continue}if(A.type==="bos"&&O[0]==="/"){E.type="globstar",E.value+=x,E.output=`(?:^|${f}|${N(r)}${f})`,b.output=E.output,b.globstar=true,ce(x+j()),G({type:"slash",value:"/",output:""});continue}b.output=b.output.slice(0,-E.output.length),E.type="globstar",E.output=N(r),E.value+=x,b.output+=E.output,b.globstar=true,ce(x);continue}let re={type:"star",value:x,output:I};if(r.bash===true){re.output=".*?",(E.type==="bos"||E.type==="slash")&&(re.output=v+re.output),G(re);continue}if(E&&(E.type==="bracket"||E.type==="paren")&&r.regex===true){re.output=x,G(re);continue}(b.index===b.start||E.type==="slash"||E.type==="dot")&&(E.type==="dot"?(b.output+=y,E.output+=y):r.dot===true?(b.output+=h,E.output+=h):(b.output+=v,E.output+=v),q()!=="*"&&(b.output+=g,E.output+=g)),G(re);}for(;b.brackets>0;){if(r.strictBrackets===true)throw new SyntaxError(ir("closing","]"));b.output=Xe.escapeLast(b.output,"["),St("brackets");}for(;b.parens>0;){if(r.strictBrackets===true)throw new SyntaxError(ir("closing",")"));b.output=Xe.escapeLast(b.output,"("),St("parens");}for(;b.braces>0;){if(r.strictBrackets===true)throw new SyntaxError(ir("closing","}"));b.output=Xe.escapeLast(b.output,"{"),St("braces");}if(r.strictSlashes!==true&&(E.type==="star"||E.type==="bracket")&&G({type:"maybe_slash",value:"",output:`${f}?`}),b.backtrack===true){b.output="";for(let O of b.tokens)b.output+=O.output!=null?O.output:O.value,O.suffix&&(b.output+=O.suffix);}return b};oa.fastpaths=(e,t)=>{let r={...t},n=typeof r.maxLength=="number"?Math.min(Cs,r.maxLength):Cs,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);e=lf[e]||e;let{DOT_LITERAL:i,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:l,NO_DOT:c,NO_DOTS:u,NO_DOTS_SLASH:p,STAR:f,START_ANCHOR:g}=As.globChars(r.windows),d=r.dot?u:c,m=r.dot?p:c,y=r.capture?"":"?:",h={negated:false,prefix:""},S=r.bash===true?".*?":f;r.capture&&(S=`(${S})`);let T=v=>v.noglobstar===true?S:`(${y}(?:(?!${g}${v.dot?l:i}).)*?)`,$=v=>{switch(v){case "*":return `${d}${a}${S}`;case ".*":return `${i}${a}${S}`;case "*.*":return `${d}${S}${i}${a}${S}`;case "*/*":return `${d}${S}${o}${a}${m}${S}`;case "**":return d+T(r);case "**/*":return `(?:${d}${T(r)}${o})?${m}${a}${S}`;case "**/*.*":return `(?:${d}${T(r)}${o})?${m}${S}${i}${a}${S}`;case "**/.*":return `(?:${d}${T(r)}${o})?${i}${a}${S}`;default:{let _=/^(.*?)\.(\w+)$/.exec(v);if(!_)return;let I=$(_[1]);return I?I+i+_[2]:void 0}}},P=Xe.removePrefix(e,h),N=$(P);return N&&r.strictSlashes!==true&&(N+=`${o}?`),N};cf.exports=oa;});var mf=ot((ZC,ff)=>{var mS=af(),aa=uf(),pf=Wr(),dS=Hr(),hS=e=>e&&typeof e=="object"&&!Array.isArray(e),ue=(e,t,r=false)=>{if(Array.isArray(e)){let u=e.map(f=>ue(f,t,r));return f=>{for(let g of u){let d=g(f);if(d)return d}return false}}let n=hS(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let s=t||{},i=s.windows,o=n?ue.compileRe(e,t):ue.makeRe(e,t,false,true),a=o.state;delete o.state;let l=()=>false;if(s.ignore){let u={...t,ignore:null,onMatch:null,onResult:null};l=ue(s.ignore,u,r);}let c=(u,p=false)=>{let{isMatch:f,match:g,output:d}=ue.test(u,o,t,{glob:e,posix:i}),m={glob:e,state:a,regex:o,posix:i,input:u,output:d,match:g,isMatch:f};return typeof s.onResult=="function"&&s.onResult(m),f===false?(m.isMatch=false,p?m:false):l(u)?(typeof s.onIgnore=="function"&&s.onIgnore(m),m.isMatch=false,p?m:false):(typeof s.onMatch=="function"&&s.onMatch(m),p?m:true)};return r&&(c.state=a),c};ue.test=(e,t,r,{glob:n,posix:s}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return {isMatch:false,output:""};let i=r||{},o=i.format||(s?pf.toPosixSlashes:null),a=e===n,l=a&&o?o(e):e;return a===false&&(l=o?o(e):e,a=l===n),(a===false||i.capture===true)&&(i.matchBase===true||i.basename===true?a=ue.matchBase(e,t,r,s):a=t.exec(l)),{isMatch:!!a,match:a,output:l}};ue.matchBase=(e,t,r)=>(t instanceof RegExp?t:ue.makeRe(t,r)).test(pf.basename(e));ue.isMatch=(e,t,r)=>ue(t,r)(e);ue.parse=(e,t)=>Array.isArray(e)?e.map(r=>ue.parse(r,t)):aa(e,{...t,fastpaths:false});ue.scan=(e,t)=>mS(e,t);ue.compileRe=(e,t,r=false,n=false)=>{if(r===true)return e.output;let s=t||{},i=s.contains?"":"^",o=s.contains?"":"$",a=`${i}(?:${e.output})${o}`;e&&e.negated===true&&(a=`^(?!${a}).*$`);let l=ue.toRegex(a,t);return n===true&&(l.state=e),l};ue.makeRe=(e,t={},r=false,n=false)=>{if(!e||typeof e!="string")throw new TypeError("Expected a non-empty string");let s={negated:false,fastpaths:true};return t.fastpaths!==false&&(e[0]==="."||e[0]==="*")&&(s.output=aa.fastpaths(e,t)),s.output||(s=aa(e,t)),ue.compileRe(s,t,r,n)};ue.toRegex=(e,t)=>{try{let r=t||{};return new RegExp(e,r.flags||(r.nocase?"i":""))}catch(r){if(t&&t.debug===true)throw r;return /$^/}};ue.constants=dS;ff.exports=ue;});var yf=ot((eR,gf)=>{var df=mf(),gS=Wr();function hf(e,t,r=false){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:gS.isWindows()}),df(e,t,r)}Object.assign(hf,df);gf.exports=hf;});function SS(e,t={}){let r=e.length,n=Array(r),s=Array(r),i=!t.noglobstar;for(let o=0;o<r;o++){let a=Ef(e[o]);n[o]=a;let l=a.length,c=Array(l);for(let u=0;u<l;u++)c[u]=(0, lr.default)(a[u],t);s[o]=c;}return o=>{let a=o.split("/");if(a[0]===".."&&bS.test(o))return true;for(let l=0;l<e.length;l++){let c=n[l],u=s[l],p=a.length,f=Math.min(p,c.length),g=0;for(;g<f;){let d=c[g];if(d.includes("/"))return true;if(!u[g](a[g]))break;if(i&&d==="**")return true;g++;}if(g===p)return true}return false}}function wf(e,t,r){if(e===t||t.startsWith(`${e}/`)){if(r){let s=xS(e)?e.length:e.length+1;return (i,o)=>i.slice(s,o?-1:void 0)||"."}let n=t.slice(e.length+1);return n?(s,i)=>{if(s===".")return n;let o=`${n}/${s}`;return i?o.slice(0,-1):o}:(s,i)=>i&&s!=="."?s.slice(0,-1):s}return r?n=>posix.relative(e,n)||".":n=>posix.relative(e,`${t}/${n}`)||"."}function _S(e,t){if(t.startsWith(`${e}/`)){let r=t.slice(e.length+1);return n=>`${r}/${n}`}return r=>{let n=posix.relative(e,`${t}/${r}`);return r.endsWith("/")&&n!==""?`${n}/`:n||"."}}function Ef(e){var t;let r=lr.default.scan(e,$S);return !((t=r.parts)===null||t===void 0)&&t.length?r.parts:[e]}function kS(e,t){let r=lr.default.scan(e);return r.isGlob||r.negated}function ar(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...e);}function la(e,t,r,n,s){let i=e;e.endsWith("/")&&(i=e.slice(0,-1)),!i.endsWith("*")&&t&&(i+="/**");let o=RS(r);bf.isAbsolute(i.replace(NS,""))?i=posix.relative(o,i):i=posix.normalize(i);let a=PS.exec(i),l=Ef(i);if(a?.[0]){let u=(a[0].length+1)/3,p=0,f=o.split("/");for(;p<u&&l[p+u]===f[f.length+p-u];)i=i.slice(0,(u-p-1)*3)+i.slice((u-p)*3+l[p+u].length+1)||".",p++;let g=posix.join(r,a[0].slice(p*3));!g.startsWith(".")&&n.root.length>g.length&&(n.root=g,n.depthOffset=-u+p);}if(!s&&n.depthOffset>=0){var c;(c=n.commonPath)!==null&&c!==void 0||(n.commonPath=l);let u=[],p=Math.min(n.commonPath.length,l.length);for(let f=0;f<p;f++){let g=l[f];if(g==="**"&&!l[f+1]){u.pop();break}if(g!==n.commonPath[f]||kS(g)||f===l.length-1)break;u.push(g);}n.depthOffset=u.length,n.commonPath=u,n.root=u.length>0?posix.join(r,...u):r;}return i}function OS({patterns:e=["**/*"],ignore:t=[],expandDirectories:r=true},n,s){typeof e=="string"&&(e=[e]),typeof t=="string"&&(t=[t]);let i=[],o=[];for(let a of t)a&&(a[0]!=="!"||a[1]==="(")&&o.push(la(a,r,n,s,true));for(let a of e)a&&(a[0]!=="!"||a[1]==="("?i.push(la(a,r,n,s,false)):(a[1]!=="!"||a[2]==="(")&&o.push(la(a.slice(1),r,n,s,true)));return {match:i,ignore:o}}function IS(e,t){for(let r=e.length-1;r>=0;r--){let n=e[r];e[r]=t(n);}return e}function LS(e){return e?e instanceof URL?fileURLToPath$1(e).replace(Rs,"/"):bf.resolve(e).replace(Rs,"/"):process.cwd().replace(Rs,"/")}function DS(e,t={}){let r=process.env.TINYGLOBBY_DEBUG?{...t,debug:true}:t,n=LS(r.cwd);if(r.debug&&ar("globbing with:",{patterns:e,options:r,cwd:n}),Array.isArray(e)&&e.length===0)return [{sync:()=>[],withPromise:async()=>[]},false];let s={root:n,commonPath:null,depthOffset:0},i=OS({...r,patterns:e},n,s);r.debug&&ar("internal processing patterns:",i);let o={dot:r.dot,nobrace:r.braceExpansion===false,nocase:r.caseSensitiveMatch===false,noextglob:r.extglob===false,noglobstar:r.globstar===false,posix:true},a=(0, lr.default)(i.match,{...o,ignore:i.ignore}),l=(0, lr.default)(i.ignore,o),c=SS(i.match,o),u=wf(n,s.root,r.absolute),p=r.absolute?u:wf(n,s.root,true),f={filters:[r.debug?(m,y)=>{let h=u(m,y),S=a(h);return S&&ar(`matched ${h}`),S}:(m,y)=>a(u(m,y))],exclude:r.debug?(m,y)=>{let h=p(y,true),S=h!=="."&&!c(h)||l(h);return ar(S?`skipped ${y}`:`crawling ${y}`),S}:(m,y)=>{let h=p(y,true);return h!=="."&&!c(h)||l(h)},fs:r.fs?{readdir:r.fs.readdir||or__default.readdir,readdirSync:r.fs.readdirSync||or__default.readdirSync,realpath:r.fs.realpath||or__default.realpath,realpathSync:r.fs.realpathSync||or__default.realpathSync,stat:r.fs.stat||or__default.stat,statSync:r.fs.statSync||or__default.statSync}:void 0,pathSeparator:"/",relativePaths:true,resolveSymlinks:true,signal:r.signal};r.deep!==void 0&&(f.maxDepth=Math.round(r.deep-s.depthOffset)),r.absolute&&(f.relativePaths=false,f.resolvePaths=true,f.includeBasePath=true),r.followSymbolicLinks===false&&(f.resolveSymlinks=false,f.excludeSymlinks=true),r.onlyDirectories?(f.excludeFiles=true,f.includeDirs=true):r.onlyFiles===false&&(f.includeDirs=true),s.root=s.root.replace(Rs,"");let g=s.root;r.debug&&ar("internal properties:",s);let d=n!==g&&!r.absolute&&_S(n,s.root);return [new zp(f).crawl(g),d]}async function zr(e,t){if(e&&t?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let r=wS(e)||typeof e=="string",n=r?t:e,s=r?e:e.patterns,[i,o]=DS(s,n);return o?IS(await i.withPromise(),o):i.withPromise()}var lr,wS,Sf,bS,ES,xS,$S,vS,TS,AS,CS,RS,PS,NS,Rs,ca=w(()=>{Vp();lr=ee(yf()),wS=Array.isArray,Sf=process.platform==="win32",bS=/^(\/?\.\.)+$/;ES=/^[A-Z]:\/$/i,xS=Sf?e=>ES.test(e):e=>e==="/";$S={parts:true};vS=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,TS=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,AS=e=>e.replace(vS,"\\$&"),CS=e=>e.replace(TS,"\\$&"),RS=Sf?CS:AS;PS=/^(\/?\.\.)+/,NS=/\\(?=[()[\]{}!*+?@|])/g,Rs=/\\/g;});function Ie(e){return e.dialect==="postgres"?"pg":e.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function ks(e){return e==="sqlite"?{schema_migrations:"migrations",seed_files:"seed_files"}:e==="pg-flat"?{schema_migrations:'"supabase_migrations.schema_migrations"',seed_files:'"supabase_migrations.seed_files"'}:{schema_migrations:"supabase_migrations.schema_migrations",seed_files:"supabase_migrations.seed_files"}}function Vr(e){return `'${e.replace(/'/g,"''")}'`}function jS(e){return `'${`{${e.map(n=>`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function FS(e){return e==="sqlite"?[`CREATE TABLE IF NOT EXISTS migrations (
|
|
63
63
|
version TEXT NOT NULL PRIMARY KEY,
|
|
64
64
|
statements TEXT,
|
|
65
65
|
name TEXT
|
|
66
|
+
)`,`CREATE TABLE IF NOT EXISTS seed_files (
|
|
67
|
+
path TEXT NOT NULL PRIMARY KEY,
|
|
68
|
+
hash TEXT NOT NULL
|
|
66
69
|
)`]:["CREATE SCHEMA IF NOT EXISTS supabase_migrations",`CREATE TABLE IF NOT EXISTS supabase_migrations.schema_migrations (
|
|
67
70
|
version text NOT NULL PRIMARY KEY,
|
|
68
71
|
statements text[],
|
|
@@ -70,21 +73,21 @@ create table test (
|
|
|
70
73
|
)`,`CREATE TABLE IF NOT EXISTS supabase_migrations.seed_files (
|
|
71
74
|
path text NOT NULL PRIMARY KEY,
|
|
72
75
|
hash text NOT NULL
|
|
73
|
-
)`]}function
|
|
74
|
-
`)+";",s=await
|
|
75
|
-
`)}function oa(e=new Date){return e.getUTCFullYear().toString().padStart(4,"0")+(e.getUTCMonth()+1).toString().padStart(2,"0")+e.getUTCDate().toString().padStart(2,"0")+e.getUTCHours().toString().padStart(2,"0")+e.getUTCMinutes().toString().padStart(2,"0")+e.getUTCSeconds().toString().padStart(2,"0")}function aa(e,t=oa()){let r=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return r.length>0?`${t}_${r}.sql`:`${t}.sql`}async function Sf(e,t,r){let n=We__default.join(process.cwd(),"supabase",At(e));ke(n);let s=aa(t,r?.ts),i=We__default.join(n,s);return await pe__default.writeFile(i,"",{flag:"wx"}),i}var kS,Ct=y(()=>{sa();Cs();bt();kS=/^(\d{14})(?:_([^.]+))?\.sql$/;});function zr(e){if("String"in e)return e.String.sval}function Rt(e){return e.map(zr).filter(t=>t!=null)}function kt(e){return e==null?[]:e.List!==void 0?e.List.items||[]:Array.isArray(e)?e:[e]}function ks(e){return QuoteUtils.quoteIdentifier(e)}function sr(e){return Object.keys(e)[0]}function Ef(e){if("A_Const"in e){if(e.A_Const.ival)return e.A_Const.ival.ival;if(e.A_Const.fval)return e.A_Const.fval.fval;if(e.A_Const.sval)return e.A_Const.sval.sval;if(e.A_Const.boolval)return e.A_Const.boolval.boolval;if(e.A_Const.isnull)return null}}var Pt=y(()=>{});function _f(e){let t=e.toLowerCase().trim();if(t.startsWith("_")||t.endsWith("[]"))return "TEXT";let r=OS[t];if(!r)throw new Nt(`Unsupported PostgreSQL type: "${e}"`);return r}function Ps(e){let t=e.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(t)}function Ns(e){let t=e.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(t)}function Os(e){let t=e.toLowerCase();return ["numeric","decimal"].includes(t)}var Nt,B,OS,xf,IS,Is,ir=y(()=>{Pt();Nt=class extends Error{},B=class extends Nt{constructor(r,n){super(n??`Unsupported node type: ${sr(r)}`);this.node=r;}},OS={int2:"INTEGER",smallint:"INTEGER",int4:"INTEGER",integer:"INTEGER",int:"INTEGER",int8:"INTEGER",bigint:"INTEGER",serial:"INTEGER",serial4:"INTEGER",bigserial:"INTEGER",serial8:"INTEGER",smallserial:"INTEGER",serial2:"INTEGER",float4:"REAL",real:"REAL",float8:"REAL","double precision":"REAL",numeric:"REAL",decimal:"REAL",text:"TEXT",varchar:"TEXT","character varying":"TEXT",char:"TEXT",character:"TEXT",bpchar:"TEXT",name:"TEXT",bytea:"BLOB",bool:"INTEGER",boolean:"INTEGER",date:"TEXT",time:"TEXT","time without time zone":"TEXT",timetz:"TEXT","time with time zone":"TEXT",timestamp:"TEXT","timestamp without time zone":"TEXT",timestamptz:"TEXT","timestamp with time zone":"TEXT",interval:"TEXT",json:"TEXT",jsonb:"TEXT",uuid:"TEXT",inet:"TEXT"},xf=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","BETWEEN","NOT BETWEEN","IN","NOT IN","LIKE","NOT LIKE","IS NULL","IS NOT NULL","IS TRUE","IS NOT TRUE","IS FALSE","IS NOT FALSE","IS UNKNOWN","IS NOT UNKNOWN","AND","OR","NOT","->>"];IS={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"error"},AlterSeqStmt:{react:"error"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},Is=new Map(Object.entries(IS));});var je,Vr,la=y(()=>{Pt();ir();je=class extends B{constructor(t,r){super(t,`Unsupported expression: ${r}`);}},Vr=class{deparse(t){if("A_Const"in t){let s=t.A_Const;if(s.boolval!==void 0)return s.boolval.boolval?{}:{$always:false}}let r=Object.keys(t)[0],n=this[r];if(!n)throw new je({[r]:t},`Unsupported expression: ${r}`);return n.call(this,t[r])}deparseValue(t){if("A_Const"in t)return this.A_Const(t.A_Const);if("ColumnRef"in t)return this.ColumnRef(t.ColumnRef);if("FuncCall"in t)return this.FuncCall(t.FuncCall);if("SubLink"in t)return this.SubLink(t.SubLink);if("TypeCast"in t)return this.TypeCast(t.TypeCast);if("A_Expr"in t){let n=this.isJwtAccessor(t.A_Expr);return n||this.A_Expr(t.A_Expr)}if("BoolExpr"in t)return this.BoolExpr(t.BoolExpr);let r=Object.keys(t)[0];throw new je({[r]:t},`deparseValue: ${r}`)}A_Expr(t){if(t.kind==="AEXPR_OP"){let r=t.name?.[0],n=r?zr(r):void 0;if(!n)throw new je({A_Expr:t},"A_Expr missing operator");let s=this.isJwtAccessor(t);if(s)return {[s]:{}};let i=t.lexpr?this.deparseValue(t.lexpr):void 0,o=t.rexpr?this.deparseValue(t.rexpr):void 0,a=this.mapOperator(n);if(!a)throw new je({A_Expr:t},`Unsupported operator: ${n}`);let l=t.rexpr!=null&&"ColumnRef"in t.rexpr;if(typeof i=="string"&&i.startsWith("{{")&&l)return {[o]:{[a]:i}};let c=l&&typeof o=="string"?{$ref:o}:o;return {[i]:{[a]:c}}}if(t.kind==="AEXPR_LIKE"||t.kind==="AEXPR_ILIKE"){let r=t.lexpr?this.deparseValue(t.lexpr):void 0,n=t.rexpr?this.deparseValue(t.rexpr):void 0,i=(t.name?.[0]?zr(t.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[r]:{[i]:n}}}if(t.kind==="AEXPR_IN"){let r=t.lexpr?this.deparseValue(t.lexpr):void 0,n=t.rexpr&&"List"in t.rexpr&&t.rexpr.List.items?t.rexpr.List.items.map(s=>this.deparseValue(s)):[];return {[r]:{$in:n}}}throw new je({A_Expr:t},`A_Expr kind: ${t.kind}`)}BoolExpr(t){let r=t.args??[];switch(t.boolop){case "AND_EXPR":return {$and:r.map(n=>this.deparse(n))};case "OR_EXPR":return {$or:r.map(n=>this.deparse(n))};case "NOT_EXPR":return {$not:this.deparse(r[0])};default:throw new je({BoolExpr:t},`BoolExpr op: ${t.boolop}`)}}NullTest(t){let r=t.arg?this.deparseValue(t.arg):void 0;return t.nulltesttype==="IS_NULL"?{[r]:{$is:null}}:{[r]:{$isNot:null}}}SubLink(t){if(t.subLinkType==="ANY_SUBLINK"){let r=t.testexpr?this.deparseValue(t.testexpr):void 0,n=t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0;return {[r]:{$in:n}}}if(t.subLinkType==="EXISTS_SUBLINK")return {$exists:t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0};if(t.subLinkType==="EXPR_SUBLINK"){let r=t.subselect?t.subselect.SelectStmt:void 0;if(r?.fromClause?.length)return this.SelectStmt(r);if(r?.targetList?.[0]){let n=r.targetList[0],s="ResTarget"in n?n.ResTarget:void 0;if(s?.val){let i=this.deparseValue(s.val);return i}}}throw new je({SubLink:t},`SubLink type: ${t.subLinkType}`)}SelectStmt(t){let{from:r,schema:n,join:s}=this.deparseFromClause(t.fromClause??[]),i=[];for(let f of t.targetList??[]){let g="ResTarget"in f?f.ResTarget:void 0;if(g?.val){let d=this.deparseValue(g.val);Array.isArray(d)?i.push(...d.map(String)):d!=null&&d!==""&&i.push(String(d));}}let o=t.whereClause?this.deparse(t.whereClause):void 0,a=this.deparseSortClause(t.sortClause),l=this.deparseLimit(t.limitCount),c=this.deparseLimit(t.limitOffset),u=this.deparseGroupClause(t.groupClause),p={type:"query",from:r,select:i};return n&&(p.schema=n),Object.keys(s).length>0&&(p.join=s),o&&(p.where=o),a.length>0&&(p.order=a),l!==void 0&&(p.limit=l),c!==void 0&&(p.offset=c),u.length>0&&(p.group=u),p}FuncCall(t){let r=this.isAuthFunc(t.funcname??[]);if(r)return r;throw new je({FuncCall:t},`FuncCall: ${Rt(t.funcname??[]).join(".")}`)}ColumnRef(t){let r=Rt(t.fields??[]);return r.length===1?r[0]:r.join(".")}A_Const(t){if(t.boolval!==void 0)return t.boolval.boolval;if(t.ival!==void 0)return t.ival.ival??0;if(t.fval!==void 0)return parseFloat(t.fval.fval??"0");if(t.sval!==void 0)return t.sval.sval??"";if(t.isnull)return null;throw new je({A_Const:t},"A_Const: unknown variant")}TypeCast(t){if(!t.arg)throw new je({TypeCast:t},"TypeCast: missing arg");return this.deparseValue(t.arg)}BooleanTest(t){let r=t.arg?this.deparseValue(t.arg):void 0;return t.booltesttype==="IS_TRUE"?{[r]:{$eq:true}}:{[r]:{$eq:false}}}deparseFromClause(t){let r={};if(t.length===0)return {from:"",join:r};let n=t[0];if("RangeVar"in n){let s=n.RangeVar;return {from:s.relname??"",schema:s.schemaname,join:r}}if("JoinExpr"in n){let{from:s,schema:i}=this.walkJoinExpr(n.JoinExpr,r);return {from:s,schema:i,join:r}}return {from:"",join:r}}walkJoinExpr(t,r){let n={from:""};if(t.larg)if("RangeVar"in t.larg){let s=t.larg.RangeVar;n={from:s.relname??"",schema:s.schemaname};}else "JoinExpr"in t.larg&&(n=this.walkJoinExpr(t.larg.JoinExpr,r));if(t.rarg&&"RangeVar"in t.rarg){let s=t.rarg.RangeVar,i=s.relname??"",o=s.alias?.aliasname??i,a=t.jointype==="JOIN_LEFT"?"left":"inner",l={from:i,type:a};t.quals&&(l.on=this.deparse(t.quals));let c=o;if(c in r){let u=2;for(;`${c}_${u}`in r;)u++;c=`${c}_${u}`;}r[c]=l;}return n}deparseSortClause(t){if(!t)return [];let r=[];for(let n of t){if(!("SortBy"in n))continue;let s=n.SortBy;if(!s.node)continue;let i=String(this.deparseValue(s.node)),o=s.sortby_dir==="SORTBY_DESC"?"desc":"asc",a={column:i,direction:o};s.sortby_nulls==="SORTBY_NULLS_FIRST"?a.nullsFirst=true:s.sortby_nulls==="SORTBY_NULLS_LAST"&&(a.nullsFirst=false),r.push(a);}return r}deparseLimit(t){if(!t)return;let r=this.deparseValue(t);return typeof r=="number"?r:Number(r)}deparseGroupClause(t){return t?t.map(r=>String(this.deparseValue(r))):[]}isAuthFunc(t){let r=Rt(t);if(r.length===2&&r[0]==="auth"){if(r[1]==="uid")return "{{auth.uid}}";if(r[1]==="jwt")return "{{auth.jwt}}";if(r[1]==="role")return "{{auth.role}}";throw new Error(`Unsupported auth function: "${r.slice(1).join(".")}"`)}return null}isJwtAccessor(t){if(t.kind!=="AEXPR_OP")return null;let r=t.name?.[0]?zr(t.name[0]):void 0;if(r!=="->"&&r!=="->>")return null;let n=t.rexpr&&"A_Const"in t.rexpr?t.rexpr.A_Const.sval?.sval:void 0;if(n===void 0)return null;if(t.lexpr&&"FuncCall"in t.lexpr)return this.isAuthFunc(t.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${n}}}`:null;if(t.lexpr&&"A_Expr"in t.lexpr){let s=this.isJwtAccessor(t.lexpr.A_Expr);if(s)return `${s.slice(0,-2)}.${n}}}`}return null}mapOperator(t){switch(t){case "=":return "$eq";case "<>":case "!=":return "$neq";case ">":return "$gt";case ">=":return "$gte";case "<":return "$lt";case "<=":return "$lte";case "~~":return "$like";case "!~~":return "$notLike";default:return}}};});var Kr,ca=y(()=>{Kr=class e{constructor(t){this.data=t;}appliesTo(t){return this.data.command==="ALL"||this.data.command===t}appliesToRole(t){return this.data.roles.length===0||this.data.roles.includes(t)}toJSON(){return this.data}static fromJSON(t){return new e(t)}};});var Jr,ua=y(()=>{Jr=class extends Error{constructor(r,n,s,i){super(`check constraint "${s}" violated for ${r}.${n}`);this.table=r;this.column=n;this.constraint=s;this.value=i;this.name="CheckConstraintError";}};});var ye,tt=y(()=>{ua();ye=class{context;constructor(t){this.context=t;}get isShimBacked(){return false}checkConstraint(){return null}serialize(t){return t}deserialize(t){return t}validateStorage(t){return {status:"pass",message:null}}validationFail(t,r){return {status:"fail",message:t,action:r}}validationPass(){return {status:"pass",message:null}}isNullish(t){return t==null}toColumnDDL(t){let{includeNullable:r=true}=t??{},n=[],s=this.context.column;n.push(this.quoteIfNeeded(s)),n.push(this.sqliteType),this.context.isPrimaryKey&&n.push("PRIMARY KEY"),this.context.isSerial&&this.context.isPrimaryKey&&n.push("AUTOINCREMENT"),r&&!this.context.nullable&&!this.context.isPrimaryKey&&n.push("NOT NULL"),this.context.isUnique&&!this.context.isPrimaryKey&&n.push("UNIQUE"),this.context.defaultValue!==null&&n.push(`DEFAULT ${this.context.defaultValue}`);let i=this.checkConstraint();return i&&n.push(`CHECK (${i})`),n.join(" ")}checkError(t,r){return new Jr(this.context.table,this.context.column,t,r)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var Ot,Ls=y(()=>{tt();Ot=class extends ye{get sqliteType(){return "INTEGER"}};});var Xr,pa=y(()=>{Ls();Xr=class extends Ot{constructor(t){super({...t,isSerial:true});}};});function LS(e,t){let{precision:r,scale:n}=t,s=10**n,i=10**(r-n);return Math.abs(Math.round(e*s)-e*s)<1e-4&&Math.abs(e)<i}var It,Ds=y(()=>{tt();It=class extends ye{numericPrecision;constructor(t,r){super(t),this.numericPrecision=r;}get isShimBacked(){return this.numericPrecision!==void 0}get sqliteType(){return "REAL"}checkConstraint(){if(this.numericPrecision){let{precision:t,scale:r}=this.numericPrecision,n=this.context.column,s=10**r,i=10**(t-r);return `ABS(ROUND(${n} * ${s}) - ${n} * ${s}) < 0.0001 AND ABS(${n}) < ${i}`}return null}validateStorage(t){if(this.isNullish(t))return this.validationPass();if(typeof t!="number"||!Number.isFinite(t))return this.validationFail("Expected finite number.","Patch rows with finite numbers.");if(this.numericPrecision){let{precision:r,scale:n}=this.numericPrecision;if(!LS(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${r}, ${n}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var oe,Fe=y(()=>{tt();oe=class extends ye{lengthConstraint;constructor(t,r){super(t),this.lengthConstraint=r;}get isShimBacked(){return this.lengthConstraint!==void 0}get sqliteType(){return "TEXT"}checkConstraint(){return this.lengthConstraint!==void 0?`length(${this.context.column}) <= ${this.lengthConstraint}`:null}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"?this.validationFail("Expected text.","Patch rows with text values."):this.lengthConstraint!==void 0&&Array.from(t).length>this.lengthConstraint?this.validationFail(`Exceeds length ${this.lengthConstraint}.`,"Patch rows with shorter text."):this.validationPass()}};});var Yr,fa=y(()=>{tt();Yr=class extends ye{get sqliteType(){return "BLOB"}};});var Qr,ma=y(()=>{tt();Qr=class extends ye{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(t){if(this.isNullish(t))return t;if(t===true||t===1)return 1;if(t===false||t===0)return 0;throw this.checkError("boolean_range",t)}deserialize(t){if(this.isNullish(t)||t===true||t===false)return t;if(typeof t=="number"&&Number.isFinite(t)){if(t===1)return true;if(t===0)return false}return t===1n?true:t===0n?false:t==="1"||t==="true"?true:t==="0"||t==="false"?false:t}validateStorage(t){return this.isNullish(t)?this.validationPass():t===1||t===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function $f(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var Zr,da=y(()=>{tt();Zr=class extends ye{get isShimBacked(){return true}get sqliteType(){return "TEXT"}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR json_valid(${t})`}serialize(t){if(this.isNullish(t))return t;try{return JSON.stringify(t)}catch{throw this.checkError("json_valid",t)}}deserialize(t){if(this.isNullish(t))return t;if(typeof t=="string"){let r=$f(t);return r.ok?r.value:t}return t}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"?this.validationFail("Expected JSON text.","Patch rows with JSON values."):$f(t).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function DS(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return false;let t=new Date(`${e}T00:00:00.000Z`);return !Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}var en,ha=y(()=>{Fe();en=class extends oe{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR date(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!DS(t)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function jS(e){let t=e.match(/^(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?([+-](\d{2}):?(\d{2}))?$/);if(!t)return false;let r=Number(t[1]),n=Number(t[2]),s=t[3]===void 0?0:Number(t[3]),i=t[5]===void 0?null:Number(t[5]),o=t[6]===void 0?null:Number(t[6]),a=i===null||o!==null&&i<=15&&o<=59;return r<=24&&n<=59&&s<=59&&(r!==24||n===0&&s===0)&&a}var tn,ga=y(()=>{Fe();tn=class extends oe{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR time(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!jS(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function FS(e){let t=e.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?(?:Z|([+-](\d{2}):?(\d{2})))?$/);if(!t)return false;let r=Number(t[1]),n=Number(t[2]),s=Number(t[3]),i=Number(t[4]),o=Number(t[5]),a=t[6]===void 0?0:Number(t[6]),l=t[8]===void 0?null:Number(t[8]),c=t[9]===void 0?null:Number(t[9]),u=new Date(Date.UTC(r,n-1,s)),p=u.getUTCFullYear()===r&&u.getUTCMonth()===n-1&&u.getUTCDate()===s,f=i<=24&&o<=59&&a<=59&&(i!==24||o===0&&a===0),g=l===null||c!==null&&l<=15&&c<=59;return p&&f&&g}var rn,ya=y(()=>{Fe();rn=class extends oe{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR datetime(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!FS(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var nn,wa=y(()=>{Fe();nn=class extends oe{get isShimBacked(){return true}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||t.trim().length===0?this.validationFail("Expected interval text.","Patch rows with interval strings."):/^-?\d+(?:\.\d+)?$/.test(t.trim())?this.validationFail("Ambiguous numeric interval.","Patch rows with explicit interval strings."):this.validationPass()}};});var sn,ba=y(()=>{Fe();sn=class extends oe{enumValues;constructor(t,r){super(t),this.enumValues=r;}get isShimBacked(){return true}checkConstraint(){let t=this.context.column,r=this.enumValues.map(n=>`'${n.replace(/'/g,"''")}'`).join(", ");return `${t} IN (${r})`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string"||!this.enumValues.includes(t))throw this.checkError("enum_membership",t);return t}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!this.enumValues.includes(t)?this.validationFail("Invalid enum value.","Patch rows with declared enum values."):this.validationPass()}};});function vf(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var ut,js=y(()=>{tt();ut=class extends ye{elementField;constructor(t,r){super(t),this.elementField=r;}get sqliteType(){return "TEXT"}get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR (json_valid(${t}) AND json_type(${t}) = 'array')`}serialize(t){if(this.isNullish(t))return t;if(!Array.isArray(t))throw this.checkError("array_type",t);return this.elementField?JSON.stringify(t.map(r=>this.elementField.serialize(r))):JSON.stringify(t)}deserialize(t){if(this.isNullish(t))return t;if(typeof t=="string"){let r=vf(t);if(r.ok&&Array.isArray(r.value))return this.elementField?r.value.map(n=>this.elementField.deserialize(n)):r.value}return t}validateStorage(t){if(this.isNullish(t))return this.validationPass();if(typeof t!="string")return this.validationFail("Expected JSON array text.","Patch rows with array values.");let r=vf(t);if(!r.ok)return this.validationFail("Invalid JSON array text.","Patch rows with array values.");if(!Array.isArray(r.value))return this.validationFail("Expected JSON array.","Patch rows with array values.");if(this.elementField)for(let n of r.value){let s=this.elementField.validateStorage(n);if(s.status==="fail")return this.validationFail(`Invalid ${this.elementField.context.pgTypeName} array element.`,s.action??"Patch rows with valid array elements.")}return this.validationPass()}};});function Tf(e){return US.test(e.toLowerCase())}var MS,US,on,Sa=y(()=>{Fe();MS="????????-????-????-????-????????????",US=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;on=class extends oe{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${MS}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let r=t.toLowerCase();if(!Tf(r))throw this.checkError("uuid_format",t);return r}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!Tf(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function BS(e){let t=e.split("/");if(t.length>2)return null;let r=t[0];if(!r)return null;if(t.length===1)return {address:r,prefix:null};let n=t[1];return !n||!/^\d+$/.test(n)?null:{address:r,prefix:Number(n)}}function qS(e){let t=e.split(".");return t.length!==4?false:t.every(r=>{if(!/^\d+$/.test(r))return false;let n=Number(r);return n>=0&&n<=255})}function HS(e){if(!e.includes(":"))return false;try{return new URL(`http://[${e}]/`),!0}catch{return false}}function Af(e){let t=BS(e);return t?qS(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:HS(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var an,Ea=y(()=>{Fe();an=class extends oe{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR (length(${t}) BETWEEN 3 AND 49 AND (instr(${t}, '.') > 0 OR instr(${t}, ':') > 0))`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("inet_format",t);let r=t.trim();if(!Af(r))throw this.checkError("inet_format",t);return r}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!Af(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var ln,xa=y(()=>{Fe();ln=class extends oe{serialize(t){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}deserialize(t){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}toColumnDDL(){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}};});function Lt(e,t){if(t?.isArray){let n=Lt(e,{...t,isArray:false});return new ut(e,n)}if(t?.enumValues)return new sn(e,t.enumValues);let r=e.pgTypeName.toLowerCase().trim();if(r.startsWith("_")||r.endsWith("[]")){let n=r.startsWith("_")?r.slice(1):r.slice(0,-2),s={...e,pgTypeName:n},i=Lt(s);return new ut(e,i)}return GS.has(r)?new Xr(e):WS.has(r)?new Ot(e):JS.has(r)?new Qr(e):XS.has(r)?new Zr(e):eE.has(r)?new en(e):tE.has(r)?new tn(e):rE.has(r)?new rn(e):nE.has(r)?new nn(e):KS.has(r)?new Yr(e):zS.has(r)?new It(e,t?.numericPrecision):YS.has(r)?new on(e):QS.has(r)?new oe(e,63):ZS.has(r)?new an(e):VS.has(r)?new oe(e,t?.lengthConstraint):new ln(e)}var WS,GS,zS,VS,KS,JS,XS,YS,QS,ZS,eE,tE,rE,nE,_a=y(()=>{Ls();pa();Ds();Fe();fa();ma();da();ha();ga();ya();wa();ba();js();Sa();Ea();xa();WS=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),GS=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),zS=new Set(["float4","real","float8","double precision","numeric","decimal"]),VS=new Set(["text","varchar","character varying","char","character","bpchar"]),KS=new Set(["bytea"]),JS=new Set(["bool","boolean"]),XS=new Set(["json","jsonb"]),YS=new Set(["uuid"]),QS=new Set(["name"]),ZS=new Set(["inet"]),eE=new Set(["date"]),tE=new Set(["time","timetz","time without time zone","time with time zone"]),rE=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),nE=new Set(["interval"]);});function $a(e,t="auto"){let r=e.toLowerCase(),n=Fs[r];if(!n)return null;switch(t){case "translate":{if(!n.sqlite)throw new Error(`No SQLite translation for function "${e}"`);return {sqliteExpr:n.sqlite(),jsFn:null}}case "synthetic":{if(!n.js)throw new Error(`No JS implementation for function "${e}"`);return {sqliteExpr:null,jsFn:n.js}}case "auto":return n.js?{sqliteExpr:null,jsFn:n.js}:n.sqlite?{sqliteExpr:n.sqlite(),jsFn:null}:null}}var Cf,Fs,va=y(()=>{Cf="lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))",Fs={gen_random_uuid:{sqlite:()=>Cf,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>Cf,js:()=>crypto.randomUUID()},now:{sqlite:()=>"datetime('now')",js:()=>new Date().toISOString()},current_timestamp:{sqlite:()=>"datetime('now')",js:()=>new Date().toISOString()},current_date:{sqlite:()=>"date('now')",js:()=>new Date().toISOString().split("T")[0]},current_time:{sqlite:()=>"time('now')",js:()=>new Date().toISOString().split("T")[1].replace("Z","")},random:{sqlite:()=>"random()",js:()=>Math.random()},length:{sqlite:()=>"length",js:null},lower:{sqlite:()=>"lower",js:null},upper:{sqlite:()=>"upper",js:null},substr:{sqlite:()=>"substr",js:null},substring:{sqlite:()=>"substr",js:null},trim:{sqlite:()=>"trim",js:null},ltrim:{sqlite:()=>"ltrim",js:null},rtrim:{sqlite:()=>"rtrim",js:null},replace:{sqlite:()=>"replace",js:null},coalesce:{sqlite:()=>"coalesce",js:null},nullif:{sqlite:()=>"nullif",js:null},count:{sqlite:()=>"count",js:null},sum:{sqlite:()=>"sum",js:null},avg:{sqlite:()=>"avg",js:null},min:{sqlite:()=>"min",js:null},max:{sqlite:()=>"max",js:null},localtime:{sqlite:()=>"time('now', 'localtime')",js:null},localtimestamp:{sqlite:()=>"datetime('now', 'localtime')",js:null}};});var cn,Rf=y(()=>{cn=class{table;schema;fields;constructor(t,r="public",n=new Map){this.table=t,this.schema=r,this.fields=n;}get(t){return this.fields.get(t)}has(t){return this.fields.has(t)}set(t,r){this.fields.set(t,r);}columns(){return Array.from(this.fields.keys())}all(){return Array.from(this.fields.values())}serializeRow(t){let r={};for(let[n,s]of Object.entries(t)){let i=this.fields.get(n);r[n]=i?i.serialize(s):s;}return r}deserializeRow(t){let r={};for(let[n,s]of Object.entries(t)){let i=this.fields.get(n);r[n]=i?i.deserialize(s):s;}return r}applyDefaults(t){let r={...t};for(let[n,s]of this.fields)!(n in r)&&s.context.defaultFn&&(r[n]=s.context.defaultFn());return r}};});var kf=y(()=>{tt();ua();Ls();pa();Ds();Fe();fa();ma();da();ha();ga();ya();wa();ba();js();Sa();Ea();xa();_a();va();Rf();});var Oa={};de(Oa,{_resetWarnedMissingToClauseForTests:()=>sE,collectComments:()=>Na,collectEnums:()=>Aa,collectPolicies:()=>Ra,collectSchema:()=>ka,collectTableConstraints:()=>Pa,collectVariables:()=>Ca});function sE(){Ta.clear();}function Aa(e){let t=new Map;for(let r of e.stmts??[]){if(!r.stmt||!("CreateEnumStmt"in r.stmt))continue;let n=r.stmt.CreateEnumStmt,s=Rt(n.typeName??[]).join(".");if(!s||!n.vals)continue;let i=Rt(n.vals);t.set(s.toLowerCase(),i);}return t}function Ca(e){let t=new Map;for(let r of e.stmts??[]){if(!r.stmt||!("VariableSetStmt"in r.stmt))continue;let n=r.stmt.VariableSetStmt,s=n.name,i=Ef(n.args?.[0]??{});t.set(s,{value:i,local:n.is_local});}return t}function Ra(e){let t=new Vr,r=new Set,n=[];for(let s of e.stmts??[])if(s.stmt){if("CreatePolicyStmt"in s.stmt){let i=s.stmt.CreatePolicyStmt,o=i.table?.relname??"",a=i.table?.schemaname,l={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},c=i.cmd_name?l[i.cmd_name]??"ALL":"ALL",u=i.permissive===true,p=[],f=false;for(let w of i.roles??[])if("RoleSpec"in w){let h=w.RoleSpec;h.roletype==="ROLESPEC_PUBLIC"?h.location===-1&&(f=true):h.roletype==="ROLESPEC_CSTRING"&&h.rolename&&p.push(h.rolename);}let g=i.qual?t.deparse(i.qual):void 0,d=i.with_check?t.deparse(i.with_check):void 0;if(f){let w=a?`${a}.${o}`:o,h=i.policy_name??"",S=`${w}::${h}`;if(!Ta.has(S)){Ta.add(S);let T=JSON.stringify(g)+JSON.stringify(d);/\{\{auth\.(uid|jwt|role)/i.test(T)||console.warn(`[supalite] policy "${h}" on "${w}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let m=new Kr({name:i.policy_name??"",table:o,schema:a,command:c,permissive:u,roles:p,using:g,withCheck:d});n.push(m);}if("AlterTableStmt"in s.stmt){let i=s.stmt.AlterTableStmt;if((i.cmds??[]).some(l=>"AlterTableCmd"in l&&(l.AlterTableCmd.subtype==="AT_EnableRowSecurity"||l.AlterTableCmd.subtype==="AT_ForceRowSecurity"))){let l=i.relation?.relname??"";r.add(l);}}}return {policies:n,tables:r}}function ka(e,t){let r=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("CreateStmt"in n.stmt))continue;let s=n.stmt.CreateStmt,i=s.relation?.relname??"",o=s.relation?.schemaname??"public";if(!i)continue;let a=new cn(i,o);for(let l of s.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,u=c.colname;if(!u)continue;let p=c.typeName?.names?.map(R=>R.String?.sval||R.String?.str).filter(Boolean),f=p&&(p.length===2&&p[0]==="pg_catalog"?p[1]:p[0]);if(!f)continue;let g=!!c.typeName?.arrayBounds?.length,d=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],m=R=>d[R]?.A_Const?.ival?.ival??d[R]?.A_Const?.val?.ival?.ival,w={isArray:g};if(Ns(f)&&d.length>0){let R=m(0);typeof R=="number"&&R>0&&(w.lengthConstraint=R);}if(Os(f)&&d.length>=2){let R=m(0),F=m(1);typeof R=="number"&&typeof F=="number"&&R>0&&F>=0&&(w.numericPrecision={precision:R,scale:F});}let h=t.get(f.toLowerCase());h&&(w.enumValues=h);let S=Array.isArray(c.constraints)?c.constraints:[],T=S.some(R=>R.Constraint?.contype==="CONSTR_PRIMARY"),$=Ps(f)||S.some(R=>R.Constraint?.contype==="CONSTR_IDENTITY"),P=S.some(R=>R.Constraint?.contype==="CONSTR_NOTNULL"),N=S.find(R=>R.Constraint?.contype==="CONSTR_UNIQUE"),v=S.find(R=>R.Constraint?.contype==="CONSTR_GENERATED"),_=S.find(R=>R.Constraint?.contype==="CONSTR_FOREIGN"),I=S.find(R=>R.Constraint?.contype==="CONSTR_CHECK"),b;if(_){let R=_.Constraint,F=R.pktable?.relname,E=R.pktable?.schemaname,x=R.pk_attrs?.[0]?.String?.sval;F&&x&&(b={refSchema:E,refTable:F,refColumn:x,constraintName:R.conname||void 0});}let D={schema:o,table:i,column:u,pgTypeName:f,nullable:!P&&!T,defaultValue:null,defaultFn:null,isPrimaryKey:T,isUnique:!!N,isSerial:$,isGenerated:!!v,fkRef:b,hasCheck:!!I,checkConstraintName:I?.Constraint?.conname||void 0,uniqueConstraintName:N?.Constraint?.conname||void 0};a.set(u,Lt(D,w));}r.set(`${o}.${i}`,a);}return r}function Pa(e){let t=[];for(let r of e.stmts??[]){if(!r.stmt||!("CreateStmt"in r.stmt))continue;let n=r.stmt.CreateStmt,s=n.relation?.relname??"",i=n.relation?.schemaname??"public";if(s)for(let o of n.tableElts??[]){if("ColumnDef"in o)continue;let a=o;if(!a.Constraint)continue;let l=a.Constraint,c=l.contype;if(c==="CONSTR_UNIQUE"){let u=(l.keys??[]).map(p=>p.String?.sval??p.String?.str).filter(Boolean);if(u.length===0)continue;t.push({schema:i,table:s,kind:"unique",name:l.conname||void 0,columns:u});}else if(c==="CONSTR_CHECK")t.push({schema:i,table:s,kind:"check",name:l.conname||void 0,columns:[]});else if(c==="CONSTR_FOREIGN"){let u=(l.fk_attrs??[]).map(g=>g.String?.sval??g.String?.str).filter(Boolean),p=(l.pk_attrs??[]).map(g=>g.String?.sval??g.String?.str).filter(Boolean),f=l.pktable?.relname;if(!f)continue;t.push({schema:i,table:s,kind:"foreign_key",name:l.conname||void 0,columns:u,refSchema:l.pktable?.schemaname,refTable:f,refColumns:p});}}}return t}function Na(e){let t=[];for(let r of e.stmts??[]){if(!r.stmt||!("CommentStmt"in r.stmt))continue;let n=r.stmt.CommentStmt,s=n.comment??"";if(!s)continue;let i=n.objtype,o=(n.object?.List?.items??n.object?.items??[]).map(a=>a.String?.sval??a.String?.str).filter(Boolean);if(o.length!==0){if(i==="OBJECT_TABLE"||i==="OBJECT_VIEW"){let[a,l]=o.length>=2?o:["public",o[0]];t.push({schema:a,table:l,text:s});}else if(i==="OBJECT_COLUMN"){let a="public",l,c;o.length>=3?[a,l,c]=o:[l,c]=o,t.push({schema:a,table:l,column:c,text:s});}}}return t}var Ta,Ia=y(()=>{la();Pt();ca();kf();ir();Ta=new Set;});async function pn(e,t){let r=await e.connection.introspect(),n=La(r);await Df(e,{...t,dbHasTables:r.tables.length>0,dbFingerprint:n}),r.tables.length===0&&await Da(e);let s=await e.connection.introspect();Ff(s,e);}async function aE(e){let t=await qr(e.config.db?.seed?.sql_paths??["./seed.sql"],{cwd:We__default.join(process.cwd(),"supabase"),absolute:true});return (await Promise.all(t.map(n=>pe__default.readFile(n,"utf-8")))).flatMap(n=>splitSqlStatements(n))}async function fn(e,t){let r=await aE(e);if(r.length===0)return 0;console.log(M.default.dim("Seeding database..."));try{return await e.connection.transaction(r),r.length}catch(n){let s=t?.recoveryHint??"Fix `supabase/seed.sql`, then run `bun run dev --recreate` to reset and reseed.";throw new Error(`Seed failed and was rolled back: ${String(n.message??n)}
|
|
76
|
-
${
|
|
76
|
+
)`]}function xf(e,t){let{schema_migrations:r}=ks(e),n=t.name===null?"NULL":Vr(t.name),s=e==="pg"?jS(t.statements):Vr(JSON.stringify(t.statements));return `INSERT INTO ${r} (version, statements, name) VALUES (${Vr(t.version)}, ${s}, ${n})`}function MS(e){let{schema_migrations:t}=ks(e);return `SELECT version FROM ${t} ORDER BY version ASC`}function US(e){let{seed_files:t}=ks(e);return t?`SELECT path, hash FROM ${t}`:null}function _f(e,t){let{seed_files:r}=ks(e);return r?`INSERT INTO ${r} (path, hash) VALUES (${Vr(t.path)}, ${Vr(t.hash)}) ON CONFLICT (path) DO UPDATE SET hash = EXCLUDED.hash`:null}async function BS(e,t){if(e.dialect==="postgres"||e.config.ddlDialect==="sqlite")return t;let n=await e.translateDdl(t);return typeof n=="string"?n:n.ddl??t}function qS(e){return e.split(/;\s*(?:\n|$)/).map(t=>t.trim()).filter(t=>t.length>0)}async function kt(e){let t=Ie(e),n=FS(t).map(i=>i.trim()).join(`;
|
|
77
|
+
`)+";",s=await BS(e,n);for(let i of qS(s))await e.exec(i);}async function Kr(e){let t=Ie(e);return ((await e.exec(MS(t)))?.rows??[]).map(n=>n.version)}async function $f(e){let t=Ie(e),r=US(t);return r?((await e.exec(r))?.rows??[]).map(s=>({path:s.path,hash:s.hash})):[]}var Pt=w(()=>{});function Tf(e){return Ie(e.connection)==="sqlite"?"./sqlite-migrations/*.sql":"./migrations/*.sql"}function Nt(e){return ze__default.posix.dirname(Tf(e))}async function Fe(e){let t=ze__default.join(process.cwd(),"supabase"),r=await zr([Tf(e)],{cwd:t,absolute:true}),n=[];for(let s of r){let i=ze__default.basename(s),o=HS.exec(i);if(!o)continue;let a=await pe__default.readFile(s,"utf-8");n.push({version:o[1],name:o[2]??null,filename:i,path:s,sql:a});}return n.sort((s,i)=>s.version.localeCompare(i.version))}async function Ps(e){return (await Fe(e)).map(r=>r.sql).join(`
|
|
78
|
+
`)}function ua(e=new Date){return e.getUTCFullYear().toString().padStart(4,"0")+(e.getUTCMonth()+1).toString().padStart(2,"0")+e.getUTCDate().toString().padStart(2,"0")+e.getUTCHours().toString().padStart(2,"0")+e.getUTCMinutes().toString().padStart(2,"0")+e.getUTCSeconds().toString().padStart(2,"0")}function pa(e,t=ua()){let r=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return r.length>0?`${t}_${r}.sql`:`${t}.sql`}async function Af(e,t,r){let n=ze__default.join(process.cwd(),"supabase",Nt(e));ke(n);let s=pa(t,r?.ts),i=ze__default.join(n,s);return await pe__default.writeFile(i,"",{flag:"wx"}),i}var HS,pt=w(()=>{ca();Pt();xt();HS=/^(\d{14})(?:_([^.]+))?\.sql$/;});function Jr(e){if("String"in e)return e.String.sval}function Ot(e){return e.map(Jr).filter(t=>t!=null)}function It(e){return e==null?[]:e.List!==void 0?e.List.items||[]:Array.isArray(e)?e:[e]}function Ns(e){return QuoteUtils.quoteIdentifier(e)}function cr(e){return Object.keys(e)[0]}function Cf(e){if("A_Const"in e){if(e.A_Const.ival)return e.A_Const.ival.ival;if(e.A_Const.fval)return e.A_Const.fval.fval;if(e.A_Const.sval)return e.A_Const.sval.sval;if(e.A_Const.boolval)return e.A_Const.boolval.boolval;if(e.A_Const.isnull)return null}}var Lt=w(()=>{});function kf(e){let t=e.toLowerCase().trim();if(t.startsWith("_")||t.endsWith("[]"))return "TEXT";let r=zS[t];if(!r)throw new Dt(`Unsupported PostgreSQL type: "${e}"`);return r}function Os(e){let t=e.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(t)}function Is(e){let t=e.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(t)}function Ls(e){let t=e.toLowerCase();return ["numeric","decimal"].includes(t)}var Dt,B,zS,Rf,VS,Ds,ur=w(()=>{Lt();Dt=class extends Error{},B=class extends Dt{constructor(r,n){super(n??`Unsupported node type: ${cr(r)}`);this.node=r;}},zS={int2:"INTEGER",smallint:"INTEGER",int4:"INTEGER",integer:"INTEGER",int:"INTEGER",int8:"INTEGER",bigint:"INTEGER",serial:"INTEGER",serial4:"INTEGER",bigserial:"INTEGER",serial8:"INTEGER",smallserial:"INTEGER",serial2:"INTEGER",float4:"REAL",real:"REAL",float8:"REAL","double precision":"REAL",numeric:"REAL",decimal:"REAL",text:"TEXT",varchar:"TEXT","character varying":"TEXT",char:"TEXT",character:"TEXT",bpchar:"TEXT",name:"TEXT",bytea:"BLOB",bool:"INTEGER",boolean:"INTEGER",date:"TEXT",time:"TEXT","time without time zone":"TEXT",timetz:"TEXT","time with time zone":"TEXT",timestamp:"TEXT","timestamp without time zone":"TEXT",timestamptz:"TEXT","timestamp with time zone":"TEXT",interval:"TEXT",json:"TEXT",jsonb:"TEXT",uuid:"TEXT",inet:"TEXT"},Rf=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","BETWEEN","NOT BETWEEN","IN","NOT IN","LIKE","NOT LIKE","IS NULL","IS NOT NULL","IS TRUE","IS NOT TRUE","IS FALSE","IS NOT FALSE","IS UNKNOWN","IS NOT UNKNOWN","AND","OR","NOT","->>"];VS={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"ignore"},AlterSeqStmt:{react:"ignore"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},PartitionElem:{react:"error"},PartitionCmd:{react:"error"},VariableSetStmt:{react:"ignore"},CompositeTypeStmt:{react:"error"},AlterEnumStmt:{react:"error"},AlterObjectSchemaStmt:{react:"error"},AlterOwnerStmt:{react:"error"},AlterTypeStmt:{react:"error"},AlterFunctionStmt:{react:"error"},AlterDefaultPrivilegesStmt:{react:"error"},GrantStmt:{react:"error"},GrantRoleStmt:{react:"error"},CopyStmt:{react:"error"},CreateCastStmt:{react:"error"},AlterOpFamilyStmt:{react:"error"},AlterOperatorStmt:{react:"error"},TruncateStmt:{react:"error"},A_Indirection:{react:"error"},XmlExpr:{react:"error"},XmlSerialize:{react:"error"},RangeTableSample:{react:"error"},GroupingSet:{react:"error"}},Ds=new Map(Object.entries(VS));});var Me,Yr,fa=w(()=>{Lt();ur();Me=class extends B{constructor(t,r){super(t,`Unsupported expression: ${r}`);}},Yr=class{deparse(t){if("A_Const"in t){let s=t.A_Const;if(s.boolval!==void 0)return s.boolval.boolval?{}:{$always:false}}let r=Object.keys(t)[0],n=this[r];if(!n)throw new Me({[r]:t},`Unsupported expression: ${r}`);return n.call(this,t[r])}deparseValue(t){if("A_Const"in t)return this.A_Const(t.A_Const);if("ColumnRef"in t)return this.ColumnRef(t.ColumnRef);if("FuncCall"in t)return this.FuncCall(t.FuncCall);if("SubLink"in t)return this.SubLink(t.SubLink);if("TypeCast"in t)return this.TypeCast(t.TypeCast);if("A_Expr"in t){let n=this.isJwtAccessor(t.A_Expr);return n||this.A_Expr(t.A_Expr)}if("BoolExpr"in t)return this.BoolExpr(t.BoolExpr);let r=Object.keys(t)[0];throw new Me({[r]:t},`deparseValue: ${r}`)}A_Expr(t){if(t.kind==="AEXPR_OP"){let r=t.name?.[0],n=r?Jr(r):void 0;if(!n)throw new Me({A_Expr:t},"A_Expr missing operator");let s=this.isJwtAccessor(t);if(s)return {[s]:{}};let i=t.lexpr?this.deparseValue(t.lexpr):void 0,o=t.rexpr?this.deparseValue(t.rexpr):void 0,a=this.mapOperator(n);if(!a)throw new Me({A_Expr:t},`Unsupported operator: ${n}`);let l=t.rexpr!=null&&"ColumnRef"in t.rexpr;if(typeof i=="string"&&i.startsWith("{{")&&l)return {[o]:{[a]:i}};let c=l&&typeof o=="string"?{$ref:o}:o;return {[i]:{[a]:c}}}if(t.kind==="AEXPR_LIKE"||t.kind==="AEXPR_ILIKE"){let r=t.lexpr?this.deparseValue(t.lexpr):void 0,n=t.rexpr?this.deparseValue(t.rexpr):void 0,i=(t.name?.[0]?Jr(t.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[r]:{[i]:n}}}if(t.kind==="AEXPR_IN"){let r=t.lexpr?this.deparseValue(t.lexpr):void 0,n=t.rexpr&&"List"in t.rexpr&&t.rexpr.List.items?t.rexpr.List.items.map(s=>this.deparseValue(s)):[];return {[r]:{$in:n}}}throw new Me({A_Expr:t},`A_Expr kind: ${t.kind}`)}BoolExpr(t){let r=t.args??[];switch(t.boolop){case "AND_EXPR":return {$and:r.map(n=>this.deparse(n))};case "OR_EXPR":return {$or:r.map(n=>this.deparse(n))};case "NOT_EXPR":return {$not:this.deparse(r[0])};default:throw new Me({BoolExpr:t},`BoolExpr op: ${t.boolop}`)}}NullTest(t){let r=t.arg?this.deparseValue(t.arg):void 0;return t.nulltesttype==="IS_NULL"?{[r]:{$is:null}}:{[r]:{$isNot:null}}}SubLink(t){if(t.subLinkType==="ANY_SUBLINK"){let r=t.testexpr?this.deparseValue(t.testexpr):void 0,n=t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0;return {[r]:{$in:n}}}if(t.subLinkType==="EXISTS_SUBLINK")return {$exists:t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0};if(t.subLinkType==="EXPR_SUBLINK"){let r=t.subselect?t.subselect.SelectStmt:void 0;if(r?.fromClause?.length)return this.SelectStmt(r);if(r?.targetList?.[0]){let n=r.targetList[0],s="ResTarget"in n?n.ResTarget:void 0;if(s?.val){let i=this.deparseValue(s.val);return i}}}throw new Me({SubLink:t},`SubLink type: ${t.subLinkType}`)}SelectStmt(t){let{from:r,schema:n,join:s}=this.deparseFromClause(t.fromClause??[]),i=[];for(let f of t.targetList??[]){let g="ResTarget"in f?f.ResTarget:void 0;if(g?.val){let d=this.deparseValue(g.val);Array.isArray(d)?i.push(...d.map(String)):d!=null&&d!==""&&i.push(String(d));}}let o=t.whereClause?this.deparse(t.whereClause):void 0,a=this.deparseSortClause(t.sortClause),l=this.deparseLimit(t.limitCount),c=this.deparseLimit(t.limitOffset),u=this.deparseGroupClause(t.groupClause),p={type:"query",from:r,select:i};return n&&(p.schema=n),Object.keys(s).length>0&&(p.join=s),o&&(p.where=o),a.length>0&&(p.order=a),l!==void 0&&(p.limit=l),c!==void 0&&(p.offset=c),u.length>0&&(p.group=u),p}FuncCall(t){let r=this.isAuthFunc(t.funcname??[]);if(r)return r;throw new Me({FuncCall:t},`FuncCall: ${Ot(t.funcname??[]).join(".")}`)}ColumnRef(t){let r=Ot(t.fields??[]);return r.length===1?r[0]:r.join(".")}A_Const(t){if(t.boolval!==void 0)return t.boolval.boolval;if(t.ival!==void 0)return t.ival.ival??0;if(t.fval!==void 0)return parseFloat(t.fval.fval??"0");if(t.sval!==void 0)return t.sval.sval??"";if(t.isnull)return null;throw new Me({A_Const:t},"A_Const: unknown variant")}TypeCast(t){if(!t.arg)throw new Me({TypeCast:t},"TypeCast: missing arg");return this.deparseValue(t.arg)}BooleanTest(t){let r=t.arg?this.deparseValue(t.arg):void 0;return t.booltesttype==="IS_TRUE"?{[r]:{$eq:true}}:{[r]:{$eq:false}}}deparseFromClause(t){let r={};if(t.length===0)return {from:"",join:r};let n=t[0];if("RangeVar"in n){let s=n.RangeVar;return {from:s.relname??"",schema:s.schemaname,join:r}}if("JoinExpr"in n){let{from:s,schema:i}=this.walkJoinExpr(n.JoinExpr,r);return {from:s,schema:i,join:r}}return {from:"",join:r}}walkJoinExpr(t,r){let n={from:""};if(t.larg)if("RangeVar"in t.larg){let s=t.larg.RangeVar;n={from:s.relname??"",schema:s.schemaname};}else "JoinExpr"in t.larg&&(n=this.walkJoinExpr(t.larg.JoinExpr,r));if(t.rarg&&"RangeVar"in t.rarg){let s=t.rarg.RangeVar,i=s.relname??"",o=s.alias?.aliasname??i,a=t.jointype==="JOIN_LEFT"?"left":"inner",l={from:i,type:a};t.quals&&(l.on=this.deparse(t.quals));let c=o;if(c in r){let u=2;for(;`${c}_${u}`in r;)u++;c=`${c}_${u}`;}r[c]=l;}return n}deparseSortClause(t){if(!t)return [];let r=[];for(let n of t){if(!("SortBy"in n))continue;let s=n.SortBy;if(!s.node)continue;let i=String(this.deparseValue(s.node)),o=s.sortby_dir==="SORTBY_DESC"?"desc":"asc",a={column:i,direction:o};s.sortby_nulls==="SORTBY_NULLS_FIRST"?a.nullsFirst=true:s.sortby_nulls==="SORTBY_NULLS_LAST"&&(a.nullsFirst=false),r.push(a);}return r}deparseLimit(t){if(!t)return;let r=this.deparseValue(t);return typeof r=="number"?r:Number(r)}deparseGroupClause(t){return t?t.map(r=>String(this.deparseValue(r))):[]}isAuthFunc(t){let r=Ot(t);if(r.length===2&&r[0]==="auth"){if(r[1]==="uid")return "{{auth.uid}}";if(r[1]==="jwt")return "{{auth.jwt}}";if(r[1]==="role")return "{{auth.role}}";throw new Error(`Unsupported auth function: "${r.slice(1).join(".")}"`)}return null}isJwtAccessor(t){if(t.kind!=="AEXPR_OP")return null;let r=t.name?.[0]?Jr(t.name[0]):void 0;if(r!=="->"&&r!=="->>")return null;let n=t.rexpr&&"A_Const"in t.rexpr?t.rexpr.A_Const.sval?.sval:void 0;if(n===void 0)return null;if(t.lexpr&&"FuncCall"in t.lexpr)return this.isAuthFunc(t.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${n}}}`:null;if(t.lexpr&&"A_Expr"in t.lexpr){let s=this.isJwtAccessor(t.lexpr.A_Expr);if(s)return `${s.slice(0,-2)}.${n}}}`}return null}mapOperator(t){switch(t){case "=":return "$eq";case "<>":case "!=":return "$neq";case ">":return "$gt";case ">=":return "$gte";case "<":return "$lt";case "<=":return "$lte";case "~~":return "$like";case "!~~":return "$notLike";default:return}}};});var Qr,ma=w(()=>{Qr=class e{constructor(t){this.data=t;}appliesTo(t){return this.data.command==="ALL"||this.data.command===t}appliesToRole(t){return this.data.roles.length===0||this.data.roles.includes(t)}toJSON(){return this.data}static fromJSON(t){return new e(t)}};});var Zr,da=w(()=>{Zr=class extends Error{constructor(r,n,s,i){super(`check constraint "${s}" violated for ${r}.${n}`);this.table=r;this.column=n;this.constraint=s;this.value=i;this.name="CheckConstraintError";}};});var we,rt=w(()=>{da();we=class{context;constructor(t){this.context=t;}get isShimBacked(){return false}checkConstraint(){return null}serialize(t){return t}deserialize(t){return t}validateStorage(t){return {status:"pass",message:null}}validationFail(t,r){return {status:"fail",message:t,action:r}}validationPass(){return {status:"pass",message:null}}isNullish(t){return t==null}toColumnDDL(t){let{includeNullable:r=true}=t??{},n=[],s=this.context.column;n.push(this.quoteIfNeeded(s)),n.push(this.sqliteType),this.context.isPrimaryKey&&n.push("PRIMARY KEY"),this.context.isSerial&&this.context.isPrimaryKey&&n.push("AUTOINCREMENT"),r&&!this.context.nullable&&!this.context.isPrimaryKey&&n.push("NOT NULL"),this.context.isUnique&&!this.context.isPrimaryKey&&n.push("UNIQUE"),this.context.defaultValue!==null&&n.push(`DEFAULT ${this.context.defaultValue}`);let i=this.checkConstraint();return i&&n.push(`CHECK (${i})`),n.join(" ")}checkError(t,r){return new Zr(this.context.table,this.context.column,t,r)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var jt,js=w(()=>{rt();jt=class extends we{get sqliteType(){return "INTEGER"}};});var en,ha=w(()=>{js();en=class extends jt{constructor(t){super({...t,isSerial:true});}};});function KS(e,t){let{precision:r,scale:n}=t,s=10**n,i=10**(r-n);return Math.abs(Math.round(e*s)-e*s)<1e-4&&Math.abs(e)<i}var Ft,Fs=w(()=>{rt();Ft=class extends we{numericPrecision;constructor(t,r){super(t),this.numericPrecision=r;}get isShimBacked(){return this.numericPrecision!==void 0}get sqliteType(){return "REAL"}checkConstraint(){if(this.numericPrecision){let{precision:t,scale:r}=this.numericPrecision,n=this.context.column,s=10**r,i=10**(t-r);return `ABS(ROUND(${n} * ${s}) - ${n} * ${s}) < 0.0001 AND ABS(${n}) < ${i}`}return null}validateStorage(t){if(this.isNullish(t))return this.validationPass();if(typeof t!="number"||!Number.isFinite(t))return this.validationFail("Expected finite number.","Patch rows with finite numbers.");if(this.numericPrecision){let{precision:r,scale:n}=this.numericPrecision;if(!KS(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${r}, ${n}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var oe,Ue=w(()=>{rt();oe=class extends we{lengthConstraint;constructor(t,r){super(t),this.lengthConstraint=r;}get isShimBacked(){return this.lengthConstraint!==void 0}get sqliteType(){return "TEXT"}checkConstraint(){return this.lengthConstraint!==void 0?`length(${this.context.column}) <= ${this.lengthConstraint}`:null}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"?this.validationFail("Expected text.","Patch rows with text values."):this.lengthConstraint!==void 0&&Array.from(t).length>this.lengthConstraint?this.validationFail(`Exceeds length ${this.lengthConstraint}.`,"Patch rows with shorter text."):this.validationPass()}};});var tn,ga=w(()=>{rt();tn=class extends we{get sqliteType(){return "BLOB"}};});var rn,ya=w(()=>{rt();rn=class extends we{get isShimBacked(){return true}get sqliteType(){return "INTEGER"}checkConstraint(){return `${this.context.column} IN (0, 1)`}serialize(t){if(this.isNullish(t))return t;if(t===true||t===1)return 1;if(t===false||t===0)return 0;throw this.checkError("boolean_range",t)}deserialize(t){if(this.isNullish(t)||t===true||t===false)return t;if(typeof t=="number"&&Number.isFinite(t)){if(t===1)return true;if(t===0)return false}return t===1n?true:t===0n?false:t==="1"||t==="true"?true:t==="0"||t==="false"?false:t}validateStorage(t){return this.isNullish(t)?this.validationPass():t===1||t===0?this.validationPass():this.validationFail("Expected 0 or 1.","Patch rows with boolean values.")}};});function Pf(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var nn,wa=w(()=>{rt();nn=class extends we{get isShimBacked(){return true}get sqliteType(){return "TEXT"}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR json_valid(${t})`}serialize(t){if(this.isNullish(t))return t;try{return JSON.stringify(t)}catch{throw this.checkError("json_valid",t)}}deserialize(t){if(this.isNullish(t))return t;if(typeof t=="string"){let r=Pf(t);return r.ok?r.value:t}return t}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"?this.validationFail("Expected JSON text.","Patch rows with JSON values."):Pf(t).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function XS(e){if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return false;let t=new Date(`${e}T00:00:00.000Z`);return !Number.isNaN(t.getTime())&&t.toISOString().slice(0,10)===e}var sn,ba=w(()=>{Ue();sn=class extends oe{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR date(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!XS(t)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function JS(e){let t=e.match(/^(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?([+-](\d{2}):?(\d{2}))?$/);if(!t)return false;let r=Number(t[1]),n=Number(t[2]),s=t[3]===void 0?0:Number(t[3]),i=t[5]===void 0?null:Number(t[5]),o=t[6]===void 0?null:Number(t[6]),a=i===null||o!==null&&i<=15&&o<=59;return r<=24&&n<=59&&s<=59&&(r!==24||n===0&&s===0)&&a}var on,Sa=w(()=>{Ue();on=class extends oe{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR time(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!JS(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function YS(e){let t=e.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?(?:Z|([+-](\d{2}):?(\d{2})))?$/);if(!t)return false;let r=Number(t[1]),n=Number(t[2]),s=Number(t[3]),i=Number(t[4]),o=Number(t[5]),a=t[6]===void 0?0:Number(t[6]),l=t[8]===void 0?null:Number(t[8]),c=t[9]===void 0?null:Number(t[9]),u=new Date(Date.UTC(r,n-1,s)),p=u.getUTCFullYear()===r&&u.getUTCMonth()===n-1&&u.getUTCDate()===s,f=i<=24&&o<=59&&a<=59&&(i!==24||o===0&&a===0),g=l===null||c!==null&&l<=15&&c<=59;return p&&f&&g}var an,Ea=w(()=>{Ue();an=class extends oe{get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR datetime(${t}) IS NOT NULL`}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!YS(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var ln,xa=w(()=>{Ue();ln=class extends oe{get isShimBacked(){return true}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||t.trim().length===0?this.validationFail("Expected interval text.","Patch rows with interval strings."):/^-?\d+(?:\.\d+)?$/.test(t.trim())?this.validationFail("Ambiguous numeric interval.","Patch rows with explicit interval strings."):this.validationPass()}};});var cn,_a=w(()=>{Ue();cn=class extends oe{enumValues;constructor(t,r){super(t),this.enumValues=r;}get isShimBacked(){return true}checkConstraint(){let t=this.context.column,r=this.enumValues.map(n=>`'${n.replace(/'/g,"''")}'`).join(", ");return `${t} IN (${r})`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string"||!this.enumValues.includes(t))throw this.checkError("enum_membership",t);return t}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!this.enumValues.includes(t)?this.validationFail("Invalid enum value.","Patch rows with declared enum values."):this.validationPass()}};});function Nf(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var ft,Ms=w(()=>{rt();ft=class extends we{elementField;constructor(t,r){super(t),this.elementField=r;}get sqliteType(){return "TEXT"}get isShimBacked(){return true}checkConstraint(){let t=this.context.column;return `${t} IS NULL OR (json_valid(${t}) AND json_type(${t}) = 'array')`}serialize(t){if(this.isNullish(t))return t;if(!Array.isArray(t))throw this.checkError("array_type",t);return this.elementField?JSON.stringify(t.map(r=>this.elementField.serialize(r))):JSON.stringify(t)}deserialize(t){if(this.isNullish(t))return t;if(typeof t=="string"){let r=Nf(t);if(r.ok&&Array.isArray(r.value))return this.elementField?r.value.map(n=>this.elementField.deserialize(n)):r.value}return t}validateStorage(t){if(this.isNullish(t))return this.validationPass();if(typeof t!="string")return this.validationFail("Expected JSON array text.","Patch rows with array values.");let r=Nf(t);if(!r.ok)return this.validationFail("Invalid JSON array text.","Patch rows with array values.");if(!Array.isArray(r.value))return this.validationFail("Expected JSON array.","Patch rows with array values.");if(this.elementField)for(let n of r.value){let s=this.elementField.validateStorage(n);if(s.status==="fail")return this.validationFail(`Invalid ${this.elementField.context.pgTypeName} array element.`,s.action??"Patch rows with valid array elements.")}return this.validationPass()}};});function Of(e){return ZS.test(e.toLowerCase())}var QS,ZS,un,$a=w(()=>{Ue();QS="????????-????-????-????-????????????",ZS=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;un=class extends oe{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${QS}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let r=t.toLowerCase();if(!Of(r))throw this.checkError("uuid_format",t);return r}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!Of(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function eE(e){let t=e.split("/");if(t.length>2)return null;let r=t[0];if(!r)return null;if(t.length===1)return {address:r,prefix:null};let n=t[1];return !n||!/^\d+$/.test(n)?null:{address:r,prefix:Number(n)}}function tE(e){let t=e.split(".");return t.length!==4?false:t.every(r=>{if(!/^\d+$/.test(r))return false;let n=Number(r);return n>=0&&n<=255})}function rE(e){if(!e.includes(":"))return false;try{return new URL(`http://[${e}]/`),!0}catch{return false}}function If(e){let t=eE(e);return t?tE(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:rE(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var pn,va=w(()=>{Ue();pn=class extends oe{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR (length(${t}) BETWEEN 3 AND 49 AND (instr(${t}, '.') > 0 OR instr(${t}, ':') > 0))`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("inet_format",t);let r=t.trim();if(!If(r))throw this.checkError("inet_format",t);return r}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!If(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var fn,Ta=w(()=>{Ue();fn=class extends oe{serialize(t){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}deserialize(t){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}toColumnDDL(){throw new Error(`Unsupported type "${this.context.pgTypeName}" for ${this.context.table}.${this.context.column}`)}};});function Mt(e,t){if(t?.isArray){let n=Mt(e,{...t,isArray:false});return new ft(e,n)}if(t?.enumValues)return new cn(e,t.enumValues);let r=e.pgTypeName.toLowerCase().trim();if(r.startsWith("_")||r.endsWith("[]")){let n=r.startsWith("_")?r.slice(1):r.slice(0,-2),s={...e,pgTypeName:n},i=Mt(s);return new ft(e,i)}return sE.has(r)?new en(e):nE.has(r)?new jt(e):lE.has(r)?new rn(e):cE.has(r)?new nn(e):mE.has(r)?new sn(e):dE.has(r)?new on(e):hE.has(r)?new an(e):gE.has(r)?new ln(e):aE.has(r)?new tn(e):iE.has(r)?new Ft(e,t?.numericPrecision):uE.has(r)?new un(e):pE.has(r)?new oe(e,63):fE.has(r)?new pn(e):oE.has(r)?new oe(e,t?.lengthConstraint):new fn(e)}var nE,sE,iE,oE,aE,lE,cE,uE,pE,fE,mE,dE,hE,gE,Aa=w(()=>{js();ha();Fs();Ue();ga();ya();wa();ba();Sa();Ea();xa();_a();Ms();$a();va();Ta();nE=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),sE=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),iE=new Set(["float4","real","float8","double precision","numeric","decimal"]),oE=new Set(["text","varchar","character varying","char","character","bpchar"]),aE=new Set(["bytea"]),lE=new Set(["bool","boolean"]),cE=new Set(["json","jsonb"]),uE=new Set(["uuid"]),pE=new Set(["name"]),fE=new Set(["inet"]),mE=new Set(["date"]),dE=new Set(["time","timetz","time without time zone","time with time zone"]),hE=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),gE=new Set(["interval"]);});function Ca(e,t="auto"){let r=e.toLowerCase(),n=Us[r];if(!n)return null;switch(t){case "translate":{if(!n.sqlite)throw new Error(`No SQLite translation for function "${e}"`);return {sqliteExpr:n.sqlite(),jsFn:null}}case "synthetic":{if(!n.js)throw new Error(`No JS implementation for function "${e}"`);return {sqliteExpr:null,jsFn:n.js}}case "auto":return n.js?{sqliteExpr:null,jsFn:n.js}:n.sqlite?{sqliteExpr:n.sqlite(),jsFn:null}:null}}var Lf,Us,Ra=w(()=>{Lf="lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))",Us={gen_random_uuid:{sqlite:()=>Lf,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>Lf,js:()=>crypto.randomUUID()},now:{sqlite:()=>"datetime('now')",js:()=>new Date().toISOString()},current_timestamp:{sqlite:()=>"datetime('now')",js:()=>new Date().toISOString()},current_date:{sqlite:()=>"date('now')",js:()=>new Date().toISOString().split("T")[0]},current_time:{sqlite:()=>"time('now')",js:()=>new Date().toISOString().split("T")[1].replace("Z","")},random:{sqlite:()=>"random()",js:()=>Math.random()},length:{sqlite:()=>"length",js:null},lower:{sqlite:()=>"lower",js:null},upper:{sqlite:()=>"upper",js:null},substr:{sqlite:()=>"substr",js:null},substring:{sqlite:()=>"substr",js:null},trim:{sqlite:()=>"trim",js:null},ltrim:{sqlite:()=>"ltrim",js:null},rtrim:{sqlite:()=>"rtrim",js:null},replace:{sqlite:()=>"replace",js:null},coalesce:{sqlite:()=>"coalesce",js:null},nullif:{sqlite:()=>"nullif",js:null},count:{sqlite:()=>"count",js:null},sum:{sqlite:()=>"sum",js:null},avg:{sqlite:()=>"avg",js:null},min:{sqlite:()=>"min",js:null},max:{sqlite:()=>"max",js:null},localtime:{sqlite:()=>"time('now', 'localtime')",js:null},localtimestamp:{sqlite:()=>"datetime('now', 'localtime')",js:null}};});var mn,Df=w(()=>{mn=class{table;schema;fields;constructor(t,r="public",n=new Map){this.table=t,this.schema=r,this.fields=n;}get(t){return this.fields.get(t)}has(t){return this.fields.has(t)}set(t,r){this.fields.set(t,r);}columns(){return Array.from(this.fields.keys())}all(){return Array.from(this.fields.values())}serializeRow(t){let r={};for(let[n,s]of Object.entries(t)){let i=this.fields.get(n);r[n]=i?i.serialize(s):s;}return r}deserializeRow(t){let r={};for(let[n,s]of Object.entries(t)){let i=this.fields.get(n);r[n]=i?i.deserialize(s):s;}return r}applyDefaults(t){let r={...t};for(let[n,s]of this.fields)!(n in r)&&s.context.defaultFn&&(r[n]=s.context.defaultFn());return r}};});var jf=w(()=>{rt();da();js();ha();Fs();Ue();ga();ya();wa();ba();Sa();Ea();xa();_a();Ms();$a();va();Ta();Aa();Ra();Df();});var ja={};de(ja,{_resetWarnedMissingToClauseForTests:()=>yE,collectComments:()=>Da,collectEnums:()=>Pa,collectPolicies:()=>Oa,collectSchema:()=>Ia,collectTableConstraints:()=>La,collectVariables:()=>Na});function yE(){ka.clear();}function Pa(e){let t=new Map;for(let r of e.stmts??[]){if(!r.stmt||!("CreateEnumStmt"in r.stmt))continue;let n=r.stmt.CreateEnumStmt,s=Ot(n.typeName??[]).join(".");if(!s||!n.vals)continue;let i=Ot(n.vals);t.set(s.toLowerCase(),i);}return t}function Na(e){let t=new Map;for(let r of e.stmts??[]){if(!r.stmt||!("VariableSetStmt"in r.stmt))continue;let n=r.stmt.VariableSetStmt,s=n.name,i=Cf(n.args?.[0]??{});t.set(s,{value:i,local:n.is_local});}return t}function Oa(e){let t=new Yr,r=new Set,n=[];for(let s of e.stmts??[])if(s.stmt){if("CreatePolicyStmt"in s.stmt){let i=s.stmt.CreatePolicyStmt,o=i.table?.relname??"",a=i.table?.schemaname,l={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},c=i.cmd_name?l[i.cmd_name]??"ALL":"ALL",u=i.permissive===true,p=[],f=false;for(let y of i.roles??[])if("RoleSpec"in y){let h=y.RoleSpec;h.roletype==="ROLESPEC_PUBLIC"?h.location===-1&&(f=true):h.roletype==="ROLESPEC_CSTRING"&&h.rolename&&p.push(h.rolename);}let g=i.qual?t.deparse(i.qual):void 0,d=i.with_check?t.deparse(i.with_check):void 0;if(f){let y=a?`${a}.${o}`:o,h=i.policy_name??"",S=`${y}::${h}`;if(!ka.has(S)){ka.add(S);let T=JSON.stringify(g)+JSON.stringify(d);/\{\{auth\.(uid|jwt|role)/i.test(T)||console.warn(`[supalite] policy "${h}" on "${y}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let m=new Qr({name:i.policy_name??"",table:o,schema:a,command:c,permissive:u,roles:p,using:g,withCheck:d});n.push(m);}if("AlterTableStmt"in s.stmt){let i=s.stmt.AlterTableStmt;if((i.cmds??[]).some(l=>"AlterTableCmd"in l&&(l.AlterTableCmd.subtype==="AT_EnableRowSecurity"||l.AlterTableCmd.subtype==="AT_ForceRowSecurity"))){let l=i.relation?.relname??"";r.add(l);}}}return {policies:n,tables:r}}function Ia(e,t){let r=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("CreateStmt"in n.stmt))continue;let s=n.stmt.CreateStmt,i=s.relation?.relname??"",o=s.relation?.schemaname??"public";if(!i)continue;let a=new mn(i,o);for(let l of s.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,u=c.colname;if(!u)continue;let p=c.typeName?.names?.map(R=>R.String?.sval||R.String?.str).filter(Boolean),f=p&&(p.length===2&&p[0]==="pg_catalog"?p[1]:p[0]);if(!f)continue;let g=!!c.typeName?.arrayBounds?.length,d=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],m=R=>d[R]?.A_Const?.ival?.ival??d[R]?.A_Const?.val?.ival?.ival,y={isArray:g};if(Is(f)&&d.length>0){let R=m(0);typeof R=="number"&&R>0&&(y.lengthConstraint=R);}if(Ls(f)&&d.length>=2){let R=m(0),F=m(1);typeof R=="number"&&typeof F=="number"&&R>0&&F>=0&&(y.numericPrecision={precision:R,scale:F});}let h=t.get(f.toLowerCase());h&&(y.enumValues=h);let S=Array.isArray(c.constraints)?c.constraints:[],T=S.some(R=>R.Constraint?.contype==="CONSTR_PRIMARY"),$=Os(f)||S.some(R=>R.Constraint?.contype==="CONSTR_IDENTITY"),P=S.some(R=>R.Constraint?.contype==="CONSTR_NOTNULL"),N=S.find(R=>R.Constraint?.contype==="CONSTR_UNIQUE"),v=S.find(R=>R.Constraint?.contype==="CONSTR_GENERATED"),_=S.find(R=>R.Constraint?.contype==="CONSTR_FOREIGN"),I=S.find(R=>R.Constraint?.contype==="CONSTR_CHECK"),b;if(_){let R=_.Constraint,F=R.pktable?.relname,E=R.pktable?.schemaname,x=R.pk_attrs?.[0]?.String?.sval;F&&x&&(b={refSchema:E,refTable:F,refColumn:x,constraintName:R.conname||void 0});}let D={schema:o,table:i,column:u,pgTypeName:f,nullable:!P&&!T,defaultValue:null,defaultFn:null,isPrimaryKey:T,isUnique:!!N,isSerial:$,isGenerated:!!v,fkRef:b,hasCheck:!!I,checkConstraintName:I?.Constraint?.conname||void 0,uniqueConstraintName:N?.Constraint?.conname||void 0};a.set(u,Mt(D,y));}r.set(`${o}.${i}`,a);}return r}function La(e){let t=[];for(let r of e.stmts??[]){if(!r.stmt||!("CreateStmt"in r.stmt))continue;let n=r.stmt.CreateStmt,s=n.relation?.relname??"",i=n.relation?.schemaname??"public";if(s)for(let o of n.tableElts??[]){if("ColumnDef"in o)continue;let a=o;if(!a.Constraint)continue;let l=a.Constraint,c=l.contype;if(c==="CONSTR_UNIQUE"){let u=(l.keys??[]).map(p=>p.String?.sval??p.String?.str).filter(Boolean);if(u.length===0)continue;t.push({schema:i,table:s,kind:"unique",name:l.conname||void 0,columns:u});}else if(c==="CONSTR_CHECK")t.push({schema:i,table:s,kind:"check",name:l.conname||void 0,columns:[]});else if(c==="CONSTR_FOREIGN"){let u=(l.fk_attrs??[]).map(g=>g.String?.sval??g.String?.str).filter(Boolean),p=(l.pk_attrs??[]).map(g=>g.String?.sval??g.String?.str).filter(Boolean),f=l.pktable?.relname;if(!f)continue;t.push({schema:i,table:s,kind:"foreign_key",name:l.conname||void 0,columns:u,refSchema:l.pktable?.schemaname,refTable:f,refColumns:p});}}}return t}function Da(e){let t=[];for(let r of e.stmts??[]){if(!r.stmt||!("CommentStmt"in r.stmt))continue;let n=r.stmt.CommentStmt,s=n.comment??"";if(!s)continue;let i=n.objtype,o=(n.object?.List?.items??n.object?.items??[]).map(a=>a.String?.sval??a.String?.str).filter(Boolean);if(o.length!==0){if(i==="OBJECT_TABLE"||i==="OBJECT_VIEW"){let[a,l]=o.length>=2?o:["public",o[0]];t.push({schema:a,table:l,text:s});}else if(i==="OBJECT_COLUMN"){let a="public",l,c;o.length>=3?[a,l,c]=o:[l,c]=o,t.push({schema:a,table:l,column:c,text:s});}}}return t}var ka,Fa=w(()=>{fa();Lt();ma();jf();ur();ka=new Set;});async function hn(e,t){let r=await e.connection.introspect(),n=Ma(r);await qf(e,{...t,dbHasTables:r.tables.length>0,dbFingerprint:n}),await Ba(e);let s=await e.connection.introspect();Wf(s,e);}async function SE(e){return zr(e.config.db?.seed?.sql_paths??["./seed.sql"],{cwd:ze__default.join(process.cwd(),"supabase"),absolute:true})}async function EE(e){let t=await SE(e);return Promise.all(t.map(async r=>{let n=await pe__default.readFile(r,"utf-8"),s=createHash("sha256").update(n).digest("hex");return {path:ze__default.relative(process.cwd(),r),hash:s,statements:splitSqlStatements(n)}}))}async function gn(e,t){if(e.config.db?.seed?.enabled===false)return 0;let n=(await EE(e)).filter(l=>l.statements.length>0);if(n.length===0)return 0;await kt(e.connection);let s=Ie(e.connection),i=new Map((await $f(e.connection)).map(l=>[l.path,l.hash])),o=n.filter(l=>i.get(l.path)!==l.hash);if(o.length===0)return 0;console.log(M.default.dim("Seeding database..."));let a=[];for(let l of o){a.push(...l.statements);let c=_f(s,{path:l.path,hash:l.hash});c&&a.push(c);}try{await e.connection.transaction(a);}catch(l){let c=t?.recoveryHint??"Fix `supabase/seed.sql`, then run `bun run dev --recreate` to reset and reseed.";throw new Error(`Seed failed and was rolled back: ${String(l.message??l)}
|
|
79
|
+
${c}`)}return o.reduce((l,c)=>l+c.statements.length,0)}async function Ba(e){await gn(e);}async function fe(e){let t=await zr(e.config?.db?.migrations?.schema_paths??["./schemas/*.sql"],{cwd:ze__default.join(process.cwd(),"supabase"),absolute:true}),r=await Promise.all(t.map(async n=>await pe__default.readFile(n,"utf-8"))).then(n=>n.map(s=>s.split(`
|
|
77
80
|
`).filter(i=>i.trim().length>0&&!i.trim().startsWith("--")).join(`
|
|
78
81
|
`)).join(`
|
|
79
|
-
`));return r||""}async function
|
|
82
|
+
`));return r||""}async function qf(e,t){let r=await fe(e);if(!(!r&&(await Fe(e)).length>0)&&!(!r&&!e.connection.config.baseSchema)){if(t?.dbHasTables&&await _E(e,r,t.dbFingerprint)){console.log(M.default.dim("Schema unchanged \u2014 skipping translation."));return}try{let n=e.connection.createMigrator(r),s=await n.diff(),i=n.translationResult?.ast,o=await e.connection.introspect(),a=Ma(o);if(s.plan.steps.length===0){await Mf(e,r,i,a);return}await n.migratePlan(s.plan,{force:t?.force??!1}),qa(s);let l=await e.connection.introspect();return await Mf(e,r,i,Ma(l)),console.log(""),dt(s),s}catch(n){if(String(n).includes("likely empty"))console.log(M.default.dim("Nothing to migrate."));else {console.error("Migration error: "+String(n));try{await e.connection.exec("rollback");}catch{}}}}}function xE(e){return e.connection.config?.baseSchema??""}function Hf(e,t){let r=createHash("sha256");return r.update(JSON.stringify([xE(e),t??""])),r.digest("hex")}function Ma(e){let t=(n,s)=>[...n].sort((i,o)=>s(i).localeCompare(s(o))),r={tables:t(e.tables??[],n=>`${n.schema??""}.${n.name}`).map(n=>({schema:n.schema,name:n.name,type:n.type,sql:n.sql})),columns:t(e.columns??[],n=>`${n.schema??""}.${n.table}.${n.name}`).map(n=>({schema:n.schema,table:n.table,name:n.name,type:n.type,nullable:n.nullable,default_value:n.default_value,is_primary_key:n.is_primary_key})),indexes:t(e.indexes??[],n=>`${n.schema??""}.${n.table}.${n.name}`).map(n=>({schema:n.schema,table:n.table,name:n.name,unique:n.unique,columns:n.columns})),foreign_keys:t(e.foreign_keys??[],n=>`${n.schema??""}.${n.table}.${n.column}->${n.ref_table}.${n.ref_column}`).map(n=>({schema:n.schema,table:n.table,column:n.column,ref_schema:n.ref_schema,ref_table:n.ref_table,ref_column:n.ref_column})),primary_keys:t(e.primary_keys??[],n=>`${n.schema??""}.${n.table}`).map(n=>({schema:n.schema,table:n.table,columns:n.columns})),check_constraints:t(e.check_constraints??[],n=>`${n.schema??""}.${n.table}.${n.name??""}.${n.column??""}`).map(n=>({schema:n.schema,table:n.table,name:n.name,column:n.column,expression:n.expression})),unique_constraints:t(e.unique_constraints??[],n=>`${n.schema??""}.${n.table}.${n.name}`).map(n=>({schema:n.schema,table:n.table,name:n.name,columns:n.columns})),views:t(e.views??[],n=>`${n.schema??""}.${n.name}`).map(n=>({schema:n.schema,name:n.name,sql:n.sql})),triggers:t(e.triggers??[],n=>`${n.schema??""}.${n.table}.${n.name}`).map(n=>({schema:n.schema,table:n.table,name:n.name,sql:n.sql})),custom_types:t(e.custom_types??[],n=>`${n.schema??""}.${n.type}`).map(n=>({schema:n.schema,type:n.type,kind:n.kind,values:n.values,fields:n.fields}))};return createHash("sha256").update(JSON.stringify(r)).digest("hex")}async function _E(e,t,r){let n=e.connection;if(typeof n.updateDeparseInfo!="function")return false;let s=ze__default.join(process.cwd(),Uf),i;try{i=await pe__default.readFile(s,"utf-8");}catch{return false}let o;try{o=JSON.parse(i);}catch{return false}if(o.v!==Bf||o.hash!==Hf(e,t)||!r||o.dbFingerprint!==r||!o.ast||typeof o.ast!="object")return false;try{let a=await Promise.resolve().then(()=>(Fa(),ja)),l=o.ast,c=a.collectEnums(l),u=a.collectSchema(l,c),p=a.collectVariables(l),f=a.collectTableConstraints(l),g=a.collectComments(l),{policies:d,tables:m}=a.collectPolicies(l);return n.updateDeparseInfo({enums:c,rls:{tables:m,policies:d},schema:u,vars:p,tableConstraints:f,comments:g}),!0}catch{return false}}async function Mf(e,t,r,n){if(!r||typeof r!="object")return;let s={v:Bf,hash:Hf(e,t),dbFingerprint:n,ast:r},i=ze__default.join(process.cwd(),Uf);try{await pe__default.mkdir(ze__default.dirname(i),{recursive:!0}),await pe__default.writeFile(i,JSON.stringify(s),"utf-8");}catch{}}function Wf(e,t){console.log();let r=(s,i)=>{let o=l=>{let c=M.default.dim;return typeof l=="number"&&(l>=0&&(c=l>0?M.default.green:M.default.dim),l<0&&(c=M.default.red)),typeof l=="boolean"?l?M.default.green("\u2713"):M.default.red("\u2717"):c(String(l))},a=Object.entries(i).map(([l,c])=>`${l}: ${o(c)}`).join(M.default.dim(" / "));console.log(`${M.default.dim("[")} ${s} ${M.default.dim("]")} ${a}`);};r(M.default.green("DATA"),{tables:e.tables.length,columns:e.columns.length,indexes:e.indexes.length});let n=t.config.rls??t.connection.config.translation?.deparse?.rls??{tables:new Set([]),policies:[]};r(M.default.green("AUTH"),{enabled:!!t.config.auth?.enabled,tables:ensureVar.Set(n.tables).size,policies:ensureVar.Array(n.policies).length});}function Gf(e,t){setTimeout(()=>{console.log(M.default.dim("Watching for changes...")),bE.watch("./supabase/schemas").on("change",async n=>{console.log(),console.log(M.default.dim(`Schema changed: ${n}`)),await qf(e,t);let s=await e.connection.introspect();Wf(s,e);});},200);}function yn(e,t){let r=t?.colorize?M.default.dim:n=>n;return e.plan.steps.flatMap(n=>[n.description?r(`-- ${n.description}`):"",n.sql+`
|
|
80
83
|
`]).filter(n=>n.trim().length>0).join(`
|
|
81
|
-
`)}function
|
|
84
|
+
`)}function $E(e){let t=new Date;return `${t.getFullYear().toString()+(t.getMonth()+1).toString().padStart(2,"0")+t.getDate().toString().padStart(2,"0")+t.getHours().toString().padStart(2,"0")+t.getMinutes().toString().padStart(2,"0")+t.getSeconds().toString().padStart(2,"0")}.sql`}function qa(e,t){let r="./supabase/.temp/migrations";ke(r);let n=$E(),s=yn(e);Et(ze__default.join(r,n),s),console.log(M.default.dim(`Migration written to ${M.default.cyan(ze__default.join(r,n))}`));}function zf(e){let t=e.schema_separator??".",r=e.ddl_dialect==="postgres",n=(a,l)=>r&&a?`${a}${t}${l}`:l;console.log(M.default.bgWhite(M.default.black(" Schema "))),console.log();let s=e.tables.filter(a=>a.type==="table"),i=r?"sqlite-postgres":"sqlite";if(console.log(M.default.dim(`${i}${e.version?` (sqlite ${e.version})`:""} \xB7 ${e.database_name}`)),console.log(),s.length===0){console.log(M.default.dim("No tables."));return}console.log(M.default.dim("Tables:"));for(let a of s){let l=n(a.schema,a.name),c=e.columns.filter(p=>p.table===a.name&&(!r||p.schema===a.schema)).sort((p,f)=>p.ordinal_position-f.ordinal_position),u=a.rows>=0?` ${M.default.dim(`(${a.rows} rows)`)}`:"";console.log(`${M.default.bold(l)}${u}`);for(let p of c){let f=[];p.is_primary_key&&f.push(M.default.green("PK")),p.nullable||f.push(M.default.dim("NOT NULL")),p.default_value!==null&&f.push(M.default.dim(`DEFAULT ${p.default_value}`));let g=f.length?" "+f.join(" "):"";console.log(` ${p.name} ${M.default.cyan(p.type)}${g}`);}console.log();}let o=e.indexes.filter(a=>!a.name.startsWith("sqlite_autoindex_"));if(o.length>0){console.log(M.default.dim("Indexes:"));for(let a of o){let l=a.unique?M.default.yellow("UNIQUE "):"";console.log(` ${a.name} on ${n(a.schema,a.table)} ${l}(${a.columns.join(", ")})`);}console.log();}if(e.foreign_keys.length>0){console.log(M.default.dim("Foreign Keys:"));for(let a of e.foreign_keys){let l=`${n(a.schema,a.table)}.${a.column}`,c=`${n(a.ref_schema,a.ref_table)}.${a.ref_column}`;console.log(` ${l} \u2192 ${c} ${M.default.dim(`ON DELETE ${a.on_delete} ON UPDATE ${a.on_update}`)}`);}console.log();}if(e.views.length>0){console.log(M.default.dim("Views:"));for(let a of e.views)console.log(` ${n(a.schema,a.name)}`);console.log();}if(e.triggers.length>0){console.log(M.default.dim("Triggers:"));for(let a of e.triggers)console.log(` ${a.name} on ${n(a.schema,a.table)}`);console.log();}}function dt({diff:e}){if(typeof e=="string"){console.log(M.default.cyan(e));return}if(!e.has_changes)return;console.log(M.default.bgWhite(M.default.black(" Schema Diff "))),console.log();let t={added:{color:M.default.green,symbol:"+"},removed:{color:M.default.red,symbol:"-"},modified:{color:M.default.yellow,symbol:"~"}};if(e.tables.length>0){console.log(M.default.dim("Tables:"));for(let r of e.tables){let{color:n,symbol:s}=t[r.type];console.log(n(`${s} ${r.name}`));}console.log();}if(e.columns.length>0){console.log(M.default.dim("Columns:"));for(let r of e.columns){let{color:n,symbol:s}=t[r.type],i="";r.changes&&(i=Object.entries(r.changes).map(([o,a])=>`${o}: ${a.from} \u2192 ${a.to}`).join(", ")),console.log(n(`${s} ${r.table}.${r.name}${i?` (${i})`:""}`));}console.log();}if(e.indexes.length>0){console.log(M.default.dim("Indexes:"));for(let r of e.indexes){let{color:n,symbol:s}=t[r.type];console.log(n(`${s} ${r.name} on ${r.table}`));}console.log();}if(e.foreign_keys.length>0){console.log(M.default.dim("Foreign Keys:"));for(let r of e.foreign_keys){let{color:n,symbol:s}=t[r.type];console.log(n(`${s} ${r.table}.${r.column} \u2192 ${r.ref_table}.${r.ref_column}`));}console.log();}}var M,Uf,Bf,He=w(()=>{ca();M=ee(ie());xt();pt();Pt();Uf="supabase/.temp/.translation-cache.json",Bf=2;});function vE(e){return e==="service_role"?"NOLOGIN BYPASSRLS":"NOLOGIN"}function ht(e){return e.size===0?"":`DO $$ BEGIN${[...e].map(r=>`
|
|
82
85
|
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${r}') THEN
|
|
83
|
-
CREATE ROLE ${r} ${
|
|
86
|
+
CREATE ROLE ${r} ${vE(r)};
|
|
84
87
|
END IF;`).join("")}
|
|
85
88
|
END $$;
|
|
86
|
-
`}function
|
|
87
|
-
`;)r++;continue}if(n==="/"&&s==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)r++;r=r<e.length?r+2:r;continue}if(n==="'"){r=
|
|
89
|
+
`}function wn(e,t){return e?e.quoted?e.value===t:e.value.toLowerCase()===t:false}function Re(e){return e?.quoted?e.value:e?.value.toLowerCase()}function TE(e,t){let r="",n=t+1;for(;n<e.length;){if(e[n]==='"'&&e[n+1]==='"'){r+='"',n+=2;continue}if(e[n]==='"')return {token:{value:r,quoted:true},end:n+1};r+=e[n],n++;}return {token:{value:r,quoted:true},end:n}}function AE(e,t){let r=t+1;for(;r<e.length;){if(e[r]==="'"&&e[r+1]==="'"){r+=2;continue}if(e[r]==="'")return r+1;r++;}return r}function CE(e,t){let r=/^\$[A-Za-z_][A-Za-z0-9_]*\$|^\$\$/.exec(e.slice(t))?.[0];if(!r)return;let n=t+r.length,s=e.indexOf(r,n);return s===-1?e.length:s+r.length}function Wa(e){let t=[],r=0;for(;r<e.length;){let n=e[r],s=e[r+1];if(/\s/.test(n)){r++;continue}if(n==="-"&&s==="-"){for(r+=2;r<e.length&&e[r]!==`
|
|
90
|
+
`;)r++;continue}if(n==="/"&&s==="*"){for(r+=2;r<e.length&&!(e[r]==="*"&&e[r+1]==="/");)r++;r=r<e.length?r+2:r;continue}if(n==="'"){r=AE(e,r);continue}if(n==="$"){let i=CE(e,r);if(i!==void 0){r=i;continue}}if(n==='"'){let{token:i,end:o}=TE(e,r);t.push(i),r=o;continue}if(n===","||n===";"){t.push({value:n,quoted:false}),r++;continue}if(/[A-Za-z_]/.test(n)){let i=r;for(r++;r<e.length&&/[A-Za-z0-9_$]/.test(e[r]);)r++;t.push({value:e.slice(i,r).toLowerCase(),quoted:false});continue}r++;}return t}function Kf(e,t){let r=Re(e[t]),n=Re(e[t+1]);if((r==="create"||r==="alter")&&(n==="role"||n==="user"||n==="group"))return e[t+2]}function qs(e){let t=new Set,r=Wa(e);for(let n=0;n<r.length;n++){if(Re(r[n])!=="create")continue;let s=Kf(r,n);for(let i of pr)wn(s,i)&&t.add(i);}return t}function Ha(e,t,r){let n=new Set([";","as","by","check","for","granted","in","on","option","using","where","with"]);for(let s=t;s<e.length;s++){let i=Re(e[s]);if(!i||n.has(i))return;for(let o of pr)wn(e[s],o)&&r.add(o);}}function RE(e){let t=[],r=[];for(let n of e){if(Re(n)===";"){r.length>0&&t.push(r),r=[];continue}r.push(n);}return r.length>0&&t.push(r),t}function Vf(e,t){return e.some(r=>Re(r)===t)}function kE(e){let t=new Set,r=RE(Wa(e));for(let n of r){let s=Re(n[0]);for(let a=0;a<n.length;a++){let l=Re(n[a]);l==="to"&&(Vf(n,"grant")||Vf(n,"policy")||Re(n[a-1])==="owner")&&Ha(n,a+1,t),l==="from"&&s==="revoke"&&Ha(n,a+1,t);}let i=n.findIndex(a=>Re(a)==="to"),o=n.findIndex(a=>Re(a)==="on");s==="grant"&&i>1&&(o===-1||i<o)&&Ha(n,1,t);}return t}function gt(e){let t=qs(e);return new Set([...kE(e)].filter(r=>!t.has(r)))}function Xf(e){let t=qs(e);return new Set(pr.filter(r=>!t.has(r)))}function Jf(e,t){let r=Wa(e);if(r.length===0)return false;let n=Kf(r,0);if(n){for(let o of t)if(wn(n,o))return true;return false}let s=Re(r[0]),i=Re(r[1]);if(s==="drop"&&(i==="role"||i==="user"||i==="group")){for(let o of r.slice(2))for(let a of t)if(wn(o,a))return true}if(s==="comment"&&Re(r[1])==="on"&&Re(r[2])==="role"){for(let o of t)if(wn(r[3],o))return true}return false}var pr,Bs,bn=w(()=>{pr=["anon","authenticated","service_role"];ht(new Set(pr)),Bs=`
|
|
88
91
|
CREATE SCHEMA IF NOT EXISTS auth;
|
|
89
92
|
|
|
90
93
|
CREATE OR REPLACE FUNCTION auth.uid() RETURNS UUID AS $$
|
|
@@ -105,89 +108,96 @@ CREATE OR REPLACE FUNCTION auth.jwt() RETURNS JSONB AS $$
|
|
|
105
108
|
'{}'
|
|
106
109
|
)::jsonb;
|
|
107
110
|
$$ LANGUAGE SQL STABLE;
|
|
108
|
-
`;});async function
|
|
109
|
-
`);if(!r.trim())return;let n=e.connection;if(typeof n.translateDdl!="function"||typeof n.updateDeparseInfo!="function")return;let s=await n.translateDdl(r),i=n.config?.translation?.deparse??{};n.updateDeparseInfo({...i,...s});}async function
|
|
110
|
-
`)),this.displayPrompt();}}),i.defineCommand("table",{help:"Show a table",action:async function(a){let l=await r.connection.introspect(),c=p=>l.columns.filter(f=>f.table===p),u=l.tables.find(p=>p.name===a);u?(console.log(`${
|
|
111
|
-
`)),console.log(),console.log(
|
|
112
|
-
`+l.tables.map(p=>`- ${
|
|
113
|
-
`))),this.displayPrompt();}}),i.defineCommand("indexes",{help:"List all indexes",action:async function(){let a=await r.connection.introspect().then(l=>l.indexes);console.log(a.map(l=>`${
|
|
114
|
-
`)),this.displayPrompt();}}),i.defineCommand("config",{help:"Show the current config",action:async function(a){console.log(a?
|
|
111
|
+
`;});async function Ut(e){await NE(e),await kt(e.connection);let t=new Set(await Kr(e.connection)),r=await Fe(e),n=Ie(e.connection),s=[],i=[];for(let o of r){if(t.has(o.version)){i.push(o);continue}let a=Xt(o.sql),l;if(n==="pg-flat"){let u=await e.connection.translateDdl(o.sql),p=typeof u=="string"?u:u.ddl??"";l=Xt(p);}else l=a;let c=xf(n,{version:o.version,name:o.name,statements:a});if(n==="pg"){let u=ht(gt(o.sql));u&&await e.connection.exec(u);}await e.connection.transaction([...l,c],{intent:"migration"}),s.push(o);}return r.length>0&&n!=="sqlite"&&await PE(e,r),{applied:s,skipped:i}}async function PE(e,t){let r=t.map(o=>o.sql).join(`
|
|
112
|
+
`);if(!r.trim())return;let n=e.connection;if(typeof n.translateDdl!="function"||typeof n.updateDeparseInfo!="function")return;let s=await n.translateDdl(r),i=n.config?.translation?.deparse??{};n.updateDeparseInfo({...i,...s});}async function NE(e){let t=e.connection.config?.baseSchema;if(!t||!t.trim())return;let r=e.connection,n=t;if(r.dialect==="sqlite"&&r.config.ddlDialect!=="sqlite"&&r.translateDdl){let s=await r.translateDdl(t);n=typeof s=="string"?s:s.ddl??t;}for(let s of Xt(n))try{await r.exec(s);}catch{}}var Hs=w(()=>{Jt();Pt();pt();bn();});function ge(e){return `${OE} ${e}`}var OE,Je=w(()=>{OE="[lite]";});var Yf={};de(Yf,{dev:()=>DE});var Be,DE,Qf=w(()=>{Xi();Ho();lt();Be=ee(ie());Kt();He();Hs();pt();Ce();xe();zt();Je();DE=e=>{e.command("dev").option("--recreate","Recreate everything",false).option("--template","Create a template for the database",false).option("--config <config>","Path to the config file").description(ge("Start the development server with schema watching")).helpGroup("Local Development:").action(async t=>{await Y(t.config),console.log(Be.default.yellow(" \u26A0 [lite] dev is experimental and works with declarative schema only.")),await Zn(async()=>{await Yn({recreate:t.recreate,template:t.template}),console.log();let n=await(await z({withSupabaseClient:false})).project.local.createApp(t.config),s=n.config.api?.port??ve.default_api_port;if((await Fe(n)).length>0){let c=await Ut(n);for(let u of c.applied)console.log(Be.default.green(" \u2713"),"Applied migration",Be.default.cyan(u.filename));}await hn(n,{force:true}),console.log();await ys(n,{port:s});console.log(Be.default.green(" \u279C"),"Server running on ",Be.default.cyan(`http://localhost:${s}`));let a=Un();a&&console.log(Be.default.yellow(` \u26A0 ${a}`)),await n.connection.ping(),Gf(n,{translate:true,force:true});let l=ze__default.join(process.cwd(),"supabase",Nt(n));setTimeout(()=>{bE.watch(l,{ignoreInitial:true}).on("add",async u=>{console.log(),console.log(Be.default.dim(`Migration added: ${u}`));try{let p=await Ut(n);for(let f of p.applied)console.log(Be.default.green(" \u2713"),"Applied",Be.default.cyan(f.filename));}catch(p){console.error(Be.default.red("Migration failed: "+String(p.message??p)));}});},200),process.on("SIGINT",async()=>{await n.connection.close(),process.exit(1);});},r=>{console.log(),console.log(Be.default.green(`Ready in ${r.toFixed(2)}ms`));});});};});async function yt(e){let t=await z({withSupabaseClient:false}),r=t.project.local.ref();if(typeof e=="boolean"&&e){if(!r)throw new Error("No project linked");if(!await t.project.remote.ping())throw new Error("Remote project is not reachable");return console.log("creating app for remote project",r),t.project.remote.createApp(r)}return t.project.local.createApp(e)}var Ga=w(()=>{Ce();});var Zf={};de(Zf,{repl:()=>jE});var be,jE,em=w(()=>{lt();be=ee(ie());Ga();xe();Je();jE=e=>{e.command("repl").option("--config <config>","Path to the config file").option("--remote","Connect REPL to a remote project").description(ge("Start a REPL session")).helpGroup("Local Development:").action(async t=>{t.remote||await Y(t.config);let r=await yt(t.remote?true:t.config);Qn()||(console.error(be.default.red("REPL is only supported on Node.js")),process.exit(1));let n={app:r,client:r.getClient(),conn:r.connection,db:r.connection.driver};console.log(be.default.green("Starting a REPL session")),console.log(be.default.bold("Available variables:"),Object.keys(n).map(o=>be.default.cyan(o)).join(", "));let i=(await import('node:repl')).start("> ");i.on("exit",async()=>{await r.connection.close(),process.exit();});for(let o of Object.keys(n))Object.defineProperty(i.context,o,{configurable:false,enumerable:true,value:n[o]});i.defineCommand("tables",{help:"List all tables",action:async function(){let a=await r.connection.introspect(),l=c=>a.columns.filter(u=>u.table===c);console.log(a.tables.map(c=>`${be.default.cyan(c.name)} (${l(c.name).length} columns)`).join(`
|
|
113
|
+
`)),this.displayPrompt();}}),i.defineCommand("table",{help:"Show a table",action:async function(a){let l=await r.connection.introspect(),c=p=>l.columns.filter(f=>f.table===p),u=l.tables.find(p=>p.name===a);u?(console.log(`${be.default.cyan(u?.name)} (${c(a).length} columns)`),console.log(c(a).map(p=>` - ${be.default.cyan(p.name)} ${be.default.yellow(p.type)}`).join(`
|
|
114
|
+
`)),console.log(),console.log(be.default.dim(u.sql))):(console.log(be.default.red(`Table ${a} not found`)),console.log(`Available tables:
|
|
115
|
+
`+l.tables.map(p=>`- ${be.default.cyan(p.name)}`).join(`
|
|
116
|
+
`))),this.displayPrompt();}}),i.defineCommand("indexes",{help:"List all indexes",action:async function(){let a=await r.connection.introspect().then(l=>l.indexes);console.log(a.map(l=>`${be.default.bold(be.default.cyan(l.name))} ${l.unique?be.default.yellow("unique "):""}on ${be.default.blue(l.table)}(${l.columns.map(c=>be.default.magenta(c)).join(", ")})`).join(`
|
|
117
|
+
`)),this.displayPrompt();}}),i.defineCommand("config",{help:"Show the current config",action:async function(a){console.log(a?Yi(r.config,a):r.config),this.displayPrompt();}});});};});var tm={};de(tm,{debug:()=>FE});var FE,rm=w(()=>{lt();xe();Je();FE=e=>{e.command("debug").description(ge("Print runtime info (bun/node detection, paths)")).helpGroup("Local Development:").action(async()=>{console.log("Debugging the application"),console.log({bun:Cr(),node:Qn(),cwd:process.cwd(),paths:{root:Xn(),dist:zi(),relativeDist:Jn()}});});};});var Va=ot((OP,nm)=>{var za={to(e,t){return t?`\x1B[${t+1};${e+1}H`:`\x1B[${e+1}G`},move(e,t){let r="";return e<0?r+=`\x1B[${-e}D`:e>0&&(r+=`\x1B[${e}C`),t<0?r+=`\x1B[${-t}A`:t>0&&(r+=`\x1B[${t}B`),r},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},ME={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},UE={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let r=0;r<e;r++)t+=this.line+(r<e-1?za.up():"");return e&&(t+=za.left),t}};nm.exports={cursor:za,scroll:ME,erase:UE,beep:"\x07"};});function Ks(e,t,r){if(!r.some(o=>!o.disabled))return e;let n=e+t,s=Math.max(r.length-1,0),i=n<0?s:n>s?0:n;return r[i].disabled?Ks(i,t<0?-1:1,r):i}function Qa(e,t,r){return String(e).normalize().replaceAll(`\r
|
|
115
118
|
`,`
|
|
116
119
|
`).split(`
|
|
117
|
-
`).map(n=>
|
|
118
|
-
`)}function
|
|
120
|
+
`).map(n=>ZE(n,t,r)).join(`
|
|
121
|
+
`)}function nl(e,t){if(typeof e=="string")return Oe.aliases.get(e)===t;for(let r of e)if(r!==void 0&&nl(r,t))return true;return false}function tx(e,t){if(e===t)return;let r=e.split(`
|
|
119
122
|
`),n=t.split(`
|
|
120
|
-
`),s=Math.max(r.length,n.length),i=[];for(let o=0;o<s;o++)r[o]!==n[o]&&i.push(o);return {lines:i,numLinesBefore:r.length,numLinesAfter:n.length,numLines:s}}function
|
|
123
|
+
`),s=Math.max(r.length,n.length),i=[];for(let o=0;o<s;o++)r[o]!==n[o]&&i.push(o);return {lines:i,numLinesBefore:r.length,numLinesAfter:n.length,numLines:s}}function Se(e){return e===Za}function Vs(e,t){let r=e;r.isTTY&&r.setRawMode(t);}function mm({input:e=stdin,output:t=stdout,overwrite:r=true,hideCursor:n=true}={}){let s=wt.createInterface({input:e,output:t,prompt:"",tabSize:1});wt.emitKeypressEvents(e,s),e instanceof ReadStream&&e.isTTY&&e.setRawMode(true);let i=(o,{name:a,sequence:l})=>{let c=String(o);if(nl([c,a,l],"cancel")){n&&t.write(_e.cursor.show),process.exit(0);return}if(!r)return;wt.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{wt.clearLine(t,1,()=>{e.once("keypress",i);});});};return n&&t.write(_e.cursor.hide),e.once("keypress",i),()=>{e.off("keypress",i),n&&t.write(_e.cursor.show),e instanceof ReadStream&&e.isTTY&&!rx&&e.setRawMode(false),s.terminal=false,s.close();}}function ti(e,t,r,n=r){let s=ei(e??stdout);return Qa(t,s-r.length,{hard:true,trim:false}).split(`
|
|
121
124
|
`).map((i,o)=>`${o===0?n:r}${i}`).join(`
|
|
122
|
-
`)}var
|
|
123
|
-
`),u=c[Symbol.iterator](),p=u.next(),f=u.next(),g=0;for(;!p.done;){let d=p.value,m=f.value;if(n+=d,d===
|
|
124
|
-
`?(i&&(n+=
|
|
125
|
-
`&&(s&&
|
|
126
|
-
`),
|
|
127
|
-
`).length-1;this.output.write(
|
|
128
|
-
`);this.output.write(a[o]),this._prevFrame=t,this.output.write(
|
|
125
|
+
`)}var _e,qE,HE,WE,Ka,Ws,Gs,Xa,zs,GE,zE,cm,VE,Sn,Zs,um,KE,tl,pm,XE,fm,rl,im,JE,om,am,YE,Ja,QE,ZE,ex,Oe,rx,Za,ei,sl,fr,Xs,Js,Ys,Qs,il=w(()=>{_e=ee(Va());qE=e=>e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109,HE=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,WE=e=>e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101632&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129672||e>=129680&&e<=129725||e>=129727&&e<=129733||e>=129742&&e<=129755||e>=129760&&e<=129768||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141,Ka=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Ws=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Gs=/\t{1,1000}/y,Xa=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,zs=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,GE=/\p{M}+/gu,zE={limit:1/0,ellipsis:""},cm=(e,t={},r={})=>{let n=t.limit??1/0,s=t.ellipsis??"",i=t?.ellipsisWidth??(s?cm(s,zE,r).width:0),o=r.ansiWidth??0,a=r.controlWidth??0,l=r.tabWidth??8,c=r.ambiguousWidth??1,u=r.emojiWidth??2,p=r.fullWidthWidth??2,f=r.regularWidth??1,g=r.wideWidth??2,d=0,m=0,y=e.length,h=0,S=false,T=y,$=Math.max(0,n-i),P=0,N=0,v=0,_=0;e:for(;;){if(N>P||m>=y&&m>d){let I=e.slice(P,N)||e.slice(d,m);h=0;for(let b of I.replaceAll(GE,"")){let D=b.codePointAt(0)||0;if(HE(D)?_=p:WE(D)?_=g:c!==f&&qE(D)?_=c:_=f,v+_>$&&(T=Math.min(T,Math.max(P,d)+h)),v+_>n){S=true;break e}h+=b.length,v+=_;}P=N=0;}if(m>=y)break;if(zs.lastIndex=m,zs.test(e)){if(h=zs.lastIndex-m,_=h*f,v+_>$&&(T=Math.min(T,m+Math.floor(($-v)/f))),v+_>n){S=true;break}v+=_,P=d,N=m,m=d=zs.lastIndex;continue}if(Ka.lastIndex=m,Ka.test(e)){if(v+o>$&&(T=Math.min(T,m)),v+o>n){S=true;break}v+=o,P=d,N=m,m=d=Ka.lastIndex;continue}if(Ws.lastIndex=m,Ws.test(e)){if(h=Ws.lastIndex-m,_=h*a,v+_>$&&(T=Math.min(T,m+Math.floor(($-v)/a))),v+_>n){S=true;break}v+=_,P=d,N=m,m=d=Ws.lastIndex;continue}if(Gs.lastIndex=m,Gs.test(e)){if(h=Gs.lastIndex-m,_=h*l,v+_>$&&(T=Math.min(T,m+Math.floor(($-v)/l))),v+_>n){S=true;break}v+=_,P=d,N=m,m=d=Gs.lastIndex;continue}if(Xa.lastIndex=m,Xa.test(e)){if(v+u>$&&(T=Math.min(T,m)),v+u>n){S=true;break}v+=u,P=d,N=m,m=d=Xa.lastIndex;continue}m+=1;}return {width:S?$:v,index:S?T:y,truncated:S,ellipsed:S&&n>=i}},VE={limit:1/0,ellipsis:"",ellipsisWidth:0},Sn=(e,t={})=>cm(e,VE,t).width,Zs="\x1B",um="\x9B",KE=39,tl="\x07",pm="[",XE="]",fm="m",rl=`${XE}8;;`,im=new RegExp(`(?:\\${pm}(?<code>\\d+)m|\\${rl}(?<uri>.*)${tl})`,"y"),JE=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},om=e=>`${Zs}${pm}${e}${fm}`,am=e=>`${Zs}${rl}${e}${tl}`,YE=e=>e.map(t=>Sn(t)),Ja=(e,t,r)=>{let n=t[Symbol.iterator](),s=false,i=false,o=e.at(-1),a=o===void 0?0:Sn(o),l=n.next(),c=n.next(),u=0;for(;!l.done;){let p=l.value,f=Sn(p);a+f<=r?e[e.length-1]+=p:(e.push(p),a=0),(p===Zs||p===um)&&(s=true,i=t.startsWith(rl,u+1)),s?i?p===tl&&(s=false,i=false):p===fm&&(s=false):(a+=f,a===r&&!c.done&&(e.push(""),a=0)),l=c,c=n.next(),u+=p.length;}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop());},QE=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(Sn(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},ZE=(e,t,r={})=>{if(r.trim!==false&&e.trim()==="")return "";let n="",s,i,o=e.split(" "),a=YE(o),l=[""];for(let[d,m]of o.entries()){r.trim!==false&&(l[l.length-1]=(l.at(-1)??"").trimStart());let y=Sn(l.at(-1)??"");if(d!==0&&(y>=t&&(r.wordWrap===false||r.trim===false)&&(l.push(""),y=0),(y>0||r.trim===false)&&(l[l.length-1]+=" ",y++)),r.hard&&a[d]>t){let h=t-y,S=1+Math.floor((a[d]-h-1)/t);Math.floor((a[d]-1)/t)<S&&l.push(""),Ja(l,m,t);continue}if(y+a[d]>t&&y>0&&a[d]>0){if(r.wordWrap===false&&y<t){Ja(l,m,t);continue}l.push("");}if(y+a[d]>t&&r.wordWrap===false){Ja(l,m,t);continue}l[l.length-1]+=m;}r.trim!==false&&(l=l.map(d=>QE(d)));let c=l.join(`
|
|
126
|
+
`),u=c[Symbol.iterator](),p=u.next(),f=u.next(),g=0;for(;!p.done;){let d=p.value,m=f.value;if(n+=d,d===Zs||d===um){im.lastIndex=g+1;let h=im.exec(c)?.groups;if(h?.code!==void 0){let S=Number.parseFloat(h.code);s=S===KE?void 0:S;}else h?.uri!==void 0&&(i=h.uri.length===0?void 0:h.uri);}let y=s?JE(s):void 0;m===`
|
|
127
|
+
`?(i&&(n+=am("")),s&&y&&(n+=om(y))):d===`
|
|
128
|
+
`&&(s&&y&&(n+=om(s)),i&&(n+=am(i))),g+=d.length,p=f,f=u.next();}return n};ex=["up","down","left","right","space","enter","cancel"],Oe={actions:new Set(ex),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:true};rx=globalThis.process.platform.startsWith("win"),Za=Symbol("clack:cancel");ei=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,sl=e=>"rows"in e&&typeof e.rows=="number"?e.rows:20;fr=class{input;output;_abortSignal;rl;opts;_render;_track=false;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,r=true){let{input:n=stdin,output:s=stdout,render:i,signal:o,...a}=t;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=i.bind(this),this._track=r,this._abortSignal=o,this.input=n,this.output=s;}unsubscribe(){this._subscribers.clear();}setSubscriber(t,r){let n=this._subscribers.get(t)??[];n.push(r),this._subscribers.set(t,n);}on(t,r){this.setSubscriber(t,{cb:r});}once(t,r){this.setSubscriber(t,{cb:r,once:true});}emit(t,...r){let n=this._subscribers.get(t)??[],s=[];for(let i of n)i.cb(...r),i.once&&s.push(()=>n.splice(n.indexOf(i),1));for(let i of s)i();}prompt(){return new Promise(t=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(Za);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close();},{once:true});}this.rl=wt__default.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:true}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,true),this.input.on("keypress",this.onKeypress),Vs(this.input,true),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(_e.cursor.show),this.output.off("resize",this.render),Vs(this.input,false),t(this.value);}),this.once("cancel",()=>{this.output.write(_e.cursor.show),this.output.off("resize",this.render),Vs(this.input,false),t(Za);});})}_isActionKey(t,r){return t===" "}_setValue(t){this.value=t,this.emit("value",this.value);}_setUserInput(t,r){this.userInput=t??"",this.emit("userInput",this.userInput),r&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor);}_clearUserInput(){this.rl?.write(null,{ctrl:true,name:"u"}),this._setUserInput("");}onKeypress(t,r){if(this._track&&r.name!=="return"&&(r.name&&this._isActionKey(t,r)&&this.rl?.write(null,{ctrl:true,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),r?.name&&(!this._track&&Oe.aliases.has(r.name)&&this.emit("cursor",Oe.aliases.get(r.name)),Oe.actions.has(r.name)&&this.emit("cursor",r.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t?.toLowerCase(),r),r?.name==="return"){if(this.opts.validate){let n=this.opts.validate(this.value);n&&(this.error=n instanceof Error?n.message:n,this.state="error",this.rl?.write(this.userInput));}this.state!=="error"&&(this.state="submit");}nl([t,r?.name,r?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close();}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
129
|
+
`),Vs(this.input,false),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe();}restoreCursor(){let t=Qa(this._prevFrame,process.stdout.columns,{hard:true,trim:false}).split(`
|
|
130
|
+
`).length-1;this.output.write(_e.cursor.move(-999,t*-1));}render(){let t=Qa(this._render(this)??"",process.stdout.columns,{hard:true,trim:false});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(_e.cursor.hide);else {let r=tx(this._prevFrame,t),n=sl(this.output);if(this.restoreCursor(),r){let s=Math.max(0,r.numLinesAfter-n),i=Math.max(0,r.numLinesBefore-n),o=r.lines.find(a=>a>=s);if(o===void 0){this._prevFrame=t;return}if(r.lines.length===1){this.output.write(_e.cursor.move(0,o-i)),this.output.write(_e.erase.lines(1));let a=t.split(`
|
|
131
|
+
`);this.output.write(a[o]),this._prevFrame=t,this.output.write(_e.cursor.move(0,a.length-o-1));return}else if(r.lines.length>1){if(s<i)o=s;else {let l=o-i;l>0&&this.output.write(_e.cursor.move(0,l));}this.output.write(_e.erase.down());let a=t.split(`
|
|
129
132
|
`).slice(o);this.output.write(a.join(`
|
|
130
|
-
`)),this._prevFrame=t;return}}this.output.write(
|
|
133
|
+
`)),this._prevFrame=t;return}}this.output.write(_e.erase.down());}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t;}}},Xs=class extends fr{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,false),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value;}),this.on("confirm",r=>{this.output.write(_e.cursor.move(0,-1)),this.value=r,this.state="submit",this.close();}),this.on("cursor",()=>{this.value=!this.value;});}},Js=class extends fr{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t=this.userInput;if(this.cursor>=t.length)return `${this.masked}${styleText(["inverse","hidden"],"_")}`;let r=this.masked,n=r.slice(0,this.cursor),s=r.slice(this.cursor);return `${n}${styleText("inverse",s[0])}${s.slice(1)}`}clear(){this._clearUserInput();}constructor({mask:t,...r}){super(r),this._mask=t??"\u2022",this.on("userInput",n=>{this._setValue(n);});}},Ys=class extends fr{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value;}constructor(t){super(t,false),this.options=t.options;let r=this.options.findIndex(({value:s})=>s===t.initialValue),n=r===-1?0:r;this.cursor=this.options[n].disabled?Ks(n,1,this.options):n,this.changeValue(),this.on("cursor",s=>{switch(s){case "left":case "up":this.cursor=Ks(this.cursor,-1,this.options);break;case "down":case "right":this.cursor=Ks(this.cursor,1,this.options);break}this.changeValue();});}},Qs=class extends fr{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return `${this.userInput}\u2588`;let r=t.slice(0,this.cursor),[n,...s]=t.slice(this.cursor);return `${r}${styleText("inverse",n)}${s.join("")}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",r=>{this._setValue(r);}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="");});}};});function nx(){return We.platform!=="win32"?We.env.TERM!=="linux":!!We.env.CI||!!We.env.WT_SESSION||!!We.env.TERMINUS_SUBLIME||We.env.ConEmuTask==="{cmd::Cmder}"||We.env.TERM_PROGRAM==="Terminus-Sublime"||We.env.TERM_PROGRAM==="vscode"||We.env.TERM==="xterm-256color"||We.env.TERM==="alacritty"||We.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function pl(e,t,r){return String(e).normalize().replaceAll(`\r
|
|
131
134
|
`,`
|
|
132
135
|
`).split(`
|
|
133
|
-
`).map(n=>
|
|
134
|
-
`)}var
|
|
135
|
-
`),u=c[Symbol.iterator](),p=u.next(),f=u.next(),g=0;for(;!p.done;){let d=p.value,m=f.value;if(n+=d,d===
|
|
136
|
-
`?(i&&(n+=
|
|
137
|
-
`&&(s&&
|
|
138
|
-
`);
|
|
139
|
-
`:""}${
|
|
136
|
+
`).map(n=>_x(n,t,r)).join(`
|
|
137
|
+
`)}var En,cl,sx,X,ix,ym,wm,fl,V,mr,ul,oi,ox,ax,lx,cx,ux,ai,px,fx,mx,dx,ol,ri,ni,al,si,hx,gx,bm,yx,xn,li,Sm,wx,ml,Em,bx,xm,dl,dm,Sx,hm,gm,Ex,ll,xx,_x,$x,vx,_n,K,$n,Tx,hl,ii,vn,Tn,Ye=w(()=>{il();il();En=ee(Va());cl=nx(),sx=()=>process.env.CI==="true",X=(e,t)=>cl?e:t,ix=X("\u25C6","*"),ym=X("\u25A0","x"),wm=X("\u25B2","x"),fl=X("\u25C7","o"),X("\u250C","T"),V=X("\u2502","|"),mr=X("\u2514","\u2014"),X("\u2510","T"),X("\u2518","\u2014"),ul=X("\u25CF",">"),oi=X("\u25CB"," "),X("\u25FB","[\u2022]"),X("\u25FC","[+]"),X("\u25FB","[ ]"),ox=X("\u25AA","\u2022"),X("\u2500","-"),X("\u256E","+"),X("\u251C","+"),X("\u256F","+"),X("\u2570","+"),X("\u256D","+"),ax=X("\u25CF","\u2022"),lx=X("\u25C6","*"),cx=X("\u25B2","!"),ux=X("\u25A0","x"),ai=e=>{switch(e){case "initial":case "active":return styleText("cyan",ix);case "cancel":return styleText("red",ym);case "error":return styleText("yellow",wm);case "submit":return styleText("green",fl)}},px=e=>{switch(e){case "initial":case "active":return styleText("cyan",V);case "cancel":return styleText("red",V);case "error":return styleText("yellow",V);case "submit":return styleText("green",V)}},fx=e=>e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109,mx=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,dx=e=>e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101632&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129672||e>=129680&&e<=129725||e>=129727&&e<=129733||e>=129742&&e<=129755||e>=129760&&e<=129768||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141,ol=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,ri=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ni=/\t{1,1000}/y,al=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,si=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,hx=/\p{M}+/gu,gx={limit:1/0,ellipsis:""},bm=(e,t={},r={})=>{let n=t.limit??1/0,s=t.ellipsis??"",i=t?.ellipsisWidth??(s?bm(s,gx,r).width:0),o=r.ansiWidth??0,a=r.controlWidth??0,l=r.tabWidth??8,c=r.ambiguousWidth??1,u=r.emojiWidth??2,p=r.fullWidthWidth??2,f=r.regularWidth??1,g=r.wideWidth??2,d=0,m=0,y=e.length,h=0,S=false,T=y,$=Math.max(0,n-i),P=0,N=0,v=0,_=0;e:for(;;){if(N>P||m>=y&&m>d){let I=e.slice(P,N)||e.slice(d,m);h=0;for(let b of I.replaceAll(hx,"")){let D=b.codePointAt(0)||0;if(mx(D)?_=p:dx(D)?_=g:c!==f&&fx(D)?_=c:_=f,v+_>$&&(T=Math.min(T,Math.max(P,d)+h)),v+_>n){S=true;break e}h+=b.length,v+=_;}P=N=0;}if(m>=y)break;if(si.lastIndex=m,si.test(e)){if(h=si.lastIndex-m,_=h*f,v+_>$&&(T=Math.min(T,m+Math.floor(($-v)/f))),v+_>n){S=true;break}v+=_,P=d,N=m,m=d=si.lastIndex;continue}if(ol.lastIndex=m,ol.test(e)){if(v+o>$&&(T=Math.min(T,m)),v+o>n){S=true;break}v+=o,P=d,N=m,m=d=ol.lastIndex;continue}if(ri.lastIndex=m,ri.test(e)){if(h=ri.lastIndex-m,_=h*a,v+_>$&&(T=Math.min(T,m+Math.floor(($-v)/a))),v+_>n){S=true;break}v+=_,P=d,N=m,m=d=ri.lastIndex;continue}if(ni.lastIndex=m,ni.test(e)){if(h=ni.lastIndex-m,_=h*l,v+_>$&&(T=Math.min(T,m+Math.floor(($-v)/l))),v+_>n){S=true;break}v+=_,P=d,N=m,m=d=ni.lastIndex;continue}if(al.lastIndex=m,al.test(e)){if(v+u>$&&(T=Math.min(T,m)),v+u>n){S=true;break}v+=u,P=d,N=m,m=d=al.lastIndex;continue}m+=1;}return {width:S?$:v,index:S?T:y,truncated:S,ellipsed:S&&n>=i}},yx={limit:1/0,ellipsis:"",ellipsisWidth:0},xn=(e,t={})=>bm(e,yx,t).width,li="\x1B",Sm="\x9B",wx=39,ml="\x07",Em="[",bx="]",xm="m",dl=`${bx}8;;`,dm=new RegExp(`(?:\\${Em}(?<code>\\d+)m|\\${dl}(?<uri>.*)${ml})`,"y"),Sx=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},hm=e=>`${li}${Em}${e}${xm}`,gm=e=>`${li}${dl}${e}${ml}`,Ex=e=>e.map(t=>xn(t)),ll=(e,t,r)=>{let n=t[Symbol.iterator](),s=false,i=false,o=e.at(-1),a=o===void 0?0:xn(o),l=n.next(),c=n.next(),u=0;for(;!l.done;){let p=l.value,f=xn(p);a+f<=r?e[e.length-1]+=p:(e.push(p),a=0),(p===li||p===Sm)&&(s=true,i=t.startsWith(dl,u+1)),s?i?p===ml&&(s=false,i=false):p===xm&&(s=false):(a+=f,a===r&&!c.done&&(e.push(""),a=0)),l=c,c=n.next(),u+=p.length;}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop());},xx=e=>{let t=e.split(" "),r=t.length;for(;r>0&&!(xn(t[r-1])>0);)r--;return r===t.length?e:t.slice(0,r).join(" ")+t.slice(r).join("")},_x=(e,t,r={})=>{if(r.trim!==false&&e.trim()==="")return "";let n="",s,i,o=e.split(" "),a=Ex(o),l=[""];for(let[d,m]of o.entries()){r.trim!==false&&(l[l.length-1]=(l.at(-1)??"").trimStart());let y=xn(l.at(-1)??"");if(d!==0&&(y>=t&&(r.wordWrap===false||r.trim===false)&&(l.push(""),y=0),(y>0||r.trim===false)&&(l[l.length-1]+=" ",y++)),r.hard&&a[d]>t){let h=t-y,S=1+Math.floor((a[d]-h-1)/t);Math.floor((a[d]-1)/t)<S&&l.push(""),ll(l,m,t);continue}if(y+a[d]>t&&y>0&&a[d]>0){if(r.wordWrap===false&&y<t){ll(l,m,t);continue}l.push("");}if(y+a[d]>t&&r.wordWrap===false){ll(l,m,t);continue}l[l.length-1]+=m;}r.trim!==false&&(l=l.map(d=>xx(d)));let c=l.join(`
|
|
138
|
+
`),u=c[Symbol.iterator](),p=u.next(),f=u.next(),g=0;for(;!p.done;){let d=p.value,m=f.value;if(n+=d,d===li||d===Sm){dm.lastIndex=g+1;let h=dm.exec(c)?.groups;if(h?.code!==void 0){let S=Number.parseFloat(h.code);s=S===wx?void 0:S;}else h?.uri!==void 0&&(i=h.uri.length===0?void 0:h.uri);}let y=s?Sx(s):void 0;m===`
|
|
139
|
+
`?(i&&(n+=gm("")),s&&y&&(n+=hm(y))):d===`
|
|
140
|
+
`&&(s&&y&&(n+=hm(s)),i&&(n+=gm(i))),g+=d.length,p=f,f=u.next();}return n};$x=(e,t,r,n,s)=>{let i=t,o=0;for(let a=r;a<n;a++){let l=e[a];if(i=i-l.length,o++,i<=s)break}return {lineCount:i,removals:o}},vx=({cursor:e,options:t,style:r,output:n=process.stdout,maxItems:s=Number.POSITIVE_INFINITY,columnPadding:i=0,rowPadding:o=4})=>{let a=ei(n)-i,l=sl(n),c=styleText("dim","..."),u=Math.max(l-o,0),p=Math.max(Math.min(s,u),5),f=0;e>=p-3&&(f=Math.max(Math.min(e-p+3,t.length-p),0));let g=p<t.length&&f>0,d=p<t.length&&f+p<t.length,m=Math.min(f+p,t.length),y=[],h=0;g&&h++,d&&h++;let S=f+(g?1:0),T=m-(d?1:0);for(let P=S;P<T;P++){let N=pl(r(t[P],P===e),a,{hard:true,trim:false}).split(`
|
|
141
|
+
`);y.push(N),h+=N.length;}if(h>u){let P=0,N=0,v=h,_=e-S,I=(b,D)=>$x(y,v,b,D,u);g?({lineCount:v,removals:P}=I(0,_),v>u&&({lineCount:v,removals:N}=I(_+1,y.length))):({lineCount:v,removals:N}=I(_+1,y.length),v>u&&({lineCount:v,removals:P}=I(0,_))),P>0&&(g=true,y.splice(0,P)),N>0&&(d=true,y.splice(y.length-N,N));}let $=[];g&&$.push(c);for(let P of y)for(let N of P)$.push(N);return d&&$.push(c),$},_n=e=>{let t=e.active??"Yes",r=e.inactive??"No";return new Xs({active:t,inactive:r,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??true,render(){let n=e.withGuide??Oe.withGuide,s=`${n?`${styleText("gray",V)}
|
|
142
|
+
`:""}${ai(this.state)} ${e.message}
|
|
140
143
|
`,i=this.value?t:r;switch(this.state){case "submit":{let o=n?`${styleText("gray",V)} `:"";return `${s}${o}${styleText("dim",i)}`}case "cancel":{let o=n?`${styleText("gray",V)} `:"";return `${s}${o}${styleText(["strikethrough","dim"],i)}${n?`
|
|
141
|
-
${styleText("gray",V)}`:""}`}default:{let o=n?`${styleText("cyan",V)} `:"",a=n?styleText("cyan",
|
|
144
|
+
${styleText("gray",V)}`:""}`}default:{let o=n?`${styleText("cyan",V)} `:"",a=n?styleText("cyan",mr):"";return `${s}${o}${this.value?`${styleText("green",ul)} ${t}`:`${styleText("dim",oi)} ${styleText("dim",t)}`}${e.vertical?n?`
|
|
142
145
|
${styleText("cyan",V)} `:`
|
|
143
|
-
`:` ${styleText("dim","/")} `}${this.value?`${styleText("dim",
|
|
146
|
+
`:` ${styleText("dim","/")} `}${this.value?`${styleText("dim",oi)} ${styleText("dim",r)}`:`${styleText("green",ul)} ${r}`}
|
|
144
147
|
${a}
|
|
145
148
|
`}}}}).prompt()},K={message:(e=[],{symbol:t=styleText("gray",V),secondarySymbol:r=styleText("gray",V),output:n=process.stdout,spacing:s=1,withGuide:i}={})=>{let o=[],a=i??Oe.withGuide,l=a?r:"",c=a?`${t} `:"",u=a?`${r} `:"";for(let f=0;f<s;f++)o.push(l);let p=Array.isArray(e)?e:e.split(`
|
|
146
149
|
`);if(p.length>0){let[f,...g]=p;f.length>0?o.push(`${c}${f}`):o.push(a?t:"");for(let d of g)d.length>0?o.push(`${u}${d}`):o.push(a?r:"");}n.write(`${o.join(`
|
|
147
150
|
`)}
|
|
148
|
-
`);},info:(e,t)=>{K.message(e,{...t,symbol:styleText("blue",
|
|
149
|
-
`:""}${
|
|
150
|
-
`,n=this.userInputWithCursor,s=this.masked;switch(this.state){case "error":{let i=t?`${styleText("yellow",V)} `:"",o=t?`${styleText("yellow",
|
|
151
|
+
`);},info:(e,t)=>{K.message(e,{...t,symbol:styleText("blue",ax)});},success:(e,t)=>{K.message(e,{...t,symbol:styleText("green",lx)});},step:(e,t)=>{K.message(e,{...t,symbol:styleText("green",fl)});},warn:(e,t)=>{K.message(e,{...t,symbol:styleText("yellow",cx)});},warning:(e,t)=>{K.warn(e,t);},error:(e,t)=>{K.message(e,{...t,symbol:styleText("red",ux)});}},$n=e=>new Js({validate:e.validate,mask:e.mask??ox,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??Oe.withGuide,r=`${t?`${styleText("gray",V)}
|
|
152
|
+
`:""}${ai(this.state)} ${e.message}
|
|
153
|
+
`,n=this.userInputWithCursor,s=this.masked;switch(this.state){case "error":{let i=t?`${styleText("yellow",V)} `:"",o=t?`${styleText("yellow",mr)} `:"",a=s??"";return e.clearOnError&&this.clear(),`${r.trim()}
|
|
151
154
|
${i}${a}
|
|
152
155
|
${o}${styleText("yellow",this.error)}
|
|
153
156
|
`}case "submit":{let i=t?`${styleText("gray",V)} `:"",o=s?styleText("dim",s):"";return `${r}${i}${o}`}case "cancel":{let i=t?`${styleText("gray",V)} `:"",o=s?styleText(["strikethrough","dim"],s):"";return `${r}${i}${o}${s&&t?`
|
|
154
|
-
${styleText("gray",V)}`:""}`}default:{let i=t?`${styleText("cyan",V)} `:"",o=t?styleText("cyan",
|
|
157
|
+
${styleText("gray",V)}`:""}`}default:{let i=t?`${styleText("cyan",V)} `:"",o=t?styleText("cyan",mr):"";return `${r}${i}${n}
|
|
155
158
|
${o}
|
|
156
|
-
`}}}}).prompt(),
|
|
157
|
-
`);let E=
|
|
158
|
-
`);E.length>1&&r.write(
|
|
159
|
-
`);let x=0,
|
|
159
|
+
`}}}}).prompt(),Tx=e=>styleText("magenta",e),hl=({indicator:e="dots",onCancel:t,output:r=process.stdout,cancelMessage:n,errorMessage:s,frames:i=cl?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=cl?80:120,signal:a,...l}={})=>{let c=sx(),u,p,f=false,g=false,d="",m,y=performance.now(),h=ei(r),S=l?.styleFrame??Tx,T=E=>{let x=E>1?s??Oe.messages.error:n??Oe.messages.cancel;g=E===1,f&&(F(x,E),g&&typeof t=="function"&&t());},$=()=>T(2),P=()=>T(1),N=()=>{process.on("uncaughtExceptionMonitor",$),process.on("unhandledRejection",$),process.on("SIGINT",P),process.on("SIGTERM",P),process.on("exit",T),a&&a.addEventListener("abort",P);},v=()=>{process.removeListener("uncaughtExceptionMonitor",$),process.removeListener("unhandledRejection",$),process.removeListener("SIGINT",P),process.removeListener("SIGTERM",P),process.removeListener("exit",T),a&&a.removeEventListener("abort",P);},_=()=>{if(m===void 0)return;c&&r.write(`
|
|
160
|
+
`);let E=pl(m,h,{hard:true,trim:false}).split(`
|
|
161
|
+
`);E.length>1&&r.write(En.cursor.up(E.length-1)),r.write(En.cursor.to(0)),r.write(En.erase.down());},I=E=>E.replace(/\.+$/,""),b=E=>{let x=(performance.now()-E)/1e3,J=Math.floor(x/60),q=Math.floor(x%60);return J>0?`[${J}m ${q}s]`:`[${q}s]`},D=l.withGuide??Oe.withGuide,R=(E="")=>{f=true,u=mm({output:r}),d=I(E),y=performance.now(),D&&r.write(`${styleText("gray",V)}
|
|
162
|
+
`);let x=0,J=0;N(),p=setInterval(()=>{if(c&&d===m)return;_(),m=d;let q=S(i[x]),j;if(c)j=`${q} ${d}...`;else if(e==="timer")j=`${q} ${d} ${b(y)}`;else {let ce=".".repeat(Math.floor(J)).slice(0,3);j=`${q} ${d}${ce}`;}let se=pl(j,h,{hard:true,trim:false});r.write(se),x=x+1<i.length?x+1:0,J=J<4?J+.125:0;},o);},F=(E="",x=0,J=false)=>{if(!f)return;f=false,clearInterval(p),_();let q=x===0?styleText("green",fl):x===1?styleText("red",ym):styleText("red",wm);d=E??d,J||(e==="timer"?r.write(`${q} ${d} ${b(y)}
|
|
160
163
|
`):r.write(`${q} ${d}
|
|
161
|
-
`)),v(),u();};return {start:R,stop:(E="")=>F(E,0),message:(E="")=>{d=I(E??d);},cancel:(E="")=>F(E,1),error:(E="")=>F(E,2),clear:()=>F("",0,true),get isCancelled(){return g}}},{light:
|
|
164
|
+
`)),v(),u();};return {start:R,stop:(E="")=>F(E,0),message:(E="")=>{d=I(E??d);},cancel:(E="")=>F(E,1),error:(E="")=>F(E,2),clear:()=>F("",0,true),get isCancelled(){return g}}},{light:X("\u2500","-"),heavy:X("\u2501","="),block:X("\u2588","#")},ii=(e,t)=>e.includes(`
|
|
162
165
|
`)?e.split(`
|
|
163
166
|
`).map(r=>t(r)).join(`
|
|
164
|
-
`):t(e),
|
|
167
|
+
`):t(e),vn=e=>{let t=(r,n)=>{let s=r.label??String(r.value);switch(n){case "disabled":return `${styleText("gray",oi)} ${ii(s,i=>styleText("gray",i))}${r.hint?` ${styleText("dim",`(${r.hint??"disabled"})`)}`:""}`;case "selected":return `${ii(s,i=>styleText("dim",i))}`;case "active":return `${styleText("green",ul)} ${s}${r.hint?` ${styleText("dim",`(${r.hint})`)}`:""}`;case "cancelled":return `${ii(s,i=>styleText(["strikethrough","dim"],i))}`;default:return `${styleText("dim",oi)} ${ii(s,i=>styleText("dim",i))}`}};return new Ys({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let r=e.withGuide??Oe.withGuide,n=`${ai(this.state)} `,s=`${px(this.state)} `,i=ti(e.output,e.message,s,n),o=`${r?`${styleText("gray",V)}
|
|
165
168
|
`:""}${i}
|
|
166
|
-
`;switch(this.state){case "submit":{let a=r?`${styleText("gray",V)} `:"",l=
|
|
167
|
-
${styleText("gray",V)}`:""}`}default:{let a=r?`${styleText("cyan",V)} `:"",l=r?styleText("cyan",
|
|
168
|
-
`).length,u=r?2:1;return `${o}${a}${
|
|
169
|
+
`;switch(this.state){case "submit":{let a=r?`${styleText("gray",V)} `:"",l=ti(e.output,t(this.options[this.cursor],"selected"),a);return `${o}${l}`}case "cancel":{let a=r?`${styleText("gray",V)} `:"",l=ti(e.output,t(this.options[this.cursor],"cancelled"),a);return `${o}${l}${r?`
|
|
170
|
+
${styleText("gray",V)}`:""}`}default:{let a=r?`${styleText("cyan",V)} `:"",l=r?styleText("cyan",mr):"",c=o.split(`
|
|
171
|
+
`).length,u=r?2:1;return `${o}${a}${vx({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:c+u,style:(p,f)=>t(p,p.disabled?"disabled":f?"active":"inactive")}).join(`
|
|
169
172
|
${a}`)}
|
|
170
173
|
${l}
|
|
171
|
-
`}}}}).prompt()},`${styleText("gray",V)} `,
|
|
172
|
-
`:""}${
|
|
173
|
-
`,n=e.placeholder?styleText("inverse",e.placeholder[0])+styleText("dim",e.placeholder.slice(1)):styleText(["inverse","hidden"],"_"),s=this.userInput?this.userInputWithCursor:n,i=this.value??"";switch(this.state){case "error":{let o=this.error?` ${styleText("yellow",this.error)}`:"",a=t?`${styleText("yellow",V)} `:"",l=t?styleText("yellow",
|
|
174
|
+
`}}}}).prompt()},`${styleText("gray",V)} `,Tn=e=>new Qs({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??Oe.withGuide,r=`${`${t?`${styleText("gray",V)}
|
|
175
|
+
`:""}${ai(this.state)} `}${e.message}
|
|
176
|
+
`,n=e.placeholder?styleText("inverse",e.placeholder[0])+styleText("dim",e.placeholder.slice(1)):styleText(["inverse","hidden"],"_"),s=this.userInput?this.userInputWithCursor:n,i=this.value??"";switch(this.state){case "error":{let o=this.error?` ${styleText("yellow",this.error)}`:"",a=t?`${styleText("yellow",V)} `:"",l=t?styleText("yellow",mr):"";return `${r.trim()}
|
|
174
177
|
${a}${s}
|
|
175
178
|
${l}${o}
|
|
176
179
|
`}case "submit":{let o=i?` ${styleText("dim",i)}`:"",a=t?styleText("gray",V):"";return `${r}${a}${o}`}case "cancel":{let o=i?` ${styleText(["strikethrough","dim"],i)}`:"",a=t?styleText("gray",V):"";return `${r}${a}${o}${i.trim()?`
|
|
177
|
-
${a}`:""}`}default:{let o=t?`${styleText("cyan",V)} `:"",a=t?styleText("cyan",
|
|
180
|
+
${a}`:""}`}default:{let o=t?`${styleText("cyan",V)} `:"",a=t?styleText("cyan",mr):"";return `${r}${o}${s}
|
|
178
181
|
${a}
|
|
179
|
-
`}}}}).prompt();});function
|
|
180
|
-
`.repeat(t?.paddingVertical??1),o=t?.renderCell??((a,l)=>l===null?
|
|
182
|
+
`}}}}).prompt();});function $m(e,t){let r=t?.renderHeader??(a=>String(a)),n=Object.keys(e[0]).filter(a=>!t?.omitKeys?.includes(a)).map(a=>{let l=r(a),c=Math.max(l.length,...e.map(u=>String(u[a]).length));return {key:a,header:l,length:c}}),s=" ".repeat(t?.paddingHorizontal??1),i=`
|
|
183
|
+
`.repeat(t?.paddingVertical??1),o=t?.renderCell??((a,l)=>l===null?_m.default.dim("null"):String(l));return `${i}${s}| ${n.map(a=>a.header.padEnd(a.length)).join(" | ")} |
|
|
181
184
|
${s}| ${n.map(a=>"\u2500".repeat(a.length)).join(" | ")} |
|
|
182
185
|
${e.map(a=>`${s}| ${Object.entries(a).filter(([l])=>!t?.omitKeys?.includes(l)).map(([l,c])=>o(l,c).padEnd(n.find(u=>u.key===l)?.length??0)).join(" | ")} |`).join(`
|
|
183
|
-
`)}${i}`}async function Z(e){try{await e(),process.exit(0);}catch(t){(process.env.LOCAL||process.env.DEBUG)&&console.error(t),K.error(String(t)),process.exit(1);}}var
|
|
186
|
+
`)}${i}`}async function Z(e){try{await e(),process.exit(0);}catch(t){(process.env.LOCAL||process.env.DEBUG)&&console.error(t),K.error(String(t)),process.exit(1);}}var _m,Le=w(()=>{_m=ee(ie());Ye();});function Tm(e){return typeof e=="object"&&e!==null&&"text"in e&&"values"in e}function Rx(e,t){if(e==null)return e;switch(t){case 20:return typeof e=="bigint"?e:BigInt(e);case 22:return Array.isArray(e)?e:typeof e=="string"?e.split(" ").map(Number).filter(r=>!Number.isNaN(r)):e;case 1002:case 1009:case 1015:return typeof e=="string"?vm(e,Ax):e;case 1005:case 1007:case 1016:return typeof e=="string"?vm(e,Cx):e;default:return e}}function gl(e){return {async query(t,r){let n=Tm(t)?t.text:t,s=Tm(t)?t.values:r??[],i=await e.driver.query(n,[...s]);return {rows:i.rows.map(a=>Object.fromEntries(i.fields.map(l=>[l.name,Rx(a[l.name],l.dataTypeID)])))}}}}var vm,Ax,Cx,Am=w(()=>{vm=(e,t=r=>r)=>{if(!e||e==="{}")return [];let r=e.slice(1,-1);if(r==="")return [];let n=[],s="",i=false,o=0;for(let a=0;a<r.length;a++){let l=r[a];l==='"'&&r[a-1]!=="\\"?(i=!i,s+=l):l==="{"&&!i?(o++,s+=l):l==="}"&&!i?(o--,s+=l):l===","&&!i&&o===0?(n.push(t(s)),s=""):s+=l;}return s!==""&&n.push(t(s)),n},Ax=e=>e==="NULL"?null:e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\(.)/g,"$1"):e,Cx=e=>e==="NULL"?null:Number.parseInt(e,10);});function Nx(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`(?<![\\w$"])${r}\\.`);return e.some(s=>n.test(s))}function Cm(e,t){let r=new Set;for(let n of t)for(let s of n.matchAll(Px))r.add(s[1]);return Object.values(e.schemas).map(n=>n.name).filter(n=>!kx.has(n)&&!r.has(n)&&Nx(t,n)).map(n=>`CREATE SCHEMA IF NOT EXISTS ${n};`)}var kx,Px,Rm=w(()=>{kx=new Set(["public","supabase_migrations"]),Px=/\bCREATE\s+SCHEMA\b(?:\s+IF\s+NOT\s+EXISTS)?\s+("?[\w$]+"?)/gi;});async function Ix(){try{return await import('@supabase/pg-delta')}catch(e){throw new Error("Postgres schema diffing requires pg-delta to be available.",{cause:e})}}function Lx(e){let t=/^drop table (.+)$/.exec(e);if(t)return {table:t[1],reason:"drop table"};let r=/^drop column (.+) on (.+)$/.exec(e);if(r)return {table:r[2],reason:`drop column ${r[1]}`};let n=/^drop sequence (.+)$/.exec(e);return n?{table:n[1],reason:"drop sequence"}:{table:"unknown",reason:e}}function Dx(e,t){let r=qs(e),n=new Set([...gt(e),...gt(t)]);return new Set(pr.filter(s=>n.has(s)&&!r.has(s)))}function jx(e){let t=e.trimEnd();return t.endsWith(";")?t:`${t};`}async function km(e,t,r=""){let{createPlan:n,extractCatalog:s}=await Ix(),{PgliteConnection:i}=await qe("@supabase/lite/pglite","pglite","@electric-sql/pglite"),o=new i,a=new i;try{let l=Xf(t),c=Dx(e,t),u=gt(t);await o.exec(ht(c)),await a.exec(ht(u)),o.config.baseSchema&&await o.exec(o.config.baseSchema),a.config.baseSchema&&await a.exec(a.config.baseSchema),r.trim()&&(await o.exec(r),await a.exec(r)),e.trim()&&await o.exec(e),t.trim()&&await a.exec(t);let p=await s(gl(o)),f=await s(gl(a)),g=await n(p,f);if(!g)return "";if(g.plan.risk?.level==="data_loss")throw new DataLossError(g.plan.risk.statements.map(Lx));let d=g.plan.statements.filter(y=>!Jf(y,l));return [...Cm(f,d),...d.map(jx)].join(`
|
|
184
187
|
|
|
185
|
-
`)}finally{await o.close().catch(()=>{}),await a.close().catch(()=>{});}}var
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
`)+(i.length?";":""));return}Uf(s);});});};});var km={};de(km,{migration:()=>Px});var ae,kx,Px,Pm=y(()=>{ae=ee(ie());Be();Ct();Bs();Cs();Ce();Ee();Je();kx="Local Development:",Px=e=>{let t=e.command("migration").description("Manage database migrations").helpGroup(kx);t.command("diff").description(ge("Diff DB state against schemas/*.sql")).option("--config <config>","Path to the config file").option("--execute","Execute the migration").option("--force","Force the migration",false).option("--sql","Show the SQL for the migration",false).option("--seed","Seed the database with data",false).action(async r=>{await Y(r.config);let s=await(await z({withSupabaseClient:false})).project.local.createApp(r.config),i=await fe(s),o=s.connection.createMigrator(i),a=await o.diff();if(console.log(),a.plan.steps.length>0){pt(a);let l=null;try{r.execute&&(await o.migratePlan(a.plan,{force:r.force??!1}),ja(a),console.log());}catch(c){l=c;}if(r.sql){let c=r.execute?l?ae.default.red:ae.default.green:ae.default.cyan;console.log(c(mn(a,{colorize:true})));}l&&(l instanceof DataLossError&&(console.log(),console.warn(ae.default.yellow("Migration would potentially cause data loss. Rerun with --force to proceed.")),process.exit(1)),console.error(ae.default.red("Migration error: "+String(l))),process.exit(1)),r.execute||console.log(ae.default.yellow("Migration not executed. Use --execute to execute."));}else console.log(ae.default.green("No changes to migrate."));r.seed&&await Da(s),process.exit(0);}),t.command("new").description("Create a new empty migration file").argument("<name>","The migration name").option("--config <config>","Path to the config file").action(async(r,n)=>{await Y(n.config);let i=await(await z({withSupabaseClient:false})).project.local.createApp(n.config),o=await Sf(i,r);console.log(ae.default.green(" \u279C"),"Created",ae.default.cyan(We__default.relative(process.cwd(),o))),process.exit(0);}),t.command("up").description("Apply pending migrations from the migrations directory").option("--config <config>","Path to the config file").option("--dry-run","Print pending migrations without applying",false).action(async r=>{await Y(r.config);let s=await(await z({withSupabaseClient:false})).project.local.createApp(r.config);if(r.dryRun){await Hr(s.connection);let i=new Set(await Wr(s.connection)),a=(await Ke(s)).filter(l=>!i.has(l.version));a.length===0&&(console.log(ae.default.green("No pending migrations.")),process.exit(0)),console.log(ae.default.dim("Pending:"));for(let l of a)console.log(" "+ae.default.cyan(l.filename));process.exit(0);}try{let i=await jt(s);if(i.applied.length===0)console.log(ae.default.green("Local database is up to date."));else for(let o of i.applied)console.log(ae.default.green(" \u2713"),"Applied",ae.default.cyan(o.filename));process.exit(0);}catch(i){console.error(ae.default.red("Migration failed: "+String(i.message??i))),process.exit(1);}}),t.command("list").description("List applied and pending migrations").option("--config <config>","Path to the config file").action(async r=>{await Y(r.config);let s=await(await z({withSupabaseClient:false})).project.local.createApp(r.config);await Hr(s.connection);let i=new Set(await Wr(s.connection)),o=await Ke(s);console.log(ae.default.dim(`Migrations in ${At(s)}:`)),o.length===0&&console.log(ae.default.dim(" (none)"));for(let c of o){let u=i.has(c.version)?ae.default.green("[applied]"):ae.default.yellow("[pending]");console.log(` ${u} ${ae.default.cyan(c.filename)}`);}let a=new Set(o.map(c=>c.version)),l=[...i].filter(c=>!a.has(c));if(l.length>0){console.log(),console.log(ae.default.dim("Recorded versions without matching file:"));for(let c of l)console.log(` ${ae.default.red("[orphan]")} ${c}`);}process.exit(0);});};});function Ox(e){let t=(e??process.env.SUPABASE_ENDPOINT??Nx).replace(/\/+$/,""),r=new URL(t),n=r.host;return {apiUrl:`${r.protocol}//${n.startsWith("api.")?n:`api.${n}`}`,projectDomain:n==="supabase.com"?"supabase.co":n}}function Nm(e){if(Array.isArray(e)){let t=e.find(n=>n.name==="anon")?.api_key??"",r=e.find(n=>n.name==="service_role")?.api_key??"";return {anon:t,service_role:r}}return e}var Nx,ai,Om=y(()=>{Nx="https://supabase.com";ai=class{constructor(t,r){this.token=t;if(!t)throw new Error("Supabase access token required");let n=Ox(r?.endpoint);this.apiUrl=n.apiUrl,this.projectDomain=n.projectDomain;}apiUrl;projectDomain;async request(t,r,n){let s=await fetch(`${this.apiUrl}${r}`,{method:t,headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json",Accept:"application/json"},body:n===void 0?void 0:JSON.stringify(n)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Supabase API ${t} ${r} failed: ${s.status} ${s.statusText}${o?` \u2014 ${o}`:""}`)}return (s.headers.get("content-type")??"").includes("application/json")?await s.json():await s.text()}listOrganizations(){return this.request("GET","/v1/organizations")}async validateToken(){try{return await this.listOrganizations(),!0}catch{return false}}listRegions(t){return this.request("GET",`/v1/projects/available-regions?organization_slug=${encodeURIComponent(t)}`)}createProject(t){return this.request("POST","/v1/projects",t)}getProject(t){return this.request("GET",`/v1/projects/${t}`)}getApiKeys(t){return this.request("GET",`/v1/projects/${t}/api-keys`)}updateAuthConfig(t,r){return this.request("PATCH",`/v1/projects/${t}/config/auth`,r)}createSigningKey(t,r){return this.request("POST",`/v1/projects/${t}/config/auth/signing-keys`,r)}runSql(t,r){return this.request("POST",`/v1/projects/${t}/database/query`,{query:r})}async waitForActive(t,r={}){let n=r.timeoutMs??6e5,s=r.intervalMs??5e3,i=Date.now();for(;;){let o=await this.getProject(t);if(r.onTick?.(o.status),o.status==="ACTIVE_HEALTHY")return o;if(Date.now()-i>n)throw new Error(`Timed out waiting for project ${t} to become ACTIVE_HEALTHY (last status: ${o.status})`);await new Promise(a=>setTimeout(a,s));}}};});function Lx(e){if(e==null||typeof e!="string")return true;try{return JSON.parse(e),!0}catch{return false}}function Dx(e){return e==null?true:typeof e!="string"?false:Ix.test(e)}function jx(e){if(e==null)return true;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="string")return false;let t=Date.parse(e);return !Number.isNaN(t)}function Im(e){if(!e)return;let t=e.match(/varchar\s*\(\s*(\d+)\s*\)/i);return t?Number(t[1]):void 0}function Lm(e){return e?/jsonb?/i.test(e):false}function Dm(e){return e?/\buuid\b/i.test(e):false}function jm(e){return e?/timestamp(tz)?|timestamp with|timestamp without/i.test(e):false}async function Fm(e){let t=await e.connection.introspect(),r=[],n=e.connection.dialect;for(let s of t.tables){let i=s.name,o=s.schema,a=n==="sqlite"&&o&&o!=="main"?`"${o}.${i}"`:o?`"${o}"."${i}"`:`"${i}"`,l=t.columns.filter(g=>g.table===i&&(g.schema??o)===o),c=0,u=[];try{let g=await e.connection.exec(`SELECT COUNT(*) as c FROM ${a}`);c=Number(g?.rows?.[0]?.c??0);}catch{r.push({table:i,schema:o,rowCount:0,issues:u});continue}if(c===0){r.push({table:i,schema:o,rowCount:c,issues:u});continue}let p=l.filter(g=>Lm(g.type)||Dm(g.type)||jm(g.type)||Im(g.type)!==void 0);if(p.length===0){r.push({table:i,schema:o,rowCount:c,issues:u});continue}let f=p.map(g=>`"${g.name}"`).join(", ");try{let d=(await e.connection.exec(`SELECT ${f} FROM ${a}`))?.rows??[];for(let m of d)for(let w of p){let h=m[w.name];if(Lm(w.type)&&!Lx(h)){u.push({table:i,column:w.name,kind:"invalid_json",message:`row contains non-parseable JSON in ${i}.${w.name}`});continue}if(Dm(w.type)&&h!=null&&!Dx(h)){u.push({table:i,column:w.name,kind:"invalid_uuid",message:`row contains invalid UUID in ${i}.${w.name}`});continue}if(jm(w.type)&&!jx(h)){u.push({table:i,column:w.name,kind:"invalid_timestamp",message:`row contains unparseable timestamp in ${i}.${w.name}`});continue}let S=Im(w.type);S!==void 0&&typeof h=="string"&&h.length>S&&u.push({table:i,column:w.name,kind:"varchar_overflow",message:`value exceeds varchar(${S}) in ${i}.${w.name}`});}}catch{}r.push({table:i,schema:o,rowCount:c,issues:u});}return r}var Ix,Mm=y(()=>{Ix=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;});function gt(e){let t=[],r="",n=0,s=false,i=false,o=false,a=false,l=null;for(;n<e.length;){let u=e[n],p=e[n+1];if(o){r+=u,u===`
|
|
190
|
-
|
|
188
|
+
`)}finally{await o.close().catch(()=>{}),await a.close().catch(()=>{});}}var Pm=w(()=>{sr();Am();Rm();bn();});async function ci(e){let{parse:t}=await import('pgsql-parser');return t(e)}var Nm=w(()=>{});var ui,Om=w(()=>{ur();Lt();ui=class{constructor(t){this.ast=t;this.result=[...this.walk(this.ast,[],{trackPaths:["returningList"]})];}result=[];*walk(t=this.ast,r=[],n={}){if(!t||typeof t!="object")return;let{trackPaths:s=[]}=n;if(Array.isArray(t)){for(let o=0;o<t.length;o++)yield*this.walk(t[o],r,n);return}let i=Object.keys(t);if(i.length===1&&i[0][0]>="A"&&i[0][0]<="Z"){let o=i[0];yield {node:t,path:r},yield*this.walk(t[o],[...r,o],n);}else for(let[o,a]of Object.entries(t))if(a&&typeof a=="object"){let l=s.includes(o)?[...r,o]:r;yield*this.walk(a,l,n);}}containsUnsupportedNode(){for(let{node:t}of this.result){let r=cr(t),n=Ds.get(r);if(n&&n.react==="error")return true}}hasFuncCall(){for(let{node:t}of this.result)if("FuncCall"in t)return true;return false}getFuncCalls(){return Array.from(this.result).map(({node:t})=>t).filter(t=>"FuncCall"in t).map(t=>t.FuncCall)}getFuncCallNames(){return this.getFuncCalls().flatMap(t=>t.funcname?.map(r=>r.String?.sval||r.String?.str))}hasSqlValueFunction(){for(let{node:t}of this.result)if("SQLValueFunction"in t)return true;return false}getSqlValueFunctions(){return Array.from(this.result).map(({node:t})=>t).filter(t=>"SQLValueFunction"in t).map(t=>t.SQLValueFunction)}getSqlValueFunctionNames(){return this.getSqlValueFunctions().map(t=>t.op)}hasUnsafeStar(){let t=this.result.filter(({node:r})=>"A_Star"in r);if(t.length===0)return false;for(let{path:r}of t)if(!r.includes("SelectStmt")&&!r.includes("returningList"))return true;return false}getRelationDefinitions(){return this.result.filter(({node:r})=>"CreateStmt"in r).map(({node:r})=>r.CreateStmt).map(r=>({relation:{relname:r.relation?.relname??"",inh:r.relation?.inh,relpersistence:r.relation?.relpersistence},columns:r.tableElts?.map(n=>{let s=n.ColumnDef?.typeName?.names?.map(o=>"String"in o?o.String.sval:""),i=s?.some(o=>o.toLowerCase().includes("pg_catalog"));return {name:n.ColumnDef?.colname??"",is_local:n.ColumnDef?.is_local,pg_catalog:i,type:s?.filter(o=>!o.toLowerCase().includes("pg_catalog"))[0]??"",types:s,constraints:n.ColumnDef?.constraints}})}))}getRelationColumnTypes(){return {has_non_pg_catalog_types:this.getRelationDefinitions().some(t=>t.columns?.some(r=>!r.pg_catalog)),types:Array.from(new Set(this.getRelationDefinitions().flatMap(t=>t.columns?.map(r=>r.type))))}}};});var Fx,Mx,Ux,Bx,dr,pi,Im=w(()=>{ur();Fx=["DECLARE","IF","ELSIF","ELSE","LOOP","WHILE","FOR","FOREACH","EXCEPTION","RAISE","PERFORM","EXECUTE","SELECT"],Mx=/^NEW\.(\w+)\s*(?::=|=)\s*(.+)$/is,Ux=/^RETURN\s+(NEW|OLD)$/i,Bx=/^(INSERT|UPDATE|DELETE)\b/i,dr=class extends Dt{constructor(r,n,s){super(s??`Unsupported PL/pgSQL: ${r}`);this.hint=r;this.body=n;}},pi=class{parse(t){let r=this.extractBlock(t),n=this.splitStatements(r),s=[],i=null;for(let o of n){let a=o.trim();if(!a)continue;this.rejectUnsupported(a);let l=a.match(Ux);if(l){i=l[1].toUpperCase(),s.push({type:"return",value:i});continue}let c=a.match(Mx);if(c){s.push({type:"assignment",column:c[1],expression:c[2].trim()});continue}if(Bx.test(a)){s.push({type:"dml",sql:a});continue}throw new dr(`"${a.substring(0,80)}" is not translatable to SQLite`,r)}if(!i)throw new Dt("Trigger function body must end with RETURN NEW or RETURN OLD");return {statements:s,returnValue:i}}extractBlock(t){let r=t.trim(),n=r.toUpperCase();if(/^\s*DECLARE\b/i.test(r))throw new dr('"DECLARE" is not translatable to SQLite',t);let s=n.indexOf("BEGIN"),i=n.lastIndexOf("END");if(s===-1||i===-1||i<=s)throw new dr("Expected BEGIN ... END block in trigger function body",t);return r.slice(s+5,i).trim()}splitStatements(t){let r=[],n="",s=0,i=false,o="";for(let l=0;l<t.length;l++){let c=t[l];if(i){n+=c,c===o&&(l+1<t.length&&t[l+1]===o?n+=t[++l]:i=false);continue}if(c==="'"||c==='"'){i=true,o=c,n+=c;continue}if(c==="("){s++,n+=c;continue}if(c===")"){s--,n+=c;continue}if(c===";"&&s===0){r.push(n.trim()),n="";continue}n+=c;}let a=n.trim();return a&&r.push(a),r}rejectUnsupported(t){let r=t.match(/^(\w+)/)?.[1]?.toUpperCase();if(r&&Fx.includes(r))throw new dr(`"${r}" is not translatable to SQLite`,t)}};});var fi,mi=w(()=>{fi=class extends Error{constructor(r){super(`Migration would cause data loss:
|
|
189
|
+
${r.map(n=>` - ${n.table}: ${n.reason}`).join(`
|
|
190
|
+
`)}`);this.warnings=r;this.name="DataLossError";}};});var di,Lm=w(()=>{Jt();di=class{makeIndexKey(t){return `${t.table}:${t.name}:${t.unique}:${t.columns.join(",")}`}makeForeignKeyKey(t){return `${t.table}:${t.column}:${t.ref_table}:${t.ref_column}`}diff(t,r){let n=[],s=[],i=[],o=[],a=new Set(t.tables.map(m=>m.name)),l=new Set(r.tables.map(m=>m.name));for(let m of r.tables)a.has(m.name)||n.push({type:"added",name:m.name,sql:m.sql});for(let m of t.tables)l.has(m.name)||n.push({type:"removed",name:m.name});for(let m of t.tables){let y=r.tables.find(T=>T.name===m.name);if(!y)continue;let h=Zi(m.sql),S=Zi(y.sql);h!==S&&n.push({type:"modified",name:m.name,sql:y.sql});}let c=t.tables.filter(m=>l.has(m.name));for(let m of c){let y=t.columns.filter($=>$.table===m.name),h=r.columns.filter($=>$.table===m.name),S=new Map(y.map($=>[$.name,$])),T=new Map(h.map($=>[$.name,$]));for(let[$,P]of T)S.has($)||s.push({type:"added",table:m.name,name:$,column:P});for(let[$]of S)T.has($)||s.push({type:"removed",table:m.name,name:$});for(let[$,P]of S){let N=T.get($);if(!N)continue;let v={};Qi(P.type)!==Qi(N.type)&&(v.type={from:P.type,to:N.type}),P.nullable!==N.nullable&&(v.nullable={from:P.nullable,to:N.nullable}),eo(P.default_value)!==eo(N.default_value)&&(v.default_value={from:P.default_value,to:N.default_value}),Object.keys(v).length>0&&s.push({type:"modified",table:m.name,name:$,changes:v});}}let u=new Map(t.indexes.map(m=>[this.makeIndexKey(m),m])),p=new Map(r.indexes.map(m=>[this.makeIndexKey(m),m]));for(let[m,y]of p)u.has(m)||i.push({type:"added",...y});for(let[m,y]of u)p.has(m)||i.push({type:"removed",...y});let f=new Map(t.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m])),g=new Map(r.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m]));for(let[m,y]of g)f.has(m)||o.push({type:"added",...y});for(let[m,y]of f)g.has(m)||o.push({type:"removed",...y});let d=n.length>0||s.length>0||i.length>0||o.length>0;return {tables:n,columns:s,indexes:i,foreign_keys:o,has_changes:d}}};});var Hx,hi,Dm=w(()=>{mi();Pr();Hx=["CURRENT_TIMESTAMP","CURRENT_TIME","CURRENT_DATE"],hi=class{plan(t,r,n,s){if(!t.has_changes)return {steps:[],warnings:[],unsafe:false};let i=[],o=[];i.push({sql:"PRAGMA foreign_keys=OFF;",description:"Disable foreign key checks",type:"disable_foreign_keys"}),i.push({sql:"BEGIN;",description:"Begin transaction",type:"begin_transaction"});for(let p of t.tables.filter(f=>f.type==="added")){i.push({sql:`${p.sql};`,description:`CREATE TABLE ${U(p.name)}`,type:"create_table"});let f=n.indexes.filter(g=>g.table===p.name);for(let g of f){let d=g.unique?"UNIQUE ":"",m=g.columns.map(y=>U(y)).join(", ");i.push({sql:`CREATE ${d}INDEX ${U(g.name)} ON ${U(p.name)} (${m});`,description:`Create index ${U(g.name)} on ${U(p.name)}`,type:"add_index"});}}let a=new Set(r.tables.map(p=>p.name)),l=new Set(n.tables.map(p=>p.name)),c=new Set(t.tables.filter(p=>p.type==="modified").map(p=>p.name)),u=[...a].filter(p=>l.has(p));for(let p of u){if(!(c.has(p)||t.columns.some(m=>m.table===p)||t.indexes.some(m=>m.table===p)||t.foreign_keys.some(m=>m.table===p)))continue;let{canAlter:g,addedCols:d}=this.canSimpleAlter(p,t,n);if(g){for(let h of d)i.push({sql:`ALTER TABLE ${U(p)} ADD COLUMN ${this.columnDef(h)};`,description:`Add column ${U(h.name)} to ${U(p)}`,type:"add_column"});let m=t.indexes.filter(h=>h.table===p&&h.type==="added"),y=t.indexes.filter(h=>h.table===p&&h.type==="removed");for(let h of y)i.push({sql:`DROP INDEX IF EXISTS ${U(h.name)};`,description:`Drop index ${U(h.name)}`,type:"drop_index"});for(let h of m){let S=h.unique?"UNIQUE ":"",T=h.columns.map($=>U($)).join(", ");i.push({sql:`CREATE ${S}INDEX ${U(h.name)} ON ${U(p)} (${T});`,description:`Create index ${U(h.name)} on ${U(p)}`,type:"add_index"});}}else {let m=this.rebuildTable(p,r,n,t);i.push(...m.steps),o.push(...m.warnings);}}for(let p of t.tables.filter(f=>f.type==="removed"))i.push({sql:`DROP TABLE ${U(p.name)};`,description:`Drop table ${U(p.name)}`,type:"drop_table"}),o.push({table:p.name,reason:"table will be dropped"});return i.push({sql:"COMMIT;",description:"Commit transaction",type:"commit_transaction"}),i.push({sql:"PRAGMA foreign_keys=ON;",description:"Re-enable foreign key checks",type:"enable_foreign_keys"}),{steps:i,warnings:o,unsafe:o.length>0}}rebuildTable(t,r,n,s){let i=[],o=[],a=n.tables.find(h=>h.name===t);if(!a)return {steps:i,warnings:o};let l=`_${t}_migrate_new`,c=a.sql.replace(new RegExp(`(CREATE\\s+TABLE\\s+)(?:"${t}"|${t})`,"i"),`$1${U(l)}`);i.push({sql:`${c};`,description:`Create temporary table ${U(l)}`,type:"create_table"});let u=r.columns.filter(h=>h.table===t).map(h=>h.name),p=n.columns.filter(h=>h.table===t).map(h=>h.name),f=u.filter(h=>p.includes(h));if(f.length>0){let h=f.map(S=>U(S)).join(", ");i.push({sql:`INSERT INTO ${U(l)} (${h})
|
|
191
|
+
SELECT ${h}
|
|
192
|
+
FROM ${U(t)};`,description:`Copy data from ${U(t)} to ${U(l)}`,type:"copy_data"});}i.push({sql:`DROP TABLE ${U(t)};`,description:`Drop old table ${U(t)}`,type:"drop_table"}),i.push({sql:`ALTER TABLE ${U(l)} RENAME TO ${U(t)};`,description:`Rename ${U(l)} to ${U(t)}`,type:"rename_table"});let g=n.indexes.filter(h=>h.table===t);for(let h of g){let S=h.unique?"UNIQUE ":"",T=h.columns.map($=>U($)).join(", ");i.push({sql:`CREATE ${S}INDEX ${U(h.name)} ON ${U(t)} (${T});`,description:`Recreate index ${U(h.name)} on ${U(t)}`,type:"add_index"});}let d=n.triggers?.filter(h=>h.table===t)??[];for(let h of d)i.push({sql:`${h.sql};`,description:`Recreate trigger ${U(h.name)} on ${U(t)}`,type:"create_trigger"});let m=s.columns.filter(h=>h.table===t&&h.type==="removed");for(let h of m)o.push({table:t,reason:`column "${h.name}" will be dropped`});let y=s.columns.filter(h=>h.table===t&&h.type==="modified");for(let h of y)h.changes?.type&&o.push({table:t,reason:`column "${h.name}" type changes from ${h.changes.type.from} to ${h.changes.type.to}`}),h.changes?.nullable&&!h.changes.nullable.to&&o.push({table:t,reason:`column "${h.name}" becomes NOT NULL`});return {steps:i,warnings:o}}canSimpleAlter(t,r,n){let s=r.columns.filter(p=>p.table===t),i=s.filter(p=>p.type==="added"),o=s.filter(p=>p.type==="removed"),a=s.filter(p=>p.type==="modified"),l=r.foreign_keys.some(p=>p.table===t);if(o.length>0||a.length>0||l)return {canAlter:false,addedCols:i};let c=n.tables.find(p=>p.name===t);return c&&/\bCHECK\s*\(/i.test(c.sql)?{canAlter:false,addedCols:i}:{canAlter:i.every(p=>{let f=p.column;return this.hasNonConstantDefault(f.default_value)?false:f.nullable||f.default_value!=null})&&i.length>0,addedCols:i}}hasNonConstantDefault(t){if(t==null)return false;let r=t.trim().toUpperCase();return Hx.includes(r)}columnDef(t){let r=t.column,n=`${U(r.name)} ${r.type||"TEXT"}`;return r.nullable||(n+=" NOT NULL"),r.default_value!=null&&(n+=` DEFAULT ${r.default_value}`),n}};});function Kx(e){let t=e?.GrantStmt??e;return t?.is_grant!==true?false:t.targtype==="ACL_TARGET_ALL_IN_SCHEMA"?t.objtype==="OBJECT_TABLE"||t.objtype==="OBJECT_SEQUENCE":t.targtype==="ACL_TARGET_OBJECT"&&Vx.has(t.objtype)}var Vx,gi,jm=w(()=>{ur();Lt();Lt();Om();lt();Im();mi();Lm();Dm();Pr();Aa();Ra();Vx=new Set(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_SEQUENCE","OBJECT_SCHEMA"]);gi=class extends Deparser{enums;schemaHandling;warnings=[];helper;config;triggerFunctions=new Map;plpgsqlParser=new pi;introspection;functionResolution;serialColumns;constructor(t,{enums:r,schemaHandling:n,introspection:s,serialColumns:i,...o}={}){super(t,o),this.schemaHandling=n??"default",this.enums=r??new Map,this.helper=new ui(t),this.config=o,this.introspection=s,this.functionResolution=o?.functionResolution??"translate",this.serialColumns=i??new WeakSet;}visit(t,r){let n=cr(t);if(n==="GrantStmt"&&Kx(t))return "";let s=Ds.get(n);if(s){if(s.react==="error")throw new B({[n]:t},`Unsupported node type: ${n}`);return s.react==="warn"&&this.warnings.push({type:n,node:t}),""}return super.visit(t,r)}deparse(t,r){if(t==null)return null;if(!r){let n=new SqlFormatter;r=new DeparserContext({formatter:n});}return typeof t=="number"||t instanceof Number?t.toString():this.visit(t,r)}RawStmt(t,r){if(!t.stmt||t.stmt.CommentStmt)return "";let n=this.deparse(t.stmt,r);return !n||n.length===0?"":t.stmt_len?n+";":n}RangeVar(t,r){this.ensureRelation(t);let n=this.effectiveSchema(t.schemaname),s=t.relname,i=this.quoteBareIfNeeded(s);n&&(this.schemaHandling==="prefix"?i=`${n}__${s}`:i=`"${n}.${s}"`);let o=t.alias?" "+this.Alias(t.alias,r):"";return i+o}getRelationName(t){this.ensureRelation(t);let r=this.effectiveSchema(t.schemaname),n=t.relname;return r?this.schemaHandling==="prefix"?`${r}__${n}`:`${r}.${n}`:n}quoteBareIfNeeded(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:`"${t.replace(/"/g,'""')}"`}effectiveSchema(t){if(t){if(this.config.forceDefaultSchema||this.schemaHandling!=="default")return t;if(t!=="public")return t}}ensureRelation(t){let r=this.config.forceDefaultSchema;r&&(!t||typeof t!="object"||r.length===0||t.schemaname||(t.schemaname=r));}CreateStmt(t,r){if(t.inhRelations&&t.inhRelations.length>0)throw new B({CreateStmt:t},"Inheritance is not supported in SQLite");if(t.ofTypename!==void 0)throw new B({CreateStmt:t},"Typed tables (CREATE TABLE ... OF type_name) are not supported. Define columns directly in the CREATE TABLE statement instead.");if(t.options&&t.options.length>0&&(t.options=void 0),!t.tableElts||t.tableElts.length===0)throw new B({CreateStmt:t},"Empty tables are not supported in SQLite. Define at least one column.");return t.accessMethod&&(t.accessMethod=void 0),super.CreateStmt(t,r)+" STRICT"}TableLikeClause(t,r){throw new B({TableLikeClause:t},"CREATE TABLE ... (LIKE ...) is not supported in SQLite. Define the table columns explicitly instead.")}DefElem(t,r){if(["oids","fillfactor",/^autovacuum_/i,"toast_tuple_target","parallel_workers","user_catalog_table"].some(i=>Xc(t.defname??"",i)))return "";let s=super.DefElem(t,r);throw new B({DefElem:t},`DefElem "${t.defname}" (${s}) not supported`)}TypeName(t,r){if(!t.names)return "";let n=t.names.map(i=>i.String?i.String.sval||i.String.str:"").filter(Boolean);if(n.length===0)return "";let s=n.length===2&&n[0]==="pg_catalog"?n[1]:n.join(".");return t.arrayBounds&&t.arrayBounds.length>0||this.enums.has(s.toLowerCase())?"TEXT":kf(s)}ColumnDef(t,r){let n=[],s=t.colname;s&&n.push(this.quoteIfNeeded(s));let i=false,o=false,a=null,l=null,c=null,u=false;if(t.typeName){let p=t.typeName.names?.map(d=>d.String?.sval||d.String?.str).filter(Boolean);c=p&&(p.length===2&&p[0]==="pg_catalog"?p[1]:p[0]),i=!!(c&&Os(c))||this.serialColumns.has(t),u=!!(t.typeName.arrayBounds&&t.typeName.arrayBounds.length>0);let f=Array.isArray(t.typeName.typmods)?t.typeName.typmods:[],g=d=>f[d]?.A_Const?.ival?.ival??f[d]?.A_Const?.val?.ival?.ival;if(c&&Is(c)&&f.length>0){let d=g(0);typeof d=="number"&&d>0&&(a={maxLen:d});}if(c&&Ls(c)&&f.length>=2){let d=g(0),m=g(1);typeof d=="number"&&typeof m=="number"&&d>0&&m>=0&&(l={precision:d,scale:m});}if(t.constraints){let d=Array.isArray(t.constraints)?t.constraints:[];o=d.some(m=>m.Constraint?.contype==="CONSTR_PRIMARY"),d.some(m=>m.Constraint?.contype==="CONSTR_IDENTITY")&&(i=true);}n.push(this.TypeName(t.typeName,r));}if(t.constraints){let p=Array.isArray(t.constraints)?t.constraints:[],f=p.map(d=>this.visit(d,r));n.push(...f.filter(Boolean));let g=p.some(d=>d.Constraint?.contype==="CONSTR_CHECK");i&&o&&!g?n.push("AUTOINCREMENT"):i&&!o&&this.warnings.push({type:"ColumnDef",node:{ColumnDef:t},message:`Column "${s}" is serial/auto-increment but not the primary key; SQLite can't auto-increment a non-primary-key column, so it becomes a plain INTEGER (no auto-increment).`});}if(s&&c){let p={isArray:u};a&&(p.lengthConstraint=a.maxLen),l&&(p.numericPrecision=l);let f=this.enums.get(c.toLowerCase());f&&(p.enumValues=f);let m=Mt({schema:"public",table:"",column:s,pgTypeName:c,nullable:true,defaultValue:null,defaultFn:null,isPrimaryKey:o,isUnique:false,isSerial:i},p).checkConstraint();m&&n.push(`CHECK (${m})`);}return n.join(" ")}Constraint(t,r){let n=t.contype;if(n==="CONSTR_IDENTITY"||n==="CONSTR_ATTR_DEFERRABLE"||n==="CONSTR_ATTR_NOT_DEFERRABLE"||n==="CONSTR_ATTR_DEFERRED"||n==="CONSTR_ATTR_IMMEDIATE")return "";if(n==="CONSTR_NULL")return "NULL";if(n==="CONSTR_NOTNULL")return "NOT NULL";if(n==="CONSTR_DEFAULT"&&t.raw_expr){let s=this.visit(t.raw_expr,r);return s.includes("(")&&!s.startsWith("(")?`DEFAULT (${s})`:`DEFAULT ${s}`}if(n==="CONSTR_CHECK"&&t.raw_expr){let s=[];t.conname&&s.push("CONSTRAINT",Ns(t.conname)),s.push("CHECK");let i=this.visit(t.raw_expr,r);return s.push(`(${i})`),s.join(" ")}if(n==="CONSTR_PRIMARY")return t.keys&&t.keys.length>0?`PRIMARY KEY (${It(t.keys).map(i=>this.visit(i,r)).join(", ")})`:"PRIMARY KEY";if(n==="CONSTR_UNIQUE")return t.keys&&t.keys.length>0?`UNIQUE (${It(t.keys).map(i=>this.visit(i,r)).join(", ")})`:"UNIQUE";if(n==="CONSTR_FOREIGN")return super.Constraint(t,r).replace(/FOREIGN\s+KEY\s+REFERENCES/gi,"REFERENCES");if(n==="CONSTR_GENERATED"&&t.raw_expr)return `GENERATED ALWAYS AS (${this.visit(t.raw_expr,r)}) STORED`;if(n==="CONSTR_EXCLUSION")throw new B({Constraint:t},"EXCLUSION constraints are not supported in SQLite");return ""}FuncCall(t,r){let s=(t.funcname||[]).map(c=>c.String?.sval||c.String?.str).filter(Boolean);if(s.length===0)throw new Error("Function call has no name");let i=s[s.length-1].toLowerCase();if(i==="extract"&&t.args&&t.args.length>=2){let c=t.args[0];if((c?.A_Const?.sval?.sval||c?.String?.sval)==="epoch")return `strftime('%s', ${this.visit(t.args[1],r)})`}let a=(t.args??[]).map(c=>this.visit(c,r));if(t.agg_star)return `${i}(*)`;if(t.agg_distinct)return `${i}(DISTINCT ${a.join(", ")})`;let l=Ca(i,this.functionResolution);if(l){if(l.sqliteExpr!==null){let c=l.sqliteExpr;return c.includes("(")?c:`${c}(${a.join(", ")})`}if(l.jsFn!==null){let c=Us[i];if(c?.sqlite){let u=c.sqlite();return u.includes("(")?u:`${u}(${a.join(", ")})`}}}throw new B({FuncCall:t},`Function call "${i}" not supported`)}SQLValueFunction(t,r){switch(t.op){case "SVFOP_CURRENT_TIMESTAMP":return "datetime('now')";case "SVFOP_CURRENT_DATE":return "date('now')";case "SVFOP_CURRENT_TIME":return "time('now')";default:throw new B({SQLValueFunction:t},`SQLValueFunction "${t.op}" not supported`)}}ResTarget(t,r){if(t.indirection&&t.indirection.length>0)throw new B({ResTarget:t},"Indirections are not supported in SQLite");let n=[];return r.update&&t.name?(n.push(this.quoteIfNeeded(t.name)),n.push("="),t.val&&n.push(this.deparse(t.val,r))):r.insertColumns&&t.name?n.push(this.quoteIfNeeded(t.name)):(t.val&&n.push(this.deparse(t.val,r)),t.name&&n.push(this.Alias({aliasname:t.name},r))),n.join(" ")}A_Expr(t,r){if(["AEXPR_OP_ALL","AEXPR_OP_ANY"].includes(t.kind))throw new B({A_Expr:t},"ALL/ANY/SOME comparison operators are not supported. Use NOT EXISTS or IN instead");if(t.name&&t.name.length>0){if(t.name.length>1)throw new B({A_Expr:t},"Schema-qualified OPERATOR() syntax is not supported in SQLite");let n=t.name[0]?.String?.sval||t.name[0]?.String?.str;if(n){if(!t.lexpr||!t.rexpr)throw new B({A_Expr:t},"A_Expr missing left or right expression");if(!Rf.includes(n.toUpperCase()))throw new B({A_Expr:t},`Operator "${n}" is not supported in SQLite`);if(n==="~~"||n==="~~*"){let s=this.visit(t.lexpr,r),i=this.visit(t.rexpr,r);return `${s} LIKE ${i}`}if(n==="!~~"||n==="!~~*"){let s=this.visit(t.lexpr,r),i=this.visit(t.rexpr,r);return `${s} NOT LIKE ${i}`}if(n==="~"||n==="~*"){let s=this.visit(t.lexpr,r),i=this.visit(t.rexpr,r);return `${s} GLOB ${i}`}}}return super.A_Expr(t,r)}IndexStmt(t,r){let n=["CREATE"];t.unique&&n.push("UNIQUE"),n.push("INDEX"),t.if_not_exists&&n.push("IF NOT EXISTS"),t.idxname&&n.push(Ns(t.idxname)),n.push("ON"),t.relation&&n.push(this.RangeVar(t.relation,r));let s=(t.indexParams??[]).map(i=>"IndexElem"in i?this.IndexElem(i.IndexElem,r):this.visit(i,r)).filter(Boolean);return n.push(`(${s.join(", ")})`),n.join(" ")}IndexElem(t,r){let n=[];return t.name?n.push(Ns(t.name)):t.expr&&n.push(`(${this.visit(t.expr,r)})`),t.ordering==="SORTBY_ASC"&&n.push("ASC"),t.ordering==="SORTBY_DESC"&&n.push("DESC"),t.nulls_ordering==="SORTBY_NULLS_FIRST"&&n.push("NULLS FIRST"),t.nulls_ordering==="SORTBY_NULLS_LAST"&&n.push("NULLS LAST"),n.join(" ")}TypeCast(t,r){if(!t.arg||!t.typeName)return super.TypeCast(t,r);if([...this.helper.walk(t)].filter(({node:o})=>"A_Star"in o).length>0)throw new B({TypeCast:t},"A.* in type casts are not supported in SQLite");if(t.typeName.arrayBounds&&t.typeName.arrayBounds.length>0){if("A_Const"in t.arg&&t.arg.A_Const.sval){let o=t.arg.A_Const.sval.sval;if(o.startsWith("{")&&o.endsWith("}")){let a=t.typeName.names?.map(p=>p.String?.sval).filter(Boolean)??[],l=a.length===2&&a[0]==="pg_catalog"?a[1]:a[0],u=["text","varchar","character varying","char","bpchar","name","uuid"].includes(l?.toLowerCase());try{let p=this.parsePgArrayLiteral(o,u);return `'${JSON.stringify(p).replace(/'/g,"''")}'`}catch{}}}return this.visit(t.arg,r)}let s=this.visit(t.arg,r),i=this.TypeName(t.typeName,r);return `CAST(${s} AS ${i})`}A_ArrayExpr(t,r){let n=It(t.elements),s=this.tryExtractStaticArray(n);return s!==void 0?`'${JSON.stringify(s).replace(/'/g,"''")}'`:`json_array(${n.map(o=>this.visit(o,r)).join(", ")})`}tryExtractStaticArray(t){let r=[];for(let n of t)if("A_ArrayExpr"in n){let s=It(n.A_ArrayExpr.elements),i=this.tryExtractStaticArray(s);if(i===void 0)return;r.push(i);}else if("A_Const"in n){let s=n.A_Const;if(s.isnull)r.push(null);else if(s.ival)r.push(s.ival.ival);else if(s.fval)r.push(parseFloat(s.fval.fval));else if(s.sval)r.push(s.sval.sval);else if("boolval"in s)r.push(s.boolval.boolval===true);else return}else return;return r}parsePgArrayLiteral(t,r){if(!t.startsWith("{")||!t.endsWith("}"))throw new Error("Not a PG array literal");let n=t.slice(1,-1);if(n.length===0)return [];let s=[],i=0;for(;i<n.length;)if(n[i]==="{"){let o=0,a=i;for(;a<n.length;){if(n[a]==="{")o++;else if(n[a]==="}"&&(o--,o===0))break;a++;}s.push(this.parsePgArrayLiteral(n.slice(i,a+1),r)),i=a+1,n[i]===","&&i++;}else if(n[i]==='"'){let o=i+1,a="";for(;o<n.length&&n[o]!=='"';)n[o]==="\\"&&o++,a+=n[o],o++;s.push(a),i=o+1,n[i]===","&&i++;}else {let o=i;for(;o<n.length&&n[o]!==","&&n[o]!=="}";)o++;if(o===i)throw new Error("Malformed PG array literal");let a=n.slice(i,o);if(a==="NULL")s.push(null);else if(r)s.push(a);else {let l=Number(a);s.push(isNaN(l)?a:l);}i=o,n[i]===","&&i++;}return s}BetweenExpr(t,r){return super.A_Expr(t,r)}AlterTableStmt(t,r){let n=t.cmds??[],s=["AT_EnableRowSecurity","AT_ForceRowSecurity"],i=n.filter(u=>"AlterTableCmd"in u&&!s.includes(u.AlterTableCmd.subtype));if(i.length===0)return "";if(!["OBJECT_TABLE","OBJECT_INDEX","OBJECT_VIEW"].includes(t.objtype))throw new B({AlterTableStmt:t},`AlterTableStmt with objtype ${t.objtype} is not supported`);let o=["AT_AddColumn","AT_DropColumn"],a=["AT_AlterColumnType","AT_SetNotNull","AT_DropNotNull","AT_ColumnDefault","AT_AddConstraint","AT_DropConstraint"],l=[],c=[];for(let u of i){let p=u.AlterTableCmd.subtype;if(o.includes(p)){let f={...t,cmds:[u]};l.push(super.AlterTableStmt(f,r));}else if(a.includes(p))c.push(u.AlterTableCmd);else throw new B({AlterTableStmt:t},`AlterTableCmd with subtype ${p} is not supported in SQLite`)}if(c.length>0){let u=this.getRelationName(t.relation);l.push(this.generateRebuildSql(u,c));}return l.join(`;
|
|
193
|
+
`)}AlterTableCmd(t,r){if(!["AT_AddColumn","AT_DropColumn"].includes(t.subtype))throw new B({AlterTableCmd:t},`AlterTableCmd with subtype ${t.subtype} is not supported`);return t.subtype==="AT_DropColumn"&&t.behavior?super.AlterTableCmd({...t,behavior:void 0},r):super.AlterTableCmd(t,r)}DefineStmt(t,r){if(t.kind==="OBJECT_AGGREGATE")throw new Error("AGGREGATE definitions are not supported in SQLite");return super.DefineStmt(t,r)}InsertStmt(t,r){if("selectStmt"in t){let s=(t.selectStmt?.SelectStmt?.valuesLists??[]).map(i=>i.List?.items?.map(o=>"SetToDefault"in o));if(s.length===1&&s[0]?.every(i=>i===true))return super.InsertStmt({...t,selectStmt:void 0,cols:void 0},r);if(s.some(i=>i.some(o=>o===true)))throw new B({InsertStmt:t},"Insert with partial DEFAULT values is not supported")}return super.InsertStmt(t,r)}SelectStmt(t,r){if(this.helper.hasUnsafeStar())throw new B({SelectStmt:t},"Row-wise comparison using .* is not supported in SQLite. Expand to explicit per-column comparisons instead.");if(t.intoClause)throw new B({SelectStmt:t},"SELECT ... INTO clause is not supported in SQLite");if(t.distinctClause){let s=It(t.distinctClause);if(s.length>0&&Object.keys(s[0]).length>0)throw new B({SelectStmt:t},"DISTINCT ON clause is not supported in SQLite. Use window functions instead.")}if(t.limitOffset&&!t.limitCount)throw new B({SelectStmt:t},"OFFSET without LIMIT is not supported in SQLite");let n=super.SelectStmt(t,r);if(/^SELECT\s+FROM/.test(n))throw new B({SelectStmt:t},"SELECT without a target list is not supported in SQLite");return n}JoinExpr(t,r){return t.alias&&this.Alias(t.alias,r),super.JoinExpr(t,r)}A_Const(t,r){if(t.bsval!==void 0)throw new B({A_Const:t},"Bit string literals are not supported in SQLite");let n=super.A_Const(t,r);return typeof n=="string"&&n.startsWith("E'")?n.substring(2,n.length-1):n}SortBy(t,r){if(t.sortby_dir==="SORTBY_USING"){let n=It(t.useOp),s=n[0]?.String?.sval;if(n.length>1||!["<",">"].includes(s??""))throw new B({SortBy:t},"Only `USING <` or `USING >` are supported.");t.sortby_dir=s==="<"?"SORTBY_DESC":"SORTBY_ASC",t.useOp=void 0;}return super.SortBy(t,r)}RangeSubselect(t,r){if(t.lateral)throw new B({RangeSubselect:t},"LATERAL subqueries are not supported in SQLite");return super.RangeSubselect(t,r)}SubLink(t,r){if(["ANY_SUBLINK","ALL_SUBLINK"].includes(t.subLinkType))throw new B({SubLink:t},"ANY/ALL/SOME subqueries are not supported. Use NOT EXISTS or IN instead");if(t.subLinkType==="ARRAY_SUBLINK")throw new B({SubLink:t},"ARRAY subqueries are not supported in SQLite");return super.SubLink(t,r)}LockingClause(t,r){return ""}UpdateStmt(t,r){if(r.parentNodeTypes.includes("SelectStmt"))throw new B({UpdateStmt:t},"UPDATE ... FROM (SELECT ...) is not supported in SQLite");return super.UpdateStmt(t,r)}Alias(t,r){if(t.colnames&&t.colnames.length>0)throw new B({Alias:t},"Aliasing with column names is not supported in SQLite");return `AS "${t.aliasname}"`}CreateFunctionStmt(t,r){let n=t.options??[],s=t.returnType?.names?.map(c=>c.String?.sval).filter(Boolean).join("."),i=n.find(c=>c.DefElem?.defname==="language")?.DefElem?.arg?.String?.sval;if(s!=="trigger"||i!=="plpgsql")throw new B({CreateFunctionStmt:t},"Only trigger functions with LANGUAGE plpgsql are supported");let o=t.funcname?.map(c=>c.String?.sval).filter(Boolean).pop();if(!o)throw new Error("Function has no name");let a=n.find(c=>c.DefElem?.defname==="as")?.DefElem?.arg?.List?.items?.[0]?.String?.sval;if(!a)throw new Error("Function has no body");let l=this.plpgsqlParser.parse(a);return this.triggerFunctions.set(o,l),""}CreateTrigStmt(t,r){let n=t.trigname,s=this.RangeVar(t.relation,r),i=t.funcname?.map(p=>p.String?.sval).filter(Boolean).pop();if(!i)throw new Error(`Trigger "${n}" has no function reference`);let o=this.triggerFunctions.get(i);if(!o)throw new B({CreateTrigStmt:t},`Trigger "${n}" references unknown function "${i}"`);let a=t.timing===2?"BEFORE":t.timing===64?"INSTEAD OF":"AFTER",l=[];if(t.events&4&&l.push("INSERT"),t.events&8&&l.push("DELETE"),t.events&16)if(t.columns?.length){let p=t.columns.map(f=>f.String?.sval).filter(Boolean);l.push(`UPDATE OF ${p.join(", ")}`);}else l.push("UPDATE");let c=l.join(" OR "),u=this.buildTriggerBody(o,s,r);return [`CREATE TRIGGER ${n}`,`${a} ${c} ON ${s}`,"FOR EACH ROW","BEGIN",...u.map(p=>` ${p};`),"END"].join(`
|
|
194
|
+
`)}buildTriggerBody(t,r,n){let s=[],i=[];for(let o of t.statements)if(o.type!=="return"){if(o.type==="assignment"){i.push(o);continue}i.length>0&&(s.push(this.buildAssignmentUpdate(i,r,n)),i.length=0),o.type==="dml"&&s.push(this.translateDml(o.sql,n));}return i.length>0&&s.push(this.buildAssignmentUpdate(i,r,n)),s}buildAssignmentUpdate(t,r,n){let s=t.map(i=>{let o=this.translateExpression(i.expression,n);return `${i.column} = ${o}`});return `UPDATE ${r} SET ${s.join(", ")} WHERE rowid = NEW.rowid`}translateExpression(t,r){try{let n=`SELECT ${t}`,s=t.trim().toLowerCase();return s==="now()"||s==="current_timestamp"?"datetime('now')":t}catch{return t}}flattenTriggerTableRef(t,r){let n=this.effectiveSchema(t);return n?this.schemaHandling==="prefix"?`${n}__${r}`:`"${n}.${r}"`:this.quoteBareIfNeeded(r)}translateDml(t,r){let n=/^(\s*)(insert\s+into|update|delete\s+from)\s+(?:"([^"]+)"|(\w+))\s*\.\s*(?:"([^"]+)"|(\w+))/i;return t=t.replace(n,(s,i,o,a,l,c,u)=>`${i}${o} ${this.flattenTriggerTableRef(a??l,c??u)}`),t.replace(/\bnow\(\)/gi,"datetime('now')").replace(/\bcurrent_timestamp\b/gi,"datetime('now')").replace(/\bgen_random_uuid\(\)/gi,this.uuidExpression()).replace(/\buuid_generate_v4\(\)/gi,this.uuidExpression())}uuidExpression(){return "lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))"}NullTest(t,r){if(t.arg?.ColumnRef?.fields?.length>1)throw new B({NullTest:t},"row-level NULL tests are not supported in SQLite");return super.NullTest(t,r)}RenameStmt(t,r){if(!t.renameType)throw new Error("RenameStmt requires renameType");let n=["OBJECT_TABLE","OBJECT_VIEW","OBJECT_COLUMN"];if(t.renameType==="OBJECT_COLUMN"&&(t.relationType==="OBJECT_FOREIGN_TABLE"||t.relationType==="OBJECT_VIEW"))throw new B({RenameStmt:t},`RenameStmt with relationType ${t.relationType} is not supported`);if(!n.includes(t.renameType))throw new B({RenameStmt:t},`RenameStmt with renameType ${t.renameType} is not supported in SQLite`);return super.RenameStmt(t,r)}DropStmt(t,r){let n=t.removeType;if(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_INDEX","OBJECT_TRIGGER"].includes(n))return super.DropStmt(t,r);if(["OBJECT_POLICY"].includes(n))return "";throw new B({DropStmt:t},`DROP with removeType ${n} is not supported in SQLite`)}generateRebuildSql(t,r){if(!this.introspection)throw new Error(`ALTER TABLE on "${t}" requires 12-step rebuild but no introspection was provided. Pass introspection in DeparseOptions to enable column type changes, NOT NULL, defaults, and constraint modifications.`);let n=this.buildDesiredSchema(this.introspection,t,r),s=new di,i=new hi,o=s.diff(this.introspection,n);return o.has_changes?i.plan(o,this.introspection,n).steps.filter(l=>!["disable_foreign_keys","begin_transaction","commit_transaction","enable_foreign_keys"].includes(l.type)).map(l=>l.sql).join(`
|
|
195
|
+
`):""}buildDesiredSchema(t,r,n){let s={...t,tables:t.tables.map(i=>({...i})),columns:t.columns.map(i=>({...i})),indexes:t.indexes.map(i=>({...i})),foreign_keys:t.foreign_keys.map(i=>({...i})),primary_keys:t.primary_keys.map(i=>({...i})),views:t.views.map(i=>({...i})),triggers:(t.triggers??[]).map(i=>({...i})),check_constraints:t.check_constraints.map(i=>({...i})),unique_constraints:(t.unique_constraints??[]).map(i=>({...i})),comments:(t.comments??[]).map(i=>({...i})),custom_types:t.custom_types.map(i=>({...i}))};for(let i of n){let o=s.columns.findIndex(a=>a.table===r&&a.name===i.name);switch(i.subtype){case "AT_AlterColumnType":{if(o===-1)break;let a=this.extractTypeName(i);a&&(s.columns[o]={...s.columns[o],type:a.toLowerCase()});break}case "AT_SetNotNull":{if(o===-1)break;s.columns[o]={...s.columns[o],nullable:false};break}case "AT_DropNotNull":{if(o===-1)break;s.columns[o]={...s.columns[o],nullable:true};break}case "AT_ColumnDefault":{if(o===-1)break;if(i.def){let a=this.extractDefaultValue(i);s.columns[o]={...s.columns[o],default_value:a};}else s.columns[o]={...s.columns[o],default_value:null};break}case "AT_AddConstraint":case "AT_DropConstraint":{let a=s.tables.findIndex(l=>l.name===r);a!==-1&&(s.tables[a]={...s.tables[a],sql:s.tables[a].sql+" /* modified */"});break}}}return this.rebuildTableSql(s,r),s}rebuildTableSql(t,r){let n=t.tables.findIndex(p=>p.name===r);if(n===-1)return;let s=t.columns.filter(p=>p.table===r),i=t.foreign_keys.filter(p=>p.table===r),o=t.check_constraints.filter(p=>p.table===r),a=s.map(p=>{let f=`${U(p.name)} ${p.type||"TEXT"}`;return p.is_primary_key&&(f+=" PRIMARY KEY"),p.nullable||(f+=" NOT NULL"),p.default_value!=null&&(f+=` DEFAULT ${p.default_value}`),f}),l=i.map(p=>`FOREIGN KEY (${U(p.column)}) REFERENCES ${U(p.ref_table)}(${U(p.ref_column)}) ON UPDATE ${p.on_update} ON DELETE ${p.on_delete}`),c=o.map(p=>`CHECK (${p.expression})`),u=[...a,...l,...c];t.tables[n]={...t.tables[n],sql:`CREATE TABLE ${U(r)} (${u.join(", ")}) STRICT`};}extractTypeName(t){let r=t.def?.ColumnDef;return r?.typeName?.TypeName?(r.typeName.TypeName.names??[]).map(s=>s.String?.sval).filter(Boolean).pop()??null:null}extractDefaultValue(t){return t.def?"Integer"in t.def?String(t.def.Integer.ival):"Float"in t.def?t.def.Float.fval:"String"in t.def?`'${t.def.String.sval}'`:null:null}};});function Fm(e){return `${e?.schemaname??"public"}.${e?.relname??""}`}function Xx(e){let t=e?.Constraint;if(!t||t.contype!=="CONSTR_DEFAULT")return false;let r=t.raw_expr?.FuncCall?.funcname;if(!Array.isArray(r))return false;let n=r.map(s=>s.String?.sval??s.String?.str).filter(Boolean);return n[n.length-1]?.toLowerCase()==="nextval"}function Jx(e){return (Array.isArray(e.constraints)?e.constraints:[]).some(r=>r.Constraint?.contype==="CONSTR_IDENTITY")}function Mm(e,t){let r=Array.isArray(e.constraints)?e.constraints:[],n=r.filter(s=>!Xx(s));n.length!==r.length?(e.constraints=n,t.add(e)):Jx(e)&&t.add(e);}function Yx(e,t,r){let n=t?.Constraint;if(!n)return false;let s=n.contype;if(s!=="CONSTR_PRIMARY"&&s!=="CONSTR_UNIQUE"&&s!=="CONSTR_FOREIGN")return false;let i=e.tableElts??[];if(s==="CONSTR_PRIMARY"){let o=(n.keys??[]).map(a=>a.String?.sval??a.String?.str).filter(Boolean);if(o.length===1){let a=i.find(l=>"ColumnDef"in l&&l.ColumnDef.colname===o[0]);if(a&&r.has(a.ColumnDef)){let l=Array.isArray(a.ColumnDef.constraints)?a.ColumnDef.constraints:[];return l.push({Constraint:{contype:"CONSTR_PRIMARY"}}),a.ColumnDef.constraints=l,true}}}return i.push(t),e.tableElts=i,true}function Um(e){let t=new WeakSet,r=new Map;for(let n of e.stmts??[]){let s=n.stmt;if(!s||!("CreateStmt"in s))continue;let i=s.CreateStmt;r.set(Fm(i.relation),i);for(let o of i.tableElts??[])"ColumnDef"in o&&Mm(o.ColumnDef,t);}for(let n of e.stmts??[]){let s=n.stmt;if(!s||!("AlterTableStmt"in s))continue;let i=s.AlterTableStmt,o=r.get(Fm(i.relation)),a=i.cmds??[],l=[];for(let c of a){let u=c.AlterTableCmd;u?.subtype==="AT_AddColumn"&&u.def&&"ColumnDef"in u.def&&Mm(u.def.ColumnDef,t),!(o&&u?.subtype==="AT_AddConstraint"&&u.def&&Yx(o,u.def,t))&&l.push(c);}i.cmds=l;}return t}var Bm=w(()=>{});async function An(e,t={}){let r=await ci(e);return {ast:r,...Qx(r,t)}}function Qx(e,t={}){let r=Um(e),n=Pa(e),s=Ia(e,n),i=Na(e),o=La(e),a=Da(e),l=new gi(e,{...t,enums:n,serialColumns:r}),{policies:c,tables:u}=Oa(e);if(t.strict)for(let p of c){if(!s.get(`${p.data.schema??"public"}.${p.data.table}`))throw new Error(`Policy "${p.data.name}" references unknown table "${p.data.table}"`);if(!u.has(p.data.table))throw new Error(`RLS is not enabled on table "${p.data.table}"`)}return {ddl:l.deparseQuery(),enums:n,rls:{tables:u,policies:c},schema:s,vars:i,tableConstraints:o,comments:a}}var yi=w(()=>{Nm();jm();Bm();fa();Fa();ma();});async function qm(e){if(e.trim())try{await ci(e);}catch(t){let r=t instanceof Error?t.message:String(t);throw new wl(`Declarative schema (schemas/*.sql) is not valid SQL: ${r}`,{cause:t})}}async function yl(e,t,r,n){if(t.trim())try{let s=t;if(r==="postgres"){let i=await e.translateDdl(t);s=typeof i=="string"?i:i.ddl??"";}for(let i of Xt(s))if(i.trim())try{await e.exec(i);}catch(o){if(!n)throw o}}catch(s){if(!n)throw s}}async function Hm(e,t){if(!t.trim())return;let r=Ie(e.connection);if(r==="pg")return;let n=r==="sqlite"?"sqlite":"postgres",s=await createConnection({url:":memory:",ddlDialect:n,translation:e.connection.config.translation});try{let i=e.connection.config.baseSchema;i&&await yl(s,i,n,!0);for(let o of await Fe(e))await yl(s,o.sql,n,!0);await yl(s,t,n,!1);}finally{await s.close().catch(()=>{});}}var wl,Wm=w(()=>{yi();Jt();pt();Pt();wl=class extends Error{constructor(t,r){super(t,r),this.name="SchemaParseError";}};});async function r0(){return qt||(qt=await import('@sentry/node')),qt}function n0(){if(zm)return;zm=true;let e=process.exit.bind(process),t=false;process.exit=(r=>{if(t)return;t=true,wi((r??0)!==0).finally(()=>e(r));});}function Xm(e){if(e)return false;let t=process.env.LITE_TELEMETRY;if(t==="0"||t==="false")return false;let r=process.env.DO_NOT_TRACK;return !(r==="1"||r==="true"||process.env.CI||process.env.LOCAL)}function s0(){let e=process.versions;return e.bun?"bun":e.deno?"deno":"node"}function i0(){if(process.env.CODESPACES)return "codespaces";if(process.env.REMOTE_CONTAINERS)return "devcontainer";try{return statSync("/.dockerenv"),"docker"}catch{return}}function o0(e){let t=e/1e6;return t<1?"<1MB":t<10?"1-10MB":t<100?"10-100MB":t<1e3?"100MB-1GB":">1GB"}function a0(e,t){if(e==="sqlite"||e==="sqlite-postgres"||e==="pglite")return !t||t===":memory:"||t.startsWith("file::memory:")?e==="pglite"&&!t?void 0:"memory":t.startsWith("file:")?"file":void 0;if(e==="postgres"){if(!t)return;try{let r=new URL(t).hostname;return r==="localhost"||r==="127.0.0.1"||r==="::1"?"local":"remote"}catch{return "remote"}}}function l0(){try{let e=ze__default.resolve(process.cwd(),ve.config_dir,"config.toml"),t;try{t=readFileSync(e,"utf-8");}catch{return {}}let r;try{r=$t(t);}catch{return {}}let n=r.db?.driver,s=n==="sqlite"||n==="sqlite-postgres"||n==="pglite"||n==="postgres"?n:"sqlite-postgres",i=r.db?.url??ve.default_db_url,o=a0(s,i),a;if(o==="file"&&i.startsWith("file:"))try{let l=i.startsWith("file://")?i.slice(7):i.slice(5),c=ze__default.resolve(process.cwd(),l);a=statSync(c).size;}catch{}return {driver:s,location:o,sizeBytes:a}}catch{return {}}}async function Jm(e){if(hr)return;hr=true;let t=await r0(),{version:r}=await Kn();t.init({dsn:t0,release:`@supabase/lite@${r}`,sendDefaultPii:false,defaultIntegrations:false,integrations:[t.httpIntegration()],tracesSampleRate:1,tracePropagationTargets:["sentry.io"],beforeSend(i){return delete i.server_name,i.user&&delete i.user.ip_address,i},beforeSendTransaction(i){return delete i.server_name,i.user&&delete i.user.ip_address,i}}),t.setTag("command",e.command),t.setTag("runtime",s0()),t.setTag("node",process.version),t.setTag("platform",process.platform),t.setTag("arch",process.arch),t.setTag("ci",!!process.env.CI);let n=i0();n&&t.setTag("container",n);try{let{determineAgent:i}=await import('@vercel/detect-agent'),o=await i();o.isAgent&&t.setTag("agent",o.agent.name);}catch{}let s=l0();s.driver&&t.setTag("db.driver",s.driver),s.location&&t.setTag("db.location",s.location),typeof s.sizeBytes=="number"&&t.setTag("db.size",o0(s.sizeBytes));for(let[i,o]of Object.entries(e.args))t.setTag(`arg.${i}`,!!o);t.startSession(),Km=true,Bt=t.startInactiveSpan({name:`cli:${e.command}`,op:"cli.command",forceTransaction:true}),n0();}async function wi(e,t){if(!hr)return;let r=qt;try{if(e&&(r.setTag("status","failed"),t instanceof Error&&r.setTag("error_class",t.constructor.name)),Bt&&(Bt.setStatus({code:e?2:1,message:e?"internal_error":"ok"}),Bt.end(),Bt=void 0),Km){let n=r.getCurrentScope().getSession();n&&e&&(n.status="crashed"),r.endSession();}}finally{await r.flush(2e3).catch(()=>{});}}function Cn(e,t){if(!hr)return Promise.resolve(t());let r=qt,n=()=>r.startSpan({name:e,op:"cli.step"},t);return Bt?r.withActiveSpan(Bt,n):n()}function bl(e,t){hr&&qt.setTag(e,t);}function Ym(e,t){if(!hr)return;let r=qt;try{r.captureException(e,{tags:{translation_gap:!0,"db.variant":t.variant,error_class:e instanceof Error?e.constructor.name:"unknown"},contexts:{translation_gap:{variant:t.variant,failing_sql:t.failingSql?t.failingSql.slice(0,4e3):void 0}}});}catch{}}var t0,qt,hr,Km,Bt,zm,bi=w(()=>{Tr();Kt();xe();t0="https://9562525a4ea320539ea7e94859533a17@o398706.ingest.us.sentry.io/4511381939290112";hr=false,Km=false,zm=false;});var ed={};de(ed,{checkPendingDeclarativeSchema:()=>Zm,db:()=>m0});function f0(){console.log(ye.default.yellow("Declarative diff includes potentially destructive changes.")),console.log(ye.default.dim("Review the schema manually and author an explicit migration for drops or other data-loss changes."));}async function Zm(e,t){let r=await fe(e);if(!r)return {hint:false,reason:"no-schemas"};try{let s=await e.connection.createMigrator(r).diff();return (typeof s.diff=="string"?s.diff.trim().length>0:s.diff.has_changes)?{hint:!0,reason:"pending"}:{hint:!1,reason:"in-sync"}}catch{return {hint:false,reason:"diff-failed"}}}async function Qm(e){let t=await yt(e),r=await fe(t);if(!r&&!t.connection.config.baseSchema){console.log(ye.default.dim("No schema files found."));return}let s=await t.connection.createMigrator(r).diff();if(typeof s.diff!="string"&&!s.diff.has_changes){console.log(ye.default.dim("Schema in sync."));return}dt(s);}var ye,p0,m0,td=w(()=>{ye=ee(ie());Le();Ga();He();pt();Pm();xe();Je();xt();Hs();He();Pt();Wm();bi();p0="Local Development:";m0=e=>{let t=e.command("db").description("Database operations").helpGroup(p0);t.command("diff").description("Diff current DB against schemas/*.sql; with -f, emit a pg migration file").option("--config <config>","Path to the config file").option("-f, --file <name>","Write the diff as a new migration file with this name").action(async r=>{console.log(),await Z(async()=>{if(await Y(r.config),!r.file){await Qm(r.config);return}let n=await yt(r.config),s=await fe(n);if(!s.trim()){console.log(ye.default.dim("No declarative schemas found \u2014 nothing to diff."));return}await qm(s);let i=Ie(n.connection);if(i==="sqlite"){console.log(ye.default.yellow('`lite db diff -f` is not supported on the bare "sqlite" driver yet.')),console.log(ye.default.dim('Declarative schema diffs require the "sqlite-postgres" driver. Set db.driver = "sqlite-postgres" in supabase/config.toml.'));return}let o;{let u=await Ps(n);try{o=await km(u,s,n.connection.config.baseSchema??"");}catch(p){if(p instanceof DataLossError){f0();return}throw p}if(!o.trim()){console.log(ye.default.green("Schema in sync \u2014 no migration written."));return}}try{await Hm(n,o);}catch(u){Ym(u,{variant:i,failingSql:o});let p=u instanceof Error?u.message:String(u);throw new Error(`Generated migration does not run on the "${i}" backend and was not written: ${p}. This likely indicates a gap in supalite's Postgres\u2192SQLite translation; it has been reported.`)}let a=ze__default.join(process.cwd(),"supabase",Nt(n));ke(a);let l=pa(r.file,ua()),c=ze__default.join(a,l);await pe__default.writeFile(c,o+`
|
|
196
|
+
`,{flag:"wx"}),console.log(ye.default.green(" \u279C"),"Wrote migration",ye.default.cyan(ze__default.relative(process.cwd(),c)));});}),t.command("reset").description(ge("Drop user objects, clear history, replay migrations + seed")).option("--config <config>","Path to the config file").option("--no-seed","Skip running seed.sql after replay").action(async r=>{console.log(),await Z(async()=>{await Y(r.config);let n=await yt(r.config),s=n.connection.dialect==="postgres",i=[];if(s){let{rows:l}=await n.connection.exec(`SELECT nspname AS name FROM pg_namespace
|
|
197
|
+
WHERE nspname NOT LIKE 'pg\\_%' AND nspname <> 'information_schema'`);for(let c of l)i.push(`DROP SCHEMA IF EXISTS "${c.name.replace(/"/g,'""')}" CASCADE`);i.push("CREATE SCHEMA IF NOT EXISTS public AUTHORIZATION pg_database_owner");}else {let c=(await n.connection.introspect()).tables.filter(p=>p.type==="table"),u=(p,f)=>`"${p?`${p}.${f}`:f}"`;for(let p of c)i.push(`DROP TABLE IF EXISTS ${u(p.schema,p.name)}`);i.push("DROP TABLE IF EXISTS migrations"),i.push("DROP TABLE IF EXISTS seed_files"),i.push('DROP TABLE IF EXISTS "supabase_migrations.schema_migrations"'),i.push('DROP TABLE IF EXISTS "supabase_migrations.seed_files"');}for(let l of i)try{await n.connection.exec(l);}catch{}await n.connection.clearSchemaCache();let o=await Ut(n);for(let l of o.applied)console.log(ye.default.green(" \u2713"),"Applied",ye.default.cyan(l.filename));(await Zm(n,o.applied.length)).hint&&(console.log(),console.log(ye.default.yellow("Declarative schemas detected with pending changes.")),console.log(ye.default.dim("Run `lite db diff -f <name>` to generate a migration, then re-run `lite db reset`."))),r.seed!==!1&&await gn(n).catch(l=>console.error(ye.default.yellow("Seed warning: "+String(l)))),console.log(ye.default.green("Database reset."));});}),t.command("query").description("Execute a SQL statement against the local or remote project").argument("<statement>","The statement to execute").option("--remote","Execute the statement on the remote project",false).option("--config <config>","Path to the config file").action(async(r,n)=>{console.log(),await Z(async()=>{n.remote||await Y(n.config);let s=await yt(n.remote?!0:n.config);console.log(`Executing: ${ye.default.cyan(r)}`);let i=await s.connection.exec(r);console.log(i);});}),t.command("schema").description(ge("Print the current database schema")).option("--diff","Diff current DB against schemas/*.sql",false).option("--sql","Print raw CREATE statements from sqlite_master",false).option("--config <config>","Path to the config file").action(async r=>{console.log(),await Z(async()=>{if(await Y(r.config),r.diff){await Qm(r.config);return}let s=await(await yt(r.config)).connection.introspect();if(r.sql){let i=[...s.tables.map(o=>o.sql),...s.views.map(o=>o.sql),...s.triggers.map(o=>o.sql)].filter(o=>o&&o.trim().length>0);console.log(i.join(`;
|
|
198
|
+
|
|
199
|
+
`)+(i.length?";":""));return}zf(s);});});};});var rd={};de(rd,{migration:()=>y0});var ae,g0,y0,nd=w(()=>{ae=ee(ie());He();pt();Hs();Pt();Ce();xe();Je();g0="Local Development:",y0=e=>{let t=e.command("migration").description("Manage database migrations").helpGroup(g0);t.command("diff").description(ge("Diff DB state against schemas/*.sql")).option("--config <config>","Path to the config file").option("--execute","Execute the migration").option("--force","Force the migration",false).option("--sql","Show the SQL for the migration",false).option("--seed","Seed the database with data",false).action(async r=>{await Y(r.config);let s=await(await z({withSupabaseClient:false})).project.local.createApp(r.config),i=await fe(s),o=s.connection.createMigrator(i),a=await o.diff();if(console.log(),a.plan.steps.length>0){dt(a);let l=null;try{r.execute&&(await o.migratePlan(a.plan,{force:r.force??!1}),qa(a),console.log());}catch(c){l=c;}if(r.sql){let c=r.execute?l?ae.default.red:ae.default.green:ae.default.cyan;console.log(c(yn(a,{colorize:true})));}l&&(l instanceof DataLossError&&(console.log(),console.warn(ae.default.yellow("Migration would potentially cause data loss. Rerun with --force to proceed.")),process.exit(1)),console.error(ae.default.red("Migration error: "+String(l))),process.exit(1)),r.execute||console.log(ae.default.yellow("Migration not executed. Use --execute to execute."));}else console.log(ae.default.green("No changes to migrate."));r.seed&&await Ba(s),process.exit(0);}),t.command("new").description("Create a new empty migration file").argument("<name>","The migration name").option("--config <config>","Path to the config file").action(async(r,n)=>{await Y(n.config);let i=await(await z({withSupabaseClient:false})).project.local.createApp(n.config),o=await Af(i,r);console.log(ae.default.green(" \u279C"),"Created",ae.default.cyan(ze__default.relative(process.cwd(),o))),process.exit(0);}),t.command("up").description("Apply pending migrations from the migrations directory").option("--config <config>","Path to the config file").option("--dry-run","Print pending migrations without applying",false).action(async r=>{await Y(r.config);let s=await(await z({withSupabaseClient:false})).project.local.createApp(r.config);if(r.dryRun){await kt(s.connection);let i=new Set(await Kr(s.connection)),a=(await Fe(s)).filter(l=>!i.has(l.version));a.length===0&&(console.log(ae.default.green("No pending migrations.")),process.exit(0)),console.log(ae.default.dim("Pending:"));for(let l of a)console.log(" "+ae.default.cyan(l.filename));process.exit(0);}try{let i=await Ut(s);if(i.applied.length===0)console.log(ae.default.green("Local database is up to date."));else for(let o of i.applied)console.log(ae.default.green(" \u2713"),"Applied",ae.default.cyan(o.filename));process.exit(0);}catch(i){console.error(ae.default.red("Migration failed: "+String(i.message??i))),process.exit(1);}}),t.command("list").description("List applied and pending migrations").option("--config <config>","Path to the config file").action(async r=>{await Y(r.config);let s=await(await z({withSupabaseClient:false})).project.local.createApp(r.config);await kt(s.connection);let i=new Set(await Kr(s.connection)),o=await Fe(s);console.log(ae.default.dim(`Migrations in ${Nt(s)}:`)),o.length===0&&console.log(ae.default.dim(" (none)"));for(let c of o){let u=i.has(c.version)?ae.default.green("[applied]"):ae.default.yellow("[pending]");console.log(` ${u} ${ae.default.cyan(c.filename)}`);}let a=new Set(o.map(c=>c.version)),l=[...i].filter(c=>!a.has(c));if(l.length>0){console.log(),console.log(ae.default.dim("Recorded versions without matching file:"));for(let c of l)console.log(` ${ae.default.red("[orphan]")} ${c}`);}process.exit(0);});};});function b0(e){let t=(e??process.env.SUPABASE_ENDPOINT??w0).replace(/\/+$/,""),r=new URL(t),n=r.host;return {apiUrl:`${r.protocol}//${n.startsWith("api.")?n:`api.${n}`}`,projectDomain:n==="supabase.com"?"supabase.co":n}}function sd(e){if(Array.isArray(e)){let t=e.find(n=>n.name==="anon")?.api_key??"",r=e.find(n=>n.name==="service_role")?.api_key??"";return {anon:t,service_role:r}}return e}var w0,Si,id=w(()=>{w0="https://supabase.com";Si=class{constructor(t,r){this.token=t;if(!t)throw new Error("Supabase access token required");let n=b0(r?.endpoint);this.apiUrl=n.apiUrl,this.projectDomain=n.projectDomain;}apiUrl;projectDomain;async request(t,r,n){let s=await fetch(`${this.apiUrl}${r}`,{method:t,headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json",Accept:"application/json"},body:n===void 0?void 0:JSON.stringify(n)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Supabase API ${t} ${r} failed: ${s.status} ${s.statusText}${o?` \u2014 ${o}`:""}`)}return (s.headers.get("content-type")??"").includes("application/json")?await s.json():await s.text()}listOrganizations(){return this.request("GET","/v1/organizations")}async validateToken(){try{return await this.listOrganizations(),!0}catch{return false}}listRegions(t){return this.request("GET",`/v1/projects/available-regions?organization_slug=${encodeURIComponent(t)}`)}createProject(t){return this.request("POST","/v1/projects",t)}getProject(t){return this.request("GET",`/v1/projects/${t}`)}getApiKeys(t){return this.request("GET",`/v1/projects/${t}/api-keys`)}updateAuthConfig(t,r){return this.request("PATCH",`/v1/projects/${t}/config/auth`,r)}createSigningKey(t,r){return this.request("POST",`/v1/projects/${t}/config/auth/signing-keys`,r)}runSql(t,r){return this.request("POST",`/v1/projects/${t}/database/query`,{query:r})}async waitForActive(t,r={}){let n=r.timeoutMs??6e5,s=r.intervalMs??5e3,i=Date.now();for(;;){let o=await this.getProject(t);if(r.onTick?.(o.status),o.status==="ACTIVE_HEALTHY")return o;if(Date.now()-i>n)throw new Error(`Timed out waiting for project ${t} to become ACTIVE_HEALTHY (last status: ${o.status})`);await new Promise(a=>setTimeout(a,s));}}};});function E0(e){if(e==null||typeof e!="string")return true;try{return JSON.parse(e),!0}catch{return false}}function x0(e){return e==null?true:typeof e!="string"?false:S0.test(e)}function _0(e){if(e==null)return true;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="string")return false;let t=Date.parse(e);return !Number.isNaN(t)}function od(e){if(!e)return;let t=e.match(/varchar\s*\(\s*(\d+)\s*\)/i);return t?Number(t[1]):void 0}function ad(e){return e?/jsonb?/i.test(e):false}function ld(e){return e?/\buuid\b/i.test(e):false}function cd(e){return e?/timestamp(tz)?|timestamp with|timestamp without/i.test(e):false}async function ud(e){let t=await e.connection.introspect(),r=[],n=e.connection.dialect;for(let s of t.tables){let i=s.name,o=s.schema,a=n==="sqlite"&&o&&o!=="main"?`"${o}.${i}"`:o?`"${o}"."${i}"`:`"${i}"`,l=t.columns.filter(g=>g.table===i&&(g.schema??o)===o),c=0,u=[];try{let g=await e.connection.exec(`SELECT COUNT(*) as c FROM ${a}`);c=Number(g?.rows?.[0]?.c??0);}catch{r.push({table:i,schema:o,rowCount:0,issues:u});continue}if(c===0){r.push({table:i,schema:o,rowCount:c,issues:u});continue}let p=l.filter(g=>ad(g.type)||ld(g.type)||cd(g.type)||od(g.type)!==void 0);if(p.length===0){r.push({table:i,schema:o,rowCount:c,issues:u});continue}let f=p.map(g=>`"${g.name}"`).join(", ");try{let d=(await e.connection.exec(`SELECT ${f} FROM ${a}`))?.rows??[];for(let m of d)for(let y of p){let h=m[y.name];if(ad(y.type)&&!E0(h)){u.push({table:i,column:y.name,kind:"invalid_json",message:`row contains non-parseable JSON in ${i}.${y.name}`});continue}if(ld(y.type)&&h!=null&&!x0(h)){u.push({table:i,column:y.name,kind:"invalid_uuid",message:`row contains invalid UUID in ${i}.${y.name}`});continue}if(cd(y.type)&&!_0(h)){u.push({table:i,column:y.name,kind:"invalid_timestamp",message:`row contains unparseable timestamp in ${i}.${y.name}`});continue}let S=od(y.type);S!==void 0&&typeof h=="string"&&h.length>S&&u.push({table:i,column:y.name,kind:"varchar_overflow",message:`value exceeds varchar(${S}) in ${i}.${y.name}`});}}catch{}r.push({table:i,schema:o,rowCount:c,issues:u});}return r}var S0,pd=w(()=>{S0=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;});function bt(e){let t=[],r="",n=0,s=false,i=false,o=false,a=false,l=null;for(;n<e.length;){let u=e[n],p=e[n+1];if(o){r+=u,u===`
|
|
200
|
+
`&&(o=false),n++;continue}if(a){if(r+=u,u==="*"&&p==="/"){r+=p,n+=2,a=false;continue}n++;continue}if(l){if(r+=u,u==="$"&&e.startsWith(l,n)){r+=e.slice(n+1,n+l.length),n+=l.length,l=null;continue}n++;continue}if(s){if(r+=u,u==="'"&&p==="'"){r+=p,n+=2;continue}u==="'"&&(s=false),n++;continue}if(i){if(r+=u,u==='"'&&p==='"'){r+=p,n+=2;continue}u==='"'&&(i=false),n++;continue}if(u==="-"&&p==="-"){o=true,r+=u,n++;continue}if(u==="/"&&p==="*"){a=true,r+=u,n++;continue}if(u==="'"){s=true,r+=u,n++;continue}if(u==='"'){i=true,r+=u,n++;continue}if(u==="$"){let f=e.slice(n).match(/^\$[A-Za-z0-9_]*\$/);if(f){l=f[0],r+=f[0],n+=f[0].length;continue}}if(u===";"){let f=r.trim();f&&t.push(f),r="",n++;continue}r+=u,n++;}let c=r.trim();return c&&t.push(c),t}var Ei=w(()=>{});async function xi(e,t){let n=e.connection.dialect==="sqlite"?`"auth.${t}"`:`auth."${t}"`;try{let s=await e.connection.exec(`SELECT COUNT(*) as c FROM ${n}`);return Number(s?.rows?.[0]?.c??0)}catch{return 0}}async function fd(e){let t=[],r=[],n=false;try{await e.connection.exec("SELECT 1"),n=!0;}catch(l){t.push(`Database not reachable: ${String(l)}`);}let s=await fe(e),i=bt(s);i.length===0&&t.push("No schema statements found in supabase/schemas/*.sql");let o=[];if(n)try{o=await ud(e);}catch(l){r.push(`Data validation skipped: ${String(l)}`);}for(let l of o)for(let c of l.issues)r.push(`${c.kind}: ${c.message}`);let a={users:0,sessions:0,refresh_tokens:0,identities:0,jwt_secret_set:!!e.config.auth?.jwt_secret};return n&&(a.users=await xi(e,"users"),a.sessions=await xi(e,"sessions"),a.refresh_tokens=await xi(e,"refresh_tokens"),a.identities=await xi(e,"identities")),a.jwt_secret_set||r.push("auth.jwt_secret is not configured \u2014 tokens will not survive upgrade"),e.config.storage?.enabled&&r.push("Storage is enabled but migration is not yet supported"),e.config.realtime?.enabled&&r.push("Realtime config migration is not yet supported"),{ok:t.length===0,errors:t,warnings:r,dbReachable:n,schemaStatementCount:i.length,schemaBytes:s.length,tables:o,auth:a}}var md=w(()=>{He();pd();Ei();});var El,dd=w(()=>{El=`-- supabase/auth core schema (Postgres)
|
|
191
201
|
-- Scope: Core Authentication + User Management
|
|
192
202
|
-- Source: GoTrue migrations + runtime analysis
|
|
193
203
|
|
|
@@ -364,14 +374,7 @@ CREATE TABLE IF NOT EXISTS auth.audit_log_entries (
|
|
|
364
374
|
created_at timestamptz DEFAULT now(),
|
|
365
375
|
ip_address varchar(64) DEFAULT ''
|
|
366
376
|
);
|
|
367
|
-
`;});function Hm(e=true){return e?_c(ml):ml}var Wm=y(()=>{$r();qm();});function Wx(e,t,r,n){if(e==null)return "NULL";if(n.includes(t))return e===true||e===1||e==="1"||e==="true"?"true":"false";if(r.includes(t)){let s=typeof e=="string"?e:JSON.stringify(e);return `${Gm(s)}::jsonb`}return typeof e=="number"?Number.isFinite(e)?String(e):"NULL":typeof e=="boolean"?e?"true":"false":Gm(String(e))}function Gm(e){return `'${e.replace(/'/g,"''")}'`}async function ui(e,t={}){let r=t.target??"supabase",n={users:[],sessions:[],identities:[],refresh_tokens:[]},s=e.connection.dialect,i=Hx[r];for(let o of Ux){let a=s==="sqlite"?`"auth.${o}"`:`auth."${o}"`,l=[];try{l=(await e.connection.exec(`SELECT * FROM ${a}`))?.rows??[];}catch{continue}if(l.length===0)continue;let c=new Set(i[o]),u=Bx[o],p=qx[o];for(let f of l){let g={...f};if(r==="supabase"&&o==="users"){let h=g.confirmed_at;h!=null&&g.email_confirmed_at==null&&(g.email_confirmed_at=h);}let d=Object.keys(g).filter(h=>!c.has(h)),m=d.map(h=>Wx(g[h],h,u,p)),w=`INSERT INTO auth.${o} (${d.map(h=>`"${h}"`).join(", ")}) VALUES (${m.join(", ")}) ON CONFLICT DO NOTHING`;n[o].push(w);}}return n}var Mx,Ux,Bx,qx,Hx,dl=y(()=>{Mx=["users","sessions","identities","refresh_tokens"],Ux=Mx,Bx={users:["raw_app_meta_data","raw_user_meta_data"],sessions:[],identities:["identity_data"],refresh_tokens:[]},qx={users:["is_sso_user","is_anonymous"],sessions:[],identities:[],refresh_tokens:["revoked"]},Hx={supabase:{users:["confirmed_at"],sessions:[],identities:["email"],refresh_tokens:["id"]},local:{users:["confirmed_at"],sessions:[],identities:["email"],refresh_tokens:[]}};});async function zm(e){let{parse:t}=await import('pgsql-parser');return t(e)}var Vm=y(()=>{});var pi,Km=y(()=>{ir();Pt();pi=class{constructor(t){this.ast=t;this.result=[...this.walk(this.ast,[],{trackPaths:["returningList"]})];}result=[];*walk(t=this.ast,r=[],n={}){if(!t||typeof t!="object")return;let{trackPaths:s=[]}=n;if(Array.isArray(t)){for(let o=0;o<t.length;o++)yield*this.walk(t[o],r,n);return}let i=Object.keys(t);if(i.length===1&&i[0][0]>="A"&&i[0][0]<="Z"){let o=i[0];yield {node:t,path:r},yield*this.walk(t[o],[...r,o],n);}else for(let[o,a]of Object.entries(t))if(a&&typeof a=="object"){let l=s.includes(o)?[...r,o]:r;yield*this.walk(a,l,n);}}containsUnsupportedNode(){for(let{node:t}of this.result){let r=sr(t),n=Is.get(r);if(n&&n.react==="error")return true}}hasFuncCall(){for(let{node:t}of this.result)if("FuncCall"in t)return true;return false}getFuncCalls(){return Array.from(this.result).map(({node:t})=>t).filter(t=>"FuncCall"in t).map(t=>t.FuncCall)}getFuncCallNames(){return this.getFuncCalls().flatMap(t=>t.funcname?.map(r=>r.String?.sval||r.String?.str))}hasSqlValueFunction(){for(let{node:t}of this.result)if("SQLValueFunction"in t)return true;return false}getSqlValueFunctions(){return Array.from(this.result).map(({node:t})=>t).filter(t=>"SQLValueFunction"in t).map(t=>t.SQLValueFunction)}getSqlValueFunctionNames(){return this.getSqlValueFunctions().map(t=>t.op)}hasUnsafeStar(){let t=this.result.filter(({node:r})=>"A_Star"in r);if(t.length===0)return false;for(let{path:r}of t)if(!r.includes("SelectStmt")&&!r.includes("returningList"))return true;return false}getRelationDefinitions(){return this.result.filter(({node:r})=>"CreateStmt"in r).map(({node:r})=>r.CreateStmt).map(r=>({relation:{relname:r.relation?.relname??"",inh:r.relation?.inh,relpersistence:r.relation?.relpersistence},columns:r.tableElts?.map(n=>{let s=n.ColumnDef?.typeName?.names?.map(o=>"String"in o?o.String.sval:""),i=s?.some(o=>o.toLowerCase().includes("pg_catalog"));return {name:n.ColumnDef?.colname??"",is_local:n.ColumnDef?.is_local,pg_catalog:i,type:s?.filter(o=>!o.toLowerCase().includes("pg_catalog"))[0]??"",types:s,constraints:n.ColumnDef?.constraints}})}))}getRelationColumnTypes(){return {has_non_pg_catalog_types:this.getRelationDefinitions().some(t=>t.columns?.some(r=>!r.pg_catalog)),types:Array.from(new Set(this.getRelationDefinitions().flatMap(t=>t.columns?.map(r=>r.type))))}}};});var Gx,zx,Vx,Kx,cr,fi,Jm=y(()=>{ir();Gx=["DECLARE","IF","ELSIF","ELSE","LOOP","WHILE","FOR","FOREACH","EXCEPTION","RAISE","PERFORM","EXECUTE","SELECT"],zx=/^NEW\.(\w+)\s*(?::=|=)\s*(.+)$/is,Vx=/^RETURN\s+(NEW|OLD)$/i,Kx=/^(INSERT|UPDATE|DELETE)\b/i,cr=class extends Nt{constructor(r,n,s){super(s??`Unsupported PL/pgSQL: ${r}`);this.hint=r;this.body=n;}},fi=class{parse(t){let r=this.extractBlock(t),n=this.splitStatements(r),s=[],i=null;for(let o of n){let a=o.trim();if(!a)continue;this.rejectUnsupported(a);let l=a.match(Vx);if(l){i=l[1].toUpperCase(),s.push({type:"return",value:i});continue}let c=a.match(zx);if(c){s.push({type:"assignment",column:c[1],expression:c[2].trim()});continue}if(Kx.test(a)){s.push({type:"dml",sql:a});continue}throw new cr(`"${a.substring(0,80)}" is not translatable to SQLite`,r)}if(!i)throw new Nt("Trigger function body must end with RETURN NEW or RETURN OLD");return {statements:s,returnValue:i}}extractBlock(t){let r=t.trim(),n=r.toUpperCase();if(/^\s*DECLARE\b/i.test(r))throw new cr('"DECLARE" is not translatable to SQLite',t);let s=n.indexOf("BEGIN"),i=n.lastIndexOf("END");if(s===-1||i===-1||i<=s)throw new cr("Expected BEGIN ... END block in trigger function body",t);return r.slice(s+5,i).trim()}splitStatements(t){let r=[],n="",s=0,i=false,o="";for(let l=0;l<t.length;l++){let c=t[l];if(i){n+=c,c===o&&(l+1<t.length&&t[l+1]===o?n+=t[++l]:i=false);continue}if(c==="'"||c==='"'){i=true,o=c,n+=c;continue}if(c==="("){s++,n+=c;continue}if(c===")"){s--,n+=c;continue}if(c===";"&&s===0){r.push(n.trim()),n="";continue}n+=c;}let a=n.trim();return a&&r.push(a),r}rejectUnsupported(t){let r=t.match(/^(\w+)/)?.[1]?.toUpperCase();if(r&&Gx.includes(r))throw new cr(`"${r}" is not translatable to SQLite`,t)}};});var mi,di=y(()=>{mi=class extends Error{constructor(r){super(`Migration would cause data loss:
|
|
368
|
-
${r.map(n=>` - ${n.table}: ${n.reason}`).join(`
|
|
369
|
-
`)}`);this.warnings=r;this.name="DataLossError";}};});var hi,Xm=y(()=>{$r();hi=class{makeIndexKey(t){return `${t.table}:${t.name}:${t.unique}:${t.columns.join(",")}`}makeForeignKeyKey(t){return `${t.table}:${t.column}:${t.ref_table}:${t.ref_column}`}diff(t,r){let n=[],s=[],i=[],o=[],a=new Set(t.tables.map(m=>m.name)),l=new Set(r.tables.map(m=>m.name));for(let m of r.tables)a.has(m.name)||n.push({type:"added",name:m.name,sql:m.sql});for(let m of t.tables)l.has(m.name)||n.push({type:"removed",name:m.name});for(let m of t.tables){let w=r.tables.find(T=>T.name===m.name);if(!w)continue;let h=Ki(m.sql),S=Ki(w.sql);h!==S&&n.push({type:"modified",name:m.name,sql:w.sql});}let c=t.tables.filter(m=>l.has(m.name));for(let m of c){let w=t.columns.filter($=>$.table===m.name),h=r.columns.filter($=>$.table===m.name),S=new Map(w.map($=>[$.name,$])),T=new Map(h.map($=>[$.name,$]));for(let[$,P]of T)S.has($)||s.push({type:"added",table:m.name,name:$,column:P});for(let[$]of S)T.has($)||s.push({type:"removed",table:m.name,name:$});for(let[$,P]of S){let N=T.get($);if(!N)continue;let v={};Vi(P.type)!==Vi(N.type)&&(v.type={from:P.type,to:N.type}),P.nullable!==N.nullable&&(v.nullable={from:P.nullable,to:N.nullable}),Ji(P.default_value)!==Ji(N.default_value)&&(v.default_value={from:P.default_value,to:N.default_value}),Object.keys(v).length>0&&s.push({type:"modified",table:m.name,name:$,changes:v});}}let u=new Map(t.indexes.map(m=>[this.makeIndexKey(m),m])),p=new Map(r.indexes.map(m=>[this.makeIndexKey(m),m]));for(let[m,w]of p)u.has(m)||i.push({type:"added",...w});for(let[m,w]of u)p.has(m)||i.push({type:"removed",...w});let f=new Map(t.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m])),g=new Map(r.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m]));for(let[m,w]of g)f.has(m)||o.push({type:"added",...w});for(let[m,w]of f)g.has(m)||o.push({type:"removed",...w});let d=n.length>0||s.length>0||i.length>0||o.length>0;return {tables:n,columns:s,indexes:i,foreign_keys:o,has_changes:d}}};});var Xx,gi,Ym=y(()=>{di();Ar();Xx=["CURRENT_TIMESTAMP","CURRENT_TIME","CURRENT_DATE"],gi=class{plan(t,r,n,s){if(!t.has_changes)return {steps:[],warnings:[],unsafe:false};let i=[],o=[];i.push({sql:"PRAGMA foreign_keys=OFF;",description:"Disable foreign key checks",type:"disable_foreign_keys"}),i.push({sql:"BEGIN;",description:"Begin transaction",type:"begin_transaction"});for(let p of t.tables.filter(f=>f.type==="added")){i.push({sql:`${p.sql};`,description:`CREATE TABLE ${U(p.name)}`,type:"create_table"});let f=n.indexes.filter(g=>g.table===p.name);for(let g of f){let d=g.unique?"UNIQUE ":"",m=g.columns.map(w=>U(w)).join(", ");i.push({sql:`CREATE ${d}INDEX ${U(g.name)} ON ${U(p.name)} (${m});`,description:`Create index ${U(g.name)} on ${U(p.name)}`,type:"add_index"});}}let a=new Set(r.tables.map(p=>p.name)),l=new Set(n.tables.map(p=>p.name)),c=new Set(t.tables.filter(p=>p.type==="modified").map(p=>p.name)),u=[...a].filter(p=>l.has(p));for(let p of u){if(!(c.has(p)||t.columns.some(m=>m.table===p)||t.indexes.some(m=>m.table===p)||t.foreign_keys.some(m=>m.table===p)))continue;let{canAlter:g,addedCols:d}=this.canSimpleAlter(p,t,n);if(g){for(let h of d)i.push({sql:`ALTER TABLE ${U(p)} ADD COLUMN ${this.columnDef(h)};`,description:`Add column ${U(h.name)} to ${U(p)}`,type:"add_column"});let m=t.indexes.filter(h=>h.table===p&&h.type==="added"),w=t.indexes.filter(h=>h.table===p&&h.type==="removed");for(let h of w)i.push({sql:`DROP INDEX IF EXISTS ${U(h.name)};`,description:`Drop index ${U(h.name)}`,type:"drop_index"});for(let h of m){let S=h.unique?"UNIQUE ":"",T=h.columns.map($=>U($)).join(", ");i.push({sql:`CREATE ${S}INDEX ${U(h.name)} ON ${U(p)} (${T});`,description:`Create index ${U(h.name)} on ${U(p)}`,type:"add_index"});}}else {let m=this.rebuildTable(p,r,n,t);i.push(...m.steps),o.push(...m.warnings);}}for(let p of t.tables.filter(f=>f.type==="removed"))i.push({sql:`DROP TABLE ${U(p.name)};`,description:`Drop table ${U(p.name)}`,type:"drop_table"}),o.push({table:p.name,reason:"table will be dropped"});return i.push({sql:"COMMIT;",description:"Commit transaction",type:"commit_transaction"}),i.push({sql:"PRAGMA foreign_keys=ON;",description:"Re-enable foreign key checks",type:"enable_foreign_keys"}),{steps:i,warnings:o,unsafe:o.length>0}}rebuildTable(t,r,n,s){let i=[],o=[],a=n.tables.find(h=>h.name===t);if(!a)return {steps:i,warnings:o};let l=`_${t}_migrate_new`,c=a.sql.replace(new RegExp(`(CREATE\\s+TABLE\\s+)(?:"${t}"|${t})`,"i"),`$1${U(l)}`);i.push({sql:`${c};`,description:`Create temporary table ${U(l)}`,type:"create_table"});let u=r.columns.filter(h=>h.table===t).map(h=>h.name),p=n.columns.filter(h=>h.table===t).map(h=>h.name),f=u.filter(h=>p.includes(h));if(f.length>0){let h=f.map(S=>U(S)).join(", ");i.push({sql:`INSERT INTO ${U(l)} (${h})
|
|
370
|
-
SELECT ${h}
|
|
371
|
-
FROM ${U(t)};`,description:`Copy data from ${U(t)} to ${U(l)}`,type:"copy_data"});}i.push({sql:`DROP TABLE ${U(t)};`,description:`Drop old table ${U(t)}`,type:"drop_table"}),i.push({sql:`ALTER TABLE ${U(l)} RENAME TO ${U(t)};`,description:`Rename ${U(l)} to ${U(t)}`,type:"rename_table"});let g=n.indexes.filter(h=>h.table===t);for(let h of g){let S=h.unique?"UNIQUE ":"",T=h.columns.map($=>U($)).join(", ");i.push({sql:`CREATE ${S}INDEX ${U(h.name)} ON ${U(t)} (${T});`,description:`Recreate index ${U(h.name)} on ${U(t)}`,type:"add_index"});}let d=n.triggers?.filter(h=>h.table===t)??[];for(let h of d)i.push({sql:`${h.sql};`,description:`Recreate trigger ${U(h.name)} on ${U(t)}`,type:"create_trigger"});let m=s.columns.filter(h=>h.table===t&&h.type==="removed");for(let h of m)o.push({table:t,reason:`column "${h.name}" will be dropped`});let w=s.columns.filter(h=>h.table===t&&h.type==="modified");for(let h of w)h.changes?.type&&o.push({table:t,reason:`column "${h.name}" type changes from ${h.changes.type.from} to ${h.changes.type.to}`}),h.changes?.nullable&&!h.changes.nullable.to&&o.push({table:t,reason:`column "${h.name}" becomes NOT NULL`});return {steps:i,warnings:o}}canSimpleAlter(t,r,n){let s=r.columns.filter(p=>p.table===t),i=s.filter(p=>p.type==="added"),o=s.filter(p=>p.type==="removed"),a=s.filter(p=>p.type==="modified"),l=r.foreign_keys.some(p=>p.table===t);if(o.length>0||a.length>0||l)return {canAlter:false,addedCols:i};let c=n.tables.find(p=>p.name===t);return c&&/\bCHECK\s*\(/i.test(c.sql)?{canAlter:false,addedCols:i}:{canAlter:i.every(p=>{let f=p.column;return this.hasNonConstantDefault(f.default_value)?false:f.nullable||f.default_value!=null})&&i.length>0,addedCols:i}}hasNonConstantDefault(t){if(t==null)return false;let r=t.trim().toUpperCase();return Xx.includes(r)}columnDef(t){let r=t.column,n=`${U(r.name)} ${r.type||"TEXT"}`;return r.nullable||(n+=" NOT NULL"),r.default_value!=null&&(n+=` DEFAULT ${r.default_value}`),n}};});function t0(e){let t=e?.GrantStmt??e;return t?.is_grant!==true?false:t.targtype==="ACL_TARGET_ALL_IN_SCHEMA"?t.objtype==="OBJECT_TABLE"||t.objtype==="OBJECT_SEQUENCE":t.targtype==="ACL_TARGET_OBJECT"&&e0.has(t.objtype)}var e0,yi,Qm=y(()=>{ir();Pt();Pt();Km();at();Jm();di();Xm();Ym();Ar();_a();va();e0=new Set(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_SEQUENCE","OBJECT_SCHEMA"]);yi=class extends Deparser{enums;schemaHandling;warnings=[];helper;config;triggerFunctions=new Map;plpgsqlParser=new fi;introspection;functionResolution;constructor(t,{enums:r,schemaHandling:n,introspection:s,...i}={}){super(t,i),this.schemaHandling=n??"default",this.enums=r??new Map,this.helper=new pi(t),this.config=i,this.introspection=s,this.functionResolution=i?.functionResolution??"translate";}visit(t,r){let n=sr(t);if(n==="GrantStmt"&&t0(t))return "";let s=Is.get(n);if(s){if(s.react==="error")throw new B({[n]:t},`Unsupported node type: ${n}`);return s.react==="warn"&&this.warnings.push({type:n,node:t}),""}return super.visit(t,r)}deparse(t,r){if(t==null)return null;if(!r){let n=new SqlFormatter;r=new DeparserContext({formatter:n});}return typeof t=="number"||t instanceof Number?t.toString():this.visit(t,r)}RawStmt(t,r){if(!t.stmt||t.stmt.CommentStmt)return "";let n=this.deparse(t.stmt,r);return !n||n.length===0?"":t.stmt_len?n+";":n}RangeVar(t,r){this.ensureRelation(t);let n=this.effectiveSchema(t.schemaname),s=t.relname,i=this.quoteBareIfNeeded(s);n&&(this.schemaHandling==="prefix"?i=`${n}__${s}`:i=`"${n}.${s}"`);let o=t.alias?" "+this.Alias(t.alias,r):"";return i+o}getRelationName(t){this.ensureRelation(t);let r=this.effectiveSchema(t.schemaname),n=t.relname;return r?this.schemaHandling==="prefix"?`${r}__${n}`:`${r}.${n}`:n}quoteBareIfNeeded(t){return /^[A-Za-z_][A-Za-z0-9_]*$/.test(t)?t:`"${t.replace(/"/g,'""')}"`}effectiveSchema(t){if(t){if(this.config.forceDefaultSchema||this.schemaHandling!=="default")return t;if(t!=="public")return t}}ensureRelation(t){let r=this.config.forceDefaultSchema;r&&(!t||typeof t!="object"||r.length===0||t.schemaname||(t.schemaname=r));}CreateStmt(t,r){if(t.inhRelations&&t.inhRelations.length>0)throw new B({CreateStmt:t},"Inheritance is not supported in SQLite");if(t.ofTypename!==void 0)throw new B({CreateStmt:t},"Typed tables (CREATE TABLE ... OF type_name) are not supported. Define columns directly in the CREATE TABLE statement instead.");if(t.options&&t.options.length>0&&(t.options=void 0),!t.tableElts||t.tableElts.length===0)throw new B({CreateStmt:t},"Empty tables are not supported in SQLite. Define at least one column.");return t.accessMethod&&(t.accessMethod=void 0),super.CreateStmt(t,r)+" STRICT"}TableLikeClause(t,r){throw new B({TableLikeClause:t},"CREATE TABLE ... (LIKE ...) is not supported in SQLite. Define the table columns explicitly instead.")}DefElem(t,r){if(["oids","fillfactor",/^autovacuum_/i,"toast_tuple_target","parallel_workers","user_catalog_table"].some(i=>Hc(t.defname??"",i)))return "";let s=super.DefElem(t,r);throw new B({DefElem:t},`DefElem "${t.defname}" (${s}) not supported`)}TypeName(t,r){if(!t.names)return "";let n=t.names.map(i=>i.String?i.String.sval||i.String.str:"").filter(Boolean);if(n.length===0)return "";let s=n.length===2&&n[0]==="pg_catalog"?n[1]:n.join(".");return t.arrayBounds&&t.arrayBounds.length>0||this.enums.has(s.toLowerCase())?"TEXT":_f(s)}ColumnDef(t,r){let n=[],s=t.colname;s&&n.push(this.quoteIfNeeded(s));let i=false,o=false,a=null,l=null,c=null,u=false;if(t.typeName){let p=t.typeName.names?.map(d=>d.String?.sval||d.String?.str).filter(Boolean);c=p&&(p.length===2&&p[0]==="pg_catalog"?p[1]:p[0]),i=!!(c&&Ps(c)),u=!!(t.typeName.arrayBounds&&t.typeName.arrayBounds.length>0);let f=Array.isArray(t.typeName.typmods)?t.typeName.typmods:[],g=d=>f[d]?.A_Const?.ival?.ival??f[d]?.A_Const?.val?.ival?.ival;if(c&&Ns(c)&&f.length>0){let d=g(0);typeof d=="number"&&d>0&&(a={maxLen:d});}if(c&&Os(c)&&f.length>=2){let d=g(0),m=g(1);typeof d=="number"&&typeof m=="number"&&d>0&&m>=0&&(l={precision:d,scale:m});}if(t.constraints){let d=Array.isArray(t.constraints)?t.constraints:[];o=d.some(m=>m.Constraint?.contype==="CONSTR_PRIMARY"),d.some(m=>m.Constraint?.contype==="CONSTR_IDENTITY")&&(i=true);}n.push(this.TypeName(t.typeName,r));}if(t.constraints){let p=Array.isArray(t.constraints)?t.constraints:[],f=p.map(d=>this.visit(d,r));n.push(...f.filter(Boolean));let g=p.some(d=>d.Constraint?.contype==="CONSTR_CHECK");i&&o&&!g&&n.push("AUTOINCREMENT");}if(s&&c){let p={isArray:u};a&&(p.lengthConstraint=a.maxLen),l&&(p.numericPrecision=l);let f=this.enums.get(c.toLowerCase());f&&(p.enumValues=f);let m=Lt({schema:"public",table:"",column:s,pgTypeName:c,nullable:true,defaultValue:null,defaultFn:null,isPrimaryKey:o,isUnique:false,isSerial:i},p).checkConstraint();m&&n.push(`CHECK (${m})`);}return n.join(" ")}Constraint(t,r){let n=t.contype;if(n==="CONSTR_IDENTITY"||n==="CONSTR_ATTR_DEFERRABLE"||n==="CONSTR_ATTR_NOT_DEFERRABLE"||n==="CONSTR_ATTR_DEFERRED"||n==="CONSTR_ATTR_IMMEDIATE")return "";if(n==="CONSTR_NULL")return "NULL";if(n==="CONSTR_NOTNULL")return "NOT NULL";if(n==="CONSTR_DEFAULT"&&t.raw_expr){let s=this.visit(t.raw_expr,r);return s.includes("(")&&!s.startsWith("(")?`DEFAULT (${s})`:`DEFAULT ${s}`}if(n==="CONSTR_CHECK"&&t.raw_expr){let s=[];t.conname&&s.push("CONSTRAINT",ks(t.conname)),s.push("CHECK");let i=this.visit(t.raw_expr,r);return s.push(`(${i})`),s.join(" ")}if(n==="CONSTR_PRIMARY")return t.keys&&t.keys.length>0?`PRIMARY KEY (${kt(t.keys).map(i=>this.visit(i,r)).join(", ")})`:"PRIMARY KEY";if(n==="CONSTR_UNIQUE")return t.keys&&t.keys.length>0?`UNIQUE (${kt(t.keys).map(i=>this.visit(i,r)).join(", ")})`:"UNIQUE";if(n==="CONSTR_FOREIGN")return super.Constraint(t,r).replace(/FOREIGN\s+KEY\s+REFERENCES/gi,"REFERENCES");if(n==="CONSTR_GENERATED"&&t.raw_expr)return `GENERATED ALWAYS AS (${this.visit(t.raw_expr,r)}) STORED`;if(n==="CONSTR_EXCLUSION")throw new B({Constraint:t},"EXCLUSION constraints are not supported in SQLite");return ""}FuncCall(t,r){let s=(t.funcname||[]).map(c=>c.String?.sval||c.String?.str).filter(Boolean);if(s.length===0)throw new Error("Function call has no name");let i=s[s.length-1].toLowerCase();if(i==="extract"&&t.args&&t.args.length>=2){let c=t.args[0];if((c?.A_Const?.sval?.sval||c?.String?.sval)==="epoch")return `strftime('%s', ${this.visit(t.args[1],r)})`}let a=(t.args??[]).map(c=>this.visit(c,r));if(t.agg_star)return `${i}(*)`;if(t.agg_distinct)return `${i}(DISTINCT ${a.join(", ")})`;let l=$a(i,this.functionResolution);if(l){if(l.sqliteExpr!==null){let c=l.sqliteExpr;return c.includes("(")?c:`${c}(${a.join(", ")})`}if(l.jsFn!==null){let c=Fs[i];if(c?.sqlite){let u=c.sqlite();return u.includes("(")?u:`${u}(${a.join(", ")})`}}}throw new B({FuncCall:t},`Function call "${i}" not supported`)}SQLValueFunction(t,r){switch(t.op){case "SVFOP_CURRENT_TIMESTAMP":return "datetime('now')";case "SVFOP_CURRENT_DATE":return "date('now')";case "SVFOP_CURRENT_TIME":return "time('now')";default:throw new B({SQLValueFunction:t},`SQLValueFunction "${t.op}" not supported`)}}ResTarget(t,r){if(t.indirection&&t.indirection.length>0)throw new B({ResTarget:t},"Indirections are not supported in SQLite");let n=[];return r.update&&t.name?(n.push(this.quoteIfNeeded(t.name)),n.push("="),t.val&&n.push(this.deparse(t.val,r))):r.insertColumns&&t.name?n.push(this.quoteIfNeeded(t.name)):(t.val&&n.push(this.deparse(t.val,r)),t.name&&n.push(this.Alias({aliasname:t.name},r))),n.join(" ")}A_Expr(t,r){if(["AEXPR_OP_ALL","AEXPR_OP_ANY"].includes(t.kind))throw new B({A_Expr:t},"ALL/ANY/SOME comparison operators are not supported. Use NOT EXISTS or IN instead");if(t.name&&t.name.length>0){if(t.name.length>1)throw new B({A_Expr:t},"Schema-qualified OPERATOR() syntax is not supported in SQLite");let n=t.name[0]?.String?.sval||t.name[0]?.String?.str;if(n){if(!t.lexpr||!t.rexpr)throw new B({A_Expr:t},"A_Expr missing left or right expression");if(!xf.includes(n.toUpperCase()))throw new B({A_Expr:t},`Operator "${n}" is not supported in SQLite`);if(n==="~~"||n==="~~*"){let s=this.visit(t.lexpr,r),i=this.visit(t.rexpr,r);return `${s} LIKE ${i}`}if(n==="!~~"||n==="!~~*"){let s=this.visit(t.lexpr,r),i=this.visit(t.rexpr,r);return `${s} NOT LIKE ${i}`}if(n==="~"||n==="~*"){let s=this.visit(t.lexpr,r),i=this.visit(t.rexpr,r);return `${s} GLOB ${i}`}}}return super.A_Expr(t,r)}IndexStmt(t,r){let n=["CREATE"];t.unique&&n.push("UNIQUE"),n.push("INDEX"),t.if_not_exists&&n.push("IF NOT EXISTS"),t.idxname&&n.push(ks(t.idxname)),n.push("ON"),t.relation&&n.push(this.RangeVar(t.relation,r));let s=(t.indexParams??[]).map(i=>"IndexElem"in i?this.IndexElem(i.IndexElem,r):this.visit(i,r)).filter(Boolean);return n.push(`(${s.join(", ")})`),n.join(" ")}IndexElem(t,r){let n=[];return t.name?n.push(ks(t.name)):t.expr&&n.push(`(${this.visit(t.expr,r)})`),t.ordering==="SORTBY_ASC"&&n.push("ASC"),t.ordering==="SORTBY_DESC"&&n.push("DESC"),t.nulls_ordering==="SORTBY_NULLS_FIRST"&&n.push("NULLS FIRST"),t.nulls_ordering==="SORTBY_NULLS_LAST"&&n.push("NULLS LAST"),n.join(" ")}TypeCast(t,r){if(!t.arg||!t.typeName)return super.TypeCast(t,r);if([...this.helper.walk(t)].filter(({node:o})=>"A_Star"in o).length>0)throw new B({TypeCast:t},"A.* in type casts are not supported in SQLite");if(t.typeName.arrayBounds&&t.typeName.arrayBounds.length>0){if("A_Const"in t.arg&&t.arg.A_Const.sval){let o=t.arg.A_Const.sval.sval;if(o.startsWith("{")&&o.endsWith("}")){let a=t.typeName.names?.map(p=>p.String?.sval).filter(Boolean)??[],l=a.length===2&&a[0]==="pg_catalog"?a[1]:a[0],u=["text","varchar","character varying","char","bpchar","name","uuid"].includes(l?.toLowerCase());try{let p=this.parsePgArrayLiteral(o,u);return `'${JSON.stringify(p).replace(/'/g,"''")}'`}catch{}}}return this.visit(t.arg,r)}let s=this.visit(t.arg,r),i=this.TypeName(t.typeName,r);return `CAST(${s} AS ${i})`}A_ArrayExpr(t,r){let n=kt(t.elements),s=this.tryExtractStaticArray(n);return s!==void 0?`'${JSON.stringify(s).replace(/'/g,"''")}'`:`json_array(${n.map(o=>this.visit(o,r)).join(", ")})`}tryExtractStaticArray(t){let r=[];for(let n of t)if("A_ArrayExpr"in n){let s=kt(n.A_ArrayExpr.elements),i=this.tryExtractStaticArray(s);if(i===void 0)return;r.push(i);}else if("A_Const"in n){let s=n.A_Const;if(s.isnull)r.push(null);else if(s.ival)r.push(s.ival.ival);else if(s.fval)r.push(parseFloat(s.fval.fval));else if(s.sval)r.push(s.sval.sval);else if("boolval"in s)r.push(s.boolval.boolval===true);else return}else return;return r}parsePgArrayLiteral(t,r){if(!t.startsWith("{")||!t.endsWith("}"))throw new Error("Not a PG array literal");let n=t.slice(1,-1);if(n.length===0)return [];let s=[],i=0;for(;i<n.length;)if(n[i]==="{"){let o=0,a=i;for(;a<n.length;){if(n[a]==="{")o++;else if(n[a]==="}"&&(o--,o===0))break;a++;}s.push(this.parsePgArrayLiteral(n.slice(i,a+1),r)),i=a+1,n[i]===","&&i++;}else if(n[i]==='"'){let o=i+1,a="";for(;o<n.length&&n[o]!=='"';)n[o]==="\\"&&o++,a+=n[o],o++;s.push(a),i=o+1,n[i]===","&&i++;}else {let o=i;for(;o<n.length&&n[o]!==","&&n[o]!=="}";)o++;if(o===i)throw new Error("Malformed PG array literal");let a=n.slice(i,o);if(a==="NULL")s.push(null);else if(r)s.push(a);else {let l=Number(a);s.push(isNaN(l)?a:l);}i=o,n[i]===","&&i++;}return s}BetweenExpr(t,r){return super.A_Expr(t,r)}AlterTableStmt(t,r){let n=t.cmds??[],s=["AT_EnableRowSecurity","AT_ForceRowSecurity"],i=n.filter(u=>"AlterTableCmd"in u&&!s.includes(u.AlterTableCmd.subtype));if(i.length===0)return "";if(!["OBJECT_TABLE","OBJECT_INDEX","OBJECT_VIEW"].includes(t.objtype))throw new B({AlterTableStmt:t},`AlterTableStmt with objtype ${t.objtype} is not supported`);let o=["AT_AddColumn","AT_DropColumn"],a=["AT_AlterColumnType","AT_SetNotNull","AT_DropNotNull","AT_ColumnDefault","AT_AddConstraint","AT_DropConstraint"],l=[],c=[];for(let u of i){let p=u.AlterTableCmd.subtype;if(o.includes(p)){let f={...t,cmds:[u]};l.push(super.AlterTableStmt(f,r));}else if(a.includes(p))c.push(u.AlterTableCmd);else throw new B({AlterTableStmt:t},`AlterTableCmd with subtype ${p} is not supported in SQLite`)}if(c.length>0){let u=this.getRelationName(t.relation);l.push(this.generateRebuildSql(u,c));}return l.join(`;
|
|
372
|
-
`)}AlterTableCmd(t,r){if(!["AT_AddColumn","AT_DropColumn"].includes(t.subtype))throw new B({AlterTableCmd:t},`AlterTableCmd with subtype ${t.subtype} is not supported`);return t.subtype==="AT_DropColumn"&&t.behavior?super.AlterTableCmd({...t,behavior:void 0},r):super.AlterTableCmd(t,r)}DefineStmt(t,r){if(t.kind==="OBJECT_AGGREGATE")throw new Error("AGGREGATE definitions are not supported in SQLite");return super.DefineStmt(t,r)}InsertStmt(t,r){if("selectStmt"in t){let s=(t.selectStmt?.SelectStmt?.valuesLists??[]).map(i=>i.List?.items?.map(o=>"SetToDefault"in o));if(s.length===1&&s[0]?.every(i=>i===true))return super.InsertStmt({...t,selectStmt:void 0,cols:void 0},r);if(s.some(i=>i.some(o=>o===true)))throw new B({InsertStmt:t},"Insert with partial DEFAULT values is not supported")}return super.InsertStmt(t,r)}SelectStmt(t,r){if(this.helper.hasUnsafeStar())throw new B({SelectStmt:t},"Row-wise comparison using .* is not supported in SQLite. Expand to explicit per-column comparisons instead.");if(t.intoClause)throw new B({SelectStmt:t},"SELECT ... INTO clause is not supported in SQLite");if(t.distinctClause){let s=kt(t.distinctClause);if(s.length>0&&Object.keys(s[0]).length>0)throw new B({SelectStmt:t},"DISTINCT ON clause is not supported in SQLite. Use window functions instead.")}if(t.limitOffset&&!t.limitCount)throw new B({SelectStmt:t},"OFFSET without LIMIT is not supported in SQLite");let n=super.SelectStmt(t,r);if(/^SELECT\s+FROM/.test(n))throw new B({SelectStmt:t},"SELECT without a target list is not supported in SQLite");return n}JoinExpr(t,r){return t.alias&&this.Alias(t.alias,r),super.JoinExpr(t,r)}A_Const(t,r){if(t.bsval!==void 0)throw new B({A_Const:t},"Bit string literals are not supported in SQLite");let n=super.A_Const(t,r);return typeof n=="string"&&n.startsWith("E'")?n.substring(2,n.length-1):n}SortBy(t,r){if(t.sortby_dir==="SORTBY_USING"){let n=kt(t.useOp),s=n[0]?.String?.sval;if(n.length>1||!["<",">"].includes(s??""))throw new B({SortBy:t},"Only `USING <` or `USING >` are supported.");t.sortby_dir=s==="<"?"SORTBY_DESC":"SORTBY_ASC",t.useOp=void 0;}return super.SortBy(t,r)}RangeSubselect(t,r){if(t.lateral)throw new B({RangeSubselect:t},"LATERAL subqueries are not supported in SQLite");return super.RangeSubselect(t,r)}SubLink(t,r){if(["ANY_SUBLINK","ALL_SUBLINK"].includes(t.subLinkType))throw new B({SubLink:t},"ANY/ALL/SOME subqueries are not supported. Use NOT EXISTS or IN instead");if(t.subLinkType==="ARRAY_SUBLINK")throw new B({SubLink:t},"ARRAY subqueries are not supported in SQLite");return super.SubLink(t,r)}LockingClause(t,r){return ""}UpdateStmt(t,r){if(r.parentNodeTypes.includes("SelectStmt"))throw new B({UpdateStmt:t},"UPDATE ... FROM (SELECT ...) is not supported in SQLite");return super.UpdateStmt(t,r)}Alias(t,r){if(t.colnames&&t.colnames.length>0)throw new B({Alias:t},"Aliasing with column names is not supported in SQLite");return `AS "${t.aliasname}"`}CreateFunctionStmt(t,r){let n=t.options??[],s=t.returnType?.names?.map(c=>c.String?.sval).filter(Boolean).join("."),i=n.find(c=>c.DefElem?.defname==="language")?.DefElem?.arg?.String?.sval;if(s!=="trigger"||i!=="plpgsql")throw new B({CreateFunctionStmt:t},"Only trigger functions with LANGUAGE plpgsql are supported");let o=t.funcname?.map(c=>c.String?.sval).filter(Boolean).pop();if(!o)throw new Error("Function has no name");let a=n.find(c=>c.DefElem?.defname==="as")?.DefElem?.arg?.List?.items?.[0]?.String?.sval;if(!a)throw new Error("Function has no body");let l=this.plpgsqlParser.parse(a);return this.triggerFunctions.set(o,l),""}CreateTrigStmt(t,r){let n=t.trigname,s=this.RangeVar(t.relation,r),i=t.funcname?.map(p=>p.String?.sval).filter(Boolean).pop();if(!i)throw new Error(`Trigger "${n}" has no function reference`);let o=this.triggerFunctions.get(i);if(!o)throw new B({CreateTrigStmt:t},`Trigger "${n}" references unknown function "${i}"`);let a=t.timing===2?"BEFORE":t.timing===64?"INSTEAD OF":"AFTER",l=[];if(t.events&4&&l.push("INSERT"),t.events&8&&l.push("DELETE"),t.events&16)if(t.columns?.length){let p=t.columns.map(f=>f.String?.sval).filter(Boolean);l.push(`UPDATE OF ${p.join(", ")}`);}else l.push("UPDATE");let c=l.join(" OR "),u=this.buildTriggerBody(o,s,r);return [`CREATE TRIGGER ${n}`,`${a} ${c} ON ${s}`,"FOR EACH ROW","BEGIN",...u.map(p=>` ${p};`),"END"].join(`
|
|
373
|
-
`)}buildTriggerBody(t,r,n){let s=[],i=[];for(let o of t.statements)if(o.type!=="return"){if(o.type==="assignment"){i.push(o);continue}i.length>0&&(s.push(this.buildAssignmentUpdate(i,r,n)),i.length=0),o.type==="dml"&&s.push(this.translateDml(o.sql,n));}return i.length>0&&s.push(this.buildAssignmentUpdate(i,r,n)),s}buildAssignmentUpdate(t,r,n){let s=t.map(i=>{let o=this.translateExpression(i.expression,n);return `${i.column} = ${o}`});return `UPDATE ${r} SET ${s.join(", ")} WHERE rowid = NEW.rowid`}translateExpression(t,r){try{let n=`SELECT ${t}`,s=t.trim().toLowerCase();return s==="now()"||s==="current_timestamp"?"datetime('now')":t}catch{return t}}translateDml(t,r){return t.replace(/\bnow\(\)/gi,"datetime('now')").replace(/\bcurrent_timestamp\b/gi,"datetime('now')").replace(/\bgen_random_uuid\(\)/gi,this.uuidExpression()).replace(/\buuid_generate_v4\(\)/gi,this.uuidExpression())}uuidExpression(){return "lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))"}NullTest(t,r){if(t.arg?.ColumnRef?.fields?.length>1)throw new B({NullTest:t},"row-level NULL tests are not supported in SQLite");return super.NullTest(t,r)}RenameStmt(t,r){if(!t.renameType)throw new Error("RenameStmt requires renameType");let n=["OBJECT_TABLE","OBJECT_VIEW","OBJECT_COLUMN"];if(t.renameType==="OBJECT_COLUMN"&&(t.relationType==="OBJECT_FOREIGN_TABLE"||t.relationType==="OBJECT_VIEW"))throw new B({RenameStmt:t},`RenameStmt with relationType ${t.relationType} is not supported`);if(!n.includes(t.renameType))throw new B({RenameStmt:t},`RenameStmt with renameType ${t.renameType} is not supported in SQLite`);return super.RenameStmt(t,r)}DropStmt(t,r){let n=t.removeType;if(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_INDEX","OBJECT_TRIGGER"].includes(n))return super.DropStmt(t,r);if(["OBJECT_POLICY"].includes(n))return "";throw new B({DropStmt:t},`DROP with removeType ${n} is not supported in SQLite`)}generateRebuildSql(t,r){if(!this.introspection)throw new Error(`ALTER TABLE on "${t}" requires 12-step rebuild but no introspection was provided. Pass introspection in DeparseOptions to enable column type changes, NOT NULL, defaults, and constraint modifications.`);let n=this.buildDesiredSchema(this.introspection,t,r),s=new hi,i=new gi,o=s.diff(this.introspection,n);return o.has_changes?i.plan(o,this.introspection,n).steps.filter(l=>!["disable_foreign_keys","begin_transaction","commit_transaction","enable_foreign_keys"].includes(l.type)).map(l=>l.sql).join(`
|
|
374
|
-
`):""}buildDesiredSchema(t,r,n){let s={...t,tables:t.tables.map(i=>({...i})),columns:t.columns.map(i=>({...i})),indexes:t.indexes.map(i=>({...i})),foreign_keys:t.foreign_keys.map(i=>({...i})),primary_keys:t.primary_keys.map(i=>({...i})),views:t.views.map(i=>({...i})),triggers:(t.triggers??[]).map(i=>({...i})),check_constraints:t.check_constraints.map(i=>({...i})),unique_constraints:(t.unique_constraints??[]).map(i=>({...i})),comments:(t.comments??[]).map(i=>({...i})),custom_types:t.custom_types.map(i=>({...i}))};for(let i of n){let o=s.columns.findIndex(a=>a.table===r&&a.name===i.name);switch(i.subtype){case "AT_AlterColumnType":{if(o===-1)break;let a=this.extractTypeName(i);a&&(s.columns[o]={...s.columns[o],type:a.toLowerCase()});break}case "AT_SetNotNull":{if(o===-1)break;s.columns[o]={...s.columns[o],nullable:false};break}case "AT_DropNotNull":{if(o===-1)break;s.columns[o]={...s.columns[o],nullable:true};break}case "AT_ColumnDefault":{if(o===-1)break;if(i.def){let a=this.extractDefaultValue(i);s.columns[o]={...s.columns[o],default_value:a};}else s.columns[o]={...s.columns[o],default_value:null};break}case "AT_AddConstraint":case "AT_DropConstraint":{let a=s.tables.findIndex(l=>l.name===r);a!==-1&&(s.tables[a]={...s.tables[a],sql:s.tables[a].sql+" /* modified */"});break}}}return this.rebuildTableSql(s,r),s}rebuildTableSql(t,r){let n=t.tables.findIndex(p=>p.name===r);if(n===-1)return;let s=t.columns.filter(p=>p.table===r),i=t.foreign_keys.filter(p=>p.table===r),o=t.check_constraints.filter(p=>p.table===r),a=s.map(p=>{let f=`${U(p.name)} ${p.type||"TEXT"}`;return p.is_primary_key&&(f+=" PRIMARY KEY"),p.nullable||(f+=" NOT NULL"),p.default_value!=null&&(f+=` DEFAULT ${p.default_value}`),f}),l=i.map(p=>`FOREIGN KEY (${U(p.column)}) REFERENCES ${U(p.ref_table)}(${U(p.ref_column)}) ON UPDATE ${p.on_update} ON DELETE ${p.on_delete}`),c=o.map(p=>`CHECK (${p.expression})`),u=[...a,...l,...c];t.tables[n]={...t.tables[n],sql:`CREATE TABLE ${U(r)} (${u.join(", ")}) STRICT`};}extractTypeName(t){let r=t.def?.ColumnDef;return r?.typeName?.TypeName?(r.typeName.TypeName.names??[]).map(s=>s.String?.sval).filter(Boolean).pop()??null:null}extractDefaultValue(t){return t.def?"Integer"in t.def?String(t.def.Integer.ival):"Float"in t.def?t.def.Float.fval:"String"in t.def?`'${t.def.String.sval}'`:null:null}};});async function _n(e,t={}){let r=await zm(e);return {ast:r,...r0(r,t)}}function r0(e,t={}){let r=Aa(e),n=ka(e,r),s=Ca(e),i=Pa(e),o=Na(e),a=new yi(e,{...t,enums:r}),{policies:l,tables:c}=Ra(e);if(t.strict)for(let u of l){if(!n.get(`${u.data.schema??"public"}.${u.data.table}`))throw new Error(`Policy "${u.data.name}" references unknown table "${u.data.table}"`);if(!c.has(u.data.table))throw new Error(`RLS is not enabled on table "${u.data.table}"`)}return {ddl:a.deparseQuery(),enums:r,rls:{tables:c,policies:l},schema:n,vars:s,tableConstraints:i,comments:o}}var hl=y(()=>{Vm();Qm();la();Ia();ca();});function wi(e){return !e||e==="main"||e==="public"?"public":e}function $n(e,t){return `${wi(e)}.${t}`}function s0(e,t){let r=new Map(e.map(a=>[$n(a.schema,a.name),a])),n=new Map,s=new Map;for(let a of r.keys())n.set(a,new Set),s.set(a,new Set);for(let a of t){let l=$n(a.schema,a.table),c=$n(a.ref_schema??a.schema,a.ref_table);!n.has(l)||!n.has(c)||(n.get(l).add(c),s.get(c).add(l));}let i=[...n.entries()].filter(([,a])=>a.size===0).map(([a])=>a),o=[];for(let a=0;a<i.length;a++){let l=i[a];o.push(l);for(let c of s.get(l)??[]){let u=n.get(c);u&&(u.delete(l),u.size===0&&i.push(c));}}if(o.length<e.length){console.warn("Warning: cycle detected in user table foreign keys; using best-effort data export order.");let a=new Set(o);for(let l of e){let c=$n(l.schema,l.name);a.has(c)||o.push(c);}}return o.map(a=>r.get(a)).filter(Boolean)}function ed(e,t){if(e==null)return "NULL";let r=(t??"").toLowerCase();if(Array.isArray(e)&&r.endsWith("[]")){let n=t?.slice(0,-2);return `ARRAY[${e.map(s=>ed(s,n)).join(", ")}]::${t}`}if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return Number.isFinite(e)?String(e):"NULL";if(r.includes("bool")&&(e===0||e===1||e==="0"||e==="1"))return e===1||e==="1"?"true":"false";if(r.includes("json")){let n=typeof e=="string"?e:JSON.stringify(e),s=r.includes("jsonb")?"::jsonb":"::json";return `${ur(n)}${s}`}return e instanceof Date?ur(e.toISOString()):typeof e=="object"?`${ur(JSON.stringify(e))}::jsonb`:ur(String(e))}function ur(e){return `'${e.replace(/'/g,"''")}'`}function gl(e){return `"${e.replace(/"/g,'""')}"`}function i0(e){let t=e.default_value??e.default;if(typeof t=="string"&&t.trim().toLowerCase().startsWith("nextval("))return true;let r=typeof e.type=="string"?e.type.toLowerCase():"",n=typeof e.pg_type=="string"?e.pg_type.toLowerCase():"";return Zm.has(r)||Zm.has(n)}function o0(e,t,r){let n=`${gl(e)}.${gl(t)}`;return `SELECT setval(pg_get_serial_sequence(${ur(n)}, ${ur(r)}), COALESCE((SELECT MAX(${gl(r)}) FROM ${n}), 1));`}async function a0(e){let t=e.connection.config?.translation?.deparse?.schema;if(t instanceof Map&&t.size>0)return t;let r=await fe(e);return r.trim()?(await _n(r)).schema:new Map}async function bi(e){let t=await e.connection.introspect(),r=e.connection.dialect,n=await a0(e),s=s0(t.tables.filter(o=>!n0.has(wi(o.schema))),t.foreign_keys),i=[];for(let o of s){let a=wi(o.schema),l=r==="sqlite"?a==="public"?`"${o.name}"`:`"${a}.${o.name}"`:`"${a}"."${o.name}"`,u=t.columns.filter(S=>S.table===o.name&&wi(S.schema)===a).filter(S=>!S.generated&&!S.is_generated),p=[];try{p=(await e.connection.exec(`SELECT * FROM ${l}`))?.rows??[];}catch{continue}if(p.length===0)continue;let f=n.get($n(a,o.name)),g=typeof e.connection.deserializeRow=="function"?e.connection.deserializeRow.bind(e.connection):S=>S;p=p.map(S=>{let T=f?f.deserializeRow(S):S;return g(T)});let d=u.map(S=>S.name),m=new Map(u.map(S=>[S.name,S.pg_type??S.type])),w=[];for(let S of p){let T=d.map($=>ed(S[$],m.get($)));w.push(`INSERT INTO "${a}"."${o.name}" (${d.map($=>`"${$}"`).join(", ")}) VALUES (${T.join(", ")}) ON CONFLICT DO NOTHING`);}let h=u.filter(i0).map(S=>o0(a,o.name,S.name));i.push({schema:a,table:o.name,inserts:w,sequenceResets:h});}return i}var n0,Zm,yl=y(()=>{hl();Be();n0=new Set(["auth","storage","realtime","supabase_functions","graphql","graphql_public","extensions","pgsodium","pgsodium_masks","vault","information_schema","pg_catalog","pg_toast"]),Zm=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]);});async function td(e){let{PGlite:t}=await Ue("@supabase/lite/pglite","pglite","@electric-sql/pglite"),r=new t,n=[],s=0,i=0,o=0,a=0;try{for(let d of ["anon","authenticated","service_role","supabase_auth_admin"])await r.exec(`CREATE ROLE ${d}`);let l=gt(Ms);for(let d=0;d<l.length;d++)try{await r.exec(l[d]);}catch(m){return n.push({phase:"schema",label:`auth helpers ${d+1}/${l.length}`,statement:l[d],error:String(m)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}if(e.config.auth?.enabled!==!1){let d=gt(Hm());s=d.length;for(let m=0;m<d.length;m++)try{await r.exec(d[m]);}catch(w){return n.push({phase:"schema",label:`auth base schema ${m+1}/${d.length}`,statement:d[m],error:String(w)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}}let c=await fe(e),u=gt(c);i=u.length;for(let d=0;d<u.length;d++)try{await r.exec(u[d]);}catch(m){return n.push({phase:"schema",label:`schema ${d+1}/${u.length}`,statement:u[d],error:String(m)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}let p=await ui(e,{target:"local"}),f=["users","sessions","identities","refresh_tokens"];for(let d of f){let m=p[d];for(let w=0;w<m.length;w++){o++;try{await r.exec(m[w]);}catch(h){n.push({phase:"auth",label:`auth.${d} row ${w+1}/${m.length}`,statement:m[w],error:String(h)});}}}let g=await bi(e);for(let d of g){for(let m=0;m<d.inserts.length;m++){a++;try{await r.exec(d.inserts[m]);}catch(w){n.push({phase:"data",label:`${d.schema}.${d.table} row ${m+1}/${d.inserts.length}`,statement:d.inserts[m],error:String(w)});}}for(let m=0;m<d.sequenceResets.length;m++)try{await r.exec(d.sequenceResets[m]);}catch(w){n.push({phase:"data",label:`${d.schema}.${d.table} sequence reset ${m+1}/${d.sequenceResets.length}`,statement:d.sequenceResets[m],error:String(w)});}}}finally{await r.close().catch(()=>{});}return {ok:n.length===0,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}var rd=y(()=>{Qt();Be();Wm();hn();li();dl();yl();});function nd(e){if(console.log(k.default.bold("Readiness Report")),console.log(` db reachable: ${e.dbReachable?k.default.green("yes"):k.default.red("no")} schema statements: ${k.default.cyan(e.schemaStatementCount)} schema bytes: ${k.default.cyan(e.schemaBytes)}`),console.log(` auth \u2014 users: ${k.default.cyan(e.auth.users)} sessions: ${k.default.cyan(e.auth.sessions)} identities: ${k.default.cyan(e.auth.identities)} refresh_tokens: ${k.default.cyan(e.auth.refresh_tokens)} jwt_secret: ${e.auth.jwt_secret_set?k.default.green("set"):k.default.yellow("unset")}`),e.tables.length>0){console.log(k.default.dim(" tables:"));for(let t of e.tables){let r=t.issues.length>0?k.default.yellow(` (${t.issues.length} issues)`):"",n=t.schema?`${t.schema}.`:"";console.log(` ${n}${t.table}: ${k.default.cyan(t.rowCount)} rows${r}`);}}if(e.errors.length>0){console.log(k.default.red("Errors:"));for(let t of e.errors)console.log(` ${k.default.red("\u2717")} ${t}`);}if(e.warnings.length>0){console.log(k.default.yellow("Warnings:"));for(let t of e.warnings)console.log(` ${k.default.yellow("!")} ${t}`);}console.log(),console.log(e.ok?k.default.green("Ready to upgrade."):k.default.red("Not ready."));}function sd(e){if(console.log(),console.log(k.default.bold("Rehearsal (in-memory pglite)")),console.log(` auth schema: ${k.default.cyan(e.baseSchemaStatements)} stmts user schema: ${k.default.cyan(e.schemaStatements)} stmts auth: ${k.default.cyan(e.authInserts)} inserts data: ${k.default.cyan(e.dataInserts)} inserts`),e.failures.length>0){console.log(k.default.red(` ${e.failures.length} failure(s):`));for(let t of e.failures)console.log(k.default.red(` \u2717 [${t.phase}] ${t.label}`)),console.log(k.default.dim(` ${t.statement}`)),console.log(k.default.dim(` ${t.error}`));}console.log(e.ok?k.default.green(" rehearsal passed"):k.default.red(" rehearsal failed"));}function id(e){console.log(),console.log(k.default.bold("SQLite Shim Audit")),console.log(` fields: ${k.default.cyan(e.summary.total)} passed: ${k.default.green(String(e.summary.passed))} warned: ${k.default.yellow(String(e.summary.warned))} failed: ${k.default.red(String(e.summary.failed))}`),e.results.length===0&&console.log(k.default.dim(" no shim-backed fields found"));for(let t of e.results.filter(r=>r.status!=="pass")){let r=t.status==="fail"?k.default.red:k.default.yellow;if(console.log(` ${r(t.status)} ${t.field} (${t.pg_type}) rows: ${k.default.cyan(t.rows_checked)} affected: ${k.default.cyan(t.affected_rows??0)}`),t.message&&console.log(` ${t.message}`),t.samples?.length)for(let n of t.samples)console.log(k.default.dim(` sample ${JSON.stringify(n.id)} raw=${JSON.stringify(n.raw_value)}`));t.action&&console.log(k.default.dim(` action: ${t.action}`));}console.log(e.summary.upgrade_safe?k.default.green(" shim audit passed"):k.default.red(" shim audit failed"));}function wl(e){if(console.log(),console.log(k.default.bold(k.default.green("Upgrade complete."))),console.log(),console.log(` ${k.default.bold("Project URL:")} ${k.default.cyan(e.projectUrl)}`),console.log(` ${k.default.bold("API URL:")} ${k.default.cyan(e.apiUrl)}`),e.studioUrl&&console.log(` ${k.default.bold("Studio URL:")} ${k.default.cyan(e.studioUrl)}`),console.log(` ${k.default.bold("Ref:")} ${k.default.cyan(e.projectRef)}`),console.log(),console.log(` ${k.default.bold("anon key:")} ${e.anonKey}`),console.log(` ${k.default.bold("service_role key:")} ${e.serviceRoleKey}`),console.log(` ${k.default.bold("db password:")} ${e.dbPassword}`),console.log(),console.log(` migrated auth \u2014 users: ${k.default.cyan(e.auth.users)} sessions: ${k.default.cyan(e.auth.sessions)} identities: ${k.default.cyan(e.auth.identities)} refresh_tokens: ${k.default.cyan(e.auth.refresh_tokens)}`),console.log(` jwt secret: ${e.jwtMigrated?k.default.green("migrated"):k.default.yellow("not migrated \u2014 users must re-authenticate")}`),e.warnings.length>0){console.log(),console.log(k.default.yellow("Warnings:"));for(let t of e.warnings)console.log(` ${k.default.yellow("!")} ${t}`);}console.log(),console.log(k.default.bold("Update your supabase-js client:")),console.log(` url: ${k.default.cyan(e.apiUrl)}`),console.log(` anonKey: ${k.default.cyan(e.anonKey)}`),console.log();}var k,od=y(()=>{k=ee(ie());});function ld(e){let t=[],r=e??"",n=r.toLowerCase(),s=Buffer$1.byteLength(r,"utf8");if(!r)return t.push("auth.jwt_secret is empty"),{strong:false,reasons:t};l0.has(r)&&t.push(`matches Supalite development default "${r}"`),s<32&&t.push(`is ${s} bytes; use at least 32 bytes for production secrets`),[/[a-z]/.test(r),/[A-Z]/.test(r),/[0-9]/.test(r),/[^A-Za-z0-9]/.test(r)].filter(Boolean).length<3&&t.push("uses too little character variety"),/^(.)\1{7,}$/.test(r)?t.push("is one repeated character"):u0(r)&&t.push("contains an obvious repeated pattern");let o=c0.find(a=>n.includes(a));return o&&t.push(`contains placeholder term "${o}"`),{strong:t.length===0,reasons:t}}function cd(e){return {kty:"oct",alg:"HS256",k:Buffer$1.from(e,"utf8").toString("base64url")}}function u0(e){if(e.length<8)return false;for(let t=2;t<=Math.floor(e.length/2);t++){if(e.length%t!==0)continue;if(e.slice(0,t).repeat(e.length/t)===e)return true}return false}var l0,c0,ud=y(()=>{l0=new Set(["unsafe-secret-change-me","dev-secret-change-me"]),c0=["change-me","changeme","secret","password","passwd","test","dev"];});async function pd(e){let t=e.trim();if(!t)return "";let{PGlite:r}=await Ue("@supabase/lite/pglite","pglite","@electric-sql/pglite"),n=new r;try{return await n.exec(ft(mt(t))),await n.exec(Ms),await p0(n,t)}finally{await n.close().catch(()=>{});}}async function p0(e,t){return t?(await e.exec(t),await f0(e)):""}async function f0(e){let t=await e.query(`
|
|
377
|
+
`;});function hd(e=true){return e?Rc(El):El}var gd=w(()=>{Jt();dd();});function k0(e,t,r,n){if(e==null)return "NULL";if(n.includes(t))return e===true||e===1||e==="1"||e==="true"?"true":"false";if(r.includes(t)){let s=typeof e=="string"?e:JSON.stringify(e);return `${yd(s)}::jsonb`}return typeof e=="number"?Number.isFinite(e)?String(e):"NULL":typeof e=="boolean"?e?"true":"false":yd(String(e))}function yd(e){return `'${e.replace(/'/g,"''")}'`}async function _i(e,t={}){let r=t.target??"supabase",n={users:[],sessions:[],identities:[],refresh_tokens:[]},s=e.connection.dialect,i=R0[r];for(let o of T0){let a=s==="sqlite"?`"auth.${o}"`:`auth."${o}"`,l=[];try{l=(await e.connection.exec(`SELECT * FROM ${a}`))?.rows??[];}catch{continue}if(l.length===0)continue;let c=new Set(i[o]),u=A0[o],p=C0[o];for(let f of l){let g={...f};if(r==="supabase"&&o==="users"){let h=g.confirmed_at;h!=null&&g.email_confirmed_at==null&&(g.email_confirmed_at=h);}let d=Object.keys(g).filter(h=>!c.has(h)),m=d.map(h=>k0(g[h],h,u,p)),y=`INSERT INTO auth.${o} (${d.map(h=>`"${h}"`).join(", ")}) VALUES (${m.join(", ")}) ON CONFLICT DO NOTHING`;n[o].push(y);}}return n}var v0,T0,A0,C0,R0,xl=w(()=>{v0=["users","sessions","identities","refresh_tokens"],T0=v0,A0={users:["raw_app_meta_data","raw_user_meta_data"],sessions:[],identities:["identity_data"],refresh_tokens:[]},C0={users:["is_sso_user","is_anonymous"],sessions:[],identities:[],refresh_tokens:["revoked"]},R0={supabase:{users:["confirmed_at"],sessions:[],identities:["email"],refresh_tokens:["id"]},local:{users:["confirmed_at"],sessions:[],identities:["email"],refresh_tokens:[]}};});function $i(e){return !e||e==="main"||e==="public"?"public":e}function Rn(e,t){return `${$i(e)}.${t}`}function N0(e,t){let r=new Map(e.map(a=>[Rn(a.schema,a.name),a])),n=new Map,s=new Map;for(let a of r.keys())n.set(a,new Set),s.set(a,new Set);for(let a of t){let l=Rn(a.schema,a.table),c=Rn(a.ref_schema??a.schema,a.ref_table);!n.has(l)||!n.has(c)||(n.get(l).add(c),s.get(c).add(l));}let i=[...n.entries()].filter(([,a])=>a.size===0).map(([a])=>a),o=[];for(let a=0;a<i.length;a++){let l=i[a];o.push(l);for(let c of s.get(l)??[]){let u=n.get(c);u&&(u.delete(l),u.size===0&&i.push(c));}}if(o.length<e.length){console.warn("Warning: cycle detected in user table foreign keys; using best-effort data export order.");let a=new Set(o);for(let l of e){let c=Rn(l.schema,l.name);a.has(c)||o.push(c);}}return o.map(a=>r.get(a)).filter(Boolean)}function bd(e,t){if(e==null)return "NULL";let r=(t??"").toLowerCase();if(Array.isArray(e)&&r.endsWith("[]")){let n=t?.slice(0,-2);return `ARRAY[${e.map(s=>bd(s,n)).join(", ")}]::${t}`}if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return Number.isFinite(e)?String(e):"NULL";if(r.includes("bool")&&(e===0||e===1||e==="0"||e==="1"))return e===1||e==="1"?"true":"false";if(r.includes("json")){let n=typeof e=="string"?e:JSON.stringify(e),s=r.includes("jsonb")?"::jsonb":"::json";return `${gr(n)}${s}`}return e instanceof Date?gr(e.toISOString()):typeof e=="object"?`${gr(JSON.stringify(e))}::jsonb`:gr(String(e))}function gr(e){return `'${e.replace(/'/g,"''")}'`}function _l(e){return `"${e.replace(/"/g,'""')}"`}function O0(e){let t=e.default_value??e.default;if(typeof t=="string"&&t.trim().toLowerCase().startsWith("nextval("))return true;let r=typeof e.type=="string"?e.type.toLowerCase():"",n=typeof e.pg_type=="string"?e.pg_type.toLowerCase():"";return wd.has(r)||wd.has(n)}function I0(e,t,r){let n=`${_l(e)}.${_l(t)}`;return `SELECT setval(pg_get_serial_sequence(${gr(n)}, ${gr(r)}), COALESCE((SELECT MAX(${_l(r)}) FROM ${n}), 1));`}async function L0(e){let t=e.connection.config?.translation?.deparse?.schema;if(t instanceof Map&&t.size>0)return t;let r=await fe(e);return r.trim()?(await An(r)).schema:new Map}async function vi(e){let t=await e.connection.introspect(),r=e.connection.dialect,n=await L0(e),s=N0(t.tables.filter(o=>!P0.has($i(o.schema))),t.foreign_keys),i=[];for(let o of s){let a=$i(o.schema),l=r==="sqlite"?a==="public"?`"${o.name}"`:`"${a}.${o.name}"`:`"${a}"."${o.name}"`,u=t.columns.filter(S=>S.table===o.name&&$i(S.schema)===a).filter(S=>!S.generated&&!S.is_generated),p=[];try{p=(await e.connection.exec(`SELECT * FROM ${l}`))?.rows??[];}catch{continue}if(p.length===0)continue;let f=n.get(Rn(a,o.name)),g=typeof e.connection.deserializeRow=="function"?e.connection.deserializeRow.bind(e.connection):S=>S;p=p.map(S=>{let T=f?f.deserializeRow(S):S;return g(T)});let d=u.map(S=>S.name),m=new Map(u.map(S=>[S.name,S.pg_type??S.type])),y=[];for(let S of p){let T=d.map($=>bd(S[$],m.get($)));y.push(`INSERT INTO "${a}"."${o.name}" (${d.map($=>`"${$}"`).join(", ")}) VALUES (${T.join(", ")}) ON CONFLICT DO NOTHING`);}let h=u.filter(O0).map(S=>I0(a,o.name,S.name));i.push({schema:a,table:o.name,inserts:y,sequenceResets:h});}return i}var P0,wd,$l=w(()=>{yi();He();P0=new Set(["auth","storage","realtime","supabase_functions","graphql","graphql_public","extensions","pgsodium","pgsodium_masks","vault","information_schema","pg_catalog","pg_toast"]),wd=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]);});async function Sd(e){let{PGlite:t}=await qe("@supabase/lite/pglite","pglite","@electric-sql/pglite"),r=new t,n=[],s=0,i=0,o=0,a=0;try{for(let d of ["anon","authenticated","service_role","supabase_auth_admin"])await r.exec(`CREATE ROLE ${d}`);let l=bt(Bs);for(let d=0;d<l.length;d++)try{await r.exec(l[d]);}catch(m){return n.push({phase:"schema",label:`auth helpers ${d+1}/${l.length}`,statement:l[d],error:String(m)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}if(e.config.auth?.enabled!==!1){let d=bt(hd());s=d.length;for(let m=0;m<d.length;m++)try{await r.exec(d[m]);}catch(y){return n.push({phase:"schema",label:`auth base schema ${m+1}/${d.length}`,statement:d[m],error:String(y)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}}let c=await fe(e),u=bt(c);i=u.length;for(let d=0;d<u.length;d++)try{await r.exec(u[d]);}catch(m){return n.push({phase:"schema",label:`schema ${d+1}/${u.length}`,statement:u[d],error:String(m)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}let p=await _i(e,{target:"local"}),f=["users","sessions","identities","refresh_tokens"];for(let d of f){let m=p[d];for(let y=0;y<m.length;y++){o++;try{await r.exec(m[y]);}catch(h){n.push({phase:"auth",label:`auth.${d} row ${y+1}/${m.length}`,statement:m[y],error:String(h)});}}}let g=await vi(e);for(let d of g){for(let m=0;m<d.inserts.length;m++){a++;try{await r.exec(d.inserts[m]);}catch(y){n.push({phase:"data",label:`${d.schema}.${d.table} row ${m+1}/${d.inserts.length}`,statement:d.inserts[m],error:String(y)});}}for(let m=0;m<d.sequenceResets.length;m++)try{await r.exec(d.sequenceResets[m]);}catch(y){n.push({phase:"data",label:`${d.schema}.${d.table} sequence reset ${m+1}/${d.sequenceResets.length}`,statement:d.sequenceResets[m],error:String(y)});}}}finally{await r.close().catch(()=>{});}return {ok:n.length===0,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}var Ed=w(()=>{sr();He();gd();bn();Ei();xl();$l();});function xd(e){if(console.log(k.default.bold("Readiness Report")),console.log(` db reachable: ${e.dbReachable?k.default.green("yes"):k.default.red("no")} schema statements: ${k.default.cyan(e.schemaStatementCount)} schema bytes: ${k.default.cyan(e.schemaBytes)}`),console.log(` auth \u2014 users: ${k.default.cyan(e.auth.users)} sessions: ${k.default.cyan(e.auth.sessions)} identities: ${k.default.cyan(e.auth.identities)} refresh_tokens: ${k.default.cyan(e.auth.refresh_tokens)} jwt_secret: ${e.auth.jwt_secret_set?k.default.green("set"):k.default.yellow("unset")}`),e.tables.length>0){console.log(k.default.dim(" tables:"));for(let t of e.tables){let r=t.issues.length>0?k.default.yellow(` (${t.issues.length} issues)`):"",n=t.schema?`${t.schema}.`:"";console.log(` ${n}${t.table}: ${k.default.cyan(t.rowCount)} rows${r}`);}}if(e.errors.length>0){console.log(k.default.red("Errors:"));for(let t of e.errors)console.log(` ${k.default.red("\u2717")} ${t}`);}if(e.warnings.length>0){console.log(k.default.yellow("Warnings:"));for(let t of e.warnings)console.log(` ${k.default.yellow("!")} ${t}`);}console.log(),console.log(e.ok?k.default.green("Ready to upgrade."):k.default.red("Not ready."));}function _d(e){if(console.log(),console.log(k.default.bold("Rehearsal (in-memory pglite)")),console.log(` auth schema: ${k.default.cyan(e.baseSchemaStatements)} stmts user schema: ${k.default.cyan(e.schemaStatements)} stmts auth: ${k.default.cyan(e.authInserts)} inserts data: ${k.default.cyan(e.dataInserts)} inserts`),e.failures.length>0){console.log(k.default.red(` ${e.failures.length} failure(s):`));for(let t of e.failures)console.log(k.default.red(` \u2717 [${t.phase}] ${t.label}`)),console.log(k.default.dim(` ${t.statement}`)),console.log(k.default.dim(` ${t.error}`));}console.log(e.ok?k.default.green(" rehearsal passed"):k.default.red(" rehearsal failed"));}function $d(e){console.log(),console.log(k.default.bold("SQLite Shim Audit")),console.log(` fields: ${k.default.cyan(e.summary.total)} passed: ${k.default.green(String(e.summary.passed))} warned: ${k.default.yellow(String(e.summary.warned))} failed: ${k.default.red(String(e.summary.failed))}`),e.results.length===0&&console.log(k.default.dim(" no shim-backed fields found"));for(let t of e.results.filter(r=>r.status!=="pass")){let r=t.status==="fail"?k.default.red:k.default.yellow;if(console.log(` ${r(t.status)} ${t.field} (${t.pg_type}) rows: ${k.default.cyan(t.rows_checked)} affected: ${k.default.cyan(t.affected_rows??0)}`),t.message&&console.log(` ${t.message}`),t.samples?.length)for(let n of t.samples)console.log(k.default.dim(` sample ${JSON.stringify(n.id)} raw=${JSON.stringify(n.raw_value)}`));t.action&&console.log(k.default.dim(` action: ${t.action}`));}console.log(e.summary.upgrade_safe?k.default.green(" shim audit passed"):k.default.red(" shim audit failed"));}function vl(e){if(console.log(),console.log(k.default.bold(k.default.green("Upgrade complete."))),console.log(),console.log(` ${k.default.bold("Project URL:")} ${k.default.cyan(e.projectUrl)}`),console.log(` ${k.default.bold("API URL:")} ${k.default.cyan(e.apiUrl)}`),e.studioUrl&&console.log(` ${k.default.bold("Studio URL:")} ${k.default.cyan(e.studioUrl)}`),console.log(` ${k.default.bold("Ref:")} ${k.default.cyan(e.projectRef)}`),console.log(),console.log(` ${k.default.bold("anon key:")} ${e.anonKey}`),console.log(` ${k.default.bold("service_role key:")} ${e.serviceRoleKey}`),console.log(` ${k.default.bold("db password:")} ${e.dbPassword}`),console.log(),console.log(` migrated auth \u2014 users: ${k.default.cyan(e.auth.users)} sessions: ${k.default.cyan(e.auth.sessions)} identities: ${k.default.cyan(e.auth.identities)} refresh_tokens: ${k.default.cyan(e.auth.refresh_tokens)}`),console.log(` jwt secret: ${e.jwtMigrated?k.default.green("migrated"):k.default.yellow("not migrated \u2014 users must re-authenticate")}`),e.warnings.length>0){console.log(),console.log(k.default.yellow("Warnings:"));for(let t of e.warnings)console.log(` ${k.default.yellow("!")} ${t}`);}console.log(),console.log(k.default.bold("Update your supabase-js client:")),console.log(` url: ${k.default.cyan(e.apiUrl)}`),console.log(` anonKey: ${k.default.cyan(e.anonKey)}`),console.log();}var k,vd=w(()=>{k=ee(ie());});function Ad(e){let t=[],r=e??"",n=r.toLowerCase(),s=Buffer$1.byteLength(r,"utf8");if(!r)return t.push("auth.jwt_secret is empty"),{strong:false,reasons:t};D0.has(r)&&t.push(`matches Supalite development default "${r}"`),s<32&&t.push(`is ${s} bytes; use at least 32 bytes for production secrets`),[/[a-z]/.test(r),/[A-Z]/.test(r),/[0-9]/.test(r),/[^A-Za-z0-9]/.test(r)].filter(Boolean).length<3&&t.push("uses too little character variety"),/^(.)\1{7,}$/.test(r)?t.push("is one repeated character"):F0(r)&&t.push("contains an obvious repeated pattern");let o=j0.find(a=>n.includes(a));return o&&t.push(`contains placeholder term "${o}"`),{strong:t.length===0,reasons:t}}function Cd(e){return {kty:"oct",alg:"HS256",k:Buffer$1.from(e,"utf8").toString("base64url")}}function F0(e){if(e.length<8)return false;for(let t=2;t<=Math.floor(e.length/2);t++){if(e.length%t!==0)continue;if(e.slice(0,t).repeat(e.length/t)===e)return true}return false}var D0,j0,Rd=w(()=>{D0=new Set(["unsafe-secret-change-me","dev-secret-change-me"]),j0=["change-me","changeme","secret","password","passwd","test","dev"];});async function kd(e){let t=e.trim();if(!t)return "";let{PGlite:r}=await qe("@supabase/lite/pglite","pglite","@electric-sql/pglite"),n=new r;try{return await n.exec(ht(gt(t))),await n.exec(Bs),await M0(n,t)}finally{await n.close().catch(()=>{});}}async function M0(e,t){return t?(await e.exec(t),await U0(e)):""}async function U0(e){let t=await e.query(`
|
|
375
378
|
SELECT table_schema, table_name, column_name, is_nullable, data_type,
|
|
376
379
|
udt_name, udt_schema, character_maximum_length,
|
|
377
380
|
numeric_precision, numeric_scale, column_default, ordinal_position
|
|
@@ -388,30 +391,30 @@ ${r.map(n=>` - ${n.table}: ${n.reason}`).join(`
|
|
|
388
391
|
WHERE tc.constraint_type = 'PRIMARY KEY'
|
|
389
392
|
AND tc.table_schema NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
|
|
390
393
|
ORDER BY kcu.ordinal_position
|
|
391
|
-
`),n=new Map;for(let o of r.rows){let a=`${o.table_schema}.${o.table_name}`,l=n.get(a)??[];l.push(o.column_name),n.set(a,l);}let s=new Map;for(let o of t.rows){let a=`${o.table_schema}.${o.table_name}`,l=s.get(a)??[];l.push(o),s.set(a,l);}let i=[];for(let[o,a]of s){let l=a[0].table_schema,c=a[0].table_name,u=n.get(o)??[],p=a.map(f=>
|
|
394
|
+
`),n=new Map;for(let o of r.rows){let a=`${o.table_schema}.${o.table_name}`,l=n.get(a)??[];l.push(o.column_name),n.set(a,l);}let s=new Map;for(let o of t.rows){let a=`${o.table_schema}.${o.table_name}`,l=s.get(a)??[];l.push(o),s.set(a,l);}let i=[];for(let[o,a]of s){let l=a[0].table_schema,c=a[0].table_name,u=n.get(o)??[],p=a.map(f=>B0(f,u));i.push(`CREATE TABLE ${Tl(l)}.${Tl(c)} (
|
|
392
395
|
${p.join(`,
|
|
393
396
|
`)}
|
|
394
397
|
);`);}return i.join(`
|
|
395
398
|
|
|
396
|
-
`)}function
|
|
397
|
-
`);return i.trim()?(await
|
|
398
|
-
${t}`,{cause:s})}}async function
|
|
399
|
+
`)}function Tl(e){return /^[a-z_][a-z0-9_]*$/.test(e)?e:`"${e.replace(/"/g,'""')}"`}function B0(e,t){let r=[Tl(e.column_name)];return r.push(q0(e)),e.is_nullable==="NO"&&!t.includes(e.column_name)&&r.push("NOT NULL"),e.column_default!==null&&r.push(`DEFAULT ${e.column_default}`),t.length===1&&t[0]===e.column_name&&r.push("PRIMARY KEY"),r.join(" ")}function q0(e){return e.data_type==="ARRAY"?`${e.udt_name.startsWith("_")?e.udt_name.slice(1):e.udt_name}[]`:e.data_type==="USER-DEFINED"?`${e.udt_schema}.${e.udt_name}`:e.data_type==="character varying"&&e.character_maximum_length?`varchar(${e.character_maximum_length})`:e.data_type==="numeric"&&e.numeric_precision&&e.numeric_scale!==null?`numeric(${e.numeric_precision},${e.numeric_scale})`:e.data_type}var Pd=w(()=>{sr();bn();});function Nd(e){return !e||e==="main"?"public":e}function Ht(e){return `"${e.replace(/"/g,'""')}"`}function W0(e,t){return Ht(e==="public"?t:`${e}.${t}`)}function Al(e){return `${e.schema}.${e.table}.${e.column}`}function G0(e){let t=e.filter(s=>s.status==="pass").length,r=e.filter(s=>s.status==="warn").length,n=e.filter(s=>s.status==="fail").length;return {total:e.length,passed:t,warned:r,failed:n,upgrade_safe:n===0}}async function z0(e){let t=e.connection.config?.translation?.deparse?.schema;if(t instanceof Map&&t.size>0)return t;let r=await Ps(e),n=await fe(e);if(r.trim()){let i=[await kd(r),n].filter(o=>o.trim().length>0).join(`
|
|
400
|
+
`);return i.trim()?(await An(i)).schema:new Map}return n.trim()?(await An(n)).schema:new Map}async function V0(e){let t=await z0(e),r=[];for(let n of t.values())for(let s of n.all())s.isShimBacked&&r.push({schema:Nd(s.context.schema),table:s.context.table,column:s.context.column,field:s});return r}function K0(e,t){return e==="fail"||t==="fail"?"fail":e==="warn"||t==="warn"?"warn":"pass"}async function X0(e,t,r){return (await e.connection.introspect()).primary_keys.find(i=>Nd(i.schema)===t&&i.table===r)?.columns??[]}async function J0(e,t){if(e.connection.dialect!=="sqlite")return {field:Al(t),pg_type:t.field.context.pgTypeName,status:"warn",rows_checked:0,affected_rows:0,message:"Shim at-rest scan only applies to SQLite-backed projects.",action:"Run this audit against the SQLite Supalite project before upgrading."};let n=W0(t.schema,t.table),s=await X0(e,t.schema,t.table),i=s.length>0?s:["rowid"],a=[...s.length>0?s.map(m=>`${Ht(m)} AS ${Ht(`id_${m}`)}`):[`rowid AS ${Ht("id_rowid")}`],`${Ht(t.column)} AS ${Ht("__lite_value")}`].join(", "),l;try{l=await e.connection.exec(`SELECT ${a} FROM ${n}`);}catch(m){return {field:Al(t),pg_type:Cl(t.field),status:"fail",rows_checked:0,affected_rows:0,message:`Declared shim field could not be scanned in SQLite: ${String(m)}`,action:"Apply the declared schema to the local Supalite database, then rerun the dry-run audit before upgrading."}}let c=l?.rows??[],u="pass",p=0,f=null,g,d=[];for(let m of c){let y=t.field.validateStorage(m.__lite_value);if(u=K0(u,y.status),y.status!=="pass"&&(p++,f??=y.message,g??=y.action,d.length<H0)){let h={};for(let S of i)h[S]=m[`id_${S}`];d.push({id:h,raw_value:m.__lite_value});}}return {field:Al(t),pg_type:Cl(t.field),status:u,rows_checked:c.length,...p>0?{affected_rows:p}:{},message:f,...d.length>0?{samples:d}:{},...g?{action:g}:{}}}function Cl(e){if(e instanceof ft)return `${e.elementField?Cl(e.elementField):e.context.pgTypeName}[]`;if(e instanceof Ft&&e.numericPrecision){let{precision:t,scale:r}=e.numericPrecision;return `${e.context.pgTypeName}(${t},${r})`}return e instanceof oe&&e.lengthConstraint!==void 0?`${e.context.pgTypeName}(${e.lengthConstraint})`:e.context.pgTypeName}async function Rl(e){let t=await V0(e),r=[];for(let n of t)r.push(await J0(e,n));return {summary:G0(r),results:r}}var H0,Od=w(()=>{He();pt();Pd();yi();Ms();Fs();Ue();H0=3;});function Id(e){let t=e.auth??{},r={};return typeof t.site_url=="string"&&(r.site_url=t.site_url),Array.isArray(t.additional_redirect_urls)&&(r.uri_allow_list=t.additional_redirect_urls.join(",")),typeof t.jwt_expiry=="number"&&(r.jwt_exp=t.jwt_expiry),typeof t.enable_signup=="boolean"&&(r.disable_signup=!t.enable_signup),typeof t.enable_anonymous_sign_ins=="boolean"&&(r.external_anonymous_users_enabled=t.enable_anonymous_sign_ins),typeof t.minimum_password_length=="number"&&(r.min_password_length=t.minimum_password_length),typeof t.email?.enable_confirmations=="boolean"&&(r.mailer_autoconfirm=!t.email.enable_confirmations),r}var Ld=w(()=>{});function Y0(e){if(e.length===0)return "";if(e.length===1)return e[0];let t=e[0].match(Dd);if(!t)return e.map(i=>i.trim().endsWith(";")?i:`${i};`).join(" ");let r=t[1],n=t[3]??"",s=[t[2]];for(let i=1;i<e.length;i++){let o=e[i].match(Dd);if(!o||o[1]!==r||(o[3]??"")!==n)return e.map(a=>a.trim().endsWith(";")?a:`${a};`).join(" ");s.push(o[2]);}return `${r}${s.join(", ")}${n}`}async function jd(e,t,r={}){let n=r.sizes??[50,10,1],s=[],i=0,o=t.length,a=async(l,c)=>{if(l.length===0)return;let u=n[c]??1;if(l.length===1||u===1){for(let p of l){try{await e.runSql(p);}catch(f){s.push({statement:p,error:String(f)});}i++,r.onProgress?.(i,o);}return}for(let p=0;p<l.length;p+=u){let f=l.slice(p,p+u),g=Y0(f);try{await e.runSql(g),i+=f.length,r.onProgress?.(i,o);}catch{await a(f,c+1);}}};return await a(t,0),s}var Dd,Fd=w(()=>{Dd=/^(INSERT INTO [^(]+\([^)]+\)\s*VALUES\s*)(\(.*\))(\s*ON CONFLICT[\s\S]*)?$/i;});async function Q0(e,t,r,n){n.onSql?.(t,r);try{await e.runSql(t);}catch(s){throw new Error(`Failed SQL (${r}): ${String(s)}
|
|
401
|
+
${t}`,{cause:s})}}async function yr(e,t,r,n,s={}){if(r.length===0)return;n.onBatchStart?.(t,r.length);let i=await jd(e,r,{sizes:s.sizes??n.batchSizes,onProgress:(o,a)=>n.onBatchProgress?.(t,o,a)});if(i.length>0)throw n.onBatchFailure?.(t,i),new Error(`${t} had ${i.length} failures`);n.onBatchEnd?.(t,r.length,s.unit??"rows");}async function kl(e,t,r){let n=await fe(e),s=bt(n);r.onSchemaStart?.(s.length);for(let c=0;c<s.length;c++)r.onSchemaProgress?.(c+1,s.length),await Q0(t,s[c],`schema ${c+1}/${s.length}`,r);r.onSchemaEnd?.(s.length);let i=await _i(e,{target:r.authTarget??"supabase"}),o={users:i.users.length,sessions:r.migrateSessions?i.sessions.length:0,identities:i.identities.length,refresh_tokens:r.migrateSessions?i.refresh_tokens.length:0};await yr(t,"Migrating auth.users",i.users,r),await yr(t,"Migrating auth.identities",i.identities,r),r.migrateSessions?(await yr(t,"Migrating auth.sessions",i.sessions,r),await yr(t,"Migrating auth.refresh_tokens",i.refresh_tokens,r)):(i.sessions.length>0||i.refresh_tokens.length>0)&&r.onSkip?.(`Skipped ${i.sessions.length} sessions and ${i.refresh_tokens.length} refresh tokens (existing tokens will be invalidated).`);let a=await vi(e),l=a.filter(c=>c.inserts.length>0);l.length===0&&r.onSkip?.("No user data rows to migrate.");for(let c of l)await yr(t,`Migrating ${c.schema}.${c.table}`,c.inserts,r);for(let c of l)await yr(t,`Resetting ${c.schema}.${c.table} sequences`,c.sequenceResets,r,{sizes:[1],unit:"statements"});if(r.syncAuthConfig!==false&&t.updateAuthConfig){let c=Id(e.config);Object.keys(c).length>0&&(r.onAuthConfigStart?.(),await t.updateAuthConfig(c),r.onAuthConfigEnd?.());}return {schemaStatements:s.length,auth:o,dataTables:a}}var Md=w(()=>{He();Ld();xl();$l();Fd();Ei();});function Nn(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function Ud(e,t=new Map){if(!e||typeof e!="object")return t;for(let[r,n]of Object.entries(e))typeof n=="string"?t.set(Nn(r),n):n&&typeof n=="object"&&Ud(n,t);return t}function kn(e,t,r){for(let n of t){let s=e.get(Nn(n));if(s)return s}throw new Error(`Supabase status JSON is missing ${r}`)}function n_(e){let t=JSON.parse(e),r=Ud(t);return {apiUrl:kn(r,["API_URL","api_url","API URL","Project URL"],"API URL"),studioUrl:r.get(Nn("Studio URL"))??r.get(Nn("STUDIO_URL"))??r.get(Nn("studio_url")),dbUrl:kn(r,["DB_URL","db_url","DB URL"],"DB URL"),anonKey:kn(r,["ANON_KEY","anon_key","anon key","Publishable"],"anon key"),serviceRoleKey:kn(r,["SERVICE_ROLE_KEY","service_role_key","service role key","Secret"],"service role key"),jwtSecret:kn(r,["JWT_SECRET","jwt_secret","JWT secret"],"JWT secret")}}function Bd(e){try{return decodeURIComponent(new URL(e).password)}catch{return ""}}function qd(e=process.cwd()){return e}async function s_(){return await new Promise((e,t)=>{let r=Z0.createServer();r.once("error",t),r.listen(0,"127.0.0.1",()=>{let n=r.address();r.close(()=>{typeof n=="object"&&n?e(n.port):t(new Error("Could not allocate a free local port"));});});})}async function i_(){let e=new Set,t=async()=>{for(;;){let r=await s_();if(!e.has(r))return e.add(r),r}};return {api:await t(),db:await t(),shadow:await t(),studio:await t(),inbucket:await t(),analytics:await t(),pooler:await t(),edgeInspector:await t()}}async function Pn(e,t={}){let r=process.env.LITE_SUPABASE_CLI?.split(/\s+/).filter(Boolean)??t_,{spawn:n}=await import('node:child_process').catch(()=>{throw new Error("Local Supabase upgrade requires a Node-compatible runtime")}),[s,...i]=r;return await new Promise((o,a)=>{let l=n(s,[...i,...e],{cwd:t.cwd,env:{...process.env,SUPABASE_TELEMETRY_DISABLED:"1",DO_NOT_TRACK:"1"}}),c=[],u=[],p=setTimeout(()=>l.kill(),t.timeoutMs??12e4);l.stdout?.on("data",f=>c.push(Buffer.from(f))),l.stderr?.on("data",f=>u.push(Buffer.from(f))),l.on("error",f=>{clearTimeout(p),a(f);}),l.on("close",f=>{clearTimeout(p);let g=Buffer.concat(c).toString("utf8"),d=Buffer.concat(u).toString("utf8");if(f!==0){a(new Error([`supabase ${e.join(" ")} failed with exit code ${f}`,g,d].filter(Boolean).join(`
|
|
399
402
|
`)));return}o({stdout:g,stderr:d});});})}function ne(e,t,r,n){let s=new RegExp(`(\\[${t.replace(".","\\.")}\\][\\s\\S]*?)(?=\\n\\[|$)`),i=e.match(s);if(!i)return `${e.trimEnd()}
|
|
400
403
|
|
|
401
404
|
[${t}]
|
|
402
405
|
${r} = ${n}
|
|
403
406
|
`;let o=i[1],a=new RegExp(`(^${r}\\s*=\\s*).*$`,"m"),l=a.test(o)?o.replace(a,`$1${n}`):`${o.trimEnd()}
|
|
404
407
|
${r} = ${n}
|
|
405
|
-
`;return e.replace(o,l)}function N0(e,t,r){let n=new RegExp(`(\\[${t.replace(".","\\.")}\\][\\s\\S]*?)(?=\\n\\[|$)`),s=e.match(n);if(!s)return e;let i=s[1],o=r.map(l=>l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),a=new RegExp(`^\\s*(${o})\\s*=.*(?:\\n|$)`,"gm");return e.replace(i,i.replace(a,""))}function O0(e){return N0(e,"db",["driver","url"])}function I0(e){let t=e.match(/(\[db\][\s\S]*?)(?=\n\[|$)/)?.[1];return t?/^\s*driver\s*=\s*["'](sqlite|sqlite-postgres|pglite|postgres)["']/m.test(t)?true:/^\s*url\s*=/m.test(t):false}async function $l(e){return await pe__default.access(e).then(()=>true).catch(()=>false)}async function $d(e){let t=We__default.join(e,"supabase","config.toml");if(!await $l(t))return null;let r=await pe__default.readFile(t,"utf-8");if(!I0(r))return null;let n=`${t}.bak`;return await $l(n)||await pe__default.writeFile(n,r,"utf-8"),n}async function L0(e){let t=We__default.join(e,"supabase","config.toml");await $l(t)||(await pe__default.mkdir(e,{recursive:true}),await Tn(["init","--workdir",e,"--yes"],{timeoutMs:6e4}));}async function D0(e,t,r){let n=We__default.join(e,"supabase","config.toml"),s=O0(await pe__default.readFile(n,"utf-8"));s=s.replace(/^project_id\s*=.*$/m,`project_id = "${t}"`),s=ne(s,"api","port",String(r.api)),s=ne(s,"db","port",String(r.db)),s=ne(s,"db","shadow_port",String(r.shadow)),s=ne(s,"db","major_version","15"),s=ne(s,"db.seed","enabled","false"),s=ne(s,"studio","enabled","true"),s=ne(s,"studio","port",String(r.studio)),s=ne(s,"inbucket","enabled","false"),s=ne(s,"inbucket","port",String(r.inbucket)),s=ne(s,"realtime","enabled","false"),s=ne(s,"storage","enabled","false"),s=ne(s,"edge_runtime","enabled","false"),s=ne(s,"edge_runtime","inspector_port",String(r.edgeInspector)),s=ne(s,"analytics","enabled","false"),s=ne(s,"analytics","port",String(r.analytics)),s=ne(s,"db.pooler","enabled","false"),s=ne(s,"db.pooler","port",String(r.pooler)),await pe__default.writeFile(n,s,"utf-8");}function vd(e){return JSON.stringify(e)}function j0(e){return `[${e.map(vd).join(", ")}]`}async function F0(e,t){if(!t)return;let r=We__default.join(e,"supabase","config.toml"),n=await pe__default.readFile(r,"utf-8"),s=t.auth??{},i=s.email??{},o=t.api??{};typeof o.max_rows=="number"&&(n=ne(n,"api","max_rows",String(o.max_rows))),typeof s.site_url=="string"&&(n=ne(n,"auth","site_url",vd(s.site_url))),Array.isArray(s.additional_redirect_urls)&&(n=ne(n,"auth","additional_redirect_urls",j0(s.additional_redirect_urls))),typeof s.jwt_expiry=="number"&&(n=ne(n,"auth","jwt_expiry",String(s.jwt_expiry))),typeof s.enable_signup=="boolean"&&(n=ne(n,"auth","enable_signup",String(s.enable_signup))),typeof s.enable_anonymous_sign_ins=="boolean"&&(n=ne(n,"auth","enable_anonymous_sign_ins",String(s.enable_anonymous_sign_ins))),typeof s.minimum_password_length=="number"&&(n=ne(n,"auth","minimum_password_length",String(s.minimum_password_length))),typeof i.enable_confirmations=="boolean"&&(n=ne(n,"auth.email","enable_confirmations",String(i.enable_confirmations))),await pe__default.writeFile(r,n,"utf-8");}var A0,C0,Si,Td=y(()=>{Qt();A0=["bunx","supabase@2.98.1"],C0=["mailpit","realtime","storage-api","imgproxy","edge-runtime","logflare","vector","supavisor"];Si=class e{constructor(t,r,n,s){this.workdir=t;this.projectId=r;this.status=n;this.cleanupOnStop=s;}stopped=false;static async start(t={}){let r=t.workdir??await pe__default.mkdtemp(We__default.join(gw.tmpdir(),"lite-local-supa-")),n=t.projectId??`lite-local-${Date.now().toString(36)}`,s=t.cleanupOnStop??!t.workdir,i=await P0();try{await L0(r),await D0(r,n,i),await F0(r,t.sourceConfig),await Tn(["start","--workdir",r,"--yes","--exclude",C0.join(",")],{timeoutMs:5*6e4});let{stdout:o}=await Tn(["status","--workdir",r,"-o","json"],{timeoutMs:6e4});return new e(r,n,R0(o),s)}catch(o){throw await Tn(["stop","--workdir",r,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),s&&await pe__default.rm(r,{recursive:true,force:true}).catch(()=>{}),o}}async runSql(t){let{createPostgresConnection:r}=await Ue("@supabase/lite/postgres","postgres","postgres"),n=r({url:this.status.dbUrl});try{await n.exec(t);}finally{await n.close();}}async stop(){this.stopped||(this.stopped=true,await Tn(["stop","--workdir",this.workdir,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),this.cleanupOnStop&&await pe__default.rm(this.workdir,{recursive:true,force:true}));}};});async function Ei(){let e=await xn({message:"Email",placeholder:"Enter your email",validate:t=>{try{Bc(t,{domains:["supabase.io"],panic:!0});return}catch(r){return r}}});return be(e)&&process.exit(1),e}async function xi(e=false){let t=await Sn({message:"Password",validate:r=>{try{qc(r,{panic:!0});return}catch(n){return n}}});if(be(t)&&process.exit(1),e){let r=await Sn({message:"Confirm Password",validate:n=>{try{if(n!==t)throw new Error("Passwords do not match");return}catch(s){return s}}});be(r)&&process.exit(1);}return t}async function Ad(){let e=await xn({message:"Project Name",placeholder:"Enter your project name"});return be(e)&&process.exit(1),e}async function _i(e){let t=await bn({message:e,initialValue:true});return be(t)&&process.exit(1),t}var fr=y(()=>{Xe();Ar();});async function B0(){return mr||(mr=await import('@sentry/node')),mr}function q0(){if(Rd)return;Rd=true;let e=process.exit.bind(process),t=false;process.exit=(r=>{if(t)return;t=true,$i((r??0)!==0).finally(()=>e(r));});}function Nd(e){if(e)return false;let t=process.env.LITE_TELEMETRY;if(t==="0"||t==="false")return false;let r=process.env.DO_NOT_TRACK;return !(r==="1"||r==="true"||process.env.CI||process.env.LOCAL)}function H0(){let e=process.versions;return e.bun?"bun":e.deno?"deno":"node"}function W0(){if(process.env.CODESPACES)return "codespaces";if(process.env.REMOTE_CONTAINERS)return "devcontainer";try{return statSync("/.dockerenv"),"docker"}catch{return}}function G0(e){let t=e/1e6;return t<1?"<1MB":t<10?"1-10MB":t<100?"10-100MB":t<1e3?"100MB-1GB":">1GB"}function z0(e,t){if(e==="sqlite"||e==="sqlite-postgres"||e==="pglite")return !t||t===":memory:"||t.startsWith("file::memory:")?e==="pglite"&&!t?void 0:"memory":t.startsWith("file:")?"file":void 0;if(e==="postgres"){if(!t)return;try{let r=new URL(t).hostname;return r==="localhost"||r==="127.0.0.1"||r==="::1"?"local":"remote"}catch{return "remote"}}}function V0(){try{let e=We__default.resolve(process.cwd(),ve.config_dir,"config.toml"),t;try{t=readFileSync(e,"utf-8");}catch{return {}}let r;try{r=Et(t);}catch{return {}}let n=r.db?.driver,s=n==="sqlite"||n==="sqlite-postgres"||n==="pglite"||n==="postgres"?n:"sqlite-postgres",i=r.db?.url??ve.default_db_url,o=z0(s,i),a;if(o==="file"&&i.startsWith("file:"))try{let l=i.startsWith("file://")?i.slice(7):i.slice(5),c=We__default.resolve(process.cwd(),l);a=statSync(c).size;}catch{}return {driver:s,location:o,sizeBytes:a}}catch{return {}}}async function Od(e){if(Rn)return;Rn=true;let t=await B0(),{version:r}=await Gn();t.init({dsn:U0,release:`@supabase/lite@${r}`,sendDefaultPii:false,defaultIntegrations:false,integrations:[t.httpIntegration()],tracesSampleRate:1,tracePropagationTargets:["sentry.io"],beforeSend(i){return delete i.server_name,i.user&&delete i.user.ip_address,i},beforeSendTransaction(i){return delete i.server_name,i.user&&delete i.user.ip_address,i}}),t.setTag("command",e.command),t.setTag("runtime",H0()),t.setTag("node",process.version),t.setTag("platform",process.platform),t.setTag("arch",process.arch),t.setTag("ci",!!process.env.CI);let n=W0();n&&t.setTag("container",n);try{let{determineAgent:i}=await import('@vercel/detect-agent'),o=await i();o.isAgent&&t.setTag("agent",o.agent.name);}catch{}let s=V0();s.driver&&t.setTag("db.driver",s.driver),s.location&&t.setTag("db.location",s.location),typeof s.sizeBytes=="number"&&t.setTag("db.size",G0(s.sizeBytes));for(let[i,o]of Object.entries(e.args))t.setTag(`arg.${i}`,!!o);t.startSession(),Pd=true,Mt=t.startInactiveSpan({name:`cli:${e.command}`,op:"cli.command",forceTransaction:true}),q0();}async function $i(e,t){if(!Rn)return;let r=mr;try{if(e&&(r.setTag("status","failed"),t instanceof Error&&r.setTag("error_class",t.constructor.name)),Mt&&(Mt.setStatus({code:e?2:1,message:e?"internal_error":"ok"}),Mt.end(),Mt=void 0),Pd){let n=r.getCurrentScope().getSession();n&&e&&(n.status="crashed"),r.endSession();}}finally{await r.flush(2e3).catch(()=>{});}}function kn(e,t){if(!Rn)return Promise.resolve(t());let r=mr,n=()=>r.startSpan({name:e,op:"cli.step"},t);return Mt?r.withActiveSpan(Mt,n):n()}function vl(e,t){Rn&&mr.setTag(e,t);}var U0,mr,Rn,Pd,Mt,Rd,Tl=y(()=>{Er();Wt();Ee();U0="https://9562525a4ea320539ea7e94859533a17@o398706.ingest.us.sentry.io/4511381939290112";Rn=false,Pd=false,Rd=false;});var Fd={};de(Fd,{isNonInteractive:()=>Al,resolveSessionMigration:()=>jd,resolveTarget:()=>Dd,upgrade:()=>r_});async function J0(e,t){let r=await e.listOrganizations();if(r.length===0)throw new Error("No Supabase organizations found for this token");if(t){let s=r.find(i=>i.id===t||i.slug===t);if(!s)throw new Error(`Organization not found: ${t}`);return s}if(r.length===1)return r[0];let n=await En({message:"Select organization",options:r.map(s=>({value:s.id,label:`${s.name} (${s.slug})`}))});return be(n)&&process.exit(1),r.find(s=>s.id===n)}async function Y0(e,t,r){if(r)return r;let n=X0;try{let o=(await e.listRegions(t)).regions??[];o.length>0&&(n=o.map(a=>({key:a.key,label:a.display_name??a.name??a.key})));}catch{}let s=await En({message:"Select region",options:n.map(i=>({value:i.key,label:i.label}))});return be(s)&&process.exit(1),s}async function Q0(e){if(e)return e;let t=await xn({message:"Project name",placeholder:"my-project",validate:r=>r&&r.trim().length>0?void 0:"Name is required"});return be(t)&&process.exit(1),t}function Z0(){return K0.randomBytes(24).toString("base64url")}function Dd(e){let t=e??"hosted";if(t==="hosted"||t==="local")return t;throw new Error(`Unknown upgrade target '${t}'. Use 'hosted' or 'local'.`)}function Al(){return process.env.CI==="true"||process.env.LITE_NON_INTERACTIVE==="1"||!process.stdin.isTTY}async function e_(e){if(typeof e=="boolean")return e;if(Al())return false;let t=await bn({message:"Migrate existing sessions (transfers JWT secret, sessions, refresh tokens)?",initialValue:false});return be(t)&&process.exit(1),t}async function t_(e){if(e)return e;let t=process.env.SUPABASE_ACCESS_TOKEN;if(t)return t;K.info("Create a personal access token at https://supabase.com/dashboard/account/tokens");let r=await Sn({message:"Supabase access token",validate:n=>n&&n.trim().length>0?void 0:"Token is required"});return be(r)&&process.exit(1),r}async function jd(e){if(!e.requested)return {migrateSessions:false,weakReasons:[]};if(!e.jwtSecret)throw new Error("Cannot migrate sessions because auth.jwt_secret is not configured. Re-run with --no-migrate-sessions to skip session migration.");let t=ld(e.jwtSecret);if(t.strong||e.allowWeakJwtSecret)return {migrateSessions:true,jwtSecret:e.jwtSecret,weakReasons:t.reasons};if(Al())throw new Error(["Cannot migrate sessions because auth.jwt_secret looks weak:",...t.reasons.map(n=>`- ${n}`),"Use --allow-weak-jwt-secret to preserve existing sessions anyway, or --no-migrate-sessions to require users to sign in again."].join(`
|
|
408
|
+
`;return e.replace(o,l)}function o_(e,t,r){let n=new RegExp(`(\\[${t.replace(".","\\.")}\\][\\s\\S]*?)(?=\\n\\[|$)`),s=e.match(n);if(!s)return e;let i=s[1],o=r.map(l=>l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),a=new RegExp(`^\\s*(${o})\\s*=.*(?:\\n|$)`,"gm");return e.replace(i,i.replace(a,""))}function a_(e){return o_(e,"db",["driver","url"])}function l_(e){let t=e.match(/(\[db\][\s\S]*?)(?=\n\[|$)/)?.[1];return t?/^\s*driver\s*=\s*["'](sqlite|sqlite-postgres|pglite|postgres)["']/m.test(t)?true:/^\s*url\s*=/m.test(t):false}async function Pl(e){return await pe__default.access(e).then(()=>true).catch(()=>false)}async function Hd(e){let t=ze__default.join(e,"supabase","config.toml");if(!await Pl(t))return null;let r=await pe__default.readFile(t,"utf-8");if(!l_(r))return null;let n=`${t}.bak`;return await Pl(n)||await pe__default.writeFile(n,r,"utf-8"),n}async function c_(e){let t=ze__default.join(e,"supabase","config.toml");await Pl(t)||(await pe__default.mkdir(e,{recursive:true}),await Pn(["init","--workdir",e,"--yes"],{timeoutMs:6e4}));}async function u_(e,t,r){let n=ze__default.join(e,"supabase","config.toml"),s=a_(await pe__default.readFile(n,"utf-8"));s=s.replace(/^project_id\s*=.*$/m,`project_id = "${t}"`),s=ne(s,"api","port",String(r.api)),s=ne(s,"db","port",String(r.db)),s=ne(s,"db","shadow_port",String(r.shadow)),s=ne(s,"db","major_version","15"),s=ne(s,"db.seed","enabled","false"),s=ne(s,"studio","enabled","true"),s=ne(s,"studio","port",String(r.studio)),s=ne(s,"inbucket","enabled","false"),s=ne(s,"inbucket","port",String(r.inbucket)),s=ne(s,"realtime","enabled","false"),s=ne(s,"storage","enabled","false"),s=ne(s,"edge_runtime","enabled","false"),s=ne(s,"edge_runtime","inspector_port",String(r.edgeInspector)),s=ne(s,"analytics","enabled","false"),s=ne(s,"analytics","port",String(r.analytics)),s=ne(s,"db.pooler","enabled","false"),s=ne(s,"db.pooler","port",String(r.pooler)),await pe__default.writeFile(n,s,"utf-8");}function Wd(e){return JSON.stringify(e)}function p_(e){return `[${e.map(Wd).join(", ")}]`}async function f_(e,t){if(!t)return;let r=ze__default.join(e,"supabase","config.toml"),n=await pe__default.readFile(r,"utf-8"),s=t.auth??{},i=s.email??{},o=t.api??{};typeof o.max_rows=="number"&&(n=ne(n,"api","max_rows",String(o.max_rows))),typeof s.site_url=="string"&&(n=ne(n,"auth","site_url",Wd(s.site_url))),Array.isArray(s.additional_redirect_urls)&&(n=ne(n,"auth","additional_redirect_urls",p_(s.additional_redirect_urls))),typeof s.jwt_expiry=="number"&&(n=ne(n,"auth","jwt_expiry",String(s.jwt_expiry))),typeof s.enable_signup=="boolean"&&(n=ne(n,"auth","enable_signup",String(s.enable_signup))),typeof s.enable_anonymous_sign_ins=="boolean"&&(n=ne(n,"auth","enable_anonymous_sign_ins",String(s.enable_anonymous_sign_ins))),typeof s.minimum_password_length=="number"&&(n=ne(n,"auth","minimum_password_length",String(s.minimum_password_length))),typeof i.enable_confirmations=="boolean"&&(n=ne(n,"auth.email","enable_confirmations",String(i.enable_confirmations))),await pe__default.writeFile(r,n,"utf-8");}var t_,r_,Ti,Gd=w(()=>{sr();t_=["bunx","supabase@2.98.1"],r_=["mailpit","realtime","storage-api","imgproxy","edge-runtime","logflare","vector","supavisor"];Ti=class e{constructor(t,r,n,s){this.workdir=t;this.projectId=r;this.status=n;this.cleanupOnStop=s;}stopped=false;static async start(t={}){let r=t.workdir??await pe__default.mkdtemp(ze__default.join(Cw.tmpdir(),"lite-local-supa-")),n=t.projectId??`lite-local-${Date.now().toString(36)}`,s=t.cleanupOnStop??!t.workdir,i=await i_();try{await c_(r),await u_(r,n,i),await f_(r,t.sourceConfig),await Pn(["start","--workdir",r,"--yes","--exclude",r_.join(",")],{timeoutMs:5*6e4});let{stdout:o}=await Pn(["status","--workdir",r,"-o","json"],{timeoutMs:6e4});return new e(r,n,n_(o),s)}catch(o){throw await Pn(["stop","--workdir",r,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),s&&await pe__default.rm(r,{recursive:true,force:true}).catch(()=>{}),o}}async runSql(t){let{createPostgresConnection:r}=await qe("@supabase/lite/postgres","postgres","postgres"),n=r({url:this.status.dbUrl});try{await n.exec(t);}finally{await n.close();}}async stop(){this.stopped||(this.stopped=true,await Pn(["stop","--workdir",this.workdir,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),this.cleanupOnStop&&await pe__default.rm(this.workdir,{recursive:true,force:true}));}};});async function Ai(){let e=await Tn({message:"Email",placeholder:"Enter your email",validate:t=>{try{Vc(t,{domains:["supabase.io"],panic:!0});return}catch(r){return r}}});return Se(e)&&process.exit(1),e}async function Ci(e=false){let t=await $n({message:"Password",validate:r=>{try{Kc(r,{panic:!0});return}catch(n){return n}}});if(Se(t)&&process.exit(1),e){let r=await $n({message:"Confirm Password",validate:n=>{try{if(n!==t)throw new Error("Passwords do not match");return}catch(s){return s}}});Se(r)&&process.exit(1);}return t}async function zd(){let e=await Tn({message:"Project Name",placeholder:"Enter your project name"});return Se(e)&&process.exit(1),e}async function Ri(e){let t=await _n({message:e,initialValue:true});return Se(t)&&process.exit(1),t}var wr=w(()=>{Ye();Pr();});var Yd={};de(Yd,{isNonInteractive:()=>Nl,resolveSessionMigration:()=>Jd,resolveTarget:()=>Xd,upgrade:()=>E_});async function d_(e,t){let r=await e.listOrganizations();if(r.length===0)throw new Error("No Supabase organizations found for this token");if(t){let s=r.find(i=>i.id===t||i.slug===t);if(!s)throw new Error(`Organization not found: ${t}`);return s}if(r.length===1)return r[0];let n=await vn({message:"Select organization",options:r.map(s=>({value:s.id,label:`${s.name} (${s.slug})`}))});return Se(n)&&process.exit(1),r.find(s=>s.id===n)}async function g_(e,t,r){if(r)return r;let n=h_;try{let o=(await e.listRegions(t)).regions??[];o.length>0&&(n=o.map(a=>({key:a.key,label:a.display_name??a.name??a.key})));}catch{}let s=await vn({message:"Select region",options:n.map(i=>({value:i.key,label:i.label}))});return Se(s)&&process.exit(1),s}async function y_(e){if(e)return e;let t=await Tn({message:"Project name",placeholder:"my-project",validate:r=>r&&r.trim().length>0?void 0:"Name is required"});return Se(t)&&process.exit(1),t}function w_(){return m_.randomBytes(24).toString("base64url")}function Xd(e){let t=e??"hosted";if(t==="hosted"||t==="local")return t;throw new Error(`Unknown upgrade target '${t}'. Use 'hosted' or 'local'.`)}function Nl(){return process.env.CI==="true"||process.env.LITE_NON_INTERACTIVE==="1"||!process.stdin.isTTY}async function b_(e){if(typeof e=="boolean")return e;if(Nl())return false;let t=await _n({message:"Migrate existing sessions (transfers JWT secret, sessions, refresh tokens)?",initialValue:false});return Se(t)&&process.exit(1),t}async function S_(e){if(e)return e;let t=process.env.SUPABASE_ACCESS_TOKEN;if(t)return t;K.info("Create a personal access token at https://supabase.com/dashboard/account/tokens");let r=await $n({message:"Supabase access token",validate:n=>n&&n.trim().length>0?void 0:"Token is required"});return Se(r)&&process.exit(1),r}async function Jd(e){if(!e.requested)return {migrateSessions:false,weakReasons:[]};if(!e.jwtSecret)throw new Error("Cannot migrate sessions because auth.jwt_secret is not configured. Re-run with --no-migrate-sessions to skip session migration.");let t=Ad(e.jwtSecret);if(t.strong||e.allowWeakJwtSecret)return {migrateSessions:true,jwtSecret:e.jwtSecret,weakReasons:t.reasons};if(Nl())throw new Error(["Cannot migrate sessions because auth.jwt_secret looks weak:",...t.reasons.map(n=>`- ${n}`),"Use --allow-weak-jwt-secret to preserve existing sessions anyway, or --no-migrate-sessions to require users to sign in again."].join(`
|
|
406
409
|
`));K.warning(["auth.jwt_secret looks weak and will become a trusted Supabase signing key:",...t.reasons.map(n=>`- ${n}`)].join(`
|
|
407
|
-
`));let r=await
|
|
408
|
-
Rehearsing upgrade against in-memory pglite...`));let b=await
|
|
409
|
-
${j}`));},onSchemaStart:j=>F.start(`Applying schema (0/${j})`),onSchemaProgress:(j,se)=>F.message(`Applying schema (${j}/${se})`),onSchemaEnd:j=>F.stop(`Schema applied (${j} statements)`),onBatchStart:(j,se)=>F.start(`${j} (0/${se})`),onBatchProgress:(j,se,ce)=>F.message(`${j} (${se}/${ce})`),onBatchEnd:(j,se,ce)=>F.stop(`${j} (${se} ${ce})`),onBatchFailure:(j,se)=>{F.stop(
|
|
410
|
-
${R}`)),j}let
|
|
411
|
-
${b}`));},onSchemaStart:b=>S.start(`Applying schema (0/${b})`),onSchemaProgress:(b,D)=>S.message(`Applying schema (${b}/${D})`),onSchemaEnd:b=>S.stop(`Schema applied (${b} statements)`),onBatchStart:(b,D)=>{S.start(`${b} (0/${D})`);},onBatchProgress:(b,D,R)=>S.message(`${b} (${D}/${R})`),onBatchEnd:(b,D,R)=>S.stop(`${b} (${D} ${R})`),onBatchFailure:(b,D)=>{S.stop(
|
|
412
|
-
`)){if(/^\s*#/.test(t))continue;let r=/^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(t);if(r)return r.groups.mountPoint.trim().replaceAll(/^["']|["']$/g,"")}}var
|
|
413
|
-
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var
|
|
414
|
-
`),o&&await
|
|
410
|
+
`));let r=await _n({message:"Preserve existing sessions anyway by importing this JWT secret?",initialValue:false});return Se(r)&&process.exit(1),r?{migrateSessions:true,jwtSecret:e.jwtSecret,weakReasons:t.reasons}:{migrateSessions:false,weakReasons:t.reasons}}var Ee,h_,E_,Qd=w(()=>{Ee=ee(ie());Ye();Le();Ce();id();md();Ed();vd();Rd();Od();Md();Gd();wr();bi();xe();h_=[{key:"us-east-1",label:"East US (N. Virginia)"},{key:"us-east-2",label:"East US (Ohio)"},{key:"us-west-1",label:"West US (N. California)"},{key:"us-west-2",label:"West US (Oregon)"},{key:"ca-central-1",label:"Canada (Central)"},{key:"sa-east-1",label:"South America (S\xE3o Paulo)"},{key:"eu-west-1",label:"West EU (Ireland)"},{key:"eu-west-2",label:"West Europe (London)"},{key:"eu-west-3",label:"West EU (Paris)"},{key:"eu-central-1",label:"Central EU (Frankfurt)"},{key:"eu-central-2",label:"Central Europe (Zurich)"},{key:"eu-north-1",label:"North EU (Stockholm)"},{key:"ap-south-1",label:"South Asia (Mumbai)"},{key:"ap-southeast-1",label:"Southeast Asia (Singapore)"},{key:"ap-southeast-2",label:"Oceania (Sydney)"},{key:"ap-northeast-1",label:"Northeast Asia (Tokyo)"},{key:"ap-northeast-2",label:"Northeast Asia (Seoul)"}];E_=e=>e.command("upgrade").description("[lite] Upgrade this Supalite project to full Supabase").option("--dry-run","Check readiness without making changes",false).option("--force","Perform the upgrade",false).option("--target <target>","'hosted' or 'local' Supabase target","hosted").option("--mode <mode>","'user' or 'platform' (only 'user' is supported)","user").option("--org-id <id>","Supabase organization ID or slug").option("--region <region>","Project region key").option("--project-name <name>","Name for the new Supabase project").option("--supabase-token <token>","Supabase personal access token").option("--local-dir <path>","Supabase CLI workdir for --target local").option("--migrate-sessions","Transfer existing sessions, refresh tokens, and JWT secret so current tokens keep working").option("--no-migrate-sessions","Skip sessions, refresh tokens, and JWT secret").option("--allow-weak-jwt-secret","Allow --migrate-sessions to import a weak JWT secret non-interactively",false).option("--dump-credentials <path>","Write credentials to a file").option("--config <config>","Path to the local config file").option("--verbose","Echo each SQL statement sent to Supabase",false).option("--json","Emit machine-readable JSON for --dry-run",false).helpGroup("Management APIs:").action(async t=>{let r=t.dryRun&&t.json,n=console.log;r||console.log(),await Z(async()=>{await Y(t.config);let s=Xd(t.target);if(bl("upgrade.target",s),bl("upgrade.dry_run",!!t.dryRun),s==="hosted"&&t.localDir)throw new Error("--local-dir can only be used with --target local.");if(s==="hosted"&&t.mode&&t.mode!=="user")throw new Error(`Mode '${t.mode}' is not yet supported. Only 'user' mode is available.`);if(s==="local"&&t.mode&&t.mode!=="user")throw new Error("--mode only applies to hosted upgrades.");r&&(console.log=()=>{});let i;try{i=await(await z({withSupabaseClient:!1})).project.local.createApp(t.config);}finally{r&&(console.log=n);}if(r){let b=await Rl(i);n(JSON.stringify(b,null,2)),b.summary.upgrade_safe||process.exit(1);return}console.log(Ee.default.dim("Running readiness checks..."));let o=await Cn("readiness",()=>fd(i));if(xd(o),!o.ok)throw new Error("Readiness checks failed. See errors above.");let a=async()=>{console.log(Ee.default.dim(`
|
|
411
|
+
Rehearsing upgrade against in-memory pglite...`));let b=await Cn("rehearsal",()=>Sd(i));return _d(b),b.ok};if(t.dryRun){let b=await Rl(i);$d(b),b.summary.upgrade_safe||process.exit(1),await a()||process.exit(1);return}if(!t.force&&!await Ri("Proceed with upgrade?"))return;if(!await a())throw new Error("Rehearsal failed. Upgrade aborted.");if(s==="local"){if(t.migrateSessions===!0)throw new Error("--target local does not support preserving existing sessions yet. Re-run with --no-migrate-sessions.");let b=ze__default.resolve(t.localDir??qd()),D=await Hd(b),R=null;if(D){let j=ze__default.relative(process.cwd(),D)||D;R=`Your project's supabase/config.toml was rewritten in place for the local Supabase CLI. The original was backed up to ${j}. To resume supalite dev (bun run dev), restore it: cp ${j} supabase/config.toml (or git checkout supabase/config.toml). Pass --local-dir <separate-dir> next time to keep the local stack isolated.`;}let F=hl(),E,x;try{F.start(`Starting local Supabase in ${b}`),E=await Ti.start({workdir:b,cleanupOnStop:!1,sourceConfig:i.config}),F.stop(`Local Supabase is running at ${E.status.apiUrl}`),x=await Cn("apply",()=>kl(i,E,{migrateSessions:!1,authTarget:"supabase",syncAuthConfig:!1,onSql:(j,se)=>{t.verbose&&console.log(Ee.default.dim(`-- ${se}
|
|
412
|
+
${j}`));},onSchemaStart:j=>F.start(`Applying schema (0/${j})`),onSchemaProgress:(j,se)=>F.message(`Applying schema (${j}/${se})`),onSchemaEnd:j=>F.stop(`Schema applied (${j} statements)`),onBatchStart:(j,se)=>F.start(`${j} (0/${se})`),onBatchProgress:(j,se,ce)=>F.message(`${j} (${se}/${ce})`),onBatchEnd:(j,se,ce)=>F.stop(`${j} (${se} ${ce})`),onBatchFailure:(j,se)=>{F.stop(Ee.default.red(`${j}: ${se.length} failed`));for(let ce of se)console.log(Ee.default.red(` \u2717 ${ce.error}`)),t.verbose&&console.log(Ee.default.dim(` ${ce.statement}`));},onSkip:j=>console.log(Ee.default.dim(j))}));}catch(j){throw R&&console.log(Ee.default.yellow(`
|
|
413
|
+
${R}`)),j}let J=["Sessions and JWT secret not migrated. Existing tokens are invalid \u2014 users must re-authenticate.","Management API auth config sync is skipped for --target local; supported local auth settings are written before Supabase starts."];R&&J.unshift(R),i.config.storage?.enabled&&J.push("Storage migration is not yet supported."),i.config.realtime?.enabled&&J.push("Realtime config migration is not yet supported.");let q=Bd(E.status.dbUrl);if(t.dumpCredentials){let j=JSON.stringify({target:"local",workdir:E.workdir,projectUrl:E.status.apiUrl,apiUrl:E.status.apiUrl,studioUrl:E.status.studioUrl,dbUrl:E.status.dbUrl,anonKey:E.status.anonKey,serviceRoleKey:E.status.serviceRoleKey,dbPassword:q},null,2);await pe__default.writeFile(t.dumpCredentials,j,"utf-8"),console.log(Ee.default.dim(`Credentials written to ${t.dumpCredentials}`));}vl({projectRef:E.projectId,projectUrl:E.status.apiUrl,apiUrl:E.status.apiUrl,studioUrl:E.status.studioUrl,anonKey:E.status.anonKey,serviceRoleKey:E.status.serviceRoleKey,dbPassword:q,auth:x.auth,jwtMigrated:!1,warnings:[`Local Supabase workdir: ${E.workdir}`,...J]});return}let c=await S_(t.supabaseToken),u=new Si(c);try{await u.listOrganizations();}catch(b){throw new Error(`Supabase access token rejected: ${String(b)}`)}let p=await d_(u,t.orgId),f=await g_(u,p.slug,t.region),g=await y_(t.projectName),d=await b_(t.migrateSessions),m=await Jd({requested:d,jwtSecret:i.config.auth?.jwt_secret,allowWeakJwtSecret:t.allowWeakJwtSecret}),y=m.migrateSessions,h=w_(),S=hl();S.start("Creating Supabase project");let T=await u.createProject({organization_id:p.id,name:g,db_pass:h,region:f}),$=T.ref??T.id;if(S.stop(`Project created: ${$}`),S.start("Waiting for project to become active"),await u.waitForActive($,{onTick:b=>S.message(`Project status: ${b}`)}),S.stop("Project is active"),y){S.start("Importing JWT signing key");try{await u.createSigningKey($,{algorithm:"HS256",status:"in_use",private_jwk:Cd(m.jwtSecret)});}catch(b){throw S.stop(Ee.default.red("JWT signing key import failed")),new Error(["Session migration is not available for this Supabase project, token, or plan.","The upgrade cannot preserve existing Supalite sessions without importing auth.jwt_secret as a signing key.","Re-run with --no-migrate-sessions if requiring users to sign in again is acceptable.",`Supabase response: ${String(b)}`].join(" "))}S.stop("JWT signing key imported");}let N=(await Cn("apply",()=>kl(i,{runSql:b=>u.runSql($,b),updateAuthConfig:b=>u.updateAuthConfig($,b)},{migrateSessions:y,authTarget:"supabase",onSql:(b,D)=>{t.verbose&&console.log(Ee.default.dim(`-- ${D}
|
|
414
|
+
${b}`));},onSchemaStart:b=>S.start(`Applying schema (0/${b})`),onSchemaProgress:(b,D)=>S.message(`Applying schema (${b}/${D})`),onSchemaEnd:b=>S.stop(`Schema applied (${b} statements)`),onBatchStart:(b,D)=>{S.start(`${b} (0/${D})`);},onBatchProgress:(b,D,R)=>S.message(`${b} (${D}/${R})`),onBatchEnd:(b,D,R)=>S.stop(`${b} (${D} ${R})`),onBatchFailure:(b,D)=>{S.stop(Ee.default.red(`${b}: ${D.length} failed`));for(let R of D)console.log(Ee.default.red(` \u2717 ${R.error}`)),t.verbose&&console.log(Ee.default.dim(` ${R.statement}`));},onAuthConfigStart:()=>S.start("Syncing auth config"),onAuthConfigEnd:()=>S.stop("Auth config synced"),onSkip:b=>console.log(Ee.default.dim(b))}))).auth,v=sd(await u.getApiKeys($)),_=`https://${$}.${u.projectDomain}`,I=[];if(y?m.weakReasons.length>0?I.push(`A weak JWT secret was imported to preserve sessions: ${m.weakReasons.join("; ")}.`):I.push("Sessions preserved by importing auth.jwt_secret as a Supabase signing key."):I.push("Sessions and JWT secret not migrated. Existing tokens are invalid \u2014 users must re-authenticate."),i.config.storage?.enabled&&I.push("Storage migration is not yet supported."),i.config.realtime?.enabled&&I.push("Realtime config migration is not yet supported."),t.dumpCredentials){let b=JSON.stringify({ref:$,projectUrl:_,anonKey:v.anon,serviceRoleKey:v.service_role,dbPassword:h},null,2);await pe__default.writeFile(t.dumpCredentials,b,"utf-8"),console.log(Ee.default.dim(`Credentials written to ${t.dumpCredentials}`));}vl({projectRef:$,projectUrl:_,apiUrl:_,anonKey:v.anon,serviceRoleKey:v.service_role,dbPassword:h,auth:N,jwtMigrated:!!(y&&m.jwtSecret),warnings:I});});});});var Zd={};de(Zd,{login:()=>x_});var Ol,x_,eh=w(()=>{Ol=ee(ie());Ye();wr();Le();Ce();x_=e=>{e.command("login").description("Login").option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{await Z(async()=>{let r=await z();K.message(Ol.default.dim("Enter your credentials to login to the cloud"));let n=await Ai(),s=await Ci(),{data:i,error:o}=await r.client.auth.signInWithPassword({email:n,password:s});o&&(K.error(o.message),process.exit(1)),t.json?console.log(JSON.stringify(i,null,2)):K.success(`Authenticated as: ${Ol.default.cyan(i.user.email)}`);});});};});var rh={};de(rh,{logout:()=>__});var th,__,nh=w(()=>{th=ee(ie());Ce();Ye();Le();__=e=>{e.command("logout").description("Logout").helpGroup("Local Development:").action(async()=>{console.log(),await Z(async()=>{let t=await z(),{error:r}=await t.client.auth.signOut();r&&(K.error(r.message),process.exit(1)),console.log(th.default.green("Logged out successfully"));});});};});var sh={};de(sh,{signup:()=>$_});var Il,$_,ih=w(()=>{Il=ee(ie());Ye();wr();Le();Ce();Je();$_=e=>{e.command("signup").description(ge("Register a supalite cloud account")).option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{K.message(Il.default.dim("Enter your credentials to sign up to the cloud")),await Z(async()=>{let r=await z(),n=await Ai(),s=await Ci(!0),{data:i,error:o}=await r.client.auth.signUp({email:n,password:s});o&&(K.error(o.message),process.exit(1)),t.json?console.log(JSON.stringify(i,null,2)):K.success(`Signed up as: ${Il.default.cyan(i.user.email)}`);});});};});var oh={};de(oh,{whoami:()=>v_});var Ll,v_,ah=w(()=>{Ll=ee(ie());Ce();Ye();Le();Je();v_=e=>{e.command("whoami").description(ge("Show the current authenticated user")).option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{console.log(),await Z(async()=>{let r=await z(),{data:n,error:s}=await r.client.auth.getUser();t.json?console.log(JSON.stringify(n,null,2)):n&&"user"in n&&n.user&&"email"in n.user?(console.log(`Authenticated as: ${Ll.default.cyan(n.user.email)}`),process.exit(0)):(console.log(Ll.default.yellow("Not authenticated")),process.exit(1)),s&&(K.error(s.message),process.exit(1));});});};});var ch={};de(ch,{link:()=>T_});var lh,T_,uh=w(()=>{Le();Ce();xe();Ye();lh=ee(ie()),T_=e=>e.command("link").description("Link to a Supalite project").option("--project-ref <project-ref>","The reference of the project to link to").option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{console.log(),await Z(async()=>{await Y();let r=await z();r.project.local.ref()&&K.warning("Project is already linked.");let n=t.projectRef;if(!n){let i=await r.project.remote.list();n=await vn({message:"Select a project:",options:i.map(o=>({value:o.id,hint:`name: ${o.name}, created: ${o.created_at}`}))}),Se(n)&&process.exit(1);}if(!n)throw new Error("No project ref found");console.log("Linking project",n);let s=await r.project.remote.get(n);r.project.local.setRef(s.id),console.log(`Finished linking project ${lh.default.cyan(s.id)}.`);});});});var ph={};de(ph,{unlink:()=>A_});var A_,fh=w(()=>{Le();Ce();xe();A_=e=>e.command("unlink").description("Unlink from a Supalite project").option("--json","Output in JSON format").helpGroup("Local Development:").action(async()=>{console.log(),await Z(async()=>{await Y(),(await z()).project.local.unlink(),console.log("Finished unlinking project.");});});});var dh={};de(dh,{status:()=>C_});var mh,C_,hh=w(()=>{Ce();Le();xe();mh=ee(ie());Je();C_=e=>e.command("status").description(ge("Show information about the linked project")).helpGroup("Local Development:").action(async()=>{console.log(),await Z(async()=>{await Y();let t=await z(),r=await t.project.remote.get();console.log(r),console.log(`Project URL: ${mh.default.cyan(t.project.remote.url(r.id))}`);});});});var yh={};de(yh,{projects:()=>R_});var Dl,R_,k_,P_,wh=w(()=>{wr();Ye();Dl=ee(ie());Le();Ce();Le();R_=e=>{e.command("projects").description("Manage Supalite cloud projects").helpGroup("Management APIs:").addCommand(P_).addCommand(k_);},k_=new Command$1().name("list").description("List projects").helpGroup("Projects:").action(async()=>{await Z(async()=>{let t=await(await z()).project.remote.list();(!Array.isArray(t)||t.length===0)&&(K.info("No projects found"),process.exit(0)),console.log($m(t,{omitKeys:["config","user_id"],renderHeader:r=>String(r).split("_").map(n=>n.toUpperCase()).join(" ")}));});}),P_=new Command$1().name("create").description("Create a project").option("--name <name>","The name of the project").helpGroup("Projects:").action(async e=>{await Z(async()=>{let t=await z(),r=e.name??await zd(),n=await t.project.remote.create({name:r});K.success(`Project ${Dl.default.cyan(n.name)} created: ${Dl.default.cyan(n.id)}`);});});});function N_(){try{return Bn.statSync("/.dockerenv"),!0}catch{return false}}function O_(){try{return Bn.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return false}}function Fl(){return jl===void 0&&(jl=N_()||O_()),jl}var jl,Sh=w(()=>{});function Wt(){return Ml===void 0&&(Ml=L_()||Fl()),Ml}var Ml,L_,Ul=w(()=>{Sh();L_=()=>{try{return Bn.statSync("/run/.containerenv"),!0}catch{return false}};});var Eh,st,ql=w(()=>{Ul();Eh=()=>{if(We.platform!=="linux")return false;if(Cw.release().toLowerCase().includes("microsoft"))return !Wt();try{if(Bn.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return !Wt()}catch{}return Bn.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||Bn.existsSync("/run/WSL")?!Wt():false},st=We.env.__IS_WSL_TEST__?Eh:Eh();});var U_,Hl,De,Wl=w(()=>{U_=promisify(M_.execFile),Hl=()=>`${We.env.SYSTEMROOT||We.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`,De=async(e,t={})=>{let{powerShellPath:r,...n}=t,s=De.encodeCommand(e);return U_(r??Hl(),[...De.argumentsPrefix,s],{encoding:"utf8",...n})};De.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];De.encodeCommand=e=>Buffer$1.from(e,"utf16le").toString("base64");De.escapeArgument=e=>`'${String(e).replaceAll("'","''")}'`;});function $h(e){for(let t of e.split(`
|
|
415
|
+
`)){if(/^\s*#/.test(t))continue;let r=/^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(t);if(r)return r.groups.mountPoint.trim().replaceAll(/^["']|["']$/g,"")}}var vh=w(()=>{});var H_,W_,G_,ki,Th,Ch,Rh,kh,Ph=w(()=>{ql();Wl();vh();ql();H_=promisify(M_.execFile),W_=(()=>{let e="/mnt/",t;return async function(){if(t)return t;let r="/etc/wsl.conf",n=false;try{await pe__default.access(r,constants.F_OK),n=!0;}catch{}if(!n)return e;let s=await pe__default.readFile(r,{encoding:"utf8"}),i=$h(s);return i===void 0?e:(t=i,t=t.endsWith("/")?t:`${t}/`,t)}})(),G_=async()=>`${await W_()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,ki=st?G_:Hl,Ch=async()=>(Th??=(async()=>{try{let e=await ki();return await pe__default.access(e,constants.X_OK),!0}catch{return false}})(),Th),Rh=async()=>{let e=await ki(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{stdout:r}=await De(t,{powerShellPath:e});return r.trim()},kh=async e=>{if(/^[a-z]+:\/\//i.test(e))return e;try{let{stdout:t}=await H_("wslpath",["-aw",e],{encoding:"utf8"});return t.trim()}catch{return e}};});function Gt(e,t,r){let n=s=>Object.defineProperty(e,t,{value:s,enumerable:true,writable:true});return Object.defineProperty(e,t,{configurable:true,enumerable:true,get(){let s=r();return n(s),s},set(s){n(s);}}),e}var Nh=w(()=>{});async function zl(){if(We.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await X_("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),r=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??"com.apple.Safari";return r==="com.apple.safari"?"com.apple.Safari":r}var X_,Oh=w(()=>{X_=promisify(execFile);});async function Ih(e,{humanReadableOutput:t=true,signal:r}={}){if(We.platform!=="darwin")throw new Error("macOS only");let n=t?[]:["-ss"],s={};r&&(s.signal=r);let{stdout:i}=await Z_("osascript",["-e",e,n],s);return i.trim()}var Z_,Lh=w(()=>{Z_=promisify(execFile);});async function Vl(e){return Ih(`tell application "Finder" to set app_path to application file id "${e}" as string
|
|
416
|
+
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}var Dh=w(()=>{Lh();});async function Jl(e=r$){let{stdout:t}=await e("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),r=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!r)throw new Kl(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:n}=r.groups,s=n.lastIndexOf("."),i=n.lastIndexOf("-"),o=s===-1?void 0:n.slice(0,s),a=i===-1?void 0:n.slice(0,i);return Pi[n]??Pi[o]??Pi[a]??{name:n,id:n}}var r$,Pi,Xl,Kl,Yl=w(()=>{r$=promisify(execFile),Pi={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},Xl=new Map(Object.entries(Pi)),Kl=class extends Error{};});async function Zl(){if(We.platform==="darwin"){let e=await zl();return {name:await Vl(e),id:e}}if(We.platform==="linux"){let{stdout:e}=await i$("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return {name:o$(t.replace(/.desktop$/,"").replace("-"," ")),id:t}}if(We.platform==="win32")return Jl();throw new Error("Only macOS, Linux, and Windows are supported")}var i$,o$,jh=w(()=>{Oh();Dh();Yl();Yl();i$=promisify(execFile),o$=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,t=>t.toUpperCase());});var a$,Fh,Mh=w(()=>{a$=!!(We.env.SSH_CONNECTION||We.env.SSH_CLIENT||We.env.SSH_TTY),Fh=a$;});function Hh(e){if(typeof e=="string"||Array.isArray(e))return e;let{[Bh]:t}=e;if(!t)throw new Error(`${Bh} is not supported`);return t}function In({[br]:e},{wsl:t}={}){if(t&&st)return Hh(t);if(!e)throw new Error(`${br} is not supported`);return Hh(e)}var Ni,tc,Uh,br,Bh,qh,Oi,f$,Sr,zh,Vh=w(()=>{Ph();Wl();Nh();jh();Ul();Mh();Ni=Symbol("fallbackAttempt"),tc=import.meta.url?ze__default.dirname(fileURLToPath(import.meta.url)):"",Uh=ze__default.join(tc,"xdg-open"),{platform:br,arch:Bh}=We,qh=async(e,t)=>{if(e.length===0)return;let r=[];for(let n of e)try{return await t(n)}catch(s){r.push(s);}throw new AggregateError(r,"Failed to open in all supported apps")},Oi=async e=>{e={wait:false,background:false,newInstance:false,allowNonzeroExitCode:false,...e};let t=e[Ni]===true;if(delete e[Ni],Array.isArray(e.app))return qh(e.app,c=>Oi({...e,app:c,[Ni]:true}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return qh(r,c=>Oi({...e,app:{name:c,arguments:n},[Ni]:true}));if(r==="browser"||r==="browserPrivate"){let c={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge","com.apple.safari":"safari"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},p;if(st){let f=await Rh();p=Xl.get(f)??{};}else p=await Zl();if(p.id in c){let f=c[p.id.toLowerCase()];if(r==="browserPrivate"){if(f==="safari")throw new Error("Safari doesn't support opening in private mode via command line");n.push(u[f]);}return Oi({...e,app:{name:Sr[f],arguments:n}})}throw new Error(`${p.name} is not supported as a default browser`)}let s,i=[],o={},a=false;if(st&&!Wt()&&!Fh&&!r&&(a=await Ch()),br==="darwin")s="open",e.wait&&i.push("--wait-apps"),e.background&&i.push("--background"),e.newInstance&&i.push("--new"),r&&i.push("-a",r);else if(br==="win32"||a){s=await ki(),i.push(...De.argumentsPrefix),st||(o.windowsVerbatimArguments=true),st&&e.target&&(e.target=await kh(e.target));let c=["$ProgressPreference = 'SilentlyContinue';","Start"];e.wait&&c.push("-Wait"),r?(c.push(De.escapeArgument(r)),e.target&&n.push(e.target)):e.target&&c.push(De.escapeArgument(e.target)),n.length>0&&(n=n.map(u=>De.escapeArgument(u)),c.push("-ArgumentList",n.join(","))),e.target=De.encodeCommand(c.join(" ")),e.wait||(o.stdio="ignore");}else {if(r)s=r;else {let c=!tc||tc==="/",u=false;try{await pe__default.access(Uh,constants.X_OK),u=!0;}catch{}s=We.versions.electron??(br==="android"||c||!u)?"xdg-open":Uh;}n.length>0&&i.push(...n),e.wait||(o.stdio="ignore",o.detached=true);}br==="darwin"&&n.length>0&&i.push("--args",...n),e.target&&i.push(e.target);let l=M_.spawn(s,i,o);return e.wait?new Promise((c,u)=>{l.once("error",u),l.once("close",p=>{if(!e.allowNonzeroExitCode&&p!==0){u(new Error(`Exited with code ${p}`));return}c(l);});}):t?new Promise((c,u)=>{l.once("error",u),l.once("spawn",()=>{l.once("close",p=>{if(l.off("error",u),p!==0){u(new Error(`Exited with code ${p}`));return}l.unref(),c(l);});});}):(l.unref(),new Promise((c,u)=>{l.once("error",u),l.once("spawn",()=>{l.off("error",u),c(l);});}))},f$=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return Oi({...t,target:e})};Sr={browser:"browser",browserPrivate:"browserPrivate"};Gt(Sr,"chrome",()=>In({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium","chromium-browser"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));Gt(Sr,"brave",()=>In({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));Gt(Sr,"firefox",()=>In({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Gt(Sr,"edge",()=>In({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Gt(Sr,"safari",()=>In({darwin:"Safari"}));zh=f$;});var Kh={};de(Kh,{cloud:()=>g$});var je,h$,g$,Xh=w(()=>{je=ee(ie());Vh();Le();Ce();wr();He();mi();zt();xe();Je();h$="Management APIs:",g$=e=>{let t=e.command("cloud").description(ge("Supalite cloud operations")).helpGroup(h$);t.command("deploy").description("Push schema + config + seed to the linked supalite cloud project").option("--config <config>","Path to the config file").option("--force","Force the push",false).action(async r=>{console.log();let n=ji();n.length>0&&(console.error(je.default.red(`Cannot deploy: experimental features enabled (${n.join(", ")}). Cloud does not support them yet.`)),process.exit(1)),await Z(async()=>{await Y(r.config);let s=await z(),i=await s.project.local.createApp(r.config),o=!1;await hn(i,{force:!0});let a=await s.project.remote.get().catch(async()=>{if(await Ri("No project found. Create a new project?"))return o=!0,await s.project.remote.create().then(m=>s.project.local.link(m));throw new Error("No project found")}),l=await s.project.remote.createApp(a.id),c=await fe(i),u=l.connection.createMigrator(c),p=await u.diff();console.log(),dt(p);let f=l.getInfoJson(),g=i.getInfoJson();if(isEqual(f,g))console.log(je.default.dim("Project config is up to date"));else {if(!await s.project.remote.setConfig(a.id,g))throw new Error("Failed to update project config");console.log(je.default.green("Project config updated"));}let d=s.project.remote.url(a.id);if(p.plan.steps.length>0)try{if(await measureTime(async()=>{await u.migratePlan(p.plan,{force:r.force??!1});},m=>{console.log(je.default.green(`Pushed changes to project in ${m.toFixed(2)}ms.`));}),o)try{let m=await gn(l,{recoveryHint:"Fix `supabase/seed.sql` and rerun `lite cloud deploy` against the new project."});m>0&&console.log(je.default.green(`Seeded remote project (${m} statements).`));}catch(m){console.warn(je.default.yellow(String(m.message??m)));}console.log(`Project URL: ${je.default.cyan(d)}
|
|
417
|
+
`),o&&await zh(d);}catch(m){m instanceof fi&&(console.warn(je.default.yellow("Migration would cause data loss. Rerun with --force to proceed.")),process.exit(1)),console.error(je.default.red("Migration error: "+String(m))),process.exit(1);}else console.log(je.default.green("No changes to push."));});}),t.command("diff").description("Diff local project against the linked supalite cloud project").option("--config <config>","Path to the config file").option("--sql","Show the SQL for the diff",false).action(async r=>{console.log(),await Z(async()=>{await Y(r.config);let n=await z(),s=await n.project.local.createApp(r.config);if(await hn(s,{force:!0}),!n.project.local.ref())throw new Error("No project linked");let i=await n.project.remote.get();if(!i)throw new Error("Project not found");let o=await n.project.remote.createApp(i.id),a=await fe(s),l=await o.connection.createMigrator(a).diff();if(l.plan.steps.length>0)if(r.sql){let c=yn(l,{colorize:!0});console.log(je.default.cyan(c));}else dt(l);else console.log(je.default.green("No changes to migrate."));});});};});var Er=ee(ie());zt();var Jh={init:()=>Promise.resolve().then(()=>(xc(),Ec)).then(e=>e.init),start:()=>Promise.resolve().then(()=>(Lp(),Ip)).then(e=>e.start),dev:()=>Promise.resolve().then(()=>(Qf(),Yf)).then(e=>e.dev),repl:()=>Promise.resolve().then(()=>(em(),Zf)).then(e=>e.repl),debug:()=>Promise.resolve().then(()=>(rm(),tm)).then(e=>e.debug),db:()=>Promise.resolve().then(()=>(td(),ed)).then(e=>e.db),migration:()=>Promise.resolve().then(()=>(nd(),rd)).then(e=>e.migration),upgrade:()=>Promise.resolve().then(()=>(Qd(),Yd)).then(e=>e.upgrade)},y$={login:()=>Promise.resolve().then(()=>(eh(),Zd)).then(e=>e.login),logout:()=>Promise.resolve().then(()=>(nh(),rh)).then(e=>e.logout),signup:()=>Promise.resolve().then(()=>(ih(),sh)).then(e=>e.signup),whoami:()=>Promise.resolve().then(()=>(ah(),oh)).then(e=>e.whoami),link:()=>Promise.resolve().then(()=>(uh(),ch)).then(e=>e.link),unlink:()=>Promise.resolve().then(()=>(fh(),ph)).then(e=>e.unlink),status:()=>Promise.resolve().then(()=>(hh(),dh)).then(e=>e.status),projects:()=>Promise.resolve().then(()=>(wh(),yh)).then(e=>e.projects),cloud:()=>Promise.resolve().then(()=>(Xh(),Kh)).then(e=>e.cloud)};function w$(){return ac("cloud")?{...Jh,...y$}:Jh}async function Yh(){let e=w$(),t=process.argv[2];return t&&Object.hasOwn(e,t)?[await e[t]()]:Promise.all(Object.values(e).map(r=>r()))}xe();bi();var rc=new Command;function S$(e){let t=[],r=e;for(;r&&r.name&&r.name()&&r.parent;)t.unshift(r.name()),r=r.parent;return t.join(" ")}async function E$(){let{version:e,name:t}=await Kn();rc.name("lite").description(`${Er.default.yellowBright("\u26A1")} ${t} v${e}`).version(e).option("--no-telemetry","disable anonymous usage telemetry").hook("preAction",async(r,n)=>{let s=r.opts?.()??{},i=typeof n.opts=="function"?n.opts():{};i.json&&i.dryRun||console.log(`${Er.default.green("\u26A1"+Er.default.bold("Supalite"))} ${Er.default.dim(Er.default.green("v"+e))}`),Xm(s.telemetry===false)&&await Jm({command:S$(n),args:i});});for(let r of await Yh())r(rc);await rc.parseAsync(),await wi(false);}E$().then(null).catch(async e=>{console.error(e),await wi(true,e),process.exitCode=1;});
|
|
415
418
|
/*! Bundled license information:
|
|
416
419
|
|
|
417
420
|
smol-toml/dist/error.js:
|