@supabase/lite 0.7.1 → 0.8.1-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import Un,{statSync,readFileSync}from'node:fs';import*as Fe from'node:path';import Fe__default,{join}from'node:path';import {parse}from'dotenv';import*as fe from'node:fs/promises';import fe__default,{stat as stat$1}from'node:fs/promises';import {fileURLToPath}from'node:url';import {createConnection}from'@supabase/lite/sqlite';import Xy from'node:os';import {createClient}from'@supabase/supabase-js';import Wx,{createHash}from'node:crypto';import {DataLossError,SqliteConnection,isEqual,measureTime,splitSqlStatements,ensureVar,App,cloud}from'@supabase/lite';import {createRequire}from'module';import {resolve,posix,isAbsolute,sep,basename,dirname,normalize,relative}from'path';import*as pw from'fs';import {statSync as statSync$1,stat,realpathSync,realpath,readdirSync,readdir}from'fs';import {fileURLToPath as fileURLToPath$1}from'url';import {Deparser,QuoteUtils}from'pgsql-deparser';import QS from'chokidar';import {styleText}from'node:util';import Ge,{stdout,stdin}from'node:process';import*as St from'node:readline';import St__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 Ox from'node:net';import {Command as Command$1}from'@commander-js/extra-typings';import {Command}from'commander';try {
2
+ import Fr,{statSync,readFileSync}from'node:fs';import*as Oe from'node:path';import Oe__default,{join}from'node:path';import {parse}from'dotenv';import*as de from'node:fs/promises';import de__default,{stat as stat$1}from'node:fs/promises';import {fileURLToPath}from'node:url';import {createConnection}from'@supabase/lite/sqlite';import {s}from'jsonv-ts';import dy from'node:os';import {createClient}from'@supabase/supabase-js';import v_,{createHash}from'node:crypto';import {DataLossError,SqliteConnection,isEqual,measureTime,splitSqlStatements,ensureVar,App,cloud}from'@supabase/lite';import {createRequire}from'module';import {resolve,posix,isAbsolute,sep,basename,dirname,normalize,relative}from'path';import*as By from'fs';import {statSync as statSync$1,stat,realpathSync,realpath,readdirSync,readdir}from'fs';import {fileURLToPath as fileURLToPath$1}from'url';import {Deparser,QuoteUtils}from'pgsql-deparser';import xS from'chokidar';import {styleText}from'node:util';import We,{stdout,stdin}from'node:process';import*as St from'node:readline';import St__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 d_ from'node:net';import {Command as Command$1}from'@commander-js/extra-typings';import {Command}from'commander';try {
3
3
  /**
4
4
  * Adding this to avoid warnings from node:sqlite being experimental
5
5
  */
@@ -10,39 +10,42 @@ import Un,{statSync,readFileSync}from'node:fs';import*as Fe from'node:path';impo
10
10
  };
11
11
  } catch {}
12
12
 
13
- var fh=Object.create;var Ni=Object.defineProperty;var mh=Object.getOwnPropertyDescriptor;var dh=Object.getOwnPropertyNames;var hh=Object.getPrototypeOf,gh=Object.prototype.hasOwnProperty;var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var ut=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),de=(e,t)=>{for(var r in t)Ni(e,r,{get:t[r],enumerable:true});},yh=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of dh(t))!gh.call(e,s)&&s!==r&&Ni(e,s,{get:()=>t[s],enumerable:!(n=mh(t,s))||n.enumerable});return e};var te=(e,t,r)=>(r=e!=null?fh(hh(e)):{},yh(Ni(r,"default",{value:e,enumerable:true}),e));var Pi,Li=b(()=>{Pi=process.stdin.isTTY?null:(async()=>{let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")})();});var ae=ut((E_,Ii)=>{var jn=process||{},ql=jn.argv||[],Dn=jn.env||{},wh=!(Dn.NO_COLOR||ql.includes("--no-color"))&&(!!Dn.FORCE_COLOR||ql.includes("--color")||jn.platform==="win32"||(jn.stdout||{}).isTTY&&Dn.TERM!=="dumb"||!!Dn.CI),bh=(e,t,r=e)=>n=>{let s=""+n,i=s.indexOf(t,e.length);return ~i?e+Sh(s,t,r,i)+t:e+s+t},Sh=(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)},Hl=(e=wh)=>{let t=e?bh:()=>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")}};Ii.exports=Hl();Ii.exports.createColors=Hl;});function xh(e){let t=typeof process<"u"&&process.env||void 0;return t?t.NODE_ENV==="test"?true:t[Eh[e]]==="1":false}function Vl(e){return Wl[e]}function Di(){return Gl.filter(e=>Wl[e])}function Fn(){let e=Di();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 Eh,Gl,Wl,zt=b(()=>{Eh={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},Gl=["storage","cloud"],Wl=Object.fromEntries(Gl.map(e=>[e,xh(e)]));});function ke(e,t){Un.existsSync(e)||(Un.mkdirSync(e,{recursive:true}),t?.());}function xt(e,t,r){Un.existsSync(e)||(Un.writeFileSync(e,t),r?.());}async function Mn(){if(!Pi)throw new Error("No input given \u2014 pass it as an argument or pipe it via stdin.");return Pi}var _t=b(()=>{Li();});function $h(e,t){let r=e.slice(0,t).split(/\r\n|\n|\r/g);return [r.length,r.pop().length+1]}function Th(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
- `,o===t&&(s+=" ".repeat(i+r+2),s+=`^
15
- `));}return s}var H,$t=b(()=>{H=class extends Error{line;column;codeblock;constructor(t,r){let[n,s]=$h(r.toml,r.ptr),i=Th(r.toml,n,s);super(`Invalid TOML document: ${t}
13
+ var Oh=Object.create;var Ii=Object.defineProperty;var Ih=Object.getOwnPropertyDescriptor;var Dh=Object.getOwnPropertyNames;var jh=Object.getPrototypeOf,Fh=Object.prototype.hasOwnProperty;var b=(e,t)=>()=>(e&&(t=e(e=0)),t);var ct=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),pe=(e,t)=>{for(var n in t)Ii(e,n,{get:t[n],enumerable:true});},Uh=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Dh(t))!Fh.call(e,s)&&s!==n&&Ii(e,s,{get:()=>t[s],enumerable:!(r=Ih(t,s))||r.enumerable});return e};var V=(e,t,n)=>(n=e!=null?Oh(jh(e)):{},Uh(Ii(n,"default",{value:e,enumerable:true}),e));var Di,ji=b(()=>{Di=process.stdin.isTTY?null:(async()=>{let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")})();});var z=ct((sT,Fi)=>{var Dr=process||{},el=Dr.argv||[],Ir=Dr.env||{},Mh=!(Ir.NO_COLOR||el.includes("--no-color"))&&(!!Ir.FORCE_COLOR||el.includes("--color")||Dr.platform==="win32"||(Dr.stdout||{}).isTTY&&Ir.TERM!=="dumb"||!!Ir.CI),Bh=(e,t,n=e)=>r=>{let s=""+r,i=s.indexOf(t,e.length);return ~i?e+qh(s,t,n,i)+t:e+s+t},qh=(e,t,n,r)=>{let s="",i=0;do s+=e.substring(i,r)+n,i=r+t.length,r=e.indexOf(t,i);while(~r);return s+e.substring(i)},tl=(e=Mh)=>{let t=e?Bh:()=>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")}};Fi.exports=tl();Fi.exports.createColors=tl;});function Gh(e){let t=typeof process<"u"&&process.env||void 0;return t?t.NODE_ENV==="test"?true:t[Hh[e]]==="1":false}function sl(e){return rl[e]}function Ui(){return nl.filter(e=>rl[e])}function jr(){let e=Ui();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 Hh,nl,rl,Kt=b(()=>{Hh={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},nl=["storage","cloud"],rl=Object.fromEntries(nl.map(e=>[e,Gh(e)]));});function $e(e,t){Fr.existsSync(e)||(Fr.mkdirSync(e,{recursive:true}),t?.());}function xt(e,t,n){Fr.existsSync(e)||(Fr.writeFileSync(e,t),n?.());}async function Ur(){if(!Di)throw new Error("No input given \u2014 pass it as an argument or pipe it via stdin.");return Di}var _t=b(()=>{ji();});function Vh(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return [n.length,n.pop().length+1]}function Kh(e,t,n){let r=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=r[o-1];a&&(s+=o.toString().padEnd(i," "),s+=": ",s+=a,s+=`
14
+ `,o===t&&(s+=" ".repeat(i+n+2),s+=`^
15
+ `));}return s}var q,Tt=b(()=>{q=class extends Error{line;column;codeblock;constructor(t,n){let[r,s]=Vh(n.toml,n.ptr),i=Kh(n.toml,r,s);super(`Invalid TOML document: ${t}
16
16
 
17
- ${i}`,r),this.line=n,this.column=s,this.codeblock=i;}};});function vh(e,t){let r=0;for(;e[t-++r]==="\\";);return --r&&r%2}function Bn(e,t=0,r=e.length){let n=e.indexOf(`
18
- `,t);return e[n-1]==="\r"&&n--,n<=r?n:-1}function Kt(e,t){for(let r=t;r<e.length;r++){let n=e[r];if(n===`
19
- `)return r;if(n==="\r"&&e[r+1]===`
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 Oe(e,t,r,n){let s;for(;(s=e[t])===" "||s===" "||!r&&(s===`
17
+ ${i}`,n),this.line=r,this.column=s,this.codeblock=i;}};});function zh(e,t){let n=0;for(;e[t-++n]==="\\";);return --n&&n%2}function Mr(e,t=0,n=e.length){let r=e.indexOf(`
18
+ `,t);return e[r-1]==="\r"&&r--,r<=n?r:-1}function zt(e,t){for(let n=t;n<e.length;n++){let r=e[n];if(r===`
19
+ `)return n;if(r==="\r"&&e[n+1]===`
20
+ `)return n+1;if(r<" "&&r!==" "||r==="\x7F")throw new q("control characters are not allowed in comments",{toml:e,ptr:t})}return e.length}function Ae(e,t,n,r){let s;for(;(s=e[t])===" "||s===" "||!n&&(s===`
21
21
  `||s==="\r"&&e[t+1]===`
22
- `);)t++;return n||s!=="#"?t:Oe(e,Kt(e,t),r)}function Kl(e,t,r,n,s=false){if(!n)return t=Bn(e,t),t<0?e.length:t;for(let i=t;i<e.length;i++){let o=e[i];if(o==="#")i=Bn(e,i);else {if(o===r)return i+1;if(o===n||s&&(o===`
22
+ `);)t++;return r||s!=="#"?t:Ae(e,zt(e,t),n)}function ol(e,t,n,r,s=false){if(!r)return t=Mr(e,t),t<0?e.length:t;for(let i=t;i<e.length;i++){let o=e[i];if(o==="#")i=Mr(e,i);else {if(o===n)return i+1;if(o===r||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 qn(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!=="'"&&vh(e,t));return t>-1&&(t+=n.length,n.length>1&&(e[t]===r&&t++,e[t]===r&&t++)),t}var Er=b(()=>{$t();});var Ch,xr,ji=b(()=>{Ch=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,xr=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(Ch);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 Hn(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
- `&&t++);let i=0,o,a="",l=t;for(;t<r-1;){let c=e[t++];if(c===`
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 p=e.slice(t,t+=c==="x"?2:c==="u"?4:8);if(!Oh.test(p))throw new H("invalid unicode escape",{toml:e,ptr:i});try{a+=String.fromCodePoint(parseInt(p,16));}catch{throw new H("invalid unicode escape",{toml:e,ptr:i})}}else if(s&&(c===`
28
- `||c===" "||c===" "||c==="\r")){if(t=Oe(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=Oe(e,t);}else if(c in Xl)a+=Xl[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 Jl(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=Ah.test(e);if(s||Rh.test(e)){if(kh.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 xr(e);if(!i.isValid())throw new H("invalid value",{toml:t,ptr:r});return i}var Ah,Rh,kh,Oh,Xl,Fi=b(()=>{Er();ji();$t();Ah=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Rh=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,kh=/^[+-]?0[0-9_]/,Oh=/^[0-9a-f]{2,8}$/i,Xl={b:"\b",t:" ",n:`
30
- `,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};});function Nh(e,t,r){let n=e.slice(t,r),s=n.indexOf("#");return s>-1&&(Kt(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==="["?Ql(e,t,n,s):Yl(e,t,n,s);if(r){if(c=Oe(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=qn(e,t);let l=Hn(e,t,o);if(r){if(o=Oe(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=Kl(e,t,",",r);let a=Nh(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=Oe(e,t+a[1]),o+=+(e[o]===",")),[Jl(a[0],e,t,s),o]}var Ui=b(()=>{Fi();Mi();Er();$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=qn(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=Bn(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(Hn(e,t,a));}else {n=e.indexOf(".",t);let a=e.slice(t,n<0||n>i?i:n);if(!Ph.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,Oe(e,i+1,true,true)]}function Yl(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=Kt(e,t);else if(o!==" "&&o!==" "&&o!==`
32
- `&&o!=="\r"){let a,l=s,c=false,[p,u]=Gn(e,t-1);for(let d=0;d<p.length;d++){if(d&&(l=c?l[a]:l[a]={}),a=p[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,h]=_r(e,u,"}",r-1,n);i.add(f),l[a]=f,t=h;}}if(!o)throw new H("unfinished table encountered",{toml:e,ptr:t});return [s,t]}function Ql(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=Kt(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 Ph,Mi=b(()=>{Fi();Ui();Er();$t();Ph=/^[a-zA-Z0-9-_]+[ \t]*$/;});function Zl(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 p=s.length-1;s=s[p],i=i[p].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 Tt(e,{maxDepth:t=1e3,integersAsBigInt:r}={}){let n={},s={},i=n,o=s;for(let a=Oe(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 p=Zl(c[0],n,s,l?2:1);if(!p)throw new H("trying to redefine an already defined table or value",{toml:e,ptr:a});o=p[2],i=p[1],a=c[1];}else {let l=Gn(e,a),c=Zl(l[0],i,o,0);if(!c)throw new H("trying to redefine an already defined table or value",{toml:e,ptr:a});let p=_r(e,l[1],void 0,t,r);c[1][c[0]]=p[0],a=p[1];}if(a=Oe(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=Oe(e,a);}return n}var ec=b(()=>{Mi();Ui();Er();$t();});function $r(e){let t=typeof e;if(t==="object"){if(Array.isArray(e))return "array";if(e instanceof Date)return "date"}return t}function Lh(e){for(let t=0;t<e.length;t++)if($r(e[t])!=="object")return false;return e.length!=0}function Bi(e){return JSON.stringify(e).replace(/\x7f/g,"\\u007f")}function qi(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 Bi(e);if(t==="date"){if(isNaN(e.getTime()))throw new TypeError("cannot serialize invalid date");return e.toISOString()}if(t==="object")return Ih(e,r,n);if(t==="array")return Dh(e,r,n)}function Ih(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+=tc.test(o)?o:Bi(o),s+=" = ",s+=qi(e[o],$r(e[o]),t-1,r);}return s+" }"}function Dh(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+=qi(e[s],$r(e[s]),t-1,r);}return n+" ]"}function jh(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&&`
24
+ `))return i}}throw new q("cannot find end of structure",{toml:e,ptr:t})}function Br(e,t){let n=e[t],r=n===e[t+1]&&e[t+1]===e[t+2]?e.slice(t,t+3):n;t+=r.length-1;do t=e.indexOf(r,++t);while(t>-1&&n!=="'"&&zh(e,t));return t>-1&&(t+=r.length,r.length>1&&(e[t]===n&&t++,e[t]===n&&t++)),t}var En=b(()=>{Tt();});var Xh,xn,Mi=b(()=>{Xh=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i,xn=class e extends Date{#e=false;#t=false;#n=null;constructor(t){let n=true,r=true,s="Z";if(typeof t=="string"){let i=t.match(Xh);i?(i[1]||(n=false,t=`0000-01-01T${t}`),r=!!i[2],r&&t[10]===" "&&(t=t.replace(" ","T")),i[2]&&+i[2]>23?t="":(s=i[3]||null,t=t.toUpperCase(),!s&&r&&(t+="Z"))):t="";}super(t),isNaN(this.getTime())||(this.#e=n,this.#t=r,this.#n=s);}isDateTime(){return this.#e&&this.#t}isLocal(){return !this.#e||!this.#t||!this.#n}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.#n===null)return t.slice(0,-1);if(this.#n==="Z")return t;let n=+this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return n=this.#n[0]==="-"?n:-n,new Date(this.getTime()-n*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n="Z"){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=false,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=false,n.#n=null,n}};});function qr(e,t=0,n=e.length){let r=e[t]==="'",s=e[t++]===e[t]&&e[t]===e[t+1];s&&(n-=2,e[t+=2]==="\r"&&t++,e[t]===`
25
+ `&&t++);let i=0,o,a="",c=t;for(;t<n-1;){let l=e[t++];if(l===`
26
+ `||l==="\r"&&e[t]===`
27
+ `){if(!s)throw new q("newlines are not allowed in strings",{toml:e,ptr:t-1})}else if(l<" "&&l!==" "||l==="\x7F")throw new q("control characters are not allowed in strings",{toml:e,ptr:t-1});if(o){if(o=false,l==="x"||l==="u"||l==="U"){let p=e.slice(t,t+=l==="x"?2:l==="u"?4:8);if(!Zh.test(p))throw new q("invalid unicode escape",{toml:e,ptr:i});try{a+=String.fromCodePoint(parseInt(p,16));}catch{throw new q("invalid unicode escape",{toml:e,ptr:i})}}else if(s&&(l===`
28
+ `||l===" "||l===" "||l==="\r")){if(t=Ae(e,t-1,true),e[t]!==`
29
+ `&&e[t]!=="\r")throw new q("invalid escape: only line-ending whitespace may be escaped",{toml:e,ptr:i});t=Ae(e,t);}else if(l in al)a+=al[l];else throw new q("unrecognized escape sequence",{toml:e,ptr:i});c=t;}else !r&&l==="\\"&&(i=t-1,o=true,a+=e.slice(c,i));}return a+e.slice(c,n-1)}function cl(e,t,n,r){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 r?0n:0;let s=Jh.test(e);if(s||Yh.test(e)){if(Qh.test(e))throw new q("leading zeroes are not allowed",{toml:t,ptr:n});e=e.replace(/_/g,"");let o=+e;if(isNaN(o))throw new q("invalid number",{toml:t,ptr:n});if(s){if((s=!Number.isSafeInteger(o))&&!r)throw new q("integer value cannot be represented losslessly",{toml:t,ptr:n});(s||r===true)&&(o=BigInt(e));}return o}let i=new xn(e);if(!i.isValid())throw new q("invalid value",{toml:t,ptr:n});return i}var Jh,Yh,Qh,Zh,al,Bi=b(()=>{En();Mi();Tt();Jh=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,Yh=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,Qh=/^[+-]?0[0-9_]/,Zh=/^[0-9a-f]{2,8}$/i,al={b:"\b",t:" ",n:`
30
+ `,f:"\f",r:"\r",e:"\x1B",'"':'"',"\\":"\\"};});function eg(e,t,n){let r=e.slice(t,n),s=r.indexOf("#");return s>-1&&(zt(e,s),r=r.slice(0,s)),[r.trimEnd(),s]}function _n(e,t,n,r,s){if(r===0)throw new q("document contains excessively nested structures. aborting.",{toml:e,ptr:t});let i=e[t];if(i==="["||i==="{"){let[c,l]=i==="["?ul(e,t,r,s):ll(e,t,r,s);if(n){if(l=Ae(e,l),e[l]===",")l++;else if(e[l]!==n)throw new q("expected comma or end of structure",{toml:e,ptr:l})}return [c,l]}let o;if(i==='"'||i==="'"){o=Br(e,t);let c=qr(e,t,o);if(n){if(o=Ae(e,o),e[o]&&e[o]!==","&&e[o]!==n&&e[o]!==`
31
+ `&&e[o]!=="\r")throw new q("unexpected character encountered",{toml:e,ptr:o});o+=+(e[o]===",");}return [c,o]}o=ol(e,t,",",n);let a=eg(e,t,o-+(e[o-1]===","));if(!a[0])throw new q("incomplete key-value declaration: no value specified",{toml:e,ptr:t});return n&&a[1]>-1&&(o=Ae(e,t+a[1]),o+=+(e[o]===",")),[cl(a[0],e,t,s),o]}var qi=b(()=>{Bi();Hi();En();Tt();});function Hr(e,t,n="="){let r=t-1,s=[],i=e.indexOf(n,t);if(i<0)throw new q("incomplete key-value: cannot find end of key",{toml:e,ptr:t});do{let o=e[t=++r];if(o!==" "&&o!==" ")if(o==='"'||o==="'"){if(o===e[t+1]&&o===e[t+2])throw new q("multiline strings are not allowed in keys",{toml:e,ptr:t});let a=Br(e,t);if(a<0)throw new q("unfinished string encountered",{toml:e,ptr:t});r=e.indexOf(".",a);let c=e.slice(a,r<0||r>i?i:r),l=Mr(c);if(l>-1)throw new q("newlines are not allowed in keys",{toml:e,ptr:t+r+l});if(c.trimStart())throw new q("found extra tokens after the string part",{toml:e,ptr:a});if(i<a&&(i=e.indexOf(n,a),i<0))throw new q("incomplete key-value: cannot find end of key",{toml:e,ptr:t});s.push(qr(e,t,a));}else {r=e.indexOf(".",t);let a=e.slice(t,r<0||r>i?i:r);if(!tg.test(a))throw new q("only letter, numbers, dashes and underscores are allowed in keys",{toml:e,ptr:t});s.push(a.trimEnd());}}while(r+1&&r<i);return [s,Ae(e,i+1,true,true)]}function ll(e,t,n,r){let s={},i=new Set,o;for(t++;(o=e[t++])!=="}"&&o;){if(o===",")throw new q("expected value, found comma",{toml:e,ptr:t-1});if(o==="#")t=zt(e,t);else if(o!==" "&&o!==" "&&o!==`
32
+ `&&o!=="\r"){let a,c=s,l=false,[p,u]=Hr(e,t-1);for(let d=0;d<p.length;d++){if(d&&(c=l?c[a]:c[a]={}),a=p[d],(l=Object.hasOwn(c,a))&&(typeof c[a]!="object"||i.has(c[a])))throw new q("trying to redefine an already defined value",{toml:e,ptr:t});!l&&a==="__proto__"&&Object.defineProperty(c,a,{enumerable:true,configurable:true,writable:true});}if(l)throw new q("trying to redefine an already defined value",{toml:e,ptr:t});let[f,h]=_n(e,u,"}",n-1,r);i.add(f),c[a]=f,t=h;}}if(!o)throw new q("unfinished table encountered",{toml:e,ptr:t});return [s,t]}function ul(e,t,n,r){let s=[],i;for(t++;(i=e[t++])!=="]"&&i;){if(i===",")throw new q("expected value, found comma",{toml:e,ptr:t-1});if(i==="#")t=zt(e,t);else if(i!==" "&&i!==" "&&i!==`
33
+ `&&i!=="\r"){let o=_n(e,t-1,"]",n-1,r);s.push(o[0]),t=o[1];}}if(!i)throw new q("unfinished array encountered",{toml:e,ptr:t});return [s,t]}var tg,Hi=b(()=>{Bi();qi();En();Tt();tg=/^[a-zA-Z0-9-_]+[ \t]*$/;});function pl(e,t,n,r){let s=t,i=n,o,a=false,c;for(let l=0;l<e.length;l++){if(l){if(s=a?s[o]:s[o]={},i=(c=i[o]).c,r===0&&(c.t===1||c.t===2))return null;if(c.t===2){let p=s.length-1;s=s[p],i=i[p].c;}}if(o=e[l],(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:l<e.length-1&&r===2?3:r,d:false,i:0,c:{}});}if(c=i[o],c.t!==r&&!(r===1&&c.t===3)||(r===2&&(c.d||(c.d=true,s[o]=[]),s[o].push(s={}),c.c[c.i++]=c={t:1,d:false,i:0,c:{}}),c.d))return null;if(c.d=true,r===1)s=a?s[o]:s[o]={};else if(r===0&&a)return null;return [o,s,c.c]}function $t(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={},s={},i=r,o=s;for(let a=Ae(e,0);a<e.length;){if(e[a]==="["){let c=e[++a]==="[",l=Hr(e,a+=+c,"]");if(c){if(e[l[1]-1]!=="]")throw new q("expected end of table declaration",{toml:e,ptr:l[1]-1});l[1]++;}let p=pl(l[0],r,s,c?2:1);if(!p)throw new q("trying to redefine an already defined table or value",{toml:e,ptr:a});o=p[2],i=p[1],a=l[1];}else {let c=Hr(e,a),l=pl(c[0],i,o,0);if(!l)throw new q("trying to redefine an already defined table or value",{toml:e,ptr:a});let p=_n(e,c[1],void 0,t,n);l[1][l[0]]=p[0],a=p[1];}if(a=Ae(e,a,true),e[a]&&e[a]!==`
34
+ `&&e[a]!=="\r")throw new q("each key-value declaration must be followed by an end-of-line",{toml:e,ptr:a});a=Ae(e,a);}return r}var fl=b(()=>{Hi();qi();En();Tt();});function Tn(e){let t=typeof e;if(t==="object"){if(Array.isArray(e))return "array";if(e instanceof Date)return "date"}return t}function ng(e){for(let t=0;t<e.length;t++)if(Tn(e[t])!=="object")return false;return e.length!=0}function Gi(e){return JSON.stringify(e).replace(/\x7f/g,"\\u007f")}function Wi(e,t,n,r){if(n===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":r&&Number.isInteger(e)?e.toFixed(1):e.toString();if(t==="bigint"||t==="boolean")return e.toString();if(t==="string")return Gi(e);if(t==="date"){if(isNaN(e.getTime()))throw new TypeError("cannot serialize invalid date");return e.toISOString()}if(t==="object")return rg(e,n,r);if(t==="array")return sg(e,n,r)}function rg(e,t,n){let r=Object.keys(e);if(r.length===0)return "{}";let s="{ ";for(let i=0;i<r.length;i++){let o=r[i];i&&(s+=", "),s+=ml.test(o)?o:Gi(o),s+=" = ",s+=Wi(e[o],Tn(e[o]),t-1,n);}return s+" }"}function sg(e,t,n){if(e.length===0)return "[]";let r="[ ";for(let s=0;s<e.length;s++){if(s&&(r+=", "),e[s]===null||e[s]===void 0)throw new TypeError("arrays cannot contain null or undefined values");r+=Wi(e[s],Tn(e[s]),t-1,n);}return r+" ]"}function ig(e,t,n,r){if(n===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+=Hi(0,e[i],t,r,n);return s}function Hi(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 p=$r(t[c]);if(p==="symbol"||p==="function")throw new TypeError(`cannot serialize values of type '${p}'`);let u=tc.test(c)?c:Bi(c);if(p==="array"&&Lh(t[c]))o+=(o&&`
37
- `)+jh(t[c],r?`${r}.${u}`:u,n-1,s);else if(p==="object"){let f=r?`${r}.${u}`:u;o+=(o&&`
38
- `)+Hi(f,t[c],f,n-1,s);}else i+=u,i+=" = ",i+=qi(t[c],p,n,s),i+=`
36
+ `,s+=Vi(0,e[i],t,n,r);return s}function Vi(e,t,n,r,s){if(r===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let i="",o="",a=Object.keys(t);for(let c=0;c<a.length;c++){let l=a[c];if(t[l]!==null&&t[l]!==void 0){let p=Tn(t[l]);if(p==="symbol"||p==="function")throw new TypeError(`cannot serialize values of type '${p}'`);let u=ml.test(l)?l:Gi(l);if(p==="array"&&ng(t[l]))o+=(o&&`
37
+ `)+ig(t[l],n?`${n}.${u}`:u,r-1,s);else if(p==="object"){let f=n?`${n}.${u}`:u;o+=(o&&`
38
+ `)+Vi(f,t[l],f,r-1,s);}else i+=u,i+=" = ",i+=Wi(t[l],p,r,s),i+=`
39
39
  `;}}return e&&(i||!o)&&(i=i?`[${e}]
40
40
  ${i}`:`[${e}]`),i&&o?`${i}
41
- ${o}`:i||o}function Gi(e,{maxDepth:t=1e3,numbersAsFloat:r=false}={}){if($r(e)!=="object")throw new TypeError("stringify can only be called with an object");let n=Hi(0,e,"",t,r);return n[n.length-1]!==`
42
- `?n+`
43
- `:n}var tc,rc=b(()=>{tc=/^[a-z0-9-_]+$/i;});var Tr=b(()=>{ec();rc();ji();$t();});var we,Xt=b(()=>{we={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"};});function Wn(e,t={}){let r=Fe__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=Mh(Fe__default.resolve(e),r);for(let a of o)for(let l of i){let c=Fe__default.join(a,l),p;try{p=Un.readFileSync(c,"utf-8");}catch{continue}let u;try{u=parse(p);}catch(f){throw new Error(`Failed to parse ${c}: ${f.message}`)}for(let[f,h]of Object.entries(u))n[f]===void 0&&(n[f]=h);}}function Mh(e,t){let r=[],n=e,s=Fe__default.parse(n).root;for(;r.push(n),!(n===t||n===s);){let i=Fe__default.dirname(n);if(i===n)break;n=i;}return r}var Wi=b(()=>{});function Vn(e,t=process.env){return Vi(e,t)}function Vi(e,t){if(typeof e=="string"){let r=e.match(Bh);return r?t[r[1]]??"":e}if(Array.isArray(e))return e.map(r=>Vi(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]=Vi(i,t);return n}return e}var Bh,zi=b(()=>{Bh=/^env\((\w+)\)$/;});function sc(e){nc=e||process.env.LITE_VERBOSE==="1";}function Qe(...e){nc&&console.error(...e);}var nc,Jt=b(()=>{nc=process.env.LITE_VERBOSE==="1";});async function Hh(e=""){try{let t=Fe__default.resolve(Jn(),Fe__default.join(e,"package.json")),r=await fe__default.readFile(t,"utf-8");if(r)return JSON.parse(r)}catch{}return {}}async function Xn(e=""){let t=await Hh(e);return t?{name:t.name,version:t.version??"unknown"}:{name:"unknown",version:"unknown"}}function Jn(){let e=Fe__default.dirname(fileURLToPath(import.meta.url));return Fe__default.resolve(e,process.env.LOCAL?"../../../":"../../")}function Ki(){return Fe__default.resolve(Jn(),"dist")}function Yn(){return Fe__default.relative(process.cwd(),Ki())}async function Cr(e){let t=Fe__default.relative(process.cwd(),we.config_dir);if(!e)for(let r of Gh){let n=Fe__default.join(t,`config.${r}`);if(await fe__default.access(n).then(()=>true).catch(()=>false)){e=n;break}}return e}async function Q(e){await Cr(e)||(console.error(Kn.default.red("No project found. Run `lite init` first.")),process.exit(1));}async function Wh(e){let t=await Cr(e);if(!t)return {};switch(Qe(Kn.default.dim(`Using config file: ${Kn.default.cyan(`./${t}`)}`)),t.split(".").pop()){case "toml":return Tt(await fe__default.readFile(t,"utf-8"));case "json":return JSON.parse(await fe__default.readFile(t,"utf-8"));case "ts":case "mts":case "js":case "mjs":case "cjs":try{return (await import(Fe__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 Vh(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 Fe__default.resolve(process.cwd(),t)}async function Qn(e){let t=await Cr(e);t&&Wn(Fe__default.dirname(Fe__default.resolve(t)));let r=Vn(await Wh(e));if("connection"in r)return;let n=r?.db?.driver;if(n==="postgres")return;let s=r?.db?.url??(n==="pglite"?we.default_db_dir:we.default_db_url);return Vh(s)}var Kn,Gh,$e=b(()=>{Tr();Xt();Wi();zi();Kn=te(ae());Jt();Gh=["toml","json","ts","mts","js","mjs","cjs"];});async function Zn(e={}){let t=process.cwd();if(e.recreate){console.log(Ji.default.dim("Recreating database..."));try{let n=await Qn();n&&Un.existsSync(n)&&(Un.rmSync(n,{recursive:!0,force:!0}),console.log(Ji.default.dim(` \u279C removed ${Fe__default.relative(t,n)}`)));}catch{}try{Un.rmSync(Fe__default.join(t,"supabase",".temp"),{recursive:!0,force:!0});}catch{}}if(ke(Fe__default.join(t,"supabase")),!await Cr()){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=Fe__default.relative(process.cwd(),Fe__default.join(t,"supabase",".temp","data")));let s=e.configFormat??"toml",i=Fe__default.join(t,"supabase",`config.${s}`);s==="json"?xt(i,JSON.stringify(n)):xt(i,Gi(n));}ke(Fe__default.join(t,"supabase",".temp")),ke(Fe__default.join(t,"supabase","schemas"),()=>{xt(Fe__default.join(t,"supabase","schemas","schema.sql"),e.template?zh:`-- This is a schema file for the database
44
- `);}),xt(Fe__default.join(t,"supabase","seed.sql"),e.template?Kh:`-- This is a seed file for the database
45
- `);}var Ji,zh,Kh,Yi=b(()=>{_t();Ji=te(ae());Tr();$e();zh=`
41
+ ${o}`:i||o}function Ki(e,{maxDepth:t=1e3,numbersAsFloat:n=false}={}){if(Tn(e)!=="object")throw new TypeError("stringify can only be called with an object");let r=Vi(0,e,"",t,n);return r[r.length-1]!==`
42
+ `?r+`
43
+ `:r}var ml,dl=b(()=>{ml=/^[a-z0-9-_]+$/i;});var $n=b(()=>{fl();dl();Mi();Tt();});var fe,At=b(()=>{fe={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"};});function Gr(e,t={}){let n=Oe__default.resolve(t.cwd??process.cwd()),r=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=cg(Oe__default.resolve(e),n);for(let a of o)for(let c of i){let l=Oe__default.join(a,c),p;try{p=Fr.readFileSync(l,"utf-8");}catch{continue}let u;try{u=parse(p);}catch(f){throw new Error(`Failed to parse ${l}: ${f.message}`)}for(let[f,h]of Object.entries(u))r[f]===void 0&&(r[f]=h);}}function cg(e,t){let n=[],r=e,s=Oe__default.parse(r).root;for(;n.push(r),!(r===t||r===s);){let i=Oe__default.dirname(r);if(i===r)break;r=i;}return n}var zi=b(()=>{});function Wr(e,t=process.env){return Xi(e,t)}function Xi(e,t){if(typeof e=="string"){let n=e.match(lg);return n?t[n[1]]??"":e}if(Array.isArray(e))return e.map(n=>Xi(n,t));if(e&&typeof e=="object"){let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)return e;let r={};for(let[s,i]of Object.entries(e))r[s]=Xi(i,t);return r}return e}var lg,Ji=b(()=>{lg=/^env\((\w+)\)$/;});function gl(e){hl=e||process.env.LITE_VERBOSE==="1";}function Me(...e){hl&&console.error(...e);}var hl,Ct=b(()=>{hl=process.env.LITE_VERBOSE==="1";});async function pg(e=""){try{let t=Oe__default.resolve(Xr(),Oe__default.join(e,"package.json")),n=await de__default.readFile(t,"utf-8");if(n)return JSON.parse(n)}catch{}return {}}async function zr(e=""){let t=await pg(e);return t?{name:t.name,version:t.version??"unknown"}:{name:"unknown",version:"unknown"}}function Xr(){let e=Oe__default.dirname(fileURLToPath(import.meta.url));return Oe__default.resolve(e,process.env.LOCAL?"../../../":"../../")}function Yi(){return Oe__default.resolve(Xr(),"dist")}function Jr(){return Oe__default.relative(process.cwd(),Yi())}async function Cn(e){let t=Oe__default.relative(process.cwd(),fe.config_dir);if(!e)for(let n of fg){let r=Oe__default.join(t,`config.${n}`);if(await de__default.access(r).then(()=>true).catch(()=>false)){e=r;break}}return e}async function ee(e){await Cn(e)||(console.error(Kr.default.red("No project found. Run `lite init` first.")),process.exit(1));}async function mg(e){let t=await Cn(e);if(!t)return {};switch(Me(Kr.default.dim(`Using config file: ${Kr.default.cyan(`./${t}`)}`)),t.split(".").pop()){case "toml":return $t(await de__default.readFile(t,"utf-8"));case "json":return JSON.parse(await de__default.readFile(t,"utf-8"));case "ts":case "mts":case "js":case "mjs":case "cjs":try{return (await import(Oe__default.join(process.cwd(),t))).default}catch(r){throw console.error("Failed to import config file",r),r}default:throw new Error(`Unsupported config file type: ${t}`)}}function dg(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 Oe__default.resolve(process.cwd(),t)}async function Yr(e){let t=await Cn(e);t&&Gr(Oe__default.dirname(Oe__default.resolve(t)));let n=Wr(await mg(e));if("connection"in n)return;let r=n?.db?.driver;if(r==="postgres")return;let s=n?.db?.url??(r==="pglite"?fe.default_db_dir:fe.default_db_url);return dg(s)}var Kr,fg,Ee=b(()=>{$n();At();zi();Ji();Kr=V(z());Ct();fg=["toml","json","ts","mts","js","mjs","cjs"];});function Qi(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function yl(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return new Uint8Array(n)}async function Xt(e,t=hg,n){let r=crypto.getRandomValues(new Uint8Array(17)),s=`sb_${e}_`,i=s+Qi(r).slice(0,22),o=Qi(await yl(`${t}|${i}`)).slice(0,8),a=`${i}_${o}`,c=await gg(a),l=a.slice(0,s.length+5);return {key:a,hash:c,prefix:l,type:e}}async function gg(e){return Qi(await yl(e))}var hg,Zi=b(()=>{hg="supabase-self-hosted";});function Qr(e,t){let n="";try{n=Fr.readFileSync(e,"utf-8");}catch{n="";}let r=n.length>0?n.split(`
44
+ `):[];r.length>0&&r[r.length-1]===""&&r.pop();let s=r.filter(i=>{let o=i.match(/^([A-Za-z_][A-Za-z0-9_]*)=/);return !(o&&o[1]in t)});for(let[i,o]of Object.entries(t))s.push(`${i}=${o}`);Fr.writeFileSync(e,s.join(`
45
+ `)+`
46
+ `);}function bl(e,t){let n;try{n=Fr.readFileSync(e,"utf-8");}catch{return [...t]}return t.filter(r=>!n.match(new RegExp(`^${r}=(.+)$`,"m"))?.[1]?.replace(/^"(.*)"$|^'(.*)'$/,(o,a,c)=>a??c??"")?.trim())}var to=b(()=>{});async function ts(e={}){let t=process.cwd();if(e.recreate){console.log(ro.default.dim("Recreating database..."));try{let o=await Yr();o&&Fr.existsSync(o)&&(Fr.rmSync(o,{recursive:!0,force:!0}),console.log(ro.default.dim(` \u279C removed ${Oe__default.relative(t,o)}`)));}catch{}try{Fr.rmSync(Oe__default.join(t,"supabase",".temp"),{recursive:!0,force:!0});}catch{}}if($e(Oe__default.join(t,"supabase")),!await Cn()){let o={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,publishable_key:`env(${Zr})`,secret_key:`env(${es})`,email:{enable_confirmations:false}}};e.driver==="pglite"&&(o.db.driver="pglite",o.db.url=Oe__default.relative(process.cwd(),Oe__default.join(t,"supabase",".temp","data")));let a=e.configFormat??"toml",c=Oe__default.join(t,"supabase",`config.${a}`);a==="json"?xt(c,JSON.stringify(o)):xt(c,Ki(o));}$e(Oe__default.join(t,"supabase",".temp")),$e(Oe__default.join(t,"supabase","schemas"),()=>{xt(Oe__default.join(t,"supabase","schemas","schema.sql"),e.template?yg:`-- This is a schema file for the database
47
+ `);}),xt(Oe__default.join(t,"supabase","seed.sql"),e.template?bg:`-- This is a seed file for the database
48
+ `);let r=Oe__default.join(t,".env"),s=bl(r,[Zr,es]),i;if(s.length>0){let o={};if(i={},s.includes(Zr)){let a=await Xt("publishable");o[Zr]=a.key,i.publishable=a.key;}if(s.includes(es)){let a=await Xt("secret");o[es]=a.key,i.secret=a.key;}Qr(r,o);}return {generatedKeys:i}}var ro,Zr,es,yg,bg,so=b(()=>{_t();ro=V(z());$n();Ee();Zi();to();Zr="SUPABASE_PUBLISHABLE_KEY",es="SUPABASE_SECRET_KEY";yg=`
46
49
  create table todos (
47
50
  id serial primary key,
48
51
  title text not null,
@@ -55,20 +58,21 @@ create table todos (
55
58
  create table test (
56
59
  id serial primary key,
57
60
  name text not null
58
- )`,Kh="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 oc={};de(oc,{init:()=>Xh});var Qi,Xh,ac=b(()=>{Qi=te(ae());Yi();Xh=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 Zn({configFormat:t.format,recreate:t.recreate,driver:t.pglite?"pglite":void 0}),console.log(),console.log(Qi.default.green(" \u279C"),"Project initialized",Qi.default.cyan("./"+Fe__default.relative(process.cwd(),Fe__default.join(process.cwd(),"supabase"))));});};});var lc=b(()=>{});var cc=b(()=>{});function Zi(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:Zi(e[s],i,r)}catch{if(typeof r<"u")return r;throw new Error(`Invalid path: ${n.join(".")}`)}}var uc=b(()=>{});var pc=b(()=>{});function es(){try{return !Ar()&&global?.process?.release?.name==="node"}catch{return false}}function Ar(){try{return typeof Bun<"u"}catch{return false}}async function ts(e,t){let r=performance.now();await e();let n=performance.now();t(n-r);}var fc=b(()=>{});function dc(e,t={}){return e.split(`
59
- `).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>!r.startsWith(t.comments??"--")).join(`
60
- `)}function vt(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=u=>{mc(u).length>0&&t.push(u.trim());},p=()=>{i=false,o=false,a=0;};for(;n<s;){let u=e[n],f=e[n+1];if(u==="-"&&f==="-"){for(;n<s&&e[n]!==`
61
- `;)r+=e[n],n++;continue}if(u==="/"&&f==="*"){for(r+="/*",n+=2;n<s&&!(e[n]==="*"&&e[n+1]==="/");)r+=e[n],n++;n<s&&(r+="*/",n+=2);continue}if(u==="'"){for(r+=u,n++;n<s;){if(e[n]==="'"&&e[n+1]==="'"){r+="''",n+=2;continue}if(r+=e[n],e[n]==="'"){n++;break}n++;}continue}if(u==='"'){for(r+=u,n++;n<s;){if(e[n]==='"'&&e[n+1]==='"'){r+='""',n+=2;continue}if(r+=e[n],e[n]==='"'){n++;break}n++;}continue}if(u==="$"){let h=e.indexOf("$",n+1);if(h!==-1){let d=e.slice(n,h+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(d)){r+=d,n=h+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(u)){let h=n;for(;h<s&&/[A-Za-z0-9_]/.test(e[h]);)h++;let d=e.slice(n,h),m=d.toLowerCase();if(m==="trigger"&&l.test(mc(r))?i=true:i&&m==="begin"?(o=true,a++):i&&o&&m==="case"?a++:i&&o&&m==="end"&&a>0&&a--,r+=d,n=h,i&&o&&a===0){let y=n;for(;y<s&&/\s/.test(e[y]);)y++;e[y]===";"&&(n=y+1),c(r),r="",p();}continue}if(u===";"){if(i&&o&&a>0){r+=u,n++;continue}c(r),r="",p(),n++;continue}r+=u,n++;}return c(r),t}function mc(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 eo(e){return (e??"").trim().toLowerCase()}function to(e){return (e??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase()}function ro(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 Ct=b(()=>{});function Jh(e,t,r=void 0){let n=typeof t=="string"?wc(t):io(t);return ss(e,n,r)}function ss(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:ss(e[s],i,r)}catch{if(typeof r<"u")return r;throw new Error(`Invalid path: ${n.join(".")}`)}}function Zh(e){return e===null}function he(e){return !Array.isArray(e)&&typeof e=="object"&&e!==null}function eg(e){return Object.prototype.toString.call(e)==="[object Object]"}function Xe(e){return typeof e=="string"}function Ze(e){return typeof e=="number"}function tg(e){return typeof e=="number"&&Number.isInteger(e)}function lo(e){return typeof e=="boolean"}function pt(e){return Array.isArray(e)}function rg(e){return typeof e!="boolean"}function ng(e){return e!==void 0&&rg(e)&&"type"in e}function Ce(e){return e!==void 0&&he(e)&&ve in e}function sg(e){return Ce(e)&&typeof e.toJSON()=="boolean"}function ig(e,t,r){if(!e)throw new Qh(t,r)}function bc(e){return Xe(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 og(e,t){return t.reduce((r,n)=>(n in e&&(r[n]=e[n]),r),{})}function Sc(e){try{return structuredClone(e)}catch{return e}}function ag(e,t,r={}){let n=t;try{n=structuredClone(t);}catch{n=JSON.parse(JSON.stringify(t));}let s={resolver:r.resolver||new co(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 is(e,t,r={}){return e.map(n=>n.validate(t,ns(r)).valid?n:void 0).filter(Boolean)}function Mg(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 co(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=no[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 no&&e[o]!==void 0){if(s===void 0)continue;let a=no[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 os(e,t,r){return new class extends et{type=e}(t,r)}function oo(e){return new Bg(e)}function gc(e,t){return Array.isArray(e)?e.map(t):e!==void 0?[t(e)]:[]}function yc(e,t,r=n=>n){return Object.fromEntries(Object.entries(e).map(([n,s])=>[n,r(t(s,n),n)]))}function Yt(e){if(lo(e))return oo(e);let t=structuredClone(e);if(!he(t))throw new Yh("non-object schemas cannot be converted to a schema",t);"properties"in t&&t.properties&&(t.properties=yc(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]=yc(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"&&(pt(t[i])?t[i]=gc(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]=gc(o,Yt);}if(ng(t))switch(t.type){case "string":return xc(t);case "number":return $c(t);case "integer":return Tc(t);case "boolean":return Cc(t);case "object":{let{properties:i,...o}=t;return as(i,o)}case "array":{let{items:i,...o}=t;return vc(i,o)}}return Ec(t)}function ey(){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(Qg.map(e=>[e,t=>Math.min(...t)])),...Object.fromEntries(Zg.map(e=>[e,t=>Math.max(...t)]))}}function ty(e){let t={...ey(),...e.resolvers};function r(n,s){if(Array.isArray(n)&&Array.isArray(s))return [...new Set([...n,...s])];if(ao(n)&&ao(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):so(a);}else i[o]=so(a);return i}return so(s)}return r}function ny(e,t={}){let r=t.deep!==false,n=ty(t);function s(i){if(Array.isArray(i))return i.map(s);if(!ao(i))return i;if(Array.isArray(i.allOf)){let a=i.allOf.map(s);if(a.some(h=>h===false))return false;let l=a.filter(h=>h!==true);if(!l.length)return true;let c=l.reduce((h,d)=>n(h,d),{}),p=ry(c);if(p!==null)return p;let u={...i};delete u.allOf;let f=n(c,r?s(u):u);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 io,wc,Z,I,Qt,ns,At,Yh,Qh,ve,co,lg,cg,ug,pg,fg,mg,dg,hg,gg,yg,wg,bg,Sg,Eg,xg,_g,$g,Tg,vg,Cg,Ag,Rg,kg,Og,Ng,Pg,Lg,Ig,Dg,jg,Fg,hc,Ug,no,et,kr,Bg,Ec,qg,Hg,as,Gg,Wg,Vg,zg,Kg,xc,_c,$c,Tc,Xg,vc,Cc,rs,Ac,Jg,Yg,ao,so,Qg,Zg,ry,sy,Rc,iy,oy,ay,kc,Oc=b(()=>{io=(e=[],t="")=>"/"+[t,...e.map(r=>String(r).replace(/\./g,"/"))].filter(Boolean).join("/"),wc=e=>e.split("/").slice(1);Z=(e={},t,r,n)=>({valid:false,errors:[...e.errors??[],{keywordLocation:io([...e.keywordPath??[],t]),instanceLocation:io(e.instancePath),error:typeof r=="string"?r:`Invalid value for ${t}`,data:n}]}),I=()=>({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}},ns=(e={})=>({...e,errors:[]}),At=class extends Error{constructor(e){super(`Expected ${e}`);}},Yh=class extends Error{constructor(e,t){super(`${e??"Invalid raw schema"}: ${JSON.stringify(t)}`),this.schema=t;}},Qh=class extends Error{constructor(e,t){super(`${e}, got: 'type "${typeof t}": ${JSON.stringify(t)}'`),this.value=t;}},ve=Symbol.for("jsonv-ts:schema");co=class{constructor(e){this.root=e,this.cache=new Map;}cache;hasRef(e,t){return t!==void 0&&"$ref"in e&&Xe(e.$ref)}resolve(e){let t=this.cache.get(e);if(!t){if(t=Jh(this.root,e),!Ce(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}};lg=({type:e},t,r={})=>{if(e===void 0||t===void 0)return I();let n,s={string:Xe,number:Ze,integer:tg,object:he,array:pt,boolean:lo,null:Zh};if(Array.isArray(e)){for(let i of e){if(!(i in s))throw new At(`Unknown type: ${i}`);if(s[i](t))return I()}n=`Expected one of: ${e.join(", ")}`;}else {if(!(e in s))throw new At(`Unknown type: ${e}`);s[e](t)||(n=`Expected ${e}`);}return n?Z(r,"type",n,t):I()},cg=({const:e},t,r={})=>Rr(e,t)?I():Z(r,"const",`Expected const: ${e}`,t),ug=({enum:e=[]},t,r={})=>e.some(n=>Rr(n,t))?I():Z(r,"enum",`Expected enum: ${JSON.stringify(e)}`,t);pg=({anyOf:e=[]},t,r={})=>is(e,t,r).length>0?I():Z(r,"anyOf","Expected at least one to match",t),fg=({oneOf:e=[]},t,r={})=>is(e,t).length===1?I():Z(r,"oneOf","Expected exactly one to match",t),mg=({allOf:e=[]},t,r={})=>is(e,t,r).length===e.length?I():Z(r,"allOf","Expected all to match",t),dg=({not:e},t,r={})=>t===void 0?I():Ce(e)&&e.validate(t,r).valid?Z(r,"not","Expected not to match",t):I(),hg=({if:e,then:t,else:r},n,s={})=>{if(e&&(t||r)){if(e.validate(n,ns(s)).valid)return t?t.validate(n,ns(s)):I();if(r)return r.validate(n,ns(s))}return I()},gg=({pattern:e=""},t,r={})=>{if(!Xe(t))return I();if(e instanceof RegExp){if(e.test(t))return I()}else if(new RegExp(e,"u").test(t))return I();return Z(r,"pattern",`Expected string matching pattern ${e}`,t)},yg=({minLength:e=0},t,r={})=>Xe(t)?[...bc(t)].length>=e?I():Z(r,"minLength",`Expected string with minimum length of ${e}`,t):I(),wg=({maxLength:e=0},t,r={})=>Xe(t)?[...bc(t)].length<=e?I():Z(r,"maxLength",`Expected string with maximum length of ${e}`,t):I(),bg=({multipleOf:e=0},t,r={})=>{if(!Ze(t))return I();if(!(Number.isFinite(t)&&Number.isFinite(e))||e<=0)throw new At("number");let n=t/e,s=Number.EPSILON*Math.max(1,Math.abs(n));return Math.abs(n-Math.round(n))<=s?I():Z(r,"multipleOf",`Expected number being a multiple of ${e}`,t)},Sg=({maximum:e=0},t,r={})=>!Ze(t)||t<=e?I():Z(r,"maximum",`Expected number less than or equal to ${e}`,t),Eg=({exclusiveMaximum:e=0},t,r={})=>!Ze(t)||t<e?I():Z(r,"exclusiveMaximum",`Expected number less than ${e}`,t),xg=({minimum:e=0},t,r={})=>!Ze(t)||t>=e?I():Z(r,"minimum",`Expected number greater than or equal to ${e}`,t),_g=({exclusiveMinimum:e=0},t,r={})=>!Ze(t)||t>e?I():Z(r,"exclusiveMinimum",`Expected number greater than ${e}`,t),$g=({properties:e={}},t,r={})=>{if(!he(t))return I();for(let[n,s]of Object.entries(t)){let i=e[n];if(!Ce(i))continue;let o=i.validate(s,Qt(r,["properties",n],n));if(!o.valid)return o}return I()},Tg=({properties:e={},additionalProperties:t,patternProperties:r},n,s={})=>{if(!he(n))return I();if(!Ce(t))throw new At("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(sg(t)){if(t.toJSON()===true)return I();let l=a.reduce((c,p)=>(c[p]=n[p],c),{});return Z(s,"additionalProperties","Additional properties are not allowed",l)}else if(Ce(t))for(let l of a){let c=t.validate(n[l],Qt(s,["additionalProperties"],l));if(!c.valid)return c}}return I()},vg=({dependentRequired:e},t,r={})=>{if(!he(t))return I();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 Z(r,"dependentRequired",`Expected dependent required property ${o}`,t)}}return I()},Cg=({required:e=[]},t,r={})=>{if(!he(t))return I();let n=Object.keys(t).filter(s=>typeof t[s]!="function");return e.every(s=>n.includes(s))?I():Z(r,"required",`Expected object with required properties ${e.join(", ")}`,t)},Ag=({dependentSchemas:e},t,r={})=>{if(!he(t))return I();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 I()},Rg=({minProperties:e=0},t,r={})=>he(t)?Object.keys(t).length>=e?I():Z(r,"minProperties",`Expected object with at least ${e} properties`,t):I(),kg=({maxProperties:e=0},t,r={})=>!he(t)||Object.keys(t).length<=e?I():Z(r,"maxProperties",`Expected object with at most ${e} properties`,t),Og=({patternProperties:e={}},t,r={})=>{if(!he(t))return I();if(!he(e))throw new At("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 I()},Ng=({propertyNames:e},t,r={})=>{if(!he(t)||e===void 0)return I();if(!Ce(e))throw new At("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 I()},Pg=({items:e,prefixItems:t=[]},r,n={})=>{if(!pt(r)||e===void 0)return I();if(!Ce(e))throw new At("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 I()},Lg=({minItems:e=0},t,r={})=>!pt(t)||t.length>=e?I():Z(r,"minItems",`Expected array with at least ${e} items`,t),Ig=({maxItems:e=0},t,r={})=>!pt(t)||t.length<=e?I():Z(r,"maxItems",`Expected array with at most ${e} items`,t),Dg=({uniqueItems:e=false},t,r={})=>{if(!pt(t)||!e)return I();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 Z(r,"uniqueItems",`Duplicated items at index ${n} and ${i}`,t)}}return I()},jg=({contains:e,minContains:t,maxContains:r},n,s={})=>{if(!Ce(e))throw new Error("contains must be a managed schema");if(!pt(n))return I();let i=n.filter(o=>e.validate(o).valid).length;return i<(t??1)?Z(s,t?"minContains":"contains",`Expected array to contain at least ${t??1}, but found ${i}`,n):r!==void 0&&i>r?Z(s,"maxContains",`Expected array to contain at most ${r}, but found ${i}`,n):I()},Fg=({prefixItems:e=[]},t,r={})=>{if(!pt(t))return I();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 I()},hc={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 p=e.charCodeAt(c);if(c===1&&o===58&&p!==58)return false;if(p>=48&&p<=57){if(++n>4)return false}else if(p===46){if(t>6||r>=3||n===0||i)return false;r++,n=0;}else if(p===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(p>=97&&p<=102||p>=65&&p<=70){if(r>0||++n>4)return false;i=true;}else return false;o=p;}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},Ug=({format:e},t,r={})=>!Xe(t)||!e?I():hc[e]?hc[e](t)?I():Z(r,"format",`Expected format: ${e}`,t):I(),no={type:lg,const:cg,enum:ug,allOf:mg,anyOf:pg,oneOf:fg,not:dg,minLength:yg,maxLength:wg,pattern:gg,format:Ug,minimum:xg,exclusiveMinimum:_g,maximum:Sg,exclusiveMaximum:Eg,multipleOf:bg,required:Cg,dependentRequired:vg,dependentSchemas:Ag,minProperties:Rg,maxProperties:kg,propertyNames:Ng,properties:$g,patternProperties:Og,additionalProperties:Tg,minItems:Lg,maxItems:Ig,uniqueItems:Dg,contains:jg,prefixItems:Fg,items:Pg,if:hg};et=class{"~standard";[ve];_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[ve]={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:wc(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[ve].raw?.template){let i=this[ve].raw.template(n,t);i!==void 0&&(n=i);}let s=this[ve].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[ve].raw?.validate;if(n!==void 0){let s=n(e,r);if(!s.valid)return s}return Mg(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[ve].raw?.coerce;if(n!==void 0)return n(e,r);let s=this[ve].overrides?.coerce?.(e,r)??e;return ag(this,s,r)}optional(){return this[ve].optional=true,this}isOptional(){return this[ve].optional}getResolver(){return this._resolver||(this._resolver=new co(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?Sc(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=ss(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}};Bg=class extends et{constructor(e){super(),this.bool=e;}toJSON(){return this.bool}validate(e,t){return this.bool?I():Z(t,"","Always fails",e)}};Ec=e=>os(e?.type,e),qg=(e,t)=>os(void 0,{...t,const:e}),Hg=class extends et{type="object";properties;required;constructor(e,t){let r=[];for(let[s,i]of Object.entries(e||{}))ig(Ce(i),"properties must be managed schemas",i),i[ve].optional||r.push(s);let n=t?.additionalProperties===false?oo(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 p=ss(o,l);if(c.isOptional()&&i?.withOptional!==true&&p===void 0&&s===void 0)continue;let u=c.template(p,i);u!==void 0&&(a[l]=u);}if(!(Object.keys(a).length===0&&!i?.withExtendedOptional))return a},coerce:(s,i)=>{let o=Object.keys(this.properties),a=Sc(s),l=o.length>0&&Object.values(this.properties).every(p=>!p[ve].optional);if(eg(a)&&(i?.dropUnknown===true||l)&&(a=og(a,o)),typeof a=="string"&&a.match(/^\{/)&&(a=JSON.parse(a)),typeof a!="object"||a===null)return;if(this.properties)for(let[p,u]of Object.entries(this.properties)){let f=a[p];f!==void 0&&(a[p]=u.coerce(f,i));}let c=this.additionalProperties;if(i?.dropUnknown!==true&&(!c||c.validate(null).valid)){let p=he(s)?s:{},u=Object.keys(p).filter(f=>!o.includes(f));for(let f of u)a[f]=c?c.coerce(p[f],i):p[f];}return a}}),this.properties=e,this.required=r;}strict(){return this.additionalProperties=oo(false),this[ve].raw.additionalProperties=false,this}partial(){for(let[,e]of Object.entries(this.properties))e[ve].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}},as=(e,t)=>new Hg(e,t),Gg=(e,t)=>as(e,t).strict(),Wg=(e,t)=>as(e,t).partial(),Vg=class extends et{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}},zg=(e,t)=>new Vg(e,t),Kg=class extends et{type="string";constructor(e){super(e,{template:(t,r)=>r?.withExtendedOptional&&(t===void 0||!Xe(t))?"":t,coerce:t=>Ze(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}))}},xc=e=>new Kg(e),_c=(e,t,r)=>os(e,r,{template:(n,s)=>s?.withExtendedOptional&&(n===void 0||!Ze(n))?r?.minimum??0:n,coerce:n=>{if(Xe(n)){let s=t.parseFn(n);if(!Number.isNaN(s))return s}return n}}),$c=e=>_c("number",{parseFn:Number},e),Tc=e=>_c("integer",{parseFn:Number.parseInt},e),Xg=class extends et{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(Ce(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}},vc=(e,t)=>new Xg(e,t),Cc=e=>os("boolean",e,{template:(t,r)=>r?.withExtendedOptional&&(t===void 0||!lo(t))?false:t,coerce:t=>{if(Xe(t)&&["true","false","1","0"].includes(t))return t==="true"||t==="1";if(Ze(t)){if(t===1)return true;if(t===0)return false}return t}}),rs=Symbol.for("unionType"),Ac=class extends et{[rs];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=is(e,n,{ignoreUnsupported:true,resolver:s?.resolver,coerce:true});return o.length>0?o[0].coerce(n,s):n}}),this[rs]=t;}get schemas(){return this[this[rs]]}children(e){let t=[];for(let[r,n]of this.schemas.entries()){let s=new kr(n,e);s.appendKeywordPath([this[rs],r]),t.push(s);}return t}},Jg=(e,t)=>new Ac(e,"anyOf",t),Yg=(e,t)=>new Ac(e,"oneOf",t);ao=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),so=e=>typeof globalThis.structuredClone=="function"?globalThis.structuredClone(e):JSON.parse(JSON.stringify(e)),Qg=["maximum","exclusiveMaximum","maxLength","maxItems","maxProperties"],Zg=["minimum","exclusiveMinimum","minLength","minItems","minProperties"];ry=e=>e===true||e===false?e:null;sy=(e,t)=>{let r=JSON.parse(JSON.stringify({...t,allOf:e}));return Yt(ny(r))},Rc=class extends et{$ref;constructor(e,t){if(!t&&!Ce(e))throw new Error("Ref not set");if(Ce(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(!Ce(i))throw new Error(`Ref not found: ${this.$ref}`);return i.coerce(n,s)}}),this.$ref=r;}},iy=(e,t)=>new Rc(e,t),oy=e=>new Rc(void 0,e),ay=e=>e(new et({$ref:"#",coerce:(t,r)=>{let n=r?.resolver?.resolve("#");if(!Ce(n))throw new Error("Ref not found: #");return n.coerce(t,r)}})),kc={boolean:Cc,any:Ec,literal:qg,object:as,strictObject:Gg,partialObject:Wg,record:zg,string:xc,number:$c,integer:Tc,array:vc,anyOf:Jg,oneOf:Yg,allOf:sy,ref:iy,refId:oy,recursive:ay};});function Nc(e,t){if(typeof e!="string"){throw new Error("Email must be a string");}if(!kc.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 Pc(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 M(e,t='"'){return `${t}${e}${t}`}function Lc(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 Or=b(()=>{Oc();});function uo(e){return typeof e=="number"?e:Number.parseInt(String(e),10)}var Ic=b(()=>{});var Dc=b(()=>{});var ft=b(()=>{lc();cc();uc();pc();fc();Ct();Or();Ic();Dc();});var po,jc=b(()=>{po=(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,p;if(e[a]?(p=e[a][0][0],n.req.routeIndex=a):p=a===e.length&&s||void 0,p)try{l=await p(n,()=>o(a+1));}catch(u){if(u instanceof Error&&t)n.error=u,l=await t(u,n),c=true;else throw u}else n.finalized===false&&r&&(l=await r(n));return l&&(n.finalized===false||c)&&(n.res=l),n}};});var Fc=b(()=>{});var Uc,Mc=b(()=>{Uc=Symbol();});async function ly(e,t){let r=await e.formData();return r?cy(r,t):{}}function cy(e,t){let r=Object.create(null);return e.forEach((n,s)=>{t.all||s.endsWith("[]")?uy(r,s,n):r[s]=n;}),t.dot&&Object.entries(r).forEach(([n,s])=>{n.includes(".")&&(py(r,n,s),delete r[n]);}),r}var Bc,uy,py,qc=b(()=>{fo();Bc=async(e,t=Object.create(null))=>{let{all:r=false,dot:n=false}=t,i=(e instanceof ls?e.raw.headers:e.headers).get("Content-Type");return i?.startsWith("multipart/form-data")||i?.startsWith("application/x-www-form-urlencoded")?ly(e,{all:r,dot:n}):{}};uy=(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;},py=(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 ho,Hc,fy,my,cs,Gc,us,dy,go,Wc,Rt,ps,mo,Vc,zc,Kc,yo,Zt=b(()=>{ho=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},Hc=e=>{let{groups:t,path:r}=fy(e),n=ho(r);return my(n,t)},fy=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let s=`@${n}`;return t.push([s,r]),s}),{groups:t,path:e}},my=(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},cs={},Gc=(e,t)=>{if(e==="*")return "*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return cs[n]||(r[2]?cs[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:cs[n]=[e,r[1],true]),cs[n]}return null},us=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},dy=e=>us(e,decodeURI),go=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 dy(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(s===63||s===35)break}return t.slice(r,n)},Wc=e=>{let t=go(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},Rt=(e,t,...r)=>(r.length&&(t=Rt(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),ps=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)},mo=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?us(e,yo):e):e,Vc=(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 mo(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=mo(l)),i=o,l==="")continue;let c;a===-1?c="":(c=e.slice(a+1,o===-1?void 0:o),n&&(c=mo(c))),r?(s[l]&&Array.isArray(s[l])||(s[l]=[]),s[l].push(c)):s[l]??=c;}return t?s[t]:s},zc=Vc,Kc=(e,t)=>Vc(e,t,true),yo=decodeURIComponent;});var Xc,ls,fo=b(()=>{Fc();Mc();qc();Zt();Xc=e=>us(e,yo),ls=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)?Xc(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)?Xc(n):n);}return e}#s(e){return this.#t[1]?this.#t[1][e]:e}query(e){return zc(this.url,e)}queries(e){return Kc(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 Bc(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[Uc](){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 Jc,Yc,wo,bo=b(()=>{Jc={Stringify:1,BeforeStream:2,Stream:3},Yc=(e,t)=>{let r=new String(e);return r.isEscaped=true,r.callbacks=t,r},wo=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=>wo(l,t,false,n,s))).then(()=>s[0]));return r?Yc(await o,i):o};});var hy,So,Nr,Qc,Zc=b(()=>{fo();bo();hy="text/plain; charset=UTF-8",So=(e,t)=>({"Content-Type":e,...t}),Nr=(e,t)=>new Response(e,t),Qc=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 ls(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,So(hy,r));json=(e,t,r)=>this.#o(JSON.stringify(e),t,So("application/json",r));html=(e,t,r)=>{let n=s=>this.#o(s,t,So("text/html; charset=UTF-8",r));return typeof e=="object"?wo(e,Jc.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 re,eu,tu,fs,ms,mt=b(()=>{re="ALL",eu="all",tu=["get","post","put","delete","options","patch"],fs="Can not add a route since the matcher is already built.",ms=class extends Error{};});var Pr,Eo=b(()=>{Pr="__COMPOSED_HANDLER";});var gy,ru,nu,iu=b(()=>{jc();Zc();mt();Eo();Zt();gy=e=>e.text("404 Not Found",404),ru=(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)},nu=class su{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...tu,eu].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(p=>{this.#i(c.toUpperCase(),this.#e,p);});}return this},this.use=(i,...o)=>(typeof i=="string"?this.#e=i:(this.#e="*",o.unshift(i)),o.forEach(a=>{this.#i(re,this.#e,a);}),this);let{strict:n,...s}=t;Object.assign(this,s),this.getPath=n??true?t.getPath??go:Wc;}#t(){let t=new su({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=gy;errorHandler=ru;route(t,r){let n=this.basePath(t);return r.routes.map(s=>{let i;r.errorHandler===ru?i=s.handler:(i=async(o,a)=>(await po([],r.errorHandler)(o,()=>s.handler(o,a))).res,i[Pr]=s.handler),n.#i(s.method,s.path,i);}),this}basePath(t){let r=this.#t();return r._basePath=Rt(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=Rt(this._basePath,t),c=l==="/"?0:l.length;return p=>{let u=new URL(p.url);return u.pathname=u.pathname.slice(c)||"/",new Request(u,p)}})();let a=async(l,c)=>{let p=await r(s(l.req.raw),...o(l));if(p)return p;await c();};return this.#i(re,Rt(t,"*"),a),this}#i(t,r,n){t=t.toUpperCase(),r=Rt(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 Qc(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(p){return this.#s(p,a)}return c instanceof Promise?c.then(p=>p||(a.finalized?a.res:this.#r(a))).catch(p=>this.#s(p,a)):c??this.#r(a)}let l=po(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${Rt("/",t)}`,r),n,s));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method));});}};});function xo(e,t){let r=this.buildAllMatchers(),n=((s,i)=>{let o=r[s]||r[re],a=o[2][i];if(a)return a;let l=i.match(o[0]);if(!l)return [[],ds];let c=l.indexOf("",1);return [o[1][c],l]});return this.match=n,n(e,t)}var ds,_o=b(()=>{mt();ds=[];});function wy(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===Lr||e===Ir?1:t===Lr||t===Ir?-1:e===hs?1:t===hs?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var hs,Lr,Ir,kt,yy,ou,To=b(()=>{hs="[^/]+",Lr=".*",Ir="(?:|/.*)",kt=Symbol(),yy=new Set(".\\+*[^]$()");ou=class $o{#e;#t;#r=Object.create(null);insert(t,r,n,s,i){if(t.length===0){if(this.#e!==void 0)throw kt;if(i)return;this.#e=r;return}let[o,...a]=t,l=o==="*"?a.length===0?["","",Lr]:["","",hs]:o==="/*"?["","",Ir]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(l){let p=l[1],u=l[2]||hs;if(p&&l[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw kt;if(c=this.#r[u],!c){if(Object.keys(this.#r).some(f=>f!==Lr&&f!==Ir))throw kt;if(i)return;c=this.#r[u]=new $o,p!==""&&(c.#t=s.varIndex++);}!i&&p!==""&&n.push([p,c.#t]);}else if(c=this.#r[o],!c){if(Object.keys(this.#r).some(p=>p.length>1&&p!==Lr&&p!==Ir))throw kt;if(i)return;c=this.#r[o]=new $o;}c.insert(a,r,n,s,i);}buildRegExpStr(){let r=Object.keys(this.#r).sort(wy).map(n=>{let s=this.#r[n];return (typeof s.#t=="number"?`(${n})@${s.#t}`:yy.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 au,lu=b(()=>{To();au=class{#e={varIndex:0};#t=new ou;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 uu(e){return cu[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function Sy(){cu=Object.create(null);}function Ey(e){let t=new au,r=[];if(e.length===0)return by;let n=e.map(c=>[!/\*|\/:/.test(c[0]),...c]).sort(([c,p],[u,f])=>c?1:u?-1:p.length-f.length),s=Object.create(null);for(let c=0,p=-1,u=n.length;c<u;c++){let[f,h,d]=n[c];f?s[h]=[d.map(([y])=>[y,Object.create(null)]),ds]:p++;let m;try{m=t.insert(h,p,f);}catch(y){throw y===kt?new ms(h):y}f||(r[p]=d.map(([y,g])=>{let E=Object.create(null);for(g-=1;g>=0;g--){let[v,T]=m[g];E[v]=T;}return [y,E]}));}let[i,o,a]=t.buildRegExp();for(let c=0,p=r.length;c<p;c++)for(let u=0,f=r[c].length;u<f;u++){let h=r[c][u]?.[1];if(!h)continue;let d=Object.keys(h);for(let m=0,y=d.length;m<y;m++)h[d[m]]=a[h[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(uu(r).test(t))return [...e[r]]}}var by,cu,gs,vo=b(()=>{mt();Zt();_o();To();lu();by=[/^$/,[],Object.create(null)],cu=Object.create(null);gs=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[re]:Object.create(null)},this.#t={[re]:Object.create(null)};}add(e,t,r){let n=this.#e,s=this.#t;if(!n||!s)throw new Error(fs);n[e]||[n,s].forEach(a=>{a[e]=Object.create(null),Object.keys(a[re]).forEach(l=>{a[e][l]=[...a[re][l]];});}),t==="/*"&&(t="*");let i=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=uu(t);e===re?Object.keys(n).forEach(l=>{n[l][t]||=er(n[l],t)||er(n[re],t)||[];}):n[e][t]||=er(n[e],t)||er(n[re],t)||[],Object.keys(n).forEach(l=>{(e===re||e===l)&&Object.keys(n[l]).forEach(c=>{a.test(c)&&n[l][c].push([r,i]);});}),Object.keys(s).forEach(l=>{(e===re||e===l)&&Object.keys(s[l]).forEach(c=>a.test(c)&&s[l][c].push([r,i]));});return}let o=ps(t)||[t];for(let a=0,l=o.length;a<l;a++){let c=o[a];Object.keys(s).forEach(p=>{(e===re||e===p)&&(s[p][c]||=[...er(n[p],c)||er(n[re],c)||[]],s[p][c].push([r,i-l+a+1]));});}}match=xo;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,Sy(),e}#r(e){let t=[],r=e===re;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!==re&&t.push(...Object.keys(n[re]).map(i=>[i,n[re][i]]));}),r?Ey(t):null}};});var pu=b(()=>{mt();_o();vo();});var fu=b(()=>{vo();pu();});var Co,mu=b(()=>{mt();Co=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers;}add(e,t,r){if(!this.#t)throw new Error(fs);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 ms)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 du=b(()=>{mu();});var Dr,xy,hu,yu=b(()=>{mt();Zt();Dr=Object.create(null),xy=e=>{for(let t in e)return true;return false},hu=class gu{#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=Hc(r),o=[];for(let a=0,l=i.length;a<l;a++){let c=i[a],p=i[a+1],u=Gc(c,p),f=Array.isArray(u)?u[0]:c;if(f in s.#t){s=s.#t[f],u&&o.push(u[1]);continue}s.#t[f]=new gu,u&&(s.#r.push(u),o.push(u[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[re],p={};if(c!==void 0&&(c.params=Object.create(null),t.push(c),s!==Dr||i&&i!==Dr))for(let u=0,f=c.possibleKeys.length;u<f;u++){let h=c.possibleKeys[u],d=p[c.score];c.params[h]=i?.[h]&&!d?i[h]:s[h]??i?.[h],p[c.score]=true;}}}search(t,r){let n=[];this.#s=Dr;let i=[this],o=ho(r),a=[],l=o.length,c=null;for(let p=0;p<l;p++){let u=o[p],f=p===l-1,h=[];for(let m=0,y=i.length;m<y;m++){let g=i[m],E=g.#t[u];E&&(E.#s=g.#s,f?(E.#t["*"]&&this.#n(n,E.#t["*"],t,g.#s),this.#n(n,E,t,g.#s)):h.push(E));for(let v=0,T=g.#r.length;v<T;v++){let A=g.#r[v],C=g.#s===Dr?{}:{...g.#s};if(A==="*"){let D=g.#t["*"];D&&(this.#n(n,D,t,g.#s),D.#s=C,h.push(D));continue}let[$,_,L]=A;if(!u&&!(L instanceof RegExp))continue;let w=g.#t[$];if(L instanceof RegExp){if(c===null){c=new Array(l);let F=r[0]==="/"?1:0;for(let S=0;S<l;S++)c[S]=F,F+=o[S].length+1;}let D=r.substring(c[p]),N=L.exec(D);if(N){if(C[_]=N[0],this.#n(n,w,t,g.#s,C),xy(w.#t)){w.#s=C;let F=N[0].match(/\//)?.length??0;(a[F]||=[]).push(w);}continue}}(L===true||L.test(u))&&(C[_]=u,f?(this.#n(n,w,t,C,g.#s),w.#t["*"]&&this.#n(n,w.#t["*"],t,C,g.#s)):(w.#s=C,h.push(w)));}}let d=a.shift();i=d?h.concat(d):h;}return n.length>1&&n.sort((p,u)=>p.score-u.score),[n.map(({handler:p,params:u})=>[p,u])]}};});var Ao,wu=b(()=>{Zt();yu();Ao=class{name="TrieRouter";#e;constructor(){this.#e=new hu;}add(e,t,r){let n=ps(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 bu=b(()=>{wu();});var Ro,Su=b(()=>{iu();fu();du();bu();Ro=class extends nu{constructor(e={}){super(e),this.router=e.router??new Co({routers:[new gs,new Ao]});}};});var Eu=b(()=>{Su();});function ko(e){return !e||typeof e!="object"?false:e.code==="EADDRINUSE"}function xu(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 Oo(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,_u=b(()=>{jr=te(ae());});function Fr(e){let t=[],r=e??"",n=r.toLowerCase(),s=new TextEncoder().encode(r).length;if(!r)return t.push("auth.jwt_secret is empty"),{strong:false,reasons:t};_y.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"):Ty(r)&&t.push("contains an obvious repeated pattern");let o=$y.find(a=>n.includes(a));return o&&t.push(`contains placeholder term "${o}"`),{strong:t.length===0,reasons:t}}function Ty(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 _y,$y,No=b(()=>{_y=new Set(["unsafe-secret-change-me","dev-secret-change-me"]),$y=["change-me","changeme","secret","password","passwd","test","dev"];});var $u,Tu=b(()=>{$u=/^\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 Lo,vu,vy,Po,Io=b(()=>{Lo=(e,t=Po)=>{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},vu=e=>{for(let t in Po)if(Po[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"},Po=vy;});var Cu,Au=b(()=>{Cu=(...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 Ru,Cy,Ay,ku,Ou=b(()=>{Tu();Io();Au();Ru={br:".br",zstd:".zst",gzip:".gz"},Cy=Object.keys(Ru),Ay="index.html",ku=e=>{let t=e.root??"./",r=e.path,n=e.join??Cu;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,Ay));let l=e.getContent,c=await l(a,s);if(c instanceof Response)return s.newResponse(c.body,c);if(c){let p=e.mimes&&Lo(a,e.mimes)||Lo(a);if(s.header("Content-Type",p||"application/octet-stream"),e.precompressed&&(!p||$u.test(p))){let u=new Set(s.req.header("Accept-Encoding")?.split(",").map(f=>f.trim()));for(let f of Cy){if(!u.has(f))continue;let h=await l(a+Ru[f],s);if(h){c=h,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 Nu,Pu=b(()=>{Ou();Nu=e=>async function(r,n){return ku({...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$1(o)).isDirectory();}catch{}return a}})(r,n)};});var Lu=b(()=>{});var Iu,Du=b(()=>{Lu();Iu=(e,t)=>{for(let[r,n]of Object.entries(t)){let s=new RegExp("/:"+r+"(?:{[^/]+})?\\??");e=e.replace(s,n?`/${n}`:"");}return e};});var Oy,ju,Fu=b(()=>{Oy=1024,ju=({concurrency:e,interval:t}={})=>{if(e||=Oy,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 Uu,Do,Mu=b(()=>{Eo();Uu=e=>e.length>1,Do=e=>e[Pr]?Do(e[Pr]):e;});var Bu,Ny,Py,Ly,Iy,Ur,qu,jo,Fo=b(()=>{mt();Mu();Bu=e=>e.split(/[\/\\]/).slice(0,-1).join("/"),Ny=e=>e.replace(/(\\)/g,"/").replace(/\/$/g,""),Py=(e,t)=>{e.length===0||t?e.push(".."):e.pop();},Ly=(e,t)=>{e=e.replace(/^\.(?!.)/,""),e!==""&&t.push(e);},Iy=(e,t)=>{let r=false;for(let n of e)n===".."?(Py(t,r),r=true):(Ly(n,t),r=false);},Ur=(...e)=>{e=e.map(Ny);let t=[];return Iy(e.join("/").split("/"),t),(e[0][0]==="/"?"/":"")+t.join("/")},qu=e=>e.routes.reduce((t,{method:r,handler:n,path:s})=>{let i=Do(n);return ["GET",re].includes(r)&&!Uu(i)&&t.push({path:s}),t},[]),jo=e=>e.split("/").some(t=>t.startsWith(":")||t.includes("*"));});var Hu,ys,Uo=b(()=>{Fo();Hu="HONO_SSG_CONTEXT",ys="x-hono-disable-ssg",(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[ys]:"true"}})}catch{return null}})();});var Gu=b(()=>{bo();});var Mo,Bo=b(()=>{Gu();Mo=()=>({afterResponseHook:e=>e.status!==200?false:e});});var Dy,jy,Fy,Uy,My,By,qy,Hy,Gy,Wy,Vy,Wu,zy,Vu,zu=b(()=>{Du();Fu();Io();Uo();Bo();Fo();Dy=2,jy="text/plain",Fy="./static",Uy=(e,t,r,n)=>{let s=qy(r,n);return e.endsWith(`.${s}`)?Ur(t,e):e==="/"?Ur(t,`index.${s}`):e.endsWith("/")?Ur(t,e,`index.${s}`):Ur(t,`${e}.${s}`)},My=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"}`)}},By={"text/html":"html","text/xml":"xml","application/xml":"xml","application/yaml":"yaml"},qy=(e,t)=>{let r=t||By;return e in r?r[e]:vu(e)||"html"},Hy=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,Gy=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,Wy=(e,t,r)=>Array.isArray(e)?async n=>{for(let s of e)await s(n,t,r);}:e,Vy=function*(e,t,r,n){let s="http://localhost",i=ju({concurrency:n});for(let o of qu(e)){let a=new URL(o.path,s).toString(),l=new Request(a);yield new Promise(async(c,p)=>{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(jo(o.path)){c(void 0);return}l.ssgParams=[{}];}let u={method:l.method,headers:l.headers};c((function*(){for(let f of l.ssgParams)yield new Promise(async(h,d)=>{try{let m=Iu(o.path,f),y=await i.run(()=>e.request(m,u,{[Hu]:!0}));if(y.headers.get(ys)){h(void 0);return}if(r){let v=await r(y);if(!v){h(void 0);return}y=v;}let g=y.headers.get("Content-Type")?.split(";")[0]||jy,E=await My(y);h({routePath:m,mimeType:g,content:E});}catch(m){d(m);}});})());}catch(u){p(u);}});}},Wu=new Set,zy=async(e,t,r,n)=>{let s=await e;if(!s)return;let{routePath:i,content:o,mimeType:a}=s,l=Uy(i,r,a,n),c=Bu(l);return Wu.has(c)||(await t.mkdir(c,{recursive:true}),Wu.add(c)),typeof o=="string"?await t.writeFile(l,o):o instanceof ArrayBuffer&&await t.writeFile(l,new Uint8Array(o)),l},Vu=async(e,t,r)=>{let n,s=[],i=[],o=r?.plugins||[Mo()],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 p of o)p.beforeRequestHook&&a.push(...Array.isArray(p.beforeRequestHook)?p.beforeRequestHook:[p.beforeRequestHook]),p.afterResponseHook&&l.push(...Array.isArray(p.afterResponseHook)?p.afterResponseHook:[p.afterResponseHook]),p.afterGenerateHook&&c.push(...Array.isArray(p.afterGenerateHook)?p.afterGenerateHook:[p.afterGenerateHook]);try{let p=r?.dir??Fy,u=r?.concurrency??Dy,f=Hy(a.length>0?a:[y=>y]),h=Gy(l.length>0?l:[y=>y]),d=Vy(e,f,h,u);for(let y of d)s.push(y.then(g=>{if(g)for(let E of g)i.push(zy(E,t,p,r?.extensionMap).catch(v=>v));}));await Promise.all(s);let m=[];for(let y of i){let g=await y;if(typeof g=="string")m.push(g);else if(g)throw g}n={success:!0,files:m};}catch(p){let u=p instanceof Error?p:new Error(String(p));n={success:false,files:[],error:u};}return c.length>0&&await Wy(c,t,r)(n,t,r),n};});var Ku=b(()=>{zu();Uo();Bo();});var Ky,qo,Xu,Ju=b(()=>{Ku();(({write:Ky}=Bun)),qo={writeFile:async(e,t)=>{await Ky(e,t);},mkdir:async()=>{}},Xu=async(e,t)=>Vu(e,qo,t);});var Yu,Qu,Zu,ep=b(()=>{Yu=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);}},Qu=e=>new MessageEvent("message",{data:e}),Zu=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,ws=b(()=>{tr=e=>"server"in e.env?e.env.server:e.env;});var Ho,Go,Wo,tp,rp=b(()=>{ep();ws();Ho=e=>new Yu({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);}}),Go=Zu((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)}),Wo={open(e){let t=e.data.events;t.onOpen&&t.onOpen(new Event("open"),Ho(e));},close(e,t,r){let n=e.data.events;n.onClose&&n.onClose(new CloseEvent("close",{code:t,reason:r}),Ho(e));},message(e,t){let r=e.data.events;if(r.onMessage){let n=typeof t=="string"?t:t.buffer;r.onMessage(Qu(n),Ho(e));}}},tp=()=>({upgradeWebSocket:Go,websocket:Wo});});var np,sp=b(()=>{ws();np=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 ip={};de(ip,{bunFileSystemModule:()=>qo,createBunWebSocket:()=>tp,getBunServer:()=>tr,getConnInfo:()=>np,serveStatic:()=>Nu,toSSG:()=>Xu,upgradeWebSocket:()=>Go,websocket:()=>Wo});var op=b(()=>{Pu();Ju();rp();sp();ws();});async function bs(e,t={port:3e3}){if(e.config.auth?.enabled){let s=Fr(e.config.auth.jwt_secret);s.strong||console.warn(`[auth] auth.jwt_secret is weak \u2014 do not use it in production:
61
+ )`,bg="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 Sl={};pe(Sl,{init:()=>wg});var Ze,wg,El=b(()=>{Ze=V(z());so();wg=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=>{let{generatedKeys:n}=await ts({configFormat:t.format,recreate:t.recreate,driver:t.pglite?"pglite":void 0});console.log(),console.log(Ze.default.green(" \u279C"),"Project initialized",Ze.default.cyan("./"+Oe__default.relative(process.cwd(),Oe__default.join(process.cwd(),"supabase")))),(n?.publishable||n?.secret)&&(console.error(Ze.default.green(" \u279C"),"Generated API keys, written to",Ze.default.cyan("./.env")),n.publishable&&console.log(Ze.default.green(" \u279C"),"Publishable key".padEnd(19),Ze.default.cyan(n.publishable)),n.secret&&console.log(Ze.default.green(" \u279C"),"Secret key".padEnd(19),Ze.default.cyan(n.secret)));});};});function me(e){return `${Sg} ${e}`}var Sg,Xe=b(()=>{Sg="[lite]";});var xl={};pe(xl,{generateKeys:()=>Tg});var io,xg,_g,Tg,_l=b(()=>{io=V(z());Xe();Zi();to();xg="SUPABASE_PUBLISHABLE_KEY",_g="SUPABASE_SECRET_KEY",Tg=e=>{e.command("generate-keys").description(me("Generate a new publishable/secret API key pair")).helpGroup("Local Development:").action(async()=>{let[t,n]=await Promise.all([Xt("publishable"),Xt("secret")]),r=Oe__default.join(process.cwd(),".env");Qr(r,{[xg]:t.key,[_g]:n.key}),console.error(io.default.green(" \u279C"),"Wrote new API keys to",io.default.cyan("./.env")),console.log(t.key),console.log(n.key);});};});var Tl=b(()=>{});var $l=b(()=>{});function oo(e,t,n=void 0){let r=typeof t=="string"?t.split(/[.[\]"]+/).filter(s=>s):t;if(r.length===0)return e;try{let[s,...i]=r;return !s||!(s in e)?n:oo(e[s],i,n)}catch{if(typeof n<"u")return n;throw new Error(`Invalid path: ${r.join(".")}`)}}var Al=b(()=>{});var Cl=b(()=>{});function ns(){try{return !vn()&&global?.process?.release?.name==="node"}catch{return false}}function vn(){try{return typeof Bun<"u"}catch{return false}}async function rs(e,t){let n=performance.now();await e();let r=performance.now();t(r-n);}var vl=b(()=>{});function kl(e,t={}){return e.split(`
62
+ `).map(n=>n.trim()).filter(n=>n.length>0).filter(n=>!n.startsWith(t.comments??"--")).join(`
63
+ `)}function vt(e){let t=[],n="",r=0,s=e.length,i=false,o=false,a=0,c=/^create(\s+or\s+replace)?(\s+temp(orary)?)?$/i,l=u=>{Rl(u).length>0&&t.push(u.trim());},p=()=>{i=false,o=false,a=0;};for(;r<s;){let u=e[r],f=e[r+1];if(u==="-"&&f==="-"){for(;r<s&&e[r]!==`
64
+ `;)n+=e[r],r++;continue}if(u==="/"&&f==="*"){for(n+="/*",r+=2;r<s&&!(e[r]==="*"&&e[r+1]==="/");)n+=e[r],r++;r<s&&(n+="*/",r+=2);continue}if(u==="'"){for(n+=u,r++;r<s;){if(e[r]==="'"&&e[r+1]==="'"){n+="''",r+=2;continue}if(n+=e[r],e[r]==="'"){r++;break}r++;}continue}if(u==='"'){for(n+=u,r++;r<s;){if(e[r]==='"'&&e[r+1]==='"'){n+='""',r+=2;continue}if(n+=e[r],e[r]==='"'){r++;break}r++;}continue}if(u==="$"){let h=e.indexOf("$",r+1);if(h!==-1){let d=e.slice(r,h+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(d)){n+=d,r=h+1;let y=e.indexOf(d,r);y===-1?(n+=e.slice(r),r=s):(n+=e.slice(r,y+d.length),r=y+d.length);continue}}}if(/[A-Za-z_]/.test(u)){let h=r;for(;h<s&&/[A-Za-z0-9_]/.test(e[h]);)h++;let d=e.slice(r,h),m=d.toLowerCase();if(m==="trigger"&&c.test(Rl(n))?i=true:i&&m==="begin"?(o=true,a++):i&&o&&m==="case"?a++:i&&o&&m==="end"&&a>0&&a--,n+=d,r=h,i&&o&&a===0){let y=r;for(;y<s&&/\s/.test(e[y]);)y++;e[y]===";"&&(r=y+1),l(n),n="",p();}continue}if(u===";"){if(i&&o&&a>0){n+=u,r++;continue}l(n),n="",p(),r++;continue}n+=u,r++;}return l(n),t}function Rl(e){let t="",n=0,r=e.length;for(;n<r;){let s=e[n],i=e[n+1];if(s==="-"&&i==="-"){for(;n<r&&e[n]!==`
65
+ `;)n++;continue}if(s==="/"&&i==="*"){for(n+=2;n<r&&!(e[n]==="*"&&e[n+1]==="/");)n++;n+=2;continue}t+=s,n++;}return t.trim()}function ao(e){return (e??"").trim().toLowerCase()}function co(e){return (e??"").replace(/\s+/g," ").replace(/"/g,"").trim().toLowerCase()}function lo(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 Rt=b(()=>{});function Pl(e,t){if(typeof e!="string"){throw new Error("Email must be a string");}if(!s.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 Nl(e,{panic:t=true,length:n=8,numbers:r=0,special:s=0}={}){try{if(typeof e!="string"){if(t)throw new Error("Password must be a string");return !1}if(e.length<n){if(t)throw new Error(`Password must be at least ${n} characters long`);return !1}if((e.match(/[0-9]/g)?.length??0)<r){if(t)throw new Error(`Password must contain at least ${r} 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 Ll(e,t,n){if(t instanceof RegExp)return t.test(e);if(typeof t=="string")switch(!n&&t.startsWith("/")&&(n="regex"),n){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 Rn=b(()=>{});function uo(e){return typeof e=="number"?e:Number.parseInt(String(e),10)}var Ol=b(()=>{});var Il=b(()=>{});var lt=b(()=>{Tl();$l();Al();Cl();vl();Rt();Rn();Ol();Il();});var po,Dl=b(()=>{po=(e,t,n)=>(r,s)=>{let i=-1;return o(0);async function o(a){if(a<=i)throw new Error("next() called multiple times");i=a;let c,l=false,p;if(e[a]?(p=e[a][0][0],r.req.routeIndex=a):p=a===e.length&&s||void 0,p)try{c=await p(r,()=>o(a+1));}catch(u){if(u instanceof Error&&t)r.error=u,c=await t(u,r),l=true;else throw u}else r.finalized===false&&n&&(c=await n(r));return c&&(r.finalized===false||l)&&(r.res=c),r}};});var jl=b(()=>{});var Fl,Ul=b(()=>{Fl=Symbol();});async function Ag(e,t){let n=await e.formData();return n?Cg(n,t):{}}function Cg(e,t){let n=Object.create(null);return e.forEach((r,s)=>{t.all||s.endsWith("[]")?vg(n,s,r):n[s]=r;}),t.dot&&Object.entries(n).forEach(([r,s])=>{r.includes(".")&&(Rg(n,r,s),delete n[r]);}),n}var Ml,vg,Rg,Bl=b(()=>{fo();Ml=async(e,t=Object.create(null))=>{let{all:n=false,dot:r=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")?Ag(e,{all:n,dot:r}):{}};vg=(e,t,n)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]:t.endsWith("[]")?e[t]=[n]:e[t]=n;},Rg=(e,t,n)=>{let r=e,s=t.split(".");s.forEach((i,o)=>{o===s.length-1?r[i]=n:((!r[i]||typeof r[i]!="object"||Array.isArray(r[i])||r[i]instanceof File)&&(r[i]=Object.create(null)),r=r[i]);});};});var ho,ql,kg,Pg,is,Hl,os,Ng,go,Gl,kt,as,mo,Wl,Vl,Kl,yo,Jt=b(()=>{ho=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},ql=e=>{let{groups:t,path:n}=kg(e),r=ho(n);return Pg(r,t)},kg=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(n,r)=>{let s=`@${r}`;return t.push([s,n]),s}),{groups:t,path:e}},Pg=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let s=e.length-1;s>=0;s--)if(e[s].includes(r)){e[s]=e[s].replace(r,t[n][1]);break}}return e},is={},Hl=(e,t)=>{if(e==="*")return "*";let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return is[r]||(n[2]?is[r]=t&&t[0]!==":"&&t[0]!=="*"?[r,n[1],new RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],new RegExp(`^${n[2]}$`)]:is[r]=[e,n[1],true]),is[r]}return null},os=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,n=>{try{return t(n)}catch{return n}})}},Ng=e=>os(e,decodeURI),go=e=>{let t=e.url,n=t.indexOf("/",t.indexOf(":")+4),r=n;for(;r<t.length;r++){let s=t.charCodeAt(r);if(s===37){let i=t.indexOf("?",r),o=t.indexOf("#",r),a=i===-1?o===-1?void 0:o:o===-1?i:Math.min(i,o),c=t.slice(n,a);return Ng(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(s===63||s===35)break}return t.slice(n,r)},Gl=e=>{let t=go(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},kt=(e,t,...n)=>(n.length&&(t=kt(t,...n)),`${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("/"),n=[],r="";return t.forEach(s=>{if(s!==""&&!/\:/.test(s))r+="/"+s;else if(/\:/.test(s))if(/\?/.test(s)){n.length===0&&r===""?n.push("/"):n.push(r);let i=s.replace("?","");r+="/"+i,n.push(r);}else r+="/"+s;}),n.filter((s,i,o)=>o.indexOf(s)===i)},mo=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?os(e,yo):e):e,Wl=(e,t,n)=>{let r;if(!n&&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 c=o+t.length+2,l=e.indexOf("&",c);return mo(e.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return "";o=e.indexOf(`&${t}`,o+1);}if(r=/[%+]/.test(e),!r)return}let s={};r??=/[%+]/.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 c=e.slice(i+1,a===-1?o===-1?void 0:o:a);if(r&&(c=mo(c)),i=o,c==="")continue;let l;a===-1?l="":(l=e.slice(a+1,o===-1?void 0:o),r&&(l=mo(l))),n?(s[c]&&Array.isArray(s[c])||(s[c]=[]),s[c].push(l)):s[c]??=l;}return t?s[t]:s},Vl=Wl,Kl=(e,t)=>Wl(e,t,true),yo=decodeURIComponent;});var zl,ss,fo=b(()=>{jl();Ul();Bl();Jt();zl=e=>os(e,yo),ss=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t="/",n=[[]]){this.raw=e,this.path=t,this.#t=n,this.#e={};}param(e){return e?this.#n(e):this.#i()}#n(e){let t=this.#t[0][this.routeIndex][1][e],n=this.#s(t);return n&&/\%/.test(n)?zl(n):n}#i(){let e={},t=Object.keys(this.#t[0][this.routeIndex][1]);for(let n of t){let r=this.#s(this.#t[0][this.routeIndex][1][n]);r!==void 0&&(e[n]=/\%/.test(r)?zl(r):r);}return e}#s(e){return this.#t[1]?this.#t[1][e]:e}query(e){return Vl(this.url,e)}queries(e){return Kl(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((n,r)=>{t[r]=n;}),t}async parseBody(e){return this.bodyCache.parsedBody??=await Ml(this,e)}#r=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let s=Object.keys(t)[0];return s?t[s].then(i=>(s==="json"&&(i=JSON.stringify(i)),new Response(i)[e]())):t[e]=n[e]()};json(){return this.#r("text").then(e=>JSON.parse(e))}text(){return this.#r("text")}arrayBuffer(){return this.#r("arrayBuffer")}blob(){return this.#r("blob")}formData(){return this.#r("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[Fl](){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 Xl,Jl,bo,wo=b(()=>{Xl={Stringify:1,BeforeStream:2,Stream:3},Jl=(e,t)=>{let n=new String(e);return n.isEscaped=true,n.callbacks=t,n},bo=async(e,t,n,r,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:r}))).then(a=>Promise.all(a.filter(Boolean).map(c=>bo(c,t,false,r,s))).then(()=>s[0]));return n?Jl(await o,i):o};});var Lg,So,kn,Yl,Ql=b(()=>{fo();wo();Lg="text/plain; charset=UTF-8",So=(e,t)=>({"Content-Type":e,...t}),kn=(e,t)=>new Response(e,t),Yl=class{#e;#t;env={};#n;finalized=false;error;#i;#s;#r;#u;#c;#l;#a;#p;#f;constructor(e,t){this.#e=e,t&&(this.#s=t.executionCtx,this.env=t.env,this.#l=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.#r||=kn(null,{headers:this.#a??=new Headers})}set res(e){if(this.#r&&e){e=kn(e.body,e);for(let[t,n]of this.#r.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let r=this.#r.headers.getSetCookie();e.headers.delete("set-cookie");for(let s of r)e.headers.append("set-cookie",s);}else e.headers.set(t,n);}this.#r=e,this.finalized=true;}render=(...e)=>(this.#c??=t=>this.html(t),this.#c(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#c=e;};header=(e,t,n)=>{this.finalized&&(this.#r=kn(this.#r.body,this.#r));let r=this.#r?this.#r.headers:this.#a??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t);};status=e=>{this.#i=e;};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t);};get=e=>this.#n?this.#n.get(e):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#o(e,t,n){let r=this.#r?new Headers(this.#r.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"?r.append(o,a):r.set(o,a);}if(n)for(let[i,o]of Object.entries(n))if(typeof o=="string")r.set(i,o);else {r.delete(i);for(let a of o)r.append(i,a);}let s=typeof t=="number"?t:t?.status??this.#i;return kn(e,{status:s,headers:r})}newResponse=(...e)=>this.#o(...e);body=(e,t,n)=>this.#o(e,t,n);text=(e,t,n)=>!this.#a&&!this.#i&&!t&&!n&&!this.finalized?new Response(e):this.#o(e,t,So(Lg,n));json=(e,t,n)=>this.#o(JSON.stringify(e),t,So("application/json",n));html=(e,t,n)=>{let r=s=>this.#o(s,t,So("text/html; charset=UTF-8",n));return typeof e=="object"?bo(e,Xl.Stringify,false,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header("Location",/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>kn(),this.#l(this))};});var ne,Zl,eu,cs,ls,ut=b(()=>{ne="ALL",Zl="all",eu=["get","post","put","delete","options","patch"],cs="Can not add a route since the matcher is already built.",ls=class extends Error{};});var Pn,Eo=b(()=>{Pn="__COMPOSED_HANDLER";});var Og,tu,nu,su=b(()=>{Dl();Ql();ut();Eo();Jt();Og=e=>e.text("404 Not Found",404),tu=(e,t)=>{if("getResponse"in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text("Internal Server Error",500)},nu=class ru{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...eu,Zl].forEach(i=>{this[i]=(o,...a)=>(typeof o=="string"?this.#e=o:this.#i(i,this.#e,o),a.forEach(c=>{this.#i(i,this.#e,c);}),this);}),this.on=(i,o,...a)=>{for(let c of [o].flat()){this.#e=c;for(let l of [i].flat())a.map(p=>{this.#i(l.toUpperCase(),this.#e,p);});}return this},this.use=(i,...o)=>(typeof i=="string"?this.#e=i:(this.#e="*",o.unshift(i)),o.forEach(a=>{this.#i(ne,this.#e,a);}),this);let{strict:r,...s}=t;Object.assign(this,s),this.getPath=r??true?t.getPath??go:Gl;}#t(){let t=new ru({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=Og;errorHandler=tu;route(t,n){let r=this.basePath(t);return n.routes.map(s=>{let i;n.errorHandler===tu?i=s.handler:(i=async(o,a)=>(await po([],n.errorHandler)(o,()=>s.handler(o,a))).res,i[Pn]=s.handler),r.#i(s.method,s.path,i);}),this}basePath(t){let n=this.#t();return n._basePath=kt(this._basePath,t),n}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#n=t,this);mount(t,n,r){let s,i;r&&(typeof r=="function"?i=r:(i=r.optionHandler,r.replaceRequest===false?s=c=>c:s=r.replaceRequest));let o=i?c=>{let l=i(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx;}catch{}return [c.env,l]};s||=(()=>{let c=kt(this._basePath,t),l=c==="/"?0:c.length;return p=>{let u=new URL(p.url);return u.pathname=u.pathname.slice(l)||"/",new Request(u,p)}})();let a=async(c,l)=>{let p=await n(s(c.req.raw),...o(c));if(p)return p;await l();};return this.#i(ne,kt(t,"*"),a),this}#i(t,n,r){t=t.toUpperCase(),n=kt(this._basePath,n);let s={basePath:this._basePath,path:n,method:t,handler:r};this.router.add(t,n,[r,s]),this.routes.push(s);}#s(t,n){if(t instanceof Error)return this.errorHandler(t,n);throw t}#r(t,n,r,s){if(s==="HEAD")return (async()=>new Response(null,await this.#r(t,n,r,"GET")))();let i=this.getPath(t,{env:r}),o=this.router.match(s,i),a=new Yl(t,{path:i,matchResult:o,env:r,executionCtx:n,notFoundHandler:this.#n});if(o[0].length===1){let l;try{l=o[0][0][0][0](a,async()=>{a.res=await this.#n(a);});}catch(p){return this.#s(p,a)}return l instanceof Promise?l.then(p=>p||(a.finalized?a.res:this.#n(a))).catch(p=>this.#s(p,a)):l??this.#n(a)}let c=po(o[0],this.errorHandler,this.#n);return (async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#s(l,a)}})()}fetch=(t,...n)=>this.#r(t,n[1],n[0],t.method);request=(t,n,r,s)=>t instanceof Request?this.fetch(n?new Request(t,n):t,r,s):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${kt("/",t)}`,n),r,s));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#r(t.request,t,void 0,t.request.method));});}};});function xo(e,t){let n=this.buildAllMatchers(),r=((s,i)=>{let o=n[s]||n[ne],a=o[2][i];if(a)return a;let c=i.match(o[0]);if(!c)return [[],us];let l=c.indexOf("",1);return [o[1][l],c]});return this.match=r,r(e,t)}var us,_o=b(()=>{ut();us=[];});function Dg(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===Nn||e===Ln?1:t===Nn||t===Ln?-1:e===ps?1:t===ps?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var ps,Nn,Ln,Pt,Ig,iu,$o=b(()=>{ps="[^/]+",Nn=".*",Ln="(?:|/.*)",Pt=Symbol(),Ig=new Set(".\\+*[^]$()");iu=class To{#e;#t;#n=Object.create(null);insert(t,n,r,s,i){if(t.length===0){if(this.#e!==void 0)throw Pt;if(i)return;this.#e=n;return}let[o,...a]=t,c=o==="*"?a.length===0?["","",Nn]:["","",ps]:o==="/*"?["","",Ln]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let p=c[1],u=c[2]||ps;if(p&&c[2]&&(u===".*"||(u=u.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(u))))throw Pt;if(l=this.#n[u],!l){if(Object.keys(this.#n).some(f=>f!==Nn&&f!==Ln))throw Pt;if(i)return;l=this.#n[u]=new To,p!==""&&(l.#t=s.varIndex++);}!i&&p!==""&&r.push([p,l.#t]);}else if(l=this.#n[o],!l){if(Object.keys(this.#n).some(p=>p.length>1&&p!==Nn&&p!==Ln))throw Pt;if(i)return;l=this.#n[o]=new To;}l.insert(a,n,r,s,i);}buildRegExpStr(){let n=Object.keys(this.#n).sort(Dg).map(r=>{let s=this.#n[r];return (typeof s.#t=="number"?`(${r})@${s.#t}`:Ig.has(r)?`\\${r}`:r)+s.buildRegExpStr()});return typeof this.#e=="number"&&n.unshift(`#${this.#e}`),n.length===0?"":n.length===1?n[0]:"(?:"+n.join("|")+")"}};});var ou,au=b(()=>{$o();ou=class{#e={varIndex:0};#t=new iu;insert(e,t,n){let r=[],s=[];for(let o=0;;){let a=false;if(e=e.replace(/\{[^}]+\}/g,c=>{let l=`@\\${o}`;return s[o]=[l,c],o++,a=true,l}),!a)break}let i=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let o=s.length-1;o>=0;o--){let[a]=s[o];for(let c=i.length-1;c>=0;c--)if(i[c].indexOf(a)!==-1){i[c]=i[c].replace(a,s[o][1]);break}}return this.#t.insert(i,t,r,this.#e,n),r}buildRegExp(){let e=this.#t.buildRegExpStr();if(e==="")return [/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,i,o)=>i!==void 0?(n[++t]=Number(i),"$()"):(o!==void 0&&(r[Number(o)]=++t),"")),[new RegExp(`^${e}`),n,r]}};});function lu(e){return cu[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,n)=>n?`\\${n}`:"(?:|/.*)")}$`)}function Fg(){cu=Object.create(null);}function Ug(e){let t=new ou,n=[];if(e.length===0)return jg;let r=e.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,p],[u,f])=>l?1:u?-1:p.length-f.length),s=Object.create(null);for(let l=0,p=-1,u=r.length;l<u;l++){let[f,h,d]=r[l];f?s[h]=[d.map(([y])=>[y,Object.create(null)]),us]:p++;let m;try{m=t.insert(h,p,f);}catch(y){throw y===Pt?new ls(h):y}f||(n[p]=d.map(([y,g])=>{let E=Object.create(null);for(g-=1;g>=0;g--){let[A,$]=m[g];E[A]=$;}return [y,E]}));}let[i,o,a]=t.buildRegExp();for(let l=0,p=n.length;l<p;l++)for(let u=0,f=n[l].length;u<f;u++){let h=n[l][u]?.[1];if(!h)continue;let d=Object.keys(h);for(let m=0,y=d.length;m<y;m++)h[d[m]]=a[h[d[m]]];}let c=[];for(let l in o)c[l]=n[o[l]];return [i,c,s]}function Yt(e,t){if(e){for(let n of Object.keys(e).sort((r,s)=>s.length-r.length))if(lu(n).test(t))return [...e[n]]}}var jg,cu,fs,Ao=b(()=>{ut();Jt();_o();$o();au();jg=[/^$/,[],Object.create(null)],cu=Object.create(null);fs=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[ne]:Object.create(null)},this.#t={[ne]:Object.create(null)};}add(e,t,n){let r=this.#e,s=this.#t;if(!r||!s)throw new Error(cs);r[e]||[r,s].forEach(a=>{a[e]=Object.create(null),Object.keys(a[ne]).forEach(c=>{a[e][c]=[...a[ne][c]];});}),t==="/*"&&(t="*");let i=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=lu(t);e===ne?Object.keys(r).forEach(c=>{r[c][t]||=Yt(r[c],t)||Yt(r[ne],t)||[];}):r[e][t]||=Yt(r[e],t)||Yt(r[ne],t)||[],Object.keys(r).forEach(c=>{(e===ne||e===c)&&Object.keys(r[c]).forEach(l=>{a.test(l)&&r[c][l].push([n,i]);});}),Object.keys(s).forEach(c=>{(e===ne||e===c)&&Object.keys(s[c]).forEach(l=>a.test(l)&&s[c][l].push([n,i]));});return}let o=as(t)||[t];for(let a=0,c=o.length;a<c;a++){let l=o[a];Object.keys(s).forEach(p=>{(e===ne||e===p)&&(s[p][l]||=[...Yt(r[p],l)||Yt(r[ne],l)||[]],s[p][l].push([n,i-c+a+1]));});}}match=xo;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(t=>{e[t]||=this.#n(t);}),this.#e=this.#t=void 0,Fg(),e}#n(e){let t=[],n=e===ne;return [this.#e,this.#t].forEach(r=>{let s=r[e]?Object.keys(r[e]).map(i=>[i,r[e][i]]):[];s.length!==0?(n||=true,t.push(...s)):e!==ne&&t.push(...Object.keys(r[ne]).map(i=>[i,r[ne][i]]));}),n?Ug(t):null}};});var uu=b(()=>{ut();_o();Ao();});var pu=b(()=>{Ao();uu();});var Co,fu=b(()=>{ut();Co=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers;}add(e,t,n){if(!this.#t)throw new Error(cs);this.#t.push([e,t,n]);}match(e,t){if(!this.#t)throw new Error("Fatal error");let n=this.#e,r=this.#t,s=n.length,i=0,o;for(;i<s;i++){let a=n[i];try{for(let c=0,l=r.length;c<l;c++)a.add(...r[c]);o=a.match(e,t);}catch(c){if(c instanceof ls)continue;throw c}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 mu=b(()=>{fu();});var On,Mg,du,gu=b(()=>{ut();Jt();On=Object.create(null),Mg=e=>{for(let t in e)return true;return false},du=class hu{#e;#t;#n;#i=0;#s=On;constructor(t,n,r){if(this.#t=r||Object.create(null),this.#e=[],t&&n){let s=Object.create(null);s[t]={handler:n,possibleKeys:[],score:0},this.#e=[s];}this.#n=[];}insert(t,n,r){this.#i=++this.#i;let s=this,i=ql(n),o=[];for(let a=0,c=i.length;a<c;a++){let l=i[a],p=i[a+1],u=Hl(l,p),f=Array.isArray(u)?u[0]:l;if(f in s.#t){s=s.#t[f],u&&o.push(u[1]);continue}s.#t[f]=new hu,u&&(s.#n.push(u),o.push(u[1])),s=s.#t[f];}return s.#e.push({[t]:{handler:r,possibleKeys:o.filter((a,c,l)=>l.indexOf(a)===c),score:this.#i}}),s}#r(t,n,r,s,i){for(let o=0,a=n.#e.length;o<a;o++){let c=n.#e[o],l=c[r]||c[ne],p={};if(l!==void 0&&(l.params=Object.create(null),t.push(l),s!==On||i&&i!==On))for(let u=0,f=l.possibleKeys.length;u<f;u++){let h=l.possibleKeys[u],d=p[l.score];l.params[h]=i?.[h]&&!d?i[h]:s[h]??i?.[h],p[l.score]=true;}}}search(t,n){let r=[];this.#s=On;let i=[this],o=ho(n),a=[],c=o.length,l=null;for(let p=0;p<c;p++){let u=o[p],f=p===c-1,h=[];for(let m=0,y=i.length;m<y;m++){let g=i[m],E=g.#t[u];E&&(E.#s=g.#s,f?(E.#t["*"]&&this.#r(r,E.#t["*"],t,g.#s),this.#r(r,E,t,g.#s)):h.push(E));for(let A=0,$=g.#n.length;A<$;A++){let v=g.#n[A],C=g.#s===On?{}:{...g.#s};if(v==="*"){let I=g.#t["*"];I&&(this.#r(r,I,t,g.#s),I.#s=C,h.push(I));continue}let[T,_,O]=v;if(!u&&!(O instanceof RegExp))continue;let w=g.#t[T];if(O instanceof RegExp){if(l===null){l=new Array(c);let j=n[0]==="/"?1:0;for(let S=0;S<c;S++)l[S]=j,j+=o[S].length+1;}let I=n.substring(l[p]),N=O.exec(I);if(N){if(C[_]=N[0],this.#r(r,w,t,g.#s,C),Mg(w.#t)){w.#s=C;let j=N[0].match(/\//)?.length??0;(a[j]||=[]).push(w);}continue}}(O===true||O.test(u))&&(C[_]=u,f?(this.#r(r,w,t,C,g.#s),w.#t["*"]&&this.#r(r,w.#t["*"],t,C,g.#s)):(w.#s=C,h.push(w)));}}let d=a.shift();i=d?h.concat(d):h;}return r.length>1&&r.sort((p,u)=>p.score-u.score),[r.map(({handler:p,params:u})=>[p,u])]}};});var vo,yu=b(()=>{Jt();gu();vo=class{name="TrieRouter";#e;constructor(){this.#e=new du;}add(e,t,n){let r=as(t);if(r){for(let s=0,i=r.length;s<i;s++)this.#e.insert(e,r[s],n);return}this.#e.insert(e,t,n);}match(e,t){return this.#e.search(e,t)}};});var bu=b(()=>{yu();});var Ro,wu=b(()=>{su();pu();mu();bu();Ro=class extends nu{constructor(e={}){super(e),this.router=e.router??new Co({routers:[new fs,new vo]});}};});var Su=b(()=>{wu();});function ko(e){return !e||typeof e!="object"?false:e.code==="EADDRINUSE"}function Eu(e,t){return new Promise((n,r)=>{let s=o=>{e.off("listening",i),r(o);},i=()=>{e.off("error",s),n();};e.once("error",s),e.once("listening",i),e.listen(t);})}function Po(e){console.error(),console.error(In.default.red(`Cannot start server: Port ${In.default.bold(String(e))} is already in use.`)),console.error(In.default.red(`Stop the process using that port, or set a different ${In.default.bold("api.port")} in your config.`)),console.error(),process.exit(1);}var In,xu=b(()=>{In=V(z());});function Dn(e){let t=[],n=e??"",r=n.toLowerCase(),s=new TextEncoder().encode(n).length;if(!n)return t.push("auth.jwt_secret is empty"),{strong:false,reasons:t};Bg.has(n)&&t.push(`matches Supalite development default "${n}"`),s<32&&t.push(`is ${s} bytes; use at least 32 bytes for production secrets`),[/[a-z]/.test(n),/[A-Z]/.test(n),/[0-9]/.test(n),/[^A-Za-z0-9]/.test(n)].filter(Boolean).length<3&&t.push("uses too little character variety"),/^(.)\1{7,}$/.test(n)?t.push("is one repeated character"):Hg(n)&&t.push("contains an obvious repeated pattern");let o=qg.find(a=>r.includes(a));return o&&t.push(`contains placeholder term "${o}"`),{strong:t.length===0,reasons:t}}function Hg(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 Bg,qg,No=b(()=>{Bg=new Set(["unsafe-secret-change-me","dev-secret-change-me"]),qg=["change-me","changeme","secret","password","passwd","test","dev"];});function Lo(e,t){t&&Object.defineProperty(e,Gg,{value:t,enumerable:false,configurable:false,writable:false});}var Gg,_u=b(()=>{Gg=Symbol("lite-peer-address");});var Tu,$u=b(()=>{Tu=/^\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 Io,Au,Wg,Oo,Do=b(()=>{Io=(e,t=Oo)=>{let n=/\.([a-zA-Z0-9]+?)$/,r=e.match(n);if(!r)return;let s=t[r[1]];return s&&s.startsWith("text")&&(s+="; charset=utf-8"),s},Au=e=>{for(let t in Oo)if(Oo[t]===e)return t},Wg={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"},Oo=Wg;});var Cu,vu=b(()=>{Cu=(...e)=>{let t=e.filter(s=>s!=="").join("/");t=t.replace(/(?<=\/)\/+/g,"");let n=t.split("/"),r=[];for(let s of n)s===".."&&r.length>0&&r.at(-1)!==".."?r.pop():s!=="."&&r.push(s);return r.join("/")||"."};});var Ru,Vg,Kg,ku,Pu=b(()=>{$u();Do();vu();Ru={br:".br",zstd:".zst",gzip:".gz"},Vg=Object.keys(Ru),Kg="index.html",ku=e=>{let t=e.root??"./",n=e.path,r=e.join??Cu;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=r(t,!n&&e.rewriteRequestPath?e.rewriteRequestPath(o):o);e.isDir&&await e.isDir(a)&&(a=r(a,Kg));let c=e.getContent,l=await c(a,s);if(l instanceof Response)return s.newResponse(l.body,l);if(l){let p=e.mimes&&Io(a,e.mimes)||Io(a);if(s.header("Content-Type",p||"application/octet-stream"),e.precompressed&&(!p||Tu.test(p))){let u=new Set(s.req.header("Accept-Encoding")?.split(",").map(f=>f.trim()));for(let f of Vg){if(!u.has(f))continue;let h=await c(a+Ru[f],s);if(h){l=h,s.header("Content-Encoding",f),s.header("Vary","Accept-Encoding",{append:true});break}}}return await e.onFound?.(a,s),s.body(l)}await e.onNotFound?.(a,s),await i();}};});var Nu,Lu=b(()=>{Pu();Nu=e=>async function(n,r){return ku({...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$1(o)).isDirectory();}catch{}return a}})(n,r)};});var Ou=b(()=>{});var Iu,Du=b(()=>{Ou();Iu=(e,t)=>{for(let[n,r]of Object.entries(t)){let s=new RegExp("/:"+n+"(?:{[^/]+})?\\??");e=e.replace(s,r?`/${r}`:"");}return e};});var Jg,ju,Fu=b(()=>{Jg=1024,ju=({concurrency:e,interval:t}={})=>{if(e||=Jg,e===1/0)return {run:async s=>s()};let n=new Set,r=async(s,i,o)=>{if(n.size>=e)return i||=new Promise(l=>o=l),setTimeout(()=>r(s,i,o)),i;let a={};n.add(a);let c=await s();return t?setTimeout(()=>n.delete(a),t):n.delete(a),o?(o(c),i):c};return {run:r}};});var Uu,jo,Mu=b(()=>{Eo();Uu=e=>e.length>1,jo=e=>e[Pn]?jo(e[Pn]):e;});var Bu,Yg,Qg,Zg,ey,jn,qu,Fo,Uo=b(()=>{ut();Mu();Bu=e=>e.split(/[\/\\]/).slice(0,-1).join("/"),Yg=e=>e.replace(/(\\)/g,"/").replace(/\/$/g,""),Qg=(e,t)=>{e.length===0||t?e.push(".."):e.pop();},Zg=(e,t)=>{e=e.replace(/^\.(?!.)/,""),e!==""&&t.push(e);},ey=(e,t)=>{let n=false;for(let r of e)r===".."?(Qg(t,n),n=true):(Zg(r,t),n=false);},jn=(...e)=>{e=e.map(Yg);let t=[];return ey(e.join("/").split("/"),t),(e[0][0]==="/"?"/":"")+t.join("/")},qu=e=>e.routes.reduce((t,{method:n,handler:r,path:s})=>{let i=jo(r);return ["GET",ne].includes(n)&&!Uu(i)&&t.push({path:s}),t},[]),Fo=e=>e.split("/").some(t=>t.startsWith(":")||t.includes("*"));});var Hu,ms,Mo=b(()=>{Uo();Hu="HONO_SSG_CONTEXT",ms="x-hono-disable-ssg",(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[ms]:"true"}})}catch{return null}})();});var Gu=b(()=>{wo();});var Bo,qo=b(()=>{Gu();Bo=()=>({afterResponseHook:e=>e.status!==200?false:e});});var ty,ny,ry,sy,iy,oy,ay,cy,ly,uy,py,Wu,fy,Vu,Ku=b(()=>{Du();Fu();Do();Mo();qo();Uo();ty=2,ny="text/plain",ry="./static",sy=(e,t,n,r)=>{let s=ay(n,r);return e.endsWith(`.${s}`)?jn(t,e):e==="/"?jn(t,`index.${s}`):e.endsWith("/")?jn(t,e,`index.${s}`):jn(t,`${e}.${s}`)},iy=async e=>{let t=e.headers.get("Content-Type");try{return t?.includes("text")||t?.includes("json")?await e.text():await e.arrayBuffer()}catch(n){throw new Error(`Error processing response: ${n instanceof Error?n.message:"Unknown error"}`)}},oy={"text/html":"html","text/xml":"xml","application/xml":"xml","application/yaml":"yaml"},ay=(e,t)=>{let n=t||oy;return e in n?n[e]:Au(e)||"html"},cy=e=>Array.isArray(e)?async t=>{let n=t;for(let r of e){let s=await r(n);if(s===false)return false;s instanceof Request&&(n=s);}return n}:e,ly=e=>Array.isArray(e)?async t=>{let n=t;for(let r of e){let s=await r(n);if(s===false)return false;s instanceof Response&&(n=s);}return n}:e,uy=(e,t,n)=>Array.isArray(e)?async r=>{for(let s of e)await s(r,t,n);}:e,py=function*(e,t,n,r){let s="http://localhost",i=ju({concurrency:r});for(let o of qu(e)){let a=new URL(o.path,s).toString(),c=new Request(a);yield new Promise(async(l,p)=>{try{if(t){let f=await t(c);if(!f){l(void 0);return}c=f;}if(await i.run(()=>e.fetch(c)),!c.ssgParams){if(Fo(o.path)){l(void 0);return}c.ssgParams=[{}];}let u={method:c.method,headers:c.headers};l((function*(){for(let f of c.ssgParams)yield new Promise(async(h,d)=>{try{let m=Iu(o.path,f),y=await i.run(()=>e.request(m,u,{[Hu]:!0}));if(y.headers.get(ms)){h(void 0);return}if(n){let A=await n(y);if(!A){h(void 0);return}y=A;}let g=y.headers.get("Content-Type")?.split(";")[0]||ny,E=await iy(y);h({routePath:m,mimeType:g,content:E});}catch(m){d(m);}});})());}catch(u){p(u);}});}},Wu=new Set,fy=async(e,t,n,r)=>{let s=await e;if(!s)return;let{routePath:i,content:o,mimeType:a}=s,c=sy(i,n,a,r),l=Bu(c);return Wu.has(l)||(await t.mkdir(l,{recursive:true}),Wu.add(l)),typeof o=="string"?await t.writeFile(c,o):o instanceof ArrayBuffer&&await t.writeFile(c,new Uint8Array(o)),c},Vu=async(e,t,n)=>{let r,s=[],i=[],o=n?.plugins||[Bo()],a=[],c=[],l=[];n?.beforeRequestHook&&a.push(...Array.isArray(n.beforeRequestHook)?n.beforeRequestHook:[n.beforeRequestHook]),n?.afterResponseHook&&c.push(...Array.isArray(n.afterResponseHook)?n.afterResponseHook:[n.afterResponseHook]),n?.afterGenerateHook&&l.push(...Array.isArray(n.afterGenerateHook)?n.afterGenerateHook:[n.afterGenerateHook]);for(let p of o)p.beforeRequestHook&&a.push(...Array.isArray(p.beforeRequestHook)?p.beforeRequestHook:[p.beforeRequestHook]),p.afterResponseHook&&c.push(...Array.isArray(p.afterResponseHook)?p.afterResponseHook:[p.afterResponseHook]),p.afterGenerateHook&&l.push(...Array.isArray(p.afterGenerateHook)?p.afterGenerateHook:[p.afterGenerateHook]);try{let p=n?.dir??ry,u=n?.concurrency??ty,f=cy(a.length>0?a:[y=>y]),h=ly(c.length>0?c:[y=>y]),d=py(e,f,h,u);for(let y of d)s.push(y.then(g=>{if(g)for(let E of g)i.push(fy(E,t,p,n?.extensionMap).catch(A=>A));}));await Promise.all(s);let m=[];for(let y of i){let g=await y;if(typeof g=="string")m.push(g);else if(g)throw g}r={success:!0,files:m};}catch(p){let u=p instanceof Error?p:new Error(String(p));r={success:false,files:[],error:u};}return l.length>0&&await uy(l,t,n)(r,t,n),r};});var zu=b(()=>{Ku();Mo();qo();});var my,Ho,Xu,Ju=b(()=>{zu();(({write:my}=Bun)),Ho={writeFile:async(e,t)=>{await my(e,t);},mkdir:async()=>{}},Xu=async(e,t)=>Vu(e,Ho,t);});var Yu,Qu,Zu,ep=b(()=>{Yu=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);}},Qu=e=>new MessageEvent("message",{data:e}),Zu=e=>((...t)=>{if(typeof t[0]=="function"){let[n,r]=t;return async function(i,o){let a=await n(i),c=await e(i,a,r);if(c)return c;await o();}}else {let[n,r,s]=t;return (async()=>{let i=await e(n,r,s);if(!i)throw new Error("Failed to upgrade WebSocket");return i})()}});});var Qt,ds=b(()=>{Qt=e=>"server"in e.env?e.env.server:e.env;});var Go,Wo,Vo,tp,np=b(()=>{ep();ds();Go=e=>new Yu({send:(t,n)=>{e.send(t,n?.compress);},raw:e,readyState:e.readyState,url:e.data.url,protocol:e.data.protocol,close(t,n){e.close(t,n);}}),Wo=Zu((e,t)=>{let n=Qt(e);if(!n)throw new TypeError("env has to include the 2nd argument of fetch.");if(n.upgrade(e.req.raw,{data:{events:t,url:new URL(e.req.url),protocol:e.req.url}}))return new Response(null)}),Vo={open(e){let t=e.data.events;t.onOpen&&t.onOpen(new Event("open"),Go(e));},close(e,t,n){let r=e.data.events;r.onClose&&r.onClose(new CloseEvent("close",{code:t,reason:n}),Go(e));},message(e,t){let n=e.data.events;if(n.onMessage){let r=typeof t=="string"?t:t.buffer;n.onMessage(Qu(r),Go(e));}}},tp=()=>({upgradeWebSocket:Wo,websocket:Vo});});var rp,sp=b(()=>{ds();rp=e=>{let t=Qt(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 n=t.requestIP(e.req.raw);return n?{remote:{address:n.address,addressType:n.family==="IPv6"||n.family==="IPv4"?n.family:void 0,port:n.port}}:{remote:{}}};});var ip={};pe(ip,{bunFileSystemModule:()=>Ho,createBunWebSocket:()=>tp,getBunServer:()=>Qt,getConnInfo:()=>rp,serveStatic:()=>Nu,toSSG:()=>Xu,upgradeWebSocket:()=>Wo,websocket:()=>Vo});var op=b(()=>{Lu();Ju();np();sp();ds();});async function hs(e,t={port:3e3}){if(e.config.auth?.enabled){let s=Dn(e.config.auth.jwt_secret);s.strong||console.warn(lp.default.yellow(`[auth] auth.jwt_secret is weak \u2014 do not use it in production:
63
66
  `+s.reasons.map(i=>` - it ${i}`).join(`
64
- `));}let r=Yn(),n=t.port??3e3;if(Ar()){let s=await Promise.resolve().then(()=>(op(),ip)).then(o=>o.serveStatic),i;try{i=Bun.serve({fetch:lp(e,r,s).fetch,port:n});}catch(o){throw ko(o)&&Oo(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:lp(e,r,i).fetch});try{await xu(o,n);}catch(a){throw ko(a)&&Oo(n),a}return ()=>new Promise(a=>{o.close(()=>{a(void 0);});})}}function lp(e,t,r){return new Ro().use("/favicon.ico",r({path:Fe__default.join(t,"static","favicon.ico")})).use("/fonts/*",r({root:Fe__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 Vo=b(()=>{ft();Eu();_u();$e();No();});var rt,zo=b(()=>{_t();rt=class e{root;constructor(t,r){let n=r??e.projectDir();this.root=Fe__default.join(n,t??"");}ensureRoot(){ke(this.root);}static homeDir(){return Fe__default.join(Xy.homedir(),".lite")}static projectDir(){return Fe__default.join(process.cwd(),"supabase")}deleteAll(t=false){try{Un.rmSync(this.root,{recursive:!0});}catch(r){if(!t)throw r}this.ensureRoot();}delete(t,r=false){try{Un.unlinkSync(Fe__default.join(this.root,t));}catch(n){if(!r)throw n}}write(t,r,n=false){try{this.ensureRoot(),Un.writeFileSync(Fe__default.join(this.root,t),r);}catch(s){if(!n)throw s}}read(t,r=false){try{return Un.readFileSync(Fe__default.join(this.root,t),"utf8")}catch(n){if(!r)throw n}}relativePath(t){return t?Fe__default.relative(process.cwd(),Fe__default.join(this.root,t)):this.root}path(t){return t?Fe__default.join(this.root,t):this.root}};});var Mr,Es,xs=b(()=>{Mr=process.env.LITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2001":"https://api.lite.dev"),Es=process.env.LITE_CLOUD_PROJECTS_URL??(process.env.LOCAL?"http://supalite.local":"https://lite.black");});var $s,cp=b(()=>{_t();$s=class{root;constructor(t){this.root=t??Fe__default.join(Xy.homedir(),".lite","auth"),ke(this.root);}async getItem(t){try{return Un.readFileSync(Fe__default.join(this.root,t+".json"),"utf8")}catch{return null}}async setItem(t,r){Un.writeFileSync(Fe__default.join(this.root,t+".json"),r);}async removeItem(t){try{Un.unlinkSync(Fe__default.join(this.root,t+".json"));}catch{return}}};});var rr,Xo=b(()=>{xs();zo();cp();rr=class{constructor(t){this.config=t;this.tempFs=new rt(".temp",this.config.root),this.projectFs=new rt("supabase",this.config.root),this.schemaFs=new rt("schemas",this.config.root),this.authStorage=this.config.authStorage??new $s(Fe__default.join(rt.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??Mr,process.env.LITE_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,Jo=b(()=>{Xo();xs();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.projectsHost??Es),s=n.hostname.replace(/^www\./,"");return `${n.protocol}//${r}.${s}${n.port?`:${n.port}`:""}`}};});function Zy(e){let t=Fe.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 vs,up=b(()=>{ft();vs=class{driver=fe;basePath;constructor(t){this.basePath=Fe.resolve(t.basePath);}filePath(t,r){return Fe.join(this.basePath,t,r)}async ensureDir(t){await fe.mkdir(Fe.dirname(t),{recursive:true});}async getObject(t,r,n,s){let i=this.filePath(t,r),o=await fe.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,p=o.size,u=200;if(s?.range){let f=s.range.match(/^bytes=(\d+)-(\d*)$/);if(f){let h=Number.parseInt(f[1],10),d=f[2]?Number.parseInt(f[2],10):o.size-1;p=d-h+1,c=`bytes ${h}-${d}/${o.size}`,u=206,l=(await fe.open(i,"r")).readableWebStream();}else l=(await fe.open(i,"r")).readableWebStream();}else l=(await fe.open(i,"r")).readableWebStream();return {httpStatusCode:u,metadata:{...this.buildMetadata(o,a,r),contentLength:p,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 u=[],f=s.getReader();for(;;){let{done:h,value:d}=await f.read();if(h)break;u.push(d);}l=Buffer.concat(u);}await fe.writeFile(a,l);let c=await fe.stat(a),p=`"${createHash("md5").update(l).digest("hex")}"`;return {cacheControl:o,contentLength:c.size,size:c.size,mimetype:i,lastModified:c.mtime,eTag:p}}async deleteObject(t,r,n){let s=this.filePath(t,r);await fe.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 fe.copyFile(o,a);let l=await fe.stat(a),c=await fe.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 fe.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:uo(t.size),size:uo(t.size),mimetype:Zy(n),lastModified:t.mtime,eTag:r}}};});async function He(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,sr=b(()=>{ew=new Function("spec","return import(spec)");});var Br,rw,Cs,fp=b(()=>{Jo();Xt();Br=te(ae());Tr();zt();up();sr();Wi();zi();Jt();rw=["toml","json","ts","mts","js","mjs","cjs"],Cs=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=Fe__default.relative(process.cwd(),we.config_dir);if(!t)for(let n of rw){let s=Fe__default.join(r,`config.${n}`);if(await fe__default.access(s).then(()=>true).catch(()=>false)){t=s;break}}return t}async readConfig(t){let r=await this.getConfigPath(t);if(!r)return {};Qe(Br.default.dim(`Using config file: ${Br.default.cyan(`./${r}`)}`));let n=Fe__default.dirname(Fe__default.resolve(r));Wn(n);let s=r.split(".").pop(),i;switch(s){case "toml":i=Tt(await fe__default.readFile(r,"utf-8"));break;case "json":i=JSON.parse(await fe__default.readFile(r,"utf-8"));break;case "ts":case "mts":case "js":case "mjs":case "cjs":try{i=(await import(Fe__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 Vn(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??we.default_db_url,n=await createConnection({url:s,ddlDialect:"sqlite"});break;case "pglite":{s=r.db?.url??Fe__default.join(process.cwd(),we.default_db_dir);let{createPgliteConnection:i}=await He("@supabase/lite/pglite","pglite","@electric-sql/pglite");n=await i({url:s});break}case "postgres":{s=r.db?.url??"";let{createPostgresConnection:i}=await He("@supabase/lite/postgres","postgres","postgres");n=await i({url:s});break}default:s=r.db?.url??we.default_db_url,n=await createConnection({url:s,ddlDialect:"postgres"});break}if(!n)throw new Error("Failed to create connection");return Qe(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 vs({basePath:Fe__default.join(process.cwd(),we.config_dir,".temp/storage")})),await n.init()}};});var As,mp=b(()=>{Jo();As=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(!Array.isArray(r))throw new Error("Failed to list projects");return r}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){if(!t.name)throw new Error("Project name is required");let r=await this.fetch("/v1/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let s=await r.text().catch(()=>"");throw new Error(`Failed to create project: ${r.status} ${r.statusText}${s?` \u2014 ${s}`:""}`)}let n=await r.json();if(!n||!n.id)throw new Error("Failed to create project");return n}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 Rs,dp=b(()=>{Xo();fp();mp();Rs=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 Cs(t),remote:new As(t)},this}};});async function V(e={}){return await new Rs({host:Mr,projectsHost:Es,root:rt.projectDir(),...e}).init()}var Ae=b(()=>{zo();xs();dp();});var hp={};de(hp,{start:()=>iw});var qr,iw,gp=b(()=>{Vo();ft();qr=te(ae());Xt();Ae();$e();zt();iw=e=>{e.command("start").option("--config <config>","Path to the config file").description("Start the development server").helpGroup("Local Development:").action(async t=>{await Q(t.config),await ts(async()=>{let n=await(await V({withSupabaseClient:false})).project.local.createApp(t.config),s=n.config.api?.port??we.default_api_port;await bs(n,{port:s});console.log(qr.default.green(" \u279C"),"Server running on ",qr.default.cyan(`http://localhost:${s}`));let o=Fn();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 fw(e){let t=normalize(e);return t.length>1&&t[t.length-1]===sep&&(t=t.substring(0,t.length-1)),t}function Sp(e,t){return e.replace(mw,t)}function hw(e){return e==="/"||dw.test(e)}function Qo(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=fw(e)),e===".")return "";let o=e[e.length-1]!==s;return Sp(o?e+s:e,s)}function Ep(e,t){return t+e}function gw(e,t){return function(r,n){return n.startsWith(e)?n.slice(e.length)+r:Sp(relative(e,n),t.pathSeparator)+t.pathSeparator+r}}function yw(e){return e}function ww(e,t,r){return t+e+r}function bw(e,t){let{relativePaths:r,includeBasePath:n}=t;return r&&e?gw(e,t):n?Ep:yw}function Sw(e){return function(t,r){r.push(t.substring(e.length)||".");}}function Ew(e){return function(t,r,n){let s=t.substring(e.length)||".";n.every(i=>i(s,true))&&r.push(s);}}function Tw(e,t){let{includeDirs:r,filters:n,relativePaths:s}=t;return r?s?n&&n.length?Ew(e):Sw(e):n&&n.length?_w:xw:$w}function Ow(e){let{excludeFiles:t,filters:r,onlyCounts:n}=e;return t?kw:r&&r.length?n?vw:Cw:n?Aw:Rw}function Lw(e){return e.group?Pw:Nw}function jw(e){return e.group?Iw:Dw}function Mw(e,t){return !e.resolveSymlinks||e.excludeSymlinks?null:t?Uw:Fw}function xp(e,t,r){if(r.options.useRealPaths)return Bw(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 Bw(e,t){return t.visited.includes(e+t.options.pathSeparator)}function ks(e,t,r,n){t(e&&!n?e:null,r);}function Jw(e,t){let{onlyCounts:r,group:n,maxFiles:s}=e;return r?t?qw:Vw:n?t?Hw:Xw:s?t?Ww:Kw:t?Gw:zw}function Zw(e){return e?Qw:Yw}function nb(e,t){return new Promise((r,n)=>{Tp(e,t,(s,i)=>{if(s)return n(s);r(i);});})}function Tp(e,t,r){new $p(e,t,r).start();}function sb(e,t){return new $p(e,t).start()}var yp,mw,dw,xw,_w,$w,vw,Cw,Aw,Rw,kw,Nw,Pw,Iw,Dw,Fw,Uw,qw,Hw,Gw,Ww,Vw,zw,Kw,Xw,_p,Yw,Qw,eb,tb,rb,$p,wp,vp,Cp,Ap=b(()=>{yp=createRequire(import.meta.url);mw=/[\\/]/g;dw=/^[a-z]:[\\/]$/i;xw=(e,t)=>{t.push(e||".");},_w=(e,t,r)=>{let n=e||".";r.every(s=>s(n,true))&&t.push(n);},$w=()=>{};vw=(e,t,r,n)=>{n.every(s=>s(e,false))&&r.files++;},Cw=(e,t,r,n)=>{n.every(s=>s(e,false))&&t.push(e);},Aw=(e,t,r,n)=>{r.files++;},Rw=(e,t)=>{t.push(e);},kw=()=>{};Nw=e=>e,Pw=()=>[""].slice(0,0);Iw=(e,t,r)=>{e.push({directory:t,files:r,dir:t});},Dw=()=>{};Fw=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()&&xp(e,a,t))return n.dequeue(null,t);r(c,a),n.dequeue(null,t);});});},Uw=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()&&xp(e,o,t))return;r(a,o);}catch(o){if(!i)throw o}};qw=e=>e.counts,Hw=e=>e.groups,Gw=e=>e.paths,Ww=e=>e.paths.slice(0,e.options.maxFiles),Vw=(e,t,r)=>(ks(t,r,e.counts,e.options.suppressErrors),null),zw=(e,t,r)=>(ks(t,r,e.paths,e.options.suppressErrors),null),Kw=(e,t,r)=>(ks(t,r,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),Xw=(e,t,r)=>(ks(t,r,e.groups,e.options.suppressErrors),null);_p={withFileTypes:true},Yw=(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||".",_p,(o,a=[])=>{s(a,r,n),e.queue.dequeue(e.options.suppressErrors?null:o,e);});},Qw=(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||".",_p);}catch(a){if(!e.options.suppressErrors)throw a}s(o,r,n);};eb=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}},rb=class{aborted=false;abort(){this.aborted=true;}},$p=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(e,t,r){this.isSynchronous=!r,this.callbackInvoker=Jw(t,this.isSynchronous),this.root=Qo(e,t),this.state={root:hw(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new tb,options:t,queue:new eb((n,s)=>this.callbackInvoker(s,n,r)),symlinks:new Map,visited:[""].slice(0,0),controller:new rb,fs:t.fs||pw},this.joinPath=bw(this.root,t),this.pushDirectory=Tw(this.root,t),this.pushFile=Ow(t),this.getArray=Lw(t),this.groupFiles=jw(t),this.resolveSymlink=Mw(t,this.isSynchronous),this.walkDirectory=Zw(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:p,pathSeparator:u},controller:f}=this.state;if(f.aborted||c&&c.aborted||l&&n.length>l)return;let h=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,h,this.state.counts,s);}else if(m.isDirectory()){let y=ww(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=Ep(m.name,t);this.resolveSymlink(y,this.state,(g,E)=>{if(g.isDirectory()){if(E=Qo(E,this.state.options),a&&a(m.name,p?E:y+u))return;this.walkDirectory(this.state,E,p?E:y+u,r-1,this.walk);}else {E=p?E:y;let v=basename(E),T=Qo(dirname(E),this.state.options);E=this.joinPath(v,T),this.pushFile(E,h,this.state.counts,s);}});}}this.groupFiles(this.state.groups,t,h);}};wp=class{constructor(e,t){this.root=e,this.options=t;}withPromise(){return nb(this.root,this.options)}withCallback(e){Tp(this.root,this.options,e);}sync(){return sb(this.root,this.options)}},vp=null;try{yp.resolve("picomatch"),vp=yp("picomatch");}catch{}Cp=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 wp(e||".",this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new wp(e||".",this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:true})}globWithOptions(e,...t){let r=this.globFunction||vp;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=ut((rA,Pp)=>{var Rp="[^\\\\/]",ib="(?=.)",kp="[^/]",ea="(?:\\/|$)",Op="(?:^|\\/)",ta=`\\.{1,2}${ea}`,ob="(?!\\.)",ab=`(?!${Op}${ta})`,lb=`(?!\\.{0,1}${ea})`,cb=`(?!${ta})`,ub="[^.\\/]",pb=`${kp}*?`,fb="/",Np={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:ib,QMARK:kp,END_ANCHOR:ea,DOTS_SLASH:ta,NO_DOT:ob,NO_DOTS:ab,NO_DOT_SLASH:lb,NO_DOTS_SLASH:cb,QMARK_NO_DOT:ub,STAR:pb,START_ANCHOR:Op,SEP:fb},mb={...Np,SLASH_LITERAL:"[\\\\/]",QMARK:Rp,STAR:`${Rp}*?`,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:"\\"},db={__proto__:null,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"};Pp.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:db,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?mb:Np}};});var Gr=ut(Ne=>{var{REGEX_BACKSLASH:hb,REGEX_REMOVE_BACKSLASH:gb,REGEX_SPECIAL_CHARS:yb,REGEX_SPECIAL_CHARS_GLOBAL:wb}=Hr();Ne.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);Ne.hasRegexChars=e=>yb.test(e);Ne.isRegexChar=e=>e.length===1&&Ne.hasRegexChars(e);Ne.escapeRegex=e=>e.replace(wb,"\\$1");Ne.toPosixSlashes=e=>e.replace(hb,"/");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(gb,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 Bp=ut((sA,Mp)=>{var Lp=Gr(),{CHAR_ASTERISK:ra,CHAR_AT:bb,CHAR_BACKWARD_SLASH:Wr,CHAR_COMMA:Sb,CHAR_DOT:na,CHAR_EXCLAMATION_MARK:sa,CHAR_FORWARD_SLASH:Up,CHAR_LEFT_CURLY_BRACE:ia,CHAR_LEFT_PARENTHESES:oa,CHAR_LEFT_SQUARE_BRACKET:Eb,CHAR_PLUS:xb,CHAR_QUESTION_MARK:Ip,CHAR_RIGHT_CURLY_BRACE:_b,CHAR_RIGHT_PARENTHESES:Dp,CHAR_RIGHT_SQUARE_BRACKET:$b}=Hr(),jp=e=>e===Up||e===Wr,Fp=e=>{e.isPrefix!==true&&(e.depth=e.isGlobstar?1/0:1);},Tb=(e,t)=>{let r=t||{},n=e.length-1,s=r.parts===true||r.scanToEnd===true,i=[],o=[],a=[],l=e,c=-1,p=0,u=0,f=false,h=false,d=false,m=false,y=false,g=false,E=false,v=false,T=false,A=false,C=0,$,_,L={value:"",depth:0,isGlob:false},w=()=>c>=n,D=()=>l.charCodeAt(c+1),N=()=>($=_,l.charCodeAt(++c));for(;c<n;){_=N();let q;if(_===Wr){E=L.backslashes=true,_=N(),_===ia&&(g=true);continue}if(g===true||_===ia){for(C++;w()!==true&&(_=N());){if(_===Wr){E=L.backslashes=true,N();continue}if(_===ia){C++;continue}if(g!==true&&_===na&&(_=N())===na){if(f=L.isBrace=true,d=L.isGlob=true,A=true,s===true)continue;break}if(g!==true&&_===Sb){if(f=L.isBrace=true,d=L.isGlob=true,A=true,s===true)continue;break}if(_===_b&&(C--,C===0)){g=false,f=L.isBrace=true,A=true;break}}if(s===true)continue;break}if(_===Up){if(i.push(c),o.push(L),L={value:"",depth:0,isGlob:false},A===true)continue;if($===na&&c===p+1){p+=2;continue}u=c+1;continue}if(r.noext!==true&&(_===xb||_===bb||_===ra||_===Ip||_===sa)===true&&D()===oa){if(d=L.isGlob=true,m=L.isExtglob=true,A=true,_===sa&&c===p&&(T=true),s===true){for(;w()!==true&&(_=N());){if(_===Wr){E=L.backslashes=true,_=N();continue}if(_===Dp){d=L.isGlob=true,A=true;break}}continue}break}if(_===ra){if($===ra&&(y=L.isGlobstar=true),d=L.isGlob=true,A=true,s===true)continue;break}if(_===Ip){if(d=L.isGlob=true,A=true,s===true)continue;break}if(_===Eb){for(;w()!==true&&(q=N());){if(q===Wr){E=L.backslashes=true,N();continue}if(q===$b){h=L.isBracket=true,d=L.isGlob=true,A=true;break}}if(s===true)continue;break}if(r.nonegate!==true&&_===sa&&c===p){v=L.negated=true,p++;continue}if(r.noparen!==true&&_===oa){if(d=L.isGlob=true,s===true){for(;w()!==true&&(_=N());){if(_===oa){E=L.backslashes=true,_=N();continue}if(_===Dp){A=true;break}}continue}break}if(d===true){if(A=true,s===true)continue;break}}r.noext===true&&(m=false,d=false);let F=l,S="",x="";p>0&&(S=l.slice(0,p),l=l.slice(p),u-=p),F&&d===true&&u>0?(F=l.slice(0,u),x=l.slice(u)):d===true?(F="",x=l):F=l,F&&F!==""&&F!=="/"&&F!==l&&jp(F.charCodeAt(F.length-1))&&(F=F.slice(0,-1)),r.unescape===true&&(x&&(x=Lp.removeBackslashes(x)),F&&E===true&&(F=Lp.removeBackslashes(F)));let Y={prefix:S,input:e,start:p,base:F,glob:x,isBrace:f,isBracket:h,isGlob:d,isExtglob:m,isGlobstar:y,negated:v,negatedExtglob:T};if(r.tokens===true&&(Y.maxDepth=0,jp(_)||o.push(L),Y.tokens=o),r.parts===true||r.tokens===true){let q;for(let j=0;j<i.length;j++){let ie=q?q+1:p,ue=i[j],lt=e.slice(ie,ue);r.tokens&&(j===0&&p!==0?(o[j].isPrefix=true,o[j].value=S):o[j].value=lt,Fp(o[j]),Y.maxDepth+=o[j].depth),(j!==0||lt!=="")&&a.push(lt),q=ue;}if(q&&q+1<e.length){let j=e.slice(q+1);a.push(j),r.tokens&&(o[o.length-1].value=j,Fp(o[o.length-1]),Y.maxDepth+=o[o.length-1].depth);}Y.slashes=i,Y.parts=a;}return Y};Mp.exports=Tb;});var Vp=ut((iA,Wp)=>{var Vr=Hr(),Le=Gr(),{MAX_LENGTH:Os,POSIX_REGEX_SOURCE:vb,REGEX_NON_SPECIAL_CHARS:Cb,REGEX_SPECIAL_CHARS_BACKREF:Ab,REPLACEMENTS:qp}=Vr,Rb=(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=>Le.escapeRegex(s)).join("..")}return r},ir=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,Hp=e=>{let t=[],r=0,n=0,s=0,i="",o=false;for(let a of e){if(o===true){i+=a,o=false;continue}if(a==="\\"){i+=a,o=true;continue}if(a==='"'){s=s===1?0:1,i+=a;continue}if(s===0){if(a==="[")r++;else if(a==="]"&&r>0)r--;else if(r===0){if(a==="(")n++;else if(a===")"&&n>0)n--;else if(a==="|"&&n===0){t.push(i),i="";continue}}}i+=a;}return t.push(i),t},kb=e=>{let t=false;for(let r of e){if(t===true){t=false;continue}if(r==="\\"){t=true;continue}if(/[?*+@!()[\]{}]/.test(r))return false}return true},Gp=e=>{let t=e.trim(),r=true;for(;r===true;)r=false,/^@\([^\\()[\]{}|]+\)$/.test(t)&&(t=t.slice(2,-1),r=true);if(kb(t))return t.replace(/\\(.)/g,"$1")},Ob=e=>{let t=e.map(Gp).filter(Boolean);for(let r=0;r<t.length;r++)for(let n=r+1;n<t.length;n++){let s=t[r],i=t[n],o=s[0];if(!(!o||s!==o.repeat(s.length)||i!==o.repeat(i.length))&&(s===i||s.startsWith(i)||i.startsWith(s)))return true}return false},aa=(e,t=true)=>{if(e[0]!=="+"&&e[0]!=="*"||e[1]!=="(")return;let r=0,n=0,s=0,i=false;for(let o=1;o<e.length;o++){let a=e[o];if(i===true){i=false;continue}if(a==="\\"){i=true;continue}if(a==='"'){s=s===1?0:1;continue}if(s!==1){if(a==="["){r++;continue}if(a==="]"&&r>0){r--;continue}if(!(r>0)){if(a==="("){n++;continue}if(a===")"&&(n--,n===0))return t===true&&o!==e.length-1?void 0:{type:e[0],body:e.slice(2,o),end:o}}}}},Nb=e=>{let t=0,r=[];for(;t<e.length;){let s=aa(e.slice(t),false);if(!s||s.type!=="*")return;let i=Hp(s.body).map(a=>a.trim());if(i.length!==1)return;let o=Gp(i[0]);if(!o||o.length!==1)return;r.push(o),t+=s.end+1;}return r.length<1?void 0:`${r.length===1?Le.escapeRegex(r[0]):`[${r.map(s=>Le.escapeRegex(s)).join("")}]`}*`},Pb=e=>{let t=0,r=e.trim(),n=aa(r);for(;n;)t++,r=n.body.trim(),n=aa(r);return t},Lb=(e,t)=>{if(t.maxExtglobRecursion===false)return {risky:false};let r=typeof t.maxExtglobRecursion=="number"?t.maxExtglobRecursion:Vr.DEFAULT_MAX_EXTGLOB_RECURSION,n=Hp(e).map(s=>s.trim());if(n.length>1&&(n.some(s=>s==="")||n.some(s=>/^[*?]+$/.test(s))||Ob(n)))return {risky:true};for(let s of n){let i=Nb(s);if(i)return {risky:true,safeOutput:i};if(Pb(s)>r)return {risky:true}}return {risky:false}},la=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=qp[e]||e;let r={...t},n=typeof r.maxLength=="number"?Math.min(Os,r.maxLength):Os,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=Vr.globChars(r.windows),c=Vr.extglobChars(l),{DOT_LITERAL:p,PLUS_LITERAL:u,SLASH_LITERAL:f,ONE_CHAR:h,DOTS_SLASH:d,NO_DOT:m,NO_DOT_SLASH:y,NO_DOTS_SLASH:g,QMARK:E,QMARK_NO_DOT:v,STAR:T,START_ANCHOR:A}=l,C=O=>`(${a}(?:(?!${A}${O.dot?d:p}).)*?)`,$=r.dot?"":m,_=r.dot?E:v,L=r.bash===true?C(r):T;r.capture&&(L=`(${L})`),typeof r.noext=="boolean"&&(r.noextglob=r.noext);let w={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=Le.removePrefix(e,w),s=e.length;let D=[],N=[],F=[],S=i,x,Y=()=>w.index===s-1,q=w.peek=(O=1)=>e[w.index+O],j=w.advance=()=>e[++w.index]||"",ie=()=>e.slice(w.index+1),ue=(O="",oe=0)=>{w.consumed+=O,w.index+=oe;},lt=O=>{w.output+=O.output!=null?O.output:O.value,ue(O.value);},uh=()=>{let O=1;for(;q()==="!"&&(q(2)!=="("||q(3)==="?");)j(),w.start++,O++;return O%2===0?false:(w.negated=true,w.start++,true)},Ln=O=>{w[O]++,F.push(O);},ct=O=>{w[O]--,F.pop();},G=O=>{if(S.type==="globstar"){let oe=w.braces>0&&(O.type==="comma"||O.type==="brace"),R=O.extglob===true||D.length&&(O.type==="pipe"||O.type==="paren");O.type!=="slash"&&O.type!=="paren"&&!oe&&!R&&(w.output=w.output.slice(0,-S.output.length),S.type="star",S.value="*",S.output=L,w.output+=S.output);}if(D.length&&O.type!=="paren"&&(D[D.length-1].inner+=O.value),(O.value||O.output)&&lt(O),S&&S.type==="text"&&O.type==="text"){S.output=(S.output||S.value)+O.value,S.value+=O.value;return}O.prev=S,o.push(O),S=O;},In=(O,oe)=>{let R={...c[oe],conditions:1,inner:""};R.prev=S,R.parens=w.parens,R.output=w.output,R.startIndex=w.index,R.tokensIndex=o.length;let W=(r.capture?"(":"")+R.open;Ln("parens"),G({type:O,value:oe,output:w.output?"":h}),G({type:"paren",extglob:true,value:j(),output:W}),D.push(R);},ph=O=>{let oe=e.slice(O.startIndex,w.index+1),R=e.slice(O.startIndex+2,w.index),W=Lb(R,r);if((O.type==="plus"||O.type==="star")&&W.risky){let ee=W.safeOutput?(O.output?"":h)+(r.capture?`(${W.safeOutput})`:W.safeOutput):void 0,Ve=o[O.tokensIndex];Ve.type="text",Ve.value=oe,Ve.output=ee||Le.escapeRegex(oe);for(let ze=O.tokensIndex+1;ze<o.length;ze++)o[ze].value="",o[ze].output="",delete o[ze].suffix;w.output=O.output+Ve.output,w.backtrack=true,G({type:"paren",extglob:true,value:x,output:""}),ct("parens");return}let ne=O.close+(r.capture?")":""),me;if(O.type==="negate"){let ee=L;if(O.inner&&O.inner.length>1&&O.inner.includes("/")&&(ee=C(r)),(ee!==L||Y()||/^\)+$/.test(ie()))&&(ne=O.close=`)$))${ee}`),O.inner.includes("*")&&(me=ie())&&/^\.[^\\/.]+$/.test(me)){let Ve=la(me,{...t,fastpaths:false}).output;ne=O.close=`)${Ve})${ee})`;}O.prev.type==="bos"&&(w.negatedExtglob=true);}G({type:"paren",extglob:true,value:x,output:ne}),ct("parens");};if(r.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let O=false,oe=e.replace(Ab,(R,W,ne,me,ee,Ve)=>me==="\\"?(O=true,R):me==="?"?W?W+me+(ee?E.repeat(ee.length):""):Ve===0?_+(ee?E.repeat(ee.length):""):E.repeat(ne.length):me==="."?p.repeat(ne.length):me==="*"?W?W+me+(ee?L:""):L:W?R:`\\${R}`);return O===true&&(r.unescape===true?oe=oe.replace(/\\/g,""):oe=oe.replace(/\\+/g,R=>R.length%2===0?"\\\\":R?"\\":"")),oe===e&&r.contains===true?(w.output=e,w):(w.output=Le.wrapOutput(oe,w,t),w)}for(;!Y();){if(x=j(),x==="\0")continue;if(x==="\\"){let R=q();if(R==="/"&&r.bash!==true||R==="."||R===";")continue;if(!R){x+="\\",G({type:"text",value:x});continue}let W=/^\\+/.exec(ie()),ne=0;if(W&&W[0].length>2&&(ne=W[0].length,w.index+=ne,ne%2!==0&&(x+="\\")),r.unescape===true?x=j():x+=j(),w.brackets===0){G({type:"text",value:x});continue}}if(w.brackets>0&&(x!=="]"||S.value==="["||S.value==="[^")){if(r.posix!==false&&x===":"){let R=S.value.slice(1);if(R.includes("[")&&(S.posix=true,R.includes(":"))){let W=S.value.lastIndexOf("["),ne=S.value.slice(0,W),me=S.value.slice(W+2),ee=vb[me];if(ee){S.value=ne+ee,w.backtrack=true,j(),!i.output&&o.indexOf(S)===1&&(i.output=h);continue}}}(x==="["&&q()!==":"||x==="-"&&q()==="]")&&(x=`\\${x}`),x==="]"&&(S.value==="["||S.value==="[^")&&(x=`\\${x}`),r.posix===true&&x==="!"&&S.value==="["&&(x="^"),S.value+=x,lt({value:x});continue}if(w.quotes===1&&x!=='"'){x=Le.escapeRegex(x),S.value+=x,lt({value:x});continue}if(x==='"'){w.quotes=w.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(w.parens===0&&r.strictBrackets===true)throw new SyntaxError(ir("opening","("));let R=D[D.length-1];if(R&&w.parens===R.parens+1){ph(D.pop());continue}G({type:"paren",value:x,output:w.parens?")":"\\)"}),ct("parens");continue}if(x==="["){if(r.nobracket===true||!ie().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||S&&S.type==="bracket"&&S.value.length===1){G({type:"text",value:x,output:`\\${x}`});continue}if(w.brackets===0){if(r.strictBrackets===true)throw new SyntaxError(ir("opening","["));G({type:"text",value:x,output:`\\${x}`});continue}ct("brackets");let R=S.value.slice(1);if(S.posix!==true&&R[0]==="^"&&!R.includes("/")&&(x=`/${x}`),S.value+=x,lt({value:x}),r.literalBrackets===false||Le.hasRegexChars(R))continue;let W=Le.escapeRegex(S.value);if(w.output=w.output.slice(0,-S.value.length),r.literalBrackets===true){w.output+=W,S.value=W;continue}S.value=`(${a}${W}|${S.value})`,w.output+=S.value;continue}if(x==="{"&&r.nobrace!==true){Ln("braces");let R={type:"brace",value:x,output:"(",outputIndex:w.output.length,tokensIndex:w.tokens.length};N.push(R),G(R);continue}if(x==="}"){let R=N[N.length-1];if(r.nobrace===true||!R){G({type:"text",value:x,output:x});continue}let W=")";if(R.dots===true){let ne=o.slice(),me=[];for(let ee=ne.length-1;ee>=0&&(o.pop(),ne[ee].type!=="brace");ee--)ne[ee].type!=="dots"&&me.unshift(ne[ee].value);W=Rb(me,r),w.backtrack=true;}if(R.comma!==true&&R.dots!==true){let ne=w.output.slice(0,R.outputIndex),me=w.tokens.slice(R.tokensIndex);R.value=R.output="\\{",x=W="\\}",w.output=ne;for(let ee of me)w.output+=ee.output||ee.value;}G({type:"brace",value:x,output:W}),ct("braces"),N.pop();continue}if(x==="|"){D.length>0&&D[D.length-1].conditions++,G({type:"text",value:x});continue}if(x===","){let R=x,W=N[N.length-1];W&&F[F.length-1]==="braces"&&(W.comma=true,R="|"),G({type:"comma",value:x,output:R});continue}if(x==="/"){if(S.type==="dot"&&w.index===w.start+1){w.start=w.index+1,w.consumed="",w.output="",o.pop(),S=i;continue}G({type:"slash",value:x,output:f});continue}if(x==="."){if(w.braces>0&&S.type==="dot"){S.value==="."&&(S.output=p);let R=N[N.length-1];S.type="dots",S.output+=x,S.value+=x,R.dots=true;continue}if(w.braces+w.parens===0&&S.type!=="bos"&&S.type!=="slash"){G({type:"text",value:x,output:p});continue}G({type:"dot",value:x,output:p});continue}if(x==="?"){if(!(S&&S.value==="(")&&r.noextglob!==true&&q()==="("&&q(2)!=="?"){In("qmark",x);continue}if(S&&S.type==="paren"){let W=q(),ne=x;(S.value==="("&&!/[!=<:]/.test(W)||W==="<"&&!/<([!=]|\w+>)/.test(ie()))&&(ne=`\\${x}`),G({type:"text",value:x,output:ne});continue}if(r.dot!==true&&(S.type==="slash"||S.type==="bos")){G({type:"qmark",value:x,output:v});continue}G({type:"qmark",value:x,output:E});continue}if(x==="!"){if(r.noextglob!==true&&q()==="("&&(q(2)!=="?"||!/[!=<:]/.test(q(3)))){In("negate",x);continue}if(r.nonegate!==true&&w.index===0){uh();continue}}if(x==="+"){if(r.noextglob!==true&&q()==="("&&q(2)!=="?"){In("plus",x);continue}if(S&&S.value==="("||r.regex===false){G({type:"plus",value:x,output:u});continue}if(S&&(S.type==="bracket"||S.type==="paren"||S.type==="brace")||w.parens>0){G({type:"plus",value:x});continue}G({type:"plus",value:u});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 R=Cb.exec(ie());R&&(x+=R[0],w.index+=R[0].length),G({type:"text",value:x});continue}if(S&&(S.type==="globstar"||S.star===true)){S.type="star",S.star=true,S.value+=x,S.output=L,w.backtrack=true,w.globstar=true,ue(x);continue}let O=ie();if(r.noextglob!==true&&/^\([^?]/.test(O)){In("star",x);continue}if(S.type==="star"){if(r.noglobstar===true){ue(x);continue}let R=S.prev,W=R.prev,ne=R.type==="slash"||R.type==="bos",me=W&&(W.type==="star"||W.type==="globstar");if(r.bash===true&&(!ne||O[0]&&O[0]!=="/")){G({type:"star",value:x,output:""});continue}let ee=w.braces>0&&(R.type==="comma"||R.type==="brace"),Ve=D.length&&(R.type==="pipe"||R.type==="paren");if(!ne&&R.type!=="paren"&&!ee&&!Ve){G({type:"star",value:x,output:""});continue}for(;O.slice(0,3)==="/**";){let ze=e[w.index+4];if(ze&&ze!=="/")break;O=O.slice(3),ue("/**",3);}if(R.type==="bos"&&Y()){S.type="globstar",S.value+=x,S.output=C(r),w.output=S.output,w.globstar=true,ue(x);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&!me&&Y()){w.output=w.output.slice(0,-(R.output+S.output).length),R.output=`(?:${R.output}`,S.type="globstar",S.output=C(r)+(r.strictSlashes?")":"|$)"),S.value+=x,w.globstar=true,w.output+=R.output+S.output,ue(x);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&O[0]==="/"){let ze=O[1]!==void 0?"|$":"";w.output=w.output.slice(0,-(R.output+S.output).length),R.output=`(?:${R.output}`,S.type="globstar",S.output=`${C(r)}${f}|${f}${ze})`,S.value+=x,w.output+=R.output+S.output,w.globstar=true,ue(x+j()),G({type:"slash",value:"/",output:""});continue}if(R.type==="bos"&&O[0]==="/"){S.type="globstar",S.value+=x,S.output=`(?:^|${f}|${C(r)}${f})`,w.output=S.output,w.globstar=true,ue(x+j()),G({type:"slash",value:"/",output:""});continue}w.output=w.output.slice(0,-S.output.length),S.type="globstar",S.output=C(r),S.value+=x,w.output+=S.output,w.globstar=true,ue(x);continue}let oe={type:"star",value:x,output:L};if(r.bash===true){oe.output=".*?",(S.type==="bos"||S.type==="slash")&&(oe.output=$+oe.output),G(oe);continue}if(S&&(S.type==="bracket"||S.type==="paren")&&r.regex===true){oe.output=x,G(oe);continue}(w.index===w.start||S.type==="slash"||S.type==="dot")&&(S.type==="dot"?(w.output+=y,S.output+=y):r.dot===true?(w.output+=g,S.output+=g):(w.output+=$,S.output+=$),q()!=="*"&&(w.output+=h,S.output+=h)),G(oe);}for(;w.brackets>0;){if(r.strictBrackets===true)throw new SyntaxError(ir("closing","]"));w.output=Le.escapeLast(w.output,"["),ct("brackets");}for(;w.parens>0;){if(r.strictBrackets===true)throw new SyntaxError(ir("closing",")"));w.output=Le.escapeLast(w.output,"("),ct("parens");}for(;w.braces>0;){if(r.strictBrackets===true)throw new SyntaxError(ir("closing","}"));w.output=Le.escapeLast(w.output,"{"),ct("braces");}if(r.strictSlashes!==true&&(S.type==="star"||S.type==="bracket")&&G({type:"maybe_slash",value:"",output:`${f}?`}),w.backtrack===true){w.output="";for(let O of w.tokens)w.output+=O.output!=null?O.output:O.value,O.suffix&&(w.output+=O.suffix);}return w};la.fastpaths=(e,t)=>{let r={...t},n=typeof r.maxLength=="number"?Math.min(Os,r.maxLength):Os,s=e.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);e=qp[e]||e;let{DOT_LITERAL:i,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:l,NO_DOT:c,NO_DOTS:p,NO_DOTS_SLASH:u,STAR:f,START_ANCHOR:h}=Vr.globChars(r.windows),d=r.dot?p:c,m=r.dot?u:c,y=r.capture?"":"?:",g={negated:false,prefix:""},E=r.bash===true?".*?":f;r.capture&&(E=`(${E})`);let v=$=>$.noglobstar===true?E:`(${y}(?:(?!${h}${$.dot?l:i}).)*?)`,T=$=>{switch($){case "*":return `${d}${a}${E}`;case ".*":return `${i}${a}${E}`;case "*.*":return `${d}${E}${i}${a}${E}`;case "*/*":return `${d}${E}${o}${a}${m}${E}`;case "**":return d+v(r);case "**/*":return `(?:${d}${v(r)}${o})?${m}${a}${E}`;case "**/*.*":return `(?:${d}${v(r)}${o})?${m}${E}${i}${a}${E}`;case "**/.*":return `(?:${d}${v(r)}${o})?${i}${a}${E}`;default:{let _=/^(.*?)\.(\w+)$/.exec($);if(!_)return;let L=T(_[1]);return L?L+i+_[2]:void 0}}},A=Le.removePrefix(e,g),C=T(A);return C&&r.strictSlashes!==true&&(C+=`${o}?`),C};Wp.exports=la;});var Xp=ut((oA,Kp)=>{var Ib=Bp(),ca=Vp(),zp=Gr(),Db=Hr(),jb=e=>e&&typeof e=="object"&&!Array.isArray(e),pe=(e,t,r=false)=>{if(Array.isArray(e)){let p=e.map(f=>pe(f,t,r));return f=>{for(let h of p){let d=h(f);if(d)return d}return false}}let n=jb(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?pe.compileRe(e,t):pe.makeRe(e,t,false,true),a=o.state;delete o.state;let l=()=>false;if(s.ignore){let p={...t,ignore:null,onMatch:null,onResult:null};l=pe(s.ignore,p,r);}let c=(p,u=false)=>{let{isMatch:f,match:h,output:d}=pe.test(p,o,t,{glob:e,posix:i}),m={glob:e,state:a,regex:o,posix:i,input:p,output:d,match:h,isMatch:f};return typeof s.onResult=="function"&&s.onResult(m),f===false?(m.isMatch=false,u?m:false):l(p)?(typeof s.onIgnore=="function"&&s.onIgnore(m),m.isMatch=false,u?m:false):(typeof s.onMatch=="function"&&s.onMatch(m),u?m:true)};return r&&(c.state=a),c};pe.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?zp.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=pe.matchBase(e,t,r,s):a=t.exec(l)),{isMatch:!!a,match:a,output:l}};pe.matchBase=(e,t,r)=>(t instanceof RegExp?t:pe.makeRe(t,r)).test(zp.basename(e));pe.isMatch=(e,t,r)=>pe(t,r)(e);pe.parse=(e,t)=>Array.isArray(e)?e.map(r=>pe.parse(r,t)):ca(e,{...t,fastpaths:false});pe.scan=(e,t)=>Ib(e,t);pe.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=pe.toRegex(a,t);return n===true&&(l.state=e),l};pe.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=ca.fastpaths(e,t)),s.output||(s=ca(e,t)),pe.compileRe(s,t,r,n)};pe.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 /$^/}};pe.constants=Db;Kp.exports=pe;});var Zp=ut((aA,Qp)=>{var Jp=Xp(),Fb=Gr();function Yp(e,t,r=false){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:Fb.isWindows()}),Jp(e,t,r)}Object.assign(Yp,Jp);Qp.exports=Yp;});function Yb(e,t={}){let r=e.length,n=Array(r),s=Array(r),i,o;for(i=0;i<r;i++){let a=of(e[i]);n[i]=a;let l=a.length,c=Array(l);for(o=0;o<l;o++)c[o]=(0, or.default)(a[o],t);s[i]=c;}return a=>{let l=a.split("/");if(l[0]===".."&&Jb.test(a))return true;for(i=0;i<r;i++){let c=n[i],p=s[i],u=l.length,f=Math.min(u,c.length);for(o=0;o<f;){let h=c[o];if(h.includes("/"))return true;if(!p[o](l[o]))break;if(!t.noglobstar&&h==="**")return true;o++;}if(o===u)return true}return false}}function ef(e,t,r){if(e===t||t.startsWith(`${e}/`)){if(r){let s=e.length+ +!Zb(e);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 eS(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[r.length-1]==="/"&&n!==""?`${n}/`:n||"."}}function tf(e){return e.replace(Xb,t=>`${t}/`)}function of(e){var t;let r=or.default.scan(e,tS);return !((t=r.parts)===null||t===void 0)&&t.length?r.parts:[e]}function aS(e,t){let r=or.default.scan(e);return r.isGlob||r.negated}function zr(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...e);}function af(e){return typeof e=="string"?[e]:e??[]}function ua(e,t,r,n){var s;let i=t.cwd,o=e;e[e.length-1]==="/"&&(o=e.slice(0,-1)),o[o.length-1]!=="*"&&t.expandDirectories&&(o+="/**");let a=oS(i);o=isAbsolute(o.replace(cS,""))?posix.relative(a,o):posix.normalize(o);let l=(s=lS.exec(o))===null||s===void 0?void 0:s[0],c=of(o);if(l){let u=(l.length+1)/3,f=0,h=a.split("/");for(;f<u&&c[f+u]===h[h.length+f-u];)o=o.slice(0,(u-f-1)*3)+o.slice((u-f)*3+c[f+u].length+1)||".",f++;let d=posix.join(i,l.slice(f*3));d[0]!=="."&&r.root.length>d.length&&(r.root=tf(d),r.depthOffset=-u+f);}if(!n&&r.depthOffset>=0){var p;(p=r.commonPath)!==null&&p!==void 0||(r.commonPath=c);let u=[],f=Math.min(r.commonPath.length,c.length);for(let h=0;h<f;h++){let d=c[h];if(d==="**"&&!c[h+1]){u.pop();break}if(h===c.length-1||d!==r.commonPath[h]||aS(d))break;u.push(d);}r.depthOffset=u.length,r.commonPath=u,r.root=tf(u.length>0?posix.join(i,...u):i);}return o}function uS(e,t,r){let n=[],s=[];for(let i of e.ignore)i&&(i[0]!=="!"||i[1]==="(")&&s.push(ua(i,e,r,true));for(let i of t)i&&(i[0]!=="!"||i[1]==="("?n.push(ua(i,e,r,false)):(i[1]!=="!"||i[2]==="(")&&s.push(ua(i.slice(1),e,r,true)));return {match:n,ignore:s}}function pS(e,t){let r=e.cwd,n={root:r,depthOffset:0},s=uS(e,t,n);e.debug&&zr("internal processing patterns:",s);let{absolute:i,caseSensitiveMatch:o,debug:a,dot:l,followSymbolicLinks:c,onlyDirectories:p}=e,u=n.root.replace(nf,""),f={dot:l,nobrace:e.braceExpansion===false,nocase:!o,noextglob:e.extglob===false,noglobstar:e.globstar===false,posix:true},h=(0, or.default)(s.match,f),d=(0, or.default)(s.ignore,f),m=Yb(s.match,f),y=ef(r,u,i),g=i?y:ef(r,u,true),E=(A,C)=>{let $=g(C,true);return $!=="."&&!m($)||d($)},v;e.deep!==void 0&&(v=Math.round(e.deep-n.depthOffset));let T=new Cp({filters:[a?(A,C)=>{let $=y(A,C),_=h($)&&!d($);return _&&zr(`matched ${$}`),_}:(A,C)=>{let $=y(A,C);return h($)&&!d($)}],exclude:a?(A,C)=>{let $=E(A,C);return zr(`${$?"skipped":"crawling"} ${C}`),$}:E,fs:e.fs,pathSeparator:"/",relativePaths:!i,resolvePaths:i,includeBasePath:i,resolveSymlinks:c,excludeSymlinks:!c,excludeFiles:p,includeDirs:p||!e.onlyFiles,maxDepth:v,signal:e.signal}).crawl(u);return e.debug&&zr("internal properties:",{...n,root:u}),[T,r!==u&&!i&&eS(r,u)]}function fS(e,t){if(t)for(let r=e.length-1;r>=0;r--)e[r]=t(e[r]);return e}function mS(e){let t=Object.assign({},e);for(let r in rf)t[r]===void 0&&Object.assign(t,{[r]:rf[r]});return t.cwd=(t.cwd instanceof URL?fileURLToPath$1(t.cwd):resolve(t.cwd||process.cwd())).replace(nf,"/"),t.ignore=af(t.ignore),t.fs&&(t.fs={readdir:t.fs.readdir||readdir,readdirSync:t.fs.readdirSync||readdirSync,realpath:t.fs.realpath||realpath,realpathSync:t.fs.realpathSync||realpathSync,stat:t.fs.stat||stat,statSync:t.fs.statSync||statSync$1}),t.debug&&zr("globbing with options:",t),t}function dS(e,t={}){var r;if(e&&t?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let n=Kb(e)||typeof e=="string",s=af((r=n?e:e.patterns)!==null&&r!==void 0?r:"**/*"),i=mS(n?t:e);return s.length>0?pS(i,s):[]}async function Kr(e,t){let[r,n]=dS(e,t);return r?fS(await r.withPromise(),n):[]}var or,Kb,nf,Xb,sf,Jb,Qb,Zb,tS,rS,nS,sS,iS,oS,lS,cS,rf,pa=b(()=>{Ap();or=te(Zp()),Kb=Array.isArray,nf=/\\/g,Xb=/^[A-Za-z]:$/,sf=process.platform==="win32",Jb=/^(\/?\.\.)+$/;Qb=/^[A-Z]:\/$/i,Zb=sf?e=>Qb.test(e):e=>e==="/";tS={parts:true};rS=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,nS=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,sS=e=>e.replace(rS,"\\$&"),iS=e=>e.replace(nS,"\\$&"),oS=sf?iS:sS;lS=/^(\/?\.\.)+/,cS=/\\(?=[()[\]{}!*+?@|])/g;rf={caseSensitiveMatch:true,debug:!!process.env.TINYGLOBBY_DEBUG,expandDirectories:true,followSymbolicLinks:true,onlyFiles:true};});function Ie(e){return e.dialect==="postgres"?"pg":e.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function Pt(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 Xr(e){return `'${e.replace(/'/g,"''")}'`}function hS(e){return `'${`{${e.map(n=>`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function lf(e,t){return t==null?"NULL":e==="pg"?hS(t):Xr(JSON.stringify(t))}function fa(e){return e==null?"NULL":Xr(e)}function yS(e){let{schema_migrations:t,seed_files:r}=Pt(e);return e==="pg"?["CREATE SCHEMA IF NOT EXISTS supabase_migrations",`CREATE TABLE IF NOT EXISTS ${t} (
67
+ `)+`
68
+ `));}let n=Jr(),r=t.port??3e3;if(vn()){let s=await Promise.resolve().then(()=>(op(),ip)).then(o=>o.serveStatic),i;try{let o=cp(e,n,s);i=Bun.serve({fetch:a=>(Lo(a,i?.requestIP(a)?.address),o.fetch(a)),port:r});}catch(o){throw ko(o)&&Po(r),o}return async()=>{await i.stop();}}else {let{createAdaptorServer:s}=await import('@hono/node-server'),i=await import('@hono/node-server/serve-static').then(c=>c.serveStatic),o=cp(e,n,i),a=s({fetch:(c,...l)=>{let p=l[0]?.incoming;return Lo(c,p?.socket?.remoteAddress),o.fetch(c)}});try{await Eu(a,r);}catch(c){throw ko(c)&&Po(r),c}return ()=>new Promise(c=>{a.close(()=>{c(void 0);});})}}function cp(e,t,n){return new Ro().use("/favicon.ico",n({path:Oe__default.join(t,"static","favicon.ico")})).use("/fonts/*",n({root:Oe__default.join(t,"static"),onNotFound:r=>{console.log("fonts not found",r,process.cwd());}})).use("/static/*",n({root:t,onNotFound(r){console.log("not found",r,process.cwd());}})).all("*",async r=>e.fetch(r.req.raw))}var lp,Ko=b(()=>{lt();Su();xu();Ee();No();_u();lp=V(z());});var tt,zo=b(()=>{_t();tt=class e{root;constructor(t,n){let r=n??e.projectDir();this.root=Oe__default.join(r,t??"");}ensureRoot(){$e(this.root);}static homeDir(){return Oe__default.join(dy.homedir(),".lite")}static projectDir(){return Oe__default.join(process.cwd(),"supabase")}deleteAll(t=false){try{Fr.rmSync(this.root,{recursive:!0});}catch(n){if(!t)throw n}this.ensureRoot();}delete(t,n=false){try{Fr.unlinkSync(Oe__default.join(this.root,t));}catch(r){if(!n)throw r}}write(t,n,r=false){try{this.ensureRoot(),Fr.writeFileSync(Oe__default.join(this.root,t),n);}catch(s){if(!r)throw s}}read(t,n=false){try{return Fr.readFileSync(Oe__default.join(this.root,t),"utf8")}catch(r){if(!n)throw r}}relativePath(t){return t?Oe__default.relative(process.cwd(),Oe__default.join(this.root,t)):this.root}path(t){return t?Oe__default.join(this.root,t):this.root}};});var Fn,ys,bs=b(()=>{Fn=process.env.LITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2001":"https://api.lite.dev"),ys=process.env.LITE_CLOUD_PROJECTS_URL??(process.env.LOCAL?"http://supalite.local":"https://lite.black");});var Ss,up=b(()=>{_t();Ss=class{root;constructor(t){this.root=t??Oe__default.join(dy.homedir(),".lite","auth"),$e(this.root);}async getItem(t){try{return Fr.readFileSync(Oe__default.join(this.root,t+".json"),"utf8")}catch{return null}}async setItem(t,n){Fr.writeFileSync(Oe__default.join(this.root,t+".json"),n);}async removeItem(t){try{Fr.unlinkSync(Oe__default.join(this.root,t+".json"));}catch{return}}};});var Zt,Jo=b(()=>{bs();zo();up();Zt=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(Oe__default.join(tt.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??Fn,process.env.LITE_CLOUD_ANON_KEY??"...",{auth:{storage:this.authStorage}}):void 0;}tempFs;projectFs;schemaFs;_client;authStorage;async fetch(t,n){if(!this.config.token)throw new Error("Not authenticated, sign in first.");let r=t instanceof URL?t:new URL(t,this.config.host??Fn);return await fetch(r,{...n,headers:{...n?.headers,Authorization:`Bearer ${this.config.token}`}})}};});var en,Yo=b(()=>{Jo();bs();en=class extends Zt{constructor(n){super(n);this.config=n;}get client(){if(!this._client)throw new Error("Supabase client not initialized");return this._client}projectRef(){return this.tempFs.read("project-ref",true)}projectUrl(n){let r=new URL(this.config.projectsHost??ys),s=r.hostname.replace(/^www\./,"");return `${r.protocol}//${n}.${s}${r.port?`:${r.port}`:""}`}};});function by(e){let t=Oe.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,pp=b(()=>{lt();xs=class{driver=de;basePath;constructor(t){this.basePath=Oe.resolve(t.basePath);}filePath(t,n){return Oe.join(this.basePath,t,n)}async ensureDir(t){await de.mkdir(Oe.dirname(t),{recursive:true});}async getObject(t,n,r,s){let i=this.filePath(t,n),o=await de.stat(i),a=`"${createHash("md5").update(`${i}:${o.mtimeMs}`).digest("hex")}"`;if(s?.ifNoneMatch===a)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,n)};if(s?.ifModifiedSince){let f=new Date(s.ifModifiedSince);if(o.mtime<=f)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,n)}}let c,l,p=o.size,u=200;if(s?.range){let f=s.range.match(/^bytes=(\d+)-(\d*)$/);if(f){let h=Number.parseInt(f[1],10),d=f[2]?Number.parseInt(f[2],10):o.size-1;p=d-h+1,l=`bytes ${h}-${d}/${o.size}`,u=206,c=(await de.open(i,"r")).readableWebStream();}else c=(await de.open(i,"r")).readableWebStream();}else c=(await de.open(i,"r")).readableWebStream();return {httpStatusCode:u,metadata:{...this.buildMetadata(o,a,n),contentLength:p,contentRange:l},body:c}}async uploadObject(t,n,r,s,i,o){let a=this.filePath(t,n);await this.ensureDir(a);let c;if(s instanceof Uint8Array||Buffer.isBuffer(s))c=s;else {let u=[],f=s.getReader();for(;;){let{done:h,value:d}=await f.read();if(h)break;u.push(d);}c=Buffer.concat(u);}await de.writeFile(a,c);let l=await de.stat(a),p=`"${createHash("md5").update(c).digest("hex")}"`;return {cacheControl:o,contentLength:l.size,size:l.size,mimetype:i,lastModified:l.mtime,eTag:p}}async deleteObject(t,n,r){let s=this.filePath(t,n);await de.unlink(s).catch(i=>{if(i.code!=="ENOENT")throw i});}async deleteObjects(t,n){for(let r of n)await this.deleteObject(t,r,void 0);}async copyObject(t,n,r,s,i){let o=this.filePath(t,n),a=this.filePath(t,s);await this.ensureDir(a),await de.copyFile(o,a);let c=await de.stat(a),l=await de.readFile(a);return {httpStatusCode:200,eTag:`"${createHash("md5").update(l).digest("hex")}"`,lastModified:c.mtime}}async headObject(t,n,r){let s=this.filePath(t,n),i=await de.stat(s),o=`"${createHash("md5").update(`${s}:${i.mtimeMs}`).digest("hex")}"`;return this.buildMetadata(i,o,n)}async privateAssetUrl(t,n,r){return `file://${this.filePath(t,n)}`}buildMetadata(t,n,r){return {cacheControl:"no-cache",contentLength:uo(t.size),size:uo(t.size),mimetype:by(r),lastModified:t.mtime,eTag:n}}};});async function qe(e,t,n){try{return await wy(e)}catch(r){throw r?.code==="ERR_MODULE_NOT_FOUND"||/Cannot find package/.test(String(r?.message))?new Error(`Driver '${t}' selected but '${n}' is not installed. Run: bun add ${n}`):r}}var wy,tn=b(()=>{wy=new Function("spec","return import(spec)");});var Un,Ey,_s,mp=b(()=>{Yo();At();Un=V(z());$n();Kt();pp();tn();zi();Ji();Ct();Ey=["toml","json","ts","mts","js","mjs","cjs"],_s=class extends en{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 n=Oe__default.relative(process.cwd(),fe.config_dir);if(!t)for(let r of Ey){let s=Oe__default.join(n,`config.${r}`);if(await de__default.access(s).then(()=>true).catch(()=>false)){t=s;break}}return t}async readConfig(t){let n=await this.getConfigPath(t);if(!n)return {};Me(Un.default.dim(`Using config file: ${Un.default.cyan(`./${n}`)}`));let r=Oe__default.dirname(Oe__default.resolve(n));Gr(r);let s=n.split(".").pop(),i;switch(s){case "toml":i=$t(await de__default.readFile(n,"utf-8"));break;case "json":i=JSON.parse(await de__default.readFile(n,"utf-8"));break;case "ts":case "mts":case "js":case "mjs":case "cjs":try{i=(await import(Oe__default.join(process.cwd(),n))).default;break}catch(o){throw console.error("Failed to import config file",o),o}default:throw new Error(`Unsupported config file type: ${n}`)}return Wr(i)}async createConnection(){throw new Error("Not implemented")}async getConfig(t){let n=await this.readConfig(t);if("connection"in n)return {...n,connection:await n.connection};let r,s;switch(n.db?.driver){case "sqlite":s=n.db?.url??fe.default_db_url,r=await createConnection({url:s,ddlDialect:"sqlite"});break;case "pglite":{s=n.db?.url??Oe__default.join(process.cwd(),fe.default_db_dir);let{createPgliteConnection:i}=await qe("@supabase/lite/pglite","pglite","@electric-sql/pglite");r=await i({url:s});break}case "postgres":{s=n.db?.url??"";let{createPostgresConnection:i}=await qe("@supabase/lite/postgres","postgres","postgres");r=await i({url:s});break}default:s=n.db?.url??fe.default_db_url,r=await createConnection({url:s,ddlDialect:"postgres"});break}if(!r)throw new Error("Failed to create connection");return Me(Un.default.green(" \u279C"),"Database located at",Un.default.cyan(s??"in-memory")),{...n,connection:r}}async createApp(t,n){let r=await this.getConfig(t),s=new App({...r,options:{...r.options,server:{...r.options?.server,admin:n?.admin??r.options?.server?.admin??n?.adminDefault}}});return s.config.storage?.enabled&&process.env.EXPERIMENTAL_STORAGE==="1"&&!s._storageAdapter&&(s._storageAdapter=new xs({basePath:Oe__default.join(process.cwd(),fe.config_dir,".temp/storage")})),await s.init()}};});var Ts,dp=b(()=>{Yo();Ts=class extends en{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 n=await t.json();if(!Array.isArray(n))throw new Error("Failed to list projects");return n}async get(t){if(t=t??this.projectRef(),!t)throw new Error("No project ref found");let n=await this.fetch(`/v1/projects/${t}`);if(!n.ok)throw new Error(`Failed to get project: ${n.status} ${n.statusText}`);let r=await n.json();if(!r||!r.id)throw new Error("Failed to get project");return r}async create(t){if(!t.name)throw new Error("Project name is required");let n=await this.fetch("/v1/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Failed to create project: ${n.status} ${n.statusText}${s?` \u2014 ${s}`:""}`)}let r=await n.json();if(!r||!r.id)throw new Error("Failed to create project");return r}async getConfig(t){let n=await this.fetch(`/v1/projects/${t}/config`);if(!n.ok)throw new Error(`Failed to get project config: ${n.status} ${n.statusText}`);let r=await n.json();if(!r)throw new Error("Failed to get project config");return r}async setConfig(t,n){let r=await this.fetch(`/v1/projects/${t}/config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error(`Failed to set project config: ${r.status} ${r.statusText}`);return true}async createApp(t){if(!this.config.host)throw new Error("No host specified");let{data:n,error:r}=await this.client.auth.getSession();if(r)throw r;if(!n?.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:n.session.access_token,host:this.config.host})}).init()}};});var $s,hp=b(()=>{Jo();mp();dp();$s=class extends Zt{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:n}=await this.getSession();if(n)throw n;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 Ts(t)},this}};});async function W(e={}){return await new $s({host:Fn,projectsHost:ys,root:tt.projectDir(),...e}).init()}var Te=b(()=>{zo();bs();hp();});function As(e){let t=false,n=async()=>{if(!t){t=true;try{await e();}catch(r){Me(r);}process.exit(0);}};process.on("SIGINT",n),process.on("SIGTERM",n);}var Zo=b(()=>{Ct();});function Cs(e){let t=e.auth?.publishable_key,n=e.auth?.secret_key;if(!t&&!n){console.log(Je.default.dim(" \u279C no API keys configured \u2014 run `lite generate-keys` (any apikey accepted)"));return}console.log(Je.default.green(" \u279C"),"Publishable key".padEnd(19),Je.default.cyan(t??"(not set)")),console.log(Je.default.green(" \u279C"),"Secret key".padEnd(19),Je.default.cyan(n??"(not set)"));}function vs(e){if(!e){console.log(Je.default.dim(" \u279C admin mode off \u2014 keyless requests are not elevated; normal auth rules apply"));return}console.log(Je.default.green(" \u279C"),"Studio admin mode".padEnd(19),Je.default.cyan("on"),Je.default.dim("(keyless same-origin localhost as service_role)"));}var Je,ea=b(()=>{Je=V(z());});function Rs(e,t){return {admin:t.getOptionValueSource?.("admin")==="cli"?e.admin:void 0,adminDefault:true}}var ta=b(()=>{});function xe(e){return e.dialect==="postgres"?"pg":e.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function ft(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 Mn(e){return `'${e.replace(/'/g,"''")}'`}function Ty(e){return `'${`{${e.map(r=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function gp(e,t){return t==null?"NULL":e==="pg"?Ty(t):Mn(JSON.stringify(t))}function na(e){return e==null?"NULL":Mn(e)}function yp(e){if(e==null)return [];if(Array.isArray(e))return e;if(typeof e=="string"){let t=e.trim();if(t==="")return [];try{let n=JSON.parse(t);return Array.isArray(n)?n:[]}catch{return []}}return []}function $y(e){return {version:String(e.version),name:e.name??null,statements:yp(e.statements),rollback:yp(e.rollback),created_by:e.created_by??null,idempotency_key:e.idempotency_key??null}}function Cy(e){let{schema_migrations:t,seed_files:n}=ft(e);return e==="pg"?["CREATE SCHEMA IF NOT EXISTS supabase_migrations",`CREATE TABLE IF NOT EXISTS ${t} (
65
69
  version text NOT NULL PRIMARY KEY,
66
70
  statements text[],
67
71
  name text,
68
72
  created_by text,
69
73
  idempotency_key text,
70
74
  rollback text[]
71
- )`,`CREATE TABLE IF NOT EXISTS ${r} (
75
+ )`,`CREATE TABLE IF NOT EXISTS ${n} (
72
76
  path text NOT NULL PRIMARY KEY,
73
77
  hash text NOT NULL
74
78
  )`]:[`CREATE TABLE IF NOT EXISTS ${t} (
@@ -78,23 +82,25 @@ create table test (
78
82
  created_by TEXT,
79
83
  idempotency_key TEXT,
80
84
  rollback TEXT
81
- )`,`CREATE TABLE IF NOT EXISTS ${r} (
85
+ )`,`CREATE TABLE IF NOT EXISTS ${n} (
82
86
  path TEXT NOT NULL PRIMARY KEY,
83
87
  hash TEXT NOT NULL
84
- )`]}function wS(e){let{schema_migrations:t}=Pt(e);return [`CREATE UNIQUE INDEX IF NOT EXISTS ${e==="sqlite"?"migrations_idempotency_key_idx":"schema_migrations_idempotency_key_idx"} ON ${t} (idempotency_key)`]}function cf(e,t){let{schema_migrations:r}=Pt(e);return `INSERT INTO ${r} (version, name, statements, rollback, created_by, idempotency_key) VALUES (${Xr(t.version)}, ${fa(t.name)}, ${lf(e,t.statements)}, ${lf(e,t.rollback??null)}, ${fa(t.created_by??null)}, ${fa(t.idempotency_key??null)}) ON CONFLICT (idempotency_key) DO UPDATE SET version = EXCLUDED.version, name = EXCLUDED.name, statements = EXCLUDED.statements, rollback = EXCLUDED.rollback, created_by = EXCLUDED.created_by`}function bS(e){let{schema_migrations:t}=Pt(e);return `SELECT version FROM ${t} ORDER BY version ASC`}function SS(e){let{seed_files:t}=Pt(e);return t?`SELECT path, hash FROM ${t}`:null}function uf(e,t){let{seed_files:r}=Pt(e);return r?`INSERT INTO ${r} (path, hash) VALUES (${Xr(t.path)}, ${Xr(t.hash)}) ON CONFLICT (path) DO UPDATE SET hash = EXCLUDED.hash`:null}async function ES(e,t){let{schema_migrations:r}=Pt(t);for(let n of gS){let s=t==="pg"?n.pgType:n.sqliteType;if(t==="pg")await e.exec(`ALTER TABLE ${r} ADD COLUMN IF NOT EXISTS ${n.name} ${s}`);else try{await e.exec(`ALTER TABLE ${r} ADD COLUMN ${n.name} ${s}`);}catch{}}}async function ar(e){let t=Ie(e);for(let r of yS(t))await e.exec(r);await ES(e,t);for(let r of wS(t))await e.exec(r);}async function Jr(e){let t=Ie(e);return ((await e.exec(bS(t)))?.rows??[]).map(n=>n.version)}async function pf(e){let t=Ie(e),r=SS(t);return r?((await e.exec(r))?.rows??[]).map(s=>({path:s.path,hash:s.hash})):[]}var gS,Lt=b(()=>{gS=[{name:"created_by",pgType:"text",sqliteType:"TEXT"},{name:"idempotency_key",pgType:"text",sqliteType:"TEXT"},{name:"rollback",pgType:"text[]",sqliteType:"TEXT"}];});function mf(e){return Ie(e.connection)==="sqlite"?"./sqlite-migrations/*.sql":"./migrations/*.sql"}function It(e){return Fe__default.posix.dirname(mf(e))}async function Ue(e){let t=Fe__default.join(process.cwd(),"supabase"),r=await Kr([mf(e)],{cwd:t,absolute:true}),n=[];for(let s of r){let i=Fe__default.basename(s),o=xS.exec(i);if(!o)continue;let a=await fe__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 Qr(e){return (await Ue(e)).map(r=>r.sql).join(`
85
- `)}function ma(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 da(e,t=ma()){let r=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return r.length>0?`${t}_${r}.sql`:`${t}.sql`}async function df(e,t,r){let n=Fe__default.join(process.cwd(),"supabase",It(e));ke(n);let s=da(t,r?.ts),i=Fe__default.join(n,s);return await fe__default.writeFile(i,"",{flag:"wx"}),i}var xS,ht=b(()=>{pa();Lt();_t();xS=/^(\d{14})(?:_([^.]+))?\.sql$/;});function Zr(e){if("String"in e)return e.String.sval}function gt(e){return e.map(Zr).filter(t=>t!=null)}function Dt(e){return e==null?[]:e.List!==void 0?e.List.items||[]:Array.isArray(e)?e:[e]}function Ns(e){return QuoteUtils.quoteIdentifier(e)}function lr(e){return Object.keys(e)[0]}function hf(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 jt=b(()=>{});function yf(e){let t=e.toLowerCase().trim();if(t.startsWith("_")||t.endsWith("[]"))return "TEXT";let r=TS[t];if(!r)throw new Ft(`Unsupported PostgreSQL type: "${e}"`);return r}function Ps(e){let t=e.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(t)}function Ls(e){let t=e.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(t)}function Is(e){let t=e.toLowerCase();return ["numeric","decimal"].includes(t)}var Ft,B,TS,gf,vS,Ds,cr=b(()=>{jt();Ft=class extends Error{},B=class extends Ft{constructor(r,n){super(n??`Unsupported node type: ${lr(r)}`);this.node=r;}},TS={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"},gf=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","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"},AlterPolicyStmt:{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,en,ha=b(()=>{jt();cr();Me=class extends B{constructor(t,r){super(t,`Unsupported expression: ${r}`);}},en=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?Zr(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]?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 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 h="ResTarget"in f?f.ResTarget:void 0;if(h?.val){let d=this.deparseValue(h.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),p=this.deparseGroupClause(t.groupClause),u={type:"query",from:r,select:i};return n&&(u.schema=n),Object.keys(s).length>0&&(u.join=s),o&&(u.where=o),a.length>0&&(u.order=a),l!==void 0&&(u.limit=l),c!==void 0&&(u.offset=c),p.length>0&&(u.group=p),u}FuncCall(t){let r=this.isAuthFunc(t.funcname??[]);if(r)return r;throw new Me({FuncCall:t},`FuncCall: ${gt(t.funcname??[]).join(".")}`)}ColumnRef(t){let r=gt(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 p=2;for(;`${c}_${p}`in r;)p++;c=`${c}_${p}`;}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=gt(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 Ut,ga=b(()=>{Ut=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 tn,ya=b(()=>{tn=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 be,nt=b(()=>{ya();be=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 tn(this.context.table,this.context.column,t,r)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var Mt,js=b(()=>{nt();Mt=class extends be{get sqliteType(){return "INTEGER"}};});var rn,wa=b(()=>{js();rn=class extends Mt{constructor(t){super({...t,isSerial:true});}};});function CS(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 Bt,Fs=b(()=>{nt();Bt=class extends be{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(!CS(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${r}, ${n}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var le,Be=b(()=>{nt();le=class extends be{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 nn,ba=b(()=>{nt();nn=class extends be{get sqliteType(){return "BLOB"}};});var sn,Sa=b(()=>{nt();sn=class extends be{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 wf(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var on,Ea=b(()=>{nt();on=class extends be{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=wf(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."):wf(t).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function AS(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 an,xa=b(()=>{Be();an=class extends le{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"||!AS(t)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function RS(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 ln,_a=b(()=>{Be();ln=class extends le{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"||!RS(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function kS(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]),p=new Date(Date.UTC(r,n-1,s)),u=p.getUTCFullYear()===r&&p.getUTCMonth()===n-1&&p.getUTCDate()===s,f=i<=24&&o<=59&&a<=59&&(i!==24||o===0&&a===0),h=l===null||c!==null&&l<=15&&c<=59;return u&&f&&h}var cn,$a=b(()=>{Be();cn=class extends le{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"||!kS(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var un,Ta=b(()=>{Be();un=class extends le{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 pn,va=b(()=>{Be();pn=class extends le{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 bf(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var yt,Us=b(()=>{nt();yt=class extends be{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=bf(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=bf(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 Sf(e){return NS.test(e.toLowerCase())}var OS,NS,fn,Ca=b(()=>{Be();OS="????????-????-????-????-????????????",NS=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;fn=class extends le{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${OS}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let r=t.toLowerCase();if(!Sf(r))throw this.checkError("uuid_format",t);return r}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!Sf(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function PS(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 LS(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 IS(e){if(!e.includes(":"))return false;try{return new URL(`http://[${e}]/`),!0}catch{return false}}function Ef(e){let t=PS(e);return t?LS(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:IS(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var mn,Aa=b(()=>{Be();mn=class extends le{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(!Ef(r))throw this.checkError("inet_format",t);return r}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!Ef(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var dn,Ra=b(()=>{Be();dn=class extends le{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 qt(e,t){if(t?.isArray){let n=qt(e,{...t,isArray:false});return new yt(e,n)}if(t?.enumValues)return new pn(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=qt(s);return new yt(e,i)}return jS.has(r)?new rn(e):DS.has(r)?new Mt(e):BS.has(r)?new sn(e):qS.has(r)?new on(e):VS.has(r)?new an(e):zS.has(r)?new ln(e):KS.has(r)?new cn(e):XS.has(r)?new un(e):MS.has(r)?new nn(e):FS.has(r)?new Bt(e,t?.numericPrecision):HS.has(r)?new fn(e):GS.has(r)?new le(e,63):WS.has(r)?new mn(e):US.has(r)?new le(e,t?.lengthConstraint):new dn(e)}var DS,jS,FS,US,MS,BS,qS,HS,GS,WS,VS,zS,KS,XS,ka=b(()=>{js();wa();Fs();Be();ba();Sa();Ea();xa();_a();$a();Ta();va();Us();Ca();Aa();Ra();DS=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),jS=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),FS=new Set(["float4","real","float8","double precision","numeric","decimal"]),US=new Set(["text","varchar","character varying","char","character","bpchar"]),MS=new Set(["bytea"]),BS=new Set(["bool","boolean"]),qS=new Set(["json","jsonb"]),HS=new Set(["uuid"]),GS=new Set(["name"]),WS=new Set(["inet"]),VS=new Set(["date"]),zS=new Set(["time","timetz","time without time zone","time with time zone"]),KS=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),XS=new Set(["interval"]);});function Oa(e,t="auto"){let r=e.toLowerCase(),n=Ms[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 xf,Ms,Na=b(()=>{xf="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)))",Ms={gen_random_uuid:{sqlite:()=>xf,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>xf,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 hn,_f=b(()=>{hn=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 $f=b(()=>{nt();ya();js();wa();Fs();Be();ba();Sa();Ea();xa();_a();$a();Ta();va();Us();Ca();Aa();Ra();ka();Na();_f();});var qa={};de(qa,{_resetWarnedMissingToClauseForTests:()=>JS,collectComments:()=>Ba,collectEnums:()=>Da,collectPolicies:()=>Fa,collectSchema:()=>Ua,collectTableConstraints:()=>Ma,collectVariables:()=>ja});function JS(){Ia.clear();}function Da(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=gt(n.typeName??[]).join(".");if(!s||!n.vals)continue;let i=gt(n.vals);t.set(s.toLowerCase(),i);}return t}function ja(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=hf(n.args?.[0]??{});t.set(s,{value:i,local:n.is_local});}return t}function Tf(e){let t=[],r=false;for(let n of e??[])if("RoleSpec"in n){let s=n.RoleSpec;s.roletype==="ROLESPEC_PUBLIC"?s.location===-1&&(r=true):s.roletype==="ROLESPEC_CSTRING"&&s.rolename&&t.push(s.rolename);}return {roles:t,implicitPublic:r}}function vf(e,t){return e&&e.length>0?e:t}function Pa(e,t,r){return e.findIndex(n=>n.data.name===t.name&&n.data.table===t.table&&vf(n.data.schema,r)===vf(t.schema,r))}function La(e,t){return new Error(`policy "${e}" for table "${t}" does not exist`)}function Fa(e,t={}){let r=t.defaultSchema||"public",n=t.validateMutations===true,s=new en,i=new Set,o=[];for(let a of e.stmts??[])if(a.stmt){if("CreatePolicyStmt"in a.stmt){let l=a.stmt.CreatePolicyStmt,c=l.table?.relname??"",p=l.table?.schemaname,u={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},f=l.cmd_name?u[l.cmd_name]??"ALL":"ALL",h=l.permissive===true,{roles:d,implicitPublic:m}=Tf(l.roles),y=l.qual?s.deparse(l.qual):void 0,g=l.with_check?s.deparse(l.with_check):void 0;if(m){let v=p?`${p}.${c}`:c,T=l.policy_name??"",A=`${v}::${T}`;if(!Ia.has(A)){Ia.add(A);let C=JSON.stringify(y)+JSON.stringify(g);/\{\{auth\.(uid|jwt|role)/i.test(C)||console.warn(`[supalite] policy "${T}" on "${v}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let E=new Ut({name:l.policy_name??"",table:c,schema:p,command:f,permissive:h,roles:d,using:y,withCheck:g});o.push(E);}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_POLICY"){let l=a.stmt.DropStmt,c=l.objects?.[0];if(c&&"List"in c){let p=gt(c.List.items??[]),u=p[p.length-1],f=p[p.length-2],h=p.length>=3?p[p.length-3]:void 0;if(u&&f){let d=Pa(o,{name:u,table:f,schema:h},r);if(d!==-1)o.splice(d,1);else if(n&&!l.missing_ok)throw La(u,f)}}}if("AlterPolicyStmt"in a.stmt){let l=a.stmt.AlterPolicyStmt,c=l.policy_name??"",p=l.table?.relname??"",u=l.table?.schemaname,f=Pa(o,{name:c,table:p,schema:u},r);if(f===-1){if(n)throw La(c,p);continue}let h=o[f].data,d=l.roles?Tf(l.roles).roles:h.roles,m=l.qual?s.deparse(l.qual):h.using,y=l.with_check?s.deparse(l.with_check):h.withCheck;o[f]=new Ut({...h,roles:d,using:m,withCheck:y});}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_POLICY"){let l=a.stmt.RenameStmt,c=l.subname??"",p=l.relation?.relname??"",u=l.relation?.schemaname,f=Pa(o,{name:c,table:p,schema:u},r);if(f===-1){if(n)throw La(c,p);continue}l.newname&&(o[f]=new Ut({...o[f].data,name:l.newname}));}if("AlterTableStmt"in a.stmt){let l=a.stmt.AlterTableStmt;if((l.cmds??[]).some(u=>"AlterTableCmd"in u&&(u.AlterTableCmd.subtype==="AT_EnableRowSecurity"||u.AlterTableCmd.subtype==="AT_ForceRowSecurity"))){let u=l.relation?.relname??"";i.add(u);}}}return {policies:o,tables:i}}function Ua(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 hn(i,o);for(let l of s.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,p=c.colname;if(!p)continue;let u=c.typeName?.names?.map(N=>N.String?.sval||N.String?.str).filter(Boolean),f=u&&(u.length===2&&u[0]==="pg_catalog"?u[1]:u[0]);if(!f)continue;let h=!!c.typeName?.arrayBounds?.length,d=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],m=N=>d[N]?.A_Const?.ival?.ival??d[N]?.A_Const?.val?.ival?.ival,y={isArray:h};if(Ls(f)&&d.length>0){let N=m(0);typeof N=="number"&&N>0&&(y.lengthConstraint=N);}if(Is(f)&&d.length>=2){let N=m(0),F=m(1);typeof N=="number"&&typeof F=="number"&&N>0&&F>=0&&(y.numericPrecision={precision:N,scale:F});}let g=t.get(f.toLowerCase());g&&(y.enumValues=g);let E=Array.isArray(c.constraints)?c.constraints:[],v=E.some(N=>N.Constraint?.contype==="CONSTR_PRIMARY"),T=Ps(f)||E.some(N=>N.Constraint?.contype==="CONSTR_IDENTITY"),A=E.some(N=>N.Constraint?.contype==="CONSTR_NOTNULL"),C=E.find(N=>N.Constraint?.contype==="CONSTR_UNIQUE"),$=E.find(N=>N.Constraint?.contype==="CONSTR_GENERATED"),_=E.find(N=>N.Constraint?.contype==="CONSTR_FOREIGN"),L=E.find(N=>N.Constraint?.contype==="CONSTR_CHECK"),w;if(_){let N=_.Constraint,F=N.pktable?.relname,S=N.pktable?.schemaname,x=N.pk_attrs?.[0]?.String?.sval;F&&x&&(w={refSchema:S,refTable:F,refColumn:x,constraintName:N.conname||void 0});}let D={schema:o,table:i,column:p,pgTypeName:f,nullable:!A&&!v,defaultValue:null,defaultFn:null,isPrimaryKey:v,isUnique:!!C,isSerial:T,isGenerated:!!$,fkRef:w,hasCheck:!!L,checkConstraintName:L?.Constraint?.conname||void 0,uniqueConstraintName:C?.Constraint?.conname||void 0};a.set(p,qt(D,y));}r.set(`${o}.${i}`,a);}return r}function Ma(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 p=(l.keys??[]).map(u=>u.String?.sval??u.String?.str).filter(Boolean);if(p.length===0)continue;t.push({schema:i,table:s,kind:"unique",name:l.conname||void 0,columns:p});}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 p=(l.fk_attrs??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean),u=(l.pk_attrs??[]).map(h=>h.String?.sval??h.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:p,refSchema:l.pktable?.schemaname,refTable:f,refColumns:u});}}}return t}function Ba(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 Ia,Ha=b(()=>{ha();jt();ga();$f();cr();Ia=new Set;});async function gn(e,t){let r=await e.connection.introspect(),n=Ga(r);await kf(e,{...t,dbHasTables:r.tables.length>0,dbFingerprint:n}),await tE(e);let s=await e.connection.introspect();Pf(s,e);}async function ZS(e){return Kr(e.config.db?.seed?.sql_paths??["./seed.sql"],{cwd:Fe__default.join(process.cwd(),"supabase"),absolute:true})}async function eE(e){let t=await ZS(e);return Promise.all(t.map(async r=>{let n=await fe__default.readFile(r,"utf-8"),s=createHash("sha256").update(n).digest("hex");return {path:Fe__default.relative(process.cwd(),r),hash:s,statements:splitSqlStatements(n)}}))}async function yn(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 ar(e.connection);let s=Ie(e.connection),i=new Map((await pf(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(U.default.dim("Seeding database..."));let a=[];for(let l of o){a.push(...l.statements);let c=uf(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 re-run `lite dev` to reapply the schema and reseed.";throw new Error(`Seed failed and was rolled back: ${String(l.message??l)}
86
- ${c}`)}return o.reduce((l,c)=>l+c.statements.length,0)}async function tE(e){await yn(e);}async function ge(e){let t=await Kr(e.config?.db?.migrations?.schema_paths??["./schemas/*.sql"],{cwd:Fe__default.join(process.cwd(),"supabase"),absolute:true}),r=await Promise.all(t.map(async n=>await fe__default.readFile(n,"utf-8"))).then(n=>n.map(s=>s.split(`
88
+ )`]}function vy(e){let{schema_migrations:t}=ft(e);return [`CREATE UNIQUE INDEX IF NOT EXISTS ${e==="sqlite"?"migrations_idempotency_key_idx":"schema_migrations_idempotency_key_idx"} ON ${t} (idempotency_key)`]}function bp(e,t){let{schema_migrations:n}=ft(e);return `INSERT INTO ${n} (version, name, statements, rollback, created_by, idempotency_key) VALUES (${Mn(t.version)}, ${na(t.name)}, ${gp(e,t.statements)}, ${gp(e,t.rollback??null)}, ${na(t.created_by??null)}, ${na(t.idempotency_key??null)}) ON CONFLICT (idempotency_key) DO UPDATE SET version = EXCLUDED.version, name = EXCLUDED.name, statements = EXCLUDED.statements, rollback = EXCLUDED.rollback, created_by = EXCLUDED.created_by`}function Ry(e){let{schema_migrations:t}=ft(e);return `SELECT version FROM ${t} ORDER BY version ASC`}function Py(e){let{schema_migrations:t}=ft(e);return `SELECT ${ky} FROM ${t} ORDER BY version ASC`}function Ny(e){let{seed_files:t}=ft(e);return t?`SELECT path, hash FROM ${t}`:null}function wp(e,t){let{seed_files:n}=ft(e);return n?`INSERT INTO ${n} (path, hash) VALUES (${Mn(t.path)}, ${Mn(t.hash)}) ON CONFLICT (path) DO UPDATE SET hash = EXCLUDED.hash`:null}async function Ly(e,t){let{schema_migrations:n}=ft(t);for(let r of Ay){let s=t==="pg"?r.pgType:r.sqliteType;if(t==="pg")await e.exec(`ALTER TABLE ${n} ADD COLUMN IF NOT EXISTS ${r.name} ${s}`);else try{await e.exec(`ALTER TABLE ${n} ADD COLUMN ${r.name} ${s}`);}catch{}}}async function nn(e){let t=xe(e);for(let n of Cy(t))await e.exec(n);await Ly(e,t);for(let n of vy(t))await e.exec(n);}async function Bn(e){let t=xe(e);return ((await e.exec(Ry(t)))?.rows??[]).map(r=>r.version)}async function qn(e){let t=xe(e);return ((await e.exec(Py(t)))?.rows??[]).map($y)}async function Sp(e){let t=xe(e),n=Ny(t);return n?((await e.exec(n))?.rows??[]).map(s=>({path:s.path,hash:s.hash})):[]}var Ay,ky,mt=b(()=>{Ay=[{name:"created_by",pgType:"text",sqliteType:"TEXT"},{name:"idempotency_key",pgType:"text",sqliteType:"TEXT"},{name:"rollback",pgType:"text[]",sqliteType:"TEXT"}];ky="version, name, statements, rollback, created_by, idempotency_key";});function Oy(e){return e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/--.*$/gm,"")}function Iy(e){let t=e.trim();return t.startsWith('"')?t.replace(/^"(.*)"$/,"$1"):t.toLowerCase()}function ks(e){let t=e.split(".");return Iy(t[t.length-1]??e)}function oa(e){let t=[...e].sort((i,o)=>i.version.localeCompare(o.version)),n=Oy(t.flatMap(i=>i.statements??[]).join(`
89
+ `)),r=new Set;sa.lastIndex=0;let s=sa.exec(n);for(;s!==null;){let[,i,o,a,c]=s;if(i&&o){let l=ks(i);o.toUpperCase()==="ENABLE"?r.add(l):r.delete(l);}else if(i&&a)r.delete(ks(i))&&r.add(ks(a));else if(c)for(let l of c.split(","))r.delete(ks(l));s=sa.exec(n);}return r}async function Ep(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}async function xp(e){let t=[...e].sort((r,s)=>r.version.localeCompare(s.version)),n=await Promise.all(t.map(async r=>{let s=await Ep((r.statements??[]).join(";"));return [r.version,s]}));return Ep(JSON.stringify(n))}var ia,ra,sa,_p=b(()=>{ia='(?:"[^"]+"|[A-Za-z_][\\w$]*)',ra=`${ia}(?:\\s*\\.\\s*${ia})?`,sa=new RegExp([`\\bALTER\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?(${ra})\\s+(?:(ENABLE|DISABLE)\\s+ROW\\s+LEVEL\\s+SECURITY\\b|RENAME\\s+TO\\s+(${ia}))`,`\\bDROP\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(${ra}(?:\\s*,\\s*${ra})*)`].join("|"),"gi");});function qy(e){let t=normalize(e);return t.length>1&&t[t.length-1]===sep&&(t=t.substring(0,t.length-1)),t}function Cp(e,t){return e.replace(Hy,t)}function Wy(e){return e==="/"||Gy.test(e)}function aa(e,t){let{resolvePaths:n,normalizePath:r,pathSeparator:s}=t,i=process.platform==="win32"&&e.includes("/")||e.startsWith(".");if(n&&(e=resolve(e)),(r||i)&&(e=qy(e)),e===".")return "";let o=e[e.length-1]!==s;return Cp(o?e+s:e,s)}function vp(e,t){return t+e}function Vy(e,t){return function(n,r){return r.startsWith(e)?r.slice(e.length)+n:Cp(relative(e,r),t.pathSeparator)+t.pathSeparator+n}}function Ky(e){return e}function zy(e,t,n){return t+e+n}function Xy(e,t){let{relativePaths:n,includeBasePath:r}=t;return n&&e?Vy(e,t):r?vp:Ky}function Jy(e){return function(t,n){n.push(t.substring(e.length)||".");}}function Yy(e){return function(t,n,r){let s=t.substring(e.length)||".";r.every(i=>i(s,true))&&n.push(s);}}function tb(e,t){let{includeDirs:n,filters:r,relativePaths:s}=t;return n?s?r&&r.length?Yy(e):Jy(e):r&&r.length?Zy:Qy:eb}function ab(e){let{excludeFiles:t,filters:n,onlyCounts:r}=e;return t?ob:n&&n.length?r?nb:rb:r?sb:ib}function ub(e){return e.group?lb:cb}function mb(e){return e.group?pb:fb}function gb(e,t){return !e.resolveSymlinks||e.excludeSymlinks?null:t?hb:db}function Rp(e,t,n){if(n.options.useRealPaths)return yb(t,n);let r=dirname(e),s=1;for(;r!==n.root&&s<2;){let i=n.symlinks.get(r);!!i&&(i===t||i.startsWith(t)||t.startsWith(i))?s++:r=dirname(r);}return n.symlinks.set(e,t),s>1}function yb(e,t){return t.visited.includes(e+t.options.pathSeparator)}function Ps(e,t,n,r){t(e&&!r?e:null,n);}function Ab(e,t){let{onlyCounts:n,group:r,maxFiles:s}=e;return n?t?bb:xb:r?t?wb:$b:s?t?Eb:Tb:t?Sb:_b}function Rb(e){return e?vb:Cb}function Lb(e,t){return new Promise((n,r)=>{Np(e,t,(s,i)=>{if(s)return r(s);n(i);});})}function Np(e,t,n){new Pp(e,t,n).start();}function Ob(e,t){return new Pp(e,t).start()}var Tp,Hy,Gy,Qy,Zy,eb,nb,rb,sb,ib,ob,cb,lb,pb,fb,db,hb,bb,wb,Sb,Eb,xb,_b,Tb,$b,kp,Cb,vb,kb,Pb,Nb,Pp,$p,Lp,Op,Ip=b(()=>{Tp=createRequire(import.meta.url);Hy=/[\\/]/g;Gy=/^[a-z]:[\\/]$/i;Qy=(e,t)=>{t.push(e||".");},Zy=(e,t,n)=>{let r=e||".";n.every(s=>s(r,true))&&t.push(r);},eb=()=>{};nb=(e,t,n,r)=>{r.every(s=>s(e,false))&&n.files++;},rb=(e,t,n,r)=>{r.every(s=>s(e,false))&&t.push(e);},sb=(e,t,n,r)=>{n.files++;},ib=(e,t)=>{t.push(e);},ob=()=>{};cb=e=>e,lb=()=>[""].slice(0,0);pb=(e,t,n)=>{e.push({directory:t,files:n,dir:t});},fb=()=>{};db=function(e,t,n){let{queue:r,fs:s,options:{suppressErrors:i}}=t;r.enqueue(),s.realpath(e,(o,a)=>{if(o)return r.dequeue(i?null:o,t);s.stat(a,(c,l)=>{if(c)return r.dequeue(i?null:c,t);if(l.isDirectory()&&Rp(e,a,t))return r.dequeue(null,t);n(l,a),r.dequeue(null,t);});});},hb=function(e,t,n){let{queue:r,fs:s,options:{suppressErrors:i}}=t;r.enqueue();try{let o=s.realpathSync(e),a=s.statSync(o);if(a.isDirectory()&&Rp(e,o,t))return;n(a,o);}catch(o){if(!i)throw o}};bb=e=>e.counts,wb=e=>e.groups,Sb=e=>e.paths,Eb=e=>e.paths.slice(0,e.options.maxFiles),xb=(e,t,n)=>(Ps(t,n,e.counts,e.options.suppressErrors),null),_b=(e,t,n)=>(Ps(t,n,e.paths,e.options.suppressErrors),null),Tb=(e,t,n)=>(Ps(t,n,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),$b=(e,t,n)=>(Ps(t,n,e.groups,e.options.suppressErrors),null);kp={withFileTypes:true},Cb=(e,t,n,r,s)=>{if(e.queue.enqueue(),r<0)return e.queue.dequeue(null,e);let{fs:i}=e;e.visited.push(t),e.counts.directories++,i.readdir(t||".",kp,(o,a=[])=>{s(a,n,r),e.queue.dequeue(e.options.suppressErrors?null:o,e);});},vb=(e,t,n,r,s)=>{let{fs:i}=e;if(r<0)return;e.visited.push(t),e.counts.directories++;let o=[];try{o=i.readdirSync(t||".",kp);}catch(a){if(!e.options.suppressErrors)throw a}s(o,n,r);};kb=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));}},Pb=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}},Nb=class{aborted=false;abort(){this.aborted=true;}},Pp=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(e,t,n){this.isSynchronous=!n,this.callbackInvoker=Ab(t,this.isSynchronous),this.root=aa(e,t),this.state={root:Wy(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new Pb,options:t,queue:new kb((r,s)=>this.callbackInvoker(s,r,n)),symlinks:new Map,visited:[""].slice(0,0),controller:new Nb,fs:t.fs||By},this.joinPath=Xy(this.root,t),this.pushDirectory=tb(this.root,t),this.pushFile=ab(t),this.getArray=ub(t),this.groupFiles=mb(t),this.resolveSymlink=gb(t,this.isSynchronous),this.walkDirectory=Rb(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,n)=>{let{paths:r,options:{filters:s,resolveSymlinks:i,excludeSymlinks:o,exclude:a,maxFiles:c,signal:l,useRealPaths:p,pathSeparator:u},controller:f}=this.state;if(f.aborted||l&&l.aborted||c&&r.length>c)return;let h=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,h,this.state.counts,s);}else if(m.isDirectory()){let y=zy(m.name,t,this.state.options.pathSeparator);if(a&&a(m.name,y))continue;this.pushDirectory(y,r,s),this.walkDirectory(this.state,y,y,n-1,this.walk);}else if(this.resolveSymlink&&m.isSymbolicLink()){let y=vp(m.name,t);this.resolveSymlink(y,this.state,(g,E)=>{if(g.isDirectory()){if(E=aa(E,this.state.options),a&&a(m.name,p?E:y+u))return;this.walkDirectory(this.state,E,p?E:y+u,n-1,this.walk);}else {E=p?E:y;let A=basename(E),$=aa(dirname(E),this.state.options);E=this.joinPath(A,$),this.pushFile(E,h,this.state.counts,s);}});}}this.groupFiles(this.state.groups,t,h);}};$p=class{constructor(e,t){this.root=e,this.options=t;}withPromise(){return Lb(this.root,this.options)}withCallback(e){Np(this.root,this.options,e);}sync(){return Ob(this.root,this.options)}},Lp=null;try{Tp.resolve("picomatch"),Lp=Tp("picomatch");}catch{}Op=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 $p(e||".",this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new $p(e||".",this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:true})}globWithOptions(e,...t){let n=this.globFunction||Lp;if(!n)throw new Error("Please specify a glob function to use glob matching.");var r=this.globCache[e.join("\0")];return r||(r=n(e,...t),this.globCache[e.join("\0")]=r),this.options.filters.push(s=>r(s)),this}};});var Hn=ct((Dv,Mp)=>{var Dp="[^\\\\/]",Ib="(?=.)",jp="[^/]",la="(?:\\/|$)",Fp="(?:^|\\/)",ua=`\\.{1,2}${la}`,Db="(?!\\.)",jb=`(?!${Fp}${ua})`,Fb=`(?!\\.{0,1}${la})`,Ub=`(?!${ua})`,Mb="[^.\\/]",Bb=`${jp}*?`,qb="/",Up={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:Ib,QMARK:jp,END_ANCHOR:la,DOTS_SLASH:ua,NO_DOT:Db,NO_DOTS:jb,NO_DOT_SLASH:Fb,NO_DOTS_SLASH:Ub,QMARK_NO_DOT:Mb,STAR:Bb,START_ANCHOR:Fp,SEP:qb},Hb={...Up,SLASH_LITERAL:"[\\\\/]",QMARK:Dp,STAR:`${Dp}*?`,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:"\\"},Gb={__proto__:null,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"};Mp.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:Gb,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?Hb:Up}};});var Gn=ct(Ce=>{var{REGEX_BACKSLASH:Wb,REGEX_REMOVE_BACKSLASH:Vb,REGEX_SPECIAL_CHARS:Kb,REGEX_SPECIAL_CHARS_GLOBAL:zb}=Hn();Ce.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);Ce.hasRegexChars=e=>Kb.test(e);Ce.isRegexChar=e=>e.length===1&&Ce.hasRegexChars(e);Ce.escapeRegex=e=>e.replace(zb,"\\$1");Ce.toPosixSlashes=e=>e.replace(Wb,"/");Ce.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};Ce.removeBackslashes=e=>e.replace(Vb,t=>t==="\\"?"":t);Ce.escapeLast=(e,t,n)=>{let r=e.lastIndexOf(t,n);return r===-1?e:e[r-1]==="\\"?Ce.escapeLast(e,t,r-1):`${e.slice(0,r)}\\${e.slice(r)}`};Ce.removePrefix=(e,t={})=>{let n=e;return n.startsWith("./")&&(n=n.slice(2),t.prefix="./"),n};Ce.wrapOutput=(e,t={},n={})=>{let r=n.contains?"":"^",s=n.contains?"":"$",i=`${r}(?:${e})${s}`;return t.negated===true&&(i=`(?:^(?!${i}).*$)`),i};Ce.basename=(e,{windows:t}={})=>{let n=e.split(t?/[\\/]/:"/"),r=n[n.length-1];return r===""?n[n.length-2]:r};});var zp=ct((Fv,Kp)=>{var Bp=Gn(),{CHAR_ASTERISK:pa,CHAR_AT:Xb,CHAR_BACKWARD_SLASH:Wn,CHAR_COMMA:Jb,CHAR_DOT:fa,CHAR_EXCLAMATION_MARK:ma,CHAR_FORWARD_SLASH:Vp,CHAR_LEFT_CURLY_BRACE:da,CHAR_LEFT_PARENTHESES:ha,CHAR_LEFT_SQUARE_BRACKET:Yb,CHAR_PLUS:Qb,CHAR_QUESTION_MARK:qp,CHAR_RIGHT_CURLY_BRACE:Zb,CHAR_RIGHT_PARENTHESES:Hp,CHAR_RIGHT_SQUARE_BRACKET:ew}=Hn(),Gp=e=>e===Vp||e===Wn,Wp=e=>{e.isPrefix!==true&&(e.depth=e.isGlobstar?1/0:1);},tw=(e,t)=>{let n=t||{},r=e.length-1,s=n.parts===true||n.scanToEnd===true,i=[],o=[],a=[],c=e,l=-1,p=0,u=0,f=false,h=false,d=false,m=false,y=false,g=false,E=false,A=false,$=false,v=false,C=0,T,_,O={value:"",depth:0,isGlob:false},w=()=>l>=r,I=()=>c.charCodeAt(l+1),N=()=>(T=_,c.charCodeAt(++l));for(;l<r;){_=N();let B;if(_===Wn){E=O.backslashes=true,_=N(),_===da&&(g=true);continue}if(g===true||_===da){for(C++;w()!==true&&(_=N());){if(_===Wn){E=O.backslashes=true,N();continue}if(_===da){C++;continue}if(g!==true&&_===fa&&(_=N())===fa){if(f=O.isBrace=true,d=O.isGlob=true,v=true,s===true)continue;break}if(g!==true&&_===Jb){if(f=O.isBrace=true,d=O.isGlob=true,v=true,s===true)continue;break}if(_===Zb&&(C--,C===0)){g=false,f=O.isBrace=true,v=true;break}}if(s===true)continue;break}if(_===Vp){if(i.push(l),o.push(O),O={value:"",depth:0,isGlob:false},v===true)continue;if(T===fa&&l===p+1){p+=2;continue}u=l+1;continue}if(n.noext!==true&&(_===Qb||_===Xb||_===pa||_===qp||_===ma)===true&&I()===ha){if(d=O.isGlob=true,m=O.isExtglob=true,v=true,_===ma&&l===p&&($=true),s===true){for(;w()!==true&&(_=N());){if(_===Wn){E=O.backslashes=true,_=N();continue}if(_===Hp){d=O.isGlob=true,v=true;break}}continue}break}if(_===pa){if(T===pa&&(y=O.isGlobstar=true),d=O.isGlob=true,v=true,s===true)continue;break}if(_===qp){if(d=O.isGlob=true,v=true,s===true)continue;break}if(_===Yb){for(;w()!==true&&(B=N());){if(B===Wn){E=O.backslashes=true,N();continue}if(B===ew){h=O.isBracket=true,d=O.isGlob=true,v=true;break}}if(s===true)continue;break}if(n.nonegate!==true&&_===ma&&l===p){A=O.negated=true,p++;continue}if(n.noparen!==true&&_===ha){if(d=O.isGlob=true,s===true){for(;w()!==true&&(_=N());){if(_===ha){E=O.backslashes=true,_=N();continue}if(_===Hp){v=true;break}}continue}break}if(d===true){if(v=true,s===true)continue;break}}n.noext===true&&(m=false,d=false);let j=c,S="",x="";p>0&&(S=c.slice(0,p),c=c.slice(p),u-=p),j&&d===true&&u>0?(j=c.slice(0,u),x=c.slice(u)):d===true?(j="",x=c):j=c,j&&j!==""&&j!=="/"&&j!==c&&Gp(j.charCodeAt(j.length-1))&&(j=j.slice(0,-1)),n.unescape===true&&(x&&(x=Bp.removeBackslashes(x)),j&&E===true&&(j=Bp.removeBackslashes(j)));let Z={prefix:S,input:e,start:p,base:j,glob:x,isBrace:f,isBracket:h,isGlob:d,isExtglob:m,isGlobstar:y,negated:A,negatedExtglob:$};if(n.tokens===true&&(Z.maxDepth=0,Gp(_)||o.push(O),Z.tokens=o),n.parts===true||n.tokens===true){let B;for(let D=0;D<i.length;D++){let oe=B?B+1:p,le=i[D],ot=e.slice(oe,le);n.tokens&&(D===0&&p!==0?(o[D].isPrefix=true,o[D].value=S):o[D].value=ot,Wp(o[D]),Z.maxDepth+=o[D].depth),(D!==0||ot!=="")&&a.push(ot),B=le;}if(B&&B+1<e.length){let D=e.slice(B+1);a.push(D),n.tokens&&(o[o.length-1].value=D,Wp(o[o.length-1]),Z.maxDepth+=o[o.length-1].depth);}Z.slashes=i,Z.parts=a;}return Z};Kp.exports=tw;});var Zp=ct((Uv,Qp)=>{var Vn=Hn(),Pe=Gn(),{MAX_LENGTH:Ns,POSIX_REGEX_SOURCE:nw,REGEX_NON_SPECIAL_CHARS:rw,REGEX_SPECIAL_CHARS_BACKREF:sw,REPLACEMENTS:Xp}=Vn,iw=(e,t)=>{if(typeof t.expandRange=="function")return t.expandRange(...e,t);e.sort();let n=`[${e.join("-")}]`;try{new RegExp(n);}catch{return e.map(s=>Pe.escapeRegex(s)).join("..")}return n},rn=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,Jp=e=>{let t=[],n=0,r=0,s=0,i="",o=false;for(let a of e){if(o===true){i+=a,o=false;continue}if(a==="\\"){i+=a,o=true;continue}if(a==='"'){s=s===1?0:1,i+=a;continue}if(s===0){if(a==="[")n++;else if(a==="]"&&n>0)n--;else if(n===0){if(a==="(")r++;else if(a===")"&&r>0)r--;else if(a==="|"&&r===0){t.push(i),i="";continue}}}i+=a;}return t.push(i),t},ow=e=>{let t=false;for(let n of e){if(t===true){t=false;continue}if(n==="\\"){t=true;continue}if(/[?*+@!()[\]{}]/.test(n))return false}return true},Yp=e=>{let t=e.trim(),n=true;for(;n===true;)n=false,/^@\([^\\()[\]{}|]+\)$/.test(t)&&(t=t.slice(2,-1),n=true);if(ow(t))return t.replace(/\\(.)/g,"$1")},aw=e=>{let t=e.map(Yp).filter(Boolean);for(let n=0;n<t.length;n++)for(let r=n+1;r<t.length;r++){let s=t[n],i=t[r],o=s[0];if(!(!o||s!==o.repeat(s.length)||i!==o.repeat(i.length))&&(s===i||s.startsWith(i)||i.startsWith(s)))return true}return false},ga=(e,t=true)=>{if(e[0]!=="+"&&e[0]!=="*"||e[1]!=="(")return;let n=0,r=0,s=0,i=false;for(let o=1;o<e.length;o++){let a=e[o];if(i===true){i=false;continue}if(a==="\\"){i=true;continue}if(a==='"'){s=s===1?0:1;continue}if(s!==1){if(a==="["){n++;continue}if(a==="]"&&n>0){n--;continue}if(!(n>0)){if(a==="("){r++;continue}if(a===")"&&(r--,r===0))return t===true&&o!==e.length-1?void 0:{type:e[0],body:e.slice(2,o),end:o}}}}},cw=e=>{let t=0,n=[];for(;t<e.length;){let s=ga(e.slice(t),false);if(!s||s.type!=="*")return;let i=Jp(s.body).map(a=>a.trim());if(i.length!==1)return;let o=Yp(i[0]);if(!o||o.length!==1)return;n.push(o),t+=s.end+1;}return n.length<1?void 0:`${n.length===1?Pe.escapeRegex(n[0]):`[${n.map(s=>Pe.escapeRegex(s)).join("")}]`}*`},lw=e=>{let t=0,n=e.trim(),r=ga(n);for(;r;)t++,n=r.body.trim(),r=ga(n);return t},uw=(e,t)=>{if(t.maxExtglobRecursion===false)return {risky:false};let n=typeof t.maxExtglobRecursion=="number"?t.maxExtglobRecursion:Vn.DEFAULT_MAX_EXTGLOB_RECURSION,r=Jp(e).map(s=>s.trim());if(r.length>1&&(r.some(s=>s==="")||r.some(s=>/^[*?]+$/.test(s))||aw(r)))return {risky:true};for(let s of r){let i=cw(s);if(i)return {risky:true,safeOutput:i};if(lw(s)>n)return {risky:true}}return {risky:false}},ya=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=Xp[e]||e;let n={...t},r=typeof n.maxLength=="number"?Math.min(Ns,n.maxLength):Ns,s=e.length;if(s>r)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${r}`);let i={type:"bos",value:"",output:n.prepend||""},o=[i],a=n.capture?"":"?:",c=Vn.globChars(n.windows),l=Vn.extglobChars(c),{DOT_LITERAL:p,PLUS_LITERAL:u,SLASH_LITERAL:f,ONE_CHAR:h,DOTS_SLASH:d,NO_DOT:m,NO_DOT_SLASH:y,NO_DOTS_SLASH:g,QMARK:E,QMARK_NO_DOT:A,STAR:$,START_ANCHOR:v}=c,C=P=>`(${a}(?:(?!${v}${P.dot?d:p}).)*?)`,T=n.dot?"":m,_=n.dot?E:A,O=n.bash===true?C(n):$;n.capture&&(O=`(${O})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let w={input:e,index:-1,start:0,dot:n.dot===true,consumed:"",output:"",prefix:"",backtrack:false,negated:false,brackets:0,braces:0,parens:0,quotes:0,globstar:false,tokens:o};e=Pe.removePrefix(e,w),s=e.length;let I=[],N=[],j=[],S=i,x,Z=()=>w.index===s-1,B=w.peek=(P=1)=>e[w.index+P],D=w.advance=()=>e[++w.index]||"",oe=()=>e.slice(w.index+1),le=(P="",ae=0)=>{w.consumed+=P,w.index+=ae;},ot=P=>{w.output+=P.output!=null?P.output:P.value,le(P.value);},Nh=()=>{let P=1;for(;B()==="!"&&(B(2)!=="("||B(3)==="?");)D(),w.start++,P++;return P%2===0?false:(w.negated=true,w.start++,true)},Lr=P=>{w[P]++,j.push(P);},at=P=>{w[P]--,j.pop();},H=P=>{if(S.type==="globstar"){let ae=w.braces>0&&(P.type==="comma"||P.type==="brace"),R=P.extglob===true||I.length&&(P.type==="pipe"||P.type==="paren");P.type!=="slash"&&P.type!=="paren"&&!ae&&!R&&(w.output=w.output.slice(0,-S.output.length),S.type="star",S.value="*",S.output=O,w.output+=S.output);}if(I.length&&P.type!=="paren"&&(I[I.length-1].inner+=P.value),(P.value||P.output)&&ot(P),S&&S.type==="text"&&P.type==="text"){S.output=(S.output||S.value)+P.value,S.value+=P.value;return}P.prev=S,o.push(P),S=P;},Or=(P,ae)=>{let R={...l[ae],conditions:1,inner:""};R.prev=S,R.parens=w.parens,R.output=w.output,R.startIndex=w.index,R.tokensIndex=o.length;let G=(n.capture?"(":"")+R.open;Lr("parens"),H({type:P,value:ae,output:w.output?"":h}),H({type:"paren",extglob:true,value:D(),output:G}),I.push(R);},Lh=P=>{let ae=e.slice(P.startIndex,w.index+1),R=e.slice(P.startIndex+2,w.index),G=uw(R,n);if((P.type==="plus"||P.type==="star")&&G.risky){let te=G.safeOutput?(P.output?"":h)+(n.capture?`(${G.safeOutput})`:G.safeOutput):void 0,Ke=o[P.tokensIndex];Ke.type="text",Ke.value=ae,Ke.output=te||Pe.escapeRegex(ae);for(let ze=P.tokensIndex+1;ze<o.length;ze++)o[ze].value="",o[ze].output="",delete o[ze].suffix;w.output=P.output+Ke.output,w.backtrack=true,H({type:"paren",extglob:true,value:x,output:""}),at("parens");return}let se=P.close+(n.capture?")":""),he;if(P.type==="negate"){let te=O;if(P.inner&&P.inner.length>1&&P.inner.includes("/")&&(te=C(n)),(te!==O||Z()||/^\)+$/.test(oe()))&&(se=P.close=`)$))${te}`),P.inner.includes("*")&&(he=oe())&&/^\.[^\\/.]+$/.test(he)){let Ke=ya(he,{...t,fastpaths:false}).output;se=P.close=`)${Ke})${te})`;}P.prev.type==="bos"&&(w.negatedExtglob=true);}H({type:"paren",extglob:true,value:x,output:se}),at("parens");};if(n.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let P=false,ae=e.replace(sw,(R,G,se,he,te,Ke)=>he==="\\"?(P=true,R):he==="?"?G?G+he+(te?E.repeat(te.length):""):Ke===0?_+(te?E.repeat(te.length):""):E.repeat(se.length):he==="."?p.repeat(se.length):he==="*"?G?G+he+(te?O:""):O:G?R:`\\${R}`);return P===true&&(n.unescape===true?ae=ae.replace(/\\/g,""):ae=ae.replace(/\\+/g,R=>R.length%2===0?"\\\\":R?"\\":"")),ae===e&&n.contains===true?(w.output=e,w):(w.output=Pe.wrapOutput(ae,w,t),w)}for(;!Z();){if(x=D(),x==="\0")continue;if(x==="\\"){let R=B();if(R==="/"&&n.bash!==true||R==="."||R===";")continue;if(!R){x+="\\",H({type:"text",value:x});continue}let G=/^\\+/.exec(oe()),se=0;if(G&&G[0].length>2&&(se=G[0].length,w.index+=se,se%2!==0&&(x+="\\")),n.unescape===true?x=D():x+=D(),w.brackets===0){H({type:"text",value:x});continue}}if(w.brackets>0&&(x!=="]"||S.value==="["||S.value==="[^")){if(n.posix!==false&&x===":"){let R=S.value.slice(1);if(R.includes("[")&&(S.posix=true,R.includes(":"))){let G=S.value.lastIndexOf("["),se=S.value.slice(0,G),he=S.value.slice(G+2),te=nw[he];if(te){S.value=se+te,w.backtrack=true,D(),!i.output&&o.indexOf(S)===1&&(i.output=h);continue}}}(x==="["&&B()!==":"||x==="-"&&B()==="]")&&(x=`\\${x}`),x==="]"&&(S.value==="["||S.value==="[^")&&(x=`\\${x}`),n.posix===true&&x==="!"&&S.value==="["&&(x="^"),S.value+=x,ot({value:x});continue}if(w.quotes===1&&x!=='"'){x=Pe.escapeRegex(x),S.value+=x,ot({value:x});continue}if(x==='"'){w.quotes=w.quotes===1?0:1,n.keepQuotes===true&&H({type:"text",value:x});continue}if(x==="("){Lr("parens"),H({type:"paren",value:x});continue}if(x===")"){if(w.parens===0&&n.strictBrackets===true)throw new SyntaxError(rn("opening","("));let R=I[I.length-1];if(R&&w.parens===R.parens+1){Lh(I.pop());continue}H({type:"paren",value:x,output:w.parens?")":"\\)"}),at("parens");continue}if(x==="["){if(n.nobracket===true||!oe().includes("]")){if(n.nobracket!==true&&n.strictBrackets===true)throw new SyntaxError(rn("closing","]"));x=`\\${x}`;}else Lr("brackets");H({type:"bracket",value:x});continue}if(x==="]"){if(n.nobracket===true||S&&S.type==="bracket"&&S.value.length===1){H({type:"text",value:x,output:`\\${x}`});continue}if(w.brackets===0){if(n.strictBrackets===true)throw new SyntaxError(rn("opening","["));H({type:"text",value:x,output:`\\${x}`});continue}at("brackets");let R=S.value.slice(1);if(S.posix!==true&&R[0]==="^"&&!R.includes("/")&&(x=`/${x}`),S.value+=x,ot({value:x}),n.literalBrackets===false||Pe.hasRegexChars(R))continue;let G=Pe.escapeRegex(S.value);if(w.output=w.output.slice(0,-S.value.length),n.literalBrackets===true){w.output+=G,S.value=G;continue}S.value=`(${a}${G}|${S.value})`,w.output+=S.value;continue}if(x==="{"&&n.nobrace!==true){Lr("braces");let R={type:"brace",value:x,output:"(",outputIndex:w.output.length,tokensIndex:w.tokens.length};N.push(R),H(R);continue}if(x==="}"){let R=N[N.length-1];if(n.nobrace===true||!R){H({type:"text",value:x,output:x});continue}let G=")";if(R.dots===true){let se=o.slice(),he=[];for(let te=se.length-1;te>=0&&(o.pop(),se[te].type!=="brace");te--)se[te].type!=="dots"&&he.unshift(se[te].value);G=iw(he,n),w.backtrack=true;}if(R.comma!==true&&R.dots!==true){let se=w.output.slice(0,R.outputIndex),he=w.tokens.slice(R.tokensIndex);R.value=R.output="\\{",x=G="\\}",w.output=se;for(let te of he)w.output+=te.output||te.value;}H({type:"brace",value:x,output:G}),at("braces"),N.pop();continue}if(x==="|"){I.length>0&&I[I.length-1].conditions++,H({type:"text",value:x});continue}if(x===","){let R=x,G=N[N.length-1];G&&j[j.length-1]==="braces"&&(G.comma=true,R="|"),H({type:"comma",value:x,output:R});continue}if(x==="/"){if(S.type==="dot"&&w.index===w.start+1){w.start=w.index+1,w.consumed="",w.output="",o.pop(),S=i;continue}H({type:"slash",value:x,output:f});continue}if(x==="."){if(w.braces>0&&S.type==="dot"){S.value==="."&&(S.output=p);let R=N[N.length-1];S.type="dots",S.output+=x,S.value+=x,R.dots=true;continue}if(w.braces+w.parens===0&&S.type!=="bos"&&S.type!=="slash"){H({type:"text",value:x,output:p});continue}H({type:"dot",value:x,output:p});continue}if(x==="?"){if(!(S&&S.value==="(")&&n.noextglob!==true&&B()==="("&&B(2)!=="?"){Or("qmark",x);continue}if(S&&S.type==="paren"){let G=B(),se=x;(S.value==="("&&!/[!=<:]/.test(G)||G==="<"&&!/<([!=]|\w+>)/.test(oe()))&&(se=`\\${x}`),H({type:"text",value:x,output:se});continue}if(n.dot!==true&&(S.type==="slash"||S.type==="bos")){H({type:"qmark",value:x,output:A});continue}H({type:"qmark",value:x,output:E});continue}if(x==="!"){if(n.noextglob!==true&&B()==="("&&(B(2)!=="?"||!/[!=<:]/.test(B(3)))){Or("negate",x);continue}if(n.nonegate!==true&&w.index===0){Nh();continue}}if(x==="+"){if(n.noextglob!==true&&B()==="("&&B(2)!=="?"){Or("plus",x);continue}if(S&&S.value==="("||n.regex===false){H({type:"plus",value:x,output:u});continue}if(S&&(S.type==="bracket"||S.type==="paren"||S.type==="brace")||w.parens>0){H({type:"plus",value:x});continue}H({type:"plus",value:u});continue}if(x==="@"){if(n.noextglob!==true&&B()==="("&&B(2)!=="?"){H({type:"at",extglob:true,value:x,output:""});continue}H({type:"text",value:x});continue}if(x!=="*"){(x==="$"||x==="^")&&(x=`\\${x}`);let R=rw.exec(oe());R&&(x+=R[0],w.index+=R[0].length),H({type:"text",value:x});continue}if(S&&(S.type==="globstar"||S.star===true)){S.type="star",S.star=true,S.value+=x,S.output=O,w.backtrack=true,w.globstar=true,le(x);continue}let P=oe();if(n.noextglob!==true&&/^\([^?]/.test(P)){Or("star",x);continue}if(S.type==="star"){if(n.noglobstar===true){le(x);continue}let R=S.prev,G=R.prev,se=R.type==="slash"||R.type==="bos",he=G&&(G.type==="star"||G.type==="globstar");if(n.bash===true&&(!se||P[0]&&P[0]!=="/")){H({type:"star",value:x,output:""});continue}let te=w.braces>0&&(R.type==="comma"||R.type==="brace"),Ke=I.length&&(R.type==="pipe"||R.type==="paren");if(!se&&R.type!=="paren"&&!te&&!Ke){H({type:"star",value:x,output:""});continue}for(;P.slice(0,3)==="/**";){let ze=e[w.index+4];if(ze&&ze!=="/")break;P=P.slice(3),le("/**",3);}if(R.type==="bos"&&Z()){S.type="globstar",S.value+=x,S.output=C(n),w.output=S.output,w.globstar=true,le(x);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&!he&&Z()){w.output=w.output.slice(0,-(R.output+S.output).length),R.output=`(?:${R.output}`,S.type="globstar",S.output=C(n)+(n.strictSlashes?")":"|$)"),S.value+=x,w.globstar=true,w.output+=R.output+S.output,le(x);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&P[0]==="/"){let ze=P[1]!==void 0?"|$":"";w.output=w.output.slice(0,-(R.output+S.output).length),R.output=`(?:${R.output}`,S.type="globstar",S.output=`${C(n)}${f}|${f}${ze})`,S.value+=x,w.output+=R.output+S.output,w.globstar=true,le(x+D()),H({type:"slash",value:"/",output:""});continue}if(R.type==="bos"&&P[0]==="/"){S.type="globstar",S.value+=x,S.output=`(?:^|${f}|${C(n)}${f})`,w.output=S.output,w.globstar=true,le(x+D()),H({type:"slash",value:"/",output:""});continue}w.output=w.output.slice(0,-S.output.length),S.type="globstar",S.output=C(n),S.value+=x,w.output+=S.output,w.globstar=true,le(x);continue}let ae={type:"star",value:x,output:O};if(n.bash===true){ae.output=".*?",(S.type==="bos"||S.type==="slash")&&(ae.output=T+ae.output),H(ae);continue}if(S&&(S.type==="bracket"||S.type==="paren")&&n.regex===true){ae.output=x,H(ae);continue}(w.index===w.start||S.type==="slash"||S.type==="dot")&&(S.type==="dot"?(w.output+=y,S.output+=y):n.dot===true?(w.output+=g,S.output+=g):(w.output+=T,S.output+=T),B()!=="*"&&(w.output+=h,S.output+=h)),H(ae);}for(;w.brackets>0;){if(n.strictBrackets===true)throw new SyntaxError(rn("closing","]"));w.output=Pe.escapeLast(w.output,"["),at("brackets");}for(;w.parens>0;){if(n.strictBrackets===true)throw new SyntaxError(rn("closing",")"));w.output=Pe.escapeLast(w.output,"("),at("parens");}for(;w.braces>0;){if(n.strictBrackets===true)throw new SyntaxError(rn("closing","}"));w.output=Pe.escapeLast(w.output,"{"),at("braces");}if(n.strictSlashes!==true&&(S.type==="star"||S.type==="bracket")&&H({type:"maybe_slash",value:"",output:`${f}?`}),w.backtrack===true){w.output="";for(let P of w.tokens)w.output+=P.output!=null?P.output:P.value,P.suffix&&(w.output+=P.suffix);}return w};ya.fastpaths=(e,t)=>{let n={...t},r=typeof n.maxLength=="number"?Math.min(Ns,n.maxLength):Ns,s=e.length;if(s>r)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${r}`);e=Xp[e]||e;let{DOT_LITERAL:i,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:c,NO_DOT:l,NO_DOTS:p,NO_DOTS_SLASH:u,STAR:f,START_ANCHOR:h}=Vn.globChars(n.windows),d=n.dot?p:l,m=n.dot?u:l,y=n.capture?"":"?:",g={negated:false,prefix:""},E=n.bash===true?".*?":f;n.capture&&(E=`(${E})`);let A=T=>T.noglobstar===true?E:`(${y}(?:(?!${h}${T.dot?c:i}).)*?)`,$=T=>{switch(T){case "*":return `${d}${a}${E}`;case ".*":return `${i}${a}${E}`;case "*.*":return `${d}${E}${i}${a}${E}`;case "*/*":return `${d}${E}${o}${a}${m}${E}`;case "**":return d+A(n);case "**/*":return `(?:${d}${A(n)}${o})?${m}${a}${E}`;case "**/*.*":return `(?:${d}${A(n)}${o})?${m}${E}${i}${a}${E}`;case "**/.*":return `(?:${d}${A(n)}${o})?${i}${a}${E}`;default:{let _=/^(.*?)\.(\w+)$/.exec(T);if(!_)return;let O=$(_[1]);return O?O+i+_[2]:void 0}}},v=Pe.removePrefix(e,g),C=$(v);return C&&n.strictSlashes!==true&&(C+=`${o}?`),C};Qp.exports=ya;});var nf=ct((Mv,tf)=>{var pw=zp(),ba=Zp(),ef=Gn(),fw=Hn(),mw=e=>e&&typeof e=="object"&&!Array.isArray(e),ue=(e,t,n=false)=>{if(Array.isArray(e)){let p=e.map(f=>ue(f,t,n));return f=>{for(let h of p){let d=h(f);if(d)return d}return false}}let r=mw(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!r)throw new TypeError("Expected pattern to be a non-empty string");let s=t||{},i=s.windows,o=r?ue.compileRe(e,t):ue.makeRe(e,t,false,true),a=o.state;delete o.state;let c=()=>false;if(s.ignore){let p={...t,ignore:null,onMatch:null,onResult:null};c=ue(s.ignore,p,n);}let l=(p,u=false)=>{let{isMatch:f,match:h,output:d}=ue.test(p,o,t,{glob:e,posix:i}),m={glob:e,state:a,regex:o,posix:i,input:p,output:d,match:h,isMatch:f};return typeof s.onResult=="function"&&s.onResult(m),f===false?(m.isMatch=false,u?m:false):c(p)?(typeof s.onIgnore=="function"&&s.onIgnore(m),m.isMatch=false,u?m:false):(typeof s.onMatch=="function"&&s.onMatch(m),u?m:true)};return n&&(l.state=a),l};ue.test=(e,t,n,{glob:r,posix:s}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return {isMatch:false,output:""};let i=n||{},o=i.format||(s?ef.toPosixSlashes:null),a=e===r,c=a&&o?o(e):e;return a===false&&(c=o?o(e):e,a=c===r),(a===false||i.capture===true)&&(i.matchBase===true||i.basename===true?a=ue.matchBase(e,t,n,s):a=t.exec(c)),{isMatch:!!a,match:a,output:c}};ue.matchBase=(e,t,n)=>(t instanceof RegExp?t:ue.makeRe(t,n)).test(ef.basename(e));ue.isMatch=(e,t,n)=>ue(t,n)(e);ue.parse=(e,t)=>Array.isArray(e)?e.map(n=>ue.parse(n,t)):ba(e,{...t,fastpaths:false});ue.scan=(e,t)=>pw(e,t);ue.compileRe=(e,t,n=false,r=false)=>{if(n===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 c=ue.toRegex(a,t);return r===true&&(c.state=e),c};ue.makeRe=(e,t={},n=false,r=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=ba.fastpaths(e,t)),s.output||(s=ba(e,t)),ue.compileRe(s,t,n,r)};ue.toRegex=(e,t)=>{try{let n=t||{};return new RegExp(e,n.flags||(n.nocase?"i":""))}catch(n){if(t&&t.debug===true)throw n;return /$^/}};ue.constants=fw;tf.exports=ue;});var af=ct((Bv,of)=>{var rf=nf(),dw=Gn();function sf(e,t,n=false){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:dw.isWindows()}),rf(e,t,n)}Object.assign(sf,rf);of.exports=sf;});function Cw(e,t={}){let n=e.length,r=Array(n),s=Array(n),i,o;for(i=0;i<n;i++){let a=mf(e[i]);r[i]=a;let c=a.length,l=Array(c);for(o=0;o<c;o++)l[o]=(0, sn.default)(a[o],t);s[i]=l;}return a=>{let c=a.split("/");if(c[0]===".."&&Aw.test(a))return true;for(i=0;i<n;i++){let l=r[i],p=s[i],u=c.length,f=Math.min(u,l.length);for(o=0;o<f;){let h=l[o];if(h.includes("/"))return true;if(!p[o](c[o]))break;if(!t.noglobstar&&h==="**")return true;o++;}if(o===u)return true}return false}}function cf(e,t,n){if(e===t||t.startsWith(`${e}/`)){if(n){let s=e.length+ +!Rw(e);return (i,o)=>i.slice(s,o?-1:void 0)||"."}let r=t.slice(e.length+1);return r?(s,i)=>{if(s===".")return r;let o=`${r}/${s}`;return i?o.slice(0,-1):o}:(s,i)=>i&&s!=="."?s.slice(0,-1):s}return n?r=>posix.relative(e,r)||".":r=>posix.relative(e,`${t}/${r}`)||"."}function kw(e,t){if(t.startsWith(`${e}/`)){let n=t.slice(e.length+1);return r=>`${n}/${r}`}return n=>{let r=posix.relative(e,`${t}/${n}`);return n[n.length-1]==="/"&&r!==""?`${r}/`:r||"."}}function lf(e){return e.replace($w,t=>`${t}/`)}function mf(e){var t;let n=sn.default.scan(e,Pw);return !((t=n.parts)===null||t===void 0)&&t.length?n.parts:[e]}function jw(e,t){let n=sn.default.scan(e);return n.isGlob||n.negated}function Kn(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...e);}function df(e){return typeof e=="string"?[e]:e??[]}function wa(e,t,n,r){var s;let i=t.cwd,o=e;e[e.length-1]==="/"&&(o=e.slice(0,-1)),o[o.length-1]!=="*"&&t.expandDirectories&&(o+="/**");let a=Dw(i);o=isAbsolute(o.replace(Uw,""))?posix.relative(a,o):posix.normalize(o);let c=(s=Fw.exec(o))===null||s===void 0?void 0:s[0],l=mf(o);if(c){let u=(c.length+1)/3,f=0,h=a.split("/");for(;f<u&&l[f+u]===h[h.length+f-u];)o=o.slice(0,(u-f-1)*3)+o.slice((u-f)*3+l[f+u].length+1)||".",f++;let d=posix.join(i,c.slice(f*3));d[0]!=="."&&n.root.length>d.length&&(n.root=lf(d),n.depthOffset=-u+f);}if(!r&&n.depthOffset>=0){var p;(p=n.commonPath)!==null&&p!==void 0||(n.commonPath=l);let u=[],f=Math.min(n.commonPath.length,l.length);for(let h=0;h<f;h++){let d=l[h];if(d==="**"&&!l[h+1]){u.pop();break}if(h===l.length-1||d!==n.commonPath[h]||jw(d))break;u.push(d);}n.depthOffset=u.length,n.commonPath=u,n.root=lf(u.length>0?posix.join(i,...u):i);}return o}function Mw(e,t,n){let r=[],s=[];for(let i of e.ignore)i&&(i[0]!=="!"||i[1]==="(")&&s.push(wa(i,e,n,true));for(let i of t)i&&(i[0]!=="!"||i[1]==="("?r.push(wa(i,e,n,false)):(i[1]!=="!"||i[2]==="(")&&s.push(wa(i.slice(1),e,n,true)));return {match:r,ignore:s}}function Bw(e,t){let n=e.cwd,r={root:n,depthOffset:0},s=Mw(e,t,r);e.debug&&Kn("internal processing patterns:",s);let{absolute:i,caseSensitiveMatch:o,debug:a,dot:c,followSymbolicLinks:l,onlyDirectories:p}=e,u=r.root.replace(pf,""),f={dot:c,nobrace:e.braceExpansion===false,nocase:!o,noextglob:e.extglob===false,noglobstar:e.globstar===false,posix:true},h=(0, sn.default)(s.match,f),d=(0, sn.default)(s.ignore,f),m=Cw(s.match,f),y=cf(n,u,i),g=i?y:cf(n,u,true),E=(v,C)=>{let T=g(C,true);return T!=="."&&!m(T)||d(T)},A;e.deep!==void 0&&(A=Math.round(e.deep-r.depthOffset));let $=new Op({filters:[a?(v,C)=>{let T=y(v,C),_=h(T)&&!d(T);return _&&Kn(`matched ${T}`),_}:(v,C)=>{let T=y(v,C);return h(T)&&!d(T)}],exclude:a?(v,C)=>{let T=E(v,C);return Kn(`${T?"skipped":"crawling"} ${C}`),T}:E,fs:e.fs,pathSeparator:"/",relativePaths:!i,resolvePaths:i,includeBasePath:i,resolveSymlinks:l,excludeSymlinks:!l,excludeFiles:p,includeDirs:p||!e.onlyFiles,maxDepth:A,signal:e.signal}).crawl(u);return e.debug&&Kn("internal properties:",{...r,root:u}),[$,n!==u&&!i&&kw(n,u)]}function qw(e,t){if(t)for(let n=e.length-1;n>=0;n--)e[n]=t(e[n]);return e}function Hw(e){let t=Object.assign({},e);for(let n in uf)t[n]===void 0&&Object.assign(t,{[n]:uf[n]});return t.cwd=(t.cwd instanceof URL?fileURLToPath$1(t.cwd):resolve(t.cwd||process.cwd())).replace(pf,"/"),t.ignore=df(t.ignore),t.fs&&(t.fs={readdir:t.fs.readdir||readdir,readdirSync:t.fs.readdirSync||readdirSync,realpath:t.fs.realpath||realpath,realpathSync:t.fs.realpathSync||realpathSync,stat:t.fs.stat||stat,statSync:t.fs.statSync||statSync$1}),t.debug&&Kn("globbing with options:",t),t}function Gw(e,t={}){var n;if(e&&t?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let r=Tw(e)||typeof e=="string",s=df((n=r?e:e.patterns)!==null&&n!==void 0?n:"**/*"),i=Hw(r?t:e);return s.length>0?Bw(i,s):[]}async function zn(e,t){let[n,r]=Gw(e,t);return n?qw(await n.withPromise(),r):[]}var sn,Tw,pf,$w,ff,Aw,vw,Rw,Pw,Nw,Lw,Ow,Iw,Dw,Fw,Uw,uf,Sa=b(()=>{Ip();sn=V(af()),Tw=Array.isArray,pf=/\\/g,$w=/^[A-Za-z]:$/,ff=process.platform==="win32",Aw=/^(\/?\.\.)+$/;vw=/^[A-Z]:\/$/i,Rw=ff?e=>vw.test(e):e=>e==="/";Pw={parts:true};Nw=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,Lw=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,Ow=e=>e.replace(Nw,"\\$&"),Iw=e=>e.replace(Lw,"\\$&"),Dw=ff?Iw:Ow;Fw=/^(\/?\.\.)+/,Uw=/\\(?=[()[\]{}!*+?@|])/g;uf={caseSensitiveMatch:true,debug:!!process.env.TINYGLOBBY_DEBUG,expandDirectories:true,followSymbolicLinks:true,onlyFiles:true};});function gf(e){return xe(e.connection)==="sqlite"?"./sqlite-migrations/*.sql":"./migrations/*.sql"}function Ot(e){return Oe__default.posix.dirname(gf(e))}async function Ie(e){let t=Oe__default.join(process.cwd(),"supabase"),n=await zn([gf(e)],{cwd:t,absolute:true}),r=[];for(let s of n){let i=Oe__default.basename(s),o=Ww.exec(i);if(!o)continue;let a=await de__default.readFile(s,"utf-8");r.push({version:o[1],name:o[2]??null,filename:i,path:s,sql:a});}return r.sort((s,i)=>s.version.localeCompare(i.version))}async function Jn(e){return (await Ie(e)).map(n=>n.sql).join(`
90
+ `)}function Ea(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 xa(e,t=Ea()){let n=e.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_|_$/g,"");return n.length>0?`${t}_${n}.sql`:`${t}.sql`}async function yf(e,t,n){let r=Oe__default.join(process.cwd(),"supabase",Ot(e));$e(r);let s=xa(t,n?.ts),i=Oe__default.join(r,s);return await de__default.writeFile(i,"",{flag:"wx"}),i}var Ww,dt=b(()=>{Sa();mt();_t();Ww=/^(\d{14})(?:_([^.]+))?\.sql$/;});function Yn(e){if("String"in e)return e.String.sval}function nt(e){return e.map(Yn).filter(t=>t!=null)}function It(e){return e==null?[]:e.List!==void 0?e.List.items||[]:Array.isArray(e)?e:[e]}function Ls(e){return QuoteUtils.quoteIdentifier(e)}function on(e){return Object.keys(e)[0]}function bf(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 Dt=b(()=>{});function Sf(e){let t=e.toLowerCase().trim();if(t.startsWith("_")||t.endsWith("[]"))return "TEXT";let n=zw[t];if(!n)throw new jt(`Unsupported PostgreSQL type: "${e}"`);return n}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 Ds(e){let t=e.toLowerCase();return ["numeric","decimal"].includes(t)}var jt,M,zw,wf,Xw,js,an=b(()=>{Dt();jt=class extends Error{},M=class extends jt{constructor(n,r){super(r??`Unsupported node type: ${on(n)}`);this.node=n;}},zw={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"},wf=["<",">","<=",">=","=","<>","!=","+","-","*","/","%","&","|","<<",">>","||","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","->>"];Xw={CreateEnumStmt:{react:"ignore"},CreateDomainStmt:{react:"warn"},CreateSeqStmt:{react:"ignore"},AlterSeqStmt:{react:"ignore"},CreateSchemaStmt:{react:"warn"},CreatePolicyStmt:{react:"ignore"},AlterPolicyStmt:{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"}},js=new Map(Object.entries(Xw));});var De,Qn,_a=b(()=>{Dt();an();De=class extends M{constructor(t,n){super(t,`Unsupported expression: ${n}`);}},Qn=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 n=Object.keys(t)[0],r=this[n];if(!r)throw new De({[n]:t},`Unsupported expression: ${n}`);return r.call(this,t[n])}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 r=this.isJwtAccessor(t.A_Expr);return r||this.A_Expr(t.A_Expr)}if("BoolExpr"in t)return this.BoolExpr(t.BoolExpr);let n=Object.keys(t)[0];throw new De({[n]:t},`deparseValue: ${n}`)}A_Expr(t){if(t.kind==="AEXPR_OP"){let n=t.name?.[0],r=n?Yn(n):void 0;if(!r)throw new De({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(r);if(!a)throw new De({A_Expr:t},`Unsupported operator: ${r}`);let c=t.rexpr!=null&&"ColumnRef"in t.rexpr;if(typeof i=="string"&&i.startsWith("{{")&&c)return {[o]:{[a]:i}};let l=c&&typeof o=="string"?{$ref:o}:o;return {[i]:{[a]:l}}}if(t.kind==="AEXPR_LIKE"||t.kind==="AEXPR_ILIKE"){let n=t.lexpr?this.deparseValue(t.lexpr):void 0,r=t.rexpr?this.deparseValue(t.rexpr):void 0,i=(t.name?.[0]?Yn(t.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[n]:{[i]:r}}}if(t.kind==="AEXPR_IN"){let n=t.lexpr?this.deparseValue(t.lexpr):void 0,r=t.rexpr&&"List"in t.rexpr&&t.rexpr.List.items?t.rexpr.List.items.map(s=>this.deparseValue(s)):[];return {[n]:{$in:r}}}throw new De({A_Expr:t},`A_Expr kind: ${t.kind}`)}BoolExpr(t){let n=t.args??[];switch(t.boolop){case "AND_EXPR":return {$and:n.map(r=>this.deparse(r))};case "OR_EXPR":return {$or:n.map(r=>this.deparse(r))};case "NOT_EXPR":return {$not:this.deparse(n[0])};default:throw new De({BoolExpr:t},`BoolExpr op: ${t.boolop}`)}}NullTest(t){let n=t.arg?this.deparseValue(t.arg):void 0;return t.nulltesttype==="IS_NULL"?{[n]:{$is:null}}:{[n]:{$isNot:null}}}SubLink(t){if(t.subLinkType==="ANY_SUBLINK"){let n=t.testexpr?this.deparseValue(t.testexpr):void 0,r=t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0;return {[n]:{$in:r}}}if(t.subLinkType==="EXISTS_SUBLINK")return {$exists:t.subselect?this.SelectStmt(t.subselect.SelectStmt):void 0};if(t.subLinkType==="EXPR_SUBLINK"){let n=t.subselect?t.subselect.SelectStmt:void 0;if(n?.fromClause?.length)return this.SelectStmt(n);if(n?.targetList?.[0]){let r=n.targetList[0],s="ResTarget"in r?r.ResTarget:void 0;if(s?.val){let i=this.deparseValue(s.val);return i}}}throw new De({SubLink:t},`SubLink type: ${t.subLinkType}`)}SelectStmt(t){let{from:n,schema:r,join:s}=this.deparseFromClause(t.fromClause??[]),i=[];for(let f of t.targetList??[]){let h="ResTarget"in f?f.ResTarget:void 0;if(h?.val){let d=this.deparseValue(h.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),c=this.deparseLimit(t.limitCount),l=this.deparseLimit(t.limitOffset),p=this.deparseGroupClause(t.groupClause),u={type:"query",from:n,select:i};return r&&(u.schema=r),Object.keys(s).length>0&&(u.join=s),o&&(u.where=o),a.length>0&&(u.order=a),c!==void 0&&(u.limit=c),l!==void 0&&(u.offset=l),p.length>0&&(u.group=p),u}FuncCall(t){let n=this.isAuthFunc(t.funcname??[]);if(n)return n;throw new De({FuncCall:t},`FuncCall: ${nt(t.funcname??[]).join(".")}`)}ColumnRef(t){let n=nt(t.fields??[]);return n.length===1?n[0]:n.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 De({A_Const:t},"A_Const: unknown variant")}TypeCast(t){if(!t.arg)throw new De({TypeCast:t},"TypeCast: missing arg");return this.deparseValue(t.arg)}BooleanTest(t){let n=t.arg?this.deparseValue(t.arg):void 0;return t.booltesttype==="IS_TRUE"?{[n]:{$eq:true}}:{[n]:{$eq:false}}}deparseFromClause(t){let n={};if(t.length===0)return {from:"",join:n};let r=t[0];if("RangeVar"in r){let s=r.RangeVar;return {from:s.relname??"",schema:s.schemaname,join:n}}if("JoinExpr"in r){let{from:s,schema:i}=this.walkJoinExpr(r.JoinExpr,n);return {from:s,schema:i,join:n}}return {from:"",join:n}}walkJoinExpr(t,n){let r={from:""};if(t.larg)if("RangeVar"in t.larg){let s=t.larg.RangeVar;r={from:s.relname??"",schema:s.schemaname};}else "JoinExpr"in t.larg&&(r=this.walkJoinExpr(t.larg.JoinExpr,n));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",c={from:i,type:a};t.quals&&(c.on=this.deparse(t.quals));let l=o;if(l in n){let p=2;for(;`${l}_${p}`in n;)p++;l=`${l}_${p}`;}n[l]=c;}return r}deparseSortClause(t){if(!t)return [];let n=[];for(let r of t){if(!("SortBy"in r))continue;let s=r.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),n.push(a);}return n}deparseLimit(t){if(!t)return;let n=this.deparseValue(t);return typeof n=="number"?n:Number(n)}deparseGroupClause(t){return t?t.map(n=>String(this.deparseValue(n))):[]}isAuthFunc(t){let n=nt(t);if(n.length===2&&n[0]==="auth"){if(n[1]==="uid")return "{{auth.uid}}";if(n[1]==="jwt")return "{{auth.jwt}}";if(n[1]==="role")return "{{auth.role}}";throw new Error(`Unsupported auth function: "${n.slice(1).join(".")}"`)}return null}isJwtAccessor(t){if(t.kind!=="AEXPR_OP")return null;let n=t.name?.[0]?Yn(t.name[0]):void 0;if(n!=="->"&&n!=="->>")return null;let r=t.rexpr&&"A_Const"in t.rexpr?t.rexpr.A_Const.sval?.sval:void 0;if(r===void 0)return null;if(t.lexpr&&"FuncCall"in t.lexpr)return this.isAuthFunc(t.lexpr.FuncCall.funcname??[])==="{{auth.jwt}}"?`{{auth.jwt.${r}}}`:null;if(t.lexpr&&"A_Expr"in t.lexpr){let s=this.isJwtAccessor(t.lexpr.A_Expr);if(s)return `${s.slice(0,-2)}.${r}}}`}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 ht,Ta=b(()=>{ht=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 Zn,$a=b(()=>{Zn=class extends Error{constructor(n,r,s,i){super(`check constraint "${s}" violated for ${n}.${r}`);this.table=n;this.column=r;this.constraint=s;this.value=i;this.name="CheckConstraintError";}};});var ge,rt=b(()=>{$a();ge=class{context;factoryExtra;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,n){return {status:"fail",message:t,action:n}}validationPass(){return {status:"pass",message:null}}isNullish(t){return t==null}toColumnDDL(t){let{includeNullable:n=true}=t??{},r=[],s=this.context.column;r.push(this.quoteIfNeeded(s)),r.push(this.sqliteType),this.context.isPrimaryKey&&r.push("PRIMARY KEY"),this.context.isSerial&&this.context.isPrimaryKey&&r.push("AUTOINCREMENT"),n&&!this.context.nullable&&!this.context.isPrimaryKey&&r.push("NOT NULL"),this.context.isUnique&&!this.context.isPrimaryKey&&r.push("UNIQUE"),this.context.defaultValue!==null&&r.push(`DEFAULT ${this.context.defaultValue}`);let i=this.checkConstraint();return i&&r.push(`CHECK (${i})`),r.join(" ")}checkError(t,n){return new Zn(this.context.table,this.context.column,t,n)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var Ft,Fs=b(()=>{rt();Ft=class extends ge{get sqliteType(){return "INTEGER"}};});var er,Aa=b(()=>{Fs();er=class extends Ft{constructor(t){super({...t,isSerial:true});}};});function Jw(e,t){let{precision:n,scale:r}=t,s=10**r,i=10**(n-r);return Math.abs(Math.round(e*s)-e*s)<1e-4&&Math.abs(e)<i}var Ut,Us=b(()=>{rt();Ut=class extends ge{numericPrecision;constructor(t,n){super(t),this.numericPrecision=n;}get isShimBacked(){return this.numericPrecision!==void 0}get sqliteType(){return "REAL"}checkConstraint(){if(this.numericPrecision){let{precision:t,scale:n}=this.numericPrecision,r=this.context.column,s=10**n,i=10**(t-n);return `ABS(ROUND(${r} * ${s}) - ${r} * ${s}) < 0.0001 AND ABS(${r}) < ${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:n,scale:r}=this.numericPrecision;if(!Jw(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var ce,je=b(()=>{rt();ce=class extends ge{lengthConstraint;constructor(t,n){super(t),this.lengthConstraint=n;}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 tr,Ca=b(()=>{rt();tr=class extends ge{get sqliteType(){return "BLOB"}};});var nr,va=b(()=>{rt();nr=class extends ge{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 Ef(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var rr,Ra=b(()=>{rt();rr=class extends ge{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 n=Ef(t);return n.ok?n.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."):Ef(t).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function Yw(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 sr,ka=b(()=>{je();sr=class extends ce{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"||!Yw(t)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function Qw(e){let t=e.match(/^(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,6})?)?([+-](\d{2}):?(\d{2}))?$/);if(!t)return false;let n=Number(t[1]),r=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 n<=24&&r<=59&&s<=59&&(n!==24||r===0&&s===0)&&a}var ir,Pa=b(()=>{je();ir=class extends ce{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"||!Qw(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function Zw(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 n=Number(t[1]),r=Number(t[2]),s=Number(t[3]),i=Number(t[4]),o=Number(t[5]),a=t[6]===void 0?0:Number(t[6]),c=t[8]===void 0?null:Number(t[8]),l=t[9]===void 0?null:Number(t[9]),p=new Date(Date.UTC(n,r-1,s)),u=p.getUTCFullYear()===n&&p.getUTCMonth()===r-1&&p.getUTCDate()===s,f=i<=24&&o<=59&&a<=59&&(i!==24||o===0&&a===0),h=c===null||l!==null&&c<=15&&l<=59;return u&&f&&h}var or,Na=b(()=>{je();or=class extends ce{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"||!Zw(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var ar,La=b(()=>{je();ar=class extends ce{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 cr,Oa=b(()=>{je();cr=class extends ce{enumValues;constructor(t,n){super(t),this.enumValues=n;}get isShimBacked(){return true}checkConstraint(){let t=this.context.column,n=this.enumValues.map(r=>`'${r.replace(/'/g,"''")}'`).join(", ");return `${t} IN (${n})`}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 xf(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var gt,Ms=b(()=>{rt();gt=class extends ge{elementField;constructor(t,n){super(t),this.elementField=n;}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(n=>this.elementField.serialize(n))):JSON.stringify(t)}deserialize(t){if(this.isNullish(t))return t;if(typeof t=="string"){let n=xf(t);if(n.ok&&Array.isArray(n.value))return this.elementField?n.value.map(r=>this.elementField.deserialize(r)):n.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 n=xf(t);if(!n.ok)return this.validationFail("Invalid JSON array text.","Patch rows with array values.");if(!Array.isArray(n.value))return this.validationFail("Expected JSON array.","Patch rows with array values.");if(this.elementField)for(let r of n.value){let s=this.elementField.validateStorage(r);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 _f(e){return tS.test(e.toLowerCase())}var eS,tS,lr,Ia=b(()=>{je();eS="????????-????-????-????-????????????",tS=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;lr=class extends ce{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${eS}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let n=t.toLowerCase();if(!_f(n))throw this.checkError("uuid_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!_f(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function nS(e){let t=e.split("/");if(t.length>2)return null;let n=t[0];if(!n)return null;if(t.length===1)return {address:n,prefix:null};let r=t[1];return !r||!/^\d+$/.test(r)?null:{address:n,prefix:Number(r)}}function rS(e){let t=e.split(".");return t.length!==4?false:t.every(n=>{if(!/^\d+$/.test(n))return false;let r=Number(n);return r>=0&&r<=255})}function sS(e){if(!e.includes(":"))return false;try{return new URL(`http://[${e}]/`),!0}catch{return false}}function Tf(e){let t=nS(e);return t?rS(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:sS(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var ur,Da=b(()=>{je();ur=class extends ce{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 n=t.trim();if(!Tf(n))throw this.checkError("inet_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!Tf(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var pr,ja=b(()=>{je();pr=class extends ce{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){let n=wS(e,t);if(t){let{enumValues:r,...s}=t;n.factoryExtra=s;}return n}function wS(e,t){if(t?.isArray){let r=Mt(e,{...t,isArray:false});return new gt(e,r)}if(t?.enumValues)return new cr(e,t.enumValues);let n=e.pgTypeName.toLowerCase().trim();if(n.startsWith("_")||n.endsWith("[]")){let r=n.startsWith("_")?n.slice(1):n.slice(0,-2),s={...e,pgTypeName:r},i=Mt(s);return new gt(e,i)}return oS.has(n)?new er(e):iS.has(n)?new Ft(e):uS.has(n)?new nr(e):pS.has(n)?new rr(e):hS.has(n)?new sr(e):gS.has(n)?new ir(e):yS.has(n)?new or(e):bS.has(n)?new ar(e):lS.has(n)?new tr(e):aS.has(n)?new Ut(e,t?.numericPrecision):fS.has(n)?new lr(e):mS.has(n)?new ce(e,63):dS.has(n)?new ur(e):cS.has(n)?new ce(e,t?.lengthConstraint):new pr(e)}var iS,oS,aS,cS,lS,uS,pS,fS,mS,dS,hS,gS,yS,bS,Fa=b(()=>{Fs();Aa();Us();je();Ca();va();Ra();ka();Pa();Na();La();Oa();Ms();Ia();Da();ja();iS=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),oS=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),aS=new Set(["float4","real","float8","double precision","numeric","decimal"]),cS=new Set(["text","varchar","character varying","char","character","bpchar"]),lS=new Set(["bytea"]),uS=new Set(["bool","boolean"]),pS=new Set(["json","jsonb"]),fS=new Set(["uuid"]),mS=new Set(["name"]),dS=new Set(["inet"]),hS=new Set(["date"]),gS=new Set(["time","timetz","time without time zone","time with time zone"]),yS=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),bS=new Set(["interval"]);});function Ua(e,t="auto"){let n=e.toLowerCase(),r=Bs[n];if(!r)return null;switch(t){case "translate":{if(!r.sqlite)throw new Error(`No SQLite translation for function "${e}"`);return {sqliteExpr:r.sqlite(),jsFn:null}}case "synthetic":{if(!r.js)throw new Error(`No JS implementation for function "${e}"`);return {sqliteExpr:null,jsFn:r.js}}case "auto":return r.js?{sqliteExpr:null,jsFn:r.js}:r.sqlite?{sqliteExpr:r.sqlite(),jsFn:null}:null}}var $f,Bs,Ma=b(()=>{$f="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)))",Bs={gen_random_uuid:{sqlite:()=>$f,js:()=>crypto.randomUUID()},uuid_generate_v4:{sqlite:()=>$f,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 fr,Af=b(()=>{fr=class{table;schema;fields;constructor(t,n="public",r=new Map){this.table=t,this.schema=n,this.fields=r;}get(t){return this.fields.get(t)}has(t){return this.fields.has(t)}set(t,n){this.fields.set(t,n);}columns(){return Array.from(this.fields.keys())}all(){return Array.from(this.fields.values())}serializeRow(t){let n={};for(let[r,s]of Object.entries(t)){let i=this.fields.get(r);n[r]=i?i.serialize(s):s;}return n}deserializeRow(t){let n={};for(let[r,s]of Object.entries(t)){let i=this.fields.get(r);n[r]=i?i.deserialize(s):s;}return n}applyDefaults(t){let n={...t};for(let[r,s]of this.fields)!(r in n)&&s.context.defaultFn&&(n[r]=s.context.defaultFn());return n}};});var Cf=b(()=>{rt();$a();Fs();Aa();Us();je();Ca();va();Ra();ka();Pa();Na();La();Oa();Ms();Ia();Da();ja();Fa();Ma();Af();});var Ja={};pe(Ja,{_resetWarnedMissingToClauseForTests:()=>SS,collectComments:()=>Xa,collectEnums:()=>Ga,collectPolicies:()=>Va,collectSchema:()=>Ka,collectTableConstraints:()=>za,collectVariables:()=>Wa});function SS(){Ha.clear();}function Ga(e){let t=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("CreateEnumStmt"in n.stmt))continue;let r=n.stmt.CreateEnumStmt,s=nt(r.typeName??[]).join(".");if(!s||!r.vals)continue;let i=nt(r.vals);t.set(s.toLowerCase(),i);}return t}function Wa(e){let t=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("VariableSetStmt"in n.stmt))continue;let r=n.stmt.VariableSetStmt,s=r.name,i=bf(r.args?.[0]??{});t.set(s,{value:i,local:r.is_local});}return t}function vf(e){let t=[],n=false;for(let r of e??[])if("RoleSpec"in r){let s=r.RoleSpec;s.roletype==="ROLESPEC_PUBLIC"?s.location===-1&&(n=true):s.roletype==="ROLESPEC_CSTRING"&&s.rolename&&t.push(s.rolename);}return {roles:t,implicitPublic:n}}function qs(e,t){return e&&e.length>0?e:t}function Ba(e,t,n){return e.findIndex(r=>r.data.name===t.name&&r.data.table===t.table&&qs(r.data.schema,n)===qs(t.schema,n))}function qa(e,t){return new Error(`policy "${e}" for table "${t}" does not exist`)}function Rf(e,t,n,r){return e.data.table===t&&qs(e.data.schema,r)===qs(n,r)}function Va(e,t={}){let n=t.defaultSchema||"public",r=t.validateMutations===true,s=new Qn,i=new Set,o=[];for(let a of e.stmts??[])if(a.stmt){if("CreatePolicyStmt"in a.stmt){let c=a.stmt.CreatePolicyStmt,l=c.table?.relname??"",p=c.table?.schemaname,u={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},f=c.cmd_name?u[c.cmd_name]??"ALL":"ALL",h=c.permissive===true,{roles:d,implicitPublic:m}=vf(c.roles),y=c.qual?s.deparse(c.qual):void 0,g=c.with_check?s.deparse(c.with_check):void 0;if(m){let A=p?`${p}.${l}`:l,$=c.policy_name??"",v=`${A}::${$}`;if(!Ha.has(v)){Ha.add(v);let C=JSON.stringify(y)+JSON.stringify(g);/\{\{auth\.(uid|jwt|role)/i.test(C)||console.warn(`[supalite] policy "${$}" on "${A}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let E=new ht({name:c.policy_name??"",table:l,schema:p,command:f,permissive:h,roles:d,using:y,withCheck:g});o.push(E);}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_POLICY"){let c=a.stmt.DropStmt,l=c.objects?.[0];if(l&&"List"in l){let p=nt(l.List.items??[]),u=p[p.length-1],f=p[p.length-2],h=p.length>=3?p[p.length-3]:void 0;if(u&&f){let d=Ba(o,{name:u,table:f,schema:h},n);if(d!==-1)o.splice(d,1);else if(r&&!c.missing_ok)throw qa(u,f)}}}if("AlterPolicyStmt"in a.stmt){let c=a.stmt.AlterPolicyStmt,l=c.policy_name??"",p=c.table?.relname??"",u=c.table?.schemaname,f=Ba(o,{name:l,table:p,schema:u},n);if(f===-1){if(r)throw qa(l,p);continue}let h=o[f].data,d=c.roles?vf(c.roles).roles:h.roles,m=c.qual?s.deparse(c.qual):h.using,y=c.with_check?s.deparse(c.with_check):h.withCheck;o[f]=new ht({...h,roles:d,using:m,withCheck:y});}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_POLICY"){let c=a.stmt.RenameStmt,l=c.subname??"",p=c.relation?.relname??"",u=c.relation?.schemaname,f=Ba(o,{name:l,table:p,schema:u},n);if(f===-1){if(r)throw qa(l,p);continue}c.newname&&(o[f]=new ht({...o[f].data,name:c.newname}));}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_TABLE"){let c=a.stmt.RenameStmt,l=c.relation?.relname??"",p=c.newname??"",u=c.relation?.schemaname;if(l&&p&&l!==p){i.delete(l)&&i.add(p);for(let f=0;f<o.length;f++)Rf(o[f],l,u,n)&&(o[f]=new ht({...o[f].data,table:p}));}}if("DropStmt"in a.stmt&&a.stmt.DropStmt.removeType==="OBJECT_TABLE")for(let c of a.stmt.DropStmt.objects??[]){if(!("List"in c))continue;let l=nt(c.List.items??[]),p=l[l.length-1],u=l.length>=2?l[l.length-2]:void 0;if(p){i.delete(p);for(let f=o.length-1;f>=0;f--)Rf(o[f],p,u,n)&&o.splice(f,1);}}if("AlterTableStmt"in a.stmt){let c=a.stmt.AlterTableStmt,l=c.relation?.relname??"";for(let p of c.cmds??[]){if(!("AlterTableCmd"in p))continue;let u=p.AlterTableCmd.subtype;u==="AT_EnableRowSecurity"?i.add(l):u==="AT_DisableRowSecurity"&&i.delete(l);}}}return {policies:o,tables:i}}function Ka(e,t){let n=new Map;for(let r of e.stmts??[]){if(!r.stmt||!("CreateStmt"in r.stmt))continue;let s=r.stmt.CreateStmt,i=s.relation?.relname??"",o=s.relation?.schemaname??"public";if(!i)continue;let a=new fr(i,o);for(let c of s.tableElts??[]){if(!("ColumnDef"in c))continue;let l=c.ColumnDef,p=l.colname;if(!p)continue;let u=l.typeName?.names?.map(N=>N.String?.sval||N.String?.str).filter(Boolean),f=u&&(u.length===2&&u[0]==="pg_catalog"?u[1]:u[0]);if(!f)continue;let h=!!l.typeName?.arrayBounds?.length,d=Array.isArray(l.typeName?.typmods)?l.typeName.typmods:[],m=N=>d[N]?.A_Const?.ival?.ival??d[N]?.A_Const?.val?.ival?.ival,y={isArray:h};if(Is(f)&&d.length>0){let N=m(0);typeof N=="number"&&N>0&&(y.lengthConstraint=N);}if(Ds(f)&&d.length>=2){let N=m(0),j=m(1);typeof N=="number"&&typeof j=="number"&&N>0&&j>=0&&(y.numericPrecision={precision:N,scale:j});}let g=t.get(f.toLowerCase());g&&(y.enumValues=g);let E=Array.isArray(l.constraints)?l.constraints:[],A=E.some(N=>N.Constraint?.contype==="CONSTR_PRIMARY"),$=Os(f)||E.some(N=>N.Constraint?.contype==="CONSTR_IDENTITY"),v=E.some(N=>N.Constraint?.contype==="CONSTR_NOTNULL"),C=E.find(N=>N.Constraint?.contype==="CONSTR_UNIQUE"),T=E.find(N=>N.Constraint?.contype==="CONSTR_GENERATED"),_=E.find(N=>N.Constraint?.contype==="CONSTR_FOREIGN"),O=E.find(N=>N.Constraint?.contype==="CONSTR_CHECK"),w;if(_){let N=_.Constraint,j=N.pktable?.relname,S=N.pktable?.schemaname,x=N.pk_attrs?.[0]?.String?.sval;j&&x&&(w={refSchema:S,refTable:j,refColumn:x,constraintName:N.conname||void 0});}let I={schema:o,table:i,column:p,pgTypeName:f,nullable:!v&&!A,defaultValue:null,defaultFn:null,isPrimaryKey:A,isUnique:!!C,isSerial:$,isGenerated:!!T,fkRef:w,hasCheck:!!O,checkConstraintName:O?.Constraint?.conname||void 0,uniqueConstraintName:C?.Constraint?.conname||void 0};a.set(p,Mt(I,y));}n.set(`${o}.${i}`,a);}return n}function za(e){let t=[];for(let n of e.stmts??[]){if(!n.stmt||!("CreateStmt"in n.stmt))continue;let r=n.stmt.CreateStmt,s=r.relation?.relname??"",i=r.relation?.schemaname??"public";if(s)for(let o of r.tableElts??[]){if("ColumnDef"in o)continue;let a=o;if(!a.Constraint)continue;let c=a.Constraint,l=c.contype;if(l==="CONSTR_UNIQUE"){let p=(c.keys??[]).map(u=>u.String?.sval??u.String?.str).filter(Boolean);if(p.length===0)continue;t.push({schema:i,table:s,kind:"unique",name:c.conname||void 0,columns:p});}else if(l==="CONSTR_CHECK")t.push({schema:i,table:s,kind:"check",name:c.conname||void 0,columns:[]});else if(l==="CONSTR_FOREIGN"){let p=(c.fk_attrs??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean),u=(c.pk_attrs??[]).map(h=>h.String?.sval??h.String?.str).filter(Boolean),f=c.pktable?.relname;if(!f)continue;t.push({schema:i,table:s,kind:"foreign_key",name:c.conname||void 0,columns:p,refSchema:c.pktable?.schemaname,refTable:f,refColumns:u});}}}return t}function Xa(e){let t=[];for(let n of e.stmts??[]){if(!n.stmt||!("CommentStmt"in n.stmt))continue;let r=n.stmt.CommentStmt,s=r.comment??"";if(!s)continue;let i=r.objtype,o=(r.object?.List?.items??r.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,c]=o.length>=2?o:["public",o[0]];t.push({schema:a,table:c,text:s});}else if(i==="OBJECT_COLUMN"){let a="public",c,l;o.length>=3?[a,c,l]=o:[c,l]=o,t.push({schema:a,table:c,column:l,text:s});}}}return t}var Ha,Ya=b(()=>{_a();Dt();Ta();Cf();an();Ha=new Set;});async function mr(e,t){let n=await e.connection.introspect(),r=Qa(n);await Of(e,{...t,dbHasTables:n.tables.length>0,dbFingerprint:r}),await $S(e);let s=await e.connection.introspect();Df(s,e);}async function _S(e){return zn(e.config.db?.seed?.sql_paths??["./seed.sql"],{cwd:Oe__default.join(process.cwd(),"supabase"),absolute:true})}async function TS(e){let t=await _S(e);return Promise.all(t.map(async n=>{let r=await de__default.readFile(n,"utf-8"),s=createHash("sha256").update(r).digest("hex");return {path:Oe__default.relative(process.cwd(),n),hash:s,statements:splitSqlStatements(r)}}))}async function dr(e,t){if(e.config.db?.seed?.enabled===false)return 0;let r=(await TS(e)).filter(c=>c.statements.length>0);if(r.length===0)return 0;await nn(e.connection);let s=xe(e.connection),i=new Map((await Sp(e.connection)).map(c=>[c.path,c.hash])),o=r.filter(c=>i.get(c.path)!==c.hash);if(o.length===0)return 0;console.log(F.default.dim("Seeding database..."));let a=[];for(let c of o){a.push(...c.statements);let l=wp(s,{path:c.path,hash:c.hash});l&&a.push(l);}try{await e.connection.transaction(a);}catch(c){let l=t?.recoveryHint??"Fix `supabase/seed.sql`, then re-run `lite dev` to reapply the schema and reseed.";throw new Error(`Seed failed and was rolled back: ${String(c.message??c)}
91
+ ${l}`)}return o.reduce((c,l)=>c+l.statements.length,0)}async function $S(e){await dr(e);}async function re(e){let t=await zn(e.config?.db?.migrations?.schema_paths??Nf,{cwd:Oe__default.join(process.cwd(),fe.config_dir),absolute:true}),n=await Promise.all(t.map(async r=>await de__default.readFile(r,"utf-8"))).then(r=>r.map(s=>s.split(`
87
92
  `).filter(i=>i.trim().length>0&&!i.trim().startsWith("--")).join(`
88
93
  `)).join(`
89
- `));return r||""}async function kf(e,t){let r=await ge(e);if(!(!r&&(await Ue(e)).length>0)&&!(!r&&!e.connection.config.baseSchema)){if(t?.dbHasTables&&await nE(e,r,t.dbFingerprint)){console.log(U.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=Ga(o);if(s.plan.steps.length===0){await Af(e,r,i,a);return}await n.migratePlan(s.plan,{force:t?.force??!1}),iE(s);let l=await e.connection.introspect();return await Af(e,r,i,Ga(l)),console.log(""),pr(s),s}catch(n){if(String(n).includes("likely empty"))console.log(U.default.dim("Nothing to migrate."));else {console.error("Migration error: "+String(n));try{await e.connection.exec("rollback");}catch{}}}}}function rE(e){return e.connection.config?.baseSchema??""}function Of(e,t){let r=createHash("sha256");return r.update(JSON.stringify([rE(e),t??""])),r.digest("hex")}function Ga(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 nE(e,t,r){let n=e.connection;if(typeof n.updateDeparseInfo!="function")return false;let s=Fe__default.join(process.cwd(),Va),i;try{i=await fe__default.readFile(s,"utf-8");}catch{return false}let o;try{o=JSON.parse(i);}catch{return false}if(o.v!==Rf||o.hash!==Of(e,t)||!r||o.dbFingerprint!==r||!o.ast||typeof o.ast!="object")return false;try{let a=await Promise.resolve().then(()=>(Ha(),qa)),l=o.ast,c=a.collectEnums(l),p=a.collectSchema(l,c),u=a.collectVariables(l),f=a.collectTableConstraints(l),h=a.collectComments(l),d=n.config?.translation?.schemas?.defaultSchema,{policies:m,tables:y}=a.collectPolicies(l,{defaultSchema:d});return n.updateDeparseInfo({enums:c,rls:{tables:y,policies:m},schema:p,vars:u,tableConstraints:f,comments:h}),!0}catch{return false}}async function Af(e,t,r,n){if(!r||typeof r!="object")return;let s={v:Rf,hash:Of(e,t),dbFingerprint:n,ast:r},i=Fe__default.join(process.cwd(),Va);try{await fe__default.mkdir(Fe__default.dirname(i),{recursive:!0}),await fe__default.writeFile(i,JSON.stringify(s),"utf-8");}catch{}}async function Nf(){let e=Fe__default.join(process.cwd(),Va);try{await fe__default.unlink(e);}catch{}}function Pf(e,t){console.log();let r=(s,i)=>{let o=l=>{let c=U.default.dim;return typeof l=="number"&&(l>=0&&(c=l>0?U.default.green:U.default.dim),l<0&&(c=U.default.red)),typeof l=="boolean"?l?U.default.green("\u2713"):U.default.red("\u2717"):c(String(l))},a=Object.entries(i).map(([l,c])=>`${l}: ${o(c)}`).join(U.default.dim(" / "));console.log(`${U.default.dim("[")} ${s} ${U.default.dim("]")} ${a}`);};r(U.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(U.default.green("AUTH"),{enabled:!!t.config.auth?.enabled,tables:ensureVar.Set(n.tables).size,policies:ensureVar.Array(n.policies).length});}function Lf(e,t){setTimeout(()=>{console.log(U.default.dim("Watching for changes...")),QS.watch("./supabase/schemas").on("change",async n=>{console.log(),console.log(U.default.dim(`Schema changed: ${n}`)),await kf(e,t);let s=await e.connection.introspect();Pf(s,e);});},200);}function za(e,t){let r=t?.colorize?U.default.dim:n=>n;return e.plan.steps.flatMap(n=>[n.description?r(`-- ${n.description}`):"",n.sql+`
90
- `]).filter(n=>n.trim().length>0).join(`
91
- `)}function sE(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 iE(e,t){let r="./supabase/.temp/migrations";ke(r);let n=sE(),s=za(e);xt(Fe__default.join(r,n),s),console.log(U.default.dim(`Migration written to ${U.default.cyan(Fe__default.join(r,n))}`));}function If(e){let t=e.schema_separator??".",r=e.ddl_dialect==="postgres",n=(a,l)=>r&&a?`${a}${t}${l}`:l;console.log(U.default.bgWhite(U.default.black(" Schema "))),console.log();let s=e.tables.filter(a=>a.type==="table"),i=r?"sqlite-postgres":"sqlite";if(console.log(U.default.dim(`${i}${e.version?` (sqlite ${e.version})`:""} \xB7 ${e.database_name}`)),console.log(),s.length===0){console.log(U.default.dim("No tables."));return}console.log(U.default.dim("Tables:"));for(let a of s){let l=n(a.schema,a.name),c=e.columns.filter(u=>u.table===a.name&&(!r||u.schema===a.schema)).sort((u,f)=>u.ordinal_position-f.ordinal_position),p=a.rows>=0?` ${U.default.dim(`(${a.rows} rows)`)}`:"";console.log(`${U.default.bold(l)}${p}`);for(let u of c){let f=[];u.is_primary_key&&f.push(U.default.green("PK")),u.nullable||f.push(U.default.dim("NOT NULL")),u.default_value!==null&&f.push(U.default.dim(`DEFAULT ${u.default_value}`));let h=f.length?" "+f.join(" "):"";console.log(` ${u.name} ${U.default.cyan(u.type)}${h}`);}console.log();}let o=e.indexes.filter(a=>!a.name.startsWith("sqlite_autoindex_"));if(o.length>0){console.log(U.default.dim("Indexes:"));for(let a of o){let l=a.unique?U.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(U.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} ${U.default.dim(`ON DELETE ${a.on_delete} ON UPDATE ${a.on_update}`)}`);}console.log();}if(e.views.length>0){console.log(U.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(U.default.dim("Triggers:"));for(let a of e.triggers)console.log(` ${a.name} on ${n(a.schema,a.table)}`);console.log();}}function pr({diff:e}){if(typeof e=="string"){console.log(U.default.cyan(e));return}if(!e.has_changes)return;console.log(U.default.bgWhite(U.default.black(" Schema Diff "))),console.log();let t={added:{color:U.default.green,symbol:"+"},removed:{color:U.default.red,symbol:"-"},modified:{color:U.default.yellow,symbol:"~"}};if(e.tables.length>0){console.log(U.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(U.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(U.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(U.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 U,Va,Rf,Je=b(()=>{pa();U=te(ae());_t();ht();Lt();Va="supabase/.temp/.translation-cache.json",Rf=2;});function oE(e){return e==="service_role"?"NOLOGIN BYPASSRLS":"NOLOGIN"}function wt(e){return e.size===0?"":`DO $$ BEGIN${[...e].map(r=>`
92
- IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${r}') THEN
93
- CREATE ROLE ${r} ${oE(r)};
94
+ `));return n||""}async function Of(e,t){let n=await re(e);if(!(!n&&(await Ie(e)).length>0)&&!(!n&&!e.connection.config.baseSchema)){if(t?.dbHasTables&&await CS(e,n,t.dbFingerprint)){console.log(F.default.dim("Schema unchanged \u2014 skipping translation.")),await yt(e);return}try{let r=e.connection.createMigrator(n),s=await r.diff(),i=r.translationResult?.ast,o=await e.connection.introspect(),a=Qa(o);if(s.plan.steps.length===0){await Pf(e,n,i,a),await yt(e);return}await r.migratePlan(s.plan,{force:t?.force??!1}),kS(s);let c=await e.connection.introspect();return await Pf(e,n,i,Qa(c)),await yt(e),console.log(""),ln(s),s}catch(r){if(String(r).includes("likely empty"))console.log(F.default.dim("Nothing to migrate."));else {console.error("Migration error: "+String(r));try{await e.connection.exec("rollback");}catch{}}}}}function AS(e){return e.connection.config?.baseSchema??""}function hr(e,t){let n=createHash("sha256");return n.update(JSON.stringify([AS(e),t??""])),n.digest("hex")}function Qa(e){let t=(r,s)=>[...r].sort((i,o)=>s(i).localeCompare(s(o))),n={tables:t(e.tables??[],r=>`${r.schema??""}.${r.name}`).map(r=>({schema:r.schema,name:r.name,type:r.type,sql:r.sql})),columns:t(e.columns??[],r=>`${r.schema??""}.${r.table}.${r.name}`).map(r=>({schema:r.schema,table:r.table,name:r.name,type:r.type,nullable:r.nullable,default_value:r.default_value,is_primary_key:r.is_primary_key})),indexes:t(e.indexes??[],r=>`${r.schema??""}.${r.table}.${r.name}`).map(r=>({schema:r.schema,table:r.table,name:r.name,unique:r.unique,columns:r.columns})),foreign_keys:t(e.foreign_keys??[],r=>`${r.schema??""}.${r.table}.${r.column}->${r.ref_table}.${r.ref_column}`).map(r=>({schema:r.schema,table:r.table,column:r.column,ref_schema:r.ref_schema,ref_table:r.ref_table,ref_column:r.ref_column})),primary_keys:t(e.primary_keys??[],r=>`${r.schema??""}.${r.table}`).map(r=>({schema:r.schema,table:r.table,columns:r.columns})),check_constraints:t(e.check_constraints??[],r=>`${r.schema??""}.${r.table}.${r.name??""}.${r.column??""}`).map(r=>({schema:r.schema,table:r.table,name:r.name,column:r.column,expression:r.expression})),unique_constraints:t(e.unique_constraints??[],r=>`${r.schema??""}.${r.table}.${r.name}`).map(r=>({schema:r.schema,table:r.table,name:r.name,columns:r.columns})),views:t(e.views??[],r=>`${r.schema??""}.${r.name}`).map(r=>({schema:r.schema,name:r.name,sql:r.sql})),triggers:t(e.triggers??[],r=>`${r.schema??""}.${r.table}.${r.name}`).map(r=>({schema:r.schema,table:r.table,name:r.name,sql:r.sql})),custom_types:t(e.custom_types??[],r=>`${r.schema??""}.${r.type}`).map(r=>({schema:r.schema,type:r.type,kind:r.kind,values:r.values,fields:r.fields}))};return createHash("sha256").update(JSON.stringify(n)).digest("hex")}async function CS(e,t,n){let r=e.connection;if(typeof r.updateDeparseInfo!="function")return false;let s=Oe__default.join(process.cwd(),ec),i;try{i=await de__default.readFile(s,"utf-8");}catch{return false}let o;try{o=JSON.parse(i);}catch{return false}if(o.v!==Lf||o.hash!==hr(e,t)||!n||o.dbFingerprint!==n||!o.ast||typeof o.ast!="object")return false;try{let a=await Promise.resolve().then(()=>(Ya(),Ja)),c=o.ast,l=a.collectEnums(c),p=a.collectSchema(c,l),u=a.collectVariables(c),f=a.collectTableConstraints(c),h=a.collectComments(c),d=r.config?.translation?.schemas?.defaultSchema,{policies:m,tables:y}=a.collectPolicies(c,{defaultSchema:d});return r.updateDeparseInfo({enums:l,rls:{tables:y,policies:m},schema:p,vars:u,tableConstraints:f,comments:h}),!0}catch{return false}}async function Pf(e,t,n,r){if(!n||typeof n!="object")return;let s={v:Lf,hash:hr(e,t),dbFingerprint:r,ast:n},i=Oe__default.join(process.cwd(),ec);try{await de__default.mkdir(Oe__default.dirname(i),{recursive:!0}),await de__default.writeFile(i,JSON.stringify(s),"utf-8");}catch{}}async function If(){let e=Oe__default.join(process.cwd(),ec);try{await de__default.unlink(e);}catch{}}function Df(e,t){console.log();let n=(s,i)=>{let o=c=>{let l=F.default.dim;return typeof c=="number"&&(c>=0&&(l=c>0?F.default.green:F.default.dim),c<0&&(l=F.default.red)),typeof c=="boolean"?c?F.default.green("\u2713"):F.default.red("\u2717"):l(String(c))},a=Object.entries(i).map(([c,l])=>`${c}: ${o(l)}`).join(F.default.dim(" / "));console.log(`${F.default.dim("[")} ${s} ${F.default.dim("]")} ${a}`);};n(F.default.green("DATA"),{tables:e.tables.length,columns:e.columns.length,indexes:e.indexes.length});let r=t.config.rls??t.connection.config.translation?.deparse?.rls??{tables:new Set([]),policies:[]};n(F.default.green("AUTH"),{enabled:!!t.config.auth?.enabled,tables:ensureVar.Set(r.tables).size,policies:ensureVar.Array(r.policies).length});}function vS(e){let t=Oe__default.join(process.cwd(),fe.config_dir),r=(e.config?.db?.migrations?.schema_paths??Nf).map(s=>{let i=s.split("/"),o=i.findIndex(c=>/[*?[{]/.test(c)),a=(o===-1?i.slice(0,-1):i.slice(0,o)).join("/");return Oe__default.resolve(t,a||".")});return [...new Set(r)]}function jf(e,t){let n,r=setTimeout(()=>{console.log(F.default.dim("Watching for changes...")),n=xS.watch(vS(e),{ignoreInitial:true});let s=async i=>{if(!i.endsWith(".sql"))return;console.log(),console.log(F.default.dim(`Schema changed: ${i}`)),await Of(e,t);let o=await e.connection.introspect();Df(o,e);};n.on("change",s),n.on("add",s);},200);return async()=>{clearTimeout(r),await n?.close();}}function tc(e,t){let n=t?.colorize?F.default.dim:r=>r;return e.plan.steps.flatMap(r=>[r.description?n(`-- ${r.description}`):"",r.sql+`
95
+ `]).filter(r=>r.trim().length>0).join(`
96
+ `)}function RS(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 kS(e,t){let n="./supabase/.temp/migrations";$e(n);let r=RS(),s=tc(e);xt(Oe__default.join(n,r),s),console.log(F.default.dim(`Migration written to ${F.default.cyan(Oe__default.join(n,r))}`));}function Ff(e){let t=e.schema_separator??".",n=e.ddl_dialect==="postgres",r=(a,c)=>n&&a?`${a}${t}${c}`:c;console.log(F.default.bgWhite(F.default.black(" Schema "))),console.log();let s=e.tables.filter(a=>a.type==="table"),i=n?"sqlite-postgres":"sqlite";if(console.log(F.default.dim(`${i}${e.version?` (sqlite ${e.version})`:""} \xB7 ${e.database_name}`)),console.log(),s.length===0){console.log(F.default.dim("No tables."));return}console.log(F.default.dim("Tables:"));for(let a of s){let c=r(a.schema,a.name),l=e.columns.filter(u=>u.table===a.name&&(!n||u.schema===a.schema)).sort((u,f)=>u.ordinal_position-f.ordinal_position),p=a.rows>=0?` ${F.default.dim(`(${a.rows} rows)`)}`:"";console.log(`${F.default.bold(c)}${p}`);for(let u of l){let f=[];u.is_primary_key&&f.push(F.default.green("PK")),u.nullable||f.push(F.default.dim("NOT NULL")),u.default_value!==null&&f.push(F.default.dim(`DEFAULT ${u.default_value}`));let h=f.length?" "+f.join(" "):"";console.log(` ${u.name} ${F.default.cyan(u.type)}${h}`);}console.log();}let o=e.indexes.filter(a=>!a.name.startsWith("sqlite_autoindex_"));if(o.length>0){console.log(F.default.dim("Indexes:"));for(let a of o){let c=a.unique?F.default.yellow("UNIQUE "):"";console.log(` ${a.name} on ${r(a.schema,a.table)} ${c}(${a.columns.join(", ")})`);}console.log();}if(e.foreign_keys.length>0){console.log(F.default.dim("Foreign Keys:"));for(let a of e.foreign_keys){let c=`${r(a.schema,a.table)}.${a.column}`,l=`${r(a.ref_schema,a.ref_table)}.${a.ref_column}`;console.log(` ${c} \u2192 ${l} ${F.default.dim(`ON DELETE ${a.on_delete} ON UPDATE ${a.on_update}`)}`);}console.log();}if(e.views.length>0){console.log(F.default.dim("Views:"));for(let a of e.views)console.log(` ${r(a.schema,a.name)}`);console.log();}if(e.triggers.length>0){console.log(F.default.dim("Triggers:"));for(let a of e.triggers)console.log(` ${a.name} on ${r(a.schema,a.table)}`);console.log();}}function ln({diff:e}){if(typeof e=="string"){console.log(F.default.cyan(e));return}if(!e.has_changes)return;console.log(F.default.bgWhite(F.default.black(" Schema Diff "))),console.log();let t={added:{color:F.default.green,symbol:"+"},removed:{color:F.default.red,symbol:"-"},modified:{color:F.default.yellow,symbol:"~"}};if(e.tables.length>0){console.log(F.default.dim("Tables:"));for(let n of e.tables){let{color:r,symbol:s}=t[n.type];console.log(r(`${s} ${n.name}`));}console.log();}if(e.columns.length>0){console.log(F.default.dim("Columns:"));for(let n of e.columns){let{color:r,symbol:s}=t[n.type],i="";n.changes&&(i=Object.entries(n.changes).map(([o,a])=>`${o}: ${a.from} \u2192 ${a.to}`).join(", ")),console.log(r(`${s} ${n.table}.${n.name}${i?` (${i})`:""}`));}console.log();}if(e.indexes.length>0){console.log(F.default.dim("Indexes:"));for(let n of e.indexes){let{color:r,symbol:s}=t[n.type];console.log(r(`${s} ${n.name} on ${n.table}`));}console.log();}if(e.foreign_keys.length>0){console.log(F.default.dim("Foreign Keys:"));for(let n of e.foreign_keys){let{color:r,symbol:s}=t[n.type];console.log(r(`${s} ${n.table}.${n.column} \u2192 ${n.ref_table}.${n.ref_column}`));}console.log();}}var F,Nf,ec,Lf,Fe=b(()=>{Sa();F=V(z());_t();dt();gr();mt();At();Nf=["./schemas/*.sql"],ec="supabase/.temp/.translation-cache.json",Lf=2;});async function PS(e){try{return await qn(e.connection)}catch{return []}}function qf(e){return xe(e.connection)==="pg-flat"}function sc(){return Oe__default.join(process.cwd(),NS)}async function Hf(e){let t=[];try{t=await qn(e.connection);}catch(n){if(!String(n).includes("no such table"))throw n}return xp(t)}async function yt(e){if(qf(e))try{let t=e.connection,n=SqliteConnection.serializeDeparseInfo(t.config?.translation?.deparse),[r,s]=await Promise.all([Hf(e),hr(e,await re(e))]),i={v:Bf,fingerprint:r,schemaHash:s,deparse:n},o=sc();await de__default.mkdir(Oe__default.dirname(o),{recursive:!0}),await de__default.writeFile(o,JSON.stringify(i),"utf-8");}catch{}}async function LS(e,t){let n;try{n=oa(await qn(e.connection));}catch{return true}if(n.size===0)return true;let r=new Set(t.rls?.tables??[]);for(let s of n)if(!r.has(s))return false;return true}async function OS(e){let t=e.connection;if(typeof t.updateDeparseInfo!="function")return false;let n;try{n=await de__default.readFile(sc(),"utf-8");}catch{return false}let r;try{r=JSON.parse(n);}catch{return false}if(r.v!==Bf)return false;let[s,i]=await Promise.all([Hf(e),hr(e,await re(e))]);if(r.fingerprint!==s||r.schemaHash!==i||!BS(r.deparse)||!await LS(e,r.deparse))return false;try{return t.updateDeparseInfo(SqliteConnection.parseDeparseInfo(r.deparse,{strict:!0})),!0}catch{return false}}function jS(e){return !(!Ye(e)||!ve(e.name)||!Bt(e.table)||!Re(e.schema,ve)||!ve(e.command)||!IS.has(e.command)||typeof e.permissive!="boolean"||!Gs(e.roles)||!Re(e.using,t=>typeof t=="object")||!Re(e.withCheck,t=>typeof t=="object"))}function FS(e){if(!Ye(e))return false;let t=e.context;return !(!Ye(t)||!ve(t.schema)||!Bt(t.table)||!Bt(t.column)||!Bt(t.pgTypeName)||typeof t.nullable!="boolean"||typeof t.isPrimaryKey!="boolean"||typeof t.isUnique!="boolean"||typeof t.isSerial!="boolean"||!(t.defaultValue===null||ve(t.defaultValue))||!Re(e.extra,Ye))}function US(e){return !(!Ye(e)||!ve(e.schema)||!Bt(e.table)||!ve(e.kind)||!DS.has(e.kind)||!Gs(e.columns)||!Re(e.name,ve)||!Re(e.refSchema,ve)||!Re(e.refTable,ve)||!Re(e.refColumns,Gs))}function MS(e){return !(!Ye(e)||!ve(e.schema)||!Bt(e.table)||!ve(e.text)||!Re(e.column,ve))}function BS(e){if(!Ye(e))return false;let t=e.rls;return !(!Ye(t)||!Array.isArray(t.tables)||!t.tables.every(Bt)||!Array.isArray(t.policies)||!t.policies.every(jS)||!Re(e.vars,n=>nc(n,Ye))||!Re(e.enums,n=>nc(n,Gs))||!Re(e.schema,n=>nc(n,r=>Array.isArray(r)&&r.every(FS)))||!Re(e.tableConstraints,n=>Array.isArray(n)&&n.every(US))||!Re(e.comments,n=>Array.isArray(n)&&n.every(MS)))}async function qS(e){let t=e.connection;if(typeof t.translateDdl!="function"||typeof t.updateDeparseInfo!="function")return false;let n=[];try{n=await qn(e.connection);}catch(a){if(!String(a).includes("no such table"))throw a}if(n.length===0)return false;let s=[...n].sort((a,c)=>a.version.localeCompare(c.version)).flatMap(a=>a.statements??[]).filter(a=>a.trim().length>0).join(`;
97
+ `);if(!s.trim())return false;let i=await t.translateDdl(s),o=t.config?.translation?.deparse??{};return t.updateDeparseInfo({...o,...i}),await yt(e),true}async function Gf(e){if(!qf(e))return "skipped";if(await OS(e))return console.log(rc.default.dim("RLS metadata restored from supabase/.temp/.deparse-cache.json")),"restored";let t="";try{t=await re(e);}catch{t="";}if(t.trim())return "failed";let n=false;try{n=await qS(e),n&&console.log(rc.default.dim("RLS metadata recalculated from migrations."));}catch{n=false;}return n?"recalculated":oa(await PS(e)).size>0?"failed":"skipped"}async function Wf(e){let t="";try{t=await re(e);}catch{t="";}return t.trim()?["`lite start` runs the migrations workflow and never applies `supabase/schemas/*.sql`, so it cannot rebuild RLS metadata for a declarative project on its own.","Ship the declarative schema as a migration, then start again:"," lite db diff -f <name> # write the pending schema changes as a migration"," lite db reset # replay the migrations onto a fresh database","Or develop declaratively with `lite dev` (or the Vite plugin), which applies the schema and rewrites the cache `lite start` restores."]:["The applied migration history no longer explains this database's RLS state.","Reapply the migrations: `lite migration up`, or `lite db reset` to replay them onto a fresh database."]}async function Vf(){try{await de__default.unlink(sc());}catch{}}var rc,NS,Bf,IS,DS,Ye,ve,Bt,Gs,Re,nc,gr=b(()=>{rc=V(z());mt();_p();Fe();NS="supabase/.temp/.deparse-cache.json",Bf=1;IS=new Set(["SELECT","INSERT","UPDATE","DELETE","ALL"]),DS=new Set(["unique","check","foreign_key"]),Ye=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ve=e=>typeof e=="string",Bt=e=>typeof e=="string"&&e.length>0,Gs=e=>Array.isArray(e)&&e.every(ve),Re=(e,t)=>e==null||t(e),nc=(e,t)=>Ye(e)&&Object.values(e).every(t);});var Kf={};pe(Kf,{start:()=>HS});var qt,HS,zf=b(()=>{Ko();lt();qt=V(z());At();Te();Ee();Kt();Zo();ea();ta();gr();HS=e=>{e.command("start").option("--config <config>","Path to the config file").option("--no-admin","Disable local admin mode (keyless requests are no longer elevated; normal authentication rules apply)").description("Start the development server").helpGroup("Local Development:").action(async(t,n)=>{await ee(t.config),await rs(async()=>{let s=await(await W({withSupabaseClient:false})).project.local.createApp(t.config,{...Rs(t,n)});if(await Gf(s)==="failed"){console.error(qt.default.red("RLS metadata could not be loaded or recalculated for this project."));for(let l of await Wf(s))console.error(qt.default.dim(l));process.exit(1);}let o=s.config.api?.port??fe.default_api_port,a=await hs(s,{port:o});console.log(qt.default.green(" \u279C"),"Server running on ",qt.default.cyan(`http://localhost:${o}`)),Cs(s.config),vs(s.adminMode);let c=jr();c&&console.log(qt.default.yellow(` \u26A0 ${c}`)),await s.connection.ping(),As(async()=>{await a(),await s.connection.close();});},r=>{console.log(),console.log(qt.default.green(`Ready in ${r.toFixed(2)}ms`));});});};});function GS(e){return e==="service_role"?"NOLOGIN BYPASSRLS":"NOLOGIN"}function bt(e){return e.size===0?"":`DO $$ BEGIN${[...e].map(n=>`
98
+ IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${n}') THEN
99
+ CREATE ROLE ${n} ${GS(n)};
94
100
  END IF;`).join("")}
95
101
  END $$;
96
- `}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 aE(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 lE(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 Xa(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]!==`
97
- `;)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=lE(e,r);continue}if(n==="$"){let i=cE(e,r);if(i!==void 0){r=i;continue}}if(n==='"'){let{token:i,end:o}=aE(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 jf(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=Xa(e);for(let n=0;n<r.length;n++){if(Re(r[n])!=="create")continue;let s=jf(r,n);for(let i of fr)wn(s,i)&&t.add(i);}return t}function Ka(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 fr)wn(e[s],o)&&r.add(o);}}function uE(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 Df(e,t){return e.some(r=>Re(r)===t)}function pE(e){let t=new Set,r=uE(Xa(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"&&(Df(n,"grant")||Df(n,"policy")||Re(n[a-1])==="owner")&&Ka(n,a+1,t),l==="from"&&s==="revoke"&&Ka(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)&&Ka(n,1,t);}return t}function bt(e){let t=qs(e);return new Set([...pE(e)].filter(r=>!t.has(r)))}function Ff(e){let t=qs(e);return new Set(fr.filter(r=>!t.has(r)))}function Uf(e,t){let r=Xa(e);if(r.length===0)return false;let n=jf(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 fr,Bs,bn=b(()=>{fr=["anon","authenticated","service_role"];wt(new Set(fr)),Bs=`
102
+ `}function Jf(e,t){return e?e.quoted?e.value===t:e.value.toLowerCase()===t:false}function Ge(e){return e?.quoted?e.value:e?.value.toLowerCase()}function WS(e,t){let n="",r=t+1;for(;r<e.length;){if(e[r]==='"'&&e[r+1]==='"'){n+='"',r+=2;continue}if(e[r]==='"')return {token:{value:n,quoted:true},end:r+1};n+=e[r],r++;}return {token:{value:n,quoted:true},end:r}}function VS(e,t){let n=t+1;for(;n<e.length;){if(e[n]==="'"&&e[n+1]==="'"){n+=2;continue}if(e[n]==="'")return n+1;n++;}return n}function KS(e,t){let n=/^\$[A-Za-z_][A-Za-z0-9_]*\$|^\$\$/.exec(e.slice(t))?.[0];if(!n)return;let r=t+n.length,s=e.indexOf(n,r);return s===-1?e.length:s+n.length}function Yf(e){let t=[],n=0;for(;n<e.length;){let r=e[n],s=e[n+1];if(/\s/.test(r)){n++;continue}if(r==="-"&&s==="-"){for(n+=2;n<e.length&&e[n]!==`
103
+ `;)n++;continue}if(r==="/"&&s==="*"){for(n+=2;n<e.length&&!(e[n]==="*"&&e[n+1]==="/");)n++;n=n<e.length?n+2:n;continue}if(r==="'"){n=VS(e,n);continue}if(r==="$"){let i=KS(e,n);if(i!==void 0){n=i;continue}}if(r==='"'){let{token:i,end:o}=WS(e,n);t.push(i),n=o;continue}if(r===","||r===";"){t.push({value:r,quoted:false}),n++;continue}if(/[A-Za-z_]/.test(r)){let i=n;for(n++;n<e.length&&/[A-Za-z0-9_$]/.test(e[n]);)n++;t.push({value:e.slice(i,n).toLowerCase(),quoted:false});continue}n++;}return t}function zS(e,t){let n=Ge(e[t]),r=Ge(e[t+1]);if((n==="create"||n==="alter")&&(r==="role"||r==="user"||r==="group"))return e[t+2]}function Vs(e){let t=new Set,n=Yf(e);for(let r=0;r<n.length;r++){if(Ge(n[r])!=="create")continue;let s=zS(n,r);for(let i of un)Jf(s,i)&&t.add(i);}return t}function ic(e,t,n){let r=new Set([";","as","by","check","for","granted","in","on","option","using","where","with"]);for(let s=t;s<e.length;s++){let i=Ge(e[s]);if(!i||r.has(i))return;for(let o of un)Jf(e[s],o)&&n.add(o);}}function XS(e){let t=[],n=[];for(let r of e){if(Ge(r)===";"){n.length>0&&t.push(n),n=[];continue}n.push(r);}return n.length>0&&t.push(n),t}function Xf(e,t){return e.some(n=>Ge(n)===t)}function JS(e){let t=new Set,n=XS(Yf(e));for(let r of n){let s=Ge(r[0]);for(let a=0;a<r.length;a++){let c=Ge(r[a]);c==="to"&&(Xf(r,"grant")||Xf(r,"policy")||Ge(r[a-1])==="owner")&&ic(r,a+1,t),c==="from"&&s==="revoke"&&ic(r,a+1,t);}let i=r.findIndex(a=>Ge(a)==="to"),o=r.findIndex(a=>Ge(a)==="on");s==="grant"&&i>1&&(o===-1||i<o)&&ic(r,1,t);}return t}function wt(e){let t=Vs(e);return new Set([...JS(e)].filter(n=>!t.has(n)))}function Qf(e){let t=Vs(e);return new Set(un.filter(n=>!t.has(n)))}var un,Ws,yr=b(()=>{un=["anon","authenticated","service_role"];bt(new Set(un)),Ws=`
98
104
  CREATE SCHEMA IF NOT EXISTS auth;
99
105
 
100
106
  CREATE OR REPLACE FUNCTION auth.uid() RETURNS UUID AS $$
@@ -115,99 +121,101 @@ CREATE OR REPLACE FUNCTION auth.jwt() RETURNS JSONB AS $$
115
121
  '{}'
116
122
  )::jsonb;
117
123
  $$ LANGUAGE SQL STABLE;
118
- `;});async function Ht(e){await e.ensureSystemSchema();let t=new Set(await Jr(e.connection)),r=await Ue(e),n=Ie(e.connection),s=[],i=[];for(let o of r){if(t.has(o.version)){i.push(o);continue}let a=vt(o.sql),l;if(n==="pg-flat"){let p=await e.connection.translateDdl(o.sql),u=typeof p=="string"?p:p.ddl??"";l=vt(u);}else l=a;let c=cf(n,{version:o.version,name:o.name,statements:a});if(n==="pg"){let p=wt(bt(o.sql));p&&await e.connection.exec(p);}await e.connection.transaction([...l,c],{intent:"migration"}),s.push(o);}return r.length>0&&n!=="sqlite"&&await fE(e,r),{applied:s,skipped:i}}async function fE(e,t){let r=t.map(o=>o.sql).join(`
119
- `);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});}var Hs=b(()=>{Ct();Lt();ht();bn();});function ye(e){return `${mE} ${e}`}var mE,it=b(()=>{mE="[lite]";});var Mf={};de(Mf,{dev:()=>gE});var qe,gE,Bf=b(()=>{Yi();Vo();ft();qe=te(ae());Xt();Je();Hs();ht();Ae();$e();zt();it();gE=e=>{e.command("dev").option("--template","Create a template for the database",false).option("--config <config>","Path to the config file").description(ye("Start the development server with schema watching")).helpGroup("Local Development:").action(async t=>{await Q(t.config),console.log(qe.default.yellow(" \u26A0 [lite] dev is experimental and works with declarative schema only.")),await ts(async()=>{await Zn({template:t.template}),console.log();let n=await(await V({withSupabaseClient:false})).project.local.createApp(t.config),s=n.config.api?.port??we.default_api_port;if((await Ue(n)).length>0){let c=await Ht(n);for(let p of c.applied)console.log(qe.default.green(" \u2713"),"Applied migration",qe.default.cyan(p.filename));}await gn(n,{force:true}),console.log();await bs(n,{port:s});console.log(qe.default.green(" \u279C"),"Server running on ",qe.default.cyan(`http://localhost:${s}`));let a=Fn();a&&console.log(qe.default.yellow(` \u26A0 ${a}`)),await n.connection.ping(),Lf(n,{translate:true,force:true});let l=Fe__default.join(process.cwd(),"supabase",It(n));setTimeout(()=>{QS.watch(l,{ignoreInitial:true}).on("add",async p=>{console.log(),console.log(qe.default.dim(`Migration added: ${p}`));try{let u=await Ht(n);for(let f of u.applied)console.log(qe.default.green(" \u2713"),"Applied",qe.default.cyan(f.filename));}catch(u){console.error(qe.default.red("Migration failed: "+String(u.message??u)));}});},200),process.on("SIGINT",async()=>{await n.connection.close(),process.exit(1);});},r=>{console.log(),console.log(qe.default.green(`Ready in ${r.toFixed(2)}ms`));});});};});async function ot(e){let t=e===true,r=await V({withSupabaseClient:t}),n=r.project.local.ref();if(t){if(!n)throw new Error("No project linked");if(!await r.project.remote.ping())throw new Error("Remote project is not reachable");return Qe("creating app for remote project",n),r.project.remote.createApp(n)}return r.project.local.createApp(e)}var Ja=b(()=>{Ae();Jt();});var qf={};de(qf,{repl:()=>yE});var Se,yE,Hf=b(()=>{ft();Se=te(ae());Ja();$e();it();yE=e=>{e.command("repl").option("--config <config>","Path to the config file").option("--remote","Connect REPL to a remote project").description(ye("Start a REPL session")).helpGroup("Local Development:").action(async t=>{t.remote||await Q(t.config);let r=await ot(t.remote?true:t.config);es()||(console.error(Se.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(Se.default.green("Starting a REPL session")),console.log(Se.default.bold("Available variables:"),Object.keys(n).map(o=>Se.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(p=>p.table===c);console.log(a.tables.map(c=>`${Se.default.cyan(c.name)} (${l(c.name).length} columns)`).join(`
120
- `)),this.displayPrompt();}}),i.defineCommand("table",{help:"Show a table",action:async function(a){let l=await r.connection.introspect(),c=u=>l.columns.filter(f=>f.table===u),p=l.tables.find(u=>u.name===a);p?(console.log(`${Se.default.cyan(p?.name)} (${c(a).length} columns)`),console.log(c(a).map(u=>` - ${Se.default.cyan(u.name)} ${Se.default.yellow(u.type)}`).join(`
121
- `)),console.log(),console.log(Se.default.dim(p.sql))):(console.log(Se.default.red(`Table ${a} not found`)),console.log(`Available tables:
122
- `+l.tables.map(u=>`- ${Se.default.cyan(u.name)}`).join(`
123
- `))),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=>`${Se.default.bold(Se.default.cyan(l.name))} ${l.unique?Se.default.yellow("unique "):""}on ${Se.default.blue(l.table)}(${l.columns.map(c=>Se.default.magenta(c)).join(", ")})`).join(`
124
- `)),this.displayPrompt();}}),i.defineCommand("config",{help:"Show the current config",action:async function(a){console.log(a?Zi(r.config,a):r.config),this.displayPrompt();}});});};});var Gf={};de(Gf,{debug:()=>wE});var wE,Wf=b(()=>{ft();$e();it();wE=e=>{e.command("debug").description(ye("Print runtime info (bun/node detection, paths)")).helpGroup("Local Development:").action(async()=>{console.log("Debugging the application"),console.log({bun:Ar(),node:es(),cwd:process.cwd(),paths:{root:Jn(),dist:Ki(),relativeDist:Yn()}});});};});var Qa=ut((Bk,Vf)=>{var Ya={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"},bE={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},SE={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?Ya.up():"");return e&&(t+=Ya.left),t}};Vf.exports={cursor:Ya,scroll:bE,erase:SE,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 nl(e,t,r){return String(e).normalize().replaceAll(`\r
124
+ `;});async function Ht(e,t={}){await e.ensureSystemSchema();let n=new Set(await Bn(e.connection)),r=await Ie(e),s=xe(e.connection),i=[],o=[];for(let c of r){if(n.has(c.version)){o.push(c);continue}let l=vt(c.sql),p;if(s==="pg-flat"){let f=await e.connection.translateDdl(c.sql),h=typeof f=="string"?f:f.ddl??"";p=vt(h);}else p=l;let u=bp(s,{version:c.version,name:c.name,statements:l});if(s==="pg"){let f=bt(wt(c.sql));f&&await e.connection.exec(f);}await e.connection.transaction([...p,u],{intent:"migration"}),i.push(c);}let a=true;return s==="pg-flat"&&!t.persistWithDeclarative&&(await re(e)).trim()&&(a=false),s!=="sqlite"&&(r.length>0?await YS(e,r,{persist:a}):s==="pg-flat"&&a&&await yt(e)),{applied:i,skipped:o}}async function YS(e,t,n){let r=t.map(a=>a.sql).join(`
125
+ `);if(!r.trim())return;let s=e.connection;if(typeof s.translateDdl!="function"||typeof s.updateDeparseInfo!="function")return;let i=await s.translateDdl(r),o=s.config?.translation?.deparse??{};s.updateDeparseInfo({...o,...i}),n?.persist!==false&&await yt(e);}var Ks=b(()=>{Rt();mt();dt();yr();gr();Fe();});var Zf={};pe(Zf,{dev:()=>eE});var Ue,eE,em=b(()=>{so();Ko();lt();Ue=V(z());At();Fe();Ks();dt();Te();Ee();Kt();Xe();Zo();ea();ta();eE=e=>{e.command("dev").option("--template","Create a template for the database",false).option("--config <config>","Path to the config file").option("--no-admin","Disable local admin mode (keyless requests are no longer elevated; normal authentication rules apply)").description(me("Start the development server with schema watching")).helpGroup("Local Development:").action(async(t,n)=>{await ee(t.config),console.log(Ue.default.yellow(" \u26A0 [lite] dev is experimental and works with declarative schema only.")),await rs(async()=>{await ts({template:t.template}),console.log();let s=await(await W({withSupabaseClient:false})).project.local.createApp(t.config,{...Rs(t,n)}),i=s.config.api?.port??fe.default_api_port;if((await Ie(s)).length>0){let h=await Ht(s);for(let d of h.applied)console.log(Ue.default.green(" \u2713"),"Applied migration",Ue.default.cyan(d.filename));}await mr(s,{force:true}),console.log();let a=await hs(s,{port:i});console.log(Ue.default.green(" \u279C"),"Server running on ",Ue.default.cyan(`http://localhost:${i}`)),Cs(s.config),vs(s.adminMode);let c=jr();c&&console.log(Ue.default.yellow(` \u26A0 ${c}`)),await s.connection.ping();let l=jf(s,{translate:true,force:true}),p=Oe__default.join(process.cwd(),"supabase",Ot(s)),u,f=setTimeout(()=>{u=xS.watch(p,{ignoreInitial:true}),u.on("add",async h=>{console.log(),console.log(Ue.default.dim(`Migration added: ${h}`));try{let d=await Ht(s);for(let m of d.applied)console.log(Ue.default.green(" \u2713"),"Applied",Ue.default.cyan(m.filename));}catch(d){console.error(Ue.default.red("Migration failed: "+String(d.message??d)));}});},200);As(async()=>{clearTimeout(f),await Promise.all([l(),u?.close()]),await a(),await s.connection.close();});},r=>{console.log(),console.log(Ue.default.green(`Ready in ${r.toFixed(2)}ms`));});});};});async function st(e){let t=e===true,n=await W({withSupabaseClient:t}),r=n.project.local.ref();if(t){if(!r)throw new Error("No project linked");if(!await n.project.remote.ping())throw new Error("Remote project is not reachable");return Me("creating app for remote project",r),n.project.remote.createApp(r)}return n.project.local.createApp(e)}var oc=b(()=>{Te();Ct();});var tm={};pe(tm,{repl:()=>tE});var ye,tE,nm=b(()=>{lt();ye=V(z());oc();Ee();Xe();tE=e=>{e.command("repl").option("--config <config>","Path to the config file").option("--remote","Connect REPL to a remote project").description(me("Start a REPL session")).helpGroup("Local Development:").action(async t=>{t.remote||await ee(t.config);let n=await st(t.remote?true:t.config);ns()||(console.error(ye.default.red("REPL is only supported on Node.js")),process.exit(1));let r={app:n,client:n.getClient(),conn:n.connection,db:n.connection.driver};console.log(ye.default.green("Starting a REPL session")),console.log(ye.default.bold("Available variables:"),Object.keys(r).map(o=>ye.default.cyan(o)).join(", "));let i=(await import('node:repl')).start("> ");i.on("exit",async()=>{await n.connection.close(),process.exit();});for(let o of Object.keys(r))Object.defineProperty(i.context,o,{configurable:false,enumerable:true,value:r[o]});i.defineCommand("tables",{help:"List all tables",action:async function(){let a=await n.connection.introspect(),c=l=>a.columns.filter(p=>p.table===l);console.log(a.tables.map(l=>`${ye.default.cyan(l.name)} (${c(l.name).length} columns)`).join(`
126
+ `)),this.displayPrompt();}}),i.defineCommand("table",{help:"Show a table",action:async function(a){let c=await n.connection.introspect(),l=u=>c.columns.filter(f=>f.table===u),p=c.tables.find(u=>u.name===a);p?(console.log(`${ye.default.cyan(p?.name)} (${l(a).length} columns)`),console.log(l(a).map(u=>` - ${ye.default.cyan(u.name)} ${ye.default.yellow(u.type)}`).join(`
127
+ `)),console.log(),console.log(ye.default.dim(p.sql))):(console.log(ye.default.red(`Table ${a} not found`)),console.log(`Available tables:
128
+ `+c.tables.map(u=>`- ${ye.default.cyan(u.name)}`).join(`
129
+ `))),this.displayPrompt();}}),i.defineCommand("indexes",{help:"List all indexes",action:async function(){let a=await n.connection.introspect().then(c=>c.indexes);console.log(a.map(c=>`${ye.default.bold(ye.default.cyan(c.name))} ${c.unique?ye.default.yellow("unique "):""}on ${ye.default.blue(c.table)}(${c.columns.map(l=>ye.default.magenta(l)).join(", ")})`).join(`
130
+ `)),this.displayPrompt();}}),i.defineCommand("config",{help:"Show the current config",action:async function(a){console.log(a?oo(n.config,a):n.config),this.displayPrompt();}});});};});var rm={};pe(rm,{debug:()=>nE});var nE,sm=b(()=>{lt();Ee();Xe();nE=e=>{e.command("debug").description(me("Print runtime info (bun/node detection, paths)")).helpGroup("Local Development:").action(async()=>{console.log("Debugging the application"),console.log({bun:vn(),node:ns(),cwd:process.cwd(),paths:{root:Xr(),dist:Yi(),relativeDist:Jr()}});});};});var cc=ct((Hk,im)=>{var ac={to(e,t){return t?`\x1B[${t+1};${e+1}H`:`\x1B[${e+1}G`},move(e,t){let n="";return e<0?n+=`\x1B[${-e}D`:e>0&&(n+=`\x1B[${e}C`),t<0?n+=`\x1B[${-t}A`:t>0&&(n+=`\x1B[${t}B`),n},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"},rE={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},sE={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 n=0;n<e;n++)t+=this.line+(n<e-1?ac.up():"");return e&&(t+=ac.left),t}};im.exports={cursor:ac,scroll:rE,erase:sE,beep:"\x07"};});function Qs(e,t,n){if(!n.some(o=>!o.disabled))return e;let r=e+t,s=Math.max(n.length-1,0),i=r<0?s:r>s?0:r;return n[i].disabled?Qs(i,t<0?-1:1,n):i}function mc(e,t,n){return String(e).normalize().replaceAll(`\r
125
131
  `,`
126
132
  `).split(`
127
- `).map(n=>PE(n,t,r)).join(`
128
- `)}function ll(e,t){if(typeof e=="string")return Pe.aliases.get(e)===t;for(let r of e)if(r!==void 0&&ll(r,t))return true;return false}function IE(e,t){if(e===t)return;let r=e.split(`
129
- `),n=t.split(`
130
- `),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 Ee(e){return e===sl}function zs(e,t){let r=e;r.isTTY&&r.setRawMode(t);}function rm({input:e=stdin,output:t=stdout,overwrite:r=true,hideCursor:n=true}={}){let s=St.createInterface({input:e,output:t,prompt:"",tabSize:1});St.emitKeypressEvents(e,s),e instanceof ReadStream&&e.isTTY&&e.setRawMode(true);let i=(o,{name:a,sequence:l})=>{let c=String(o);if(ll([c,a,l],"cancel")){n&&t.write(Te.cursor.show),process.exit(0);return}if(!r)return;St.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{St.clearLine(t,1,()=>{e.once("keypress",i);});});};return n&&t.write(Te.cursor.hide),e.once("keypress",i),()=>{e.off("keypress",i),n&&t.write(Te.cursor.show),e instanceof ReadStream&&e.isTTY&&!DE&&e.setRawMode(false),s.terminal=false,s.close();}}function ti(e,t,r,n=r){let s=ei(e??stdout);return nl(t,s-r.length,{hard:true,trim:false}).split(`
131
- `).map((i,o)=>`${o===0?n:r}${i}`).join(`
132
- `)}var Te,xE,_E,$E,Za,Gs,Ws,el,Vs,TE,vE,Qf,CE,Sn,Zs,Zf,AE,ol,em,RE,tm,al,Kf,kE,Xf,Jf,OE,tl,NE,PE,LE,Pe,DE,sl,ei,cl,mr,Xs,Js,Ys,Qs,ul=b(()=>{Te=te(Qa());xE=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,_E=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,$E=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,Za=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Gs=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ws=/\t{1,1000}/y,el=/[\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,Vs=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,TE=/\p{M}+/gu,vE={limit:1/0,ellipsis:""},Qf=(e,t={},r={})=>{let n=t.limit??1/0,s=t.ellipsis??"",i=t?.ellipsisWidth??(s?Qf(s,vE,r).width:0),o=r.ansiWidth??0,a=r.controlWidth??0,l=r.tabWidth??8,c=r.ambiguousWidth??1,p=r.emojiWidth??2,u=r.fullWidthWidth??2,f=r.regularWidth??1,h=r.wideWidth??2,d=0,m=0,y=e.length,g=0,E=false,v=y,T=Math.max(0,n-i),A=0,C=0,$=0,_=0;e:for(;;){if(C>A||m>=y&&m>d){let L=e.slice(A,C)||e.slice(d,m);g=0;for(let w of L.replaceAll(TE,"")){let D=w.codePointAt(0)||0;if(_E(D)?_=u:$E(D)?_=h:c!==f&&xE(D)?_=c:_=f,$+_>T&&(v=Math.min(v,Math.max(A,d)+g)),$+_>n){E=true;break e}g+=w.length,$+=_;}A=C=0;}if(m>=y)break;if(Vs.lastIndex=m,Vs.test(e)){if(g=Vs.lastIndex-m,_=g*f,$+_>T&&(v=Math.min(v,m+Math.floor((T-$)/f))),$+_>n){E=true;break}$+=_,A=d,C=m,m=d=Vs.lastIndex;continue}if(Za.lastIndex=m,Za.test(e)){if($+o>T&&(v=Math.min(v,m)),$+o>n){E=true;break}$+=o,A=d,C=m,m=d=Za.lastIndex;continue}if(Gs.lastIndex=m,Gs.test(e)){if(g=Gs.lastIndex-m,_=g*a,$+_>T&&(v=Math.min(v,m+Math.floor((T-$)/a))),$+_>n){E=true;break}$+=_,A=d,C=m,m=d=Gs.lastIndex;continue}if(Ws.lastIndex=m,Ws.test(e)){if(g=Ws.lastIndex-m,_=g*l,$+_>T&&(v=Math.min(v,m+Math.floor((T-$)/l))),$+_>n){E=true;break}$+=_,A=d,C=m,m=d=Ws.lastIndex;continue}if(el.lastIndex=m,el.test(e)){if($+p>T&&(v=Math.min(v,m)),$+p>n){E=true;break}$+=p,A=d,C=m,m=d=el.lastIndex;continue}m+=1;}return {width:E?T:$,index:E?v:y,truncated:E,ellipsed:E&&n>=i}},CE={limit:1/0,ellipsis:"",ellipsisWidth:0},Sn=(e,t={})=>Qf(e,CE,t).width,Zs="\x1B",Zf="\x9B",AE=39,ol="\x07",em="[",RE="]",tm="m",al=`${RE}8;;`,Kf=new RegExp(`(?:\\${em}(?<code>\\d+)m|\\${al}(?<uri>.*)${ol})`,"y"),kE=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},Xf=e=>`${Zs}${em}${e}${tm}`,Jf=e=>`${Zs}${al}${e}${ol}`,OE=e=>e.map(t=>Sn(t)),tl=(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(),p=0;for(;!l.done;){let u=l.value,f=Sn(u);a+f<=r?e[e.length-1]+=u:(e.push(u),a=0),(u===Zs||u===Zf)&&(s=true,i=t.startsWith(al,p+1)),s?i?u===ol&&(s=false,i=false):u===tm&&(s=false):(a+=f,a===r&&!c.done&&(e.push(""),a=0)),l=c,c=n.next(),p+=u.length;}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop());},NE=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("")},PE=(e,t,r={})=>{if(r.trim!==false&&e.trim()==="")return "";let n="",s,i,o=e.split(" "),a=OE(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 g=t-y,E=1+Math.floor((a[d]-g-1)/t);Math.floor((a[d]-1)/t)<E&&l.push(""),tl(l,m,t);continue}if(y+a[d]>t&&y>0&&a[d]>0){if(r.wordWrap===false&&y<t){tl(l,m,t);continue}l.push("");}if(y+a[d]>t&&r.wordWrap===false){tl(l,m,t);continue}l[l.length-1]+=m;}r.trim!==false&&(l=l.map(d=>NE(d)));let c=l.join(`
133
- `),p=c[Symbol.iterator](),u=p.next(),f=p.next(),h=0;for(;!u.done;){let d=u.value,m=f.value;if(n+=d,d===Zs||d===Zf){Kf.lastIndex=h+1;let g=Kf.exec(c)?.groups;if(g?.code!==void 0){let E=Number.parseFloat(g.code);s=E===AE?void 0:E;}else g?.uri!==void 0&&(i=g.uri.length===0?void 0:g.uri);}let y=s?kE(s):void 0;m===`
134
- `?(i&&(n+=Jf("")),s&&y&&(n+=Xf(y))):d===`
135
- `&&(s&&y&&(n+=Xf(s)),i&&(n+=Jf(i))),h+=d.length,u=f,f=p.next();}return n};LE=["up","down","left","right","space","enter","cancel"],Pe={actions:new Set(LE),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:true};DE=globalThis.process.platform.startsWith("win"),sl=Symbol("clack:cancel");ei=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,cl=e=>"rows"in e&&typeof e.rows=="number"?e.rows:20;mr=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(sl);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close();},{once:true});}this.rl=St__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),zs(this.input,true),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Te.cursor.show),this.output.off("resize",this.render),zs(this.input,false),t(this.value);}),this.once("cancel",()=>{this.output.write(Te.cursor.show),this.output.off("resize",this.render),zs(this.input,false),t(sl);});})}_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&&Pe.aliases.has(r.name)&&this.emit("cursor",Pe.aliases.get(r.name)),Pe.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");}ll([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(`
136
- `),zs(this.input,false),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe();}restoreCursor(){let t=nl(this._prevFrame,process.stdout.columns,{hard:true,trim:false}).split(`
137
- `).length-1;this.output.write(Te.cursor.move(-999,t*-1));}render(){let t=nl(this._render(this)??"",process.stdout.columns,{hard:true,trim:false});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Te.cursor.hide);else {let r=IE(this._prevFrame,t),n=cl(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(Te.cursor.move(0,o-i)),this.output.write(Te.erase.lines(1));let a=t.split(`
138
- `);this.output.write(a[o]),this._prevFrame=t,this.output.write(Te.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(Te.cursor.move(0,l));}this.output.write(Te.erase.down());let a=t.split(`
133
+ `).map(r=>yE(r,t,n)).join(`
134
+ `)}function bc(e,t){if(typeof e=="string")return ke.aliases.get(e)===t;for(let n of e)if(n!==void 0&&bc(n,t))return true;return false}function wE(e,t){if(e===t)return;let n=e.split(`
135
+ `),r=t.split(`
136
+ `),s=Math.max(n.length,r.length),i=[];for(let o=0;o<s;o++)n[o]!==r[o]&&i.push(o);return {lines:i,numLinesBefore:n.length,numLinesAfter:r.length,numLines:s}}function be(e){return e===dc}function Ys(e,t){let n=e;n.isTTY&&n.setRawMode(t);}function hm({input:e=stdin,output:t=stdout,overwrite:n=true,hideCursor:r=true}={}){let s=St.createInterface({input:e,output:t,prompt:"",tabSize:1});St.emitKeypressEvents(e,s),e instanceof ReadStream&&e.isTTY&&e.setRawMode(true);let i=(o,{name:a,sequence:c})=>{let l=String(o);if(bc([l,a,c],"cancel")){r&&t.write(_e.cursor.show),process.exit(0);return}if(!n)return;St.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{St.clearLine(t,1,()=>{e.once("keypress",i);});});};return r&&t.write(_e.cursor.hide),e.once("keypress",i),()=>{e.off("keypress",i),r&&t.write(_e.cursor.show),e instanceof ReadStream&&e.isTTY&&!SE&&e.setRawMode(false),s.terminal=false,s.close();}}function ii(e,t,n,r=n){let s=si(e??stdout);return mc(t,s-n.length,{hard:true,trim:false}).split(`
137
+ `).map((i,o)=>`${o===0?r:n}${i}`).join(`
138
+ `)}var _e,oE,aE,cE,lc,zs,Xs,uc,Js,lE,uE,pm,pE,br,ri,fm,fE,gc,mm,mE,dm,yc,am,dE,cm,lm,hE,pc,gE,yE,bE,ke,SE,dc,si,wc,pn,Zs,ei,ti,ni,Sc=b(()=>{_e=V(cc());oE=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,aE=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,cE=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,lc=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,zs=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Xs=/\t{1,1000}/y,uc=/[\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,Js=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,lE=/\p{M}+/gu,uE={limit:1/0,ellipsis:""},pm=(e,t={},n={})=>{let r=t.limit??1/0,s=t.ellipsis??"",i=t?.ellipsisWidth??(s?pm(s,uE,n).width:0),o=n.ansiWidth??0,a=n.controlWidth??0,c=n.tabWidth??8,l=n.ambiguousWidth??1,p=n.emojiWidth??2,u=n.fullWidthWidth??2,f=n.regularWidth??1,h=n.wideWidth??2,d=0,m=0,y=e.length,g=0,E=false,A=y,$=Math.max(0,r-i),v=0,C=0,T=0,_=0;e:for(;;){if(C>v||m>=y&&m>d){let O=e.slice(v,C)||e.slice(d,m);g=0;for(let w of O.replaceAll(lE,"")){let I=w.codePointAt(0)||0;if(aE(I)?_=u:cE(I)?_=h:l!==f&&oE(I)?_=l:_=f,T+_>$&&(A=Math.min(A,Math.max(v,d)+g)),T+_>r){E=true;break e}g+=w.length,T+=_;}v=C=0;}if(m>=y)break;if(Js.lastIndex=m,Js.test(e)){if(g=Js.lastIndex-m,_=g*f,T+_>$&&(A=Math.min(A,m+Math.floor(($-T)/f))),T+_>r){E=true;break}T+=_,v=d,C=m,m=d=Js.lastIndex;continue}if(lc.lastIndex=m,lc.test(e)){if(T+o>$&&(A=Math.min(A,m)),T+o>r){E=true;break}T+=o,v=d,C=m,m=d=lc.lastIndex;continue}if(zs.lastIndex=m,zs.test(e)){if(g=zs.lastIndex-m,_=g*a,T+_>$&&(A=Math.min(A,m+Math.floor(($-T)/a))),T+_>r){E=true;break}T+=_,v=d,C=m,m=d=zs.lastIndex;continue}if(Xs.lastIndex=m,Xs.test(e)){if(g=Xs.lastIndex-m,_=g*c,T+_>$&&(A=Math.min(A,m+Math.floor(($-T)/c))),T+_>r){E=true;break}T+=_,v=d,C=m,m=d=Xs.lastIndex;continue}if(uc.lastIndex=m,uc.test(e)){if(T+p>$&&(A=Math.min(A,m)),T+p>r){E=true;break}T+=p,v=d,C=m,m=d=uc.lastIndex;continue}m+=1;}return {width:E?$:T,index:E?A:y,truncated:E,ellipsed:E&&r>=i}},pE={limit:1/0,ellipsis:"",ellipsisWidth:0},br=(e,t={})=>pm(e,pE,t).width,ri="\x1B",fm="\x9B",fE=39,gc="\x07",mm="[",mE="]",dm="m",yc=`${mE}8;;`,am=new RegExp(`(?:\\${mm}(?<code>\\d+)m|\\${yc}(?<uri>.*)${gc})`,"y"),dE=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},cm=e=>`${ri}${mm}${e}${dm}`,lm=e=>`${ri}${yc}${e}${gc}`,hE=e=>e.map(t=>br(t)),pc=(e,t,n)=>{let r=t[Symbol.iterator](),s=false,i=false,o=e.at(-1),a=o===void 0?0:br(o),c=r.next(),l=r.next(),p=0;for(;!c.done;){let u=c.value,f=br(u);a+f<=n?e[e.length-1]+=u:(e.push(u),a=0),(u===ri||u===fm)&&(s=true,i=t.startsWith(yc,p+1)),s?i?u===gc&&(s=false,i=false):u===dm&&(s=false):(a+=f,a===n&&!l.done&&(e.push(""),a=0)),c=l,l=r.next(),p+=u.length;}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop());},gE=e=>{let t=e.split(" "),n=t.length;for(;n>0&&!(br(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},yE=(e,t,n={})=>{if(n.trim!==false&&e.trim()==="")return "";let r="",s,i,o=e.split(" "),a=hE(o),c=[""];for(let[d,m]of o.entries()){n.trim!==false&&(c[c.length-1]=(c.at(-1)??"").trimStart());let y=br(c.at(-1)??"");if(d!==0&&(y>=t&&(n.wordWrap===false||n.trim===false)&&(c.push(""),y=0),(y>0||n.trim===false)&&(c[c.length-1]+=" ",y++)),n.hard&&a[d]>t){let g=t-y,E=1+Math.floor((a[d]-g-1)/t);Math.floor((a[d]-1)/t)<E&&c.push(""),pc(c,m,t);continue}if(y+a[d]>t&&y>0&&a[d]>0){if(n.wordWrap===false&&y<t){pc(c,m,t);continue}c.push("");}if(y+a[d]>t&&n.wordWrap===false){pc(c,m,t);continue}c[c.length-1]+=m;}n.trim!==false&&(c=c.map(d=>gE(d)));let l=c.join(`
139
+ `),p=l[Symbol.iterator](),u=p.next(),f=p.next(),h=0;for(;!u.done;){let d=u.value,m=f.value;if(r+=d,d===ri||d===fm){am.lastIndex=h+1;let g=am.exec(l)?.groups;if(g?.code!==void 0){let E=Number.parseFloat(g.code);s=E===fE?void 0:E;}else g?.uri!==void 0&&(i=g.uri.length===0?void 0:g.uri);}let y=s?dE(s):void 0;m===`
140
+ `?(i&&(r+=lm("")),s&&y&&(r+=cm(y))):d===`
141
+ `&&(s&&y&&(r+=cm(s)),i&&(r+=lm(i))),h+=d.length,u=f,f=p.next();}return r};bE=["up","down","left","right","space","enter","cancel"],ke={actions:new Set(bE),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:true};SE=globalThis.process.platform.startsWith("win"),dc=Symbol("clack:cancel");si=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,wc=e=>"rows"in e&&typeof e.rows=="number"?e.rows:20;pn=class{input;output;_abortSignal;rl;opts;_render;_track=false;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,n=true){let{input:r=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=n,this._abortSignal=o,this.input=r,this.output=s;}unsubscribe(){this._subscribers.clear();}setSubscriber(t,n){let r=this._subscribers.get(t)??[];r.push(n),this._subscribers.set(t,r);}on(t,n){this.setSubscriber(t,{cb:n});}once(t,n){this.setSubscriber(t,{cb:n,once:true});}emit(t,...n){let r=this._subscribers.get(t)??[],s=[];for(let i of r)i.cb(...n),i.once&&s.push(()=>r.splice(r.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(dc);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close();},{once:true});}this.rl=St__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),Ys(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),Ys(this.input,false),t(this.value);}),this.once("cancel",()=>{this.output.write(_e.cursor.show),this.output.off("resize",this.render),Ys(this.input,false),t(dc);});})}_isActionKey(t,n){return t===" "}_setValue(t){this.value=t,this.emit("value",this.value);}_setUserInput(t,n){this.userInput=t??"",this.emit("userInput",this.userInput),n&&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,n){if(this._track&&n.name!=="return"&&(n.name&&this._isActionKey(t,n)&&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"),n?.name&&(!this._track&&ke.aliases.has(n.name)&&this.emit("cursor",ke.aliases.get(n.name)),ke.actions.has(n.name)&&this.emit("cursor",n.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t?.toLowerCase(),n),n?.name==="return"){if(this.opts.validate){let r=this.opts.validate(this.value);r&&(this.error=r instanceof Error?r.message:r,this.state="error",this.rl?.write(this.userInput));}this.state!=="error"&&(this.state="submit");}bc([t,n?.name,n?.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(`
142
+ `),Ys(this.input,false),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe();}restoreCursor(){let t=mc(this._prevFrame,process.stdout.columns,{hard:true,trim:false}).split(`
143
+ `).length-1;this.output.write(_e.cursor.move(-999,t*-1));}render(){let t=mc(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 n=wE(this._prevFrame,t),r=wc(this.output);if(this.restoreCursor(),n){let s=Math.max(0,n.numLinesAfter-r),i=Math.max(0,n.numLinesBefore-r),o=n.lines.find(a=>a>=s);if(o===void 0){this._prevFrame=t;return}if(n.lines.length===1){this.output.write(_e.cursor.move(0,o-i)),this.output.write(_e.erase.lines(1));let a=t.split(`
144
+ `);this.output.write(a[o]),this._prevFrame=t,this.output.write(_e.cursor.move(0,a.length-o-1));return}else if(n.lines.length>1){if(s<i)o=s;else {let c=o-i;c>0&&this.output.write(_e.cursor.move(0,c));}this.output.write(_e.erase.down());let a=t.split(`
139
145
  `).slice(o);this.output.write(a.join(`
140
- `)),this._prevFrame=t;return}}this.output.write(Te.erase.down());}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t;}}},Xs=class extends mr{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(Te.cursor.move(0,-1)),this.value=r,this.state="submit",this.close();}),this.on("cursor",()=>{this.value=!this.value;});}},Js=class extends mr{_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 mr{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 mr{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 jE(){return Ge.platform!=="win32"?Ge.env.TERM!=="linux":!!Ge.env.CI||!!Ge.env.WT_SESSION||!!Ge.env.TERMINUS_SUBLIME||Ge.env.ConEmuTask==="{cmd::Cmder}"||Ge.env.TERM_PROGRAM==="Terminus-Sublime"||Ge.env.TERM_PROGRAM==="vscode"||Ge.env.TERM==="xterm-256color"||Ge.env.TERM==="alacritty"||Ge.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function gl(e,t,r){return String(e).normalize().replaceAll(`\r
146
+ `)),this._prevFrame=t;return}}this.output.write(_e.erase.down());}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t;}}},Zs=class extends pn{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",n=>{this.output.write(_e.cursor.move(0,-1)),this.value=n,this.state="submit",this.close();}),this.on("cursor",()=>{this.value=!this.value;});}},ei=class extends pn{_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 n=this.masked,r=n.slice(0,this.cursor),s=n.slice(this.cursor);return `${r}${styleText("inverse",s[0])}${s.slice(1)}`}clear(){this._clearUserInput();}constructor({mask:t,...n}){super(n),this._mask=t??"\u2022",this.on("userInput",r=>{this._setValue(r);});}},ti=class extends pn{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 n=this.options.findIndex(({value:s})=>s===t.initialValue),r=n===-1?0:n;this.cursor=this.options[r].disabled?Qs(r,1,this.options):r,this.changeValue(),this.on("cursor",s=>{switch(s){case "left":case "up":this.cursor=Qs(this.cursor,-1,this.options);break;case "down":case "right":this.cursor=Qs(this.cursor,1,this.options);break}this.changeValue();});}},ni=class extends pn{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return `${this.userInput}\u2588`;let n=t.slice(0,this.cursor),[r,...s]=t.slice(this.cursor);return `${n}${styleText("inverse",r)}${s.join("")}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",n=>{this._setValue(n);}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="");});}};});function EE(){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 Ac(e,t,n){return String(e).normalize().replaceAll(`\r
141
147
  `,`
142
148
  `).split(`
143
- `).map(n=>n0(n,t,r)).join(`
144
- `)}var En,dl,FE,X,UE,om,am,yl,z,dr,hl,oi,ME,BE,qE,HE,GE,ai,WE,VE,zE,KE,pl,ri,ni,fl,si,XE,JE,lm,YE,xn,li,cm,QE,wl,um,ZE,pm,bl,nm,e0,sm,im,t0,ml,r0,n0,s0,i0,_n,K,$n,o0,Sl,ii,Tn,vn,Ye=b(()=>{ul();ul();En=te(Qa());dl=jE(),FE=()=>process.env.CI==="true",X=(e,t)=>dl?e:t,UE=X("\u25C6","*"),om=X("\u25A0","x"),am=X("\u25B2","x"),yl=X("\u25C7","o"),X("\u250C","T"),z=X("\u2502","|"),dr=X("\u2514","\u2014"),X("\u2510","T"),X("\u2518","\u2014"),hl=X("\u25CF",">"),oi=X("\u25CB"," "),X("\u25FB","[\u2022]"),X("\u25FC","[+]"),X("\u25FB","[ ]"),ME=X("\u25AA","\u2022"),X("\u2500","-"),X("\u256E","+"),X("\u251C","+"),X("\u256F","+"),X("\u2570","+"),X("\u256D","+"),BE=X("\u25CF","\u2022"),qE=X("\u25C6","*"),HE=X("\u25B2","!"),GE=X("\u25A0","x"),ai=e=>{switch(e){case "initial":case "active":return styleText("cyan",UE);case "cancel":return styleText("red",om);case "error":return styleText("yellow",am);case "submit":return styleText("green",yl)}},WE=e=>{switch(e){case "initial":case "active":return styleText("cyan",z);case "cancel":return styleText("red",z);case "error":return styleText("yellow",z);case "submit":return styleText("green",z)}},VE=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,zE=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,KE=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,pl=/[\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,fl=/[\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,XE=/\p{M}+/gu,JE={limit:1/0,ellipsis:""},lm=(e,t={},r={})=>{let n=t.limit??1/0,s=t.ellipsis??"",i=t?.ellipsisWidth??(s?lm(s,JE,r).width:0),o=r.ansiWidth??0,a=r.controlWidth??0,l=r.tabWidth??8,c=r.ambiguousWidth??1,p=r.emojiWidth??2,u=r.fullWidthWidth??2,f=r.regularWidth??1,h=r.wideWidth??2,d=0,m=0,y=e.length,g=0,E=false,v=y,T=Math.max(0,n-i),A=0,C=0,$=0,_=0;e:for(;;){if(C>A||m>=y&&m>d){let L=e.slice(A,C)||e.slice(d,m);g=0;for(let w of L.replaceAll(XE,"")){let D=w.codePointAt(0)||0;if(zE(D)?_=u:KE(D)?_=h:c!==f&&VE(D)?_=c:_=f,$+_>T&&(v=Math.min(v,Math.max(A,d)+g)),$+_>n){E=true;break e}g+=w.length,$+=_;}A=C=0;}if(m>=y)break;if(si.lastIndex=m,si.test(e)){if(g=si.lastIndex-m,_=g*f,$+_>T&&(v=Math.min(v,m+Math.floor((T-$)/f))),$+_>n){E=true;break}$+=_,A=d,C=m,m=d=si.lastIndex;continue}if(pl.lastIndex=m,pl.test(e)){if($+o>T&&(v=Math.min(v,m)),$+o>n){E=true;break}$+=o,A=d,C=m,m=d=pl.lastIndex;continue}if(ri.lastIndex=m,ri.test(e)){if(g=ri.lastIndex-m,_=g*a,$+_>T&&(v=Math.min(v,m+Math.floor((T-$)/a))),$+_>n){E=true;break}$+=_,A=d,C=m,m=d=ri.lastIndex;continue}if(ni.lastIndex=m,ni.test(e)){if(g=ni.lastIndex-m,_=g*l,$+_>T&&(v=Math.min(v,m+Math.floor((T-$)/l))),$+_>n){E=true;break}$+=_,A=d,C=m,m=d=ni.lastIndex;continue}if(fl.lastIndex=m,fl.test(e)){if($+p>T&&(v=Math.min(v,m)),$+p>n){E=true;break}$+=p,A=d,C=m,m=d=fl.lastIndex;continue}m+=1;}return {width:E?T:$,index:E?v:y,truncated:E,ellipsed:E&&n>=i}},YE={limit:1/0,ellipsis:"",ellipsisWidth:0},xn=(e,t={})=>lm(e,YE,t).width,li="\x1B",cm="\x9B",QE=39,wl="\x07",um="[",ZE="]",pm="m",bl=`${ZE}8;;`,nm=new RegExp(`(?:\\${um}(?<code>\\d+)m|\\${bl}(?<uri>.*)${wl})`,"y"),e0=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},sm=e=>`${li}${um}${e}${pm}`,im=e=>`${li}${bl}${e}${wl}`,t0=e=>e.map(t=>xn(t)),ml=(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(),p=0;for(;!l.done;){let u=l.value,f=xn(u);a+f<=r?e[e.length-1]+=u:(e.push(u),a=0),(u===li||u===cm)&&(s=true,i=t.startsWith(bl,p+1)),s?i?u===wl&&(s=false,i=false):u===pm&&(s=false):(a+=f,a===r&&!c.done&&(e.push(""),a=0)),l=c,c=n.next(),p+=u.length;}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop());},r0=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("")},n0=(e,t,r={})=>{if(r.trim!==false&&e.trim()==="")return "";let n="",s,i,o=e.split(" "),a=t0(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 g=t-y,E=1+Math.floor((a[d]-g-1)/t);Math.floor((a[d]-1)/t)<E&&l.push(""),ml(l,m,t);continue}if(y+a[d]>t&&y>0&&a[d]>0){if(r.wordWrap===false&&y<t){ml(l,m,t);continue}l.push("");}if(y+a[d]>t&&r.wordWrap===false){ml(l,m,t);continue}l[l.length-1]+=m;}r.trim!==false&&(l=l.map(d=>r0(d)));let c=l.join(`
145
- `),p=c[Symbol.iterator](),u=p.next(),f=p.next(),h=0;for(;!u.done;){let d=u.value,m=f.value;if(n+=d,d===li||d===cm){nm.lastIndex=h+1;let g=nm.exec(c)?.groups;if(g?.code!==void 0){let E=Number.parseFloat(g.code);s=E===QE?void 0:E;}else g?.uri!==void 0&&(i=g.uri.length===0?void 0:g.uri);}let y=s?e0(s):void 0;m===`
146
- `?(i&&(n+=im("")),s&&y&&(n+=sm(y))):d===`
147
- `&&(s&&y&&(n+=sm(s)),i&&(n+=im(i))),h+=d.length,u=f,f=p.next();}return n};s0=(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}},i0=({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=cl(n),c=styleText("dim","..."),p=Math.max(l-o,0),u=Math.max(Math.min(s,p),5),f=0;e>=u-3&&(f=Math.max(Math.min(e-u+3,t.length-u),0));let h=u<t.length&&f>0,d=u<t.length&&f+u<t.length,m=Math.min(f+u,t.length),y=[],g=0;h&&g++,d&&g++;let E=f+(h?1:0),v=m-(d?1:0);for(let A=E;A<v;A++){let C=gl(r(t[A],A===e),a,{hard:true,trim:false}).split(`
148
- `);y.push(C),g+=C.length;}if(g>p){let A=0,C=0,$=g,_=e-E,L=(w,D)=>s0(y,$,w,D,p);h?({lineCount:$,removals:A}=L(0,_),$>p&&({lineCount:$,removals:C}=L(_+1,y.length))):({lineCount:$,removals:C}=L(_+1,y.length),$>p&&({lineCount:$,removals:A}=L(0,_))),A>0&&(h=true,y.splice(0,A)),C>0&&(d=true,y.splice(y.length-C,C));}let T=[];h&&T.push(c);for(let A of y)for(let C of A)T.push(C);return d&&T.push(c),T},_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??Pe.withGuide,s=`${n?`${styleText("gray",z)}
149
- `:""}${ai(this.state)} ${e.message}
150
- `,i=this.value?t:r;switch(this.state){case "submit":{let o=n?`${styleText("gray",z)} `:"";return `${s}${o}${styleText("dim",i)}`}case "cancel":{let o=n?`${styleText("gray",z)} `:"";return `${s}${o}${styleText(["strikethrough","dim"],i)}${n?`
151
- ${styleText("gray",z)}`:""}`}default:{let o=n?`${styleText("cyan",z)} `:"",a=n?styleText("cyan",dr):"";return `${s}${o}${this.value?`${styleText("green",hl)} ${t}`:`${styleText("dim",oi)} ${styleText("dim",t)}`}${e.vertical?n?`
152
- ${styleText("cyan",z)} `:`
153
- `:` ${styleText("dim","/")} `}${this.value?`${styleText("dim",oi)} ${styleText("dim",r)}`:`${styleText("green",hl)} ${r}`}
149
+ `).map(r=>BE(r,t,n)).join(`
150
+ `)}var wr,Tc,xE,J,_E,wm,Sm,Cc,K,fn,$c,ui,TE,$E,AE,CE,vE,pi,RE,kE,PE,NE,Ec,oi,ai,xc,ci,LE,OE,Em,IE,Sr,fi,xm,DE,vc,_m,jE,Tm,Rc,gm,FE,ym,bm,UE,_c,ME,BE,qE,HE,Er,X,xr,GE,kc,li,_r,Tr,Qe=b(()=>{Sc();Sc();wr=V(cc());Tc=EE(),xE=()=>process.env.CI==="true",J=(e,t)=>Tc?e:t,_E=J("\u25C6","*"),wm=J("\u25A0","x"),Sm=J("\u25B2","x"),Cc=J("\u25C7","o"),J("\u250C","T"),K=J("\u2502","|"),fn=J("\u2514","\u2014"),J("\u2510","T"),J("\u2518","\u2014"),$c=J("\u25CF",">"),ui=J("\u25CB"," "),J("\u25FB","[\u2022]"),J("\u25FC","[+]"),J("\u25FB","[ ]"),TE=J("\u25AA","\u2022"),J("\u2500","-"),J("\u256E","+"),J("\u251C","+"),J("\u256F","+"),J("\u2570","+"),J("\u256D","+"),$E=J("\u25CF","\u2022"),AE=J("\u25C6","*"),CE=J("\u25B2","!"),vE=J("\u25A0","x"),pi=e=>{switch(e){case "initial":case "active":return styleText("cyan",_E);case "cancel":return styleText("red",wm);case "error":return styleText("yellow",Sm);case "submit":return styleText("green",Cc)}},RE=e=>{switch(e){case "initial":case "active":return styleText("cyan",K);case "cancel":return styleText("red",K);case "error":return styleText("yellow",K);case "submit":return styleText("green",K)}},kE=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,PE=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,NE=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,Ec=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,oi=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ai=/\t{1,1000}/y,xc=/[\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,ci=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,LE=/\p{M}+/gu,OE={limit:1/0,ellipsis:""},Em=(e,t={},n={})=>{let r=t.limit??1/0,s=t.ellipsis??"",i=t?.ellipsisWidth??(s?Em(s,OE,n).width:0),o=n.ansiWidth??0,a=n.controlWidth??0,c=n.tabWidth??8,l=n.ambiguousWidth??1,p=n.emojiWidth??2,u=n.fullWidthWidth??2,f=n.regularWidth??1,h=n.wideWidth??2,d=0,m=0,y=e.length,g=0,E=false,A=y,$=Math.max(0,r-i),v=0,C=0,T=0,_=0;e:for(;;){if(C>v||m>=y&&m>d){let O=e.slice(v,C)||e.slice(d,m);g=0;for(let w of O.replaceAll(LE,"")){let I=w.codePointAt(0)||0;if(PE(I)?_=u:NE(I)?_=h:l!==f&&kE(I)?_=l:_=f,T+_>$&&(A=Math.min(A,Math.max(v,d)+g)),T+_>r){E=true;break e}g+=w.length,T+=_;}v=C=0;}if(m>=y)break;if(ci.lastIndex=m,ci.test(e)){if(g=ci.lastIndex-m,_=g*f,T+_>$&&(A=Math.min(A,m+Math.floor(($-T)/f))),T+_>r){E=true;break}T+=_,v=d,C=m,m=d=ci.lastIndex;continue}if(Ec.lastIndex=m,Ec.test(e)){if(T+o>$&&(A=Math.min(A,m)),T+o>r){E=true;break}T+=o,v=d,C=m,m=d=Ec.lastIndex;continue}if(oi.lastIndex=m,oi.test(e)){if(g=oi.lastIndex-m,_=g*a,T+_>$&&(A=Math.min(A,m+Math.floor(($-T)/a))),T+_>r){E=true;break}T+=_,v=d,C=m,m=d=oi.lastIndex;continue}if(ai.lastIndex=m,ai.test(e)){if(g=ai.lastIndex-m,_=g*c,T+_>$&&(A=Math.min(A,m+Math.floor(($-T)/c))),T+_>r){E=true;break}T+=_,v=d,C=m,m=d=ai.lastIndex;continue}if(xc.lastIndex=m,xc.test(e)){if(T+p>$&&(A=Math.min(A,m)),T+p>r){E=true;break}T+=p,v=d,C=m,m=d=xc.lastIndex;continue}m+=1;}return {width:E?$:T,index:E?A:y,truncated:E,ellipsed:E&&r>=i}},IE={limit:1/0,ellipsis:"",ellipsisWidth:0},Sr=(e,t={})=>Em(e,IE,t).width,fi="\x1B",xm="\x9B",DE=39,vc="\x07",_m="[",jE="]",Tm="m",Rc=`${jE}8;;`,gm=new RegExp(`(?:\\${_m}(?<code>\\d+)m|\\${Rc}(?<uri>.*)${vc})`,"y"),FE=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},ym=e=>`${fi}${_m}${e}${Tm}`,bm=e=>`${fi}${Rc}${e}${vc}`,UE=e=>e.map(t=>Sr(t)),_c=(e,t,n)=>{let r=t[Symbol.iterator](),s=false,i=false,o=e.at(-1),a=o===void 0?0:Sr(o),c=r.next(),l=r.next(),p=0;for(;!c.done;){let u=c.value,f=Sr(u);a+f<=n?e[e.length-1]+=u:(e.push(u),a=0),(u===fi||u===xm)&&(s=true,i=t.startsWith(Rc,p+1)),s?i?u===vc&&(s=false,i=false):u===Tm&&(s=false):(a+=f,a===n&&!l.done&&(e.push(""),a=0)),c=l,l=r.next(),p+=u.length;}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop());},ME=e=>{let t=e.split(" "),n=t.length;for(;n>0&&!(Sr(t[n-1])>0);)n--;return n===t.length?e:t.slice(0,n).join(" ")+t.slice(n).join("")},BE=(e,t,n={})=>{if(n.trim!==false&&e.trim()==="")return "";let r="",s,i,o=e.split(" "),a=UE(o),c=[""];for(let[d,m]of o.entries()){n.trim!==false&&(c[c.length-1]=(c.at(-1)??"").trimStart());let y=Sr(c.at(-1)??"");if(d!==0&&(y>=t&&(n.wordWrap===false||n.trim===false)&&(c.push(""),y=0),(y>0||n.trim===false)&&(c[c.length-1]+=" ",y++)),n.hard&&a[d]>t){let g=t-y,E=1+Math.floor((a[d]-g-1)/t);Math.floor((a[d]-1)/t)<E&&c.push(""),_c(c,m,t);continue}if(y+a[d]>t&&y>0&&a[d]>0){if(n.wordWrap===false&&y<t){_c(c,m,t);continue}c.push("");}if(y+a[d]>t&&n.wordWrap===false){_c(c,m,t);continue}c[c.length-1]+=m;}n.trim!==false&&(c=c.map(d=>ME(d)));let l=c.join(`
151
+ `),p=l[Symbol.iterator](),u=p.next(),f=p.next(),h=0;for(;!u.done;){let d=u.value,m=f.value;if(r+=d,d===fi||d===xm){gm.lastIndex=h+1;let g=gm.exec(l)?.groups;if(g?.code!==void 0){let E=Number.parseFloat(g.code);s=E===DE?void 0:E;}else g?.uri!==void 0&&(i=g.uri.length===0?void 0:g.uri);}let y=s?FE(s):void 0;m===`
152
+ `?(i&&(r+=bm("")),s&&y&&(r+=ym(y))):d===`
153
+ `&&(s&&y&&(r+=ym(s)),i&&(r+=bm(i))),h+=d.length,u=f,f=p.next();}return r};qE=(e,t,n,r,s)=>{let i=t,o=0;for(let a=n;a<r;a++){let c=e[a];if(i=i-c.length,o++,i<=s)break}return {lineCount:i,removals:o}},HE=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:s=Number.POSITIVE_INFINITY,columnPadding:i=0,rowPadding:o=4})=>{let a=si(r)-i,c=wc(r),l=styleText("dim","..."),p=Math.max(c-o,0),u=Math.max(Math.min(s,p),5),f=0;e>=u-3&&(f=Math.max(Math.min(e-u+3,t.length-u),0));let h=u<t.length&&f>0,d=u<t.length&&f+u<t.length,m=Math.min(f+u,t.length),y=[],g=0;h&&g++,d&&g++;let E=f+(h?1:0),A=m-(d?1:0);for(let v=E;v<A;v++){let C=Ac(n(t[v],v===e),a,{hard:true,trim:false}).split(`
154
+ `);y.push(C),g+=C.length;}if(g>p){let v=0,C=0,T=g,_=e-E,O=(w,I)=>qE(y,T,w,I,p);h?({lineCount:T,removals:v}=O(0,_),T>p&&({lineCount:T,removals:C}=O(_+1,y.length))):({lineCount:T,removals:C}=O(_+1,y.length),T>p&&({lineCount:T,removals:v}=O(0,_))),v>0&&(h=true,y.splice(0,v)),C>0&&(d=true,y.splice(y.length-C,C));}let $=[];h&&$.push(l);for(let v of y)for(let C of v)$.push(C);return d&&$.push(l),$},Er=e=>{let t=e.active??"Yes",n=e.inactive??"No";return new Zs({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??true,render(){let r=e.withGuide??ke.withGuide,s=`${r?`${styleText("gray",K)}
155
+ `:""}${pi(this.state)} ${e.message}
156
+ `,i=this.value?t:n;switch(this.state){case "submit":{let o=r?`${styleText("gray",K)} `:"";return `${s}${o}${styleText("dim",i)}`}case "cancel":{let o=r?`${styleText("gray",K)} `:"";return `${s}${o}${styleText(["strikethrough","dim"],i)}${r?`
157
+ ${styleText("gray",K)}`:""}`}default:{let o=r?`${styleText("cyan",K)} `:"",a=r?styleText("cyan",fn):"";return `${s}${o}${this.value?`${styleText("green",$c)} ${t}`:`${styleText("dim",ui)} ${styleText("dim",t)}`}${e.vertical?r?`
158
+ ${styleText("cyan",K)} `:`
159
+ `:` ${styleText("dim","/")} `}${this.value?`${styleText("dim",ui)} ${styleText("dim",n)}`:`${styleText("green",$c)} ${n}`}
154
160
  ${a}
155
- `}}}}).prompt()},K={message:(e=[],{symbol:t=styleText("gray",z),secondarySymbol:r=styleText("gray",z),output:n=process.stdout,spacing:s=1,withGuide:i}={})=>{let o=[],a=i??Pe.withGuide,l=a?r:"",c=a?`${t} `:"",p=a?`${r} `:"";for(let f=0;f<s;f++)o.push(l);let u=Array.isArray(e)?e:e.split(`
156
- `);if(u.length>0){let[f,...h]=u;f.length>0?o.push(`${c}${f}`):o.push(a?t:"");for(let d of h)d.length>0?o.push(`${p}${d}`):o.push(a?r:"");}n.write(`${o.join(`
161
+ `}}}}).prompt()},X={message:(e=[],{symbol:t=styleText("gray",K),secondarySymbol:n=styleText("gray",K),output:r=process.stdout,spacing:s=1,withGuide:i}={})=>{let o=[],a=i??ke.withGuide,c=a?n:"",l=a?`${t} `:"",p=a?`${n} `:"";for(let f=0;f<s;f++)o.push(c);let u=Array.isArray(e)?e:e.split(`
162
+ `);if(u.length>0){let[f,...h]=u;f.length>0?o.push(`${l}${f}`):o.push(a?t:"");for(let d of h)d.length>0?o.push(`${p}${d}`):o.push(a?n:"");}r.write(`${o.join(`
157
163
  `)}
158
- `);},info:(e,t)=>{K.message(e,{...t,symbol:styleText("blue",BE)});},success:(e,t)=>{K.message(e,{...t,symbol:styleText("green",qE)});},step:(e,t)=>{K.message(e,{...t,symbol:styleText("green",yl)});},warn:(e,t)=>{K.message(e,{...t,symbol:styleText("yellow",HE)});},warning:(e,t)=>{K.warn(e,t);},error:(e,t)=>{K.message(e,{...t,symbol:styleText("red",GE)});}},$n=e=>new Js({validate:e.validate,mask:e.mask??ME,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??Pe.withGuide,r=`${t?`${styleText("gray",z)}
159
- `:""}${ai(this.state)} ${e.message}
160
- `,n=this.userInputWithCursor,s=this.masked;switch(this.state){case "error":{let i=t?`${styleText("yellow",z)} `:"",o=t?`${styleText("yellow",dr)} `:"",a=s??"";return e.clearOnError&&this.clear(),`${r.trim()}
164
+ `);},info:(e,t)=>{X.message(e,{...t,symbol:styleText("blue",$E)});},success:(e,t)=>{X.message(e,{...t,symbol:styleText("green",AE)});},step:(e,t)=>{X.message(e,{...t,symbol:styleText("green",Cc)});},warn:(e,t)=>{X.message(e,{...t,symbol:styleText("yellow",CE)});},warning:(e,t)=>{X.warn(e,t);},error:(e,t)=>{X.message(e,{...t,symbol:styleText("red",vE)});}},xr=e=>new ei({validate:e.validate,mask:e.mask??TE,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??ke.withGuide,n=`${t?`${styleText("gray",K)}
165
+ `:""}${pi(this.state)} ${e.message}
166
+ `,r=this.userInputWithCursor,s=this.masked;switch(this.state){case "error":{let i=t?`${styleText("yellow",K)} `:"",o=t?`${styleText("yellow",fn)} `:"",a=s??"";return e.clearOnError&&this.clear(),`${n.trim()}
161
167
  ${i}${a}
162
168
  ${o}${styleText("yellow",this.error)}
163
- `}case "submit":{let i=t?`${styleText("gray",z)} `:"",o=s?styleText("dim",s):"";return `${r}${i}${o}`}case "cancel":{let i=t?`${styleText("gray",z)} `:"",o=s?styleText(["strikethrough","dim"],s):"";return `${r}${i}${o}${s&&t?`
164
- ${styleText("gray",z)}`:""}`}default:{let i=t?`${styleText("cyan",z)} `:"",o=t?styleText("cyan",dr):"";return `${r}${i}${n}
169
+ `}case "submit":{let i=t?`${styleText("gray",K)} `:"",o=s?styleText("dim",s):"";return `${n}${i}${o}`}case "cancel":{let i=t?`${styleText("gray",K)} `:"",o=s?styleText(["strikethrough","dim"],s):"";return `${n}${i}${o}${s&&t?`
170
+ ${styleText("gray",K)}`:""}`}default:{let i=t?`${styleText("cyan",K)} `:"",o=t?styleText("cyan",fn):"";return `${n}${i}${r}
165
171
  ${o}
166
- `}}}}).prompt(),o0=e=>styleText("magenta",e),Sl=({indicator:e="dots",onCancel:t,output:r=process.stdout,cancelMessage:n,errorMessage:s,frames:i=dl?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=dl?80:120,signal:a,...l}={})=>{let c=FE(),p,u,f=false,h=false,d="",m,y=performance.now(),g=ei(r),E=l?.styleFrame??o0,v=S=>{let x=S>1?s??Pe.messages.error:n??Pe.messages.cancel;h=S===1,f&&(F(x,S),h&&typeof t=="function"&&t());},T=()=>v(2),A=()=>v(1),C=()=>{process.on("uncaughtExceptionMonitor",T),process.on("unhandledRejection",T),process.on("SIGINT",A),process.on("SIGTERM",A),process.on("exit",v),a&&a.addEventListener("abort",A);},$=()=>{process.removeListener("uncaughtExceptionMonitor",T),process.removeListener("unhandledRejection",T),process.removeListener("SIGINT",A),process.removeListener("SIGTERM",A),process.removeListener("exit",v),a&&a.removeEventListener("abort",A);},_=()=>{if(m===void 0)return;c&&r.write(`
167
- `);let S=gl(m,g,{hard:true,trim:false}).split(`
168
- `);S.length>1&&r.write(En.cursor.up(S.length-1)),r.write(En.cursor.to(0)),r.write(En.erase.down());},L=S=>S.replace(/\.+$/,""),w=S=>{let x=(performance.now()-S)/1e3,Y=Math.floor(x/60),q=Math.floor(x%60);return Y>0?`[${Y}m ${q}s]`:`[${q}s]`},D=l.withGuide??Pe.withGuide,N=(S="")=>{f=true,p=rm({output:r}),d=L(S),y=performance.now(),D&&r.write(`${styleText("gray",z)}
169
- `);let x=0,Y=0;C(),u=setInterval(()=>{if(c&&d===m)return;_(),m=d;let q=E(i[x]),j;if(c)j=`${q} ${d}...`;else if(e==="timer")j=`${q} ${d} ${w(y)}`;else {let ue=".".repeat(Math.floor(Y)).slice(0,3);j=`${q} ${d}${ue}`;}let ie=gl(j,g,{hard:true,trim:false});r.write(ie),x=x+1<i.length?x+1:0,Y=Y<4?Y+.125:0;},o);},F=(S="",x=0,Y=false)=>{if(!f)return;f=false,clearInterval(u),_();let q=x===0?styleText("green",yl):x===1?styleText("red",om):styleText("red",am);d=S??d,Y||(e==="timer"?r.write(`${q} ${d} ${w(y)}
170
- `):r.write(`${q} ${d}
171
- `)),$(),p();};return {start:N,stop:(S="")=>F(S,0),message:(S="")=>{d=L(S??d);},cancel:(S="")=>F(S,1),error:(S="")=>F(S,2),clear:()=>F("",0,true),get isCancelled(){return h}}},{light:X("\u2500","-"),heavy:X("\u2501","="),block:X("\u2588","#")},ii=(e,t)=>e.includes(`
172
+ `}}}}).prompt(),GE=e=>styleText("magenta",e),kc=({indicator:e="dots",onCancel:t,output:n=process.stdout,cancelMessage:r,errorMessage:s,frames:i=Tc?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=Tc?80:120,signal:a,...c}={})=>{let l=xE(),p,u,f=false,h=false,d="",m,y=performance.now(),g=si(n),E=c?.styleFrame??GE,A=S=>{let x=S>1?s??ke.messages.error:r??ke.messages.cancel;h=S===1,f&&(j(x,S),h&&typeof t=="function"&&t());},$=()=>A(2),v=()=>A(1),C=()=>{process.on("uncaughtExceptionMonitor",$),process.on("unhandledRejection",$),process.on("SIGINT",v),process.on("SIGTERM",v),process.on("exit",A),a&&a.addEventListener("abort",v);},T=()=>{process.removeListener("uncaughtExceptionMonitor",$),process.removeListener("unhandledRejection",$),process.removeListener("SIGINT",v),process.removeListener("SIGTERM",v),process.removeListener("exit",A),a&&a.removeEventListener("abort",v);},_=()=>{if(m===void 0)return;l&&n.write(`
173
+ `);let S=Ac(m,g,{hard:true,trim:false}).split(`
174
+ `);S.length>1&&n.write(wr.cursor.up(S.length-1)),n.write(wr.cursor.to(0)),n.write(wr.erase.down());},O=S=>S.replace(/\.+$/,""),w=S=>{let x=(performance.now()-S)/1e3,Z=Math.floor(x/60),B=Math.floor(x%60);return Z>0?`[${Z}m ${B}s]`:`[${B}s]`},I=c.withGuide??ke.withGuide,N=(S="")=>{f=true,p=hm({output:n}),d=O(S),y=performance.now(),I&&n.write(`${styleText("gray",K)}
175
+ `);let x=0,Z=0;C(),u=setInterval(()=>{if(l&&d===m)return;_(),m=d;let B=E(i[x]),D;if(l)D=`${B} ${d}...`;else if(e==="timer")D=`${B} ${d} ${w(y)}`;else {let le=".".repeat(Math.floor(Z)).slice(0,3);D=`${B} ${d}${le}`;}let oe=Ac(D,g,{hard:true,trim:false});n.write(oe),x=x+1<i.length?x+1:0,Z=Z<4?Z+.125:0;},o);},j=(S="",x=0,Z=false)=>{if(!f)return;f=false,clearInterval(u),_();let B=x===0?styleText("green",Cc):x===1?styleText("red",wm):styleText("red",Sm);d=S??d,Z||(e==="timer"?n.write(`${B} ${d} ${w(y)}
176
+ `):n.write(`${B} ${d}
177
+ `)),T(),p();};return {start:N,stop:(S="")=>j(S,0),message:(S="")=>{d=O(S??d);},cancel:(S="")=>j(S,1),error:(S="")=>j(S,2),clear:()=>j("",0,true),get isCancelled(){return h}}},{light:J("\u2500","-"),heavy:J("\u2501","="),block:J("\u2588","#")},li=(e,t)=>e.includes(`
172
178
  `)?e.split(`
173
- `).map(r=>t(r)).join(`
174
- `):t(e),Tn=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",hl)} ${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??Pe.withGuide,n=`${ai(this.state)} `,s=`${WE(this.state)} `,i=ti(e.output,e.message,s,n),o=`${r?`${styleText("gray",z)}
179
+ `).map(n=>t(n)).join(`
180
+ `):t(e),_r=e=>{let t=(n,r)=>{let s=n.label??String(n.value);switch(r){case "disabled":return `${styleText("gray",ui)} ${li(s,i=>styleText("gray",i))}${n.hint?` ${styleText("dim",`(${n.hint??"disabled"})`)}`:""}`;case "selected":return `${li(s,i=>styleText("dim",i))}`;case "active":return `${styleText("green",$c)} ${s}${n.hint?` ${styleText("dim",`(${n.hint})`)}`:""}`;case "cancelled":return `${li(s,i=>styleText(["strikethrough","dim"],i))}`;default:return `${styleText("dim",ui)} ${li(s,i=>styleText("dim",i))}`}};return new ti({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let n=e.withGuide??ke.withGuide,r=`${pi(this.state)} `,s=`${RE(this.state)} `,i=ii(e.output,e.message,s,r),o=`${n?`${styleText("gray",K)}
175
181
  `:""}${i}
176
- `;switch(this.state){case "submit":{let a=r?`${styleText("gray",z)} `:"",l=ti(e.output,t(this.options[this.cursor],"selected"),a);return `${o}${l}`}case "cancel":{let a=r?`${styleText("gray",z)} `:"",l=ti(e.output,t(this.options[this.cursor],"cancelled"),a);return `${o}${l}${r?`
177
- ${styleText("gray",z)}`:""}`}default:{let a=r?`${styleText("cyan",z)} `:"",l=r?styleText("cyan",dr):"",c=o.split(`
178
- `).length,p=r?2:1;return `${o}${a}${i0({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:c+p,style:(u,f)=>t(u,u.disabled?"disabled":f?"active":"inactive")}).join(`
182
+ `;switch(this.state){case "submit":{let a=n?`${styleText("gray",K)} `:"",c=ii(e.output,t(this.options[this.cursor],"selected"),a);return `${o}${c}`}case "cancel":{let a=n?`${styleText("gray",K)} `:"",c=ii(e.output,t(this.options[this.cursor],"cancelled"),a);return `${o}${c}${n?`
183
+ ${styleText("gray",K)}`:""}`}default:{let a=n?`${styleText("cyan",K)} `:"",c=n?styleText("cyan",fn):"",l=o.split(`
184
+ `).length,p=n?2:1;return `${o}${a}${HE({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:l+p,style:(u,f)=>t(u,u.disabled?"disabled":f?"active":"inactive")}).join(`
179
185
  ${a}`)}
180
- ${l}
181
- `}}}}).prompt()},`${styleText("gray",z)} `,vn=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??Pe.withGuide,r=`${`${t?`${styleText("gray",z)}
182
- `:""}${ai(this.state)} `}${e.message}
183
- `,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",z)} `:"",l=t?styleText("yellow",dr):"";return `${r.trim()}
186
+ ${c}
187
+ `}}}}).prompt()},`${styleText("gray",K)} `,Tr=e=>new ni({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??ke.withGuide,n=`${`${t?`${styleText("gray",K)}
188
+ `:""}${pi(this.state)} `}${e.message}
189
+ `,r=e.placeholder?styleText("inverse",e.placeholder[0])+styleText("dim",e.placeholder.slice(1)):styleText(["inverse","hidden"],"_"),s=this.userInput?this.userInputWithCursor:r,i=this.value??"";switch(this.state){case "error":{let o=this.error?` ${styleText("yellow",this.error)}`:"",a=t?`${styleText("yellow",K)} `:"",c=t?styleText("yellow",fn):"";return `${n.trim()}
184
190
  ${a}${s}
185
- ${l}${o}
186
- `}case "submit":{let o=i?` ${styleText("dim",i)}`:"",a=t?styleText("gray",z):"";return `${r}${a}${o}`}case "cancel":{let o=i?` ${styleText(["strikethrough","dim"],i)}`:"",a=t?styleText("gray",z):"";return `${r}${a}${o}${i.trim()?`
187
- ${a}`:""}`}default:{let o=t?`${styleText("cyan",z)} `:"",a=t?styleText("cyan",dr):"";return `${r}${o}${s}
191
+ ${c}${o}
192
+ `}case "submit":{let o=i?` ${styleText("dim",i)}`:"",a=t?styleText("gray",K):"";return `${n}${a}${o}`}case "cancel":{let o=i?` ${styleText(["strikethrough","dim"],i)}`:"",a=t?styleText("gray",K):"";return `${n}${a}${o}${i.trim()?`
193
+ ${a}`:""}`}default:{let o=t?`${styleText("cyan",K)} `:"",a=t?styleText("cyan",fn):"";return `${n}${o}${s}
188
194
  ${a}
189
- `}}}}).prompt();});function mm(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(p=>String(p[a]).length));return {key:a,header:l,length:c}}),s=" ".repeat(t?.paddingHorizontal??1),i=`
190
- `.repeat(t?.paddingVertical??1),o=t?.renderCell??((a,l)=>l===null?fm.default.dim("null"):String(l));return `${i}${s}| ${n.map(a=>a.header.padEnd(a.length)).join(" | ")} |
191
- ${s}| ${n.map(a=>"\u2500".repeat(a.length)).join(" | ")} |
192
- ${e.map(a=>`${s}| ${Object.entries(a).filter(([l])=>!t?.omitKeys?.includes(l)).map(([l,c])=>o(l,c).padEnd(n.find(p=>p.key===l)?.length??0)).join(" | ")} |`).join(`
193
- `)}${i}`}async function J(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 fm,De=b(()=>{fm=te(ae());Ye();});function hm(e){return typeof e=="object"&&e!==null&&"text"in e&&"values"in e}function c0(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"?dm(e,a0):e;case 1005:case 1007:case 1016:return typeof e=="string"?dm(e,l0):e;default:return e}}function El(e){return {async query(t,r){let n=hm(t)?t.text:t,s=hm(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,c0(a[l.name],l.dataTypeID)])))}}}}var dm,a0,l0,gm=b(()=>{dm=(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},a0=e=>e==="NULL"?null:e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\(.)/g,"$1"):e,l0=e=>e==="NULL"?null:Number.parseInt(e,10);});function f0(e,t){let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`(?<![\\w$"])${r}\\.`);return e.some(s=>n.test(s))}function ym(e,t){let r=new Set;for(let n of t)for(let s of n.matchAll(p0))r.add(s[1]);return Object.values(e.schemas).map(n=>n.name).filter(n=>!u0.has(n)&&!r.has(n)&&f0(t,n)).map(n=>`CREATE SCHEMA IF NOT EXISTS ${n};`)}var u0,p0,wm=b(()=>{u0=new Set(["public","supabase_migrations"]),p0=/\bCREATE\s+SCHEMA\b(?:\s+IF\s+NOT\s+EXISTS)?\s+("?[\w$]+"?)/gi;});async function d0(){try{return await import('@supabase/pg-delta')}catch(e){throw new Error("Postgres schema diffing requires pg-delta to be available.",{cause:e})}}function h0(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 g0(e,t){let r=qs(e),n=new Set([...bt(e),...bt(t)]);return new Set(fr.filter(s=>n.has(s)&&!r.has(s)))}function y0(e){let t=e.trimEnd();return t.endsWith(";")?t:`${t};`}async function bm(e,t,r=""){let{createPlan:n,extractCatalog:s}=await d0(),{PgliteConnection:i}=await He("@supabase/lite/pglite","pglite","@electric-sql/pglite"),o=new i,a=new i;try{let l=Ff(t),c=g0(e,t),p=bt(t);await o.exec(wt(c)),await a.exec(wt(p)),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 u=await s(El(o)),f=await s(El(a)),h=await n(u,f);if(!h)return "";if(h.plan.risk?.level==="data_loss")throw new DataLossError(h.plan.risk.statements.map(h0));let d=h.plan.statements.filter(y=>!Uf(y,l));return [...ym(f,d),...d.map(y0)].join(`
194
-
195
- `)}finally{await o.close().catch(()=>{}),await a.close().catch(()=>{});}}var Sm=b(()=>{sr();gm();wm();bn();});async function ci(e){let{parse:t}=await import('pgsql-parser');return t(e)}var Em=b(()=>{});var ui,xm=b(()=>{cr();jt();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=lr(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 w0,b0,S0,E0,hr,pi,_m=b(()=>{cr();w0=["DECLARE","IF","ELSIF","ELSE","LOOP","WHILE","FOR","FOREACH","EXCEPTION","RAISE","PERFORM","EXECUTE","SELECT"],b0=/^NEW\.(\w+)\s*(?::=|=)\s*(.+)$/is,S0=/^RETURN\s+(NEW|OLD)$/i,E0=/^(INSERT|UPDATE|DELETE)\b/i,hr=class extends Ft{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(S0);if(l){i=l[1].toUpperCase(),s.push({type:"return",value:i});continue}let c=a.match(b0);if(c){s.push({type:"assignment",column:c[1],expression:c[2].trim()});continue}if(E0.test(a)){s.push({type:"dml",sql:a});continue}throw new hr(`"${a.substring(0,80)}" is not translatable to SQLite`,r)}if(!i)throw new Ft("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 hr('"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 hr("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&&w0.includes(r))throw new hr(`"${r}" is not translatable to SQLite`,t)}};});var fi,mi=b(()=>{fi=class extends Error{constructor(r){super(`Migration would cause data loss:
196
- ${r.map(n=>` - ${n.table}: ${n.reason}`).join(`
197
- `)}`);this.warnings=r;this.name="DataLossError";}};});var di,$m=b(()=>{Ct();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(v=>v.name===m.name);if(!y)continue;let g=to(m.sql),E=to(y.sql);g!==E&&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(T=>T.table===m.name),g=r.columns.filter(T=>T.table===m.name),E=new Map(y.map(T=>[T.name,T])),v=new Map(g.map(T=>[T.name,T]));for(let[T,A]of v)E.has(T)||s.push({type:"added",table:m.name,name:T,column:A});for(let[T]of E)v.has(T)||s.push({type:"removed",table:m.name,name:T});for(let[T,A]of E){let C=v.get(T);if(!C)continue;let $={};eo(A.type)!==eo(C.type)&&($.type={from:A.type,to:C.type}),A.nullable!==C.nullable&&($.nullable={from:A.nullable,to:C.nullable}),ro(A.default_value)!==ro(C.default_value)&&($.default_value={from:A.default_value,to:C.default_value}),Object.keys($).length>0&&s.push({type:"modified",table:m.name,name:T,changes:$});}}let p=new Map(t.indexes.map(m=>[this.makeIndexKey(m),m])),u=new Map(r.indexes.map(m=>[this.makeIndexKey(m),m]));for(let[m,y]of u)p.has(m)||i.push({type:"added",...y});for(let[m,y]of p)u.has(m)||i.push({type:"removed",...y});let f=new Map(t.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m])),h=new Map(r.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m]));for(let[m,y]of h)f.has(m)||o.push({type:"added",...y});for(let[m,y]of f)h.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 _0,hi,Tm=b(()=>{mi();Or();_0=["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 u of t.tables.filter(f=>f.type==="added")){i.push({sql:`${u.sql};`,description:`CREATE TABLE ${M(u.name)}`,type:"create_table"});let f=n.indexes.filter(h=>h.table===u.name);for(let h of f){let d=h.unique?"UNIQUE ":"",m=h.columns.map(y=>M(y)).join(", ");i.push({sql:`CREATE ${d}INDEX ${M(h.name)} ON ${M(u.name)} (${m});`,description:`Create index ${M(h.name)} on ${M(u.name)}`,type:"add_index"});}}let a=new Set(r.tables.map(u=>u.name)),l=new Set(n.tables.map(u=>u.name)),c=new Set(t.tables.filter(u=>u.type==="modified").map(u=>u.name)),p=[...a].filter(u=>l.has(u));for(let u of p){if(!(c.has(u)||t.columns.some(m=>m.table===u)||t.indexes.some(m=>m.table===u)||t.foreign_keys.some(m=>m.table===u)))continue;let{canAlter:h,addedCols:d}=this.canSimpleAlter(u,t,n);if(h){for(let g of d)i.push({sql:`ALTER TABLE ${M(u)} ADD COLUMN ${this.columnDef(g)};`,description:`Add column ${M(g.name)} to ${M(u)}`,type:"add_column"});let m=t.indexes.filter(g=>g.table===u&&g.type==="added"),y=t.indexes.filter(g=>g.table===u&&g.type==="removed");for(let g of y)i.push({sql:`DROP INDEX IF EXISTS ${M(g.name)};`,description:`Drop index ${M(g.name)}`,type:"drop_index"});for(let g of m){let E=g.unique?"UNIQUE ":"",v=g.columns.map(T=>M(T)).join(", ");i.push({sql:`CREATE ${E}INDEX ${M(g.name)} ON ${M(u)} (${v});`,description:`Create index ${M(g.name)} on ${M(u)}`,type:"add_index"});}}else {let m=this.rebuildTable(u,r,n,t);i.push(...m.steps),o.push(...m.warnings);}}for(let u of t.tables.filter(f=>f.type==="removed"))i.push({sql:`DROP TABLE ${M(u.name)};`,description:`Drop table ${M(u.name)}`,type:"drop_table"}),o.push({table:u.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(g=>g.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${M(l)}`);i.push({sql:`${c};`,description:`Create temporary table ${M(l)}`,type:"create_table"});let p=r.columns.filter(g=>g.table===t).map(g=>g.name),u=n.columns.filter(g=>g.table===t).map(g=>g.name),f=p.filter(g=>u.includes(g));if(f.length>0){let g=f.map(E=>M(E)).join(", ");i.push({sql:`INSERT INTO ${M(l)} (${g})
195
+ `}}}}).prompt();});async function KE(){return Wt||(Wt=await import('@sentry/node')),Wt}function vm(e){if(e)return false;let t=process.env.LITE_TELEMETRY;if(t==="0"||t==="false")return false;let n=process.env.DO_NOT_TRACK;return !(n==="1"||n==="true"||process.env.CI||process.env.LOCAL)}function zE(){let e=process.versions;return e.bun?"bun":e.deno?"deno":"node"}function XE(){if(process.env.CODESPACES)return "codespaces";if(process.env.REMOTE_CONTAINERS)return "devcontainer";try{return statSync("/.dockerenv"),"docker"}catch{return}}function JE(e){let t=e/1e6;return t<1?"<1MB":t<10?"1-10MB":t<100?"10-100MB":t<1e3?"100MB-1GB":">1GB"}function YE(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 n=new URL(t).hostname;return n==="localhost"||n==="127.0.0.1"||n==="::1"?"local":"remote"}catch{return "remote"}}}function QE(){try{let e=Oe__default.resolve(process.cwd(),fe.config_dir,"config.toml"),t;try{t=readFileSync(e,"utf-8");}catch{return {}}let n;try{n=$t(t);}catch{return {}}let r=n.db?.driver,s=r==="sqlite"||r==="sqlite-postgres"||r==="pglite"||r==="postgres"?r:"sqlite-postgres",i=n.db?.url??fe.default_db_url,o=YE(s,i),a;if(o==="file"&&i.startsWith("file:"))try{let c=i.startsWith("file://")?i.slice(7):i.slice(5),l=Oe__default.resolve(process.cwd(),c);a=statSync(l).size;}catch{}return {driver:s,location:o,sizeBytes:a}}catch{return {}}}async function Rm(e){if(mn)return;mn=true;let t=await KE(),{version:n}=await zr();t.init({dsn:VE,release:`@supabase/lite@${n}`,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",zE()),t.setTag("node",process.version),t.setTag("platform",process.platform),t.setTag("arch",process.arch),t.setTag("ci",!!process.env.CI);let r=XE();r&&t.setTag("container",r);try{let{determineAgent:i}=await import('@vercel/detect-agent'),o=await i();o.isAgent&&t.setTag("agent",o.agent.name);}catch{}let s=QE();s.driver&&t.setTag("db.driver",s.driver),s.location&&t.setTag("db.location",s.location),typeof s.sizeBytes=="number"&&t.setTag("db.size",JE(s.sizeBytes));for(let[i,o]of Object.entries(e.args))t.setTag(`arg.${i}`,!!o);t.startSession(),Cm=true,Gt=t.startInactiveSpan({name:`cli:${e.command}`,op:"cli.command",forceTransaction:true});}async function dn(e,t){if(!mn)return;let n=Wt;try{if(e&&(n.setTag("status","failed"),t instanceof Error&&n.setTag("error_class",t.constructor.name)),Gt&&(Gt.setStatus({code:e?2:1,message:e?"internal_error":"ok"}),Gt.end(),Gt=void 0),Cm){let r=n.getCurrentScope().getSession();r&&e&&(r.status="crashed"),n.endSession();}}finally{await n.flush(2e3).catch(()=>{});}}function $r(e,t){if(!mn)return Promise.resolve(t());let n=Wt,r=()=>n.startSpan({name:e,op:"cli.step"},t);return Gt?n.withActiveSpan(Gt,r):r()}function Pc(e,t){mn&&Wt.setTag(e,t);}function km(e,t){if(!mn)return;let n=Wt;try{n.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 VE,Wt,mn,Cm,Gt,Ar=b(()=>{$n();At();Ee();VE="https://9562525a4ea320539ea7e94859533a17@o398706.ingest.us.sentry.io/4511381939290112";mn=false,Cm=false;});function hn(e){return e instanceof mi}function Nm(){if(Pm)return;Pm=true;let e=process.exit.bind(process),t=false;process.exit=(n=>{let r=typeof n=="number"?n:Number(process.exitCode??0);throw t||(t=true,dn(r!==0).finally(()=>e(r))),new mi(r)});}var mi,Pm,Nc=b(()=>{Ar();mi=class extends Error{code;constructor(t){super(`process.exit(${t})`),this.name="ProcessExit",this.code=t;}};Pm=false;});function Om(e,t){let n=t?.renderHeader??(a=>String(a)),r=Object.keys(e[0]).filter(a=>!t?.omitKeys?.includes(a)).map(a=>{let c=n(a),l=Math.max(c.length,...e.map(p=>String(p[a]).length));return {key:a,header:c,length:l}}),s=" ".repeat(t?.paddingHorizontal??1),i=`
196
+ `.repeat(t?.paddingVertical??1),o=t?.renderCell??((a,c)=>c===null?Lm.default.dim("null"):String(c));return `${i}${s}| ${r.map(a=>a.header.padEnd(a.length)).join(" | ")} |
197
+ ${s}| ${r.map(a=>"\u2500".repeat(a.length)).join(" | ")} |
198
+ ${e.map(a=>`${s}| ${Object.entries(a).filter(([c])=>!t?.omitKeys?.includes(c)).map(([c,l])=>o(c,l).padEnd(r.find(p=>p.key===c)?.length??0)).join(" | ")} |`).join(`
199
+ `)}${i}`}async function Y(e){try{await e();}catch(t){if(hn(t))throw t;(process.env.LOCAL||process.env.DEBUG)&&console.error(t),X.error(String(t)),process.exit(1);}process.exit(0);}var Lm,Ne=b(()=>{Lm=V(z());Qe();Nc();});function tx(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(n=>!Number.isNaN(n)):e;case 1002:case 1009:case 1015:return typeof e=="string"?Im(e,ZE):e;case 1005:case 1007:case 1016:return typeof e=="string"?Im(e,ex):e;default:return e}}function Lc(e){let t=async(n,r)=>{let s=await e.driver.query(n,r?[...r]:[]);return {rows:s.rows.map(o=>Object.fromEntries(s.fields.map(a=>[a.name,tx(o[a.name],a.dataTypeID)])))}};return {query:t,connect:async()=>({query:t,release:()=>{}}),end:async()=>{}}}var Im,ZE,ex,Dm=b(()=>{Im=(e,t=n=>n)=>{if(!e||e==="{}")return [];let n=e.slice(1,-1);if(n==="")return [];let r=[],s="",i=false,o=0;for(let a=0;a<n.length;a++){let c=n[a];c==='"'&&n[a-1]!=="\\"?(i=!i,s+=c):c==="{"&&!i?(o++,s+=c):c==="}"&&!i?(o--,s+=c):c===","&&!i&&o===0?(r.push(t(s)),s=""):s+=c;}return s!==""&&r.push(t(s)),r},ZE=e=>e==="NULL"?null:e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1).replace(/\\(.)/g,"$1"):e,ex=e=>e==="NULL"?null:Number.parseInt(e,10);});async function Fm(){try{let[{extract:e},{plan:t},{segmentActions:n}]=await Promise.all([import('@supabase/pg-delta/extract'),import('@supabase/pg-delta/plan'),import('@supabase/pg-delta/apply')]);return {extract:e,plan:t,segmentActions:n}}catch(e){throw new Error("Postgres schema diffing requires pg-delta to be available.",{cause:e})}}function Um(e){let t=[...e.assumedRoles??[]],n=[{match:{all:[{kind:"acl"},{idField:{field:"grantee",glob:"postgres"}}]},action:"exclude"},{match:{all:[{verb:["link","unlink"]},{edgeTo:{edgeKind:"owner"}}]},action:"exclude"}];return t.length>0&&n.push({match:{all:[{kind:"role"},{name:t}]},action:"exclude"}),e.only?n.push({match:{not:{any:jm(e.only)}},action:"exclude"}):e.exclude?.length&&n.push({match:{any:jm(e.exclude)},action:"exclude"}),{id:"supabase-lite",filter:n,assumedRoles:["postgres",...t]}}function jm(e){let t=[...e];return [{all:[{kind:"schema"},{name:t}]},{schema:t},{target:{schema:t}}]}function Mm(e,t){return e.segmentActions(t.actions).map(n=>({transactional:n.transactional,statements:t.actions.slice(n.start,n.end).map(r=>r.sql)}))}function Bm(e){return e.preamble.filter(t=>t.name!=="search_path").map(t=>`SET LOCAL ${t.name} = ${nx(t.value)}`)}function nx(e){return `'${e.replace(/'/g,"''")}'`}function qm(e){let t=[];for(let n of e.actions)n.dataLoss==="destructive"&&t.push(rx(n));return t}function rx(e){for(let t of e.destroys)if(t.kind==="table")return {table:Oc(t.schema,t.name),reason:"drop table"};for(let t of e.destroys)if(t.kind==="column")return {table:Oc(t.schema,t.table),reason:`drop column ${t.name}`};for(let t of e.destroys)if(t.kind==="sequence")return {table:Oc(t.schema,t.name),reason:"drop sequence"};return {table:"unknown",reason:e.sql}}function Oc(e,t){return e==="public"?t:`${e}.${t}`}var Hm=b(()=>{});function ox(e,t){let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`(?<![\\w$])"?${n}"?\\.`);return e.some(s=>r.test(s))}function Gm(e,t){let n=new Set;for(let r of t)for(let s of r.matchAll(ix))n.add(s[1]);return e.facts().filter(r=>r.id.kind==="schema").map(r=>r.id.name).filter(r=>!sx.has(r)&&!n.has(r)&&ox(t,r)).map(r=>`CREATE SCHEMA IF NOT EXISTS "${r}";`)}var sx,ix,Wm=b(()=>{sx=new Set(["public","supabase_migrations"]),ix=/\bCREATE\s+SCHEMA\b(?:\s+IF\s+NOT\s+EXISTS)?\s+"?([\w$]+)"?/gi;});function cx(e,t){let n=Vs(e),r=new Set([...wt(e),...wt(t)]);return new Set(un.filter(s=>r.has(s)&&!n.has(s)))}function Vm(e){let t=e.trimEnd();return t.endsWith(";")?t:`${t};`}async function Km(e,t,n=""){let r=await Fm(),{PgliteConnection:s}=await qe("@supabase/lite/pglite","pglite","@electric-sql/pglite"),i=new s,o=new s;try{let a=cx(e,t),c=wt(t);await i.exec(bt(a)),await o.exec(bt(c)),i.config.baseSchema&&await i.exec(i.config.baseSchema),o.config.baseSchema&&await o.exec(o.config.baseSchema),n.trim()&&(await i.exec(n),await o.exec(n)),e.trim()&&await i.exec(e),t.trim()&&await o.exec(t);let{factBase:l}=await r.extract(Lc(i)),{factBase:p}=await r.extract(Lc(o)),u=r.plan(l,p,{policy:Um({assumedRoles:Qf(t)})});if(u.actions.length===0)return [];if(u.safetyReport.destructiveActions>0)throw new DataLossError(qm(u));let f=Mm(r,u),h=Gm(p,f.flatMap(m=>m.statements)),d=Bm(u).map(Vm);return f.map((m,y)=>[...d,...y===0?h:[],...m.statements.map(Vm)].join(`
200
+
201
+ `))}finally{await i.close().catch(()=>{}),await o.close().catch(()=>{});}}var zm=b(()=>{tn();Dm();Hm();Wm();yr();});async function di(e){let{parse:t}=await import('pgsql-parser');return t(e)}var Xm=b(()=>{});var hi,Jm=b(()=>{an();Dt();hi=class{constructor(t){this.ast=t;this.result=[...this.walk(this.ast,[],{trackPaths:["returningList"]})];}result=[];*walk(t=this.ast,n=[],r={}){if(!t||typeof t!="object")return;let{trackPaths:s=[]}=r;if(Array.isArray(t)){for(let o=0;o<t.length;o++)yield*this.walk(t[o],n,r);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:n},yield*this.walk(t[o],[...n,o],r);}else for(let[o,a]of Object.entries(t))if(a&&typeof a=="object"){let c=s.includes(o)?[...n,o]:n;yield*this.walk(a,c,r);}}containsUnsupportedNode(){for(let{node:t}of this.result){let n=on(t),r=js.get(n);if(r&&r.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(n=>n.String?.sval||n.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:n})=>"A_Star"in n);if(t.length===0)return false;for(let{path:n}of t)if(!n.includes("SelectStmt")&&!n.includes("returningList"))return true;return false}getRelationDefinitions(){return this.result.filter(({node:n})=>"CreateStmt"in n).map(({node:n})=>n.CreateStmt).map(n=>({relation:{relname:n.relation?.relname??"",inh:n.relation?.inh,relpersistence:n.relation?.relpersistence},columns:n.tableElts?.map(r=>{let s=r.ColumnDef?.typeName?.names?.map(o=>"String"in o?o.String.sval:""),i=s?.some(o=>o.toLowerCase().includes("pg_catalog"));return {name:r.ColumnDef?.colname??"",is_local:r.ColumnDef?.is_local,pg_catalog:i,type:s?.filter(o=>!o.toLowerCase().includes("pg_catalog"))[0]??"",types:s,constraints:r.ColumnDef?.constraints}})}))}getRelationColumnTypes(){return {has_non_pg_catalog_types:this.getRelationDefinitions().some(t=>t.columns?.some(n=>!n.pg_catalog)),types:Array.from(new Set(this.getRelationDefinitions().flatMap(t=>t.columns?.map(n=>n.type))))}}};});var lx,ux,px,fx,gn,gi,Ym=b(()=>{an();lx=["DECLARE","IF","ELSIF","ELSE","LOOP","WHILE","FOR","FOREACH","EXCEPTION","RAISE","PERFORM","EXECUTE","SELECT"],ux=/^NEW\.(\w+)\s*(?::=|=)\s*(.+)$/is,px=/^RETURN\s+(NEW|OLD)$/i,fx=/^(INSERT|UPDATE|DELETE)\b/i,gn=class extends jt{constructor(n,r,s){super(s??`Unsupported PL/pgSQL: ${n}`);this.hint=n;this.body=r;}},gi=class{parse(t){let n=this.extractBlock(t),r=this.splitStatements(n),s=[],i=null;for(let o of r){let a=o.trim();if(!a)continue;this.rejectUnsupported(a);let c=a.match(px);if(c){i=c[1].toUpperCase(),s.push({type:"return",value:i});continue}let l=a.match(ux);if(l){s.push({type:"assignment",column:l[1],expression:l[2].trim()});continue}if(fx.test(a)){s.push({type:"dml",sql:a});continue}throw new gn(`"${a.substring(0,80)}" is not translatable to SQLite`,n)}if(!i)throw new jt("Trigger function body must end with RETURN NEW or RETURN OLD");return {statements:s,returnValue:i}}extractBlock(t){let n=t.trim(),r=n.toUpperCase();if(/^\s*DECLARE\b/i.test(n))throw new gn('"DECLARE" is not translatable to SQLite',t);let s=r.indexOf("BEGIN"),i=r.lastIndexOf("END");if(s===-1||i===-1||i<=s)throw new gn("Expected BEGIN ... END block in trigger function body",t);return n.slice(s+5,i).trim()}splitStatements(t){let n=[],r="",s=0,i=false,o="";for(let c=0;c<t.length;c++){let l=t[c];if(i){r+=l,l===o&&(c+1<t.length&&t[c+1]===o?r+=t[++c]:i=false);continue}if(l==="'"||l==='"'){i=true,o=l,r+=l;continue}if(l==="("){s++,r+=l;continue}if(l===")"){s--,r+=l;continue}if(l===";"&&s===0){n.push(r.trim()),r="";continue}r+=l;}let a=r.trim();return a&&n.push(a),n}rejectUnsupported(t){let n=t.match(/^(\w+)/)?.[1]?.toUpperCase();if(n&&lx.includes(n))throw new gn(`"${n}" is not translatable to SQLite`,t)}};});var yi,bi=b(()=>{yi=class extends Error{constructor(n){super(`Migration would cause data loss:
202
+ ${n.map(r=>` - ${r.table}: ${r.reason}`).join(`
203
+ `)}`);this.warnings=n;this.name="DataLossError";}};});var wi,Qm=b(()=>{Rt();wi=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,n){let r=[],s=[],i=[],o=[],a=new Set(t.tables.map(m=>m.name)),c=new Set(n.tables.map(m=>m.name));for(let m of n.tables)a.has(m.name)||r.push({type:"added",name:m.name,sql:m.sql});for(let m of t.tables)c.has(m.name)||r.push({type:"removed",name:m.name});for(let m of t.tables){let y=n.tables.find(A=>A.name===m.name);if(!y)continue;let g=co(m.sql),E=co(y.sql);g!==E&&r.push({type:"modified",name:m.name,sql:y.sql});}let l=t.tables.filter(m=>c.has(m.name));for(let m of l){let y=t.columns.filter($=>$.table===m.name),g=n.columns.filter($=>$.table===m.name),E=new Map(y.map($=>[$.name,$])),A=new Map(g.map($=>[$.name,$]));for(let[$,v]of A)E.has($)||s.push({type:"added",table:m.name,name:$,column:v});for(let[$]of E)A.has($)||s.push({type:"removed",table:m.name,name:$});for(let[$,v]of E){let C=A.get($);if(!C)continue;let T={};ao(v.type)!==ao(C.type)&&(T.type={from:v.type,to:C.type}),v.nullable!==C.nullable&&(T.nullable={from:v.nullable,to:C.nullable}),lo(v.default_value)!==lo(C.default_value)&&(T.default_value={from:v.default_value,to:C.default_value}),Object.keys(T).length>0&&s.push({type:"modified",table:m.name,name:$,changes:T});}}let p=new Map(t.indexes.map(m=>[this.makeIndexKey(m),m])),u=new Map(n.indexes.map(m=>[this.makeIndexKey(m),m]));for(let[m,y]of u)p.has(m)||i.push({type:"added",...y});for(let[m,y]of p)u.has(m)||i.push({type:"removed",...y});let f=new Map(t.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m])),h=new Map(n.foreign_keys.map(m=>[this.makeForeignKeyKey(m),m]));for(let[m,y]of h)f.has(m)||o.push({type:"added",...y});for(let[m,y]of f)h.has(m)||o.push({type:"removed",...y});let d=r.length>0||s.length>0||i.length>0||o.length>0;return {tables:r,columns:s,indexes:i,foreign_keys:o,has_changes:d}}};});var dx,Si,Zm=b(()=>{bi();Rn();dx=["CURRENT_TIMESTAMP","CURRENT_TIME","CURRENT_DATE"],Si=class{plan(t,n,r,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 u of t.tables.filter(f=>f.type==="added")){i.push({sql:`${u.sql};`,description:`CREATE TABLE ${U(u.name)}`,type:"create_table"});let f=r.indexes.filter(h=>h.table===u.name);for(let h of f){let d=h.unique?"UNIQUE ":"",m=h.columns.map(y=>U(y)).join(", ");i.push({sql:`CREATE ${d}INDEX ${U(h.name)} ON ${U(u.name)} (${m});`,description:`Create index ${U(h.name)} on ${U(u.name)}`,type:"add_index"});}}let a=new Set(n.tables.map(u=>u.name)),c=new Set(r.tables.map(u=>u.name)),l=new Set(t.tables.filter(u=>u.type==="modified").map(u=>u.name)),p=[...a].filter(u=>c.has(u));for(let u of p){if(!(l.has(u)||t.columns.some(m=>m.table===u)||t.indexes.some(m=>m.table===u)||t.foreign_keys.some(m=>m.table===u)))continue;let{canAlter:h,addedCols:d}=this.canSimpleAlter(u,t,r);if(h){for(let g of d)i.push({sql:`ALTER TABLE ${U(u)} ADD COLUMN ${this.columnDef(g)};`,description:`Add column ${U(g.name)} to ${U(u)}`,type:"add_column"});let m=t.indexes.filter(g=>g.table===u&&g.type==="added"),y=t.indexes.filter(g=>g.table===u&&g.type==="removed");for(let g of y)i.push({sql:`DROP INDEX IF EXISTS ${U(g.name)};`,description:`Drop index ${U(g.name)}`,type:"drop_index"});for(let g of m){let E=g.unique?"UNIQUE ":"",A=g.columns.map($=>U($)).join(", ");i.push({sql:`CREATE ${E}INDEX ${U(g.name)} ON ${U(u)} (${A});`,description:`Create index ${U(g.name)} on ${U(u)}`,type:"add_index"});}}else {let m=this.rebuildTable(u,n,r,t);i.push(...m.steps),o.push(...m.warnings);}}for(let u of t.tables.filter(f=>f.type==="removed"))i.push({sql:`DROP TABLE ${U(u.name)};`,description:`Drop table ${U(u.name)}`,type:"drop_table"}),o.push({table:u.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,n,r,s){let i=[],o=[],a=r.tables.find(g=>g.name===t);if(!a)return {steps:i,warnings:o};let c=`_${t}_migrate_new`,l=a.sql.replace(new RegExp(`(CREATE\\s+TABLE\\s+)(?:"${t}"|${t})`,"i"),`$1${U(c)}`);i.push({sql:`${l};`,description:`Create temporary table ${U(c)}`,type:"create_table"});let p=n.columns.filter(g=>g.table===t).map(g=>g.name),u=r.columns.filter(g=>g.table===t).map(g=>g.name),f=p.filter(g=>u.includes(g));if(f.length>0){let g=f.map(E=>U(E)).join(", ");i.push({sql:`INSERT INTO ${U(c)} (${g})
198
204
  SELECT ${g}
199
- FROM ${M(t)};`,description:`Copy data from ${M(t)} to ${M(l)}`,type:"copy_data"});}i.push({sql:`DROP TABLE ${M(t)};`,description:`Drop old table ${M(t)}`,type:"drop_table"}),i.push({sql:`ALTER TABLE ${M(l)} RENAME TO ${M(t)};`,description:`Rename ${M(l)} to ${M(t)}`,type:"rename_table"});let h=n.indexes.filter(g=>g.table===t);for(let g of h){let E=g.unique?"UNIQUE ":"",v=g.columns.map(T=>M(T)).join(", ");i.push({sql:`CREATE ${E}INDEX ${M(g.name)} ON ${M(t)} (${v});`,description:`Recreate index ${M(g.name)} on ${M(t)}`,type:"add_index"});}let d=n.triggers?.filter(g=>g.table===t)??[];for(let g of d)i.push({sql:`${g.sql};`,description:`Recreate trigger ${M(g.name)} on ${M(t)}`,type:"create_trigger"});let m=s.columns.filter(g=>g.table===t&&g.type==="removed");for(let g of m)o.push({table:t,reason:`column "${g.name}" will be dropped`});let y=s.columns.filter(g=>g.table===t&&g.type==="modified");for(let g of y)g.changes?.type&&o.push({table:t,reason:`column "${g.name}" type changes from ${g.changes.type.from} to ${g.changes.type.to}`}),g.changes?.nullable&&!g.changes.nullable.to&&o.push({table:t,reason:`column "${g.name}" becomes NOT NULL`});return {steps:i,warnings:o}}canSimpleAlter(t,r,n){let s=r.columns.filter(u=>u.table===t),i=s.filter(u=>u.type==="added"),o=s.filter(u=>u.type==="removed"),a=s.filter(u=>u.type==="modified"),l=r.foreign_keys.some(u=>u.table===t);if(o.length>0||a.length>0||l)return {canAlter:false,addedCols:i};let c=n.tables.find(u=>u.name===t);return c&&/\bCHECK\s*\(/i.test(c.sql)?{canAlter:false,addedCols:i}:{canAlter:i.every(u=>{let f=u.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 _0.includes(r)}columnDef(t){let r=t.column,n=`${M(r.name)} ${r.type||"TEXT"}`;return r.nullable||(n+=" NOT NULL"),r.default_value!=null&&(n+=` DEFAULT ${r.default_value}`),n}};});function A0(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"&&C0.has(t.objtype)}var C0,gi,vm=b(()=>{cr();jt();jt();xm();ft();_m();mi();$m();Tm();Or();ka();Na();C0=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=lr(t);if(n==="GrantStmt"&&A0(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=>Lc(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":yf(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,p=false;if(t.typeName){let u=t.typeName.names?.map(d=>d.String?.sval||d.String?.str).filter(Boolean);c=u&&(u.length===2&&u[0]==="pg_catalog"?u[1]:u[0]),i=!!(c&&Ps(c))||this.serialColumns.has(t),p=!!(t.typeName.arrayBounds&&t.typeName.arrayBounds.length>0);let f=Array.isArray(t.typeName.typmods)?t.typeName.typmods:[],h=d=>f[d]?.A_Const?.ival?.ival??f[d]?.A_Const?.val?.ival?.ival;if(c&&Ls(c)&&f.length>0){let d=h(0);typeof d=="number"&&d>0&&(a={maxLen:d});}if(c&&Is(c)&&f.length>=2){let d=h(0),m=h(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 u=Array.isArray(t.constraints)?t.constraints:[],f=u.map(d=>this.visit(d,r));n.push(...f.filter(Boolean));let h=u.some(d=>d.Constraint?.contype==="CONSTR_CHECK");i&&o&&!h?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 u={isArray:p};a&&(u.lengthConstraint=a.maxLen),l&&(u.numericPrecision=l);let f=this.enums.get(c.toLowerCase());f&&(u.enumValues=f);let m=qt({schema:"public",table:"",column:s,pgTypeName:c,nullable:true,defaultValue:null,defaultFn:null,isPrimaryKey:o,isUnique:false,isSerial:i},u).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 (${Dt(t.keys).map(i=>this.visit(i,r)).join(", ")})`:"PRIMARY KEY";if(n==="CONSTR_UNIQUE")return t.keys&&t.keys.length>0?`UNIQUE (${Dt(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=Oa(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=Ms[i];if(c?.sqlite){let p=c.sqlite();return p.includes("(")?p:`${p}(${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(!gf.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(u=>u.String?.sval).filter(Boolean)??[],l=a.length===2&&a[0]==="pg_catalog"?a[1]:a[0],p=["text","varchar","character varying","char","bpchar","name","uuid"].includes(l?.toLowerCase());try{let u=this.parsePgArrayLiteral(o,p);return `'${JSON.stringify(u).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=Dt(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=Dt(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(p=>"AlterTableCmd"in p&&!s.includes(p.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 p of i){let u=p.AlterTableCmd.subtype;if(o.includes(u)){let f={...t,cmds:[p]};l.push(super.AlterTableStmt(f,r));}else if(a.includes(u))c.push(p.AlterTableCmd);else throw new B({AlterTableStmt:t},`AlterTableCmd with subtype ${u} is not supported in SQLite`)}if(c.length>0){let p=this.getRelationName(t.relation);l.push(this.generateRebuildSql(p,c));}return l.join(`;
200
- `)}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=Dt(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=Dt(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(u=>u.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 u=t.columns.map(f=>f.String?.sval).filter(Boolean);l.push(`UPDATE OF ${u.join(", ")}`);}else l.push("UPDATE");let c=l.join(" OR "),p=this.buildTriggerBody(o,s,r);return [`CREATE TRIGGER ${n}`,`${a} ${c} ON ${s}`,"FOR EACH ROW","BEGIN",...p.map(u=>` ${u};`),"END"].join(`
201
- `)}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,p)=>`${i}${o} ${this.flattenTriggerTableRef(a??l,c??p)}`),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");if(t.renameType==="OBJECT_POLICY")return "";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(`
202
- `):""}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(u=>u.name===r);if(n===-1)return;let s=t.columns.filter(u=>u.table===r),i=t.foreign_keys.filter(u=>u.table===r),o=t.check_constraints.filter(u=>u.table===r),a=s.map(u=>{let f=`${M(u.name)} ${u.type||"TEXT"}`;return u.is_primary_key&&(f+=" PRIMARY KEY"),u.nullable||(f+=" NOT NULL"),u.default_value!=null&&(f+=` DEFAULT ${u.default_value}`),f}),l=i.map(u=>`FOREIGN KEY (${M(u.column)}) REFERENCES ${M(u.ref_table)}(${M(u.ref_column)}) ON UPDATE ${u.on_update} ON DELETE ${u.on_delete}`),c=o.map(u=>`CHECK (${u.expression})`),p=[...a,...l,...c];t.tables[n]={...t.tables[n],sql:`CREATE TABLE ${M(r)} (${p.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 Cm(e){return `${e?.schemaname??"public"}.${e?.relname??""}`}function R0(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 k0(e){return (Array.isArray(e.constraints)?e.constraints:[]).some(r=>r.Constraint?.contype==="CONSTR_IDENTITY")}function Am(e,t){let r=Array.isArray(e.constraints)?e.constraints:[],n=r.filter(s=>!R0(s));n.length!==r.length?(e.constraints=n,t.add(e)):k0(e)&&t.add(e);}function O0(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 Rm(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(Cm(i.relation),i);for(let o of i.tableElts??[])"ColumnDef"in o&&Am(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(Cm(i.relation)),a=i.cmds??[],l=[];for(let c of a){let p=c.AlterTableCmd;p?.subtype==="AT_AddColumn"&&p.def&&"ColumnDef"in p.def&&Am(p.def.ColumnDef,t),!(o&&p?.subtype==="AT_AddConstraint"&&p.def&&O0(o,p.def,t))&&l.push(c);}i.cmds=l;}return t}var km=b(()=>{});async function Cn(e,t={}){let r=await ci(e);return {ast:r,...N0(r,t)}}function N0(e,t={}){let r=Rm(e),n=Da(e),s=Ua(e,n),i=ja(e),o=Ma(e),a=Ba(e),l=new gi(e,{...t,enums:n,serialColumns:r}),{policies:c,tables:p}=Fa(e,{defaultSchema:t.defaultSchema,validateMutations:t.strict});if(t.strict)for(let u of c){if(!s.get(`${u.data.schema??"public"}.${u.data.table}`))throw new Error(`Policy "${u.data.name}" references unknown table "${u.data.table}"`);if(!p.has(u.data.table))throw new Error(`RLS is not enabled on table "${u.data.table}"`)}return {ddl:l.deparseQuery(),enums:n,rls:{tables:p,policies:c},schema:s,vars:i,tableConstraints:o,comments:a}}var yi=b(()=>{Em();vm();km();ha();Ha();ga();});async function Om(e){if(e.trim())try{await ci(e);}catch(t){let r=t instanceof Error?t.message:String(t);throw new _l(`Declarative schema (schemas/*.sql) is not valid SQL: ${r}`,{cause:t})}}async function xl(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 vt(s))if(i.trim())try{await e.exec(i);}catch(o){if(!n)throw o}}catch(s){if(!n)throw s}}async function Nm(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 xl(s,i,n,!0);for(let o of await Ue(e))await xl(s,o.sql,n,!0);await xl(s,t,n,!1);}finally{await s.close().catch(()=>{});}}var _l,Pm=b(()=>{yi();Ct();ht();Lt();_l=class extends Error{constructor(t,r){super(t,r),this.name="SchemaParseError";}};});async function D0(){return Wt||(Wt=await import('@sentry/node')),Wt}function j0(){if(Im)return;Im=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 Fm(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 F0(){let e=process.versions;return e.bun?"bun":e.deno?"deno":"node"}function U0(){if(process.env.CODESPACES)return "codespaces";if(process.env.REMOTE_CONTAINERS)return "devcontainer";try{return statSync("/.dockerenv"),"docker"}catch{return}}function M0(e){let t=e/1e6;return t<1?"<1MB":t<10?"1-10MB":t<100?"10-100MB":t<1e3?"100MB-1GB":">1GB"}function B0(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 q0(){try{let e=Fe__default.resolve(process.cwd(),we.config_dir,"config.toml"),t;try{t=readFileSync(e,"utf-8");}catch{return {}}let r;try{r=Tt(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??we.default_db_url,o=B0(s,i),a;if(o==="file"&&i.startsWith("file:"))try{let l=i.startsWith("file://")?i.slice(7):i.slice(5),c=Fe__default.resolve(process.cwd(),l);a=statSync(c).size;}catch{}return {driver:s,location:o,sizeBytes:a}}catch{return {}}}async function Um(e){if(gr)return;gr=true;let t=await D0(),{version:r}=await Xn();t.init({dsn:I0,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",F0()),t.setTag("node",process.version),t.setTag("platform",process.platform),t.setTag("arch",process.arch),t.setTag("ci",!!process.env.CI);let n=U0();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=q0();s.driver&&t.setTag("db.driver",s.driver),s.location&&t.setTag("db.location",s.location),typeof s.sizeBytes=="number"&&t.setTag("db.size",M0(s.sizeBytes));for(let[i,o]of Object.entries(e.args))t.setTag(`arg.${i}`,!!o);t.startSession(),jm=true,Gt=t.startInactiveSpan({name:`cli:${e.command}`,op:"cli.command",forceTransaction:true}),j0();}async function wi(e,t){if(!gr)return;let r=Wt;try{if(e&&(r.setTag("status","failed"),t instanceof Error&&r.setTag("error_class",t.constructor.name)),Gt&&(Gt.setStatus({code:e?2:1,message:e?"internal_error":"ok"}),Gt.end(),Gt=void 0),jm){let n=r.getCurrentScope().getSession();n&&e&&(n.status="crashed"),r.endSession();}}finally{await r.flush(2e3).catch(()=>{});}}function An(e,t){if(!gr)return Promise.resolve(t());let r=Wt,n=()=>r.startSpan({name:e,op:"cli.step"},t);return Gt?r.withActiveSpan(Gt,n):n()}function $l(e,t){gr&&Wt.setTag(e,t);}function Mm(e,t){if(!gr)return;let r=Wt;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 I0,Wt,gr,jm,Gt,Im,bi=b(()=>{Tr();Xt();$e();I0="https://9562525a4ea320539ea7e94859533a17@o398706.ingest.us.sentry.io/4511381939290112";gr=false,jm=false,Im=false;});var Hm={};de(Hm,{checkPendingDeclarativeSchema:()=>qm,db:()=>K0});function V0(){console.log(ce.default.yellow("Declarative diff includes potentially destructive changes.")),console.log(ce.default.dim("Review the schema manually and author an explicit migration for drops or other data-loss changes."));}async function qm(e,t){let r=await ge(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 Bm(e){let t=await ot(e),r=await ge(t);if(!r&&!t.connection.config.baseSchema){console.log(ce.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(ce.default.dim("Schema in sync."));return}pr(s);}async function z0(e,t){if(t?.trim())return t;if(!process.stdin.isTTY){let s=await Mn();if(s.trim())return s}let r=await ge(e);if(r?.trim())return r;let n=await Qr(e);if(n?.trim())return n;throw new Error("No SQL provided and no declarative schemas or migrations found to deparse.")}var ce,W0,K0,Gm=b(()=>{ce=te(ae());De();Ja();Je();ht();Sm();$e();it();_t();Jt();Ct();Hs();Je();Lt();Pm();bi();W0="Local Development:";K0=e=>{let t=e.command("db").description("Database operations").helpGroup(W0);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 J(async()=>{if(await Q(r.config),!r.file){await Bm(r.config);return}let n=await ot(r.config),s=await ge(n);if(!s.trim()){console.log(ce.default.dim("No declarative schemas found \u2014 nothing to diff."));return}await Om(s);let i=Ie(n.connection);if(i==="sqlite"){console.log(ce.default.yellow('`lite db diff -f` is not supported on the bare "sqlite" driver yet.')),console.log(ce.default.dim('Declarative schema diffs require the "sqlite-postgres" driver. Set db.driver = "sqlite-postgres" in supabase/config.toml.'));return}let o;{let p=await Qr(n);try{o=await bm(p,s,n.connection.config.baseSchema??"");}catch(u){throw u instanceof DataLossError?(V0(),new Error("Declarative diff includes potentially destructive changes.")):u}if(!o.trim()){console.log(ce.default.green("Schema in sync \u2014 no migration written."));return}}try{await Nm(n,o);}catch(p){Mm(p,{variant:i,failingSql:o});let u=p instanceof Error?p.message:String(p);throw new Error(`Generated migration does not run on the "${i}" backend and was not written: ${u}. This likely indicates a gap in supalite's Postgres\u2192SQLite translation; it has been reported.`)}let a=Fe__default.join(process.cwd(),"supabase",It(n));ke(a);let l=da(r.file,ma()),c=Fe__default.join(a,l);await fe__default.writeFile(c,o+`
203
- `,{flag:"wx"}),console.log(ce.default.green(" \u279C"),"Wrote migration",ce.default.cyan(Fe__default.relative(process.cwd(),c)));});}),t.command("reset").description(ye("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").option("--hard","Delete and recreate the local DB file/dir instead of dropping objects via SQL",false).action(async r=>{console.log(),await J(async()=>{if(await Q(r.config),r.hard){let l=await Qn(r.config);if(l){await fe__default.rm(l,{recursive:!0,force:!0});for(let c of ["-wal","-shm","-journal"])await fe__default.rm(`${l}${c}`,{force:!0});console.log(ce.default.dim(` \u279C removed ${Fe__default.relative(process.cwd(),l)}`));}else console.log(ce.default.dim("--hard: no local database file to delete; resetting via SQL."));}let n=await ot(r.config),s=n.connection.dialect==="postgres",i=[];if(s){let{rows:l}=await n.connection.exec(`SELECT nspname AS name FROM pg_namespace
204
- 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(u=>u.type==="table"),p=(u,f)=>`"${u?`${u}.${f}`:f}"`;for(let u of c)i.push(`DROP TABLE IF EXISTS ${p(u.schema,u.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(),await Nf();let o=await Ht(n);for(let l of o.applied)console.log(ce.default.green(" \u2713"),"Applied",ce.default.cyan(l.filename));(await qm(n,o.applied.length)).hint&&(console.log(),console.log(ce.default.yellow("Declarative schemas detected with pending changes.")),console.log(ce.default.dim("Run `lite db diff -f <name>` to generate a migration, then re-run `lite db reset`."))),r.seed!==!1&&await yn(n).catch(l=>console.error(ce.default.yellow("Seed warning: "+String(l)))),console.log(ce.default.green("Database reset."));});}),t.command("translate").description("Translate Postgres SQL to this project's backend dialect").argument("[sql]","SQL to translate; reads stdin if omitted").option("--config <config>","Path to the config file").option("--deparse",ye("Emit the JSON deparse payload (RLS policies + session vars) instead of DDL, for edge/serverless runtimes")).option("-o, --out <file>","Write output to a file instead of stdout").action(async(r,n)=>{await J(async()=>{await Q(n.config);let s=await ot(n.config);try{if(n.deparse){let l=await z0(s,r),p=[s.connection.config.baseSchema??"",l].filter(d=>d.trim()).join(`
205
-
206
- `),u=await s.connection.translateDdl(p),f=SqliteConnection.serializeDeparseInfo(u),h=JSON.stringify(f,null,2);n.out?(await fe__default.writeFile(n.out,h+`
207
- `,"utf8"),console.error(ce.default.green(" \u279C"),`Wrote ${f.rls.policies.length} policies to`,ce.default.cyan(Fe__default.relative(process.cwd(),Fe__default.resolve(n.out))))):console.log(h);return}let i=r??await Mn(),o=await s.connection.translateDdl(i),a=typeof o=="string"?o:o.ddl??"";console.log(a);}finally{await s.connection.close();}});}),t.command("query").description("Execute a SQL statement against the local or remote project").argument("[statement]","The statement to execute; reads stdin if omitted").option("--remote","Execute the statement on the remote project",false).option("--config <config>","Path to the config file").action(async(r,n)=>{await J(async()=>{n.remote||await Q(n.config);let s=await ot(n.remote?!0:n.config);try{if(r){Qe(`Executing: ${ce.default.cyan(r)}`);let o=await s.connection.exec(r);console.log(o);return}let i=await Mn();for(let o of vt(i)){if(!o.trim())continue;let a=await s.connection.exec(o);console.log(a);}}finally{await s.connection.close();}});}),t.command("schema").description(ye("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 J(async()=>{if(await Q(r.config),r.diff){await Bm(r.config);return}let s=await(await ot(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(`;
208
-
209
- `)+(i.length?";":""));return}If(s);});});};});var Wm={};de(Wm,{migration:()=>Y0});var xe,J0,Y0,Vm=b(()=>{xe=te(ae());ht();Hs();Lt();Ae();$e();J0="Local Development:",Y0=e=>{let t=e.command("migration").description("Manage database migrations").helpGroup(J0);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 Q(n.config);let i=await(await V({withSupabaseClient:false})).project.local.createApp(n.config),o=await df(i,r);console.log(xe.default.green(" \u279C"),"Created",xe.default.cyan(Fe__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 Q(r.config);let s=await(await V({withSupabaseClient:false})).project.local.createApp(r.config);if(r.dryRun){await ar(s.connection);let i=new Set(await Jr(s.connection)),a=(await Ue(s)).filter(l=>!i.has(l.version));a.length===0&&(console.log(xe.default.green("No pending migrations.")),process.exit(0)),console.log(xe.default.dim("Pending:"));for(let l of a)console.log(" "+xe.default.cyan(l.filename));process.exit(0);}try{let i=await Ht(s);if(i.applied.length===0)console.log(xe.default.green("Local database is up to date."));else for(let o of i.applied)console.log(xe.default.green(" \u2713"),"Applied",xe.default.cyan(o.filename));process.exit(0);}catch(i){console.error(xe.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 Q(r.config);let s=await(await V({withSupabaseClient:false})).project.local.createApp(r.config);await ar(s.connection);let i=new Set(await Jr(s.connection)),o=await Ue(s);console.log(xe.default.dim(`Migrations in ${It(s)}:`)),o.length===0&&console.log(xe.default.dim(" (none)"));for(let c of o){let p=i.has(c.version)?xe.default.green("[applied]"):xe.default.yellow("[pending]");console.log(` ${p} ${xe.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(xe.default.dim("Recorded versions without matching file:"));for(let c of l)console.log(` ${xe.default.red("[orphan]")} ${c}`);}process.exit(0);});};});function Z0(e){let t=(e??process.env.SUPABASE_ENDPOINT??Q0).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 zm(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 Q0,Ei,Km=b(()=>{Q0="https://supabase.com";Ei=class{constructor(t,r){this.token=t;if(!t)throw new Error("Supabase access token required");let n=Z0(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 tx(e){if(e==null||typeof e!="string")return true;try{return JSON.parse(e),!0}catch{return false}}function rx(e){return e==null?true:typeof e!="string"?false:ex.test(e)}function nx(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 Xm(e){if(!e)return;let t=e.match(/varchar\s*\(\s*(\d+)\s*\)/i);return t?Number(t[1]):void 0}function Jm(e){return e?/jsonb?/i.test(e):false}function Ym(e){return e?/\buuid\b/i.test(e):false}function Qm(e){return e?/timestamp(tz)?|timestamp with|timestamp without/i.test(e):false}async function Zm(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(h=>h.table===i&&(h.schema??o)===o),c=0,p=[];try{let h=await e.connection.exec(`SELECT COUNT(*) as c FROM ${a}`);c=Number(h?.rows?.[0]?.c??0);}catch{r.push({table:i,schema:o,rowCount:0,issues:p});continue}if(c===0){r.push({table:i,schema:o,rowCount:c,issues:p});continue}let u=l.filter(h=>Jm(h.type)||Ym(h.type)||Qm(h.type)||Xm(h.type)!==void 0);if(u.length===0){r.push({table:i,schema:o,rowCount:c,issues:p});continue}let f=u.map(h=>`"${h.name}"`).join(", ");try{let d=(await e.connection.exec(`SELECT ${f} FROM ${a}`))?.rows??[];for(let m of d)for(let y of u){let g=m[y.name];if(Jm(y.type)&&!tx(g)){p.push({table:i,column:y.name,kind:"invalid_json",message:`row contains non-parseable JSON in ${i}.${y.name}`});continue}if(Ym(y.type)&&g!=null&&!rx(g)){p.push({table:i,column:y.name,kind:"invalid_uuid",message:`row contains invalid UUID in ${i}.${y.name}`});continue}if(Qm(y.type)&&!nx(g)){p.push({table:i,column:y.name,kind:"invalid_timestamp",message:`row contains unparseable timestamp in ${i}.${y.name}`});continue}let E=Xm(y.type);E!==void 0&&typeof g=="string"&&g.length>E&&p.push({table:i,column:y.name,kind:"varchar_overflow",message:`value exceeds varchar(${E}) in ${i}.${y.name}`});}}catch{}r.push({table:i,schema:o,rowCount:c,issues:p});}return r}var ex,ed=b(()=>{ex=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;});function Et(e){let t=[],r="",n=0,s=false,i=false,o=false,a=false,l=null;for(;n<e.length;){let p=e[n],u=e[n+1];if(o){r+=p,p===`
210
- `&&(o=false),n++;continue}if(a){if(r+=p,p==="*"&&u==="/"){r+=u,n+=2,a=false;continue}n++;continue}if(l){if(r+=p,p==="$"&&e.startsWith(l,n)){r+=e.slice(n+1,n+l.length),n+=l.length,l=null;continue}n++;continue}if(s){if(r+=p,p==="'"&&u==="'"){r+=u,n+=2;continue}p==="'"&&(s=false),n++;continue}if(i){if(r+=p,p==='"'&&u==='"'){r+=u,n+=2;continue}p==='"'&&(i=false),n++;continue}if(p==="-"&&u==="-"){o=true,r+=p,n++;continue}if(p==="/"&&u==="*"){a=true,r+=p,n++;continue}if(p==="'"){s=true,r+=p,n++;continue}if(p==='"'){i=true,r+=p,n++;continue}if(p==="$"){let f=e.slice(n).match(/^\$[A-Za-z0-9_]*\$/);if(f){l=f[0],r+=f[0],n+=f[0].length;continue}}if(p===";"){let f=r.trim();f&&t.push(f),r="",n++;continue}r+=p,n++;}let c=r.trim();return c&&t.push(c),t}var xi=b(()=>{});async function _i(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 td(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 ge(e),i=Et(s);i.length===0&&t.push("No schema statements found in supabase/schemas/*.sql");let o=[];if(n)try{o=await Zm(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 _i(e,"users"),a.sessions=await _i(e,"sessions"),a.refresh_tokens=await _i(e,"refresh_tokens"),a.identities=await _i(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 rd=b(()=>{Je();ed();xi();});var Tl,nd=b(()=>{Tl=`-- supabase/auth core schema (Postgres)
205
+ FROM ${U(t)};`,description:`Copy data from ${U(t)} to ${U(c)}`,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(c)} RENAME TO ${U(t)};`,description:`Rename ${U(c)} to ${U(t)}`,type:"rename_table"});let h=r.indexes.filter(g=>g.table===t);for(let g of h){let E=g.unique?"UNIQUE ":"",A=g.columns.map($=>U($)).join(", ");i.push({sql:`CREATE ${E}INDEX ${U(g.name)} ON ${U(t)} (${A});`,description:`Recreate index ${U(g.name)} on ${U(t)}`,type:"add_index"});}let d=r.triggers?.filter(g=>g.table===t)??[];for(let g of d)i.push({sql:`${g.sql};`,description:`Recreate trigger ${U(g.name)} on ${U(t)}`,type:"create_trigger"});let m=s.columns.filter(g=>g.table===t&&g.type==="removed");for(let g of m)o.push({table:t,reason:`column "${g.name}" will be dropped`});let y=s.columns.filter(g=>g.table===t&&g.type==="modified");for(let g of y)g.changes?.type&&o.push({table:t,reason:`column "${g.name}" type changes from ${g.changes.type.from} to ${g.changes.type.to}`}),g.changes?.nullable&&!g.changes.nullable.to&&o.push({table:t,reason:`column "${g.name}" becomes NOT NULL`});return {steps:i,warnings:o}}canSimpleAlter(t,n,r){let s=n.columns.filter(u=>u.table===t),i=s.filter(u=>u.type==="added"),o=s.filter(u=>u.type==="removed"),a=s.filter(u=>u.type==="modified"),c=n.foreign_keys.some(u=>u.table===t);if(o.length>0||a.length>0||c)return {canAlter:false,addedCols:i};let l=r.tables.find(u=>u.name===t);return l&&/\bCHECK\s*\(/i.test(l.sql)?{canAlter:false,addedCols:i}:{canAlter:i.every(u=>{let f=u.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 n=t.trim().toUpperCase();return dx.includes(n)}columnDef(t){let n=t.column,r=`${U(n.name)} ${n.type||"TEXT"}`;return n.nullable||(r+=" NOT NULL"),n.default_value!=null&&(r+=` DEFAULT ${n.default_value}`),r}};});function wx(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"&&bx.has(t.objtype)}var bx,Ei,ed=b(()=>{an();Dt();Dt();Jm();lt();Ym();bi();Qm();Zm();Rn();Fa();Ma();bx=new Set(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_SEQUENCE","OBJECT_SCHEMA"]);Ei=class extends Deparser{enums;schemaHandling;warnings=[];helper;config;triggerFunctions=new Map;plpgsqlParser=new gi;introspection;functionResolution;serialColumns;constructor(t,{enums:n,schemaHandling:r,introspection:s,serialColumns:i,...o}={}){super(t,o),this.schemaHandling=r??"default",this.enums=n??new Map,this.helper=new hi(t),this.config=o,this.introspection=s,this.functionResolution=o?.functionResolution??"translate",this.serialColumns=i??new WeakSet;}visit(t,n){let r=on(t);if(r==="GrantStmt"&&wx(t))return "";let s=js.get(r);if(s){if(s.react==="error")throw new M({[r]:t},`Unsupported node type: ${r}`);return s.react==="warn"&&this.warnings.push({type:r,node:t}),""}return super.visit(t,n)}deparse(t,n){if(t==null)return null;if(!n){let r=new SqlFormatter;n=new DeparserContext({formatter:r});}return typeof t=="number"||t instanceof Number?t.toString():this.visit(t,n)}RawStmt(t,n){if(!t.stmt||t.stmt.CommentStmt)return "";let r=this.deparse(t.stmt,n);return !r||r.length===0?"":t.stmt_len?r+";":r}RangeVar(t,n){this.ensureRelation(t);let r=this.effectiveSchema(t.schemaname),s=t.relname,i=this.quoteBareIfNeeded(s);r&&(this.schemaHandling==="prefix"?i=`${r}__${s}`:i=`"${r}.${s}"`);let o=t.alias?" "+this.Alias(t.alias,n):"";return i+o}getRelationName(t){this.ensureRelation(t);let n=this.effectiveSchema(t.schemaname),r=t.relname;return n?this.schemaHandling==="prefix"?`${n}__${r}`:`${n}.${r}`:r}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 n=this.config.forceDefaultSchema;n&&(!t||typeof t!="object"||n.length===0||t.schemaname||(t.schemaname=n));}CreateStmt(t,n){if(t.inhRelations&&t.inhRelations.length>0)throw new M({CreateStmt:t},"Inheritance is not supported in SQLite");if(t.ofTypename!==void 0)throw new M({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 M({CreateStmt:t},"Empty tables are not supported in SQLite. Define at least one column.");return t.accessMethod&&(t.accessMethod=void 0),super.CreateStmt(t,n)+" STRICT"}TableLikeClause(t,n){throw new M({TableLikeClause:t},"CREATE TABLE ... (LIKE ...) is not supported in SQLite. Define the table columns explicitly instead.")}DefElem(t,n){if(["oids","fillfactor",/^autovacuum_/i,"toast_tuple_target","parallel_workers","user_catalog_table"].some(i=>Ll(t.defname??"",i)))return "";let s=super.DefElem(t,n);throw new M({DefElem:t},`DefElem "${t.defname}" (${s}) not supported`)}TypeName(t,n){if(!t.names)return "";let r=t.names.map(i=>i.String?i.String.sval||i.String.str:"").filter(Boolean);if(r.length===0)return "";let s=r.length===2&&r[0]==="pg_catalog"?r[1]:r.join(".");return t.arrayBounds&&t.arrayBounds.length>0||this.enums.has(s.toLowerCase())?"TEXT":Sf(s)}ColumnDef(t,n){let r=[],s=t.colname;s&&r.push(this.quoteIfNeeded(s));let i=false,o=false,a=null,c=null,l=null,p=false;if(t.typeName){let u=t.typeName.names?.map(d=>d.String?.sval||d.String?.str).filter(Boolean);l=u&&(u.length===2&&u[0]==="pg_catalog"?u[1]:u[0]),i=!!(l&&Os(l))||this.serialColumns.has(t),p=!!(t.typeName.arrayBounds&&t.typeName.arrayBounds.length>0);let f=Array.isArray(t.typeName.typmods)?t.typeName.typmods:[],h=d=>f[d]?.A_Const?.ival?.ival??f[d]?.A_Const?.val?.ival?.ival;if(l&&Is(l)&&f.length>0){let d=h(0);typeof d=="number"&&d>0&&(a={maxLen:d});}if(l&&Ds(l)&&f.length>=2){let d=h(0),m=h(1);typeof d=="number"&&typeof m=="number"&&d>0&&m>=0&&(c={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);}r.push(this.TypeName(t.typeName,n));}if(t.constraints){let u=Array.isArray(t.constraints)?t.constraints:[],f=u.map(d=>this.visit(d,n));r.push(...f.filter(Boolean));let h=u.some(d=>d.Constraint?.contype==="CONSTR_CHECK");i&&o&&!h?r.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&&l){let u={isArray:p};a&&(u.lengthConstraint=a.maxLen),c&&(u.numericPrecision=c);let f=this.enums.get(l.toLowerCase());f&&(u.enumValues=f);let m=Mt({schema:"public",table:"",column:s,pgTypeName:l,nullable:true,defaultValue:null,defaultFn:null,isPrimaryKey:o,isUnique:false,isSerial:i},u).checkConstraint();m&&r.push(`CHECK (${m})`);}return r.join(" ")}Constraint(t,n){let r=t.contype;if(r==="CONSTR_IDENTITY"||r==="CONSTR_ATTR_DEFERRABLE"||r==="CONSTR_ATTR_NOT_DEFERRABLE"||r==="CONSTR_ATTR_DEFERRED"||r==="CONSTR_ATTR_IMMEDIATE")return "";if(r==="CONSTR_NULL")return "NULL";if(r==="CONSTR_NOTNULL")return "NOT NULL";if(r==="CONSTR_DEFAULT"&&t.raw_expr){let s=this.visit(t.raw_expr,n);return s.includes("(")&&!s.startsWith("(")?`DEFAULT (${s})`:`DEFAULT ${s}`}if(r==="CONSTR_CHECK"&&t.raw_expr){let s=[];t.conname&&s.push("CONSTRAINT",Ls(t.conname)),s.push("CHECK");let i=this.visit(t.raw_expr,n);return s.push(`(${i})`),s.join(" ")}if(r==="CONSTR_PRIMARY")return t.keys&&t.keys.length>0?`PRIMARY KEY (${It(t.keys).map(i=>this.visit(i,n)).join(", ")})`:"PRIMARY KEY";if(r==="CONSTR_UNIQUE")return t.keys&&t.keys.length>0?`UNIQUE (${It(t.keys).map(i=>this.visit(i,n)).join(", ")})`:"UNIQUE";if(r==="CONSTR_FOREIGN")return super.Constraint(t,n).replace(/FOREIGN\s+KEY\s+REFERENCES/gi,"REFERENCES");if(r==="CONSTR_GENERATED"&&t.raw_expr)return `GENERATED ALWAYS AS (${this.visit(t.raw_expr,n)}) STORED`;if(r==="CONSTR_EXCLUSION")throw new M({Constraint:t},"EXCLUSION constraints are not supported in SQLite");return ""}FuncCall(t,n){let s=(t.funcname||[]).map(l=>l.String?.sval||l.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 l=t.args[0];if((l?.A_Const?.sval?.sval||l?.String?.sval)==="epoch")return `strftime('%s', ${this.visit(t.args[1],n)})`}let a=(t.args??[]).map(l=>this.visit(l,n));if(t.agg_star)return `${i}(*)`;if(t.agg_distinct)return `${i}(DISTINCT ${a.join(", ")})`;let c=Ua(i,this.functionResolution);if(c){if(c.sqliteExpr!==null){let l=c.sqliteExpr;return l.includes("(")?l:`${l}(${a.join(", ")})`}if(c.jsFn!==null){let l=Bs[i];if(l?.sqlite){let p=l.sqlite();return p.includes("(")?p:`${p}(${a.join(", ")})`}}}throw new M({FuncCall:t},`Function call "${i}" not supported`)}SQLValueFunction(t,n){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 M({SQLValueFunction:t},`SQLValueFunction "${t.op}" not supported`)}}ResTarget(t,n){if(t.indirection&&t.indirection.length>0)throw new M({ResTarget:t},"Indirections are not supported in SQLite");let r=[];return n.update&&t.name?(r.push(this.quoteIfNeeded(t.name)),r.push("="),t.val&&r.push(this.deparse(t.val,n))):n.insertColumns&&t.name?r.push(this.quoteIfNeeded(t.name)):(t.val&&r.push(this.deparse(t.val,n)),t.name&&r.push(this.Alias({aliasname:t.name},n))),r.join(" ")}A_Expr(t,n){if(["AEXPR_OP_ALL","AEXPR_OP_ANY"].includes(t.kind))throw new M({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 M({A_Expr:t},"Schema-qualified OPERATOR() syntax is not supported in SQLite");let r=t.name[0]?.String?.sval||t.name[0]?.String?.str;if(r){if(!t.lexpr||!t.rexpr)throw new M({A_Expr:t},"A_Expr missing left or right expression");if(!wf.includes(r.toUpperCase()))throw new M({A_Expr:t},`Operator "${r}" is not supported in SQLite`);if(r==="~~"||r==="~~*"){let s=this.visit(t.lexpr,n),i=this.visit(t.rexpr,n);return `${s} LIKE ${i}`}if(r==="!~~"||r==="!~~*"){let s=this.visit(t.lexpr,n),i=this.visit(t.rexpr,n);return `${s} NOT LIKE ${i}`}if(r==="~"||r==="~*"){let s=this.visit(t.lexpr,n),i=this.visit(t.rexpr,n);return `${s} GLOB ${i}`}}}return super.A_Expr(t,n)}IndexStmt(t,n){let r=["CREATE"];t.unique&&r.push("UNIQUE"),r.push("INDEX"),t.if_not_exists&&r.push("IF NOT EXISTS"),t.idxname&&r.push(Ls(t.idxname)),r.push("ON"),t.relation&&r.push(this.RangeVar(t.relation,n));let s=(t.indexParams??[]).map(i=>"IndexElem"in i?this.IndexElem(i.IndexElem,n):this.visit(i,n)).filter(Boolean);return r.push(`(${s.join(", ")})`),r.join(" ")}IndexElem(t,n){let r=[];return t.name?r.push(Ls(t.name)):t.expr&&r.push(`(${this.visit(t.expr,n)})`),t.ordering==="SORTBY_ASC"&&r.push("ASC"),t.ordering==="SORTBY_DESC"&&r.push("DESC"),t.nulls_ordering==="SORTBY_NULLS_FIRST"&&r.push("NULLS FIRST"),t.nulls_ordering==="SORTBY_NULLS_LAST"&&r.push("NULLS LAST"),r.join(" ")}TypeCast(t,n){if(!t.arg||!t.typeName)return super.TypeCast(t,n);if([...this.helper.walk(t)].filter(({node:o})=>"A_Star"in o).length>0)throw new M({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(u=>u.String?.sval).filter(Boolean)??[],c=a.length===2&&a[0]==="pg_catalog"?a[1]:a[0],p=["text","varchar","character varying","char","bpchar","name","uuid"].includes(c?.toLowerCase());try{let u=this.parsePgArrayLiteral(o,p);return `'${JSON.stringify(u).replace(/'/g,"''")}'`}catch{}}}return this.visit(t.arg,n)}let s=this.visit(t.arg,n),i=this.TypeName(t.typeName,n);return `CAST(${s} AS ${i})`}A_ArrayExpr(t,n){let r=It(t.elements),s=this.tryExtractStaticArray(r);return s!==void 0?`'${JSON.stringify(s).replace(/'/g,"''")}'`:`json_array(${r.map(o=>this.visit(o,n)).join(", ")})`}tryExtractStaticArray(t){let n=[];for(let r of t)if("A_ArrayExpr"in r){let s=It(r.A_ArrayExpr.elements),i=this.tryExtractStaticArray(s);if(i===void 0)return;n.push(i);}else if("A_Const"in r){let s=r.A_Const;if(s.isnull)n.push(null);else if(s.ival)n.push(s.ival.ival);else if(s.fval)n.push(parseFloat(s.fval.fval));else if(s.sval)n.push(s.sval.sval);else if("boolval"in s)n.push(s.boolval.boolval===true);else return}else return;return n}parsePgArrayLiteral(t,n){if(!t.startsWith("{")||!t.endsWith("}"))throw new Error("Not a PG array literal");let r=t.slice(1,-1);if(r.length===0)return [];let s=[],i=0;for(;i<r.length;)if(r[i]==="{"){let o=0,a=i;for(;a<r.length;){if(r[a]==="{")o++;else if(r[a]==="}"&&(o--,o===0))break;a++;}s.push(this.parsePgArrayLiteral(r.slice(i,a+1),n)),i=a+1,r[i]===","&&i++;}else if(r[i]==='"'){let o=i+1,a="";for(;o<r.length&&r[o]!=='"';)r[o]==="\\"&&o++,a+=r[o],o++;s.push(a),i=o+1,r[i]===","&&i++;}else {let o=i;for(;o<r.length&&r[o]!==","&&r[o]!=="}";)o++;if(o===i)throw new Error("Malformed PG array literal");let a=r.slice(i,o);if(a==="NULL")s.push(null);else if(n)s.push(a);else {let c=Number(a);s.push(isNaN(c)?a:c);}i=o,r[i]===","&&i++;}return s}BetweenExpr(t,n){return super.A_Expr(t,n)}AlterTableStmt(t,n){let r=t.cmds??[],s=["AT_EnableRowSecurity","AT_ForceRowSecurity","AT_ChangeOwner"],i=r.filter(p=>"AlterTableCmd"in p&&!s.includes(p.AlterTableCmd.subtype));if(i.length===0)return "";if(!["OBJECT_TABLE","OBJECT_INDEX","OBJECT_VIEW"].includes(t.objtype))throw new M({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"],c=[],l=[];for(let p of i){let u=p.AlterTableCmd.subtype;if(o.includes(u)){let f={...t,cmds:[p]};c.push(super.AlterTableStmt(f,n));}else if(a.includes(u))l.push(p.AlterTableCmd);else throw new M({AlterTableStmt:t},`AlterTableCmd with subtype ${u} is not supported in SQLite`)}if(l.length>0){let p=this.getRelationName(t.relation);c.push(this.generateRebuildSql(p,l));}return c.join(`;
206
+ `)}AlterTableCmd(t,n){if(!["AT_AddColumn","AT_DropColumn"].includes(t.subtype))throw new M({AlterTableCmd:t},`AlterTableCmd with subtype ${t.subtype} is not supported`);return t.subtype==="AT_DropColumn"&&t.behavior?super.AlterTableCmd({...t,behavior:void 0},n):super.AlterTableCmd(t,n)}DefineStmt(t,n){if(t.kind==="OBJECT_AGGREGATE")throw new Error("AGGREGATE definitions are not supported in SQLite");return super.DefineStmt(t,n)}InsertStmt(t,n){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},n);if(s.some(i=>i.some(o=>o===true)))throw new M({InsertStmt:t},"Insert with partial DEFAULT values is not supported")}return super.InsertStmt(t,n)}SelectStmt(t,n){if(this.helper.hasUnsafeStar())throw new M({SelectStmt:t},"Row-wise comparison using .* is not supported in SQLite. Expand to explicit per-column comparisons instead.");if(t.intoClause)throw new M({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 M({SelectStmt:t},"DISTINCT ON clause is not supported in SQLite. Use window functions instead.")}if(t.limitOffset&&!t.limitCount)throw new M({SelectStmt:t},"OFFSET without LIMIT is not supported in SQLite");let r=super.SelectStmt(t,n);if(/^SELECT\s+FROM/.test(r))throw new M({SelectStmt:t},"SELECT without a target list is not supported in SQLite");return r}JoinExpr(t,n){return t.alias&&this.Alias(t.alias,n),super.JoinExpr(t,n)}A_Const(t,n){if(t.bsval!==void 0)throw new M({A_Const:t},"Bit string literals are not supported in SQLite");let r=super.A_Const(t,n);return typeof r=="string"&&r.startsWith("E'")?r.substring(2,r.length-1):r}SortBy(t,n){if(t.sortby_dir==="SORTBY_USING"){let r=It(t.useOp),s=r[0]?.String?.sval;if(r.length>1||!["<",">"].includes(s??""))throw new M({SortBy:t},"Only `USING <` or `USING >` are supported.");t.sortby_dir=s==="<"?"SORTBY_DESC":"SORTBY_ASC",t.useOp=void 0;}return super.SortBy(t,n)}RangeSubselect(t,n){if(t.lateral)throw new M({RangeSubselect:t},"LATERAL subqueries are not supported in SQLite");return super.RangeSubselect(t,n)}SubLink(t,n){if(["ANY_SUBLINK","ALL_SUBLINK"].includes(t.subLinkType))throw new M({SubLink:t},"ANY/ALL/SOME subqueries are not supported. Use NOT EXISTS or IN instead");if(t.subLinkType==="ARRAY_SUBLINK")throw new M({SubLink:t},"ARRAY subqueries are not supported in SQLite");return super.SubLink(t,n)}LockingClause(t,n){return ""}UpdateStmt(t,n){if(n.parentNodeTypes.includes("SelectStmt"))throw new M({UpdateStmt:t},"UPDATE ... FROM (SELECT ...) is not supported in SQLite");return super.UpdateStmt(t,n)}Alias(t,n){if(t.colnames&&t.colnames.length>0)throw new M({Alias:t},"Aliasing with column names is not supported in SQLite");return `AS "${t.aliasname}"`}CreateFunctionStmt(t,n){let r=t.options??[],s=t.returnType?.names?.map(l=>l.String?.sval).filter(Boolean).join("."),i=r.find(l=>l.DefElem?.defname==="language")?.DefElem?.arg?.String?.sval;if(s!=="trigger"||i!=="plpgsql")throw new M({CreateFunctionStmt:t},"Only trigger functions with LANGUAGE plpgsql are supported");let o=t.funcname?.map(l=>l.String?.sval).filter(Boolean).pop();if(!o)throw new Error("Function has no name");let a=r.find(l=>l.DefElem?.defname==="as")?.DefElem?.arg?.List?.items?.[0]?.String?.sval;if(!a)throw new Error("Function has no body");let c=this.plpgsqlParser.parse(a);return this.triggerFunctions.set(o,c),""}CreateTrigStmt(t,n){let r=t.trigname,s=this.RangeVar(t.relation,n),i=t.funcname?.map(u=>u.String?.sval).filter(Boolean).pop();if(!i)throw new Error(`Trigger "${r}" has no function reference`);let o=this.triggerFunctions.get(i);if(!o)throw new M({CreateTrigStmt:t},`Trigger "${r}" references unknown function "${i}"`);let a=t.timing===2?"BEFORE":t.timing===64?"INSTEAD OF":"AFTER",c=[];if(t.events&4&&c.push("INSERT"),t.events&8&&c.push("DELETE"),t.events&16)if(t.columns?.length){let u=t.columns.map(f=>f.String?.sval).filter(Boolean);c.push(`UPDATE OF ${u.join(", ")}`);}else c.push("UPDATE");let l=c.join(" OR "),p=this.buildTriggerBody(o,s,n);return [`CREATE TRIGGER ${r}`,`${a} ${l} ON ${s}`,"FOR EACH ROW","BEGIN",...p.map(u=>` ${u};`),"END"].join(`
207
+ `)}buildTriggerBody(t,n,r){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,n,r)),i.length=0),o.type==="dml"&&s.push(this.translateDml(o.sql,r));}return i.length>0&&s.push(this.buildAssignmentUpdate(i,n,r)),s}buildAssignmentUpdate(t,n,r){let s=t.map(i=>{let o=this.translateExpression(i.expression,r);return `${i.column} = ${o}`});return `UPDATE ${n} SET ${s.join(", ")} WHERE rowid = NEW.rowid`}translateExpression(t,n){try{let r=`SELECT ${t}`,s=t.trim().toLowerCase();return s==="now()"||s==="current_timestamp"?"datetime('now')":t}catch{return t}}flattenTriggerTableRef(t,n){let r=this.effectiveSchema(t);return r?this.schemaHandling==="prefix"?`${r}__${n}`:`"${r}.${n}"`:this.quoteBareIfNeeded(n)}translateDml(t,n){let r=/^(\s*)(insert\s+into|update|delete\s+from)\s+(?:"([^"]+)"|(\w+))\s*\.\s*(?:"([^"]+)"|(\w+))/i;return t=t.replace(r,(s,i,o,a,c,l,p)=>`${i}${o} ${this.flattenTriggerTableRef(a??c,l??p)}`),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,n){if(t.arg?.ColumnRef?.fields?.length>1)throw new M({NullTest:t},"row-level NULL tests are not supported in SQLite");return super.NullTest(t,n)}RenameStmt(t,n){if(!t.renameType)throw new Error("RenameStmt requires renameType");if(t.renameType==="OBJECT_POLICY")return "";let r=["OBJECT_TABLE","OBJECT_VIEW","OBJECT_COLUMN"];if(t.renameType==="OBJECT_COLUMN"&&(t.relationType==="OBJECT_FOREIGN_TABLE"||t.relationType==="OBJECT_VIEW"))throw new M({RenameStmt:t},`RenameStmt with relationType ${t.relationType} is not supported`);if(!r.includes(t.renameType))throw new M({RenameStmt:t},`RenameStmt with renameType ${t.renameType} is not supported in SQLite`);return super.RenameStmt(t,n)}DropStmt(t,n){let r=t.removeType;if(["OBJECT_TABLE","OBJECT_VIEW","OBJECT_INDEX","OBJECT_TRIGGER"].includes(r))return this.foldDropObjectSchemas(t),super.DropStmt(t,n);if(["OBJECT_POLICY"].includes(r))return "";throw new M({DropStmt:t},`DROP with removeType ${r} is not supported in SQLite`)}foldDropObjectSchemas(t){let n=t.removeType==="OBJECT_TRIGGER"?3:2;for(let r of t.objects??[]){let s=r?.List?.items;if(!Array.isArray(s)||s.length!==n)continue;let i=s[0]?.String?.sval,o=s[1]?.String?.sval;if(typeof i!="string"||typeof o!="string")continue;let a=this.effectiveSchema(i),c=a===void 0?o:this.schemaHandling==="prefix"?`${a}__${o}`:`${a}.${o}`;s.splice(0,2,{String:{sval:c}});}}generateRebuildSql(t,n){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 r=this.buildDesiredSchema(this.introspection,t,n),s=new wi,i=new Si,o=s.diff(this.introspection,r);return o.has_changes?i.plan(o,this.introspection,r).steps.filter(c=>!["disable_foreign_keys","begin_transaction","commit_transaction","enable_foreign_keys"].includes(c.type)).map(c=>c.sql).join(`
208
+ `):""}buildDesiredSchema(t,n,r){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 r){let o=s.columns.findIndex(a=>a.table===n&&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(c=>c.name===n);a!==-1&&(s.tables[a]={...s.tables[a],sql:s.tables[a].sql+" /* modified */"});break}}}return this.rebuildTableSql(s,n),s}rebuildTableSql(t,n){let r=t.tables.findIndex(u=>u.name===n);if(r===-1)return;let s=t.columns.filter(u=>u.table===n),i=t.foreign_keys.filter(u=>u.table===n),o=t.check_constraints.filter(u=>u.table===n),a=s.map(u=>{let f=`${U(u.name)} ${u.type||"TEXT"}`;return u.is_primary_key&&(f+=" PRIMARY KEY"),u.nullable||(f+=" NOT NULL"),u.default_value!=null&&(f+=` DEFAULT ${u.default_value}`),f}),c=i.map(u=>`FOREIGN KEY (${U(u.column)}) REFERENCES ${U(u.ref_table)}(${U(u.ref_column)}) ON UPDATE ${u.on_update} ON DELETE ${u.on_delete}`),l=o.map(u=>`CHECK (${u.expression})`),p=[...a,...c,...l];t.tables[r]={...t.tables[r],sql:`CREATE TABLE ${U(n)} (${p.join(", ")}) STRICT`};}extractTypeName(t){let n=t.def?.ColumnDef;return n?.typeName?.TypeName?(n.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 td(e){return `${e?.schemaname??"public"}.${e?.relname??""}`}function Sx(e){let t=e?.Constraint;if(!t||t.contype!=="CONSTR_DEFAULT")return false;let n=t.raw_expr?.FuncCall?.funcname;if(!Array.isArray(n))return false;let r=n.map(s=>s.String?.sval??s.String?.str).filter(Boolean);return r[r.length-1]?.toLowerCase()==="nextval"}function Ex(e){return (Array.isArray(e.constraints)?e.constraints:[]).some(n=>n.Constraint?.contype==="CONSTR_IDENTITY")}function nd(e,t){let n=Array.isArray(e.constraints)?e.constraints:[],r=n.filter(s=>!Sx(s));r.length!==n.length?(e.constraints=r,t.add(e)):Ex(e)&&t.add(e);}function xx(e,t,n){let r=t?.Constraint;if(!r)return false;let s=r.contype;if(s!=="CONSTR_PRIMARY"&&s!=="CONSTR_UNIQUE"&&s!=="CONSTR_FOREIGN")return false;let i=e.tableElts??[];return s==="CONSTR_PRIMARY"&&rd(e,r,n)||(i.push(t),e.tableElts=i),true}function rd(e,t,n){let r=(t.keys??[]).map(o=>o.String?.sval??o.String?.str).filter(Boolean);if(r.length!==1)return false;let s=(e.tableElts??[]).find(o=>"ColumnDef"in o&&o.ColumnDef.colname===r[0]);if(!s||!n.has(s.ColumnDef))return false;let i=Array.isArray(s.ColumnDef.constraints)?s.ColumnDef.constraints:[];return i.push({Constraint:{contype:"CONSTR_PRIMARY"}}),s.ColumnDef.constraints=i,true}function _x(e,t){let n=e.tableElts??[],r=n.filter(s=>{let i=s?.Constraint;return !i||i.contype!=="CONSTR_PRIMARY"?true:!rd(e,i,t)});r.length!==n.length&&(e.tableElts=r);}function sd(e){let t=new WeakSet,n=new Map;for(let r of e.stmts??[]){let s=r.stmt;if(!s||!("CreateStmt"in s))continue;let i=s.CreateStmt;n.set(td(i.relation),i);for(let o of i.tableElts??[])"ColumnDef"in o&&nd(o.ColumnDef,t);_x(i,t);}for(let r of e.stmts??[]){let s=r.stmt;if(!s||!("AlterTableStmt"in s))continue;let i=s.AlterTableStmt,o=n.get(td(i.relation)),a=i.cmds??[],c=[];for(let l of a){let p=l.AlterTableCmd;p?.subtype==="AT_AddColumn"&&p.def&&"ColumnDef"in p.def&&nd(p.def.ColumnDef,t),!(o&&p?.subtype==="AT_AddConstraint"&&p.def&&xx(o,p.def,t))&&c.push(l);}i.cmds=c;}return t}var id=b(()=>{});async function Cr(e,t={}){let n=await di(e);return {ast:n,...Tx(n,t)}}function Tx(e,t={}){let n=sd(e),r=Ga(e),s=Ka(e,r),i=Wa(e),o=za(e),a=Xa(e),c=new Ei(e,{...t,enums:r,serialColumns:n}),{policies:l,tables:p}=Va(e,{defaultSchema:t.defaultSchema,validateMutations:t.strict});if(t.strict)for(let u of l){if(!s.get(`${u.data.schema??"public"}.${u.data.table}`))throw new Error(`Policy "${u.data.name}" references unknown table "${u.data.table}"`);if(!p.has(u.data.table))throw new Error(`RLS is not enabled on table "${u.data.table}"`)}return {ddl:c.deparseQuery(),enums:r,rls:{tables:p,policies:l},schema:s,vars:i,tableConstraints:o,comments:a}}var xi=b(()=>{Xm();ed();id();_a();Ya();Ta();});async function od(e){if(e.trim())try{await di(e);}catch(t){let n=t instanceof Error?t.message:String(t);throw new Dc(`Declarative schema (schemas/*.sql) is not valid SQL: ${n}`,{cause:t})}}async function Ic(e,t,n,r){if(t.trim())try{let s=t;if(n==="postgres"){let i=await e.translateDdl(t);s=typeof i=="string"?i:i.ddl??"";}for(let i of vt(s))if(i.trim())try{await e.exec(i);}catch(o){if(!r)throw o}}catch(s){if(!r)throw s}}async function ad(e,t){if(!t.trim())return;let n=xe(e.connection);if(n==="pg")return;let r=n==="sqlite"?"sqlite":"postgres",s=await createConnection({url:":memory:",ddlDialect:r,translation:e.connection.config.translation});try{let i=e.connection.config.baseSchema;i&&await Ic(s,i,r,!0);for(let o of await Ie(e))await Ic(s,o.sql,r,!0);await Ic(s,t,r,!1);}finally{await s.close().catch(()=>{});}}var Dc,cd=b(()=>{xi();Rt();dt();mt();Dc=class extends Error{constructor(t,n){super(t,n),this.name="SchemaParseError";}};});var pd={};pe(pd,{checkPendingDeclarativeSchema:()=>ud,db:()=>Px});function Rx(){console.log(Q.default.yellow("Declarative diff includes potentially destructive changes.")),console.log(Q.default.dim("Review the schema manually and author an explicit migration for drops or other data-loss changes."));}async function ud(e,t){let n=await re(e);if(!n)return {hint:false,reason:"no-schemas"};try{let s=await e.connection.createMigrator(n).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(r){return {hint:false,reason:"diff-failed",error:r instanceof Error?r.message:String(r)}}}async function ld(e){let t=await st(e),n=await re(t);if(!n&&!t.connection.config.baseSchema){console.log(Q.default.dim("No schema files found."));return}let s=await t.connection.createMigrator(n).diff();if(typeof s.diff!="string"&&!s.diff.has_changes){console.log(Q.default.dim("Schema in sync."));return}ln(s);}async function kx(e,t){if(t?.trim())return t;if(!process.stdin.isTTY){let s=await Ur();if(s.trim())return s}let n=await re(e);if(n?.trim())return n;let r=await Jn(e);if(r?.trim())return r;throw new Error("No SQL provided and no declarative schemas or migrations found to deparse.")}var Q,vx,Px,fd=b(()=>{Q=V(z());Ne();oc();Fe();gr();dt();zm();Ee();Xe();_t();Ct();Rt();Ks();Fe();mt();cd();Ar();vx="Local Development:";Px=e=>{let t=e.command("db").description("Database operations").helpGroup(vx);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 n=>{console.log(),await Y(async()=>{if(await ee(n.config),!n.file){await ld(n.config);return}let r=await st(n.config),s=await re(r);if(!s.trim()){console.log(Q.default.dim("No declarative schemas found \u2014 nothing to diff."));return}await od(s);let i=xe(r.connection);if(i==="sqlite"){console.log(Q.default.yellow('`lite db diff -f` is not supported on the bare "sqlite" driver yet.')),console.log(Q.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 Jn(r);try{o=await Km(u,s,r.connection.config.baseSchema??"");}catch(f){throw f instanceof DataLossError?(Rx(),new Error("Declarative diff includes potentially destructive changes.")):f}if(o=o.filter(f=>f.trim()),o.length===0){console.log(Q.default.green("Schema in sync \u2014 no migration written."));return}}let a=o.join(`
209
+
210
+ `);try{await ad(r,a);}catch(u){km(u,{variant:i,failingSql:a});let f=u instanceof Error?u.message:String(u);throw new Error(`Generated migration does not run on the "${i}" backend and was not written: ${f}. This likely indicates a gap in supalite's Postgres\u2192SQLite translation; it has been reported.`)}let c=Oe__default.join(process.cwd(),"supabase",Ot(r));$e(c);let l=new Date,p=o.length>1;for(let[u,f]of o.entries()){let h=Ea(new Date(l.getTime()+u*1e3)),d=p?`${n.file}_${u+1}`:n.file,m=Oe__default.join(c,xa(d,h));await de__default.writeFile(m,f+`
211
+ `,{flag:"wx"}),console.log(Q.default.green(" \u279C"),"Wrote migration",Q.default.cyan(Oe__default.relative(process.cwd(),m)));}o.length>1&&console.log(Q.default.dim(`Split into ${o.length} files: pg-delta requires a COMMIT between them.`));});}),t.command("reset").description(me("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").option("--hard","Delete and recreate the local DB file/dir instead of dropping objects via SQL",false).action(async n=>{console.log(),await Y(async()=>{if(await ee(n.config),n.hard){let c=await Yr(n.config);if(c){await de__default.rm(c,{recursive:!0,force:!0});for(let l of ["-wal","-shm","-journal"])await de__default.rm(`${c}${l}`,{force:!0});console.log(Q.default.dim(` \u279C removed ${Oe__default.relative(process.cwd(),c)}`));}else console.log(Q.default.dim("--hard: no local database file to delete; resetting via SQL."));}let r=await st(n.config),s=r.connection.dialect==="postgres",i=[];if(s){let{rows:c}=await r.connection.exec(`SELECT nspname AS name FROM pg_namespace
212
+ WHERE nspname NOT LIKE 'pg\\_%' AND nspname <> 'information_schema'`);for(let l of c)i.push(`DROP SCHEMA IF EXISTS "${l.name.replace(/"/g,'""')}" CASCADE`);i.push("CREATE SCHEMA IF NOT EXISTS public AUTHORIZATION pg_database_owner");}else {let l=(await r.connection.introspect()).tables.filter(u=>u.type==="table"),p=(u,f)=>`"${u?`${u}.${f}`:f}"`;for(let u of l)i.push(`DROP TABLE IF EXISTS ${p(u.schema,u.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 c of i)try{await r.connection.exec(c);}catch{}await r.connection.clearSchemaCache(),await If(),await Vf();let o=await Ht(r,{persistWithDeclarative:!0});for(let c of o.applied)console.log(Q.default.green(" \u2713"),"Applied",Q.default.cyan(c.filename));let a=await ud(r,o.applied.length);a.hint?(console.log(),console.log(Q.default.yellow("Declarative schemas detected with pending changes.")),console.log(Q.default.dim("The reset database reflects the migrations only \u2014 schema changes that were never diffed, including RLS policies, are gone.")),console.log(Q.default.dim("Run `lite db diff -f <name>` to capture them as a migration, then re-run `lite db reset`."))):a.reason==="diff-failed"&&(console.error(),console.error(Q.default.yellow("Declarative schemas detected but could not be checked.")),a.error&&console.error(Q.default.dim(a.error)),console.error(Q.default.dim("The reset database and its RLS metadata reflect the migrations only \u2014 anything `supabase/schemas/*.sql` declares, policies included, may be missing.")),console.error(Q.default.dim("Fix the schema files, then `lite db diff -f <name>` and re-run `lite db reset`."))),n.seed!==!1&&await dr(r).catch(c=>console.error(Q.default.yellow("Seed warning: "+String(c)))),console.log(Q.default.green("Database reset."));});}),t.command("translate").description("Translate Postgres SQL to this project's backend dialect").argument("[sql]","SQL to translate; reads stdin if omitted").option("--config <config>","Path to the config file").option("--deparse",me("Emit the JSON deparse payload (RLS policies + session vars) instead of DDL, for edge/serverless runtimes")).option("-o, --out <file>","Write output to a file instead of stdout").action(async(n,r)=>{await Y(async()=>{await ee(r.config);let s=await st(r.config);try{if(r.deparse){let c=await kx(s,n),p=[s.connection.config.baseSchema??"",c].filter(d=>d.trim()).join(`
213
+
214
+ `),u=await s.connection.translateDdl(p),f=SqliteConnection.serializeDeparseInfo(u),h=JSON.stringify(f,null,2);r.out?(await de__default.writeFile(r.out,h+`
215
+ `,"utf8"),console.error(Q.default.green(" \u279C"),`Wrote ${f.rls.policies.length} policies to`,Q.default.cyan(Oe__default.relative(process.cwd(),Oe__default.resolve(r.out))))):console.log(h);return}let i=n??await Ur(),o=await s.connection.translateDdl(i),a=typeof o=="string"?o:o.ddl??"";console.log(a);}finally{await s.connection.close();}});}),t.command("query").description("Execute a SQL statement against the local or remote project").argument("[statement]","The statement to execute; reads stdin if omitted").option("--remote","Execute the statement on the remote project",false).option("--config <config>","Path to the config file").action(async(n,r)=>{await Y(async()=>{r.remote||await ee(r.config);let s=await st(r.remote?!0:r.config);try{if(n){Me(`Executing: ${Q.default.cyan(n)}`);let o=await s.connection.exec(n);console.log(o);return}let i=await Ur();for(let o of vt(i)){if(!o.trim())continue;let a=await s.connection.exec(o);console.log(a);}}finally{await s.connection.close();}});}),t.command("schema").description(me("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 n=>{console.log(),await Y(async()=>{if(await ee(n.config),n.diff){await ld(n.config);return}let s=await(await st(n.config)).connection.introspect();if(n.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(`;
216
+
217
+ `)+(i.length?";":""));return}Ff(s);});});};});var md={};pe(md,{migration:()=>Ox});var we,Lx,Ox,dd=b(()=>{we=V(z());dt();Ks();mt();Te();Ee();Lx="Local Development:",Ox=e=>{let t=e.command("migration").description("Manage database migrations").helpGroup(Lx);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(n,r)=>{await ee(r.config);let i=await(await W({withSupabaseClient:false})).project.local.createApp(r.config),o=await yf(i,n);console.log(we.default.green(" \u279C"),"Created",we.default.cyan(Oe__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 n=>{await ee(n.config);let s=await(await W({withSupabaseClient:false})).project.local.createApp(n.config);if(n.dryRun){await nn(s.connection);let i=new Set(await Bn(s.connection)),a=(await Ie(s)).filter(c=>!i.has(c.version));a.length===0&&(console.log(we.default.green("No pending migrations.")),process.exit(0)),console.log(we.default.dim("Pending:"));for(let c of a)console.log(" "+we.default.cyan(c.filename));process.exit(0);}try{let i=await Ht(s);if(i.applied.length===0)console.log(we.default.green("Local database is up to date."));else for(let o of i.applied)console.log(we.default.green(" \u2713"),"Applied",we.default.cyan(o.filename));}catch(i){console.error(we.default.red("Migration failed: "+String(i.message??i))),process.exit(1);}process.exit(0);}),t.command("list").description("List applied and pending migrations").option("--config <config>","Path to the config file").action(async n=>{await ee(n.config);let s=await(await W({withSupabaseClient:false})).project.local.createApp(n.config);await nn(s.connection);let i=new Set(await Bn(s.connection)),o=await Ie(s);console.log(we.default.dim(`Migrations in ${Ot(s)}:`)),o.length===0&&console.log(we.default.dim(" (none)"));for(let l of o){let p=i.has(l.version)?we.default.green("[applied]"):we.default.yellow("[pending]");console.log(` ${p} ${we.default.cyan(l.filename)}`);}let a=new Set(o.map(l=>l.version)),c=[...i].filter(l=>!a.has(l));if(c.length>0){console.log(),console.log(we.default.dim("Recorded versions without matching file:"));for(let l of c)console.log(` ${we.default.red("[orphan]")} ${l}`);}process.exit(0);});};});function Dx(e){let t=(e??process.env.SUPABASE_ENDPOINT??Ix).replace(/\/+$/,""),n=new URL(t),r=n.host;return {apiUrl:`${n.protocol}//${r.startsWith("api.")?r:`api.${r}`}`,projectDomain:r==="supabase.com"?"supabase.co":r}}function hd(e){if(Array.isArray(e)){let t=e.find(r=>r.name==="anon")?.api_key??"",n=e.find(r=>r.name==="service_role")?.api_key??"";return {anon:t,service_role:n}}return e}var Ix,Ti,gd=b(()=>{Ix="https://supabase.com";Ti=class{constructor(t,n){this.token=t;if(!t)throw new Error("Supabase access token required");let r=Dx(n?.endpoint);this.apiUrl=r.apiUrl,this.projectDomain=r.projectDomain;}apiUrl;projectDomain;async request(t,n,r){let s=await fetch(`${this.apiUrl}${n}`,{method:t,headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json",Accept:"application/json"},body:r===void 0?void 0:JSON.stringify(r)});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Supabase API ${t} ${n} 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,n){return this.request("PATCH",`/v1/projects/${t}/config/auth`,n)}createSigningKey(t,n){return this.request("POST",`/v1/projects/${t}/config/auth/signing-keys`,n)}runSql(t,n){return this.request("POST",`/v1/projects/${t}/database/query`,{query:n})}async waitForActive(t,n={}){let r=n.timeoutMs??6e5,s=n.intervalMs??5e3,i=Date.now();for(;;){let o=await this.getProject(t);if(n.onTick?.(o.status),o.status==="ACTIVE_HEALTHY")return o;if(Date.now()-i>r)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 Fx(e){if(e==null||typeof e!="string")return true;try{return JSON.parse(e),!0}catch{return false}}function Ux(e){return e==null?true:typeof e!="string"?false:jx.test(e)}function Mx(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 yd(e){if(!e)return;let t=e.match(/varchar\s*\(\s*(\d+)\s*\)/i);return t?Number(t[1]):void 0}function bd(e){return e?/jsonb?/i.test(e):false}function wd(e){return e?/\buuid\b/i.test(e):false}function Sd(e){return e?/timestamp(tz)?|timestamp with|timestamp without/i.test(e):false}async function Ed(e){let t=await e.connection.introspect(),n=[],r=e.connection.dialect;for(let s of t.tables){let i=s.name,o=s.schema,a=r==="sqlite"&&o&&o!=="main"?`"${o}.${i}"`:o?`"${o}"."${i}"`:`"${i}"`,c=t.columns.filter(h=>h.table===i&&(h.schema??o)===o),l=0,p=[];try{let h=await e.connection.exec(`SELECT COUNT(*) as c FROM ${a}`);l=Number(h?.rows?.[0]?.c??0);}catch{n.push({table:i,schema:o,rowCount:0,issues:p});continue}if(l===0){n.push({table:i,schema:o,rowCount:l,issues:p});continue}let u=c.filter(h=>bd(h.type)||wd(h.type)||Sd(h.type)||yd(h.type)!==void 0);if(u.length===0){n.push({table:i,schema:o,rowCount:l,issues:p});continue}let f=u.map(h=>`"${h.name}"`).join(", ");try{let d=(await e.connection.exec(`SELECT ${f} FROM ${a}`))?.rows??[];for(let m of d)for(let y of u){let g=m[y.name];if(bd(y.type)&&!Fx(g)){p.push({table:i,column:y.name,kind:"invalid_json",message:`row contains non-parseable JSON in ${i}.${y.name}`});continue}if(wd(y.type)&&g!=null&&!Ux(g)){p.push({table:i,column:y.name,kind:"invalid_uuid",message:`row contains invalid UUID in ${i}.${y.name}`});continue}if(Sd(y.type)&&!Mx(g)){p.push({table:i,column:y.name,kind:"invalid_timestamp",message:`row contains unparseable timestamp in ${i}.${y.name}`});continue}let E=yd(y.type);E!==void 0&&typeof g=="string"&&g.length>E&&p.push({table:i,column:y.name,kind:"varchar_overflow",message:`value exceeds varchar(${E}) in ${i}.${y.name}`});}}catch{}n.push({table:i,schema:o,rowCount:l,issues:p});}return n}var jx,xd=b(()=>{jx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;});function Et(e){let t=[],n="",r=0,s=false,i=false,o=false,a=false,c=null;for(;r<e.length;){let p=e[r],u=e[r+1];if(o){n+=p,p===`
218
+ `&&(o=false),r++;continue}if(a){if(n+=p,p==="*"&&u==="/"){n+=u,r+=2,a=false;continue}r++;continue}if(c){if(n+=p,p==="$"&&e.startsWith(c,r)){n+=e.slice(r+1,r+c.length),r+=c.length,c=null;continue}r++;continue}if(s){if(n+=p,p==="'"&&u==="'"){n+=u,r+=2;continue}p==="'"&&(s=false),r++;continue}if(i){if(n+=p,p==='"'&&u==='"'){n+=u,r+=2;continue}p==='"'&&(i=false),r++;continue}if(p==="-"&&u==="-"){o=true,n+=p,r++;continue}if(p==="/"&&u==="*"){a=true,n+=p,r++;continue}if(p==="'"){s=true,n+=p,r++;continue}if(p==='"'){i=true,n+=p,r++;continue}if(p==="$"){let f=e.slice(r).match(/^\$[A-Za-z0-9_]*\$/);if(f){c=f[0],n+=f[0],r+=f[0].length;continue}}if(p===";"){let f=n.trim();f&&t.push(f),n="",r++;continue}n+=p,r++;}let l=n.trim();return l&&t.push(l),t}var $i=b(()=>{});async function Ai(e,t){let r=e.connection.dialect==="sqlite"?`"auth.${t}"`:`auth."${t}"`;try{let s=await e.connection.exec(`SELECT COUNT(*) as c FROM ${r}`);return Number(s?.rows?.[0]?.c??0)}catch{return 0}}async function _d(e){let t=[],n=[],r=false;try{await e.connection.exec("SELECT 1"),r=!0;}catch(c){t.push(`Database not reachable: ${String(c)}`);}let s=await re(e),i=Et(s);i.length===0&&t.push("No schema statements found in supabase/schemas/*.sql");let o=[];if(r)try{o=await Ed(e);}catch(c){n.push(`Data validation skipped: ${String(c)}`);}for(let c of o)for(let l of c.issues)n.push(`${l.kind}: ${l.message}`);let a={users:0,sessions:0,refresh_tokens:0,identities:0,jwt_secret_set:!!e.config.auth?.jwt_secret};return r&&(a.users=await Ai(e,"users"),a.sessions=await Ai(e,"sessions"),a.refresh_tokens=await Ai(e,"refresh_tokens"),a.identities=await Ai(e,"identities")),a.jwt_secret_set||n.push("auth.jwt_secret is not configured \u2014 tokens will not survive upgrade"),e.config.storage?.enabled&&n.push("Storage is enabled but migration is not yet supported"),e.config.realtime?.enabled&&n.push("Realtime config migration is not yet supported"),{ok:t.length===0,errors:t,warnings:n,dbReachable:r,schemaStatementCount:i.length,schemaBytes:s.length,tables:o,auth:a}}var Td=b(()=>{Fe();xd();$i();});var jc,$d=b(()=>{jc=`-- supabase/auth core schema (Postgres)
211
219
  -- Scope: Core Authentication + User Management
212
220
  -- Source: GoTrue migrations + runtime analysis
213
221
 
@@ -375,6 +383,36 @@ CREATE TABLE IF NOT EXISTS auth.identities (
375
383
  CREATE INDEX IF NOT EXISTS identities_user_id_idx ON auth.identities (user_id);
376
384
  CREATE INDEX IF NOT EXISTS identities_email_idx ON auth.identities (email);
377
385
 
386
+ -- ============================================================
387
+ -- FLOW STATE (OAuth / PKCE)
388
+ -- ============================================================
389
+
390
+ CREATE TABLE IF NOT EXISTS auth.flow_state (
391
+ id uuid PRIMARY KEY, -- app-generated UUID
392
+ user_id uuid,
393
+ auth_code text,
394
+ authentication_method text NOT NULL,
395
+ code_challenge_method text CHECK (code_challenge_method IN ('s256', 'plain')),
396
+ code_challenge text,
397
+ provider_type text NOT NULL,
398
+ provider_access_token text,
399
+ provider_refresh_token text,
400
+ auth_code_issued_at timestamptz,
401
+ invite_token text,
402
+ referrer text,
403
+ oauth_client_state_id uuid,
404
+ linking_target_id uuid,
405
+ email_optional boolean NOT NULL DEFAULT false,
406
+ created_at timestamptz DEFAULT now(),
407
+ updated_at timestamptz DEFAULT now()
408
+ );
409
+
410
+ CREATE INDEX IF NOT EXISTS idx_auth_code ON auth.flow_state (auth_code);
411
+ CREATE INDEX IF NOT EXISTS idx_user_id_auth_method ON auth.flow_state (user_id, authentication_method);
412
+ -- Supports the opportunistic cleanup of abandoned flows on /authorize
413
+ -- (GoTrue prunes flow_state by created_at in internal/models/cleanup.go).
414
+ CREATE INDEX IF NOT EXISTS flow_state_created_at_idx ON auth.flow_state (created_at);
415
+
378
416
  -- ============================================================
379
417
  -- AUDIT LOG
380
418
  -- ============================================================
@@ -385,14 +423,14 @@ CREATE TABLE IF NOT EXISTS auth.audit_log_entries (
385
423
  created_at timestamptz DEFAULT now(),
386
424
  ip_address varchar(64) DEFAULT ''
387
425
  );
388
- `;});function sd(e=true){return e?dc(Tl):Tl}var id=b(()=>{Ct();nd();});function ux(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 `${od(s)}::jsonb`}return typeof e=="number"?Number.isFinite(e)?String(e):"NULL":typeof e=="boolean"?e?"true":"false":od(String(e))}function od(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=cx[r];for(let o of ox){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]),p=ax[o],u=lx[o];for(let f of l){let h={...f};if(r==="supabase"&&o==="users"){let g=h.confirmed_at;g!=null&&h.email_confirmed_at==null&&(h.email_confirmed_at=g);}let d=Object.keys(h).filter(g=>!c.has(g)),m=d.map(g=>ux(h[g],g,p,u)),y=`INSERT INTO auth.${o} (${d.map(g=>`"${g}"`).join(", ")}) VALUES (${m.join(", ")}) ON CONFLICT DO NOTHING`;n[o].push(y);}}return n}var ix,ox,ax,lx,cx,vl=b(()=>{ix=["users","sessions","identities","refresh_tokens"],ox=ix,ax={users:["raw_app_meta_data","raw_user_meta_data"],sessions:[],identities:["identity_data"],refresh_tokens:[]},lx={users:["is_sso_user","is_anonymous"],sessions:[],identities:[],refresh_tokens:["revoked"]},cx={supabase:{users:["confirmed_at"],sessions:[],identities:["email"],refresh_tokens:["id"]},local:{users:["confirmed_at"],sessions:[],identities:["email"],refresh_tokens:[]}};});function Ti(e){return !e||e==="main"||e==="public"?"public":e}function Rn(e,t){return `${Ti(e)}.${t}`}function fx(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 p=n.get(c);p&&(p.delete(l),p.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 ld(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=>ld(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 `${wr(n)}${s}`}return e instanceof Date?wr(e.toISOString()):typeof e=="object"?`${wr(JSON.stringify(e))}::jsonb`:wr(String(e))}function wr(e){return `'${e.replace(/'/g,"''")}'`}function Cl(e){return `"${e.replace(/"/g,'""')}"`}function mx(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 ad.has(r)||ad.has(n)}function dx(e,t,r){let n=`${Cl(e)}.${Cl(t)}`;return `SELECT setval(pg_get_serial_sequence(${wr(n)}, ${wr(r)}), COALESCE((SELECT MAX(${Cl(r)}) FROM ${n}), 1));`}async function hx(e){let t=e.connection.config?.translation?.deparse?.schema;if(t instanceof Map&&t.size>0)return t;let r=await ge(e);return r.trim()?(await Cn(r)).schema:new Map}async function vi(e){let t=await e.connection.introspect(),r=e.connection.dialect,n=await hx(e),s=fx(t.tables.filter(o=>!px.has(Ti(o.schema))),t.foreign_keys),i=[];for(let o of s){let a=Ti(o.schema),l=r==="sqlite"?a==="public"?`"${o.name}"`:`"${a}.${o.name}"`:`"${a}"."${o.name}"`,p=t.columns.filter(E=>E.table===o.name&&Ti(E.schema)===a).filter(E=>!E.generated&&!E.is_generated),u=[];try{u=(await e.connection.exec(`SELECT * FROM ${l}`))?.rows??[];}catch{continue}if(u.length===0)continue;let f=n.get(Rn(a,o.name)),h=typeof e.connection.deserializeRow=="function"?e.connection.deserializeRow.bind(e.connection):E=>E;u=u.map(E=>{let v=f?f.deserializeRow(E):E;return h(v)});let d=p.map(E=>E.name),m=new Map(p.map(E=>[E.name,E.pg_type??E.type])),y=[];for(let E of u){let v=d.map(T=>ld(E[T],m.get(T)));y.push(`INSERT INTO "${a}"."${o.name}" (${d.map(T=>`"${T}"`).join(", ")}) VALUES (${v.join(", ")}) ON CONFLICT DO NOTHING`);}let g=p.filter(mx).map(E=>dx(a,o.name,E.name));i.push({schema:a,table:o.name,inserts:y,sequenceResets:g});}return i}var px,ad,Al=b(()=>{yi();Je();px=new Set(["auth","storage","realtime","supabase_functions","graphql","graphql_public","extensions","pgsodium","pgsodium_masks","vault","information_schema","pg_catalog","pg_toast"]),ad=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]);});async function cd(e){let{PGlite:t}=await He("@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=Et(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=Et(sd());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 ge(e),p=Et(c);i=p.length;for(let d=0;d<p.length;d++)try{await r.exec(p[d]);}catch(m){return n.push({phase:"schema",label:`schema ${d+1}/${p.length}`,statement:p[d],error:String(m)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:n}}let u=await $i(e,{target:"local"}),f=["users","sessions","identities","refresh_tokens"];for(let d of f){let m=u[d];for(let y=0;y<m.length;y++){o++;try{await r.exec(m[y]);}catch(g){n.push({phase:"auth",label:`auth.${d} row ${y+1}/${m.length}`,statement:m[y],error:String(g)});}}}let h=await vi(e);for(let d of h){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 ud=b(()=>{sr();Je();id();bn();xi();vl();Al();});function pd(e){if(console.log(P.default.bold("Readiness Report")),console.log(` db reachable: ${e.dbReachable?P.default.green("yes"):P.default.red("no")} schema statements: ${P.default.cyan(e.schemaStatementCount)} schema bytes: ${P.default.cyan(e.schemaBytes)}`),console.log(` auth \u2014 users: ${P.default.cyan(e.auth.users)} sessions: ${P.default.cyan(e.auth.sessions)} identities: ${P.default.cyan(e.auth.identities)} refresh_tokens: ${P.default.cyan(e.auth.refresh_tokens)} jwt_secret: ${e.auth.jwt_secret_set?P.default.green("set"):P.default.yellow("unset")}`),e.tables.length>0){console.log(P.default.dim(" tables:"));for(let t of e.tables){let r=t.issues.length>0?P.default.yellow(` (${t.issues.length} issues)`):"",n=t.schema?`${t.schema}.`:"";console.log(` ${n}${t.table}: ${P.default.cyan(t.rowCount)} rows${r}`);}}if(e.errors.length>0){console.log(P.default.red("Errors:"));for(let t of e.errors)console.log(` ${P.default.red("\u2717")} ${t}`);}if(e.warnings.length>0){console.log(P.default.yellow("Warnings:"));for(let t of e.warnings)console.log(` ${P.default.yellow("!")} ${t}`);}console.log(),console.log(e.ok?P.default.green("Ready to upgrade."):P.default.red("Not ready."));}function fd(e){if(console.log(),console.log(P.default.bold("Rehearsal (in-memory pglite)")),console.log(` auth schema: ${P.default.cyan(e.baseSchemaStatements)} stmts user schema: ${P.default.cyan(e.schemaStatements)} stmts auth: ${P.default.cyan(e.authInserts)} inserts data: ${P.default.cyan(e.dataInserts)} inserts`),e.failures.length>0){console.log(P.default.red(` ${e.failures.length} failure(s):`));for(let t of e.failures)console.log(P.default.red(` \u2717 [${t.phase}] ${t.label}`)),console.log(P.default.dim(` ${t.statement}`)),console.log(P.default.dim(` ${t.error}`));}console.log(e.ok?P.default.green(" rehearsal passed"):P.default.red(" rehearsal failed"));}function md(e){console.log(),console.log(P.default.bold("SQLite Shim Audit")),console.log(` fields: ${P.default.cyan(e.summary.total)} passed: ${P.default.green(String(e.summary.passed))} warned: ${P.default.yellow(String(e.summary.warned))} failed: ${P.default.red(String(e.summary.failed))}`),e.results.length===0&&console.log(P.default.dim(" no shim-backed fields found"));for(let t of e.results.filter(r=>r.status!=="pass")){let r=t.status==="fail"?P.default.red:P.default.yellow;if(console.log(` ${r(t.status)} ${t.field} (${t.pg_type}) rows: ${P.default.cyan(t.rows_checked)} affected: ${P.default.cyan(t.affected_rows??0)}`),t.message&&console.log(` ${t.message}`),t.samples?.length)for(let n of t.samples)console.log(P.default.dim(` sample ${JSON.stringify(n.id)} raw=${JSON.stringify(n.raw_value)}`));t.action&&console.log(P.default.dim(` action: ${t.action}`));}console.log(e.summary.upgrade_safe?P.default.green(" shim audit passed"):P.default.red(" shim audit failed"));}function Rl(e){if(console.log(),console.log(P.default.bold(P.default.green("Upgrade complete."))),console.log(),console.log(` ${P.default.bold("Project URL:")} ${P.default.cyan(e.projectUrl)}`),console.log(` ${P.default.bold("API URL:")} ${P.default.cyan(e.apiUrl)}`),e.studioUrl&&console.log(` ${P.default.bold("Studio URL:")} ${P.default.cyan(e.studioUrl)}`),console.log(` ${P.default.bold("Ref:")} ${P.default.cyan(e.projectRef)}`),console.log(),console.log(` ${P.default.bold("anon key:")} ${e.anonKey}`),console.log(` ${P.default.bold("service_role key:")} ${e.serviceRoleKey}`),console.log(` ${P.default.bold("db password:")} ${e.dbPassword}`),console.log(),console.log(` migrated auth \u2014 users: ${P.default.cyan(e.auth.users)} sessions: ${P.default.cyan(e.auth.sessions)} identities: ${P.default.cyan(e.auth.identities)} refresh_tokens: ${P.default.cyan(e.auth.refresh_tokens)}`),console.log(` jwt secret: ${e.jwtMigrated?P.default.green("migrated"):P.default.yellow("not migrated \u2014 users must re-authenticate")}`),e.warnings.length>0){console.log(),console.log(P.default.yellow("Warnings:"));for(let t of e.warnings)console.log(` ${P.default.yellow("!")} ${t}`);}console.log(),console.log(P.default.bold("Update your supabase-js client:")),console.log(` url: ${P.default.cyan(e.apiUrl)}`),console.log(` anonKey: ${P.default.cyan(e.anonKey)}`),console.log();}var P,dd=b(()=>{P=te(ae());});function hd(e){return {kty:"oct",alg:"HS256",k:Buffer$1.from(e,"utf8").toString("base64url")}}var gd=b(()=>{No();});async function yd(e){let t=e.trim();if(!t)return "";let{PGlite:r}=await He("@supabase/lite/pglite","pglite","@electric-sql/pglite"),n=new r;try{return await n.exec(wt(bt(t))),await n.exec(Bs),await yx(n,t)}finally{await n.close().catch(()=>{});}}async function yx(e,t){return t?(await e.exec(t),await wx(e)):""}async function wx(e){let t=await e.query(`
426
+ `;});function Ad(e=true){return e?kl(jc):jc}var Cd=b(()=>{Rt();$d();});function Kx(e,t,n,r){if(e==null)return "NULL";if(r.includes(t))return e===true||e===1||e==="1"||e==="true"?"true":"false";if(n.includes(t)){let s=typeof e=="string"?e:JSON.stringify(e);return `${vd(s)}::jsonb`}return typeof e=="number"?Number.isFinite(e)?String(e):"NULL":typeof e=="boolean"?e?"true":"false":vd(String(e))}function vd(e){return `'${e.replace(/'/g,"''")}'`}async function Ci(e,t={}){let n=t.target??"supabase",r={users:[],sessions:[],identities:[],refresh_tokens:[]},s=e.connection.dialect,i=Vx[n];for(let o of Hx){let a=s==="sqlite"?`"auth.${o}"`:`auth."${o}"`,c=[];try{c=(await e.connection.exec(`SELECT * FROM ${a}`))?.rows??[];}catch{continue}if(c.length===0)continue;let l=new Set(i[o]),p=Gx[o],u=Wx[o];for(let f of c){let h={...f};if(n==="supabase"&&o==="users"){let g=h.confirmed_at;g!=null&&h.email_confirmed_at==null&&(h.email_confirmed_at=g);}let d=Object.keys(h).filter(g=>!l.has(g)),m=d.map(g=>Kx(h[g],g,p,u)),y=`INSERT INTO auth.${o} (${d.map(g=>`"${g}"`).join(", ")}) VALUES (${m.join(", ")}) ON CONFLICT DO NOTHING`;r[o].push(y);}}return r}var qx,Hx,Gx,Wx,Vx,Fc=b(()=>{qx=["users","sessions","identities","refresh_tokens"],Hx=qx,Gx={users:["raw_app_meta_data","raw_user_meta_data"],sessions:[],identities:["identity_data"],refresh_tokens:[]},Wx={users:["is_sso_user","is_anonymous"],sessions:[],identities:[],refresh_tokens:["revoked"]},Vx={supabase:{users:["confirmed_at"],sessions:[],identities:["email"],refresh_tokens:["id"]},local:{users:["confirmed_at"],sessions:[],identities:["email"],refresh_tokens:[]}};});function vi(e){return !e||e==="main"||e==="public"?"public":e}function vr(e,t){return `${vi(e)}.${t}`}function Xx(e,t){let n=new Map(e.map(a=>[vr(a.schema,a.name),a])),r=new Map,s=new Map;for(let a of n.keys())r.set(a,new Set),s.set(a,new Set);for(let a of t){let c=vr(a.schema,a.table),l=vr(a.ref_schema??a.schema,a.ref_table);!r.has(c)||!r.has(l)||(r.get(c).add(l),s.get(l).add(c));}let i=[...r.entries()].filter(([,a])=>a.size===0).map(([a])=>a),o=[];for(let a=0;a<i.length;a++){let c=i[a];o.push(c);for(let l of s.get(c)??[]){let p=r.get(l);p&&(p.delete(c),p.size===0&&i.push(l));}}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 c of e){let l=vr(c.schema,c.name);a.has(l)||o.push(l);}}return o.map(a=>n.get(a)).filter(Boolean)}function kd(e,t){if(e==null)return "NULL";let n=(t??"").toLowerCase();if(Array.isArray(e)&&n.endsWith("[]")){let r=t?.slice(0,-2);return `ARRAY[${e.map(s=>kd(s,r)).join(", ")}]::${t}`}if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return Number.isFinite(e)?String(e):"NULL";if(n.includes("bool")&&(e===0||e===1||e==="0"||e==="1"))return e===1||e==="1"?"true":"false";if(n.includes("json")){let r=typeof e=="string"?e:JSON.stringify(e),s=n.includes("jsonb")?"::jsonb":"::json";return `${bn(r)}${s}`}return e instanceof Date?bn(e.toISOString()):typeof e=="object"?`${bn(JSON.stringify(e))}::jsonb`:bn(String(e))}function bn(e){return `'${e.replace(/'/g,"''")}'`}function Uc(e){return `"${e.replace(/"/g,'""')}"`}function Jx(e){let t=e.default_value??e.default;if(typeof t=="string"&&t.trim().toLowerCase().startsWith("nextval("))return true;let n=typeof e.type=="string"?e.type.toLowerCase():"",r=typeof e.pg_type=="string"?e.pg_type.toLowerCase():"";return Rd.has(n)||Rd.has(r)}function Yx(e,t,n){let r=`${Uc(e)}.${Uc(t)}`;return `SELECT setval(pg_get_serial_sequence(${bn(r)}, ${bn(n)}), COALESCE((SELECT MAX(${Uc(n)}) FROM ${r}), 1));`}async function Qx(e){let t=e.connection.config?.translation?.deparse?.schema;if(t instanceof Map&&t.size>0)return t;let n=await re(e);return n.trim()?(await Cr(n)).schema:new Map}async function Ri(e){let t=await e.connection.introspect(),n=e.connection.dialect,r=await Qx(e),s=Xx(t.tables.filter(o=>!zx.has(vi(o.schema))),t.foreign_keys),i=[];for(let o of s){let a=vi(o.schema),c=n==="sqlite"?a==="public"?`"${o.name}"`:`"${a}.${o.name}"`:`"${a}"."${o.name}"`,p=t.columns.filter(E=>E.table===o.name&&vi(E.schema)===a).filter(E=>!E.generated&&!E.is_generated),u=[];try{u=(await e.connection.exec(`SELECT * FROM ${c}`))?.rows??[];}catch{continue}if(u.length===0)continue;let f=r.get(vr(a,o.name)),h=typeof e.connection.deserializeRow=="function"?e.connection.deserializeRow.bind(e.connection):E=>E;u=u.map(E=>{let A=f?f.deserializeRow(E):E;return h(A)});let d=p.map(E=>E.name),m=new Map(p.map(E=>[E.name,E.pg_type??E.type])),y=[];for(let E of u){let A=d.map($=>kd(E[$],m.get($)));y.push(`INSERT INTO "${a}"."${o.name}" (${d.map($=>`"${$}"`).join(", ")}) VALUES (${A.join(", ")}) ON CONFLICT DO NOTHING`);}let g=p.filter(Jx).map(E=>Yx(a,o.name,E.name));i.push({schema:a,table:o.name,inserts:y,sequenceResets:g});}return i}var zx,Rd,Mc=b(()=>{xi();Fe();zx=new Set(["auth","storage","realtime","supabase_functions","graphql","graphql_public","extensions","pgsodium","pgsodium_masks","vault","information_schema","pg_catalog","pg_toast"]),Rd=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]);});async function Pd(e){let{PGlite:t}=await qe("@supabase/lite/pglite","pglite","@electric-sql/pglite"),n=new t,r=[],s=0,i=0,o=0,a=0;try{for(let d of ["anon","authenticated","service_role","supabase_auth_admin"])await n.exec(`CREATE ROLE ${d}`);let c=Et(Ws);for(let d=0;d<c.length;d++)try{await n.exec(c[d]);}catch(m){return r.push({phase:"schema",label:`auth helpers ${d+1}/${c.length}`,statement:c[d],error:String(m)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:r}}if(e.config.auth?.enabled!==!1){let d=Et(Ad());s=d.length;for(let m=0;m<d.length;m++)try{await n.exec(d[m]);}catch(y){return r.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:r}}}let l=await re(e),p=Et(l);i=p.length;for(let d=0;d<p.length;d++)try{await n.exec(p[d]);}catch(m){return r.push({phase:"schema",label:`schema ${d+1}/${p.length}`,statement:p[d],error:String(m)}),{ok:!1,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:r}}let u=await Ci(e,{target:"local"}),f=["users","sessions","identities","refresh_tokens"];for(let d of f){let m=u[d];for(let y=0;y<m.length;y++){o++;try{await n.exec(m[y]);}catch(g){r.push({phase:"auth",label:`auth.${d} row ${y+1}/${m.length}`,statement:m[y],error:String(g)});}}}let h=await Ri(e);for(let d of h){for(let m=0;m<d.inserts.length;m++){a++;try{await n.exec(d.inserts[m]);}catch(y){r.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 n.exec(d.sequenceResets[m]);}catch(y){r.push({phase:"data",label:`${d.schema}.${d.table} sequence reset ${m+1}/${d.sequenceResets.length}`,statement:d.sequenceResets[m],error:String(y)});}}}finally{await n.close().catch(()=>{});}return {ok:r.length===0,baseSchemaStatements:s,schemaStatements:i,authInserts:o,dataInserts:a,failures:r}}var Nd=b(()=>{tn();Fe();Cd();yr();$i();Fc();Mc();});function Ld(e){if(console.log(L.default.bold("Readiness Report")),console.log(` db reachable: ${e.dbReachable?L.default.green("yes"):L.default.red("no")} schema statements: ${L.default.cyan(e.schemaStatementCount)} schema bytes: ${L.default.cyan(e.schemaBytes)}`),console.log(` auth \u2014 users: ${L.default.cyan(e.auth.users)} sessions: ${L.default.cyan(e.auth.sessions)} identities: ${L.default.cyan(e.auth.identities)} refresh_tokens: ${L.default.cyan(e.auth.refresh_tokens)} jwt_secret: ${e.auth.jwt_secret_set?L.default.green("set"):L.default.yellow("unset")}`),e.tables.length>0){console.log(L.default.dim(" tables:"));for(let t of e.tables){let n=t.issues.length>0?L.default.yellow(` (${t.issues.length} issues)`):"",r=t.schema?`${t.schema}.`:"";console.log(` ${r}${t.table}: ${L.default.cyan(t.rowCount)} rows${n}`);}}if(e.errors.length>0){console.log(L.default.red("Errors:"));for(let t of e.errors)console.log(` ${L.default.red("\u2717")} ${t}`);}if(e.warnings.length>0){console.log(L.default.yellow("Warnings:"));for(let t of e.warnings)console.log(` ${L.default.yellow("!")} ${t}`);}console.log(),console.log(e.ok?L.default.green("Ready to upgrade."):L.default.red("Not ready."));}function Od(e){if(console.log(),console.log(L.default.bold("Rehearsal (in-memory pglite)")),console.log(` auth schema: ${L.default.cyan(e.baseSchemaStatements)} stmts user schema: ${L.default.cyan(e.schemaStatements)} stmts auth: ${L.default.cyan(e.authInserts)} inserts data: ${L.default.cyan(e.dataInserts)} inserts`),e.failures.length>0){console.log(L.default.red(` ${e.failures.length} failure(s):`));for(let t of e.failures)console.log(L.default.red(` \u2717 [${t.phase}] ${t.label}`)),console.log(L.default.dim(` ${t.statement}`)),console.log(L.default.dim(` ${t.error}`));}console.log(e.ok?L.default.green(" rehearsal passed"):L.default.red(" rehearsal failed"));}function Id(e){console.log(),console.log(L.default.bold("SQLite Shim Audit")),console.log(` fields: ${L.default.cyan(e.summary.total)} passed: ${L.default.green(String(e.summary.passed))} warned: ${L.default.yellow(String(e.summary.warned))} failed: ${L.default.red(String(e.summary.failed))}`),e.results.length===0&&console.log(L.default.dim(" no shim-backed fields found"));for(let t of e.results.filter(n=>n.status!=="pass")){let n=t.status==="fail"?L.default.red:L.default.yellow;if(console.log(` ${n(t.status)} ${t.field} (${t.pg_type}) rows: ${L.default.cyan(t.rows_checked)} affected: ${L.default.cyan(t.affected_rows??0)}`),t.message&&console.log(` ${t.message}`),t.samples?.length)for(let r of t.samples)console.log(L.default.dim(` sample ${JSON.stringify(r.id)} raw=${JSON.stringify(r.raw_value)}`));t.action&&console.log(L.default.dim(` action: ${t.action}`));}console.log(e.summary.upgrade_safe?L.default.green(" shim audit passed"):L.default.red(" shim audit failed"));}function Bc(e){if(console.log(),console.log(L.default.bold(L.default.green("Upgrade complete."))),console.log(),console.log(` ${L.default.bold("Project URL:")} ${L.default.cyan(e.projectUrl)}`),console.log(` ${L.default.bold("API URL:")} ${L.default.cyan(e.apiUrl)}`),e.studioUrl&&console.log(` ${L.default.bold("Studio URL:")} ${L.default.cyan(e.studioUrl)}`),console.log(` ${L.default.bold("Ref:")} ${L.default.cyan(e.projectRef)}`),console.log(),console.log(` ${L.default.bold("anon key:")} ${e.anonKey}`),console.log(` ${L.default.bold("service_role key:")} ${e.serviceRoleKey}`),console.log(` ${L.default.bold("db password:")} ${e.dbPassword}`),console.log(),console.log(` migrated auth \u2014 users: ${L.default.cyan(e.auth.users)} sessions: ${L.default.cyan(e.auth.sessions)} identities: ${L.default.cyan(e.auth.identities)} refresh_tokens: ${L.default.cyan(e.auth.refresh_tokens)}`),console.log(` jwt secret: ${e.jwtMigrated?L.default.green("migrated"):L.default.yellow("not migrated \u2014 users must re-authenticate")}`),e.warnings.length>0){console.log(),console.log(L.default.yellow("Warnings:"));for(let t of e.warnings)console.log(` ${L.default.yellow("!")} ${t}`);}console.log(),console.log(L.default.bold("Update your supabase-js client:")),console.log(` url: ${L.default.cyan(e.apiUrl)}`),console.log(` anonKey: ${L.default.cyan(e.anonKey)}`),console.log();}var L,Dd=b(()=>{L=V(z());});function jd(e){return {kty:"oct",alg:"HS256",k:Buffer$1.from(e,"utf8").toString("base64url")}}var Fd=b(()=>{No();});async function Ud(e){let t=e.trim();if(!t)return "";let{PGlite:n}=await qe("@supabase/lite/pglite","pglite","@electric-sql/pglite"),r=new n;try{return await r.exec(bt(wt(t))),await r.exec(Ws),await e_(r,t)}finally{await r.close().catch(()=>{});}}async function e_(e,t){return t?(await e.exec(t),await t_(e)):""}async function t_(e){let t=await e.query(`
389
427
  SELECT table_schema, table_name, column_name, is_nullable, data_type,
390
428
  udt_name, udt_schema, character_maximum_length,
391
429
  numeric_precision, numeric_scale, column_default, ordinal_position
392
430
  FROM information_schema.columns
393
431
  WHERE table_schema NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
394
432
  ORDER BY table_schema, table_name, ordinal_position
395
- `),r=await e.query(`
433
+ `),n=await e.query(`
396
434
  SELECT kcu.table_schema, kcu.table_name, kcu.column_name
397
435
  FROM information_schema.table_constraints tc
398
436
  JOIN information_schema.key_column_usage kcu
@@ -402,28 +440,28 @@ CREATE TABLE IF NOT EXISTS auth.audit_log_entries (
402
440
  WHERE tc.constraint_type = 'PRIMARY KEY'
403
441
  AND tc.table_schema NOT IN ('pg_catalog', 'information_schema', 'pg_toast')
404
442
  ORDER BY kcu.ordinal_position
405
- `),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,p=n.get(o)??[],u=a.map(f=>bx(f,p));i.push(`CREATE TABLE ${kl(l)}.${kl(c)} (
443
+ `),r=new Map;for(let o of n.rows){let a=`${o.table_schema}.${o.table_name}`,c=r.get(a)??[];c.push(o.column_name),r.set(a,c);}let s=new Map;for(let o of t.rows){let a=`${o.table_schema}.${o.table_name}`,c=s.get(a)??[];c.push(o),s.set(a,c);}let i=[];for(let[o,a]of s){let c=a[0].table_schema,l=a[0].table_name,p=r.get(o)??[],u=a.map(f=>n_(f,p));i.push(`CREATE TABLE ${qc(c)}.${qc(l)} (
406
444
  ${u.join(`,
407
445
  `)}
408
446
  );`);}return i.join(`
409
447
 
410
- `)}function kl(e){return /^[a-z_][a-z0-9_]*$/.test(e)?e:`"${e.replace(/"/g,'""')}"`}function bx(e,t){let r=[kl(e.column_name)];return r.push(Sx(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 Sx(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 wd=b(()=>{sr();bn();});function bd(e){return !e||e==="main"?"public":e}function Vt(e){return `"${e.replace(/"/g,'""')}"`}function xx(e,t){return Vt(e==="public"?t:`${e}.${t}`)}function Ol(e){return `${e.schema}.${e.table}.${e.column}`}function _x(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 $x(e){let t=e.connection.config?.translation?.deparse?.schema;if(t instanceof Map&&t.size>0)return t;let r=await Qr(e),n=await ge(e);if(r.trim()){let i=[await yd(r),n].filter(o=>o.trim().length>0).join(`
411
- `);return i.trim()?(await Cn(i)).schema:new Map}return n.trim()?(await Cn(n)).schema:new Map}async function Tx(e){let t=await $x(e),r=[];for(let n of t.values())for(let s of n.all())s.isShimBacked&&r.push({schema:bd(s.context.schema),table:s.context.table,column:s.context.column,field:s});return r}function vx(e,t){return e==="fail"||t==="fail"?"fail":e==="warn"||t==="warn"?"warn":"pass"}async function Cx(e,t,r){return (await e.connection.introspect()).primary_keys.find(i=>bd(i.schema)===t&&i.table===r)?.columns??[]}async function Ax(e,t){if(e.connection.dialect!=="sqlite")return {field:Ol(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=xx(t.schema,t.table),s=await Cx(e,t.schema,t.table),i=s.length>0?s:["rowid"],a=[...s.length>0?s.map(m=>`${Vt(m)} AS ${Vt(`id_${m}`)}`):[`rowid AS ${Vt("id_rowid")}`],`${Vt(t.column)} AS ${Vt("__lite_value")}`].join(", "),l;try{l=await e.connection.exec(`SELECT ${a} FROM ${n}`);}catch(m){return {field:Ol(t),pg_type:Nl(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??[],p="pass",u=0,f=null,h,d=[];for(let m of c){let y=t.field.validateStorage(m.__lite_value);if(p=vx(p,y.status),y.status!=="pass"&&(u++,f??=y.message,h??=y.action,d.length<Ex)){let g={};for(let E of i)g[E]=m[`id_${E}`];d.push({id:g,raw_value:m.__lite_value});}}return {field:Ol(t),pg_type:Nl(t.field),status:p,rows_checked:c.length,...u>0?{affected_rows:u}:{},message:f,...d.length>0?{samples:d}:{},...h?{action:h}:{}}}function Nl(e){if(e instanceof yt)return `${e.elementField?Nl(e.elementField):e.context.pgTypeName}[]`;if(e instanceof Bt&&e.numericPrecision){let{precision:t,scale:r}=e.numericPrecision;return `${e.context.pgTypeName}(${t},${r})`}return e instanceof le&&e.lengthConstraint!==void 0?`${e.context.pgTypeName}(${e.lengthConstraint})`:e.context.pgTypeName}async function Pl(e){let t=await Tx(e),r=[];for(let n of t)r.push(await Ax(e,n));return {summary:_x(r),results:r}}var Ex,Sd=b(()=>{Je();ht();wd();yi();Us();Fs();Be();Ex=3;});function Ed(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 xd=b(()=>{});function Rx(e){if(e.length===0)return "";if(e.length===1)return e[0];let t=e[0].match(_d);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(_d);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 $d(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 p=n[c]??1;if(l.length===1||p===1){for(let u of l){try{await e.runSql(u);}catch(f){s.push({statement:u,error:String(f)});}i++,r.onProgress?.(i,o);}return}for(let u=0;u<l.length;u+=p){let f=l.slice(u,u+p),h=Rx(f);try{await e.runSql(h),i+=f.length,r.onProgress?.(i,o);}catch{await a(f,c+1);}}};return await a(t,0),s}var _d,Td=b(()=>{_d=/^(INSERT INTO [^(]+\([^)]+\)\s*VALUES\s*)(\(.*\))(\s*ON CONFLICT[\s\S]*)?$/i;});async function kx(e,t,r,n){n.onSql?.(t,r);try{await e.runSql(t);}catch(s){throw new Error(`Failed SQL (${r}): ${String(s)}
412
- ${t}`,{cause:s})}}async function br(e,t,r,n,s={}){if(r.length===0)return;n.onBatchStart?.(t,r.length);let i=await $d(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 Ll(e,t,r){let n=await ge(e),s=Et(n);r.onSchemaStart?.(s.length);for(let c=0;c<s.length;c++)r.onSchemaProgress?.(c+1,s.length),await kx(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 br(t,"Migrating auth.users",i.users,r),await br(t,"Migrating auth.identities",i.identities,r),r.migrateSessions?(await br(t,"Migrating auth.sessions",i.sessions,r),await br(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 br(t,`Migrating ${c.schema}.${c.table}`,c.inserts,r);for(let c of l)await br(t,`Resetting ${c.schema}.${c.table} sequences`,c.sequenceResets,r,{sizes:[1],unit:"statements"});if(r.syncAuthConfig!==false&&t.updateAuthConfig){let c=Ed(e.config);Object.keys(c).length>0&&(r.onAuthConfigStart?.(),await t.updateAuthConfig(c),r.onAuthConfigEnd?.());}return {schemaStatements:s.length,auth:o,dataTables:a}}var vd=b(()=>{Je();xd();vl();Al();Td();xi();});function Nn(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function Cd(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"&&Cd(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 Ix(e){let t=JSON.parse(e),r=Cd(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 Ad(e){try{return decodeURIComponent(new URL(e).password)}catch{return ""}}function Rd(e=process.cwd()){return e}async function Dx(){return await new Promise((e,t)=>{let r=Ox.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 jx(){let e=new Set,t=async()=>{for(;;){let r=await Dx();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 On(e,t={}){let r=process.env.LITE_SUPABASE_CLI?.split(/\s+/).filter(Boolean)??Px,{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=[],p=[],u=setTimeout(()=>l.kill(),t.timeoutMs??12e4);l.stdout?.on("data",f=>c.push(Buffer.from(f))),l.stderr?.on("data",f=>p.push(Buffer.from(f))),l.on("error",f=>{clearTimeout(u),a(f);}),l.on("close",f=>{clearTimeout(u);let h=Buffer.concat(c).toString("utf8"),d=Buffer.concat(p).toString("utf8");if(f!==0){a(new Error([`supabase ${e.join(" ")} failed with exit code ${f}`,h,d].filter(Boolean).join(`
413
- `)));return}o({stdout:h,stderr:d});});})}function se(e,t,r,n){let s=new RegExp(`(\\[${t.replace(".","\\.")}\\][\\s\\S]*?)(?=\\n\\[|$)`),i=e.match(s);if(!i)return `${e.trimEnd()}
448
+ `)}function qc(e){return /^[a-z_][a-z0-9_]*$/.test(e)?e:`"${e.replace(/"/g,'""')}"`}function n_(e,t){let n=[qc(e.column_name)];return n.push(r_(e)),e.is_nullable==="NO"&&!t.includes(e.column_name)&&n.push("NOT NULL"),e.column_default!==null&&n.push(`DEFAULT ${e.column_default}`),t.length===1&&t[0]===e.column_name&&n.push("PRIMARY KEY"),n.join(" ")}function r_(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 Md=b(()=>{tn();yr();});function Bd(e){return !e||e==="main"?"public":e}function Vt(e){return `"${e.replace(/"/g,'""')}"`}function i_(e,t){return Vt(e==="public"?t:`${e}.${t}`)}function Hc(e){return `${e.schema}.${e.table}.${e.column}`}function o_(e){let t=e.filter(s=>s.status==="pass").length,n=e.filter(s=>s.status==="warn").length,r=e.filter(s=>s.status==="fail").length;return {total:e.length,passed:t,warned:n,failed:r,upgrade_safe:r===0}}async function a_(e){let t=e.connection.config?.translation?.deparse?.schema;if(t instanceof Map&&t.size>0)return t;let n=await Jn(e),r=await re(e);if(n.trim()){let i=[await Ud(n),r].filter(o=>o.trim().length>0).join(`
449
+ `);return i.trim()?(await Cr(i)).schema:new Map}return r.trim()?(await Cr(r)).schema:new Map}async function c_(e){let t=await a_(e),n=[];for(let r of t.values())for(let s of r.all())s.isShimBacked&&n.push({schema:Bd(s.context.schema),table:s.context.table,column:s.context.column,field:s});return n}function l_(e,t){return e==="fail"||t==="fail"?"fail":e==="warn"||t==="warn"?"warn":"pass"}async function u_(e,t,n){return (await e.connection.introspect()).primary_keys.find(i=>Bd(i.schema)===t&&i.table===n)?.columns??[]}async function p_(e,t){if(e.connection.dialect!=="sqlite")return {field:Hc(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 r=i_(t.schema,t.table),s=await u_(e,t.schema,t.table),i=s.length>0?s:["rowid"],a=[...s.length>0?s.map(m=>`${Vt(m)} AS ${Vt(`id_${m}`)}`):[`rowid AS ${Vt("id_rowid")}`],`${Vt(t.column)} AS ${Vt("__lite_value")}`].join(", "),c;try{c=await e.connection.exec(`SELECT ${a} FROM ${r}`);}catch(m){return {field:Hc(t),pg_type:Gc(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 l=c?.rows??[],p="pass",u=0,f=null,h,d=[];for(let m of l){let y=t.field.validateStorage(m.__lite_value);if(p=l_(p,y.status),y.status!=="pass"&&(u++,f??=y.message,h??=y.action,d.length<s_)){let g={};for(let E of i)g[E]=m[`id_${E}`];d.push({id:g,raw_value:m.__lite_value});}}return {field:Hc(t),pg_type:Gc(t.field),status:p,rows_checked:l.length,...u>0?{affected_rows:u}:{},message:f,...d.length>0?{samples:d}:{},...h?{action:h}:{}}}function Gc(e){if(e instanceof gt)return `${e.elementField?Gc(e.elementField):e.context.pgTypeName}[]`;if(e instanceof Ut&&e.numericPrecision){let{precision:t,scale:n}=e.numericPrecision;return `${e.context.pgTypeName}(${t},${n})`}return e instanceof ce&&e.lengthConstraint!==void 0?`${e.context.pgTypeName}(${e.lengthConstraint})`:e.context.pgTypeName}async function Wc(e){let t=await c_(e),n=[];for(let r of t)n.push(await p_(e,r));return {summary:o_(n),results:n}}var s_,qd=b(()=>{Fe();dt();Md();xi();Ms();Us();je();s_=3;});function Hd(e){let t=e.auth??{},n={};return typeof t.site_url=="string"&&(n.site_url=t.site_url),Array.isArray(t.additional_redirect_urls)&&(n.uri_allow_list=t.additional_redirect_urls.join(",")),typeof t.jwt_expiry=="number"&&(n.jwt_exp=t.jwt_expiry),typeof t.enable_signup=="boolean"&&(n.disable_signup=!t.enable_signup),typeof t.enable_anonymous_sign_ins=="boolean"&&(n.external_anonymous_users_enabled=t.enable_anonymous_sign_ins),typeof t.minimum_password_length=="number"&&(n.min_password_length=t.minimum_password_length),typeof t.email?.enable_confirmations=="boolean"&&(n.mailer_autoconfirm=!t.email.enable_confirmations),n}var Gd=b(()=>{});function f_(e){if(e.length===0)return "";if(e.length===1)return e[0];let t=e[0].match(Wd);if(!t)return e.map(i=>i.trim().endsWith(";")?i:`${i};`).join(" ");let n=t[1],r=t[3]??"",s=[t[2]];for(let i=1;i<e.length;i++){let o=e[i].match(Wd);if(!o||o[1]!==n||(o[3]??"")!==r)return e.map(a=>a.trim().endsWith(";")?a:`${a};`).join(" ");s.push(o[2]);}return `${n}${s.join(", ")}${r}`}async function Vd(e,t,n={}){let r=n.sizes??[50,10,1],s=[],i=0,o=t.length,a=async(c,l)=>{if(c.length===0)return;let p=r[l]??1;if(c.length===1||p===1){for(let u of c){try{await e.runSql(u);}catch(f){s.push({statement:u,error:String(f)});}i++,n.onProgress?.(i,o);}return}for(let u=0;u<c.length;u+=p){let f=c.slice(u,u+p),h=f_(f);try{await e.runSql(h),i+=f.length,n.onProgress?.(i,o);}catch{await a(f,l+1);}}};return await a(t,0),s}var Wd,Kd=b(()=>{Wd=/^(INSERT INTO [^(]+\([^)]+\)\s*VALUES\s*)(\(.*\))(\s*ON CONFLICT[\s\S]*)?$/i;});async function m_(e,t,n,r){r.onSql?.(t,n);try{await e.runSql(t);}catch(s){throw new Error(`Failed SQL (${n}): ${String(s)}
450
+ ${t}`,{cause:s})}}async function wn(e,t,n,r,s={}){if(n.length===0)return;r.onBatchStart?.(t,n.length);let i=await Vd(e,n,{sizes:s.sizes??r.batchSizes,onProgress:(o,a)=>r.onBatchProgress?.(t,o,a)});if(i.length>0)throw r.onBatchFailure?.(t,i),new Error(`${t} had ${i.length} failures`);r.onBatchEnd?.(t,n.length,s.unit??"rows");}async function Vc(e,t,n){let r=await re(e),s=Et(r);n.onSchemaStart?.(s.length);for(let l=0;l<s.length;l++)n.onSchemaProgress?.(l+1,s.length),await m_(t,s[l],`schema ${l+1}/${s.length}`,n);n.onSchemaEnd?.(s.length);let i=await Ci(e,{target:n.authTarget??"supabase"}),o={users:i.users.length,sessions:n.migrateSessions?i.sessions.length:0,identities:i.identities.length,refresh_tokens:n.migrateSessions?i.refresh_tokens.length:0};await wn(t,"Migrating auth.users",i.users,n),await wn(t,"Migrating auth.identities",i.identities,n),n.migrateSessions?(await wn(t,"Migrating auth.sessions",i.sessions,n),await wn(t,"Migrating auth.refresh_tokens",i.refresh_tokens,n)):(i.sessions.length>0||i.refresh_tokens.length>0)&&n.onSkip?.(`Skipped ${i.sessions.length} sessions and ${i.refresh_tokens.length} refresh tokens (existing tokens will be invalidated).`);let a=await Ri(e),c=a.filter(l=>l.inserts.length>0);c.length===0&&n.onSkip?.("No user data rows to migrate.");for(let l of c)await wn(t,`Migrating ${l.schema}.${l.table}`,l.inserts,n);for(let l of c)await wn(t,`Resetting ${l.schema}.${l.table} sequences`,l.sequenceResets,n,{sizes:[1],unit:"statements"});if(n.syncAuthConfig!==false&&t.updateAuthConfig){let l=Hd(e.config);Object.keys(l).length>0&&(n.onAuthConfigStart?.(),await t.updateAuthConfig(l),n.onAuthConfigEnd?.());}return {schemaStatements:s.length,auth:o,dataTables:a}}var zd=b(()=>{Fe();Gd();Fc();Mc();Kd();$i();});function Pr(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}function Xd(e,t=new Map){if(!e||typeof e!="object")return t;for(let[n,r]of Object.entries(e))typeof r=="string"?t.set(Pr(n),r):r&&typeof r=="object"&&Xd(r,t);return t}function Rr(e,t,n){for(let r of t){let s=e.get(Pr(r));if(s)return s}throw new Error(`Supabase status JSON is missing ${n}`)}function b_(e){let t=JSON.parse(e),n=Xd(t);return {apiUrl:Rr(n,["API_URL","api_url","API URL","Project URL"],"API URL"),studioUrl:n.get(Pr("Studio URL"))??n.get(Pr("STUDIO_URL"))??n.get(Pr("studio_url")),dbUrl:Rr(n,["DB_URL","db_url","DB URL"],"DB URL"),anonKey:Rr(n,["ANON_KEY","anon_key","anon key","Publishable"],"anon key"),serviceRoleKey:Rr(n,["SERVICE_ROLE_KEY","service_role_key","service role key","Secret"],"service role key"),jwtSecret:Rr(n,["JWT_SECRET","jwt_secret","JWT secret"],"JWT secret")}}function Jd(e){try{return decodeURIComponent(new URL(e).password)}catch{return ""}}function Yd(e=process.cwd()){return e}async function w_(){return await new Promise((e,t)=>{let n=d_.createServer();n.once("error",t),n.listen(0,"127.0.0.1",()=>{let r=n.address();n.close(()=>{typeof r=="object"&&r?e(r.port):t(new Error("Could not allocate a free local port"));});});})}async function S_(){let e=new Set,t=async()=>{for(;;){let n=await w_();if(!e.has(n))return e.add(n),n}};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 kr(e,t={}){let n=process.env.LITE_SUPABASE_CLI?.split(/\s+/).filter(Boolean)??g_,{spawn:r}=await import('node:child_process').catch(()=>{throw new Error("Local Supabase upgrade requires a Node-compatible runtime")}),[s,...i]=n;return await new Promise((o,a)=>{let c=r(s,[...i,...e],{cwd:t.cwd,env:{...process.env,SUPABASE_TELEMETRY_DISABLED:"1",DO_NOT_TRACK:"1"}}),l=[],p=[],u=setTimeout(()=>c.kill(),t.timeoutMs??12e4);c.stdout?.on("data",f=>l.push(Buffer.from(f))),c.stderr?.on("data",f=>p.push(Buffer.from(f))),c.on("error",f=>{clearTimeout(u),a(f);}),c.on("close",f=>{clearTimeout(u);let h=Buffer.concat(l).toString("utf8"),d=Buffer.concat(p).toString("utf8");if(f!==0){a(new Error([`supabase ${e.join(" ")} failed with exit code ${f}`,h,d].filter(Boolean).join(`
451
+ `)));return}o({stdout:h,stderr:d});});})}function ie(e,t,n,r){let s=new RegExp(`(\\[${t.replace(".","\\.")}\\][\\s\\S]*?)(?=\\n\\[|$)`),i=e.match(s);if(!i)return `${e.trimEnd()}
414
452
 
415
453
  [${t}]
416
- ${r} = ${n}
417
- `;let o=i[1],a=new RegExp(`(^${r}\\s*=\\s*).*$`,"m"),l=a.test(o)?o.replace(a,`$1${n}`):`${o.trimEnd()}
418
- ${r} = ${n}
419
- `;return e.replace(o,l)}function Fx(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 Ux(e){return Fx(e,"db",["driver","url"])}function Mx(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 Il(e){return await fe__default.access(e).then(()=>true).catch(()=>false)}async function kd(e){let t=Fe__default.join(e,"supabase","config.toml");if(!await Il(t))return null;let r=await fe__default.readFile(t,"utf-8");if(!Mx(r))return null;let n=`${t}.bak`;return await Il(n)||await fe__default.writeFile(n,r,"utf-8"),n}async function Bx(e){let t=Fe__default.join(e,"supabase","config.toml");await Il(t)||(await fe__default.mkdir(e,{recursive:true}),await On(["init","--workdir",e,"--yes"],{timeoutMs:6e4}));}async function qx(e,t,r){let n=Fe__default.join(e,"supabase","config.toml"),s=Ux(await fe__default.readFile(n,"utf-8"));s=s.replace(/^project_id\s*=.*$/m,`project_id = "${t}"`),s=se(s,"api","port",String(r.api)),s=se(s,"db","port",String(r.db)),s=se(s,"db","shadow_port",String(r.shadow)),s=se(s,"db","major_version","15"),s=se(s,"db.seed","enabled","false"),s=se(s,"studio","enabled","true"),s=se(s,"studio","port",String(r.studio)),s=se(s,"inbucket","enabled","false"),s=se(s,"inbucket","port",String(r.inbucket)),s=se(s,"realtime","enabled","false"),s=se(s,"storage","enabled","false"),s=se(s,"edge_runtime","enabled","false"),s=se(s,"edge_runtime","inspector_port",String(r.edgeInspector)),s=se(s,"analytics","enabled","false"),s=se(s,"analytics","port",String(r.analytics)),s=se(s,"db.pooler","enabled","false"),s=se(s,"db.pooler","port",String(r.pooler)),await fe__default.writeFile(n,s,"utf-8");}function Od(e){return JSON.stringify(e)}function Hx(e){return `[${e.map(Od).join(", ")}]`}async function Gx(e,t){if(!t)return;let r=Fe__default.join(e,"supabase","config.toml"),n=await fe__default.readFile(r,"utf-8"),s=t.auth??{},i=s.email??{},o=t.api??{};typeof o.max_rows=="number"&&(n=se(n,"api","max_rows",String(o.max_rows))),typeof s.site_url=="string"&&(n=se(n,"auth","site_url",Od(s.site_url))),Array.isArray(s.additional_redirect_urls)&&(n=se(n,"auth","additional_redirect_urls",Hx(s.additional_redirect_urls))),typeof s.jwt_expiry=="number"&&(n=se(n,"auth","jwt_expiry",String(s.jwt_expiry))),typeof s.enable_signup=="boolean"&&(n=se(n,"auth","enable_signup",String(s.enable_signup))),typeof s.enable_anonymous_sign_ins=="boolean"&&(n=se(n,"auth","enable_anonymous_sign_ins",String(s.enable_anonymous_sign_ins))),typeof s.minimum_password_length=="number"&&(n=se(n,"auth","minimum_password_length",String(s.minimum_password_length))),typeof i.enable_confirmations=="boolean"&&(n=se(n,"auth.email","enable_confirmations",String(i.enable_confirmations))),await fe__default.writeFile(r,n,"utf-8");}var Px,Lx,Ci,Nd=b(()=>{sr();Px=["bunx","supabase@2.98.1"],Lx=["mailpit","realtime","storage-api","imgproxy","edge-runtime","logflare","vector","supavisor"];Ci=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 fe__default.mkdtemp(Fe__default.join(Xy.tmpdir(),"lite-local-supa-")),n=t.projectId??`lite-local-${Date.now().toString(36)}`,s=t.cleanupOnStop??!t.workdir,i=await jx();try{await Bx(r),await qx(r,n,i),await Gx(r,t.sourceConfig),await On(["start","--workdir",r,"--yes","--exclude",Lx.join(",")],{timeoutMs:5*6e4});let{stdout:o}=await On(["status","--workdir",r,"-o","json"],{timeoutMs:6e4});return new e(r,n,Ix(o),s)}catch(o){throw await On(["stop","--workdir",r,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),s&&await fe__default.rm(r,{recursive:true,force:true}).catch(()=>{}),o}}async runSql(t){let{createPostgresConnection:r}=await He("@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 On(["stop","--workdir",this.workdir,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),this.cleanupOnStop&&await fe__default.rm(this.workdir,{recursive:true,force:true}));}};});async function Ai(){let e=await vn({message:"Email",placeholder:"Enter your email",validate:t=>{try{Nc(t,{domains:["supabase.io"],panic:!0});return}catch(r){return r}}});return Ee(e)&&process.exit(1),e}async function Ri(e=false){let t=await $n({message:"Password",validate:r=>{try{Pc(r,{panic:!0});return}catch(n){return n}}});if(Ee(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}}});Ee(r)&&process.exit(1);}return t}async function ki(){let e=await vn({message:"Project Name",placeholder:"Enter your project name",validate:t=>t?.trim()?void 0:"Project name is required"});return Ee(e)&&process.exit(1),e.trim()}async function Oi(e){let t=await _n({message:e,initialValue:true});return Ee(t)&&process.exit(1),t}var Sr=b(()=>{Ye();Or();});var jd={};de(jd,{isNonInteractive:()=>Dl,resolveSessionMigration:()=>Dd,resolveTarget:()=>Id,upgrade:()=>Zx});async function Vx(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 Tn({message:"Select organization",options:r.map(s=>({value:s.id,label:`${s.name} (${s.slug})`}))});return Ee(n)&&process.exit(1),r.find(s=>s.id===n)}async function Kx(e,t,r){if(r)return r;let n=zx;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 Tn({message:"Select region",options:n.map(i=>({value:i.key,label:i.label}))});return Ee(s)&&process.exit(1),s}async function Xx(e){if(e)return e;let t=await vn({message:"Project name",placeholder:"my-project",validate:r=>r&&r.trim().length>0?void 0:"Name is required"});return Ee(t)&&process.exit(1),t}function Jx(){return Wx.randomBytes(24).toString("base64url")}function Id(e){let t=e??"hosted";if(t==="hosted"||t==="local")return t;throw new Error(`Unknown upgrade target '${t}'. Use 'hosted' or 'local'.`)}function Dl(){return process.env.CI==="true"||process.env.LITE_NON_INTERACTIVE==="1"||!process.stdin.isTTY}async function Yx(e){if(typeof e=="boolean")return e;if(Dl())return false;let t=await _n({message:"Migrate existing sessions (transfers JWT secret, sessions, refresh tokens)?",initialValue:false});return Ee(t)&&process.exit(1),t}async function Qx(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 Ee(r)&&process.exit(1),r}async function Dd(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=Fr(e.jwtSecret);if(t.strong||e.allowWeakJwtSecret)return {migrateSessions:true,jwtSecret:e.jwtSecret,weakReasons:t.reasons};if(Dl())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(`
420
- `));K.warning(["auth.jwt_secret looks weak and will become a trusted Supabase signing key:",...t.reasons.map(n=>`- ${n}`)].join(`
421
- `));let r=await _n({message:"Preserve existing sessions anyway by importing this JWT secret?",initialValue:false});return Ee(r)&&process.exit(1),r?{migrateSessions:true,jwtSecret:e.jwtSecret,weakReasons:t.reasons}:{migrateSessions:false,weakReasons:t.reasons}}var _e,zx,Zx,Fd=b(()=>{_e=te(ae());Ye();De();Ae();Km();rd();ud();dd();gd();Sd();vd();Nd();Sr();bi();$e();zx=[{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)"}];Zx=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 J(async()=>{await Q(t.config);let s=Id(t.target);if($l("upgrade.target",s),$l("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 V({withSupabaseClient:!1})).project.local.createApp(t.config);}finally{r&&(console.log=n);}if(r){let w=await Pl(i);n(JSON.stringify(w,null,2)),w.summary.upgrade_safe||process.exit(1);return}console.log(_e.default.dim("Running readiness checks..."));let o=await An("readiness",()=>td(i));if(pd(o),!o.ok)throw new Error("Readiness checks failed. See errors above.");let a=async()=>{console.log(_e.default.dim(`
422
- Rehearsing upgrade against in-memory pglite...`));let w=await An("rehearsal",()=>cd(i));return fd(w),w.ok};if(t.dryRun){let w=await Pl(i);md(w),w.summary.upgrade_safe||process.exit(1),await a()||process.exit(1);return}if(!t.force&&!await Oi("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 w=Fe__default.resolve(t.localDir??Rd()),D=await kd(w),N=null;if(D){let j=Fe__default.relative(process.cwd(),D)||D;N=`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=Sl(),S,x;try{F.start(`Starting local Supabase in ${w}`),S=await Ci.start({workdir:w,cleanupOnStop:!1,sourceConfig:i.config}),F.stop(`Local Supabase is running at ${S.status.apiUrl}`),x=await An("apply",()=>Ll(i,S,{migrateSessions:!1,authTarget:"supabase",syncAuthConfig:!1,onSql:(j,ie)=>{t.verbose&&console.log(_e.default.dim(`-- ${ie}
423
- ${j}`));},onSchemaStart:j=>F.start(`Applying schema (0/${j})`),onSchemaProgress:(j,ie)=>F.message(`Applying schema (${j}/${ie})`),onSchemaEnd:j=>F.stop(`Schema applied (${j} statements)`),onBatchStart:(j,ie)=>F.start(`${j} (0/${ie})`),onBatchProgress:(j,ie,ue)=>F.message(`${j} (${ie}/${ue})`),onBatchEnd:(j,ie,ue)=>F.stop(`${j} (${ie} ${ue})`),onBatchFailure:(j,ie)=>{F.stop(_e.default.red(`${j}: ${ie.length} failed`));for(let ue of ie)console.log(_e.default.red(` \u2717 ${ue.error}`)),t.verbose&&console.log(_e.default.dim(` ${ue.statement}`));},onSkip:j=>console.log(_e.default.dim(j))}));}catch(j){throw N&&console.log(_e.default.yellow(`
424
- ${N}`)),j}let Y=["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."];N&&Y.unshift(N),i.config.storage?.enabled&&Y.push("Storage migration is not yet supported."),i.config.realtime?.enabled&&Y.push("Realtime config migration is not yet supported.");let q=Ad(S.status.dbUrl);if(t.dumpCredentials){let j=JSON.stringify({target:"local",workdir:S.workdir,projectUrl:S.status.apiUrl,apiUrl:S.status.apiUrl,studioUrl:S.status.studioUrl,dbUrl:S.status.dbUrl,anonKey:S.status.anonKey,serviceRoleKey:S.status.serviceRoleKey,dbPassword:q},null,2);await fe__default.writeFile(t.dumpCredentials,j,"utf-8"),console.log(_e.default.dim(`Credentials written to ${t.dumpCredentials}`));}Rl({projectRef:S.projectId,projectUrl:S.status.apiUrl,apiUrl:S.status.apiUrl,studioUrl:S.status.studioUrl,anonKey:S.status.anonKey,serviceRoleKey:S.status.serviceRoleKey,dbPassword:q,auth:x.auth,jwtMigrated:!1,warnings:[`Local Supabase workdir: ${S.workdir}`,...Y]});return}let c=await Qx(t.supabaseToken),p=new Ei(c);try{await p.listOrganizations();}catch(w){throw new Error(`Supabase access token rejected: ${String(w)}`)}let u=await Vx(p,t.orgId),f=await Kx(p,u.slug,t.region),h=await Xx(t.projectName),d=await Yx(t.migrateSessions),m=await Dd({requested:d,jwtSecret:i.config.auth?.jwt_secret,allowWeakJwtSecret:t.allowWeakJwtSecret}),y=m.migrateSessions,g=Jx(),E=Sl();E.start("Creating Supabase project");let v=await p.createProject({organization_id:u.id,name:h,db_pass:g,region:f}),T=v.ref??v.id;if(E.stop(`Project created: ${T}`),E.start("Waiting for project to become active"),await p.waitForActive(T,{onTick:w=>E.message(`Project status: ${w}`)}),E.stop("Project is active"),y){E.start("Importing JWT signing key");try{await p.createSigningKey(T,{algorithm:"HS256",status:"in_use",private_jwk:hd(m.jwtSecret)});}catch(w){throw E.stop(_e.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(w)}`].join(" "))}E.stop("JWT signing key imported");}let C=(await An("apply",()=>Ll(i,{runSql:w=>p.runSql(T,w),updateAuthConfig:w=>p.updateAuthConfig(T,w)},{migrateSessions:y,authTarget:"supabase",onSql:(w,D)=>{t.verbose&&console.log(_e.default.dim(`-- ${D}
425
- ${w}`));},onSchemaStart:w=>E.start(`Applying schema (0/${w})`),onSchemaProgress:(w,D)=>E.message(`Applying schema (${w}/${D})`),onSchemaEnd:w=>E.stop(`Schema applied (${w} statements)`),onBatchStart:(w,D)=>{E.start(`${w} (0/${D})`);},onBatchProgress:(w,D,N)=>E.message(`${w} (${D}/${N})`),onBatchEnd:(w,D,N)=>E.stop(`${w} (${D} ${N})`),onBatchFailure:(w,D)=>{E.stop(_e.default.red(`${w}: ${D.length} failed`));for(let N of D)console.log(_e.default.red(` \u2717 ${N.error}`)),t.verbose&&console.log(_e.default.dim(` ${N.statement}`));},onAuthConfigStart:()=>E.start("Syncing auth config"),onAuthConfigEnd:()=>E.stop("Auth config synced"),onSkip:w=>console.log(_e.default.dim(w))}))).auth,$=zm(await p.getApiKeys(T)),_=`https://${T}.${p.projectDomain}`,L=[];if(y?m.weakReasons.length>0?L.push(`A weak JWT secret was imported to preserve sessions: ${m.weakReasons.join("; ")}.`):L.push("Sessions preserved by importing auth.jwt_secret as a Supabase signing key."):L.push("Sessions and JWT secret not migrated. Existing tokens are invalid \u2014 users must re-authenticate."),i.config.storage?.enabled&&L.push("Storage migration is not yet supported."),i.config.realtime?.enabled&&L.push("Realtime config migration is not yet supported."),t.dumpCredentials){let w=JSON.stringify({ref:T,projectUrl:_,anonKey:$.anon,serviceRoleKey:$.service_role,dbPassword:g},null,2);await fe__default.writeFile(t.dumpCredentials,w,"utf-8"),console.log(_e.default.dim(`Credentials written to ${t.dumpCredentials}`));}Rl({projectRef:T,projectUrl:_,apiUrl:_,anonKey:$.anon,serviceRoleKey:$.service_role,dbPassword:g,auth:C,jwtMigrated:!!(y&&m.jwtSecret),warnings:L});});});});var Ud={};de(Ud,{login:()=>e_});var jl,e_,Md=b(()=>{jl=te(ae());Ye();Sr();De();Ae();e_=e=>{e.command("login").description("Login").option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{await J(async()=>{let r=await V();K.message(jl.default.dim("Enter your credentials to login to the cloud"));let n=await Ai(),s=await Ri(),{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: ${jl.default.cyan(i.user.email)}`);});});};});var qd={};de(qd,{logout:()=>t_});var Bd,t_,Hd=b(()=>{Bd=te(ae());Ae();Ye();De();t_=e=>{e.command("logout").description("Logout").helpGroup("Local Development:").action(async()=>{console.log(),await J(async()=>{let t=await V(),{error:r}=await t.client.auth.signOut();r&&(K.error(r.message),process.exit(1)),console.log(Bd.default.green("Logged out successfully"));});});};});var Gd={};de(Gd,{signup:()=>r_});var Fl,r_,Wd=b(()=>{Fl=te(ae());Ye();Sr();De();Ae();it();r_=e=>{e.command("signup").description(ye("Register a supalite cloud account")).option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{K.message(Fl.default.dim("Enter your credentials to sign up to the cloud")),await J(async()=>{let r=await V(),n=await Ai(),s=await Ri(!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: ${Fl.default.cyan(i.user.email)}`);});});};});var Vd={};de(Vd,{whoami:()=>n_});var Ul,n_,zd=b(()=>{Ul=te(ae());Ae();Ye();De();it();n_=e=>{e.command("whoami").description(ye("Show the current authenticated user")).option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{console.log(),await J(async()=>{let r=await V(),{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: ${Ul.default.cyan(n.user.email)}`),process.exit(0)):(console.log(Ul.default.yellow("Not authenticated")),process.exit(1)),s&&(K.error(s.message),process.exit(1));});});};});var Xd={};de(Xd,{link:()=>s_});var Kd,s_,Jd=b(()=>{De();Ae();$e();Ye();Kd=te(ae()),s_=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 J(async()=>{await Q();let r=await V();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 Tn({message:"Select a project:",options:i.map(o=>({value:o.id,hint:`name: ${o.name}, created: ${o.created_at}`}))}),Ee(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 ${Kd.default.cyan(s.id)}.`);});});});var Yd={};de(Yd,{unlink:()=>i_});var i_,Qd=b(()=>{De();Ae();$e();i_=e=>e.command("unlink").description("Unlink from a Supalite project").option("--json","Output in JSON format").helpGroup("Local Development:").action(async()=>{console.log(),await J(async()=>{await Q(),(await V()).project.local.unlink(),console.log("Finished unlinking project.");});});});var eh={};de(eh,{status:()=>o_});var Zd,o_,th=b(()=>{Ae();De();$e();Zd=te(ae());it();o_=e=>e.command("status").description(ye("Show information about the linked project")).helpGroup("Local Development:").action(async()=>{console.log(),await J(async()=>{await Q();let t=await V(),r=await t.project.remote.get();console.log(r),console.log(`Project URL: ${Zd.default.cyan(t.project.remote.url(r.id))}`);});});});var nh={};de(nh,{projects:()=>a_});var Ml,a_,l_,c_,sh=b(()=>{Sr();Ye();Ml=te(ae());De();Ae();De();a_=e=>{e.command("projects").description("Manage Supalite cloud projects").helpGroup("Management APIs:").addCommand(c_).addCommand(l_);},l_=new Command$1().name("list").description("List projects").helpGroup("Projects:").action(async()=>{await J(async()=>{let t=await(await V()).project.remote.list();(!Array.isArray(t)||t.length===0)&&(K.info("No projects found"),process.exit(0)),console.log(mm(t,{omitKeys:["config","user_id"],renderHeader:r=>String(r).split("_").map(n=>n.toUpperCase()).join(" ")}));});}),c_=new Command$1().name("create").description("Create a project").option("--name <name>","The name of the project").helpGroup("Projects:").action(async e=>{await J(async()=>{let t=await V(),r=e.name??await ki(),n=await t.project.remote.create({name:r});K.success(`Project ${Ml.default.cyan(n.name)} created: ${Ml.default.cyan(n.id)}`);});});});var ih={};de(ih,{cloud:()=>m_});var je,f_,m_,oh=b(()=>{je=te(ae());De();Ae();Sr();Je();mi();zt();$e();it();f_="Management APIs:",m_=e=>{let t=e.command("cloud").description(ye("Supalite cloud operations")).helpGroup(f_);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).option("--create","Create a new project if none present",false).option("--name <name>","Name of the project (paired with --create)").action(async r=>{let n=Di().filter(s=>s!=="cloud");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 J(async()=>{await Q(r.config);let s=await V(),i=await s.project.local.createApp(r.config),o=!1;await gn(i,{force:!0});let a=await s.project.remote.get().catch(async()=>{if(r.create||await Oi("No project found. Create a new project?")){o=!0;let m=r.name||await ki();return await s.project.remote.create({name:m}).then(y=>s.project.local.link(y))}throw new Error("No project found")}),l=await s.project.remote.createApp(a.id),c=await ge(i),p=l.connection.createMigrator(c),u=await p.diff();console.log(),pr(u);let f=l.getInfoJson(),h=i.getInfoJson();if(isEqual(f,h))console.log(je.default.dim("Project config is up to date"));else {if(!await s.project.remote.setConfig(a.id,h))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(u.plan.steps.length>0)try{if(await measureTime(async()=>{await p.migratePlan(u.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 yn(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)}
426
- `);}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 J(async()=>{await Q(r.config);let n=await V(),s=await n.project.local.createApp(r.config);if(await gn(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 ge(s),l=await o.connection.createMigrator(a).diff();if(l.plan.steps.length>0)if(r.sql){let c=za(l,{colorize:!0});console.log(je.default.cyan(c));}else pr(l);else console.log(je.default.green("No changes to migrate."));});});};});Li();var ch=te(ae());zt();var ah={init:()=>Promise.resolve().then(()=>(ac(),oc)).then(e=>e.init),start:()=>Promise.resolve().then(()=>(gp(),hp)).then(e=>e.start),dev:()=>Promise.resolve().then(()=>(Bf(),Mf)).then(e=>e.dev),repl:()=>Promise.resolve().then(()=>(Hf(),qf)).then(e=>e.repl),debug:()=>Promise.resolve().then(()=>(Wf(),Gf)).then(e=>e.debug),db:()=>Promise.resolve().then(()=>(Gm(),Hm)).then(e=>e.db),migration:()=>Promise.resolve().then(()=>(Vm(),Wm)).then(e=>e.migration),upgrade:()=>Promise.resolve().then(()=>(Fd(),jd)).then(e=>e.upgrade)},d_={login:()=>Promise.resolve().then(()=>(Md(),Ud)).then(e=>e.login),logout:()=>Promise.resolve().then(()=>(Hd(),qd)).then(e=>e.logout),signup:()=>Promise.resolve().then(()=>(Wd(),Gd)).then(e=>e.signup),whoami:()=>Promise.resolve().then(()=>(zd(),Vd)).then(e=>e.whoami),link:()=>Promise.resolve().then(()=>(Jd(),Xd)).then(e=>e.link),unlink:()=>Promise.resolve().then(()=>(Qd(),Yd)).then(e=>e.unlink),status:()=>Promise.resolve().then(()=>(th(),eh)).then(e=>e.status),projects:()=>Promise.resolve().then(()=>(sh(),nh)).then(e=>e.projects),cloud:()=>Promise.resolve().then(()=>(oh(),ih)).then(e=>e.cloud)};function h_(){return Vl("cloud")?{...ah,...d_}:ah}async function lh(){let e=h_(),t=process.argv[2];return t&&Object.hasOwn(e,t)?[await e[t]()]:Promise.all(Object.values(e).map(r=>r()))}$e();bi();Jt();var Bl=new Command;function y_(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 w_(){let{version:e,name:t}=await Xn();Bl.name("lite").description(`${ch.default.yellowBright("\u26A1")} ${t} v${e}`).version(e).option("--no-telemetry","disable anonymous usage telemetry").option("--verbose","show diagnostic output").hook("preAction",async(r,n)=>{let s=r.opts?.()??{},i=typeof n.opts=="function"?n.opts():{};sc(s.verbose===true),Fm(s.telemetry===false)&&await Um({command:y_(n),args:i});});for(let r of await lh())r(Bl);await Bl.parseAsync(),await wi(false);}w_().then(null).catch(async e=>{console.error(e),await wi(true,e),process.exitCode=1;});
454
+ ${n} = ${r}
455
+ `;let o=i[1],a=new RegExp(`(^${n}\\s*=\\s*).*$`,"m"),c=a.test(o)?o.replace(a,`$1${r}`):`${o.trimEnd()}
456
+ ${n} = ${r}
457
+ `;return e.replace(o,c)}function E_(e,t,n){let r=new RegExp(`(\\[${t.replace(".","\\.")}\\][\\s\\S]*?)(?=\\n\\[|$)`),s=e.match(r);if(!s)return e;let i=s[1],o=n.map(c=>c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),a=new RegExp(`^\\s*(${o})\\s*=.*(?:\\n|$)`,"gm");return e.replace(i,i.replace(a,""))}function x_(e){return E_(e,"db",["driver","url"])}function __(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 Kc(e){return await de__default.access(e).then(()=>true).catch(()=>false)}async function Qd(e){let t=Oe__default.join(e,"supabase","config.toml");if(!await Kc(t))return null;let n=await de__default.readFile(t,"utf-8");if(!__(n))return null;let r=`${t}.bak`;return await Kc(r)||await de__default.writeFile(r,n,"utf-8"),r}async function T_(e){let t=Oe__default.join(e,"supabase","config.toml");await Kc(t)||(await de__default.mkdir(e,{recursive:true}),await kr(["init","--workdir",e,"--yes"],{timeoutMs:6e4}));}async function $_(e,t,n){let r=Oe__default.join(e,"supabase","config.toml"),s=x_(await de__default.readFile(r,"utf-8"));s=s.replace(/^project_id\s*=.*$/m,`project_id = "${t}"`),s=ie(s,"api","port",String(n.api)),s=ie(s,"db","port",String(n.db)),s=ie(s,"db","shadow_port",String(n.shadow)),s=ie(s,"db","major_version","15"),s=ie(s,"db.seed","enabled","false"),s=ie(s,"studio","enabled","true"),s=ie(s,"studio","port",String(n.studio)),s=ie(s,"inbucket","enabled","false"),s=ie(s,"inbucket","port",String(n.inbucket)),s=ie(s,"realtime","enabled","false"),s=ie(s,"storage","enabled","false"),s=ie(s,"edge_runtime","enabled","false"),s=ie(s,"edge_runtime","inspector_port",String(n.edgeInspector)),s=ie(s,"analytics","enabled","false"),s=ie(s,"analytics","port",String(n.analytics)),s=ie(s,"db.pooler","enabled","false"),s=ie(s,"db.pooler","port",String(n.pooler)),await de__default.writeFile(r,s,"utf-8");}function Zd(e){return JSON.stringify(e)}function A_(e){return `[${e.map(Zd).join(", ")}]`}async function C_(e,t){if(!t)return;let n=Oe__default.join(e,"supabase","config.toml"),r=await de__default.readFile(n,"utf-8"),s=t.auth??{},i=s.email??{},o=t.api??{};typeof o.max_rows=="number"&&(r=ie(r,"api","max_rows",String(o.max_rows))),typeof s.site_url=="string"&&(r=ie(r,"auth","site_url",Zd(s.site_url))),Array.isArray(s.additional_redirect_urls)&&(r=ie(r,"auth","additional_redirect_urls",A_(s.additional_redirect_urls))),typeof s.jwt_expiry=="number"&&(r=ie(r,"auth","jwt_expiry",String(s.jwt_expiry))),typeof s.enable_signup=="boolean"&&(r=ie(r,"auth","enable_signup",String(s.enable_signup))),typeof s.enable_anonymous_sign_ins=="boolean"&&(r=ie(r,"auth","enable_anonymous_sign_ins",String(s.enable_anonymous_sign_ins))),typeof s.minimum_password_length=="number"&&(r=ie(r,"auth","minimum_password_length",String(s.minimum_password_length))),typeof i.enable_confirmations=="boolean"&&(r=ie(r,"auth.email","enable_confirmations",String(i.enable_confirmations))),await de__default.writeFile(n,r,"utf-8");}var g_,y_,ki,eh=b(()=>{tn();g_=["bunx","supabase@2.98.1"],y_=["mailpit","realtime","storage-api","imgproxy","edge-runtime","logflare","vector","supavisor"];ki=class e{constructor(t,n,r,s){this.workdir=t;this.projectId=n;this.status=r;this.cleanupOnStop=s;}stopped=false;static async start(t={}){let n=t.workdir??await de__default.mkdtemp(Oe__default.join(dy.tmpdir(),"lite-local-supa-")),r=t.projectId??`lite-local-${Date.now().toString(36)}`,s=t.cleanupOnStop??!t.workdir,i=await S_();try{await T_(n),await $_(n,r,i),await C_(n,t.sourceConfig),await kr(["start","--workdir",n,"--yes","--exclude",y_.join(",")],{timeoutMs:5*6e4});let{stdout:o}=await kr(["status","--workdir",n,"-o","json"],{timeoutMs:6e4});return new e(n,r,b_(o),s)}catch(o){throw await kr(["stop","--workdir",n,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),s&&await de__default.rm(n,{recursive:true,force:true}).catch(()=>{}),o}}async runSql(t){let{createPostgresConnection:n}=await qe("@supabase/lite/postgres","postgres","postgres"),r=n({url:this.status.dbUrl});try{await r.exec(t);}finally{await r.close();}}async stop(){this.stopped||(this.stopped=true,await kr(["stop","--workdir",this.workdir,"--no-backup"],{timeoutMs:12e4}).catch(()=>{}),this.cleanupOnStop&&await de__default.rm(this.workdir,{recursive:true,force:true}));}};});async function Pi(){let e=await Tr({message:"Email",placeholder:"Enter your email",validate:t=>{try{Pl(t,{domains:["supabase.io"],panic:!0});return}catch(n){return n}}});return be(e)&&process.exit(1),e}async function Ni(e=false){let t=await xr({message:"Password",validate:n=>{try{Nl(n,{panic:!0});return}catch(r){return r}}});if(be(t)&&process.exit(1),e){let n=await xr({message:"Confirm Password",validate:r=>{try{if(r!==t)throw new Error("Passwords do not match");return}catch(s){return s}}});be(n)&&process.exit(1);}return t}async function Li(){let e=await Tr({message:"Project Name",placeholder:"Enter your project name",validate:t=>t?.trim()?void 0:"Project name is required"});return be(e)&&process.exit(1),e.trim()}async function Oi(e){let t=await Er({message:e,initialValue:true});return be(t)&&process.exit(1),t}var Sn=b(()=>{Qe();Rn();});var ih={};pe(ih,{isNonInteractive:()=>zc,resolveSessionMigration:()=>sh,resolveTarget:()=>rh,upgrade:()=>D_});async function R_(e,t){let n=await e.listOrganizations();if(n.length===0)throw new Error("No Supabase organizations found for this token");if(t){let s=n.find(i=>i.id===t||i.slug===t);if(!s)throw new Error(`Organization not found: ${t}`);return s}if(n.length===1)return n[0];let r=await _r({message:"Select organization",options:n.map(s=>({value:s.id,label:`${s.name} (${s.slug})`}))});return be(r)&&process.exit(1),n.find(s=>s.id===r)}async function P_(e,t,n){if(n)return n;let r=k_;try{let o=(await e.listRegions(t)).regions??[];o.length>0&&(r=o.map(a=>({key:a.key,label:a.display_name??a.name??a.key})));}catch{}let s=await _r({message:"Select region",options:r.map(i=>({value:i.key,label:i.label}))});return be(s)&&process.exit(1),s}async function N_(e){if(e)return e;let t=await Tr({message:"Project name",placeholder:"my-project",validate:n=>n&&n.trim().length>0?void 0:"Name is required"});return be(t)&&process.exit(1),t}function L_(){return v_.randomBytes(24).toString("base64url")}function rh(e){let t=e??"hosted";if(t==="hosted"||t==="local")return t;throw new Error(`Unknown upgrade target '${t}'. Use 'hosted' or 'local'.`)}function zc(){return process.env.CI==="true"||process.env.LITE_NON_INTERACTIVE==="1"||!process.stdin.isTTY}async function O_(e){if(typeof e=="boolean")return e;if(zc())return false;let t=await Er({message:"Migrate existing sessions (transfers JWT secret, sessions, refresh tokens)?",initialValue:false});return be(t)&&process.exit(1),t}async function I_(e){if(e)return e;let t=process.env.SUPABASE_ACCESS_TOKEN;if(t)return t;X.info("Create a personal access token at https://supabase.com/dashboard/account/tokens");let n=await xr({message:"Supabase access token",validate:r=>r&&r.trim().length>0?void 0:"Token is required"});return be(n)&&process.exit(1),n}async function sh(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=Dn(e.jwtSecret);if(t.strong||e.allowWeakJwtSecret)return {migrateSessions:true,jwtSecret:e.jwtSecret,weakReasons:t.reasons};if(zc())throw new Error(["Cannot migrate sessions because auth.jwt_secret looks weak:",...t.reasons.map(r=>`- ${r}`),"Use --allow-weak-jwt-secret to preserve existing sessions anyway, or --no-migrate-sessions to require users to sign in again."].join(`
458
+ `));X.warning(["auth.jwt_secret looks weak and will become a trusted Supabase signing key:",...t.reasons.map(r=>`- ${r}`)].join(`
459
+ `));let n=await Er({message:"Preserve existing sessions anyway by importing this JWT secret?",initialValue:false});return be(n)&&process.exit(1),n?{migrateSessions:true,jwtSecret:e.jwtSecret,weakReasons:t.reasons}:{migrateSessions:false,weakReasons:t.reasons}}var Se,k_,D_,oh=b(()=>{Se=V(z());Qe();Ne();Te();gd();Td();Nd();Dd();Fd();qd();zd();eh();Sn();Ar();Ee();k_=[{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)"}];D_=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 n=t.dryRun&&t.json,r=console.log;n||console.log(),await Y(async()=>{await ee(t.config);let s=rh(t.target);if(Pc("upgrade.target",s),Pc("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.");n&&(console.log=()=>{});let i;try{i=await(await W({withSupabaseClient:!1})).project.local.createApp(t.config);}finally{n&&(console.log=r);}if(n){let w=await Wc(i);r(JSON.stringify(w,null,2)),w.summary.upgrade_safe||process.exit(1);return}console.log(Se.default.dim("Running readiness checks..."));let o=await $r("readiness",()=>_d(i));if(Ld(o),!o.ok)throw new Error("Readiness checks failed. See errors above.");let a=async()=>{console.log(Se.default.dim(`
460
+ Rehearsing upgrade against in-memory pglite...`));let w=await $r("rehearsal",()=>Pd(i));return Od(w),w.ok};if(t.dryRun){let w=await Wc(i);Id(w),w.summary.upgrade_safe||process.exit(1),await a()||process.exit(1);return}if(!t.force&&!await Oi("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 w=Oe__default.resolve(t.localDir??Yd()),I=await Qd(w),N=null;if(I){let D=Oe__default.relative(process.cwd(),I)||I;N=`Your project's supabase/config.toml was rewritten in place for the local Supabase CLI. The original was backed up to ${D}. To resume supalite dev (bun run dev), restore it: cp ${D} supabase/config.toml (or git checkout supabase/config.toml). Pass --local-dir <separate-dir> next time to keep the local stack isolated.`;}let j=kc(),S,x;try{j.start(`Starting local Supabase in ${w}`),S=await ki.start({workdir:w,cleanupOnStop:!1,sourceConfig:i.config}),j.stop(`Local Supabase is running at ${S.status.apiUrl}`),x=await $r("apply",()=>Vc(i,S,{migrateSessions:!1,authTarget:"supabase",syncAuthConfig:!1,onSql:(D,oe)=>{t.verbose&&console.log(Se.default.dim(`-- ${oe}
461
+ ${D}`));},onSchemaStart:D=>j.start(`Applying schema (0/${D})`),onSchemaProgress:(D,oe)=>j.message(`Applying schema (${D}/${oe})`),onSchemaEnd:D=>j.stop(`Schema applied (${D} statements)`),onBatchStart:(D,oe)=>j.start(`${D} (0/${oe})`),onBatchProgress:(D,oe,le)=>j.message(`${D} (${oe}/${le})`),onBatchEnd:(D,oe,le)=>j.stop(`${D} (${oe} ${le})`),onBatchFailure:(D,oe)=>{j.stop(Se.default.red(`${D}: ${oe.length} failed`));for(let le of oe)console.log(Se.default.red(` \u2717 ${le.error}`)),t.verbose&&console.log(Se.default.dim(` ${le.statement}`));},onSkip:D=>console.log(Se.default.dim(D))}));}catch(D){throw N&&console.log(Se.default.yellow(`
462
+ ${N}`)),D}let Z=["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."];N&&Z.unshift(N),i.config.storage?.enabled&&Z.push("Storage migration is not yet supported."),i.config.realtime?.enabled&&Z.push("Realtime config migration is not yet supported.");let B=Jd(S.status.dbUrl);if(t.dumpCredentials){let D=JSON.stringify({target:"local",workdir:S.workdir,projectUrl:S.status.apiUrl,apiUrl:S.status.apiUrl,studioUrl:S.status.studioUrl,dbUrl:S.status.dbUrl,anonKey:S.status.anonKey,serviceRoleKey:S.status.serviceRoleKey,dbPassword:B},null,2);await de__default.writeFile(t.dumpCredentials,D,"utf-8"),console.log(Se.default.dim(`Credentials written to ${t.dumpCredentials}`));}Bc({projectRef:S.projectId,projectUrl:S.status.apiUrl,apiUrl:S.status.apiUrl,studioUrl:S.status.studioUrl,anonKey:S.status.anonKey,serviceRoleKey:S.status.serviceRoleKey,dbPassword:B,auth:x.auth,jwtMigrated:!1,warnings:[`Local Supabase workdir: ${S.workdir}`,...Z]});return}let l=await I_(t.supabaseToken),p=new Ti(l);try{await p.listOrganizations();}catch(w){throw new Error(`Supabase access token rejected: ${String(w)}`)}let u=await R_(p,t.orgId),f=await P_(p,u.slug,t.region),h=await N_(t.projectName),d=await O_(t.migrateSessions),m=await sh({requested:d,jwtSecret:i.config.auth?.jwt_secret,allowWeakJwtSecret:t.allowWeakJwtSecret}),y=m.migrateSessions,g=L_(),E=kc();E.start("Creating Supabase project");let A=await p.createProject({organization_id:u.id,name:h,db_pass:g,region:f}),$=A.ref??A.id;if(E.stop(`Project created: ${$}`),E.start("Waiting for project to become active"),await p.waitForActive($,{onTick:w=>E.message(`Project status: ${w}`)}),E.stop("Project is active"),y){E.start("Importing JWT signing key");try{await p.createSigningKey($,{algorithm:"HS256",status:"in_use",private_jwk:jd(m.jwtSecret)});}catch(w){throw E.stop(Se.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(w)}`].join(" "))}E.stop("JWT signing key imported");}let C=(await $r("apply",()=>Vc(i,{runSql:w=>p.runSql($,w),updateAuthConfig:w=>p.updateAuthConfig($,w)},{migrateSessions:y,authTarget:"supabase",onSql:(w,I)=>{t.verbose&&console.log(Se.default.dim(`-- ${I}
463
+ ${w}`));},onSchemaStart:w=>E.start(`Applying schema (0/${w})`),onSchemaProgress:(w,I)=>E.message(`Applying schema (${w}/${I})`),onSchemaEnd:w=>E.stop(`Schema applied (${w} statements)`),onBatchStart:(w,I)=>{E.start(`${w} (0/${I})`);},onBatchProgress:(w,I,N)=>E.message(`${w} (${I}/${N})`),onBatchEnd:(w,I,N)=>E.stop(`${w} (${I} ${N})`),onBatchFailure:(w,I)=>{E.stop(Se.default.red(`${w}: ${I.length} failed`));for(let N of I)console.log(Se.default.red(` \u2717 ${N.error}`)),t.verbose&&console.log(Se.default.dim(` ${N.statement}`));},onAuthConfigStart:()=>E.start("Syncing auth config"),onAuthConfigEnd:()=>E.stop("Auth config synced"),onSkip:w=>console.log(Se.default.dim(w))}))).auth,T=hd(await p.getApiKeys($)),_=`https://${$}.${p.projectDomain}`,O=[];if(y?m.weakReasons.length>0?O.push(`A weak JWT secret was imported to preserve sessions: ${m.weakReasons.join("; ")}.`):O.push("Sessions preserved by importing auth.jwt_secret as a Supabase signing key."):O.push("Sessions and JWT secret not migrated. Existing tokens are invalid \u2014 users must re-authenticate."),i.config.storage?.enabled&&O.push("Storage migration is not yet supported."),i.config.realtime?.enabled&&O.push("Realtime config migration is not yet supported."),t.dumpCredentials){let w=JSON.stringify({ref:$,projectUrl:_,anonKey:T.anon,serviceRoleKey:T.service_role,dbPassword:g},null,2);await de__default.writeFile(t.dumpCredentials,w,"utf-8"),console.log(Se.default.dim(`Credentials written to ${t.dumpCredentials}`));}Bc({projectRef:$,projectUrl:_,apiUrl:_,anonKey:T.anon,serviceRoleKey:T.service_role,dbPassword:g,auth:C,jwtMigrated:!!(y&&m.jwtSecret),warnings:O});});});});var ah={};pe(ah,{login:()=>j_});var Xc,j_,ch=b(()=>{Xc=V(z());Qe();Sn();Ne();Te();j_=e=>{e.command("login").description("Login").option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{await Y(async()=>{let n=await W();X.message(Xc.default.dim("Enter your credentials to login to the cloud"));let r=await Pi(),s=await Ni(),{data:i,error:o}=await n.client.auth.signInWithPassword({email:r,password:s});o&&(X.error(o.message),process.exit(1)),t.json?console.log(JSON.stringify(i,null,2)):X.success(`Authenticated as: ${Xc.default.cyan(i.user.email)}`);});});};});var uh={};pe(uh,{logout:()=>F_});var lh,F_,ph=b(()=>{lh=V(z());Te();Qe();Ne();F_=e=>{e.command("logout").description("Logout").helpGroup("Local Development:").action(async()=>{console.log(),await Y(async()=>{let t=await W(),{error:n}=await t.client.auth.signOut();n&&(X.error(n.message),process.exit(1)),console.log(lh.default.green("Logged out successfully"));});});};});var fh={};pe(fh,{signup:()=>U_});var Jc,U_,mh=b(()=>{Jc=V(z());Qe();Sn();Ne();Te();Xe();U_=e=>{e.command("signup").description(me("Register a supalite cloud account")).option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{X.message(Jc.default.dim("Enter your credentials to sign up to the cloud")),await Y(async()=>{let n=await W(),r=await Pi(),s=await Ni(!0),{data:i,error:o}=await n.client.auth.signUp({email:r,password:s});o&&(X.error(o.message),process.exit(1)),t.json?console.log(JSON.stringify(i,null,2)):X.success(`Signed up as: ${Jc.default.cyan(i.user.email)}`);});});};});var dh={};pe(dh,{whoami:()=>M_});var Yc,M_,hh=b(()=>{Yc=V(z());Te();Qe();Ne();Xe();M_=e=>{e.command("whoami").description(me("Show the current authenticated user")).option("--json","Output in JSON format").helpGroup("Local Development:").action(async t=>{console.log(),await Y(async()=>{let n=await W(),{data:r,error:s}=await n.client.auth.getUser();t.json?console.log(JSON.stringify(r,null,2)):r&&"user"in r&&r.user&&"email"in r.user?(console.log(`Authenticated as: ${Yc.default.cyan(r.user.email)}`),process.exit(0)):(console.log(Yc.default.yellow("Not authenticated")),process.exit(1)),s&&(X.error(s.message),process.exit(1));});});};});var yh={};pe(yh,{link:()=>B_});var gh,B_,bh=b(()=>{Ne();Te();Ee();Qe();gh=V(z()),B_=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 Y(async()=>{await ee();let n=await W();n.project.local.ref()&&X.warning("Project is already linked.");let r=t.projectRef;if(!r){let i=await n.project.remote.list();r=await _r({message:"Select a project:",options:i.map(o=>({value:o.id,hint:`name: ${o.name}, created: ${o.created_at}`}))}),be(r)&&process.exit(1);}if(!r)throw new Error("No project ref found");console.log("Linking project",r);let s=await n.project.remote.get(r);n.project.local.setRef(s.id),console.log(`Finished linking project ${gh.default.cyan(s.id)}.`);});});});var wh={};pe(wh,{unlink:()=>q_});var q_,Sh=b(()=>{Ne();Te();Ee();q_=e=>e.command("unlink").description("Unlink from a Supalite project").option("--json","Output in JSON format").helpGroup("Local Development:").action(async()=>{console.log(),await Y(async()=>{await ee(),(await W()).project.local.unlink(),console.log("Finished unlinking project.");});});});var xh={};pe(xh,{status:()=>H_});var Eh,H_,_h=b(()=>{Te();Ne();Ee();Eh=V(z());Xe();H_=e=>e.command("status").description(me("Show information about the linked project")).helpGroup("Local Development:").action(async()=>{console.log(),await Y(async()=>{await ee();let t=await W(),n=await t.project.remote.get();console.log(n),console.log(`Project URL: ${Eh.default.cyan(t.project.remote.url(n.id))}`);});});});var $h={};pe($h,{projects:()=>G_});var Qc,G_,W_,V_,Ah=b(()=>{Sn();Qe();Qc=V(z());Ne();Te();Ne();G_=e=>{e.command("projects").description("Manage Supalite cloud projects").helpGroup("Management APIs:").addCommand(V_).addCommand(W_);},W_=new Command$1().name("list").description("List projects").helpGroup("Projects:").action(async()=>{await Y(async()=>{let t=await(await W()).project.remote.list();(!Array.isArray(t)||t.length===0)&&(X.info("No projects found"),process.exit(0)),console.log(Om(t,{omitKeys:["config","user_id"],renderHeader:n=>String(n).split("_").map(r=>r.toUpperCase()).join(" ")}));});}),V_=new Command$1().name("create").description("Create a project").option("--name <name>","The name of the project").helpGroup("Projects:").action(async e=>{await Y(async()=>{let t=await W(),n=e.name??await Li(),r=await t.project.remote.create({name:n});X.success(`Project ${Qc.default.cyan(r.name)} created: ${Qc.default.cyan(r.id)}`);});});});var Ch={};pe(Ch,{cloud:()=>J_});var Le,X_,J_,vh=b(()=>{Le=V(z());Ne();Te();Sn();Fe();bi();Kt();Ee();Xe();X_="Management APIs:",J_=e=>{let t=e.command("cloud").description(me("Supalite cloud operations")).helpGroup(X_);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).option("--create","Create a new project if none present",false).option("--name <name>","Name of the project (paired with --create)").action(async n=>{let r=Ui().filter(s=>s!=="cloud");r.length>0&&(console.error(Le.default.red(`Cannot deploy: experimental features enabled (${r.join(", ")}). Cloud does not support them yet.`)),process.exit(1)),await Y(async()=>{await ee(n.config);let s=await W(),i=await s.project.local.createApp(n.config),o=!1;await mr(i,{force:!0});let a=await s.project.remote.get().catch(async()=>{if(n.create||await Oi("No project found. Create a new project?")){o=!0;let m=n.name||await Li();return await s.project.remote.create({name:m}).then(y=>s.project.local.link(y))}throw new Error("No project found")}),c=await s.project.remote.createApp(a.id),l=await re(i),p=c.connection.createMigrator(l),u=await p.diff();console.log(),ln(u);let f=c.getInfoJson(),h=i.getInfoJson();if(isEqual(f,h))console.log(Le.default.dim("Project config is up to date"));else {if(!await s.project.remote.setConfig(a.id,h))throw new Error("Failed to update project config");console.log(Le.default.green("Project config updated"));}let d=s.project.remote.url(a.id);if(u.plan.steps.length>0)try{if(await measureTime(async()=>{await p.migratePlan(u.plan,{force:n.force??!1});},m=>{console.log(Le.default.green(`Pushed changes to project in ${m.toFixed(2)}ms.`));}),o)try{let m=await dr(c,{recoveryHint:"Fix `supabase/seed.sql` and rerun `lite cloud deploy` against the new project."});m>0&&console.log(Le.default.green(`Seeded remote project (${m} statements).`));}catch(m){console.warn(Le.default.yellow(String(m.message??m)));}console.log(`Project URL: ${Le.default.cyan(d)}
464
+ `);}catch(m){m instanceof yi&&(console.warn(Le.default.yellow("Migration would cause data loss. Rerun with --force to proceed.")),process.exit(1)),console.error(Le.default.red("Migration error: "+String(m))),process.exit(1);}else console.log(Le.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 n=>{console.log(),await Y(async()=>{await ee(n.config);let r=await W(),s=await r.project.local.createApp(n.config);if(await mr(s,{force:!0}),!r.project.local.ref())throw new Error("No project linked");let i=await r.project.remote.get();if(!i)throw new Error("Project not found");let o=await r.project.remote.createApp(i.id),a=await re(s),c=await o.connection.createMigrator(a).diff();if(c.plan.steps.length>0)if(n.sql){let l=tc(c,{colorize:!0});console.log(Le.default.cyan(l));}else ln(c);else console.log(Le.default.green("No changes to migrate."));});});};});ji();var Ph=V(z());Kt();var Rh={init:()=>Promise.resolve().then(()=>(El(),Sl)).then(e=>e.init),"generate-keys":()=>Promise.resolve().then(()=>(_l(),xl)).then(e=>e.generateKeys),start:()=>Promise.resolve().then(()=>(zf(),Kf)).then(e=>e.start),dev:()=>Promise.resolve().then(()=>(em(),Zf)).then(e=>e.dev),repl:()=>Promise.resolve().then(()=>(nm(),tm)).then(e=>e.repl),debug:()=>Promise.resolve().then(()=>(sm(),rm)).then(e=>e.debug),db:()=>Promise.resolve().then(()=>(fd(),pd)).then(e=>e.db),migration:()=>Promise.resolve().then(()=>(dd(),md)).then(e=>e.migration),upgrade:()=>Promise.resolve().then(()=>(oh(),ih)).then(e=>e.upgrade)},Y_={login:()=>Promise.resolve().then(()=>(ch(),ah)).then(e=>e.login),logout:()=>Promise.resolve().then(()=>(ph(),uh)).then(e=>e.logout),signup:()=>Promise.resolve().then(()=>(mh(),fh)).then(e=>e.signup),whoami:()=>Promise.resolve().then(()=>(hh(),dh)).then(e=>e.whoami),link:()=>Promise.resolve().then(()=>(bh(),yh)).then(e=>e.link),unlink:()=>Promise.resolve().then(()=>(Sh(),wh)).then(e=>e.unlink),status:()=>Promise.resolve().then(()=>(_h(),xh)).then(e=>e.status),projects:()=>Promise.resolve().then(()=>(Ah(),$h)).then(e=>e.projects),cloud:()=>Promise.resolve().then(()=>(vh(),Ch)).then(e=>e.cloud)};function Q_(){return sl("cloud")?{...Rh,...Y_}:Rh}async function kh(){let e=Q_(),t=process.argv[2];return t&&Object.hasOwn(e,t)?[await e[t]()]:Promise.all(Object.values(e).map(n=>n()))}Ee();Ar();Ct();Nc();var Zc=new Command;function eT(e){let t=[],n=e;for(;n&&n.name&&n.name()&&n.parent;)t.unshift(n.name()),n=n.parent;return t.join(" ")}async function tT(){Nm();let{version:e,name:t}=await zr();Zc.name("lite").description(`${Ph.default.yellowBright("\u26A1")} ${t} v${e}`).version(e).option("--no-telemetry","disable anonymous usage telemetry").option("--verbose","show diagnostic output").hook("preAction",async(n,r)=>{let s=n.opts?.()??{},i=typeof r.opts=="function"?r.opts():{};gl(s.verbose===true),vm(s.telemetry===false)&&await Rm({command:eT(r),args:i});});for(let n of await kh())n(Zc);await Zc.parseAsync(),await dn(false);}process.on("unhandledRejection",e=>{if(!hn(e))throw e});process.on("uncaughtException",e=>{hn(e)||(console.error(e),dn(true,e).finally(()=>process.exit(1)));});tT().then(null).catch(async e=>{hn(e)||(console.error(e),await dn(true,e),process.exitCode=1);});
427
465
  /*! Bundled license information:
428
466
 
429
467
  smol-toml/dist/error.js: