@supabase/lite 0.7.1-next.1 → 0.7.1-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/lib.js CHANGED
@@ -1,4 +1,4 @@
1
- import'pgsql-deparser';import*as at from'node:path';import at__default from'node:path';import Ii from'node:os';import he from'node:fs';import {createClient}from'@supabase/supabase-js';import {ensureVar,App,cloud,splitSqlStatements}from'@supabase/lite';import {createConnection}from'@supabase/lite/sqlite';import*as V from'node:fs/promises';import V__default from'node:fs/promises';import {createHash}from'node:crypto';import {parse}from'dotenv';import'node:url';import*as Ns from'fs';import {statSync,stat,realpathSync,realpath,readdirSync,readdir}from'fs';import {resolve,posix,sep,isAbsolute,basename,dirname,normalize,relative}from'path';import {fileURLToPath}from'url';import {createRequire}from'module';import El from'chokidar';try {
1
+ import'pgsql-deparser';import*as at from'node:path';import at__default from'node:path';import Ii from'node:os';import de from'node:fs';import {createClient}from'@supabase/supabase-js';import {ensureVar,App,cloud,splitSqlStatements}from'@supabase/lite';import {createConnection}from'@supabase/lite/sqlite';import*as V from'node:fs/promises';import V__default from'node:fs/promises';import {createHash}from'node:crypto';import {parse}from'dotenv';import'node:url';import*as Ns from'fs';import {statSync,stat,realpathSync,realpath,readdirSync,readdir}from'fs';import {resolve,posix,sep,isAbsolute,basename,dirname,normalize,relative}from'path';import {fileURLToPath}from'url';import {createRequire}from'module';import El from'chokidar';try {
2
2
  /**
3
3
  * Adding this to avoid warnings from node:sqlite being experimental
4
4
  */
@@ -9,7 +9,7 @@ import'pgsql-deparser';import*as at from'node:path';import at__default from'node
9
9
  };
10
10
  } catch {}
11
11
 
12
- var $i=Object.create;var He=Object.defineProperty;var vi=Object.getOwnPropertyDescriptor;var Ni=Object.getOwnPropertyNames;var ki=Object.getPrototypeOf,Pi=Object.prototype.hasOwnProperty;var F=(e,t)=>()=>(e&&(t=e(e=0)),t);var bt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Li=(e,t)=>{for(var n in t)He(e,n,{get:t[n],enumerable:true});},Oi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ni(t))!Pi.call(e,i)&&i!==n&&He(e,i,{get:()=>t[i],enumerable:!(r=vi(t,i))||r.enumerable});return e};var kt=(e,t,n)=>(n=e!=null?$i(ki(e)):{},Oi(He(n,"default",{value:e,enumerable:true}),e));var Lt=bt((bc,Ve)=>{var xe=process||{},qn=xe.argv||[],we=xe.env||{},Ui=!(we.NO_COLOR||qn.includes("--no-color"))&&(!!we.FORCE_COLOR||qn.includes("--color")||xe.platform==="win32"||(xe.stdout||{}).isTTY&&we.TERM!=="dumb"||!!we.CI),Mi=(e,t,n=e)=>r=>{let i=""+r,s=i.indexOf(t,e.length);return ~s?e+Hi(i,t,n,s)+t:e+i+t},Hi=(e,t,n,r)=>{let i="",s=0;do i+=e.substring(s,r)+n,s=r+t.length,r=e.indexOf(t,s);while(~r);return i+e.substring(s)},Vn=(e=Ui)=>{let t=e?Mi:()=>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")}};Ve.exports=Vn();Ve.exports.createColors=Vn;});var Mt=bt((_f,yr)=>{var mr="[^\\\\/]",_o="(?=.)",dr="[^/]",on="(?:\\/|$)",hr="(?:^|\\/)",an=`\\.{1,2}${on}`,Co="(?!\\.)",Ro=`(?!${hr}${an})`,$o=`(?!\\.{0,1}${on})`,vo=`(?!${an})`,No="[^.\\/]",ko=`${dr}*?`,Po="/",gr={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:_o,QMARK:dr,END_ANCHOR:on,DOTS_SLASH:an,NO_DOT:Co,NO_DOTS:Ro,NO_DOT_SLASH:$o,NO_DOTS_SLASH:vo,QMARK_NO_DOT:No,STAR:ko,START_ANCHOR:hr,SEP:Po},Lo={...gr,SLASH_LITERAL:"[\\\\/]",QMARK:mr,STAR:`${mr}*?`,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:"\\"},Oo={__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"};yr.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:Oo,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?Lo:gr}};});var Ht=bt(J=>{var{REGEX_BACKSLASH:Fo,REGEX_REMOVE_BACKSLASH:Io,REGEX_SPECIAL_CHARS:Do,REGEX_SPECIAL_CHARS_GLOBAL:jo}=Mt();J.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);J.hasRegexChars=e=>Do.test(e);J.isRegexChar=e=>e.length===1&&J.hasRegexChars(e);J.escapeRegex=e=>e.replace(jo,"\\$1");J.toPosixSlashes=e=>e.replace(Fo,"/");J.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};J.removeBackslashes=e=>e.replace(Io,t=>t==="\\"?"":t);J.escapeLast=(e,t,n)=>{let r=e.lastIndexOf(t,n);return r===-1?e:e[r-1]==="\\"?J.escapeLast(e,t,r-1):`${e.slice(0,r)}\\${e.slice(r)}`};J.removePrefix=(e,t={})=>{let n=e;return n.startsWith("./")&&(n=n.slice(2),t.prefix="./"),n};J.wrapOutput=(e,t={},n={})=>{let r=n.contains?"":"^",i=n.contains?"":"$",s=`${r}(?:${e})${i}`;return t.negated===true&&(s=`(?:^(?!${s}).*$)`),s};J.basename=(e,{windows:t}={})=>{let n=e.split(t?/[\\/]/:"/"),r=n[n.length-1];return r===""?n[n.length-2]:r};});var _r=bt((Rf,Ar)=>{var br=Ht(),{CHAR_ASTERISK:ln,CHAR_AT:Bo,CHAR_BACKWARD_SLASH:qt,CHAR_COMMA:Uo,CHAR_DOT:cn,CHAR_EXCLAMATION_MARK:un,CHAR_FORWARD_SLASH:Tr,CHAR_LEFT_CURLY_BRACE:fn,CHAR_LEFT_PARENTHESES:pn,CHAR_LEFT_SQUARE_BRACKET:Mo,CHAR_PLUS:Ho,CHAR_QUESTION_MARK:wr,CHAR_RIGHT_CURLY_BRACE:qo,CHAR_RIGHT_PARENTHESES:xr,CHAR_RIGHT_SQUARE_BRACKET:Vo}=Mt(),Sr=e=>e===Tr||e===qt,Er=e=>{e.isPrefix!==true&&(e.depth=e.isGlobstar?1/0:1);},Go=(e,t)=>{let n=t||{},r=e.length-1,i=n.parts===true||n.scanToEnd===true,s=[],o=[],a=[],l=e,c=-1,u=0,p=0,h=false,y=false,g=false,E=false,A=false,q=false,S=false,M=false,W=false,O=false,v=0,N,T,C={value:"",depth:0,isGlob:false},m=()=>c>=r,X=()=>l.charCodeAt(c+1),x=()=>(N=T,l.charCodeAt(++c));for(;c<r;){T=x();let L;if(T===qt){S=C.backslashes=true,T=x(),T===fn&&(q=true);continue}if(q===true||T===fn){for(v++;m()!==true&&(T=x());){if(T===qt){S=C.backslashes=true,x();continue}if(T===fn){v++;continue}if(q!==true&&T===cn&&(T=x())===cn){if(h=C.isBrace=true,g=C.isGlob=true,O=true,i===true)continue;break}if(q!==true&&T===Uo){if(h=C.isBrace=true,g=C.isGlob=true,O=true,i===true)continue;break}if(T===qo&&(v--,v===0)){q=false,h=C.isBrace=true,O=true;break}}if(i===true)continue;break}if(T===Tr){if(s.push(c),o.push(C),C={value:"",depth:0,isGlob:false},O===true)continue;if(N===cn&&c===u+1){u+=2;continue}p=c+1;continue}if(n.noext!==true&&(T===Ho||T===Bo||T===ln||T===wr||T===un)===true&&X()===pn){if(g=C.isGlob=true,E=C.isExtglob=true,O=true,T===un&&c===u&&(W=true),i===true){for(;m()!==true&&(T=x());){if(T===qt){S=C.backslashes=true,T=x();continue}if(T===xr){g=C.isGlob=true,O=true;break}}continue}break}if(T===ln){if(N===ln&&(A=C.isGlobstar=true),g=C.isGlob=true,O=true,i===true)continue;break}if(T===wr){if(g=C.isGlob=true,O=true,i===true)continue;break}if(T===Mo){for(;m()!==true&&(L=x());){if(L===qt){S=C.backslashes=true,x();continue}if(L===Vo){y=C.isBracket=true,g=C.isGlob=true,O=true;break}}if(i===true)continue;break}if(n.nonegate!==true&&T===un&&c===u){M=C.negated=true,u++;continue}if(n.noparen!==true&&T===pn){if(g=C.isGlob=true,i===true){for(;m()!==true&&(T=x());){if(T===pn){S=C.backslashes=true,T=x();continue}if(T===xr){O=true;break}}continue}break}if(g===true){if(O=true,i===true)continue;break}}n.noext===true&&(E=false,g=false);let P=l,d="",f="";u>0&&(d=l.slice(0,u),l=l.slice(u),p-=u),P&&g===true&&p>0?(P=l.slice(0,p),f=l.slice(p)):g===true?(P="",f=l):P=l,P&&P!==""&&P!=="/"&&P!==l&&Sr(P.charCodeAt(P.length-1))&&(P=P.slice(0,-1)),n.unescape===true&&(f&&(f=br.removeBackslashes(f)),P&&S===true&&(P=br.removeBackslashes(P)));let Q={prefix:d,input:e,start:u,base:P,glob:f,isBrace:h,isBracket:y,isGlob:g,isExtglob:E,isGlobstar:A,negated:M,negatedExtglob:W};if(n.tokens===true&&(Q.maxDepth=0,Sr(T)||o.push(C),Q.tokens=o),n.parts===true||n.tokens===true){let L;for(let B=0;B<s.length;B++){let lt=L?L+1:u,Z=s[B],mt=e.slice(lt,Z);n.tokens&&(B===0&&u!==0?(o[B].isPrefix=true,o[B].value=d):o[B].value=mt,Er(o[B]),Q.maxDepth+=o[B].depth),(B!==0||mt!=="")&&a.push(mt),L=Z;}if(L&&L+1<e.length){let B=e.slice(L+1);a.push(B),n.tokens&&(o[o.length-1].value=B,Er(o[o.length-1]),Q.maxDepth+=o[o.length-1].depth);}Q.slashes=s,Q.parts=a;}return Q};Ar.exports=Go;});var Nr=bt(($f,vr)=>{var Vt=Mt(),Y=Ht(),{MAX_LENGTH:Fe,POSIX_REGEX_SOURCE:zo,REGEX_NON_SPECIAL_CHARS:Wo,REGEX_SPECIAL_CHARS_BACKREF:Xo,REPLACEMENTS:Cr}=Vt,Ko=(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(i=>Y.escapeRegex(i)).join("..")}return n},Rt=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,Rr=e=>{let t=[],n=0,r=0,i=0,s="",o=false;for(let a of e){if(o===true){s+=a,o=false;continue}if(a==="\\"){s+=a,o=true;continue}if(a==='"'){i=i===1?0:1,s+=a;continue}if(i===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(s),s="";continue}}}s+=a;}return t.push(s),t},Jo=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},$r=e=>{let t=e.trim(),n=true;for(;n===true;)n=false,/^@\([^\\()[\]{}|]+\)$/.test(t)&&(t=t.slice(2,-1),n=true);if(Jo(t))return t.replace(/\\(.)/g,"$1")},Yo=e=>{let t=e.map($r).filter(Boolean);for(let n=0;n<t.length;n++)for(let r=n+1;r<t.length;r++){let i=t[n],s=t[r],o=i[0];if(!(!o||i!==o.repeat(i.length)||s!==o.repeat(s.length))&&(i===s||i.startsWith(s)||s.startsWith(i)))return true}return false},mn=(e,t=true)=>{if(e[0]!=="+"&&e[0]!=="*"||e[1]!=="(")return;let n=0,r=0,i=0,s=false;for(let o=1;o<e.length;o++){let a=e[o];if(s===true){s=false;continue}if(a==="\\"){s=true;continue}if(a==='"'){i=i===1?0:1;continue}if(i!==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}}}}},Qo=e=>{let t=0,n=[];for(;t<e.length;){let i=mn(e.slice(t),false);if(!i||i.type!=="*")return;let s=Rr(i.body).map(a=>a.trim());if(s.length!==1)return;let o=$r(s[0]);if(!o||o.length!==1)return;n.push(o),t+=i.end+1;}return n.length<1?void 0:`${n.length===1?Y.escapeRegex(n[0]):`[${n.map(i=>Y.escapeRegex(i)).join("")}]`}*`},Zo=e=>{let t=0,n=e.trim(),r=mn(n);for(;r;)t++,n=r.body.trim(),r=mn(n);return t},ta=(e,t)=>{if(t.maxExtglobRecursion===false)return {risky:false};let n=typeof t.maxExtglobRecursion=="number"?t.maxExtglobRecursion:Vt.DEFAULT_MAX_EXTGLOB_RECURSION,r=Rr(e).map(i=>i.trim());if(r.length>1&&(r.some(i=>i==="")||r.some(i=>/^[*?]+$/.test(i))||Yo(r)))return {risky:true};for(let i of r){let s=Qo(i);if(s)return {risky:true,safeOutput:s};if(Zo(i)>n)return {risky:true}}return {risky:false}},dn=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=Cr[e]||e;let n={...t},r=typeof n.maxLength=="number"?Math.min(Fe,n.maxLength):Fe,i=e.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);let s={type:"bos",value:"",output:n.prepend||""},o=[s],a=n.capture?"":"?:",l=Vt.globChars(n.windows),c=Vt.extglobChars(l),{DOT_LITERAL:u,PLUS_LITERAL:p,SLASH_LITERAL:h,ONE_CHAR:y,DOTS_SLASH:g,NO_DOT:E,NO_DOT_SLASH:A,NO_DOTS_SLASH:q,QMARK:S,QMARK_NO_DOT:M,STAR:W,START_ANCHOR:O}=l,v=w=>`(${a}(?:(?!${O}${w.dot?g:u}).)*?)`,N=n.dot?"":E,T=n.dot?S:M,C=n.bash===true?v(n):W;n.capture&&(C=`(${C})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let m={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=Y.removePrefix(e,m),i=e.length;let X=[],x=[],P=[],d=s,f,Q=()=>m.index===i-1,L=m.peek=(w=1)=>e[m.index+w],B=m.advance=()=>e[++m.index]||"",lt=()=>e.slice(m.index+1),Z=(w="",j=0)=>{m.consumed+=w,m.index+=j;},mt=w=>{m.output+=w.output!=null?w.output:w.value,Z(w.value);},Ci=()=>{let w=1;for(;L()==="!"&&(L(2)!=="("||L(3)==="?");)B(),m.start++,w++;return w%2===0?false:(m.negated=true,m.start++,true)},me=w=>{m[w]++,P.push(w);},dt=w=>{m[w]--,P.pop();},R=w=>{if(d.type==="globstar"){let j=m.braces>0&&(w.type==="comma"||w.type==="brace"),b=w.extglob===true||X.length&&(w.type==="pipe"||w.type==="paren");w.type!=="slash"&&w.type!=="paren"&&!j&&!b&&(m.output=m.output.slice(0,-d.output.length),d.type="star",d.value="*",d.output=C,m.output+=d.output);}if(X.length&&w.type!=="paren"&&(X[X.length-1].inner+=w.value),(w.value||w.output)&&mt(w),d&&d.type==="text"&&w.type==="text"){d.output=(d.output||d.value)+w.value,d.value+=w.value;return}w.prev=d,o.push(w),d=w;},de=(w,j)=>{let b={...c[j],conditions:1,inner:""};b.prev=d,b.parens=m.parens,b.output=m.output,b.startIndex=m.index,b.tokensIndex=o.length;let $=(n.capture?"(":"")+b.open;me("parens"),R({type:w,value:j,output:m.output?"":y}),R({type:"paren",extglob:true,value:B(),output:$}),X.push(b);},Ri=w=>{let j=e.slice(w.startIndex,m.index+1),b=e.slice(w.startIndex+2,m.index),$=ta(b,n);if((w.type==="plus"||w.type==="star")&&$.risky){let I=$.safeOutput?(w.output?"":y)+(n.capture?`(${$.safeOutput})`:$.safeOutput):void 0,it=o[w.tokensIndex];it.type="text",it.value=j,it.output=I||Y.escapeRegex(j);for(let st=w.tokensIndex+1;st<o.length;st++)o[st].value="",o[st].output="",delete o[st].suffix;m.output=w.output+it.output,m.backtrack=true,R({type:"paren",extglob:true,value:f,output:""}),dt("parens");return}let D=w.close+(n.capture?")":""),G;if(w.type==="negate"){let I=C;if(w.inner&&w.inner.length>1&&w.inner.includes("/")&&(I=v(n)),(I!==C||Q()||/^\)+$/.test(lt()))&&(D=w.close=`)$))${I}`),w.inner.includes("*")&&(G=lt())&&/^\.[^\\/.]+$/.test(G)){let it=dn(G,{...t,fastpaths:false}).output;D=w.close=`)${it})${I})`;}w.prev.type==="bos"&&(m.negatedExtglob=true);}R({type:"paren",extglob:true,value:f,output:D}),dt("parens");};if(n.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let w=false,j=e.replace(Xo,(b,$,D,G,I,it)=>G==="\\"?(w=true,b):G==="?"?$?$+G+(I?S.repeat(I.length):""):it===0?T+(I?S.repeat(I.length):""):S.repeat(D.length):G==="."?u.repeat(D.length):G==="*"?$?$+G+(I?C:""):C:$?b:`\\${b}`);return w===true&&(n.unescape===true?j=j.replace(/\\/g,""):j=j.replace(/\\+/g,b=>b.length%2===0?"\\\\":b?"\\":"")),j===e&&n.contains===true?(m.output=e,m):(m.output=Y.wrapOutput(j,m,t),m)}for(;!Q();){if(f=B(),f==="\0")continue;if(f==="\\"){let b=L();if(b==="/"&&n.bash!==true||b==="."||b===";")continue;if(!b){f+="\\",R({type:"text",value:f});continue}let $=/^\\+/.exec(lt()),D=0;if($&&$[0].length>2&&(D=$[0].length,m.index+=D,D%2!==0&&(f+="\\")),n.unescape===true?f=B():f+=B(),m.brackets===0){R({type:"text",value:f});continue}}if(m.brackets>0&&(f!=="]"||d.value==="["||d.value==="[^")){if(n.posix!==false&&f===":"){let b=d.value.slice(1);if(b.includes("[")&&(d.posix=true,b.includes(":"))){let $=d.value.lastIndexOf("["),D=d.value.slice(0,$),G=d.value.slice($+2),I=zo[G];if(I){d.value=D+I,m.backtrack=true,B(),!s.output&&o.indexOf(d)===1&&(s.output=y);continue}}}(f==="["&&L()!==":"||f==="-"&&L()==="]")&&(f=`\\${f}`),f==="]"&&(d.value==="["||d.value==="[^")&&(f=`\\${f}`),n.posix===true&&f==="!"&&d.value==="["&&(f="^"),d.value+=f,mt({value:f});continue}if(m.quotes===1&&f!=='"'){f=Y.escapeRegex(f),d.value+=f,mt({value:f});continue}if(f==='"'){m.quotes=m.quotes===1?0:1,n.keepQuotes===true&&R({type:"text",value:f});continue}if(f==="("){me("parens"),R({type:"paren",value:f});continue}if(f===")"){if(m.parens===0&&n.strictBrackets===true)throw new SyntaxError(Rt("opening","("));let b=X[X.length-1];if(b&&m.parens===b.parens+1){Ri(X.pop());continue}R({type:"paren",value:f,output:m.parens?")":"\\)"}),dt("parens");continue}if(f==="["){if(n.nobracket===true||!lt().includes("]")){if(n.nobracket!==true&&n.strictBrackets===true)throw new SyntaxError(Rt("closing","]"));f=`\\${f}`;}else me("brackets");R({type:"bracket",value:f});continue}if(f==="]"){if(n.nobracket===true||d&&d.type==="bracket"&&d.value.length===1){R({type:"text",value:f,output:`\\${f}`});continue}if(m.brackets===0){if(n.strictBrackets===true)throw new SyntaxError(Rt("opening","["));R({type:"text",value:f,output:`\\${f}`});continue}dt("brackets");let b=d.value.slice(1);if(d.posix!==true&&b[0]==="^"&&!b.includes("/")&&(f=`/${f}`),d.value+=f,mt({value:f}),n.literalBrackets===false||Y.hasRegexChars(b))continue;let $=Y.escapeRegex(d.value);if(m.output=m.output.slice(0,-d.value.length),n.literalBrackets===true){m.output+=$,d.value=$;continue}d.value=`(${a}${$}|${d.value})`,m.output+=d.value;continue}if(f==="{"&&n.nobrace!==true){me("braces");let b={type:"brace",value:f,output:"(",outputIndex:m.output.length,tokensIndex:m.tokens.length};x.push(b),R(b);continue}if(f==="}"){let b=x[x.length-1];if(n.nobrace===true||!b){R({type:"text",value:f,output:f});continue}let $=")";if(b.dots===true){let D=o.slice(),G=[];for(let I=D.length-1;I>=0&&(o.pop(),D[I].type!=="brace");I--)D[I].type!=="dots"&&G.unshift(D[I].value);$=Ko(G,n),m.backtrack=true;}if(b.comma!==true&&b.dots!==true){let D=m.output.slice(0,b.outputIndex),G=m.tokens.slice(b.tokensIndex);b.value=b.output="\\{",f=$="\\}",m.output=D;for(let I of G)m.output+=I.output||I.value;}R({type:"brace",value:f,output:$}),dt("braces"),x.pop();continue}if(f==="|"){X.length>0&&X[X.length-1].conditions++,R({type:"text",value:f});continue}if(f===","){let b=f,$=x[x.length-1];$&&P[P.length-1]==="braces"&&($.comma=true,b="|"),R({type:"comma",value:f,output:b});continue}if(f==="/"){if(d.type==="dot"&&m.index===m.start+1){m.start=m.index+1,m.consumed="",m.output="",o.pop(),d=s;continue}R({type:"slash",value:f,output:h});continue}if(f==="."){if(m.braces>0&&d.type==="dot"){d.value==="."&&(d.output=u);let b=x[x.length-1];d.type="dots",d.output+=f,d.value+=f,b.dots=true;continue}if(m.braces+m.parens===0&&d.type!=="bos"&&d.type!=="slash"){R({type:"text",value:f,output:u});continue}R({type:"dot",value:f,output:u});continue}if(f==="?"){if(!(d&&d.value==="(")&&n.noextglob!==true&&L()==="("&&L(2)!=="?"){de("qmark",f);continue}if(d&&d.type==="paren"){let $=L(),D=f;(d.value==="("&&!/[!=<:]/.test($)||$==="<"&&!/<([!=]|\w+>)/.test(lt()))&&(D=`\\${f}`),R({type:"text",value:f,output:D});continue}if(n.dot!==true&&(d.type==="slash"||d.type==="bos")){R({type:"qmark",value:f,output:M});continue}R({type:"qmark",value:f,output:S});continue}if(f==="!"){if(n.noextglob!==true&&L()==="("&&(L(2)!=="?"||!/[!=<:]/.test(L(3)))){de("negate",f);continue}if(n.nonegate!==true&&m.index===0){Ci();continue}}if(f==="+"){if(n.noextglob!==true&&L()==="("&&L(2)!=="?"){de("plus",f);continue}if(d&&d.value==="("||n.regex===false){R({type:"plus",value:f,output:p});continue}if(d&&(d.type==="bracket"||d.type==="paren"||d.type==="brace")||m.parens>0){R({type:"plus",value:f});continue}R({type:"plus",value:p});continue}if(f==="@"){if(n.noextglob!==true&&L()==="("&&L(2)!=="?"){R({type:"at",extglob:true,value:f,output:""});continue}R({type:"text",value:f});continue}if(f!=="*"){(f==="$"||f==="^")&&(f=`\\${f}`);let b=Wo.exec(lt());b&&(f+=b[0],m.index+=b[0].length),R({type:"text",value:f});continue}if(d&&(d.type==="globstar"||d.star===true)){d.type="star",d.star=true,d.value+=f,d.output=C,m.backtrack=true,m.globstar=true,Z(f);continue}let w=lt();if(n.noextglob!==true&&/^\([^?]/.test(w)){de("star",f);continue}if(d.type==="star"){if(n.noglobstar===true){Z(f);continue}let b=d.prev,$=b.prev,D=b.type==="slash"||b.type==="bos",G=$&&($.type==="star"||$.type==="globstar");if(n.bash===true&&(!D||w[0]&&w[0]!=="/")){R({type:"star",value:f,output:""});continue}let I=m.braces>0&&(b.type==="comma"||b.type==="brace"),it=X.length&&(b.type==="pipe"||b.type==="paren");if(!D&&b.type!=="paren"&&!I&&!it){R({type:"star",value:f,output:""});continue}for(;w.slice(0,3)==="/**";){let st=e[m.index+4];if(st&&st!=="/")break;w=w.slice(3),Z("/**",3);}if(b.type==="bos"&&Q()){d.type="globstar",d.value+=f,d.output=v(n),m.output=d.output,m.globstar=true,Z(f);continue}if(b.type==="slash"&&b.prev.type!=="bos"&&!G&&Q()){m.output=m.output.slice(0,-(b.output+d.output).length),b.output=`(?:${b.output}`,d.type="globstar",d.output=v(n)+(n.strictSlashes?")":"|$)"),d.value+=f,m.globstar=true,m.output+=b.output+d.output,Z(f);continue}if(b.type==="slash"&&b.prev.type!=="bos"&&w[0]==="/"){let st=w[1]!==void 0?"|$":"";m.output=m.output.slice(0,-(b.output+d.output).length),b.output=`(?:${b.output}`,d.type="globstar",d.output=`${v(n)}${h}|${h}${st})`,d.value+=f,m.output+=b.output+d.output,m.globstar=true,Z(f+B()),R({type:"slash",value:"/",output:""});continue}if(b.type==="bos"&&w[0]==="/"){d.type="globstar",d.value+=f,d.output=`(?:^|${h}|${v(n)}${h})`,m.output=d.output,m.globstar=true,Z(f+B()),R({type:"slash",value:"/",output:""});continue}m.output=m.output.slice(0,-d.output.length),d.type="globstar",d.output=v(n),d.value+=f,m.output+=d.output,m.globstar=true,Z(f);continue}let j={type:"star",value:f,output:C};if(n.bash===true){j.output=".*?",(d.type==="bos"||d.type==="slash")&&(j.output=N+j.output),R(j);continue}if(d&&(d.type==="bracket"||d.type==="paren")&&n.regex===true){j.output=f,R(j);continue}(m.index===m.start||d.type==="slash"||d.type==="dot")&&(d.type==="dot"?(m.output+=A,d.output+=A):n.dot===true?(m.output+=q,d.output+=q):(m.output+=N,d.output+=N),L()!=="*"&&(m.output+=y,d.output+=y)),R(j);}for(;m.brackets>0;){if(n.strictBrackets===true)throw new SyntaxError(Rt("closing","]"));m.output=Y.escapeLast(m.output,"["),dt("brackets");}for(;m.parens>0;){if(n.strictBrackets===true)throw new SyntaxError(Rt("closing",")"));m.output=Y.escapeLast(m.output,"("),dt("parens");}for(;m.braces>0;){if(n.strictBrackets===true)throw new SyntaxError(Rt("closing","}"));m.output=Y.escapeLast(m.output,"{"),dt("braces");}if(n.strictSlashes!==true&&(d.type==="star"||d.type==="bracket")&&R({type:"maybe_slash",value:"",output:`${h}?`}),m.backtrack===true){m.output="";for(let w of m.tokens)m.output+=w.output!=null?w.output:w.value,w.suffix&&(m.output+=w.suffix);}return m};dn.fastpaths=(e,t)=>{let n={...t},r=typeof n.maxLength=="number"?Math.min(Fe,n.maxLength):Fe,i=e.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);e=Cr[e]||e;let{DOT_LITERAL:s,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:l,NO_DOT:c,NO_DOTS:u,NO_DOTS_SLASH:p,STAR:h,START_ANCHOR:y}=Vt.globChars(n.windows),g=n.dot?u:c,E=n.dot?p:c,A=n.capture?"":"?:",q={negated:false,prefix:""},S=n.bash===true?".*?":h;n.capture&&(S=`(${S})`);let M=N=>N.noglobstar===true?S:`(${A}(?:(?!${y}${N.dot?l:s}).)*?)`,W=N=>{switch(N){case "*":return `${g}${a}${S}`;case ".*":return `${s}${a}${S}`;case "*.*":return `${g}${S}${s}${a}${S}`;case "*/*":return `${g}${S}${o}${a}${E}${S}`;case "**":return g+M(n);case "**/*":return `(?:${g}${M(n)}${o})?${E}${a}${S}`;case "**/*.*":return `(?:${g}${M(n)}${o})?${E}${S}${s}${a}${S}`;case "**/.*":return `(?:${g}${M(n)}${o})?${s}${a}${S}`;default:{let T=/^(.*?)\.(\w+)$/.exec(N);if(!T)return;let C=W(T[1]);return C?C+s+T[2]:void 0}}},O=Y.removePrefix(e,q),v=W(O);return v&&n.strictSlashes!==true&&(v+=`${o}?`),v};vr.exports=dn;});var Lr=bt((vf,Pr)=>{var ea=_r(),hn=Nr(),kr=Ht(),na=Mt(),ra=e=>e&&typeof e=="object"&&!Array.isArray(e),H=(e,t,n=false)=>{if(Array.isArray(e)){let u=e.map(h=>H(h,t,n));return h=>{for(let y of u){let g=y(h);if(g)return g}return false}}let r=ra(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!r)throw new TypeError("Expected pattern to be a non-empty string");let i=t||{},s=i.windows,o=r?H.compileRe(e,t):H.makeRe(e,t,false,true),a=o.state;delete o.state;let l=()=>false;if(i.ignore){let u={...t,ignore:null,onMatch:null,onResult:null};l=H(i.ignore,u,n);}let c=(u,p=false)=>{let{isMatch:h,match:y,output:g}=H.test(u,o,t,{glob:e,posix:s}),E={glob:e,state:a,regex:o,posix:s,input:u,output:g,match:y,isMatch:h};return typeof i.onResult=="function"&&i.onResult(E),h===false?(E.isMatch=false,p?E:false):l(u)?(typeof i.onIgnore=="function"&&i.onIgnore(E),E.isMatch=false,p?E:false):(typeof i.onMatch=="function"&&i.onMatch(E),p?E:true)};return n&&(c.state=a),c};H.test=(e,t,n,{glob:r,posix:i}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return {isMatch:false,output:""};let s=n||{},o=s.format||(i?kr.toPosixSlashes:null),a=e===r,l=a&&o?o(e):e;return a===false&&(l=o?o(e):e,a=l===r),(a===false||s.capture===true)&&(s.matchBase===true||s.basename===true?a=H.matchBase(e,t,n,i):a=t.exec(l)),{isMatch:!!a,match:a,output:l}};H.matchBase=(e,t,n)=>(t instanceof RegExp?t:H.makeRe(t,n)).test(kr.basename(e));H.isMatch=(e,t,n)=>H(t,n)(e);H.parse=(e,t)=>Array.isArray(e)?e.map(n=>H.parse(n,t)):hn(e,{...t,fastpaths:false});H.scan=(e,t)=>ea(e,t);H.compileRe=(e,t,n=false,r=false)=>{if(n===true)return e.output;let i=t||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${e.output})${o}`;e&&e.negated===true&&(a=`^(?!${a}).*$`);let l=H.toRegex(a,t);return r===true&&(l.state=e),l};H.makeRe=(e,t={},n=false,r=false)=>{if(!e||typeof e!="string")throw new TypeError("Expected a non-empty string");let i={negated:false,fastpaths:true};return t.fastpaths!==false&&(e[0]==="."||e[0]==="*")&&(i.output=hn.fastpaths(e,t)),i.output||(i=hn(e,t)),H.compileRe(i,t,n,r)};H.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 /$^/}};H.constants=na;Pr.exports=H;});var Dr=bt((Nf,Ir)=>{var Or=Lr(),ia=Ht();function Fr(e,t,n=false){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:ia.isWindows()}),Or(e,t,n)}Object.assign(Fr,Or);Ir.exports=Fr;});function Kt(e){if("String"in e)return e.String.sval}function gt(e){return e.map(Kt).filter(t=>t!=null)}function Jr(e){return Object.keys(e)[0]}function Yr(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 je=F(()=>{});function Qr(e){let t=e.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(t)}function Zr(e){let t=e.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(t)}function ti(e){let t=e.toLowerCase();return ["numeric","decimal"].includes(t)}var bn,Be,Va,wn=F(()=>{je();bn=class extends Error{},Be=class extends bn{constructor(n,r){super(r??`Unsupported node type: ${Jr(n)}`);this.node=n;}};Va={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"}},new Map(Object.entries(Va));});var tt,Ue,ei=F(()=>{je();wn();tt=class extends Be{constructor(t,n){super(t,`Unsupported expression: ${n}`);}},Ue=class{deparse(t){if("A_Const"in t){let i=t.A_Const;if(i.boolval!==void 0)return i.boolval.boolval?{}:{$always:false}}let n=Object.keys(t)[0],r=this[n];if(!r)throw new tt({[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 tt({[n]:t},`deparseValue: ${n}`)}A_Expr(t){if(t.kind==="AEXPR_OP"){let n=t.name?.[0],r=n?Kt(n):void 0;if(!r)throw new tt({A_Expr:t},"A_Expr missing operator");let i=this.isJwtAccessor(t);if(i)return {[i]:{}};let s=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 tt({A_Expr:t},`Unsupported operator: ${r}`);let l=t.rexpr!=null&&"ColumnRef"in t.rexpr;if(typeof s=="string"&&s.startsWith("{{")&&l)return {[o]:{[a]:s}};let c=l&&typeof o=="string"?{$ref:o}:o;return {[s]:{[a]:c}}}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,s=(t.name?.[0]?Kt(t.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[n]:{[s]: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(i=>this.deparseValue(i)):[];return {[n]:{$in:r}}}throw new tt({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 tt({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],i="ResTarget"in r?r.ResTarget:void 0;if(i?.val){let s=this.deparseValue(i.val);return s}}}throw new tt({SubLink:t},`SubLink type: ${t.subLinkType}`)}SelectStmt(t){let{from:n,schema:r,join:i}=this.deparseFromClause(t.fromClause??[]),s=[];for(let h of t.targetList??[]){let y="ResTarget"in h?h.ResTarget:void 0;if(y?.val){let g=this.deparseValue(y.val);Array.isArray(g)?s.push(...g.map(String)):g!=null&&g!==""&&s.push(String(g));}}let o=t.whereClause?this.deparse(t.whereClause):void 0,a=this.deparseSortClause(t.sortClause),l=this.deparseLimit(t.limitCount),c=this.deparseLimit(t.limitOffset),u=this.deparseGroupClause(t.groupClause),p={type:"query",from:n,select:s};return r&&(p.schema=r),Object.keys(i).length>0&&(p.join=i),o&&(p.where=o),a.length>0&&(p.order=a),l!==void 0&&(p.limit=l),c!==void 0&&(p.offset=c),u.length>0&&(p.group=u),p}FuncCall(t){let n=this.isAuthFunc(t.funcname??[]);if(n)return n;throw new tt({FuncCall:t},`FuncCall: ${gt(t.funcname??[]).join(".")}`)}ColumnRef(t){let n=gt(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 tt({A_Const:t},"A_Const: unknown variant")}TypeCast(t){if(!t.arg)throw new tt({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 i=r.RangeVar;return {from:i.relname??"",schema:i.schemaname,join:n}}if("JoinExpr"in r){let{from:i,schema:s}=this.walkJoinExpr(r.JoinExpr,n);return {from:i,schema:s,join:n}}return {from:"",join:n}}walkJoinExpr(t,n){let r={from:""};if(t.larg)if("RangeVar"in t.larg){let i=t.larg.RangeVar;r={from:i.relname??"",schema:i.schemaname};}else "JoinExpr"in t.larg&&(r=this.walkJoinExpr(t.larg.JoinExpr,n));if(t.rarg&&"RangeVar"in t.rarg){let i=t.rarg.RangeVar,s=i.relname??"",o=i.alias?.aliasname??s,a=t.jointype==="JOIN_LEFT"?"left":"inner",l={from:s,type:a};t.quals&&(l.on=this.deparse(t.quals));let c=o;if(c in n){let u=2;for(;`${c}_${u}`in n;)u++;c=`${c}_${u}`;}n[c]=l;}return r}deparseSortClause(t){if(!t)return [];let n=[];for(let r of t){if(!("SortBy"in r))continue;let i=r.SortBy;if(!i.node)continue;let s=String(this.deparseValue(i.node)),o=i.sortby_dir==="SORTBY_DESC"?"desc":"asc",a={column:s,direction:o};i.sortby_nulls==="SORTBY_NULLS_FIRST"?a.nullsFirst=true:i.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=gt(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]?Kt(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 i=this.isJwtAccessor(t.lexpr.A_Expr);if(i)return `${i.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 vt,ni=F(()=>{vt=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 Jt,xn=F(()=>{Jt=class extends Error{constructor(n,r,i,s){super(`check constraint "${i}" violated for ${n}.${r}`);this.table=n;this.column=r;this.constraint=i;this.value=s;this.name="CheckConstraintError";}};});var z,pt=F(()=>{xn();z=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,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=[],i=this.context.column;r.push(this.quoteIfNeeded(i)),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 s=this.checkConstraint();return s&&r.push(`CHECK (${s})`),r.join(" ")}checkError(t,n){return new Jt(this.context.table,this.context.column,t,n)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var Et,Me=F(()=>{pt();Et=class extends z{get sqliteType(){return "INTEGER"}};});var Yt,Sn=F(()=>{Me();Yt=class extends Et{constructor(t){super({...t,isSerial:true});}};});function Ga(e,t){let{precision:n,scale:r}=t,i=10**r,s=10**(n-r);return Math.abs(Math.round(e*i)-e*i)<1e-4&&Math.abs(e)<s}var Qt,En=F(()=>{pt();Qt=class extends z{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,i=10**n,s=10**(t-n);return `ABS(ROUND(${r} * ${i}) - ${r} * ${i}) < 0.0001 AND ABS(${r}) < ${s}`}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(!Ga(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var U,nt=F(()=>{pt();U=class extends z{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 Zt,Tn=F(()=>{pt();Zt=class extends z{get sqliteType(){return "BLOB"}};});var te,An=F(()=>{pt();te=class extends z{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 ri(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var ee,_n=F(()=>{pt();ee=class extends z{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=ri(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."):ri(t).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function za(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 ne,Cn=F(()=>{nt();ne=class extends U{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"||!za(t)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function Wa(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]),i=t[3]===void 0?0:Number(t[3]),s=t[5]===void 0?null:Number(t[5]),o=t[6]===void 0?null:Number(t[6]),a=s===null||o!==null&&s<=15&&o<=59;return n<=24&&r<=59&&i<=59&&(n!==24||r===0&&i===0)&&a}var re,Rn=F(()=>{nt();re=class extends U{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"||!Wa(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function Xa(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]),i=Number(t[3]),s=Number(t[4]),o=Number(t[5]),a=t[6]===void 0?0:Number(t[6]),l=t[8]===void 0?null:Number(t[8]),c=t[9]===void 0?null:Number(t[9]),u=new Date(Date.UTC(n,r-1,i)),p=u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===i,h=s<=24&&o<=59&&a<=59&&(s!==24||o===0&&a===0),y=l===null||c!==null&&l<=15&&c<=59;return p&&h&&y}var ie,$n=F(()=>{nt();ie=class extends U{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"||!Xa(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var se,vn=F(()=>{nt();se=class extends U{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 oe,Nn=F(()=>{nt();oe=class extends U{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 ii(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var Nt,kn=F(()=>{pt();Nt=class extends z{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=ii(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=ii(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 i=this.elementField.validateStorage(r);if(i.status==="fail")return this.validationFail(`Invalid ${this.elementField.context.pgTypeName} array element.`,i.action??"Patch rows with valid array elements.")}return this.validationPass()}};});function si(e){return Ja.test(e.toLowerCase())}var Ka,Ja,ae,Pn=F(()=>{nt();Ka="????????-????-????-????-????????????",Ja=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;ae=class extends U{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${Ka}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let n=t.toLowerCase();if(!si(n))throw this.checkError("uuid_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!si(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function Ya(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 Qa(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 Za(e){if(!e.includes(":"))return false;try{return new URL(`http://[${e}]/`),!0}catch{return false}}function oi(e){let t=Ya(e);return t?Qa(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:Za(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var le,Ln=F(()=>{nt();le=class extends U{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(!oi(n))throw this.checkError("inet_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!oi(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var ce,On=F(()=>{nt();ce=class extends U{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 ue(e,t){if(t?.isArray){let r=ue(e,{...t,isArray:false});return new Nt(e,r)}if(t?.enumValues)return new oe(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),i={...e,pgTypeName:r},s=ue(i);return new Nt(e,s)}return el.has(n)?new Yt(e):tl.has(n)?new Et(e):sl.has(n)?new te(e):ol.has(n)?new ee(e):ul.has(n)?new ne(e):fl.has(n)?new re(e):pl.has(n)?new ie(e):ml.has(n)?new se(e):il.has(n)?new Zt(e):nl.has(n)?new Qt(e,t?.numericPrecision):al.has(n)?new ae(e):ll.has(n)?new U(e,63):cl.has(n)?new le(e):rl.has(n)?new U(e,t?.lengthConstraint):new ce(e)}var tl,el,nl,rl,il,sl,ol,al,ll,cl,ul,fl,pl,ml,ai=F(()=>{Me();Sn();En();nt();Tn();An();_n();Cn();Rn();$n();vn();Nn();kn();Pn();Ln();On();tl=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),el=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),nl=new Set(["float4","real","float8","double precision","numeric","decimal"]),rl=new Set(["text","varchar","character varying","char","character","bpchar"]),il=new Set(["bytea"]),sl=new Set(["bool","boolean"]),ol=new Set(["json","jsonb"]),al=new Set(["uuid"]),ll=new Set(["name"]),cl=new Set(["inet"]),ul=new Set(["date"]),fl=new Set(["time","timetz","time without time zone","time with time zone"]),pl=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),ml=new Set(["interval"]);});var li=F(()=>{});var fe,ci=F(()=>{fe=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,i]of Object.entries(t)){let s=this.fields.get(r);n[r]=s?s.serialize(i):i;}return n}deserializeRow(t){let n={};for(let[r,i]of Object.entries(t)){let s=this.fields.get(r);n[r]=s?s.deserialize(i):i;}return n}applyDefaults(t){let n={...t};for(let[r,i]of this.fields)!(r in n)&&i.context.defaultFn&&(n[r]=i.context.defaultFn());return n}};});var ui=F(()=>{pt();xn();Me();Sn();En();nt();Tn();An();_n();Cn();Rn();$n();vn();Nn();kn();Pn();Ln();On();ai();li();ci();});var mi={};Li(mi,{_resetWarnedMissingToClauseForTests:()=>dl,collectComments:()=>xl,collectEnums:()=>hl,collectPolicies:()=>yl,collectSchema:()=>bl,collectTableConstraints:()=>wl,collectVariables:()=>gl});function dl(){Dn.clear();}function hl(e){let t=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("CreateEnumStmt"in n.stmt))continue;let r=n.stmt.CreateEnumStmt,i=gt(r.typeName??[]).join(".");if(!i||!r.vals)continue;let s=gt(r.vals);t.set(i.toLowerCase(),s);}return t}function gl(e){let t=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("VariableSetStmt"in n.stmt))continue;let r=n.stmt.VariableSetStmt,i=r.name,s=Yr(r.args?.[0]??{});t.set(i,{value:s,local:r.is_local});}return t}function fi(e){let t=[],n=false;for(let r of e??[])if("RoleSpec"in r){let i=r.RoleSpec;i.roletype==="ROLESPEC_PUBLIC"?i.location===-1&&(n=true):i.roletype==="ROLESPEC_CSTRING"&&i.rolename&&t.push(i.rolename);}return {roles:t,implicitPublic:n}}function pi(e,t){return e&&e.length>0?e:t}function Fn(e,t,n){return e.findIndex(r=>r.data.name===t.name&&r.data.table===t.table&&pi(r.data.schema,n)===pi(t.schema,n))}function In(e,t){return new Error(`policy "${e}" for table "${t}" does not exist`)}function yl(e,t={}){let n=t.defaultSchema||"public",r=t.validateMutations===true,i=new Ue,s=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??"",u=l.table?.schemaname,p={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},h=l.cmd_name?p[l.cmd_name]??"ALL":"ALL",y=l.permissive===true,{roles:g,implicitPublic:E}=fi(l.roles),A=l.qual?i.deparse(l.qual):void 0,q=l.with_check?i.deparse(l.with_check):void 0;if(E){let M=u?`${u}.${c}`:c,W=l.policy_name??"",O=`${M}::${W}`;if(!Dn.has(O)){Dn.add(O);let v=JSON.stringify(A)+JSON.stringify(q);/\{\{auth\.(uid|jwt|role)/i.test(v)||console.warn(`[supalite] policy "${W}" on "${M}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let S=new vt({name:l.policy_name??"",table:c,schema:u,command:h,permissive:y,roles:g,using:A,withCheck:q});o.push(S);}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 u=gt(c.List.items??[]),p=u[u.length-1],h=u[u.length-2],y=u.length>=3?u[u.length-3]:void 0;if(p&&h){let g=Fn(o,{name:p,table:h,schema:y},n);if(g!==-1)o.splice(g,1);else if(r&&!l.missing_ok)throw In(p,h)}}}if("AlterPolicyStmt"in a.stmt){let l=a.stmt.AlterPolicyStmt,c=l.policy_name??"",u=l.table?.relname??"",p=l.table?.schemaname,h=Fn(o,{name:c,table:u,schema:p},n);if(h===-1){if(r)throw In(c,u);continue}let y=o[h].data,g=l.roles?fi(l.roles).roles:y.roles,E=l.qual?i.deparse(l.qual):y.using,A=l.with_check?i.deparse(l.with_check):y.withCheck;o[h]=new vt({...y,roles:g,using:E,withCheck:A});}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_POLICY"){let l=a.stmt.RenameStmt,c=l.subname??"",u=l.relation?.relname??"",p=l.relation?.schemaname,h=Fn(o,{name:c,table:u,schema:p},n);if(h===-1){if(r)throw In(c,u);continue}l.newname&&(o[h]=new vt({...o[h].data,name:l.newname}));}if("AlterTableStmt"in a.stmt){let l=a.stmt.AlterTableStmt;if((l.cmds??[]).some(p=>"AlterTableCmd"in p&&(p.AlterTableCmd.subtype==="AT_EnableRowSecurity"||p.AlterTableCmd.subtype==="AT_ForceRowSecurity"))){let p=l.relation?.relname??"";s.add(p);}}}return {policies:o,tables:s}}function bl(e,t){let n=new Map;for(let r of e.stmts??[]){if(!r.stmt||!("CreateStmt"in r.stmt))continue;let i=r.stmt.CreateStmt,s=i.relation?.relname??"",o=i.relation?.schemaname??"public";if(!s)continue;let a=new fe(s,o);for(let l of i.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,u=c.colname;if(!u)continue;let p=c.typeName?.names?.map(x=>x.String?.sval||x.String?.str).filter(Boolean),h=p&&(p.length===2&&p[0]==="pg_catalog"?p[1]:p[0]);if(!h)continue;let y=!!c.typeName?.arrayBounds?.length,g=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],E=x=>g[x]?.A_Const?.ival?.ival??g[x]?.A_Const?.val?.ival?.ival,A={isArray:y};if(Zr(h)&&g.length>0){let x=E(0);typeof x=="number"&&x>0&&(A.lengthConstraint=x);}if(ti(h)&&g.length>=2){let x=E(0),P=E(1);typeof x=="number"&&typeof P=="number"&&x>0&&P>=0&&(A.numericPrecision={precision:x,scale:P});}let q=t.get(h.toLowerCase());q&&(A.enumValues=q);let S=Array.isArray(c.constraints)?c.constraints:[],M=S.some(x=>x.Constraint?.contype==="CONSTR_PRIMARY"),W=Qr(h)||S.some(x=>x.Constraint?.contype==="CONSTR_IDENTITY"),O=S.some(x=>x.Constraint?.contype==="CONSTR_NOTNULL"),v=S.find(x=>x.Constraint?.contype==="CONSTR_UNIQUE"),N=S.find(x=>x.Constraint?.contype==="CONSTR_GENERATED"),T=S.find(x=>x.Constraint?.contype==="CONSTR_FOREIGN"),C=S.find(x=>x.Constraint?.contype==="CONSTR_CHECK"),m;if(T){let x=T.Constraint,P=x.pktable?.relname,d=x.pktable?.schemaname,f=x.pk_attrs?.[0]?.String?.sval;P&&f&&(m={refSchema:d,refTable:P,refColumn:f,constraintName:x.conname||void 0});}let X={schema:o,table:s,column:u,pgTypeName:h,nullable:!O&&!M,defaultValue:null,defaultFn:null,isPrimaryKey:M,isUnique:!!v,isSerial:W,isGenerated:!!N,fkRef:m,hasCheck:!!C,checkConstraintName:C?.Constraint?.conname||void 0,uniqueConstraintName:v?.Constraint?.conname||void 0};a.set(u,ue(X,A));}n.set(`${o}.${s}`,a);}return n}function wl(e){let t=[];for(let n of e.stmts??[]){if(!n.stmt||!("CreateStmt"in n.stmt))continue;let r=n.stmt.CreateStmt,i=r.relation?.relname??"",s=r.relation?.schemaname??"public";if(i)for(let o of r.tableElts??[]){if("ColumnDef"in o)continue;let a=o;if(!a.Constraint)continue;let l=a.Constraint,c=l.contype;if(c==="CONSTR_UNIQUE"){let u=(l.keys??[]).map(p=>p.String?.sval??p.String?.str).filter(Boolean);if(u.length===0)continue;t.push({schema:s,table:i,kind:"unique",name:l.conname||void 0,columns:u});}else if(c==="CONSTR_CHECK")t.push({schema:s,table:i,kind:"check",name:l.conname||void 0,columns:[]});else if(c==="CONSTR_FOREIGN"){let u=(l.fk_attrs??[]).map(y=>y.String?.sval??y.String?.str).filter(Boolean),p=(l.pk_attrs??[]).map(y=>y.String?.sval??y.String?.str).filter(Boolean),h=l.pktable?.relname;if(!h)continue;t.push({schema:s,table:i,kind:"foreign_key",name:l.conname||void 0,columns:u,refSchema:l.pktable?.schemaname,refTable:h,refColumns:p});}}}return t}function xl(e){let t=[];for(let n of e.stmts??[]){if(!n.stmt||!("CommentStmt"in n.stmt))continue;let r=n.stmt.CommentStmt,i=r.comment??"";if(!i)continue;let s=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(s==="OBJECT_TABLE"||s==="OBJECT_VIEW"){let[a,l]=o.length>=2?o:["public",o[0]];t.push({schema:a,table:l,text:i});}else if(s==="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:i});}}}return t}var Dn,di=F(()=>{ei();je();ni();ui();wn();Dn=new Set;});process.stdin.isTTY?null:(async()=>{let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")})();function et(e,t){he.existsSync(e)||(he.mkdirSync(e,{recursive:true}),t?.());}function wt(e,t,n){he.existsSync(e)||(he.writeFileSync(e,t),n?.());}var ut=class e{root;constructor(t,n){let r=n??e.projectDir();this.root=at__default.join(r,t??"");}ensureRoot(){et(this.root);}static homeDir(){return at__default.join(Ii.homedir(),".lite")}static projectDir(){return at__default.join(process.cwd(),"supabase")}deleteAll(t=false){try{he.rmSync(this.root,{recursive:!0});}catch(n){if(!t)throw n}this.ensureRoot();}delete(t,n=false){try{he.unlinkSync(at__default.join(this.root,t));}catch(r){if(!n)throw r}}write(t,n,r=false){try{this.ensureRoot(),he.writeFileSync(at__default.join(this.root,t),n);}catch(i){if(!r)throw i}}read(t,n=false){try{return he.readFileSync(at__default.join(this.root,t),"utf8")}catch(r){if(!n)throw r}}relativePath(t){return t?at__default.relative(process.cwd(),at__default.join(this.root,t)):this.root}path(t){return t?at__default.join(this.root,t):this.root}};var Pt=process.env.SUPALITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2000":"https://www.lite.dev");var be=class{root;constructor(t){this.root=t??at__default.join(Ii.homedir(),".lite","auth"),et(this.root);}async getItem(t){try{return he.readFileSync(at__default.join(this.root,t+".json"),"utf8")}catch{return null}}async setItem(t,n){he.writeFileSync(at__default.join(this.root,t+".json"),n);}async removeItem(t){try{he.unlinkSync(at__default.join(this.root,t+".json"));}catch{return}}};var Tt=class{constructor(t){this.config=t;this.tempFs=new ut(".temp",this.config.root),this.projectFs=new ut("supabase",this.config.root),this.schemaFs=new ut("schemas",this.config.root),this.authStorage=this.config.authStorage??new be(at__default.join(ut.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??Pt,process.env.SUPALITE_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??Pt);return await fetch(r,{...n,headers:{...n?.headers,Authorization:`Bearer ${this.config.token}`}})}};var At=class extends Tt{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.host),i=r.hostname==="localhost"?"supalite.local":r.hostname,s=i.split(".").filter(a=>a!=="www"),o=s.length>=2?s.slice(-2).join("."):i;return `${r.protocol}//${n}.${o}${r.port?`:${r.port}`:""}`}};var ot={config_dir:"supabase",default_db_url:"file:supabase/.temp/data.db",default_db_dir:"supabase/.temp/data"};var Ut=kt(Lt());function qi(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return [n.length,n.pop().length+1]}function Vi(e,t,n){let r=e.split(/\r\n|\n|\r/g),i="",s=(Math.log10(t+1)|0)+1;for(let o=t-1;o<=t+1;o++){let a=r[o-1];a&&(i+=o.toString().padEnd(s," "),i+=": ",i+=a,i+=`
12
+ var $i=Object.create;var He=Object.defineProperty;var vi=Object.getOwnPropertyDescriptor;var Ni=Object.getOwnPropertyNames;var ki=Object.getPrototypeOf,Pi=Object.prototype.hasOwnProperty;var F=(e,t)=>()=>(e&&(t=e(e=0)),t);var bt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Li=(e,t)=>{for(var n in t)He(e,n,{get:t[n],enumerable:true});},Oi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ni(t))!Pi.call(e,i)&&i!==n&&He(e,i,{get:()=>t[i],enumerable:!(r=vi(t,i))||r.enumerable});return e};var kt=(e,t,n)=>(n=e!=null?$i(ki(e)):{},Oi(He(n,"default",{value:e,enumerable:true}),e));var Lt=bt((bc,Ve)=>{var xe=process||{},qn=xe.argv||[],we=xe.env||{},Ui=!(we.NO_COLOR||qn.includes("--no-color"))&&(!!we.FORCE_COLOR||qn.includes("--color")||xe.platform==="win32"||(xe.stdout||{}).isTTY&&we.TERM!=="dumb"||!!we.CI),Mi=(e,t,n=e)=>r=>{let i=""+r,s=i.indexOf(t,e.length);return ~s?e+Hi(i,t,n,s)+t:e+i+t},Hi=(e,t,n,r)=>{let i="",s=0;do i+=e.substring(s,r)+n,s=r+t.length,r=e.indexOf(t,s);while(~r);return i+e.substring(s)},Vn=(e=Ui)=>{let t=e?Mi:()=>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")}};Ve.exports=Vn();Ve.exports.createColors=Vn;});var Mt=bt((_f,yr)=>{var mr="[^\\\\/]",_o="(?=.)",hr="[^/]",on="(?:\\/|$)",dr="(?:^|\\/)",an=`\\.{1,2}${on}`,Co="(?!\\.)",Ro=`(?!${dr}${an})`,$o=`(?!\\.{0,1}${on})`,vo=`(?!${an})`,No="[^.\\/]",ko=`${hr}*?`,Po="/",gr={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:_o,QMARK:hr,END_ANCHOR:on,DOTS_SLASH:an,NO_DOT:Co,NO_DOTS:Ro,NO_DOT_SLASH:$o,NO_DOTS_SLASH:vo,QMARK_NO_DOT:No,STAR:ko,START_ANCHOR:dr,SEP:Po},Lo={...gr,SLASH_LITERAL:"[\\\\/]",QMARK:mr,STAR:`${mr}*?`,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:"\\"},Oo={__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"};yr.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:Oo,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?Lo:gr}};});var Ht=bt(J=>{var{REGEX_BACKSLASH:Fo,REGEX_REMOVE_BACKSLASH:Io,REGEX_SPECIAL_CHARS:Do,REGEX_SPECIAL_CHARS_GLOBAL:jo}=Mt();J.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);J.hasRegexChars=e=>Do.test(e);J.isRegexChar=e=>e.length===1&&J.hasRegexChars(e);J.escapeRegex=e=>e.replace(jo,"\\$1");J.toPosixSlashes=e=>e.replace(Fo,"/");J.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};J.removeBackslashes=e=>e.replace(Io,t=>t==="\\"?"":t);J.escapeLast=(e,t,n)=>{let r=e.lastIndexOf(t,n);return r===-1?e:e[r-1]==="\\"?J.escapeLast(e,t,r-1):`${e.slice(0,r)}\\${e.slice(r)}`};J.removePrefix=(e,t={})=>{let n=e;return n.startsWith("./")&&(n=n.slice(2),t.prefix="./"),n};J.wrapOutput=(e,t={},n={})=>{let r=n.contains?"":"^",i=n.contains?"":"$",s=`${r}(?:${e})${i}`;return t.negated===true&&(s=`(?:^(?!${s}).*$)`),s};J.basename=(e,{windows:t}={})=>{let n=e.split(t?/[\\/]/:"/"),r=n[n.length-1];return r===""?n[n.length-2]:r};});var _r=bt((Rf,Ar)=>{var br=Ht(),{CHAR_ASTERISK:ln,CHAR_AT:Bo,CHAR_BACKWARD_SLASH:qt,CHAR_COMMA:Uo,CHAR_DOT:cn,CHAR_EXCLAMATION_MARK:un,CHAR_FORWARD_SLASH:Tr,CHAR_LEFT_CURLY_BRACE:fn,CHAR_LEFT_PARENTHESES:pn,CHAR_LEFT_SQUARE_BRACKET:Mo,CHAR_PLUS:Ho,CHAR_QUESTION_MARK:wr,CHAR_RIGHT_CURLY_BRACE:qo,CHAR_RIGHT_PARENTHESES:xr,CHAR_RIGHT_SQUARE_BRACKET:Vo}=Mt(),Sr=e=>e===Tr||e===qt,Er=e=>{e.isPrefix!==true&&(e.depth=e.isGlobstar?1/0:1);},Go=(e,t)=>{let n=t||{},r=e.length-1,i=n.parts===true||n.scanToEnd===true,s=[],o=[],a=[],l=e,c=-1,u=0,p=0,d=false,y=false,g=false,E=false,A=false,q=false,S=false,M=false,W=false,O=false,v=0,N,T,C={value:"",depth:0,isGlob:false},m=()=>c>=r,X=()=>l.charCodeAt(c+1),x=()=>(N=T,l.charCodeAt(++c));for(;c<r;){T=x();let L;if(T===qt){S=C.backslashes=true,T=x(),T===fn&&(q=true);continue}if(q===true||T===fn){for(v++;m()!==true&&(T=x());){if(T===qt){S=C.backslashes=true,x();continue}if(T===fn){v++;continue}if(q!==true&&T===cn&&(T=x())===cn){if(d=C.isBrace=true,g=C.isGlob=true,O=true,i===true)continue;break}if(q!==true&&T===Uo){if(d=C.isBrace=true,g=C.isGlob=true,O=true,i===true)continue;break}if(T===qo&&(v--,v===0)){q=false,d=C.isBrace=true,O=true;break}}if(i===true)continue;break}if(T===Tr){if(s.push(c),o.push(C),C={value:"",depth:0,isGlob:false},O===true)continue;if(N===cn&&c===u+1){u+=2;continue}p=c+1;continue}if(n.noext!==true&&(T===Ho||T===Bo||T===ln||T===wr||T===un)===true&&X()===pn){if(g=C.isGlob=true,E=C.isExtglob=true,O=true,T===un&&c===u&&(W=true),i===true){for(;m()!==true&&(T=x());){if(T===qt){S=C.backslashes=true,T=x();continue}if(T===xr){g=C.isGlob=true,O=true;break}}continue}break}if(T===ln){if(N===ln&&(A=C.isGlobstar=true),g=C.isGlob=true,O=true,i===true)continue;break}if(T===wr){if(g=C.isGlob=true,O=true,i===true)continue;break}if(T===Mo){for(;m()!==true&&(L=x());){if(L===qt){S=C.backslashes=true,x();continue}if(L===Vo){y=C.isBracket=true,g=C.isGlob=true,O=true;break}}if(i===true)continue;break}if(n.nonegate!==true&&T===un&&c===u){M=C.negated=true,u++;continue}if(n.noparen!==true&&T===pn){if(g=C.isGlob=true,i===true){for(;m()!==true&&(T=x());){if(T===pn){S=C.backslashes=true,T=x();continue}if(T===xr){O=true;break}}continue}break}if(g===true){if(O=true,i===true)continue;break}}n.noext===true&&(E=false,g=false);let P=l,h="",f="";u>0&&(h=l.slice(0,u),l=l.slice(u),p-=u),P&&g===true&&p>0?(P=l.slice(0,p),f=l.slice(p)):g===true?(P="",f=l):P=l,P&&P!==""&&P!=="/"&&P!==l&&Sr(P.charCodeAt(P.length-1))&&(P=P.slice(0,-1)),n.unescape===true&&(f&&(f=br.removeBackslashes(f)),P&&S===true&&(P=br.removeBackslashes(P)));let Q={prefix:h,input:e,start:u,base:P,glob:f,isBrace:d,isBracket:y,isGlob:g,isExtglob:E,isGlobstar:A,negated:M,negatedExtglob:W};if(n.tokens===true&&(Q.maxDepth=0,Sr(T)||o.push(C),Q.tokens=o),n.parts===true||n.tokens===true){let L;for(let B=0;B<s.length;B++){let lt=L?L+1:u,Z=s[B],mt=e.slice(lt,Z);n.tokens&&(B===0&&u!==0?(o[B].isPrefix=true,o[B].value=h):o[B].value=mt,Er(o[B]),Q.maxDepth+=o[B].depth),(B!==0||mt!=="")&&a.push(mt),L=Z;}if(L&&L+1<e.length){let B=e.slice(L+1);a.push(B),n.tokens&&(o[o.length-1].value=B,Er(o[o.length-1]),Q.maxDepth+=o[o.length-1].depth);}Q.slashes=s,Q.parts=a;}return Q};Ar.exports=Go;});var Nr=bt(($f,vr)=>{var Vt=Mt(),Y=Ht(),{MAX_LENGTH:Fe,POSIX_REGEX_SOURCE:zo,REGEX_NON_SPECIAL_CHARS:Wo,REGEX_SPECIAL_CHARS_BACKREF:Xo,REPLACEMENTS:Cr}=Vt,Ko=(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(i=>Y.escapeRegex(i)).join("..")}return n},Rt=(e,t)=>`Missing ${e}: "${t}" - use "\\\\${t}" to match literal characters`,Rr=e=>{let t=[],n=0,r=0,i=0,s="",o=false;for(let a of e){if(o===true){s+=a,o=false;continue}if(a==="\\"){s+=a,o=true;continue}if(a==='"'){i=i===1?0:1,s+=a;continue}if(i===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(s),s="";continue}}}s+=a;}return t.push(s),t},Jo=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},$r=e=>{let t=e.trim(),n=true;for(;n===true;)n=false,/^@\([^\\()[\]{}|]+\)$/.test(t)&&(t=t.slice(2,-1),n=true);if(Jo(t))return t.replace(/\\(.)/g,"$1")},Yo=e=>{let t=e.map($r).filter(Boolean);for(let n=0;n<t.length;n++)for(let r=n+1;r<t.length;r++){let i=t[n],s=t[r],o=i[0];if(!(!o||i!==o.repeat(i.length)||s!==o.repeat(s.length))&&(i===s||i.startsWith(s)||s.startsWith(i)))return true}return false},mn=(e,t=true)=>{if(e[0]!=="+"&&e[0]!=="*"||e[1]!=="(")return;let n=0,r=0,i=0,s=false;for(let o=1;o<e.length;o++){let a=e[o];if(s===true){s=false;continue}if(a==="\\"){s=true;continue}if(a==='"'){i=i===1?0:1;continue}if(i!==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}}}}},Qo=e=>{let t=0,n=[];for(;t<e.length;){let i=mn(e.slice(t),false);if(!i||i.type!=="*")return;let s=Rr(i.body).map(a=>a.trim());if(s.length!==1)return;let o=$r(s[0]);if(!o||o.length!==1)return;n.push(o),t+=i.end+1;}return n.length<1?void 0:`${n.length===1?Y.escapeRegex(n[0]):`[${n.map(i=>Y.escapeRegex(i)).join("")}]`}*`},Zo=e=>{let t=0,n=e.trim(),r=mn(n);for(;r;)t++,n=r.body.trim(),r=mn(n);return t},ta=(e,t)=>{if(t.maxExtglobRecursion===false)return {risky:false};let n=typeof t.maxExtglobRecursion=="number"?t.maxExtglobRecursion:Vt.DEFAULT_MAX_EXTGLOB_RECURSION,r=Rr(e).map(i=>i.trim());if(r.length>1&&(r.some(i=>i==="")||r.some(i=>/^[*?]+$/.test(i))||Yo(r)))return {risky:true};for(let i of r){let s=Qo(i);if(s)return {risky:true,safeOutput:s};if(Zo(i)>n)return {risky:true}}return {risky:false}},hn=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=Cr[e]||e;let n={...t},r=typeof n.maxLength=="number"?Math.min(Fe,n.maxLength):Fe,i=e.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);let s={type:"bos",value:"",output:n.prepend||""},o=[s],a=n.capture?"":"?:",l=Vt.globChars(n.windows),c=Vt.extglobChars(l),{DOT_LITERAL:u,PLUS_LITERAL:p,SLASH_LITERAL:d,ONE_CHAR:y,DOTS_SLASH:g,NO_DOT:E,NO_DOT_SLASH:A,NO_DOTS_SLASH:q,QMARK:S,QMARK_NO_DOT:M,STAR:W,START_ANCHOR:O}=l,v=w=>`(${a}(?:(?!${O}${w.dot?g:u}).)*?)`,N=n.dot?"":E,T=n.dot?S:M,C=n.bash===true?v(n):W;n.capture&&(C=`(${C})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let m={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=Y.removePrefix(e,m),i=e.length;let X=[],x=[],P=[],h=s,f,Q=()=>m.index===i-1,L=m.peek=(w=1)=>e[m.index+w],B=m.advance=()=>e[++m.index]||"",lt=()=>e.slice(m.index+1),Z=(w="",j=0)=>{m.consumed+=w,m.index+=j;},mt=w=>{m.output+=w.output!=null?w.output:w.value,Z(w.value);},Ci=()=>{let w=1;for(;L()==="!"&&(L(2)!=="("||L(3)==="?");)B(),m.start++,w++;return w%2===0?false:(m.negated=true,m.start++,true)},me=w=>{m[w]++,P.push(w);},ht=w=>{m[w]--,P.pop();},R=w=>{if(h.type==="globstar"){let j=m.braces>0&&(w.type==="comma"||w.type==="brace"),b=w.extglob===true||X.length&&(w.type==="pipe"||w.type==="paren");w.type!=="slash"&&w.type!=="paren"&&!j&&!b&&(m.output=m.output.slice(0,-h.output.length),h.type="star",h.value="*",h.output=C,m.output+=h.output);}if(X.length&&w.type!=="paren"&&(X[X.length-1].inner+=w.value),(w.value||w.output)&&mt(w),h&&h.type==="text"&&w.type==="text"){h.output=(h.output||h.value)+w.value,h.value+=w.value;return}w.prev=h,o.push(w),h=w;},he=(w,j)=>{let b={...c[j],conditions:1,inner:""};b.prev=h,b.parens=m.parens,b.output=m.output,b.startIndex=m.index,b.tokensIndex=o.length;let $=(n.capture?"(":"")+b.open;me("parens"),R({type:w,value:j,output:m.output?"":y}),R({type:"paren",extglob:true,value:B(),output:$}),X.push(b);},Ri=w=>{let j=e.slice(w.startIndex,m.index+1),b=e.slice(w.startIndex+2,m.index),$=ta(b,n);if((w.type==="plus"||w.type==="star")&&$.risky){let I=$.safeOutput?(w.output?"":y)+(n.capture?`(${$.safeOutput})`:$.safeOutput):void 0,it=o[w.tokensIndex];it.type="text",it.value=j,it.output=I||Y.escapeRegex(j);for(let st=w.tokensIndex+1;st<o.length;st++)o[st].value="",o[st].output="",delete o[st].suffix;m.output=w.output+it.output,m.backtrack=true,R({type:"paren",extglob:true,value:f,output:""}),ht("parens");return}let D=w.close+(n.capture?")":""),G;if(w.type==="negate"){let I=C;if(w.inner&&w.inner.length>1&&w.inner.includes("/")&&(I=v(n)),(I!==C||Q()||/^\)+$/.test(lt()))&&(D=w.close=`)$))${I}`),w.inner.includes("*")&&(G=lt())&&/^\.[^\\/.]+$/.test(G)){let it=hn(G,{...t,fastpaths:false}).output;D=w.close=`)${it})${I})`;}w.prev.type==="bos"&&(m.negatedExtglob=true);}R({type:"paren",extglob:true,value:f,output:D}),ht("parens");};if(n.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let w=false,j=e.replace(Xo,(b,$,D,G,I,it)=>G==="\\"?(w=true,b):G==="?"?$?$+G+(I?S.repeat(I.length):""):it===0?T+(I?S.repeat(I.length):""):S.repeat(D.length):G==="."?u.repeat(D.length):G==="*"?$?$+G+(I?C:""):C:$?b:`\\${b}`);return w===true&&(n.unescape===true?j=j.replace(/\\/g,""):j=j.replace(/\\+/g,b=>b.length%2===0?"\\\\":b?"\\":"")),j===e&&n.contains===true?(m.output=e,m):(m.output=Y.wrapOutput(j,m,t),m)}for(;!Q();){if(f=B(),f==="\0")continue;if(f==="\\"){let b=L();if(b==="/"&&n.bash!==true||b==="."||b===";")continue;if(!b){f+="\\",R({type:"text",value:f});continue}let $=/^\\+/.exec(lt()),D=0;if($&&$[0].length>2&&(D=$[0].length,m.index+=D,D%2!==0&&(f+="\\")),n.unescape===true?f=B():f+=B(),m.brackets===0){R({type:"text",value:f});continue}}if(m.brackets>0&&(f!=="]"||h.value==="["||h.value==="[^")){if(n.posix!==false&&f===":"){let b=h.value.slice(1);if(b.includes("[")&&(h.posix=true,b.includes(":"))){let $=h.value.lastIndexOf("["),D=h.value.slice(0,$),G=h.value.slice($+2),I=zo[G];if(I){h.value=D+I,m.backtrack=true,B(),!s.output&&o.indexOf(h)===1&&(s.output=y);continue}}}(f==="["&&L()!==":"||f==="-"&&L()==="]")&&(f=`\\${f}`),f==="]"&&(h.value==="["||h.value==="[^")&&(f=`\\${f}`),n.posix===true&&f==="!"&&h.value==="["&&(f="^"),h.value+=f,mt({value:f});continue}if(m.quotes===1&&f!=='"'){f=Y.escapeRegex(f),h.value+=f,mt({value:f});continue}if(f==='"'){m.quotes=m.quotes===1?0:1,n.keepQuotes===true&&R({type:"text",value:f});continue}if(f==="("){me("parens"),R({type:"paren",value:f});continue}if(f===")"){if(m.parens===0&&n.strictBrackets===true)throw new SyntaxError(Rt("opening","("));let b=X[X.length-1];if(b&&m.parens===b.parens+1){Ri(X.pop());continue}R({type:"paren",value:f,output:m.parens?")":"\\)"}),ht("parens");continue}if(f==="["){if(n.nobracket===true||!lt().includes("]")){if(n.nobracket!==true&&n.strictBrackets===true)throw new SyntaxError(Rt("closing","]"));f=`\\${f}`;}else me("brackets");R({type:"bracket",value:f});continue}if(f==="]"){if(n.nobracket===true||h&&h.type==="bracket"&&h.value.length===1){R({type:"text",value:f,output:`\\${f}`});continue}if(m.brackets===0){if(n.strictBrackets===true)throw new SyntaxError(Rt("opening","["));R({type:"text",value:f,output:`\\${f}`});continue}ht("brackets");let b=h.value.slice(1);if(h.posix!==true&&b[0]==="^"&&!b.includes("/")&&(f=`/${f}`),h.value+=f,mt({value:f}),n.literalBrackets===false||Y.hasRegexChars(b))continue;let $=Y.escapeRegex(h.value);if(m.output=m.output.slice(0,-h.value.length),n.literalBrackets===true){m.output+=$,h.value=$;continue}h.value=`(${a}${$}|${h.value})`,m.output+=h.value;continue}if(f==="{"&&n.nobrace!==true){me("braces");let b={type:"brace",value:f,output:"(",outputIndex:m.output.length,tokensIndex:m.tokens.length};x.push(b),R(b);continue}if(f==="}"){let b=x[x.length-1];if(n.nobrace===true||!b){R({type:"text",value:f,output:f});continue}let $=")";if(b.dots===true){let D=o.slice(),G=[];for(let I=D.length-1;I>=0&&(o.pop(),D[I].type!=="brace");I--)D[I].type!=="dots"&&G.unshift(D[I].value);$=Ko(G,n),m.backtrack=true;}if(b.comma!==true&&b.dots!==true){let D=m.output.slice(0,b.outputIndex),G=m.tokens.slice(b.tokensIndex);b.value=b.output="\\{",f=$="\\}",m.output=D;for(let I of G)m.output+=I.output||I.value;}R({type:"brace",value:f,output:$}),ht("braces"),x.pop();continue}if(f==="|"){X.length>0&&X[X.length-1].conditions++,R({type:"text",value:f});continue}if(f===","){let b=f,$=x[x.length-1];$&&P[P.length-1]==="braces"&&($.comma=true,b="|"),R({type:"comma",value:f,output:b});continue}if(f==="/"){if(h.type==="dot"&&m.index===m.start+1){m.start=m.index+1,m.consumed="",m.output="",o.pop(),h=s;continue}R({type:"slash",value:f,output:d});continue}if(f==="."){if(m.braces>0&&h.type==="dot"){h.value==="."&&(h.output=u);let b=x[x.length-1];h.type="dots",h.output+=f,h.value+=f,b.dots=true;continue}if(m.braces+m.parens===0&&h.type!=="bos"&&h.type!=="slash"){R({type:"text",value:f,output:u});continue}R({type:"dot",value:f,output:u});continue}if(f==="?"){if(!(h&&h.value==="(")&&n.noextglob!==true&&L()==="("&&L(2)!=="?"){he("qmark",f);continue}if(h&&h.type==="paren"){let $=L(),D=f;(h.value==="("&&!/[!=<:]/.test($)||$==="<"&&!/<([!=]|\w+>)/.test(lt()))&&(D=`\\${f}`),R({type:"text",value:f,output:D});continue}if(n.dot!==true&&(h.type==="slash"||h.type==="bos")){R({type:"qmark",value:f,output:M});continue}R({type:"qmark",value:f,output:S});continue}if(f==="!"){if(n.noextglob!==true&&L()==="("&&(L(2)!=="?"||!/[!=<:]/.test(L(3)))){he("negate",f);continue}if(n.nonegate!==true&&m.index===0){Ci();continue}}if(f==="+"){if(n.noextglob!==true&&L()==="("&&L(2)!=="?"){he("plus",f);continue}if(h&&h.value==="("||n.regex===false){R({type:"plus",value:f,output:p});continue}if(h&&(h.type==="bracket"||h.type==="paren"||h.type==="brace")||m.parens>0){R({type:"plus",value:f});continue}R({type:"plus",value:p});continue}if(f==="@"){if(n.noextglob!==true&&L()==="("&&L(2)!=="?"){R({type:"at",extglob:true,value:f,output:""});continue}R({type:"text",value:f});continue}if(f!=="*"){(f==="$"||f==="^")&&(f=`\\${f}`);let b=Wo.exec(lt());b&&(f+=b[0],m.index+=b[0].length),R({type:"text",value:f});continue}if(h&&(h.type==="globstar"||h.star===true)){h.type="star",h.star=true,h.value+=f,h.output=C,m.backtrack=true,m.globstar=true,Z(f);continue}let w=lt();if(n.noextglob!==true&&/^\([^?]/.test(w)){he("star",f);continue}if(h.type==="star"){if(n.noglobstar===true){Z(f);continue}let b=h.prev,$=b.prev,D=b.type==="slash"||b.type==="bos",G=$&&($.type==="star"||$.type==="globstar");if(n.bash===true&&(!D||w[0]&&w[0]!=="/")){R({type:"star",value:f,output:""});continue}let I=m.braces>0&&(b.type==="comma"||b.type==="brace"),it=X.length&&(b.type==="pipe"||b.type==="paren");if(!D&&b.type!=="paren"&&!I&&!it){R({type:"star",value:f,output:""});continue}for(;w.slice(0,3)==="/**";){let st=e[m.index+4];if(st&&st!=="/")break;w=w.slice(3),Z("/**",3);}if(b.type==="bos"&&Q()){h.type="globstar",h.value+=f,h.output=v(n),m.output=h.output,m.globstar=true,Z(f);continue}if(b.type==="slash"&&b.prev.type!=="bos"&&!G&&Q()){m.output=m.output.slice(0,-(b.output+h.output).length),b.output=`(?:${b.output}`,h.type="globstar",h.output=v(n)+(n.strictSlashes?")":"|$)"),h.value+=f,m.globstar=true,m.output+=b.output+h.output,Z(f);continue}if(b.type==="slash"&&b.prev.type!=="bos"&&w[0]==="/"){let st=w[1]!==void 0?"|$":"";m.output=m.output.slice(0,-(b.output+h.output).length),b.output=`(?:${b.output}`,h.type="globstar",h.output=`${v(n)}${d}|${d}${st})`,h.value+=f,m.output+=b.output+h.output,m.globstar=true,Z(f+B()),R({type:"slash",value:"/",output:""});continue}if(b.type==="bos"&&w[0]==="/"){h.type="globstar",h.value+=f,h.output=`(?:^|${d}|${v(n)}${d})`,m.output=h.output,m.globstar=true,Z(f+B()),R({type:"slash",value:"/",output:""});continue}m.output=m.output.slice(0,-h.output.length),h.type="globstar",h.output=v(n),h.value+=f,m.output+=h.output,m.globstar=true,Z(f);continue}let j={type:"star",value:f,output:C};if(n.bash===true){j.output=".*?",(h.type==="bos"||h.type==="slash")&&(j.output=N+j.output),R(j);continue}if(h&&(h.type==="bracket"||h.type==="paren")&&n.regex===true){j.output=f,R(j);continue}(m.index===m.start||h.type==="slash"||h.type==="dot")&&(h.type==="dot"?(m.output+=A,h.output+=A):n.dot===true?(m.output+=q,h.output+=q):(m.output+=N,h.output+=N),L()!=="*"&&(m.output+=y,h.output+=y)),R(j);}for(;m.brackets>0;){if(n.strictBrackets===true)throw new SyntaxError(Rt("closing","]"));m.output=Y.escapeLast(m.output,"["),ht("brackets");}for(;m.parens>0;){if(n.strictBrackets===true)throw new SyntaxError(Rt("closing",")"));m.output=Y.escapeLast(m.output,"("),ht("parens");}for(;m.braces>0;){if(n.strictBrackets===true)throw new SyntaxError(Rt("closing","}"));m.output=Y.escapeLast(m.output,"{"),ht("braces");}if(n.strictSlashes!==true&&(h.type==="star"||h.type==="bracket")&&R({type:"maybe_slash",value:"",output:`${d}?`}),m.backtrack===true){m.output="";for(let w of m.tokens)m.output+=w.output!=null?w.output:w.value,w.suffix&&(m.output+=w.suffix);}return m};hn.fastpaths=(e,t)=>{let n={...t},r=typeof n.maxLength=="number"?Math.min(Fe,n.maxLength):Fe,i=e.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);e=Cr[e]||e;let{DOT_LITERAL:s,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:l,NO_DOT:c,NO_DOTS:u,NO_DOTS_SLASH:p,STAR:d,START_ANCHOR:y}=Vt.globChars(n.windows),g=n.dot?u:c,E=n.dot?p:c,A=n.capture?"":"?:",q={negated:false,prefix:""},S=n.bash===true?".*?":d;n.capture&&(S=`(${S})`);let M=N=>N.noglobstar===true?S:`(${A}(?:(?!${y}${N.dot?l:s}).)*?)`,W=N=>{switch(N){case "*":return `${g}${a}${S}`;case ".*":return `${s}${a}${S}`;case "*.*":return `${g}${S}${s}${a}${S}`;case "*/*":return `${g}${S}${o}${a}${E}${S}`;case "**":return g+M(n);case "**/*":return `(?:${g}${M(n)}${o})?${E}${a}${S}`;case "**/*.*":return `(?:${g}${M(n)}${o})?${E}${S}${s}${a}${S}`;case "**/.*":return `(?:${g}${M(n)}${o})?${s}${a}${S}`;default:{let T=/^(.*?)\.(\w+)$/.exec(N);if(!T)return;let C=W(T[1]);return C?C+s+T[2]:void 0}}},O=Y.removePrefix(e,q),v=W(O);return v&&n.strictSlashes!==true&&(v+=`${o}?`),v};vr.exports=hn;});var Lr=bt((vf,Pr)=>{var ea=_r(),dn=Nr(),kr=Ht(),na=Mt(),ra=e=>e&&typeof e=="object"&&!Array.isArray(e),H=(e,t,n=false)=>{if(Array.isArray(e)){let u=e.map(d=>H(d,t,n));return d=>{for(let y of u){let g=y(d);if(g)return g}return false}}let r=ra(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!r)throw new TypeError("Expected pattern to be a non-empty string");let i=t||{},s=i.windows,o=r?H.compileRe(e,t):H.makeRe(e,t,false,true),a=o.state;delete o.state;let l=()=>false;if(i.ignore){let u={...t,ignore:null,onMatch:null,onResult:null};l=H(i.ignore,u,n);}let c=(u,p=false)=>{let{isMatch:d,match:y,output:g}=H.test(u,o,t,{glob:e,posix:s}),E={glob:e,state:a,regex:o,posix:s,input:u,output:g,match:y,isMatch:d};return typeof i.onResult=="function"&&i.onResult(E),d===false?(E.isMatch=false,p?E:false):l(u)?(typeof i.onIgnore=="function"&&i.onIgnore(E),E.isMatch=false,p?E:false):(typeof i.onMatch=="function"&&i.onMatch(E),p?E:true)};return n&&(c.state=a),c};H.test=(e,t,n,{glob:r,posix:i}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return {isMatch:false,output:""};let s=n||{},o=s.format||(i?kr.toPosixSlashes:null),a=e===r,l=a&&o?o(e):e;return a===false&&(l=o?o(e):e,a=l===r),(a===false||s.capture===true)&&(s.matchBase===true||s.basename===true?a=H.matchBase(e,t,n,i):a=t.exec(l)),{isMatch:!!a,match:a,output:l}};H.matchBase=(e,t,n)=>(t instanceof RegExp?t:H.makeRe(t,n)).test(kr.basename(e));H.isMatch=(e,t,n)=>H(t,n)(e);H.parse=(e,t)=>Array.isArray(e)?e.map(n=>H.parse(n,t)):dn(e,{...t,fastpaths:false});H.scan=(e,t)=>ea(e,t);H.compileRe=(e,t,n=false,r=false)=>{if(n===true)return e.output;let i=t||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${e.output})${o}`;e&&e.negated===true&&(a=`^(?!${a}).*$`);let l=H.toRegex(a,t);return r===true&&(l.state=e),l};H.makeRe=(e,t={},n=false,r=false)=>{if(!e||typeof e!="string")throw new TypeError("Expected a non-empty string");let i={negated:false,fastpaths:true};return t.fastpaths!==false&&(e[0]==="."||e[0]==="*")&&(i.output=dn.fastpaths(e,t)),i.output||(i=dn(e,t)),H.compileRe(i,t,n,r)};H.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 /$^/}};H.constants=na;Pr.exports=H;});var Dr=bt((Nf,Ir)=>{var Or=Lr(),ia=Ht();function Fr(e,t,n=false){return t&&(t.windows===null||t.windows===void 0)&&(t={...t,windows:ia.isWindows()}),Or(e,t,n)}Object.assign(Fr,Or);Ir.exports=Fr;});function Kt(e){if("String"in e)return e.String.sval}function gt(e){return e.map(Kt).filter(t=>t!=null)}function Jr(e){return Object.keys(e)[0]}function Yr(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 je=F(()=>{});function Qr(e){let t=e.toLowerCase();return ["serial","serial4","bigserial","serial8","smallserial","serial2"].includes(t)}function Zr(e){let t=e.toLowerCase();return ["varchar","character varying","char","character","bpchar"].includes(t)}function ti(e){let t=e.toLowerCase();return ["numeric","decimal"].includes(t)}var bn,Be,Va,wn=F(()=>{je();bn=class extends Error{},Be=class extends bn{constructor(n,r){super(r??`Unsupported node type: ${Jr(n)}`);this.node=n;}};Va={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"}},new Map(Object.entries(Va));});var tt,Ue,ei=F(()=>{je();wn();tt=class extends Be{constructor(t,n){super(t,`Unsupported expression: ${n}`);}},Ue=class{deparse(t){if("A_Const"in t){let i=t.A_Const;if(i.boolval!==void 0)return i.boolval.boolval?{}:{$always:false}}let n=Object.keys(t)[0],r=this[n];if(!r)throw new tt({[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 tt({[n]:t},`deparseValue: ${n}`)}A_Expr(t){if(t.kind==="AEXPR_OP"){let n=t.name?.[0],r=n?Kt(n):void 0;if(!r)throw new tt({A_Expr:t},"A_Expr missing operator");let i=this.isJwtAccessor(t);if(i)return {[i]:{}};let s=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 tt({A_Expr:t},`Unsupported operator: ${r}`);let l=t.rexpr!=null&&"ColumnRef"in t.rexpr;if(typeof s=="string"&&s.startsWith("{{")&&l)return {[o]:{[a]:s}};let c=l&&typeof o=="string"?{$ref:o}:o;return {[s]:{[a]:c}}}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,s=(t.name?.[0]?Kt(t.name[0]):"~~")==="!~~"?"$notLike":"$like";return {[n]:{[s]: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(i=>this.deparseValue(i)):[];return {[n]:{$in:r}}}throw new tt({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 tt({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],i="ResTarget"in r?r.ResTarget:void 0;if(i?.val){let s=this.deparseValue(i.val);return s}}}throw new tt({SubLink:t},`SubLink type: ${t.subLinkType}`)}SelectStmt(t){let{from:n,schema:r,join:i}=this.deparseFromClause(t.fromClause??[]),s=[];for(let d of t.targetList??[]){let y="ResTarget"in d?d.ResTarget:void 0;if(y?.val){let g=this.deparseValue(y.val);Array.isArray(g)?s.push(...g.map(String)):g!=null&&g!==""&&s.push(String(g));}}let o=t.whereClause?this.deparse(t.whereClause):void 0,a=this.deparseSortClause(t.sortClause),l=this.deparseLimit(t.limitCount),c=this.deparseLimit(t.limitOffset),u=this.deparseGroupClause(t.groupClause),p={type:"query",from:n,select:s};return r&&(p.schema=r),Object.keys(i).length>0&&(p.join=i),o&&(p.where=o),a.length>0&&(p.order=a),l!==void 0&&(p.limit=l),c!==void 0&&(p.offset=c),u.length>0&&(p.group=u),p}FuncCall(t){let n=this.isAuthFunc(t.funcname??[]);if(n)return n;throw new tt({FuncCall:t},`FuncCall: ${gt(t.funcname??[]).join(".")}`)}ColumnRef(t){let n=gt(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 tt({A_Const:t},"A_Const: unknown variant")}TypeCast(t){if(!t.arg)throw new tt({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 i=r.RangeVar;return {from:i.relname??"",schema:i.schemaname,join:n}}if("JoinExpr"in r){let{from:i,schema:s}=this.walkJoinExpr(r.JoinExpr,n);return {from:i,schema:s,join:n}}return {from:"",join:n}}walkJoinExpr(t,n){let r={from:""};if(t.larg)if("RangeVar"in t.larg){let i=t.larg.RangeVar;r={from:i.relname??"",schema:i.schemaname};}else "JoinExpr"in t.larg&&(r=this.walkJoinExpr(t.larg.JoinExpr,n));if(t.rarg&&"RangeVar"in t.rarg){let i=t.rarg.RangeVar,s=i.relname??"",o=i.alias?.aliasname??s,a=t.jointype==="JOIN_LEFT"?"left":"inner",l={from:s,type:a};t.quals&&(l.on=this.deparse(t.quals));let c=o;if(c in n){let u=2;for(;`${c}_${u}`in n;)u++;c=`${c}_${u}`;}n[c]=l;}return r}deparseSortClause(t){if(!t)return [];let n=[];for(let r of t){if(!("SortBy"in r))continue;let i=r.SortBy;if(!i.node)continue;let s=String(this.deparseValue(i.node)),o=i.sortby_dir==="SORTBY_DESC"?"desc":"asc",a={column:s,direction:o};i.sortby_nulls==="SORTBY_NULLS_FIRST"?a.nullsFirst=true:i.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=gt(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]?Kt(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 i=this.isJwtAccessor(t.lexpr.A_Expr);if(i)return `${i.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 vt,ni=F(()=>{vt=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 Jt,xn=F(()=>{Jt=class extends Error{constructor(n,r,i,s){super(`check constraint "${i}" violated for ${n}.${r}`);this.table=n;this.column=r;this.constraint=i;this.value=s;this.name="CheckConstraintError";}};});var z,pt=F(()=>{xn();z=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,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=[],i=this.context.column;r.push(this.quoteIfNeeded(i)),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 s=this.checkConstraint();return s&&r.push(`CHECK (${s})`),r.join(" ")}checkError(t,n){return new Jt(this.context.table,this.context.column,t,n)}quoteIfNeeded(t){return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?t:`"${t}"`}};});var Et,Me=F(()=>{pt();Et=class extends z{get sqliteType(){return "INTEGER"}};});var Yt,Sn=F(()=>{Me();Yt=class extends Et{constructor(t){super({...t,isSerial:true});}};});function Ga(e,t){let{precision:n,scale:r}=t,i=10**r,s=10**(n-r);return Math.abs(Math.round(e*i)-e*i)<1e-4&&Math.abs(e)<s}var Qt,En=F(()=>{pt();Qt=class extends z{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,i=10**n,s=10**(t-n);return `ABS(ROUND(${r} * ${i}) - ${r} * ${i}) < 0.0001 AND ABS(${r}) < ${s}`}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(!Ga(t,this.numericPrecision))return this.validationFail(`Does not fit numeric(${n}, ${r}).`,"Patch rows within numeric precision.")}return this.validationPass()}};});var U,nt=F(()=>{pt();U=class extends z{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 Zt,Tn=F(()=>{pt();Zt=class extends z{get sqliteType(){return "BLOB"}};});var te,An=F(()=>{pt();te=class extends z{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 ri(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var ee,_n=F(()=>{pt();ee=class extends z{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=ri(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."):ri(t).ok?this.validationPass():this.validationFail("Invalid JSON text.","Patch rows with valid JSON.")}};});function za(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 ne,Cn=F(()=>{nt();ne=class extends U{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"||!za(t)?this.validationFail("Invalid date.","Patch rows with YYYY-MM-DD dates."):this.validationPass()}};});function Wa(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]),i=t[3]===void 0?0:Number(t[3]),s=t[5]===void 0?null:Number(t[5]),o=t[6]===void 0?null:Number(t[6]),a=s===null||o!==null&&s<=15&&o<=59;return n<=24&&r<=59&&i<=59&&(n!==24||r===0&&i===0)&&a}var re,Rn=F(()=>{nt();re=class extends U{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"||!Wa(t)?this.validationFail("Invalid time.","Patch rows with HH:MM[:SS] times."):this.validationPass()}};});function Xa(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]),i=Number(t[3]),s=Number(t[4]),o=Number(t[5]),a=t[6]===void 0?0:Number(t[6]),l=t[8]===void 0?null:Number(t[8]),c=t[9]===void 0?null:Number(t[9]),u=new Date(Date.UTC(n,r-1,i)),p=u.getUTCFullYear()===n&&u.getUTCMonth()===r-1&&u.getUTCDate()===i,d=s<=24&&o<=59&&a<=59&&(s!==24||o===0&&a===0),y=l===null||c!==null&&l<=15&&c<=59;return p&&d&&y}var ie,$n=F(()=>{nt();ie=class extends U{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"||!Xa(t)?this.validationFail("Invalid timestamp.","Patch rows with ISO timestamps."):this.validationPass()}};});var se,vn=F(()=>{nt();se=class extends U{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 oe,Nn=F(()=>{nt();oe=class extends U{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 ii(e){try{return {ok:!0,value:JSON.parse(e)}}catch{return {ok:false}}}var Nt,kn=F(()=>{pt();Nt=class extends z{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=ii(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=ii(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 i=this.elementField.validateStorage(r);if(i.status==="fail")return this.validationFail(`Invalid ${this.elementField.context.pgTypeName} array element.`,i.action??"Patch rows with valid array elements.")}return this.validationPass()}};});function si(e){return Ja.test(e.toLowerCase())}var Ka,Ja,ae,Pn=F(()=>{nt();Ka="????????-????-????-????-????????????",Ja=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;ae=class extends U{get isShimBacked(){return true}checkConstraint(){let t=this.quoteIfNeeded(this.context.column);return `${t} IS NULL OR ${t} GLOB '${Ka}'`}serialize(t){if(this.isNullish(t))return t;if(typeof t!="string")throw this.checkError("uuid_format",t);let n=t.toLowerCase();if(!si(n))throw this.checkError("uuid_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!si(t)?this.validationFail("Invalid UUID.","Patch rows with valid UUIDs."):this.validationPass()}};});function Ya(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 Qa(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 Za(e){if(!e.includes(":"))return false;try{return new URL(`http://[${e}]/`),!0}catch{return false}}function oi(e){let t=Ya(e);return t?Qa(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=32:Za(t.address)?t.prefix===null||t.prefix>=0&&t.prefix<=128:false:false}var le,Ln=F(()=>{nt();le=class extends U{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(!oi(n))throw this.checkError("inet_format",t);return n}validateStorage(t){return this.isNullish(t)?this.validationPass():typeof t!="string"||!oi(t.trim())?this.validationFail("Invalid inet address.","Patch rows with valid inet strings."):this.validationPass()}};});var ce,On=F(()=>{nt();ce=class extends U{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 ue(e,t){if(t?.isArray){let r=ue(e,{...t,isArray:false});return new Nt(e,r)}if(t?.enumValues)return new oe(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),i={...e,pgTypeName:r},s=ue(i);return new Nt(e,s)}return el.has(n)?new Yt(e):tl.has(n)?new Et(e):sl.has(n)?new te(e):ol.has(n)?new ee(e):ul.has(n)?new ne(e):fl.has(n)?new re(e):pl.has(n)?new ie(e):ml.has(n)?new se(e):il.has(n)?new Zt(e):nl.has(n)?new Qt(e,t?.numericPrecision):al.has(n)?new ae(e):ll.has(n)?new U(e,63):cl.has(n)?new le(e):rl.has(n)?new U(e,t?.lengthConstraint):new ce(e)}var tl,el,nl,rl,il,sl,ol,al,ll,cl,ul,fl,pl,ml,ai=F(()=>{Me();Sn();En();nt();Tn();An();_n();Cn();Rn();$n();vn();Nn();kn();Pn();Ln();On();tl=new Set(["int2","smallint","int4","integer","int","int8","bigint"]),el=new Set(["serial","serial4","bigserial","serial8","smallserial","serial2"]),nl=new Set(["float4","real","float8","double precision","numeric","decimal"]),rl=new Set(["text","varchar","character varying","char","character","bpchar"]),il=new Set(["bytea"]),sl=new Set(["bool","boolean"]),ol=new Set(["json","jsonb"]),al=new Set(["uuid"]),ll=new Set(["name"]),cl=new Set(["inet"]),ul=new Set(["date"]),fl=new Set(["time","timetz","time without time zone","time with time zone"]),pl=new Set(["timestamp","timestamptz","timestamp without time zone","timestamp with time zone"]),ml=new Set(["interval"]);});var li=F(()=>{});var fe,ci=F(()=>{fe=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,i]of Object.entries(t)){let s=this.fields.get(r);n[r]=s?s.serialize(i):i;}return n}deserializeRow(t){let n={};for(let[r,i]of Object.entries(t)){let s=this.fields.get(r);n[r]=s?s.deserialize(i):i;}return n}applyDefaults(t){let n={...t};for(let[r,i]of this.fields)!(r in n)&&i.context.defaultFn&&(n[r]=i.context.defaultFn());return n}};});var ui=F(()=>{pt();xn();Me();Sn();En();nt();Tn();An();_n();Cn();Rn();$n();vn();Nn();kn();Pn();Ln();On();ai();li();ci();});var mi={};Li(mi,{_resetWarnedMissingToClauseForTests:()=>hl,collectComments:()=>xl,collectEnums:()=>dl,collectPolicies:()=>yl,collectSchema:()=>bl,collectTableConstraints:()=>wl,collectVariables:()=>gl});function hl(){Dn.clear();}function dl(e){let t=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("CreateEnumStmt"in n.stmt))continue;let r=n.stmt.CreateEnumStmt,i=gt(r.typeName??[]).join(".");if(!i||!r.vals)continue;let s=gt(r.vals);t.set(i.toLowerCase(),s);}return t}function gl(e){let t=new Map;for(let n of e.stmts??[]){if(!n.stmt||!("VariableSetStmt"in n.stmt))continue;let r=n.stmt.VariableSetStmt,i=r.name,s=Yr(r.args?.[0]??{});t.set(i,{value:s,local:r.is_local});}return t}function fi(e){let t=[],n=false;for(let r of e??[])if("RoleSpec"in r){let i=r.RoleSpec;i.roletype==="ROLESPEC_PUBLIC"?i.location===-1&&(n=true):i.roletype==="ROLESPEC_CSTRING"&&i.rolename&&t.push(i.rolename);}return {roles:t,implicitPublic:n}}function pi(e,t){return e&&e.length>0?e:t}function Fn(e,t,n){return e.findIndex(r=>r.data.name===t.name&&r.data.table===t.table&&pi(r.data.schema,n)===pi(t.schema,n))}function In(e,t){return new Error(`policy "${e}" for table "${t}" does not exist`)}function yl(e,t={}){let n=t.defaultSchema||"public",r=t.validateMutations===true,i=new Ue,s=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??"",u=l.table?.schemaname,p={select:"SELECT",insert:"INSERT",update:"UPDATE",delete:"DELETE"},d=l.cmd_name?p[l.cmd_name]??"ALL":"ALL",y=l.permissive===true,{roles:g,implicitPublic:E}=fi(l.roles),A=l.qual?i.deparse(l.qual):void 0,q=l.with_check?i.deparse(l.with_check):void 0;if(E){let M=u?`${u}.${c}`:c,W=l.policy_name??"",O=`${M}::${W}`;if(!Dn.has(O)){Dn.add(O);let v=JSON.stringify(A)+JSON.stringify(q);/\{\{auth\.(uid|jwt|role)/i.test(v)||console.warn(`[supalite] policy "${W}" on "${M}" has no TO clause \u2014 applies to all roles (PUBLIC). For clarity, prefer an explicit \`TO <role>\` clause (e.g. \`TO authenticated\`).`);}}let S=new vt({name:l.policy_name??"",table:c,schema:u,command:d,permissive:y,roles:g,using:A,withCheck:q});o.push(S);}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 u=gt(c.List.items??[]),p=u[u.length-1],d=u[u.length-2],y=u.length>=3?u[u.length-3]:void 0;if(p&&d){let g=Fn(o,{name:p,table:d,schema:y},n);if(g!==-1)o.splice(g,1);else if(r&&!l.missing_ok)throw In(p,d)}}}if("AlterPolicyStmt"in a.stmt){let l=a.stmt.AlterPolicyStmt,c=l.policy_name??"",u=l.table?.relname??"",p=l.table?.schemaname,d=Fn(o,{name:c,table:u,schema:p},n);if(d===-1){if(r)throw In(c,u);continue}let y=o[d].data,g=l.roles?fi(l.roles).roles:y.roles,E=l.qual?i.deparse(l.qual):y.using,A=l.with_check?i.deparse(l.with_check):y.withCheck;o[d]=new vt({...y,roles:g,using:E,withCheck:A});}if("RenameStmt"in a.stmt&&a.stmt.RenameStmt.renameType==="OBJECT_POLICY"){let l=a.stmt.RenameStmt,c=l.subname??"",u=l.relation?.relname??"",p=l.relation?.schemaname,d=Fn(o,{name:c,table:u,schema:p},n);if(d===-1){if(r)throw In(c,u);continue}l.newname&&(o[d]=new vt({...o[d].data,name:l.newname}));}if("AlterTableStmt"in a.stmt){let l=a.stmt.AlterTableStmt;if((l.cmds??[]).some(p=>"AlterTableCmd"in p&&(p.AlterTableCmd.subtype==="AT_EnableRowSecurity"||p.AlterTableCmd.subtype==="AT_ForceRowSecurity"))){let p=l.relation?.relname??"";s.add(p);}}}return {policies:o,tables:s}}function bl(e,t){let n=new Map;for(let r of e.stmts??[]){if(!r.stmt||!("CreateStmt"in r.stmt))continue;let i=r.stmt.CreateStmt,s=i.relation?.relname??"",o=i.relation?.schemaname??"public";if(!s)continue;let a=new fe(s,o);for(let l of i.tableElts??[]){if(!("ColumnDef"in l))continue;let c=l.ColumnDef,u=c.colname;if(!u)continue;let p=c.typeName?.names?.map(x=>x.String?.sval||x.String?.str).filter(Boolean),d=p&&(p.length===2&&p[0]==="pg_catalog"?p[1]:p[0]);if(!d)continue;let y=!!c.typeName?.arrayBounds?.length,g=Array.isArray(c.typeName?.typmods)?c.typeName.typmods:[],E=x=>g[x]?.A_Const?.ival?.ival??g[x]?.A_Const?.val?.ival?.ival,A={isArray:y};if(Zr(d)&&g.length>0){let x=E(0);typeof x=="number"&&x>0&&(A.lengthConstraint=x);}if(ti(d)&&g.length>=2){let x=E(0),P=E(1);typeof x=="number"&&typeof P=="number"&&x>0&&P>=0&&(A.numericPrecision={precision:x,scale:P});}let q=t.get(d.toLowerCase());q&&(A.enumValues=q);let S=Array.isArray(c.constraints)?c.constraints:[],M=S.some(x=>x.Constraint?.contype==="CONSTR_PRIMARY"),W=Qr(d)||S.some(x=>x.Constraint?.contype==="CONSTR_IDENTITY"),O=S.some(x=>x.Constraint?.contype==="CONSTR_NOTNULL"),v=S.find(x=>x.Constraint?.contype==="CONSTR_UNIQUE"),N=S.find(x=>x.Constraint?.contype==="CONSTR_GENERATED"),T=S.find(x=>x.Constraint?.contype==="CONSTR_FOREIGN"),C=S.find(x=>x.Constraint?.contype==="CONSTR_CHECK"),m;if(T){let x=T.Constraint,P=x.pktable?.relname,h=x.pktable?.schemaname,f=x.pk_attrs?.[0]?.String?.sval;P&&f&&(m={refSchema:h,refTable:P,refColumn:f,constraintName:x.conname||void 0});}let X={schema:o,table:s,column:u,pgTypeName:d,nullable:!O&&!M,defaultValue:null,defaultFn:null,isPrimaryKey:M,isUnique:!!v,isSerial:W,isGenerated:!!N,fkRef:m,hasCheck:!!C,checkConstraintName:C?.Constraint?.conname||void 0,uniqueConstraintName:v?.Constraint?.conname||void 0};a.set(u,ue(X,A));}n.set(`${o}.${s}`,a);}return n}function wl(e){let t=[];for(let n of e.stmts??[]){if(!n.stmt||!("CreateStmt"in n.stmt))continue;let r=n.stmt.CreateStmt,i=r.relation?.relname??"",s=r.relation?.schemaname??"public";if(i)for(let o of r.tableElts??[]){if("ColumnDef"in o)continue;let a=o;if(!a.Constraint)continue;let l=a.Constraint,c=l.contype;if(c==="CONSTR_UNIQUE"){let u=(l.keys??[]).map(p=>p.String?.sval??p.String?.str).filter(Boolean);if(u.length===0)continue;t.push({schema:s,table:i,kind:"unique",name:l.conname||void 0,columns:u});}else if(c==="CONSTR_CHECK")t.push({schema:s,table:i,kind:"check",name:l.conname||void 0,columns:[]});else if(c==="CONSTR_FOREIGN"){let u=(l.fk_attrs??[]).map(y=>y.String?.sval??y.String?.str).filter(Boolean),p=(l.pk_attrs??[]).map(y=>y.String?.sval??y.String?.str).filter(Boolean),d=l.pktable?.relname;if(!d)continue;t.push({schema:s,table:i,kind:"foreign_key",name:l.conname||void 0,columns:u,refSchema:l.pktable?.schemaname,refTable:d,refColumns:p});}}}return t}function xl(e){let t=[];for(let n of e.stmts??[]){if(!n.stmt||!("CommentStmt"in n.stmt))continue;let r=n.stmt.CommentStmt,i=r.comment??"";if(!i)continue;let s=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(s==="OBJECT_TABLE"||s==="OBJECT_VIEW"){let[a,l]=o.length>=2?o:["public",o[0]];t.push({schema:a,table:l,text:i});}else if(s==="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:i});}}}return t}var Dn,hi=F(()=>{ei();je();ni();ui();wn();Dn=new Set;});process.stdin.isTTY?null:(async()=>{let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")})();function et(e,t){de.existsSync(e)||(de.mkdirSync(e,{recursive:true}),t?.());}function wt(e,t,n){de.existsSync(e)||(de.writeFileSync(e,t),n?.());}var ut=class e{root;constructor(t,n){let r=n??e.projectDir();this.root=at__default.join(r,t??"");}ensureRoot(){et(this.root);}static homeDir(){return at__default.join(Ii.homedir(),".lite")}static projectDir(){return at__default.join(process.cwd(),"supabase")}deleteAll(t=false){try{de.rmSync(this.root,{recursive:!0});}catch(n){if(!t)throw n}this.ensureRoot();}delete(t,n=false){try{de.unlinkSync(at__default.join(this.root,t));}catch(r){if(!n)throw r}}write(t,n,r=false){try{this.ensureRoot(),de.writeFileSync(at__default.join(this.root,t),n);}catch(i){if(!r)throw i}}read(t,n=false){try{return de.readFileSync(at__default.join(this.root,t),"utf8")}catch(r){if(!n)throw r}}relativePath(t){return t?at__default.relative(process.cwd(),at__default.join(this.root,t)):this.root}path(t){return t?at__default.join(this.root,t):this.root}};var Pt=process.env.SUPALITE_CLOUD_URL??(process.env.LOCAL?"http://localhost:2000":"https://www.lite.dev");var be=class{root;constructor(t){this.root=t??at__default.join(Ii.homedir(),".lite","auth"),et(this.root);}async getItem(t){try{return de.readFileSync(at__default.join(this.root,t+".json"),"utf8")}catch{return null}}async setItem(t,n){de.writeFileSync(at__default.join(this.root,t+".json"),n);}async removeItem(t){try{de.unlinkSync(at__default.join(this.root,t+".json"));}catch{return}}};var Tt=class{constructor(t){this.config=t;this.tempFs=new ut(".temp",this.config.root),this.projectFs=new ut("supabase",this.config.root),this.schemaFs=new ut("schemas",this.config.root),this.authStorage=this.config.authStorage??new be(at__default.join(ut.homeDir(),"auth")),this._client=this.config.withSupabaseClient!==false?this.config.client??createClient(this.config.host??Pt,process.env.SUPALITE_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??Pt);return await fetch(r,{...n,headers:{...n?.headers,Authorization:`Bearer ${this.config.token}`}})}};var At=class extends Tt{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.host),i=r.hostname==="localhost"?"supalite.local":r.hostname,s=i.split(".").filter(a=>a!=="www"),o=s.length>=2?s.slice(-2).join("."):i;return `${r.protocol}//${n}.${o}${r.port?`:${r.port}`:""}`}};var ot={config_dir:"supabase",default_db_url:"file:supabase/.temp/data.db",default_db_dir:"supabase/.temp/data"};var Ut=kt(Lt());function qi(e,t){let n=e.slice(0,t).split(/\r\n|\n|\r/g);return [n.length,n.pop().length+1]}function Vi(e,t,n){let r=e.split(/\r\n|\n|\r/g),i="",s=(Math.log10(t+1)|0)+1;for(let o=t-1;o<=t+1;o++){let a=r[o-1];a&&(i+=o.toString().padEnd(s," "),i+=": ",i+=a,i+=`
13
13
  `,o===t&&(i+=" ".repeat(s+n+2),i+=`^
14
14
  `));}return i}var _=class extends Error{line;column;codeblock;constructor(t,n){let[r,i]=qi(n.toml,n.ptr),s=Vi(n.toml,r,i);super(`Invalid TOML document: ${t}
15
15
 
@@ -28,20 +28,20 @@ ${s}`,n),this.line=r,this.column=i,this.codeblock=s;}};function Gi(e,t){let n=0;
28
28
  `||c===" "||c===" "||c==="\r")){if(t=K(e,t-1,true),e[t]!==`
29
29
  `&&e[t]!=="\r")throw new _("invalid escape: only line-ending whitespace may be escaped",{toml:e,ptr:s});t=K(e,t);}else if(c in zn)a+=zn[c];else throw new _("unrecognized escape sequence",{toml:e,ptr:s});l=t;}else !r&&c==="\\"&&(s=t-1,o=true,a+=e.slice(l,s));}return a+e.slice(l,n-1)}function Wn(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 i=Wi.test(e);if(i||Xi.test(e)){if(Ki.test(e))throw new _("leading zeroes are not allowed",{toml:t,ptr:n});e=e.replace(/_/g,"");let o=+e;if(isNaN(o))throw new _("invalid number",{toml:t,ptr:n});if(i){if((i=!Number.isSafeInteger(o))&&!r)throw new _("integer value cannot be represented losslessly",{toml:t,ptr:n});(i||r===true)&&(o=BigInt(e));}return o}let s=new Ot(e);if(!s.isValid())throw new _("invalid value",{toml:t,ptr:n});return s}function Yi(e,t,n){let r=e.slice(t,n),i=r.indexOf("#");return i>-1&&(_t(e,i),r=r.slice(0,i)),[r.trimEnd(),i]}function Ft(e,t,n,r,i){if(r===0)throw new _("document contains excessively nested structures. aborting.",{toml:e,ptr:t});let s=e[t];if(s==="["||s==="{"){let[l,c]=s==="["?Kn(e,t,r,i):Xn(e,t,r,i);if(n){if(c=K(e,c),e[c]===",")c++;else if(e[c]!==n)throw new _("expected comma or end of structure",{toml:e,ptr:c})}return [l,c]}let o;if(s==='"'||s==="'"){o=Ee(e,t);let l=Te(e,t,o);if(n){if(o=K(e,o),e[o]&&e[o]!==","&&e[o]!==n&&e[o]!==`
30
30
  `&&e[o]!=="\r")throw new _("unexpected character encountered",{toml:e,ptr:o});o+=+(e[o]===",");}return [l,o]}o=Gn(e,t,",",n);let a=Yi(e,t,o-+(e[o-1]===","));if(!a[0])throw new _("incomplete key-value declaration: no value specified",{toml:e,ptr:t});return n&&a[1]>-1&&(o=K(e,t+a[1]),o+=+(e[o]===",")),[Wn(a[0],e,t,i),o]}var Qi=/^[a-zA-Z0-9-_]+[ \t]*$/;function Ae(e,t,n="="){let r=t-1,i=[],s=e.indexOf(n,t);if(s<0)throw new _("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 _("multiline strings are not allowed in keys",{toml:e,ptr:t});let a=Ee(e,t);if(a<0)throw new _("unfinished string encountered",{toml:e,ptr:t});r=e.indexOf(".",a);let l=e.slice(a,r<0||r>s?s:r),c=Se(l);if(c>-1)throw new _("newlines are not allowed in keys",{toml:e,ptr:t+r+c});if(l.trimStart())throw new _("found extra tokens after the string part",{toml:e,ptr:a});if(s<a&&(s=e.indexOf(n,a),s<0))throw new _("incomplete key-value: cannot find end of key",{toml:e,ptr:t});i.push(Te(e,t,a));}else {r=e.indexOf(".",t);let a=e.slice(t,r<0||r>s?s:r);if(!Qi.test(a))throw new _("only letter, numbers, dashes and underscores are allowed in keys",{toml:e,ptr:t});i.push(a.trimEnd());}}while(r+1&&r<s);return [i,K(e,s+1,true,true)]}function Xn(e,t,n,r){let i={},s=new Set,o;for(t++;(o=e[t++])!=="}"&&o;){if(o===",")throw new _("expected value, found comma",{toml:e,ptr:t-1});if(o==="#")t=_t(e,t);else if(o!==" "&&o!==" "&&o!==`
31
- `&&o!=="\r"){let a,l=i,c=false,[u,p]=Ae(e,t-1);for(let g=0;g<u.length;g++){if(g&&(l=c?l[a]:l[a]={}),a=u[g],(c=Object.hasOwn(l,a))&&(typeof l[a]!="object"||s.has(l[a])))throw new _("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 _("trying to redefine an already defined value",{toml:e,ptr:t});let[h,y]=Ft(e,p,"}",n-1,r);s.add(h),l[a]=h,t=y;}}if(!o)throw new _("unfinished table encountered",{toml:e,ptr:t});return [i,t]}function Kn(e,t,n,r){let i=[],s;for(t++;(s=e[t++])!=="]"&&s;){if(s===",")throw new _("expected value, found comma",{toml:e,ptr:t-1});if(s==="#")t=_t(e,t);else if(s!==" "&&s!==" "&&s!==`
31
+ `&&o!=="\r"){let a,l=i,c=false,[u,p]=Ae(e,t-1);for(let g=0;g<u.length;g++){if(g&&(l=c?l[a]:l[a]={}),a=u[g],(c=Object.hasOwn(l,a))&&(typeof l[a]!="object"||s.has(l[a])))throw new _("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 _("trying to redefine an already defined value",{toml:e,ptr:t});let[d,y]=Ft(e,p,"}",n-1,r);s.add(d),l[a]=d,t=y;}}if(!o)throw new _("unfinished table encountered",{toml:e,ptr:t});return [i,t]}function Kn(e,t,n,r){let i=[],s;for(t++;(s=e[t++])!=="]"&&s;){if(s===",")throw new _("expected value, found comma",{toml:e,ptr:t-1});if(s==="#")t=_t(e,t);else if(s!==" "&&s!==" "&&s!==`
32
32
  `&&s!=="\r"){let o=Ft(e,t-1,"]",n-1,r);i.push(o[0]),t=o[1];}}if(!s)throw new _("unfinished array encountered",{toml:e,ptr:t});return [i,t]}function Jn(e,t,n,r){let i=t,s=n,o,a=false,l;for(let c=0;c<e.length;c++){if(c){if(i=a?i[o]:i[o]={},s=(l=s[o]).c,r===0&&(l.t===1||l.t===2))return null;if(l.t===2){let u=i.length-1;i=i[u],s=s[u].c;}}if(o=e[c],(a=Object.hasOwn(i,o))&&s[o]?.t===0&&s[o]?.d)return null;a||(o==="__proto__"&&(Object.defineProperty(i,o,{enumerable:true,configurable:true,writable:true}),Object.defineProperty(s,o,{enumerable:true,configurable:true,writable:true})),s[o]={t:c<e.length-1&&r===2?3:r,d:false,i:0,c:{}});}if(l=s[o],l.t!==r&&!(r===1&&l.t===3)||(r===2&&(l.d||(l.d=true,i[o]=[]),i[o].push(i={}),l.c[l.i++]=l={t:1,d:false,i:0,c:{}}),l.d))return null;if(l.d=true,r===1)i=a?i[o]:i[o]={};else if(r===0&&a)return null;return [o,i,l.c]}function It(e,{maxDepth:t=1e3,integersAsBigInt:n}={}){let r={},i={},s=r,o=i;for(let a=K(e,0);a<e.length;){if(e[a]==="["){let l=e[++a]==="[",c=Ae(e,a+=+l,"]");if(l){if(e[c[1]-1]!=="]")throw new _("expected end of table declaration",{toml:e,ptr:c[1]-1});c[1]++;}let u=Jn(c[0],r,i,l?2:1);if(!u)throw new _("trying to redefine an already defined table or value",{toml:e,ptr:a});o=u[2],s=u[1],a=c[1];}else {let l=Ae(e,a),c=Jn(l[0],s,o,0);if(!c)throw new _("trying to redefine an already defined table or value",{toml:e,ptr:a});let u=Ft(e,l[1],void 0,t,n);c[1][c[0]]=u[0],a=u[1];}if(a=K(e,a,true),e[a]&&e[a]!==`
33
33
  `&&e[a]!=="\r")throw new _("each key-value declaration must be followed by an end-of-line",{toml:e,ptr:a});a=K(e,a);}return r}var Yn=/^[a-z0-9-_]+$/i;function Dt(e){let t=typeof e;if(t==="object"){if(Array.isArray(e))return "array";if(e instanceof Date)return "date"}return t}function Zi(e){for(let t=0;t<e.length;t++)if(Dt(e[t])!=="object")return false;return e.length!=0}function Ge(e){return JSON.stringify(e).replace(/\x7f/g,"\\u007f")}function ze(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 Ge(e);if(t==="date"){if(isNaN(e.getTime()))throw new TypeError("cannot serialize invalid date");return e.toISOString()}if(t==="object")return ts(e,n,r);if(t==="array")return es(e,n,r)}function ts(e,t,n){let r=Object.keys(e);if(r.length===0)return "{}";let i="{ ";for(let s=0;s<r.length;s++){let o=r[s];s&&(i+=", "),i+=Yn.test(o)?o:Ge(o),i+=" = ",i+=ze(e[o],Dt(e[o]),t-1,n);}return i+" }"}function es(e,t,n){if(e.length===0)return "[]";let r="[ ";for(let i=0;i<e.length;i++){if(i&&(r+=", "),e[i]===null||e[i]===void 0)throw new TypeError("arrays cannot contain null or undefined values");r+=ze(e[i],Dt(e[i]),t-1,n);}return r+" ]"}function ns(e,t,n,r){if(n===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let i="";for(let s=0;s<e.length;s++)i+=`${i&&`
34
34
  `}[[${t}]]
35
35
  `,i+=We(0,e[s],t,n,r);return i}function We(e,t,n,r,i){if(r===0)throw new Error("Could not stringify the object: maximum object depth exceeded");let s="",o="",a=Object.keys(t);for(let l=0;l<a.length;l++){let c=a[l];if(t[c]!==null&&t[c]!==void 0){let u=Dt(t[c]);if(u==="symbol"||u==="function")throw new TypeError(`cannot serialize values of type '${u}'`);let p=Yn.test(c)?c:Ge(c);if(u==="array"&&Zi(t[c]))o+=(o&&`
36
- `)+ns(t[c],n?`${n}.${p}`:p,r-1,i);else if(u==="object"){let h=n?`${n}.${p}`:p;o+=(o&&`
37
- `)+We(h,t[c],h,r-1,i);}else s+=p,s+=" = ",s+=ze(t[c],u,r,i),s+=`
36
+ `)+ns(t[c],n?`${n}.${p}`:p,r-1,i);else if(u==="object"){let d=n?`${n}.${p}`:p;o+=(o&&`
37
+ `)+We(d,t[c],d,r-1,i);}else s+=p,s+=" = ",s+=ze(t[c],u,r,i),s+=`
38
38
  `;}}return e&&(s||!o)&&(s=s?`[${e}]
39
39
  ${s}`:`[${e}]`),s&&o?`${s}
40
40
  ${o}`:s||o}function Xe(e,{maxDepth:t=1e3,numbersAsFloat:n=false}={}){if(Dt(e)!=="object")throw new TypeError("stringify can only be called with an object");let r=We(0,e,"",t,n);return r[r.length-1]!==`
41
41
  `?r+`
42
- `:r}var rs={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},is=["storage","cloud"];Object.fromEntries(is.map(e=>[e,ss(e)]));function ss(e){let t=typeof process<"u"&&process.env||void 0;return t?t.NODE_ENV==="test"?true:t[rs[e]]==="1":false}function _e(e){let t=[],n="",r=0,i=e.length,s=false,o=false,a=0,l=/^create(\s+or\s+replace)?(\s+temp(orary)?)?$/i,c=p=>{Zn(p).length>0&&t.push(p.trim());},u=()=>{s=false,o=false,a=0;};for(;r<i;){let p=e[r],h=e[r+1];if(p==="-"&&h==="-"){for(;r<i&&e[r]!==`
43
- `;)n+=e[r],r++;continue}if(p==="/"&&h==="*"){for(n+="/*",r+=2;r<i&&!(e[r]==="*"&&e[r+1]==="/");)n+=e[r],r++;r<i&&(n+="*/",r+=2);continue}if(p==="'"){for(n+=p,r++;r<i;){if(e[r]==="'"&&e[r+1]==="'"){n+="''",r+=2;continue}if(n+=e[r],e[r]==="'"){r++;break}r++;}continue}if(p==='"'){for(n+=p,r++;r<i;){if(e[r]==='"'&&e[r+1]==='"'){n+='""',r+=2;continue}if(n+=e[r],e[r]==='"'){r++;break}r++;}continue}if(p==="$"){let y=e.indexOf("$",r+1);if(y!==-1){let g=e.slice(r,y+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(g)){n+=g,r=y+1;let A=e.indexOf(g,r);A===-1?(n+=e.slice(r),r=i):(n+=e.slice(r,A+g.length),r=A+g.length);continue}}}if(/[A-Za-z_]/.test(p)){let y=r;for(;y<i&&/[A-Za-z0-9_]/.test(e[y]);)y++;let g=e.slice(r,y),E=g.toLowerCase();if(E==="trigger"&&l.test(Zn(n))?s=true:s&&E==="begin"?(o=true,a++):s&&o&&E==="case"?a++:s&&o&&E==="end"&&a>0&&a--,n+=g,r=y,s&&o&&a===0){let A=r;for(;A<i&&/\s/.test(e[A]);)A++;e[A]===";"&&(r=A+1),c(n),n="",u();}continue}if(p===";"){if(s&&o&&a>0){n+=p,r++;continue}c(n),n="",u(),r++;continue}n+=p,r++;}return c(n),t}function Zn(e){let t="",n=0,r=e.length;for(;n<r;){let i=e[n],s=e[n+1];if(i==="-"&&s==="-"){for(;n<r&&e[n]!==`
44
- `;)n++;continue}if(i==="/"&&s==="*"){for(n+=2;n<r&&!(e[n]==="*"&&e[n+1]==="/");)n++;n+=2;continue}t+=i,n++;}return t.trim()}function Ke(e){return typeof e=="number"?e:Number.parseInt(String(e),10)}var Re=class{driver=V;basePath;constructor(t){this.basePath=at.resolve(t.basePath);}filePath(t,n){return at.join(this.basePath,t,n)}async ensureDir(t){await V.mkdir(at.dirname(t),{recursive:true});}async getObject(t,n,r,i){let s=this.filePath(t,n),o=await V.stat(s),a=`"${createHash("md5").update(`${s}:${o.mtimeMs}`).digest("hex")}"`;if(i?.ifNoneMatch===a)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,n)};if(i?.ifModifiedSince){let h=new Date(i.ifModifiedSince);if(o.mtime<=h)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,n)}}let l,c,u=o.size,p=200;if(i?.range){let h=i.range.match(/^bytes=(\d+)-(\d*)$/);if(h){let y=Number.parseInt(h[1],10),g=h[2]?Number.parseInt(h[2],10):o.size-1;u=g-y+1,c=`bytes ${y}-${g}/${o.size}`,p=206,l=(await V.open(s,"r")).readableWebStream();}else l=(await V.open(s,"r")).readableWebStream();}else l=(await V.open(s,"r")).readableWebStream();return {httpStatusCode:p,metadata:{...this.buildMetadata(o,a,n),contentLength:u,contentRange:c},body:l}}async uploadObject(t,n,r,i,s,o){let a=this.filePath(t,n);await this.ensureDir(a);let l;if(i instanceof Uint8Array||Buffer.isBuffer(i))l=i;else {let p=[],h=i.getReader();for(;;){let{done:y,value:g}=await h.read();if(y)break;p.push(g);}l=Buffer.concat(p);}await V.writeFile(a,l);let c=await V.stat(a),u=`"${createHash("md5").update(l).digest("hex")}"`;return {cacheControl:o,contentLength:c.size,size:c.size,mimetype:s,lastModified:c.mtime,eTag:u}}async deleteObject(t,n,r){let i=this.filePath(t,n);await V.unlink(i).catch(s=>{if(s.code!=="ENOENT")throw s});}async deleteObjects(t,n){for(let r of n)await this.deleteObject(t,r,void 0);}async copyObject(t,n,r,i,s){let o=this.filePath(t,n),a=this.filePath(t,i);await this.ensureDir(a),await V.copyFile(o,a);let l=await V.stat(a),c=await V.readFile(a);return {httpStatusCode:200,eTag:`"${createHash("md5").update(c).digest("hex")}"`,lastModified:l.mtime}}async headObject(t,n,r){let i=this.filePath(t,n),s=await V.stat(i),o=`"${createHash("md5").update(`${i}:${s.mtimeMs}`).digest("hex")}"`;return this.buildMetadata(s,o,n)}async privateAssetUrl(t,n,r){return `file://${this.filePath(t,n)}`}buildMetadata(t,n,r){return {cacheControl:"no-cache",contentLength:Ke(t.size),size:Ke(t.size),mimetype:as(r),lastModified:t.mtime,eTag:n}}};function as(e){let t=at.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 ls=new Function("spec","return import(spec)");async function Je(e,t,n){try{return await ls(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}}function $e(e,t={}){let n=at__default.resolve(t.cwd??process.cwd()),r=t.env??process.env,i=process.env.SUPABASE_ENV||"development",s=[`.env.${i}.local`,i==="test"?null:".env.local",`.env.${i}`,".env"].filter(a=>a!==null),o=fs(at__default.resolve(e),n);for(let a of o)for(let l of s){let c=at__default.join(a,l),u;try{u=he.readFileSync(c,"utf-8");}catch{continue}let p;try{p=parse(u);}catch(h){throw new Error(`Failed to parse ${c}: ${h.message}`)}for(let[h,y]of Object.entries(p))r[h]===void 0&&(r[h]=y);}}function fs(e,t){let n=[],r=e,i=at__default.parse(r).root;for(;n.push(r),!(r===t||r===i);){let s=at__default.dirname(r);if(s===r)break;r=s;}return n}var ps=/^env\((\w+)\)$/;function ve(e,t=process.env){return Ye(e,t)}function Ye(e,t){if(typeof e=="string"){let n=e.match(ps);return n?t[n[1]]??"":e}if(Array.isArray(e))return e.map(n=>Ye(n,t));if(e&&typeof e=="object"){let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)return e;let r={};for(let[i,s]of Object.entries(e))r[i]=Ye(s,t);return r}return e}var ms=process.env.LITE_VERBOSE==="1";function Bt(...e){ms&&console.error(...e);}var hs=["toml","json","ts","mts","js","mjs","cjs"],Ne=class extends At{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=at__default.relative(process.cwd(),ot.config_dir);if(!t)for(let r of hs){let i=at__default.join(n,`config.${r}`);if(await V__default.access(i).then(()=>true).catch(()=>false)){t=i;break}}return t}async readConfig(t){let n=await this.getConfigPath(t);if(!n)return {};Bt(Ut.default.dim(`Using config file: ${Ut.default.cyan(`./${n}`)}`));let r=at__default.dirname(at__default.resolve(n));$e(r);let i=n.split(".").pop(),s;switch(i){case "toml":s=It(await V__default.readFile(n,"utf-8"));break;case "json":s=JSON.parse(await V__default.readFile(n,"utf-8"));break;case "ts":case "mts":case "js":case "mjs":case "cjs":try{s=(await import(at__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 ve(s)}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,i;switch(n.db?.driver){case "sqlite":i=n.db?.url??ot.default_db_url,r=await createConnection({url:i,ddlDialect:"sqlite"});break;case "pglite":{i=n.db?.url??at__default.join(process.cwd(),ot.default_db_dir);let{createPgliteConnection:s}=await Je("@supabase/lite/pglite","pglite","@electric-sql/pglite");r=await s({url:i});break}case "postgres":{i=n.db?.url??"";let{createPostgresConnection:s}=await Je("@supabase/lite/postgres","postgres","postgres");r=await s({url:i});break}default:i=n.db?.url??ot.default_db_url,r=await createConnection({url:i,ddlDialect:"postgres"});break}if(!r)throw new Error("Failed to create connection");return Bt(Ut.default.green(" \u279C"),"Database located at",Ut.default.cyan(i??"in-memory")),{...n,connection:r}}async createApp(t){let n=await this.getConfig(t),r=new App(n);return r.config.storage?.enabled&&process.env.EXPERIMENTAL_STORAGE==="1"&&!r._storageAdapter&&(r._storageAdapter=new Re({basePath:at__default.join(process.cwd(),ot.config_dir,".temp/storage")})),await r.init()}};var ke=class extends At{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(!n||!n.data)throw new Error("Failed to list projects");return n.data}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={}){let n=await this.fetch("/v1/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`Failed to create project: ${n.status} ${n.statusText}`);let r=await n.json();if(!r.data||!r.data.id)throw new Error("Failed to create project");return r.data}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 i=await this.getConfig(t);return await new App({...i.config,connection:cloud({projectRef:t,token:n.session.access_token,host:this.config.host})}).init()}};var Pe=class extends Tt{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 Ne(t),remote:new ke(t)},this}};async function bs(e={}){return await new Pe({host:Pt,root:ut.projectDir(),...e}).init()}var nn=kt(Lt());var tn=kt(Lt());var ws=["toml","json","ts","mts","js","mjs","cjs"];async function Le(e){let t=at__default.relative(process.cwd(),ot.config_dir);if(!e)for(let n of ws){let r=at__default.join(t,`config.${n}`);if(await V__default.access(r).then(()=>true).catch(()=>false)){e=r;break}}return e}async function xs(e){let t=await Le(e);if(!t)return {};switch(Bt(tn.default.dim(`Using config file: ${tn.default.cyan(`./${t}`)}`)),t.split(".").pop()){case "toml":return It(await V__default.readFile(t,"utf-8"));case "json":return JSON.parse(await V__default.readFile(t,"utf-8"));case "ts":case "mts":case "js":case "mjs":case "cjs":try{return (await import(at__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 Ss(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 at__default.resolve(process.cwd(),t)}async function er(e){let t=await Le(e);t&&$e(at__default.dirname(at__default.resolve(t)));let n=ve(await xs(e));if("connection"in n)return;let r=n?.db?.driver;if(r==="postgres")return;let i=n?.db?.url??(r==="pglite"?ot.default_db_dir:ot.default_db_url);return Ss(i)}async function Es(e={}){let t=process.cwd();if(e.recreate){console.log(nn.default.dim("Recreating database..."));try{let r=await er();r&&he.existsSync(r)&&(he.rmSync(r,{recursive:!0,force:!0}),console.log(nn.default.dim(` \u279C removed ${at__default.relative(t,r)}`)));}catch{}try{he.rmSync(at__default.join(t,"supabase",".temp"),{recursive:!0,force:!0});}catch{}}if(et(at__default.join(t,"supabase")),!await Le()){let r={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"&&(r.db.driver="pglite",r.db.url=at__default.relative(process.cwd(),at__default.join(t,"supabase",".temp","data")));let i=e.configFormat??"toml",s=at__default.join(t,"supabase",`config.${i}`);i==="json"?wt(s,JSON.stringify(r)):wt(s,Xe(r));}et(at__default.join(t,"supabase",".temp")),et(at__default.join(t,"supabase","schemas"),()=>{wt(at__default.join(t,"supabase","schemas","schema.sql"),e.template?Ts:`-- This is a schema file for the database
42
+ `:r}var rs={storage:"EXPERIMENTAL_STORAGE",cloud:"EXPERIMENTAL_CLOUD"},is=["storage","cloud"];Object.fromEntries(is.map(e=>[e,ss(e)]));function ss(e){let t=typeof process<"u"&&process.env||void 0;return t?t.NODE_ENV==="test"?true:t[rs[e]]==="1":false}function _e(e){let t=[],n="",r=0,i=e.length,s=false,o=false,a=0,l=/^create(\s+or\s+replace)?(\s+temp(orary)?)?$/i,c=p=>{Zn(p).length>0&&t.push(p.trim());},u=()=>{s=false,o=false,a=0;};for(;r<i;){let p=e[r],d=e[r+1];if(p==="-"&&d==="-"){for(;r<i&&e[r]!==`
43
+ `;)n+=e[r],r++;continue}if(p==="/"&&d==="*"){for(n+="/*",r+=2;r<i&&!(e[r]==="*"&&e[r+1]==="/");)n+=e[r],r++;r<i&&(n+="*/",r+=2);continue}if(p==="'"){for(n+=p,r++;r<i;){if(e[r]==="'"&&e[r+1]==="'"){n+="''",r+=2;continue}if(n+=e[r],e[r]==="'"){r++;break}r++;}continue}if(p==='"'){for(n+=p,r++;r<i;){if(e[r]==='"'&&e[r+1]==='"'){n+='""',r+=2;continue}if(n+=e[r],e[r]==='"'){r++;break}r++;}continue}if(p==="$"){let y=e.indexOf("$",r+1);if(y!==-1){let g=e.slice(r,y+1);if(/^\$[A-Za-z_][A-Za-z0-9_]*\$$|^\$\$$/.test(g)){n+=g,r=y+1;let A=e.indexOf(g,r);A===-1?(n+=e.slice(r),r=i):(n+=e.slice(r,A+g.length),r=A+g.length);continue}}}if(/[A-Za-z_]/.test(p)){let y=r;for(;y<i&&/[A-Za-z0-9_]/.test(e[y]);)y++;let g=e.slice(r,y),E=g.toLowerCase();if(E==="trigger"&&l.test(Zn(n))?s=true:s&&E==="begin"?(o=true,a++):s&&o&&E==="case"?a++:s&&o&&E==="end"&&a>0&&a--,n+=g,r=y,s&&o&&a===0){let A=r;for(;A<i&&/\s/.test(e[A]);)A++;e[A]===";"&&(r=A+1),c(n),n="",u();}continue}if(p===";"){if(s&&o&&a>0){n+=p,r++;continue}c(n),n="",u(),r++;continue}n+=p,r++;}return c(n),t}function Zn(e){let t="",n=0,r=e.length;for(;n<r;){let i=e[n],s=e[n+1];if(i==="-"&&s==="-"){for(;n<r&&e[n]!==`
44
+ `;)n++;continue}if(i==="/"&&s==="*"){for(n+=2;n<r&&!(e[n]==="*"&&e[n+1]==="/");)n++;n+=2;continue}t+=i,n++;}return t.trim()}function Ke(e){return typeof e=="number"?e:Number.parseInt(String(e),10)}var Re=class{driver=V;basePath;constructor(t){this.basePath=at.resolve(t.basePath);}filePath(t,n){return at.join(this.basePath,t,n)}async ensureDir(t){await V.mkdir(at.dirname(t),{recursive:true});}async getObject(t,n,r,i){let s=this.filePath(t,n),o=await V.stat(s),a=`"${createHash("md5").update(`${s}:${o.mtimeMs}`).digest("hex")}"`;if(i?.ifNoneMatch===a)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,n)};if(i?.ifModifiedSince){let d=new Date(i.ifModifiedSince);if(o.mtime<=d)return {httpStatusCode:304,metadata:this.buildMetadata(o,a,n)}}let l,c,u=o.size,p=200;if(i?.range){let d=i.range.match(/^bytes=(\d+)-(\d*)$/);if(d){let y=Number.parseInt(d[1],10),g=d[2]?Number.parseInt(d[2],10):o.size-1;u=g-y+1,c=`bytes ${y}-${g}/${o.size}`,p=206,l=(await V.open(s,"r")).readableWebStream();}else l=(await V.open(s,"r")).readableWebStream();}else l=(await V.open(s,"r")).readableWebStream();return {httpStatusCode:p,metadata:{...this.buildMetadata(o,a,n),contentLength:u,contentRange:c},body:l}}async uploadObject(t,n,r,i,s,o){let a=this.filePath(t,n);await this.ensureDir(a);let l;if(i instanceof Uint8Array||Buffer.isBuffer(i))l=i;else {let p=[],d=i.getReader();for(;;){let{done:y,value:g}=await d.read();if(y)break;p.push(g);}l=Buffer.concat(p);}await V.writeFile(a,l);let c=await V.stat(a),u=`"${createHash("md5").update(l).digest("hex")}"`;return {cacheControl:o,contentLength:c.size,size:c.size,mimetype:s,lastModified:c.mtime,eTag:u}}async deleteObject(t,n,r){let i=this.filePath(t,n);await V.unlink(i).catch(s=>{if(s.code!=="ENOENT")throw s});}async deleteObjects(t,n){for(let r of n)await this.deleteObject(t,r,void 0);}async copyObject(t,n,r,i,s){let o=this.filePath(t,n),a=this.filePath(t,i);await this.ensureDir(a),await V.copyFile(o,a);let l=await V.stat(a),c=await V.readFile(a);return {httpStatusCode:200,eTag:`"${createHash("md5").update(c).digest("hex")}"`,lastModified:l.mtime}}async headObject(t,n,r){let i=this.filePath(t,n),s=await V.stat(i),o=`"${createHash("md5").update(`${i}:${s.mtimeMs}`).digest("hex")}"`;return this.buildMetadata(s,o,n)}async privateAssetUrl(t,n,r){return `file://${this.filePath(t,n)}`}buildMetadata(t,n,r){return {cacheControl:"no-cache",contentLength:Ke(t.size),size:Ke(t.size),mimetype:as(r),lastModified:t.mtime,eTag:n}}};function as(e){let t=at.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 ls=new Function("spec","return import(spec)");async function Je(e,t,n){try{return await ls(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}}function $e(e,t={}){let n=at__default.resolve(t.cwd??process.cwd()),r=t.env??process.env,i=process.env.SUPABASE_ENV||"development",s=[`.env.${i}.local`,i==="test"?null:".env.local",`.env.${i}`,".env"].filter(a=>a!==null),o=fs(at__default.resolve(e),n);for(let a of o)for(let l of s){let c=at__default.join(a,l),u;try{u=de.readFileSync(c,"utf-8");}catch{continue}let p;try{p=parse(u);}catch(d){throw new Error(`Failed to parse ${c}: ${d.message}`)}for(let[d,y]of Object.entries(p))r[d]===void 0&&(r[d]=y);}}function fs(e,t){let n=[],r=e,i=at__default.parse(r).root;for(;n.push(r),!(r===t||r===i);){let s=at__default.dirname(r);if(s===r)break;r=s;}return n}var ps=/^env\((\w+)\)$/;function ve(e,t=process.env){return Ye(e,t)}function Ye(e,t){if(typeof e=="string"){let n=e.match(ps);return n?t[n[1]]??"":e}if(Array.isArray(e))return e.map(n=>Ye(n,t));if(e&&typeof e=="object"){let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)return e;let r={};for(let[i,s]of Object.entries(e))r[i]=Ye(s,t);return r}return e}var ms=process.env.LITE_VERBOSE==="1";function Bt(...e){ms&&console.error(...e);}var ds=["toml","json","ts","mts","js","mjs","cjs"],Ne=class extends At{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=at__default.relative(process.cwd(),ot.config_dir);if(!t)for(let r of ds){let i=at__default.join(n,`config.${r}`);if(await V__default.access(i).then(()=>true).catch(()=>false)){t=i;break}}return t}async readConfig(t){let n=await this.getConfigPath(t);if(!n)return {};Bt(Ut.default.dim(`Using config file: ${Ut.default.cyan(`./${n}`)}`));let r=at__default.dirname(at__default.resolve(n));$e(r);let i=n.split(".").pop(),s;switch(i){case "toml":s=It(await V__default.readFile(n,"utf-8"));break;case "json":s=JSON.parse(await V__default.readFile(n,"utf-8"));break;case "ts":case "mts":case "js":case "mjs":case "cjs":try{s=(await import(at__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 ve(s)}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,i;switch(n.db?.driver){case "sqlite":i=n.db?.url??ot.default_db_url,r=await createConnection({url:i,ddlDialect:"sqlite"});break;case "pglite":{i=n.db?.url??at__default.join(process.cwd(),ot.default_db_dir);let{createPgliteConnection:s}=await Je("@supabase/lite/pglite","pglite","@electric-sql/pglite");r=await s({url:i});break}case "postgres":{i=n.db?.url??"";let{createPostgresConnection:s}=await Je("@supabase/lite/postgres","postgres","postgres");r=await s({url:i});break}default:i=n.db?.url??ot.default_db_url,r=await createConnection({url:i,ddlDialect:"postgres"});break}if(!r)throw new Error("Failed to create connection");return Bt(Ut.default.green(" \u279C"),"Database located at",Ut.default.cyan(i??"in-memory")),{...n,connection:r}}async createApp(t){let n=await this.getConfig(t),r=new App(n);return r.config.storage?.enabled&&process.env.EXPERIMENTAL_STORAGE==="1"&&!r._storageAdapter&&(r._storageAdapter=new Re({basePath:at__default.join(process.cwd(),ot.config_dir,".temp/storage")})),await r.init()}};var ke=class extends At{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={}){let n=await this.fetch("/v1/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`Failed to create project: ${n.status} ${n.statusText}`);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 i=await this.getConfig(t);return await new App({...i.config,connection:cloud({projectRef:t,token:n.session.access_token,host:this.config.host})}).init()}};var Pe=class extends Tt{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 Ne(t),remote:new ke(t)},this}};async function bs(e={}){return await new Pe({host:Pt,root:ut.projectDir(),...e}).init()}var nn=kt(Lt());var tn=kt(Lt());var ws=["toml","json","ts","mts","js","mjs","cjs"];async function Le(e){let t=at__default.relative(process.cwd(),ot.config_dir);if(!e)for(let n of ws){let r=at__default.join(t,`config.${n}`);if(await V__default.access(r).then(()=>true).catch(()=>false)){e=r;break}}return e}async function xs(e){let t=await Le(e);if(!t)return {};switch(Bt(tn.default.dim(`Using config file: ${tn.default.cyan(`./${t}`)}`)),t.split(".").pop()){case "toml":return It(await V__default.readFile(t,"utf-8"));case "json":return JSON.parse(await V__default.readFile(t,"utf-8"));case "ts":case "mts":case "js":case "mjs":case "cjs":try{return (await import(at__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 Ss(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 at__default.resolve(process.cwd(),t)}async function er(e){let t=await Le(e);t&&$e(at__default.dirname(at__default.resolve(t)));let n=ve(await xs(e));if("connection"in n)return;let r=n?.db?.driver;if(r==="postgres")return;let i=n?.db?.url??(r==="pglite"?ot.default_db_dir:ot.default_db_url);return Ss(i)}async function Es(e={}){let t=process.cwd();if(e.recreate){console.log(nn.default.dim("Recreating database..."));try{let r=await er();r&&de.existsSync(r)&&(de.rmSync(r,{recursive:!0,force:!0}),console.log(nn.default.dim(` \u279C removed ${at__default.relative(t,r)}`)));}catch{}try{de.rmSync(at__default.join(t,"supabase",".temp"),{recursive:!0,force:!0});}catch{}}if(et(at__default.join(t,"supabase")),!await Le()){let r={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"&&(r.db.driver="pglite",r.db.url=at__default.relative(process.cwd(),at__default.join(t,"supabase",".temp","data")));let i=e.configFormat??"toml",s=at__default.join(t,"supabase",`config.${i}`);i==="json"?wt(s,JSON.stringify(r)):wt(s,Xe(r));}et(at__default.join(t,"supabase",".temp")),et(at__default.join(t,"supabase","schemas"),()=>{wt(at__default.join(t,"supabase","schemas","schema.sql"),e.template?Ts:`-- This is a schema file for the database
45
45
  `);}),wt(at__default.join(t,"supabase","seed.sql"),e.template?As:`-- This is a seed file for the database
46
46
  `);}var Ts=`
47
47
  create table todos (
@@ -56,7 +56,7 @@ create table todos (
56
56
  create table test (
57
57
  id serial primary key,
58
58
  name text not null
59
- )`,As="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 nr=createRequire(import.meta.url);function ks(e){let t=normalize(e);return t.length>1&&t[t.length-1]===sep&&(t=t.substring(0,t.length-1)),t}var Ps=/[\\/]/g;function sr(e,t){return e.replace(Ps,t)}var Ls=/^[a-z]:[\\/]$/i;function Os(e){return e==="/"||Ls.test(e)}function rn(e,t){let{resolvePaths:n,normalizePath:r,pathSeparator:i}=t,s=process.platform==="win32"&&e.includes("/")||e.startsWith(".");if(n&&(e=resolve(e)),(r||s)&&(e=ks(e)),e===".")return "";let o=e[e.length-1]!==i;return sr(o?e+i:e,i)}function or(e,t){return t+e}function Fs(e,t){return function(n,r){return r.startsWith(e)?r.slice(e.length)+n:sr(relative(e,r),t.pathSeparator)+t.pathSeparator+n}}function Is(e){return e}function Ds(e,t,n){return t+e+n}function js(e,t){let{relativePaths:n,includeBasePath:r}=t;return n&&e?Fs(e,t):r?or:Is}function Bs(e){return function(t,n){n.push(t.substring(e.length)||".");}}function Us(e){return function(t,n,r){let i=t.substring(e.length)||".";r.every(s=>s(i,true))&&n.push(i);}}var Ms=(e,t)=>{t.push(e||".");},Hs=(e,t,n)=>{let r=e||".";n.every(i=>i(r,true))&&t.push(r);},qs=()=>{};function Vs(e,t){let{includeDirs:n,filters:r,relativePaths:i}=t;return n?i?r&&r.length?Us(e):Bs(e):r&&r.length?Hs:Ms:qs}var Gs=(e,t,n,r)=>{r.every(i=>i(e,false))&&n.files++;},zs=(e,t,n,r)=>{r.every(i=>i(e,false))&&t.push(e);},Ws=(e,t,n,r)=>{n.files++;},Xs=(e,t)=>{t.push(e);},Ks=()=>{};function Js(e){let{excludeFiles:t,filters:n,onlyCounts:r}=e;return t?Ks:n&&n.length?r?Gs:zs:r?Ws:Xs}var Ys=e=>e,Qs=()=>[""].slice(0,0);function Zs(e){return e.group?Qs:Ys}var to=(e,t,n)=>{e.push({directory:t,files:n,dir:t});},eo=()=>{};function no(e){return e.group?to:eo}var ro=function(e,t,n){let{queue:r,fs:i,options:{suppressErrors:s}}=t;r.enqueue(),i.realpath(e,(o,a)=>{if(o)return r.dequeue(s?null:o,t);i.stat(a,(l,c)=>{if(l)return r.dequeue(s?null:l,t);if(c.isDirectory()&&ar(e,a,t))return r.dequeue(null,t);n(c,a),r.dequeue(null,t);});});},io=function(e,t,n){let{queue:r,fs:i,options:{suppressErrors:s}}=t;r.enqueue();try{let o=i.realpathSync(e),a=i.statSync(o);if(a.isDirectory()&&ar(e,o,t))return;n(a,o);}catch(o){if(!s)throw o}};function so(e,t){return !e.resolveSymlinks||e.excludeSymlinks?null:t?io:ro}function ar(e,t,n){if(n.options.useRealPaths)return oo(t,n);let r=dirname(e),i=1;for(;r!==n.root&&i<2;){let s=n.symlinks.get(r);!!s&&(s===t||s.startsWith(t)||t.startsWith(s))?i++:r=dirname(r);}return n.symlinks.set(e,t),i>1}function oo(e,t){return t.visited.includes(e+t.options.pathSeparator)}var ao=e=>e.counts,lo=e=>e.groups,co=e=>e.paths,uo=e=>e.paths.slice(0,e.options.maxFiles),fo=(e,t,n)=>(Oe(t,n,e.counts,e.options.suppressErrors),null),po=(e,t,n)=>(Oe(t,n,e.paths,e.options.suppressErrors),null),mo=(e,t,n)=>(Oe(t,n,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),ho=(e,t,n)=>(Oe(t,n,e.groups,e.options.suppressErrors),null);function Oe(e,t,n,r){t(e&&!r?e:null,n);}function go(e,t){let{onlyCounts:n,group:r,maxFiles:i}=e;return n?t?ao:fo:r?t?lo:ho:i?t?uo:mo:t?co:po}var lr={withFileTypes:true},yo=(e,t,n,r,i)=>{if(e.queue.enqueue(),r<0)return e.queue.dequeue(null,e);let{fs:s}=e;e.visited.push(t),e.counts.directories++,s.readdir(t||".",lr,(o,a=[])=>{i(a,n,r),e.queue.dequeue(e.options.suppressErrors?null:o,e);});},bo=(e,t,n,r,i)=>{let{fs:s}=e;if(r<0)return;e.visited.push(t),e.counts.directories++;let o=[];try{o=s.readdirSync(t||".",lr);}catch(a){if(!e.options.suppressErrors)throw a}i(o,n,r);};function wo(e){return e?bo:yo}var xo=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));}},So=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}},Eo=class{aborted=false;abort(){this.aborted=true;}},cr=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(e,t,n){this.isSynchronous=!n,this.callbackInvoker=go(t,this.isSynchronous),this.root=rn(e,t),this.state={root:Os(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new So,options:t,queue:new xo((r,i)=>this.callbackInvoker(i,r,n)),symlinks:new Map,visited:[""].slice(0,0),controller:new Eo,fs:t.fs||Ns},this.joinPath=js(this.root,t),this.pushDirectory=Vs(this.root,t),this.pushFile=Js(t),this.getArray=Zs(t),this.groupFiles=no(t),this.resolveSymlink=so(t,this.isSynchronous),this.walkDirectory=wo(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:i,resolveSymlinks:s,excludeSymlinks:o,exclude:a,maxFiles:l,signal:c,useRealPaths:u,pathSeparator:p},controller:h}=this.state;if(h.aborted||c&&c.aborted||l&&r.length>l)return;let y=this.getArray(this.state.paths);for(let g=0;g<e.length;++g){let E=e[g];if(E.isFile()||E.isSymbolicLink()&&!s&&!o){let A=this.joinPath(E.name,t);this.pushFile(A,y,this.state.counts,i);}else if(E.isDirectory()){let A=Ds(E.name,t,this.state.options.pathSeparator);if(a&&a(E.name,A))continue;this.pushDirectory(A,r,i),this.walkDirectory(this.state,A,A,n-1,this.walk);}else if(this.resolveSymlink&&E.isSymbolicLink()){let A=or(E.name,t);this.resolveSymlink(A,this.state,(q,S)=>{if(q.isDirectory()){if(S=rn(S,this.state.options),a&&a(E.name,u?S:A+p))return;this.walkDirectory(this.state,S,u?S:A+p,n-1,this.walk);}else {S=u?S:A;let M=basename(S),W=rn(dirname(S),this.state.options);S=this.joinPath(M,W),this.pushFile(S,y,this.state.counts,i);}});}}this.groupFiles(this.state.groups,t,y);}};function To(e,t){return new Promise((n,r)=>{ur(e,t,(i,s)=>{if(i)return r(i);n(s);});})}function ur(e,t,n){new cr(e,t,n).start();}function Ao(e,t){return new cr(e,t).start()}var rr=class{constructor(e,t){this.root=e,this.options=t;}withPromise(){return To(this.root,this.options)}withCallback(e){ur(this.root,this.options,e);}sync(){return Ao(this.root,this.options)}},fr=null;try{nr.resolve("picomatch"),fr=nr("picomatch");}catch{}var pr=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 rr(e||".",this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new rr(e||".",this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:true})}globWithOptions(e,...t){let n=this.globFunction||fr;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(i=>r(i)),this}};var $t=kt(Dr()),da=Array.isArray,Mr=/\\/g,ha=/^[A-Za-z]:$/,Hr=process.platform==="win32",ga=/^(\/?\.\.)+$/;function ya(e,t={}){let n=e.length,r=Array(n),i=Array(n),s,o;for(s=0;s<n;s++){let a=qr(e[s]);r[s]=a;let l=a.length,c=Array(l);for(o=0;o<l;o++)c[o]=(0, $t.default)(a[o],t);i[s]=c;}return a=>{let l=a.split("/");if(l[0]===".."&&ga.test(a))return true;for(s=0;s<n;s++){let c=r[s],u=i[s],p=l.length,h=Math.min(p,c.length);for(o=0;o<h;){let y=c[o];if(y.includes("/"))return true;if(!u[o](l[o]))break;if(!t.noglobstar&&y==="**")return true;o++;}if(o===p)return true}return false}}var ba=/^[A-Z]:\/$/i,wa=Hr?e=>ba.test(e):e=>e==="/";function jr(e,t,n){if(e===t||t.startsWith(`${e}/`)){if(n){let i=e.length+ +!wa(e);return (s,o)=>s.slice(i,o?-1:void 0)||"."}let r=t.slice(e.length+1);return r?(i,s)=>{if(i===".")return r;let o=`${r}/${i}`;return s?o.slice(0,-1):o}:(i,s)=>s&&i!=="."?i.slice(0,-1):i}return n?r=>posix.relative(e,r)||".":r=>posix.relative(e,`${t}/${r}`)||"."}function xa(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 Br(e){return e.replace(ha,t=>`${t}/`)}var Sa={parts:true};function qr(e){var t;let n=$t.default.scan(e,Sa);return !((t=n.parts)===null||t===void 0)&&t.length?n.parts:[e]}var Ea=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,Ta=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,Aa=e=>e.replace(Ea,"\\$&"),_a=e=>e.replace(Ta,"\\$&"),Ca=Hr?_a:Aa;function Ra(e,t){let n=$t.default.scan(e);return n.isGlob||n.negated}function Gt(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...e);}function Vr(e){return typeof e=="string"?[e]:e??[]}var $a=/^(\/?\.\.)+/,va=/\\(?=[()[\]{}!*+?@|])/g;function gn(e,t,n,r){var i;let s=t.cwd,o=e;e[e.length-1]==="/"&&(o=e.slice(0,-1)),o[o.length-1]!=="*"&&t.expandDirectories&&(o+="/**");let a=Ca(s);o=isAbsolute(o.replace(va,""))?posix.relative(a,o):posix.normalize(o);let l=(i=$a.exec(o))===null||i===void 0?void 0:i[0],c=qr(o);if(l){let p=(l.length+1)/3,h=0,y=a.split("/");for(;h<p&&c[h+p]===y[y.length+h-p];)o=o.slice(0,(p-h-1)*3)+o.slice((p-h)*3+c[h+p].length+1)||".",h++;let g=posix.join(s,l.slice(h*3));g[0]!=="."&&n.root.length>g.length&&(n.root=Br(g),n.depthOffset=-p+h);}if(!r&&n.depthOffset>=0){var u;(u=n.commonPath)!==null&&u!==void 0||(n.commonPath=c);let p=[],h=Math.min(n.commonPath.length,c.length);for(let y=0;y<h;y++){let g=c[y];if(g==="**"&&!c[y+1]){p.pop();break}if(y===c.length-1||g!==n.commonPath[y]||Ra(g))break;p.push(g);}n.depthOffset=p.length,n.commonPath=p,n.root=Br(p.length>0?posix.join(s,...p):s);}return o}function Na(e,t,n){let r=[],i=[];for(let s of e.ignore)s&&(s[0]!=="!"||s[1]==="(")&&i.push(gn(s,e,n,true));for(let s of t)s&&(s[0]!=="!"||s[1]==="("?r.push(gn(s,e,n,false)):(s[1]!=="!"||s[2]==="(")&&i.push(gn(s.slice(1),e,n,true)));return {match:r,ignore:i}}function ka(e,t){let n=e.cwd,r={root:n,depthOffset:0},i=Na(e,t,r);e.debug&&Gt("internal processing patterns:",i);let{absolute:s,caseSensitiveMatch:o,debug:a,dot:l,followSymbolicLinks:c,onlyDirectories:u}=e,p=r.root.replace(Mr,""),h={dot:l,nobrace:e.braceExpansion===false,nocase:!o,noextglob:e.extglob===false,noglobstar:e.globstar===false,posix:true},y=(0, $t.default)(i.match,h),g=(0, $t.default)(i.ignore,h),E=ya(i.match,h),A=jr(n,p,s),q=s?A:jr(n,p,true),S=(O,v)=>{let N=q(v,true);return N!=="."&&!E(N)||g(N)},M;e.deep!==void 0&&(M=Math.round(e.deep-r.depthOffset));let W=new pr({filters:[a?(O,v)=>{let N=A(O,v),T=y(N)&&!g(N);return T&&Gt(`matched ${N}`),T}:(O,v)=>{let N=A(O,v);return y(N)&&!g(N)}],exclude:a?(O,v)=>{let N=S(O,v);return Gt(`${N?"skipped":"crawling"} ${v}`),N}:S,fs:e.fs,pathSeparator:"/",relativePaths:!s,resolvePaths:s,includeBasePath:s,resolveSymlinks:c,excludeSymlinks:!c,excludeFiles:u,includeDirs:u||!e.onlyFiles,maxDepth:M,signal:e.signal}).crawl(p);return e.debug&&Gt("internal properties:",{...r,root:p}),[W,n!==p&&!s&&xa(n,p)]}function Pa(e,t){if(t)for(let n=e.length-1;n>=0;n--)e[n]=t(e[n]);return e}var Ur={caseSensitiveMatch:true,debug:!!process.env.TINYGLOBBY_DEBUG,expandDirectories:true,followSymbolicLinks:true,onlyFiles:true};function La(e){let t=Object.assign({},e);for(let n in Ur)t[n]===void 0&&Object.assign(t,{[n]:Ur[n]});return t.cwd=(t.cwd instanceof URL?fileURLToPath(t.cwd):resolve(t.cwd||process.cwd())).replace(Mr,"/"),t.ignore=Vr(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}),t.debug&&Gt("globbing with options:",t),t}function Oa(e,t={}){var n;if(e&&t?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let r=da(e)||typeof e=="string",i=Vr((n=r?e:e.patterns)!==null&&n!==void 0?n:"**/*"),s=La(r?t:e);return i.length>0?ka(s,i):[]}async function zt(e,t){let[n,r]=Oa(e,t);return n?Pa(await n.withPromise(),r):[]}var k=kt(Lt());function ft(e){return e.dialect==="postgres"?"pg":e.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function Ie(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 Wt(e){return `'${e.replace(/'/g,"''")}'`}function Fa(e){return `'${`{${e.map(r=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function Ia(e){return e==="sqlite"?[`CREATE TABLE IF NOT EXISTS migrations (
59
+ )`,As="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 nr=createRequire(import.meta.url);function ks(e){let t=normalize(e);return t.length>1&&t[t.length-1]===sep&&(t=t.substring(0,t.length-1)),t}var Ps=/[\\/]/g;function sr(e,t){return e.replace(Ps,t)}var Ls=/^[a-z]:[\\/]$/i;function Os(e){return e==="/"||Ls.test(e)}function rn(e,t){let{resolvePaths:n,normalizePath:r,pathSeparator:i}=t,s=process.platform==="win32"&&e.includes("/")||e.startsWith(".");if(n&&(e=resolve(e)),(r||s)&&(e=ks(e)),e===".")return "";let o=e[e.length-1]!==i;return sr(o?e+i:e,i)}function or(e,t){return t+e}function Fs(e,t){return function(n,r){return r.startsWith(e)?r.slice(e.length)+n:sr(relative(e,r),t.pathSeparator)+t.pathSeparator+n}}function Is(e){return e}function Ds(e,t,n){return t+e+n}function js(e,t){let{relativePaths:n,includeBasePath:r}=t;return n&&e?Fs(e,t):r?or:Is}function Bs(e){return function(t,n){n.push(t.substring(e.length)||".");}}function Us(e){return function(t,n,r){let i=t.substring(e.length)||".";r.every(s=>s(i,true))&&n.push(i);}}var Ms=(e,t)=>{t.push(e||".");},Hs=(e,t,n)=>{let r=e||".";n.every(i=>i(r,true))&&t.push(r);},qs=()=>{};function Vs(e,t){let{includeDirs:n,filters:r,relativePaths:i}=t;return n?i?r&&r.length?Us(e):Bs(e):r&&r.length?Hs:Ms:qs}var Gs=(e,t,n,r)=>{r.every(i=>i(e,false))&&n.files++;},zs=(e,t,n,r)=>{r.every(i=>i(e,false))&&t.push(e);},Ws=(e,t,n,r)=>{n.files++;},Xs=(e,t)=>{t.push(e);},Ks=()=>{};function Js(e){let{excludeFiles:t,filters:n,onlyCounts:r}=e;return t?Ks:n&&n.length?r?Gs:zs:r?Ws:Xs}var Ys=e=>e,Qs=()=>[""].slice(0,0);function Zs(e){return e.group?Qs:Ys}var to=(e,t,n)=>{e.push({directory:t,files:n,dir:t});},eo=()=>{};function no(e){return e.group?to:eo}var ro=function(e,t,n){let{queue:r,fs:i,options:{suppressErrors:s}}=t;r.enqueue(),i.realpath(e,(o,a)=>{if(o)return r.dequeue(s?null:o,t);i.stat(a,(l,c)=>{if(l)return r.dequeue(s?null:l,t);if(c.isDirectory()&&ar(e,a,t))return r.dequeue(null,t);n(c,a),r.dequeue(null,t);});});},io=function(e,t,n){let{queue:r,fs:i,options:{suppressErrors:s}}=t;r.enqueue();try{let o=i.realpathSync(e),a=i.statSync(o);if(a.isDirectory()&&ar(e,o,t))return;n(a,o);}catch(o){if(!s)throw o}};function so(e,t){return !e.resolveSymlinks||e.excludeSymlinks?null:t?io:ro}function ar(e,t,n){if(n.options.useRealPaths)return oo(t,n);let r=dirname(e),i=1;for(;r!==n.root&&i<2;){let s=n.symlinks.get(r);!!s&&(s===t||s.startsWith(t)||t.startsWith(s))?i++:r=dirname(r);}return n.symlinks.set(e,t),i>1}function oo(e,t){return t.visited.includes(e+t.options.pathSeparator)}var ao=e=>e.counts,lo=e=>e.groups,co=e=>e.paths,uo=e=>e.paths.slice(0,e.options.maxFiles),fo=(e,t,n)=>(Oe(t,n,e.counts,e.options.suppressErrors),null),po=(e,t,n)=>(Oe(t,n,e.paths,e.options.suppressErrors),null),mo=(e,t,n)=>(Oe(t,n,e.paths.slice(0,e.options.maxFiles),e.options.suppressErrors),null),ho=(e,t,n)=>(Oe(t,n,e.groups,e.options.suppressErrors),null);function Oe(e,t,n,r){t(e&&!r?e:null,n);}function go(e,t){let{onlyCounts:n,group:r,maxFiles:i}=e;return n?t?ao:fo:r?t?lo:ho:i?t?uo:mo:t?co:po}var lr={withFileTypes:true},yo=(e,t,n,r,i)=>{if(e.queue.enqueue(),r<0)return e.queue.dequeue(null,e);let{fs:s}=e;e.visited.push(t),e.counts.directories++,s.readdir(t||".",lr,(o,a=[])=>{i(a,n,r),e.queue.dequeue(e.options.suppressErrors?null:o,e);});},bo=(e,t,n,r,i)=>{let{fs:s}=e;if(r<0)return;e.visited.push(t),e.counts.directories++;let o=[];try{o=s.readdirSync(t||".",lr);}catch(a){if(!e.options.suppressErrors)throw a}i(o,n,r);};function wo(e){return e?bo:yo}var xo=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));}},So=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}},Eo=class{aborted=false;abort(){this.aborted=true;}},cr=class{root;isSynchronous;state;joinPath;pushDirectory;pushFile;getArray;groupFiles;resolveSymlink;walkDirectory;callbackInvoker;constructor(e,t,n){this.isSynchronous=!n,this.callbackInvoker=go(t,this.isSynchronous),this.root=rn(e,t),this.state={root:Os(this.root)?this.root:this.root.slice(0,-1),paths:[""].slice(0,0),groups:[],counts:new So,options:t,queue:new xo((r,i)=>this.callbackInvoker(i,r,n)),symlinks:new Map,visited:[""].slice(0,0),controller:new Eo,fs:t.fs||Ns},this.joinPath=js(this.root,t),this.pushDirectory=Vs(this.root,t),this.pushFile=Js(t),this.getArray=Zs(t),this.groupFiles=no(t),this.resolveSymlink=so(t,this.isSynchronous),this.walkDirectory=wo(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:i,resolveSymlinks:s,excludeSymlinks:o,exclude:a,maxFiles:l,signal:c,useRealPaths:u,pathSeparator:p},controller:d}=this.state;if(d.aborted||c&&c.aborted||l&&r.length>l)return;let y=this.getArray(this.state.paths);for(let g=0;g<e.length;++g){let E=e[g];if(E.isFile()||E.isSymbolicLink()&&!s&&!o){let A=this.joinPath(E.name,t);this.pushFile(A,y,this.state.counts,i);}else if(E.isDirectory()){let A=Ds(E.name,t,this.state.options.pathSeparator);if(a&&a(E.name,A))continue;this.pushDirectory(A,r,i),this.walkDirectory(this.state,A,A,n-1,this.walk);}else if(this.resolveSymlink&&E.isSymbolicLink()){let A=or(E.name,t);this.resolveSymlink(A,this.state,(q,S)=>{if(q.isDirectory()){if(S=rn(S,this.state.options),a&&a(E.name,u?S:A+p))return;this.walkDirectory(this.state,S,u?S:A+p,n-1,this.walk);}else {S=u?S:A;let M=basename(S),W=rn(dirname(S),this.state.options);S=this.joinPath(M,W),this.pushFile(S,y,this.state.counts,i);}});}}this.groupFiles(this.state.groups,t,y);}};function To(e,t){return new Promise((n,r)=>{ur(e,t,(i,s)=>{if(i)return r(i);n(s);});})}function ur(e,t,n){new cr(e,t,n).start();}function Ao(e,t){return new cr(e,t).start()}var rr=class{constructor(e,t){this.root=e,this.options=t;}withPromise(){return To(this.root,this.options)}withCallback(e){ur(this.root,this.options,e);}sync(){return Ao(this.root,this.options)}},fr=null;try{nr.resolve("picomatch"),fr=nr("picomatch");}catch{}var pr=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 rr(e||".",this.options)}withGlobFunction(e){return this.globFunction=e,this}crawlWithOptions(e,t){return this.options={...this.options,...t},new rr(e||".",this.options)}glob(...e){return this.globFunction?this.globWithOptions(e):this.globWithOptions(e,{dot:true})}globWithOptions(e,...t){let n=this.globFunction||fr;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(i=>r(i)),this}};var $t=kt(Dr()),ha=Array.isArray,Mr=/\\/g,da=/^[A-Za-z]:$/,Hr=process.platform==="win32",ga=/^(\/?\.\.)+$/;function ya(e,t={}){let n=e.length,r=Array(n),i=Array(n),s,o;for(s=0;s<n;s++){let a=qr(e[s]);r[s]=a;let l=a.length,c=Array(l);for(o=0;o<l;o++)c[o]=(0, $t.default)(a[o],t);i[s]=c;}return a=>{let l=a.split("/");if(l[0]===".."&&ga.test(a))return true;for(s=0;s<n;s++){let c=r[s],u=i[s],p=l.length,d=Math.min(p,c.length);for(o=0;o<d;){let y=c[o];if(y.includes("/"))return true;if(!u[o](l[o]))break;if(!t.noglobstar&&y==="**")return true;o++;}if(o===p)return true}return false}}var ba=/^[A-Z]:\/$/i,wa=Hr?e=>ba.test(e):e=>e==="/";function jr(e,t,n){if(e===t||t.startsWith(`${e}/`)){if(n){let i=e.length+ +!wa(e);return (s,o)=>s.slice(i,o?-1:void 0)||"."}let r=t.slice(e.length+1);return r?(i,s)=>{if(i===".")return r;let o=`${r}/${i}`;return s?o.slice(0,-1):o}:(i,s)=>s&&i!=="."?i.slice(0,-1):i}return n?r=>posix.relative(e,r)||".":r=>posix.relative(e,`${t}/${r}`)||"."}function xa(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 Br(e){return e.replace(da,t=>`${t}/`)}var Sa={parts:true};function qr(e){var t;let n=$t.default.scan(e,Sa);return !((t=n.parts)===null||t===void 0)&&t.length?n.parts:[e]}var Ea=/(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g,Ta=/(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g,Aa=e=>e.replace(Ea,"\\$&"),_a=e=>e.replace(Ta,"\\$&"),Ca=Hr?_a:Aa;function Ra(e,t){let n=$t.default.scan(e);return n.isGlob||n.negated}function Gt(...e){console.log(`[tinyglobby ${new Date().toLocaleTimeString("es")}]`,...e);}function Vr(e){return typeof e=="string"?[e]:e??[]}var $a=/^(\/?\.\.)+/,va=/\\(?=[()[\]{}!*+?@|])/g;function gn(e,t,n,r){var i;let s=t.cwd,o=e;e[e.length-1]==="/"&&(o=e.slice(0,-1)),o[o.length-1]!=="*"&&t.expandDirectories&&(o+="/**");let a=Ca(s);o=isAbsolute(o.replace(va,""))?posix.relative(a,o):posix.normalize(o);let l=(i=$a.exec(o))===null||i===void 0?void 0:i[0],c=qr(o);if(l){let p=(l.length+1)/3,d=0,y=a.split("/");for(;d<p&&c[d+p]===y[y.length+d-p];)o=o.slice(0,(p-d-1)*3)+o.slice((p-d)*3+c[d+p].length+1)||".",d++;let g=posix.join(s,l.slice(d*3));g[0]!=="."&&n.root.length>g.length&&(n.root=Br(g),n.depthOffset=-p+d);}if(!r&&n.depthOffset>=0){var u;(u=n.commonPath)!==null&&u!==void 0||(n.commonPath=c);let p=[],d=Math.min(n.commonPath.length,c.length);for(let y=0;y<d;y++){let g=c[y];if(g==="**"&&!c[y+1]){p.pop();break}if(y===c.length-1||g!==n.commonPath[y]||Ra(g))break;p.push(g);}n.depthOffset=p.length,n.commonPath=p,n.root=Br(p.length>0?posix.join(s,...p):s);}return o}function Na(e,t,n){let r=[],i=[];for(let s of e.ignore)s&&(s[0]!=="!"||s[1]==="(")&&i.push(gn(s,e,n,true));for(let s of t)s&&(s[0]!=="!"||s[1]==="("?r.push(gn(s,e,n,false)):(s[1]!=="!"||s[2]==="(")&&i.push(gn(s.slice(1),e,n,true)));return {match:r,ignore:i}}function ka(e,t){let n=e.cwd,r={root:n,depthOffset:0},i=Na(e,t,r);e.debug&&Gt("internal processing patterns:",i);let{absolute:s,caseSensitiveMatch:o,debug:a,dot:l,followSymbolicLinks:c,onlyDirectories:u}=e,p=r.root.replace(Mr,""),d={dot:l,nobrace:e.braceExpansion===false,nocase:!o,noextglob:e.extglob===false,noglobstar:e.globstar===false,posix:true},y=(0, $t.default)(i.match,d),g=(0, $t.default)(i.ignore,d),E=ya(i.match,d),A=jr(n,p,s),q=s?A:jr(n,p,true),S=(O,v)=>{let N=q(v,true);return N!=="."&&!E(N)||g(N)},M;e.deep!==void 0&&(M=Math.round(e.deep-r.depthOffset));let W=new pr({filters:[a?(O,v)=>{let N=A(O,v),T=y(N)&&!g(N);return T&&Gt(`matched ${N}`),T}:(O,v)=>{let N=A(O,v);return y(N)&&!g(N)}],exclude:a?(O,v)=>{let N=S(O,v);return Gt(`${N?"skipped":"crawling"} ${v}`),N}:S,fs:e.fs,pathSeparator:"/",relativePaths:!s,resolvePaths:s,includeBasePath:s,resolveSymlinks:c,excludeSymlinks:!c,excludeFiles:u,includeDirs:u||!e.onlyFiles,maxDepth:M,signal:e.signal}).crawl(p);return e.debug&&Gt("internal properties:",{...r,root:p}),[W,n!==p&&!s&&xa(n,p)]}function Pa(e,t){if(t)for(let n=e.length-1;n>=0;n--)e[n]=t(e[n]);return e}var Ur={caseSensitiveMatch:true,debug:!!process.env.TINYGLOBBY_DEBUG,expandDirectories:true,followSymbolicLinks:true,onlyFiles:true};function La(e){let t=Object.assign({},e);for(let n in Ur)t[n]===void 0&&Object.assign(t,{[n]:Ur[n]});return t.cwd=(t.cwd instanceof URL?fileURLToPath(t.cwd):resolve(t.cwd||process.cwd())).replace(Mr,"/"),t.ignore=Vr(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}),t.debug&&Gt("globbing with options:",t),t}function Oa(e,t={}){var n;if(e&&t?.patterns)throw new Error("Cannot pass patterns as both an argument and an option");let r=ha(e)||typeof e=="string",i=Vr((n=r?e:e.patterns)!==null&&n!==void 0?n:"**/*"),s=La(r?t:e);return i.length>0?ka(s,i):[]}async function zt(e,t){let[n,r]=Oa(e,t);return n?Pa(await n.withPromise(),r):[]}var k=kt(Lt());function ft(e){return e.dialect==="postgres"?"pg":e.config?.ddlDialect==="sqlite"?"sqlite":"pg-flat"}function Ie(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 Wt(e){return `'${e.replace(/'/g,"''")}'`}function Fa(e){return `'${`{${e.map(r=>`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`).join(",")}}`.replace(/'/g,"''")}'`}function Ia(e){return e==="sqlite"?[`CREATE TABLE IF NOT EXISTS migrations (
60
60
  version TEXT NOT NULL PRIMARY KEY,
61
61
  statements TEXT,
62
62
  name TEXT
@@ -75,7 +75,7 @@ create table test (
75
75
  ${c}`)}return o.reduce((l,c)=>l+c.statements.length,0)}async function Rl(e){await Cl(e);}async function $l(e){let t=await zt(e.config?.db?.migrations?.schema_paths??["./schemas/*.sql"],{cwd:at__default.join(process.cwd(),"supabase"),absolute:true}),n=await Promise.all(t.map(async r=>await V__default.readFile(r,"utf-8"))).then(r=>r.map(i=>i.split(`
76
76
  `).filter(s=>s.trim().length>0&&!s.trim().startsWith("--")).join(`
77
77
  `)).join(`
78
- `));return n||""}async function wi(e,t){let n=await $l(e);if(!(!n&&(await Xt(e)).length>0)&&!(!n&&!e.connection.config.baseSchema)){if(t?.dbHasTables&&await Nl(e,n,t.dbFingerprint)){console.log(k.default.dim("Schema unchanged \u2014 skipping translation."));return}try{let r=e.connection.createMigrator(n),i=await r.diff(),s=r.translationResult?.ast,o=await e.connection.introspect(),a=jn(o);if(i.plan.steps.length===0){await gi(e,n,s,a);return}await r.migratePlan(i.plan,{force:t?.force??!1}),Ol(i);let l=await e.connection.introspect();return await gi(e,n,s,jn(l)),console.log(""),Fl(i),i}catch(r){if(String(r).includes("likely empty"))console.log(k.default.dim("Nothing to migrate."));else {console.error("Migration error: "+String(r));try{await e.connection.exec("rollback");}catch{}}}}}function vl(e){return e.connection.config?.baseSchema??""}function xi(e,t){let n=createHash("sha256");return n.update(JSON.stringify([vl(e),t??""])),n.digest("hex")}function jn(e){let t=(r,i)=>[...r].sort((s,o)=>i(s).localeCompare(i(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 Nl(e,t,n){let r=e.connection;if(typeof r.updateDeparseInfo!="function")return false;let i=at__default.join(process.cwd(),yi),s;try{s=await V__default.readFile(i,"utf-8");}catch{return false}let o;try{o=JSON.parse(s);}catch{return false}if(o.v!==bi||o.hash!==xi(e,t)||!n||o.dbFingerprint!==n||!o.ast||typeof o.ast!="object")return false;try{let a=await Promise.resolve().then(()=>(di(),mi)),l=o.ast,c=a.collectEnums(l),u=a.collectSchema(l,c),p=a.collectVariables(l),h=a.collectTableConstraints(l),y=a.collectComments(l),g=r.config?.translation?.schemas?.defaultSchema,{policies:E,tables:A}=a.collectPolicies(l,{defaultSchema:g});return r.updateDeparseInfo({enums:c,rls:{tables:A,policies:E},schema:u,vars:p,tableConstraints:h,comments:y}),!0}catch{return false}}async function gi(e,t,n,r){if(!n||typeof n!="object")return;let i={v:bi,hash:xi(e,t),dbFingerprint:r,ast:n},s=at__default.join(process.cwd(),yi);try{await V__default.mkdir(at__default.dirname(s),{recursive:!0}),await V__default.writeFile(s,JSON.stringify(i),"utf-8");}catch{}}function Si(e,t){console.log();let n=(i,s)=>{let o=l=>{let c=k.default.dim;return typeof l=="number"&&(l>=0&&(c=l>0?k.default.green:k.default.dim),l<0&&(c=k.default.red)),typeof l=="boolean"?l?k.default.green("\u2713"):k.default.red("\u2717"):c(String(l))},a=Object.entries(s).map(([l,c])=>`${l}: ${o(c)}`).join(k.default.dim(" / "));console.log(`${k.default.dim("[")} ${i} ${k.default.dim("]")} ${a}`);};n(k.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(k.default.green("AUTH"),{enabled:!!t.config.auth?.enabled,tables:ensureVar.Set(r.tables).size,policies:ensureVar.Array(r.policies).length});}function kl(e,t){setTimeout(()=>{console.log(k.default.dim("Watching for changes...")),El.watch("./supabase/schemas").on("change",async r=>{console.log(),console.log(k.default.dim(`Schema changed: ${r}`)),await wi(e,t);let i=await e.connection.introspect();Si(i,e);});},200);}function Pl(e,t){let n=r=>r;return e.plan.steps.flatMap(r=>[r.description?n(`-- ${r.description}`):"",r.sql+`
78
+ `));return n||""}async function wi(e,t){let n=await $l(e);if(!(!n&&(await Xt(e)).length>0)&&!(!n&&!e.connection.config.baseSchema)){if(t?.dbHasTables&&await Nl(e,n,t.dbFingerprint)){console.log(k.default.dim("Schema unchanged \u2014 skipping translation."));return}try{let r=e.connection.createMigrator(n),i=await r.diff(),s=r.translationResult?.ast,o=await e.connection.introspect(),a=jn(o);if(i.plan.steps.length===0){await gi(e,n,s,a);return}await r.migratePlan(i.plan,{force:t?.force??!1}),Ol(i);let l=await e.connection.introspect();return await gi(e,n,s,jn(l)),console.log(""),Fl(i),i}catch(r){if(String(r).includes("likely empty"))console.log(k.default.dim("Nothing to migrate."));else {console.error("Migration error: "+String(r));try{await e.connection.exec("rollback");}catch{}}}}}function vl(e){return e.connection.config?.baseSchema??""}function xi(e,t){let n=createHash("sha256");return n.update(JSON.stringify([vl(e),t??""])),n.digest("hex")}function jn(e){let t=(r,i)=>[...r].sort((s,o)=>i(s).localeCompare(i(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 Nl(e,t,n){let r=e.connection;if(typeof r.updateDeparseInfo!="function")return false;let i=at__default.join(process.cwd(),yi),s;try{s=await V__default.readFile(i,"utf-8");}catch{return false}let o;try{o=JSON.parse(s);}catch{return false}if(o.v!==bi||o.hash!==xi(e,t)||!n||o.dbFingerprint!==n||!o.ast||typeof o.ast!="object")return false;try{let a=await Promise.resolve().then(()=>(hi(),mi)),l=o.ast,c=a.collectEnums(l),u=a.collectSchema(l,c),p=a.collectVariables(l),d=a.collectTableConstraints(l),y=a.collectComments(l),g=r.config?.translation?.schemas?.defaultSchema,{policies:E,tables:A}=a.collectPolicies(l,{defaultSchema:g});return r.updateDeparseInfo({enums:c,rls:{tables:A,policies:E},schema:u,vars:p,tableConstraints:d,comments:y}),!0}catch{return false}}async function gi(e,t,n,r){if(!n||typeof n!="object")return;let i={v:bi,hash:xi(e,t),dbFingerprint:r,ast:n},s=at__default.join(process.cwd(),yi);try{await V__default.mkdir(at__default.dirname(s),{recursive:!0}),await V__default.writeFile(s,JSON.stringify(i),"utf-8");}catch{}}function Si(e,t){console.log();let n=(i,s)=>{let o=l=>{let c=k.default.dim;return typeof l=="number"&&(l>=0&&(c=l>0?k.default.green:k.default.dim),l<0&&(c=k.default.red)),typeof l=="boolean"?l?k.default.green("\u2713"):k.default.red("\u2717"):c(String(l))},a=Object.entries(s).map(([l,c])=>`${l}: ${o(c)}`).join(k.default.dim(" / "));console.log(`${k.default.dim("[")} ${i} ${k.default.dim("]")} ${a}`);};n(k.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(k.default.green("AUTH"),{enabled:!!t.config.auth?.enabled,tables:ensureVar.Set(r.tables).size,policies:ensureVar.Array(r.policies).length});}function kl(e,t){setTimeout(()=>{console.log(k.default.dim("Watching for changes...")),El.watch("./supabase/schemas").on("change",async r=>{console.log(),console.log(k.default.dim(`Schema changed: ${r}`)),await wi(e,t);let i=await e.connection.introspect();Si(i,e);});},200);}function Pl(e,t){let n=r=>r;return e.plan.steps.flatMap(r=>[r.description?n(`-- ${r.description}`):"",r.sql+`
79
79
  `]).filter(r=>r.trim().length>0).join(`
80
80
  `)}function Ll(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 Ol(e,t){let n="./supabase/.temp/migrations";et(n);let r=Ll(),i=Pl(e);wt(at__default.join(n,r),i),console.log(k.default.dim(`Migration written to ${k.default.cyan(at__default.join(n,r))}`));}function Fl({diff:e}){if(typeof e=="string"){console.log(k.default.cyan(e));return}if(!e.has_changes)return;console.log(k.default.bgWhite(k.default.black(" Schema Diff "))),console.log();let t={added:{color:k.default.green,symbol:"+"},removed:{color:k.default.red,symbol:"-"},modified:{color:k.default.yellow,symbol:"~"}};if(e.tables.length>0){console.log(k.default.dim("Tables:"));for(let n of e.tables){let{color:r,symbol:i}=t[n.type];console.log(r(`${i} ${n.name}`));}console.log();}if(e.columns.length>0){console.log(k.default.dim("Columns:"));for(let n of e.columns){let{color:r,symbol:i}=t[n.type],s="";n.changes&&(s=Object.entries(n.changes).map(([o,a])=>`${o}: ${a.from} \u2192 ${a.to}`).join(", ")),console.log(r(`${i} ${n.table}.${n.name}${s?` (${s})`:""}`));}console.log();}if(e.indexes.length>0){console.log(k.default.dim("Indexes:"));for(let n of e.indexes){let{color:r,symbol:i}=t[n.type];console.log(r(`${i} ${n.name} on ${n.table}`));}console.log();}if(e.foreign_keys.length>0){console.log(k.default.dim("Foreign Keys:"));for(let n of e.foreign_keys){let{color:r,symbol:i}=t[n.type];console.log(r(`${i} ${n.table}.${n.column} \u2192 ${n.ref_table}.${n.ref_column}`));}console.log();}}var Mn=["anon","authenticated","service_role"];function Il(e){return e==="service_role"?"NOLOGIN BYPASSRLS":"NOLOGIN"}function Hn(e){return e.size===0?"":`DO $$ BEGIN${[...e].map(n=>`
81
81
  IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '${n}') THEN