@vitnode/core 1.2.0-canary.17 → 1.2.0-canary.18

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.
@@ -3,17 +3,15 @@ import 'tsx/esm';
3
3
  import { createRequire } from 'module';
4
4
  const require = createRequire(import.meta.url);
5
5
 
6
- var Jo=Object.create;var Ps=Object.defineProperty;var Yo=Object.getOwnPropertyDescriptor;var Ho=Object.getOwnPropertyNames;var Go=Object.getPrototypeOf,Zo=Object.prototype.hasOwnProperty;var St=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var $s=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Xo=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ho(e))!Zo.call(r,s)&&s!==t&&Ps(r,s,{get:()=>e[s],enumerable:!(i=Yo(e,s))||i.enumerable});return r};var ea=(r,e,t)=>(t=r!=null?Jo(Go(r)):{},Xo(e||!r||!r.__esModule?Ps(t,"default",{value:r,enumerable:!0}):t,r));var sn=$s((pc,al)=>{al.exports={name:"dotenv",version:"16.5.0",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var cn=$s((gc,ge)=>{"use strict";var Tr=St("fs"),Cr=St("path"),ll=St("os"),cl=St("crypto"),ul=sn(),on=ul.version,fl=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function ml(r){let e={},t=r.toString();t=t.replace(/\r\n?/mg,`
7
- `);let i;for(;(i=fl.exec(t))!=null;){let s=i[1],n=i[2]||"";n=n.trim();let o=n[0];n=n.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),o==='"'&&(n=n.replace(/\\n/g,`
8
- `),n=n.replace(/\\r/g,"\r")),e[s]=n}return e}function dl(r){let e=ln(r),t=B.configDotenv({path:e});if(!t.parsed){let o=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw o.code="MISSING_DATA",o}let i=an(r).split(","),s=i.length,n;for(let o=0;o<s;o++)try{let a=i[o].trim(),u=pl(t,a);n=B.decrypt(u.ciphertext,u.key);break}catch(a){if(o+1>=s)throw a}return B.parse(n)}function hl(r){console.log(`[dotenv@${on}][WARN] ${r}`)}function Je(r){console.log(`[dotenv@${on}][DEBUG] ${r}`)}function an(r){return r&&r.DOTENV_KEY&&r.DOTENV_KEY.length>0?r.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function pl(r,e){let t;try{t=new URL(e)}catch(a){if(a.code==="ERR_INVALID_URL"){let u=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw u.code="INVALID_DOTENV_KEY",u}throw a}let i=t.password;if(!i){let a=new Error("INVALID_DOTENV_KEY: Missing key part");throw a.code="INVALID_DOTENV_KEY",a}let s=t.searchParams.get("environment");if(!s){let a=new Error("INVALID_DOTENV_KEY: Missing environment part");throw a.code="INVALID_DOTENV_KEY",a}let n=`DOTENV_VAULT_${s.toUpperCase()}`,o=r.parsed[n];if(!o){let a=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${n} in your .env.vault file.`);throw a.code="NOT_FOUND_DOTENV_ENVIRONMENT",a}return{ciphertext:o,key:i}}function ln(r){let e=null;if(r&&r.path&&r.path.length>0)if(Array.isArray(r.path))for(let t of r.path)Tr.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=r.path.endsWith(".vault")?r.path:`${r.path}.vault`;else e=Cr.resolve(process.cwd(),".env.vault");return Tr.existsSync(e)?e:null}function nn(r){return r[0]==="~"?Cr.join(ll.homedir(),r.slice(1)):r}function gl(r){!!(r&&r.debug)&&Je("Loading env from encrypted .env.vault");let t=B._parseVault(r),i=process.env;return r&&r.processEnv!=null&&(i=r.processEnv),B.populate(i,t,r),{parsed:t}}function yl(r){let e=Cr.resolve(process.cwd(),".env"),t="utf8",i=!!(r&&r.debug);r&&r.encoding?t=r.encoding:i&&Je("No encoding is specified. UTF-8 is used by default");let s=[e];if(r&&r.path)if(!Array.isArray(r.path))s=[nn(r.path)];else{s=[];for(let u of r.path)s.push(nn(u))}let n,o={};for(let u of s)try{let m=B.parse(Tr.readFileSync(u,{encoding:t}));B.populate(o,m,r)}catch(m){i&&Je(`Failed to load ${u} ${m.message}`),n=m}let a=process.env;return r&&r.processEnv!=null&&(a=r.processEnv),B.populate(a,o,r),n?{parsed:o,error:n}:{parsed:o}}function wl(r){if(an(r).length===0)return B.configDotenv(r);let e=ln(r);return e?B._configVault(r):(hl(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),B.configDotenv(r))}function bl(r,e){let t=Buffer.from(e.slice(-64),"hex"),i=Buffer.from(r,"base64"),s=i.subarray(0,12),n=i.subarray(-16);i=i.subarray(12,-16);try{let o=cl.createDecipheriv("aes-256-gcm",t,s);return o.setAuthTag(n),`${o.update(i)}${o.final()}`}catch(o){let a=o instanceof RangeError,u=o.message==="Invalid key length",m=o.message==="Unsupported state or unable to authenticate data";if(a||u){let c=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw c.code="INVALID_DOTENV_KEY",c}else if(m){let c=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw c.code="DECRYPTION_FAILED",c}else throw o}}function _l(r,e,t={}){let i=!!(t&&t.debug),s=!!(t&&t.override);if(typeof e!="object"){let n=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw n.code="OBJECT_REQUIRED",n}for(let n of Object.keys(e))Object.prototype.hasOwnProperty.call(r,n)?(s===!0&&(r[n]=e[n]),i&&Je(s===!0?`"${n}" is already defined and WAS overwritten`:`"${n}" is already defined and was NOT overwritten`)):r[n]=e[n]}var B={configDotenv:yl,_configVault:gl,_parseVault:dl,config:wl,decrypt:bl,parse:ml,populate:_l};ge.exports.configDotenv=B.configDotenv;ge.exports._configVault=B._configVault;ge.exports._parseVault=B._parseVault;ge.exports.config=B.config;ge.exports.decrypt=B.decrypt;ge.exports.parse=B.parse;ge.exports.populate=B.populate;ge.exports=B});import{stat as Da}from"fs";import{stat as Aa,readdir as Ia}from"fs/promises";import{EventEmitter as La}from"events";import*as T from"path";import{stat as ta,lstat as Es,readdir as ra,realpath as ia}from"fs/promises";import{Readable as sa}from"stream";import{resolve as Ds,relative as na,join as oa,sep as aa}from"path";var ie={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},fr={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:ie.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(fr);var Fs="READDIRP_RECURSIVE_ERROR",la=new Set(["ENOENT","EPERM","EACCES","ELOOP",Fs]),As=[ie.DIR_TYPE,ie.EVERYTHING_TYPE,ie.FILE_DIR_TYPE,ie.FILE_TYPE],ca=new Set([ie.DIR_TYPE,ie.EVERYTHING_TYPE,ie.FILE_DIR_TYPE]),ua=new Set([ie.EVERYTHING_TYPE,ie.FILE_DIR_TYPE,ie.FILE_TYPE]),fa=r=>la.has(r.code),ma=process.platform==="win32",Is=r=>!0,Ls=r=>{if(r===void 0)return Is;if(typeof r=="function")return r;if(typeof r=="string"){let e=r.trim();return t=>t.basename===e}if(Array.isArray(r)){let e=r.map(t=>t.trim());return t=>e.some(i=>t.basename===i)}return Is},mr=class extends sa{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...fr,...e},{root:i,type:s}=t;this._fileFilter=Ls(t.fileFilter),this._directoryFilter=Ls(t.directoryFilter);let n=t.lstat?Es:ta;ma?this._stat=o=>n(o,{bigint:!0}):this._stat=n,this._maxDepth=t.depth??fr.depth,this._wantsDir=s?ca.has(s):!1,this._wantsFile=s?ua.has(s):!1,this._wantsEverything=s===ie.EVERYTHING_TYPE,this._root=Ds(i),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(i,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,i=t&&t.files;if(i&&i.length>0){let{path:s,depth:n}=t,o=i.splice(0,e).map(u=>this._formatEntry(u,s)),a=await Promise.all(o);for(let u of a){if(!u)continue;if(this.destroyed)return;let m=await this._getEntryType(u);m==="directory"&&this._directoryFilter(u)?(n<=this._maxDepth&&this.parents.push(this._exploreDir(u.fullPath,n+1)),this._wantsDir&&(this.push(u),e--)):(m==="file"||this._includeAsFile(u))&&this._fileFilter(u)&&this._wantsFile&&(this.push(u),e--)}}else{let s=this.parents.pop();if(!s){this.push(null);break}if(this.parent=await s,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let i;try{i=await ra(e,this._rdOptions)}catch(s){this._onError(s)}return{files:i,depth:t,path:e}}async _formatEntry(e,t){let i,s=this._isDirent?e.name:e;try{let n=Ds(oa(t,s));i={path:na(this._root,n),fullPath:n,basename:s},i[this._statsProp]=this._isDirent?e:await this._stat(n)}catch(n){this._onError(n);return}return i}_onError(e){fa(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return"";let t=e[this._statsProp];if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let i=e.fullPath;try{let s=await ia(i),n=await Es(s);if(n.isFile())return"file";if(n.isDirectory()){let o=s.length;if(i.startsWith(s)&&i.substr(o,1)===aa){let a=new Error(`Circular symlink detected: "${i}" points to "${s}"`);return a.code=Fs,this._onError(a)}return"directory"}}catch(s){return this._onError(s),""}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function Os(r,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=ie.FILE_DIR_TYPE),t&&(e.type=t),r){if(typeof r!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(t&&!As.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${As.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new mr(e)}import{watchFile as da,unwatchFile as qs,watch as ha}from"fs";import{open as pa,stat as zs,lstat as ga,realpath as dr}from"fs/promises";import*as F from"path";import{type as ya}from"os";var wa="data",gr="end",Rs="close",Ct=()=>{};var Pt=process.platform,yr=Pt==="win32",ba=Pt==="darwin",_a=Pt==="linux",Sa=Pt==="freebsd",Qs=ya()==="OS400",q={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},ne=q,xa="watch",va={lstat:ga,stat:zs},Te="listeners",xt="errHandlers",Ie="rawEmitters",Na=[Te,xt,Ie],Ta=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),Ca=r=>Ta.has(F.extname(r).slice(1).toLowerCase()),pr=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},Ke=(r,e,t)=>{let i=r[e];i instanceof Set||(r[e]=i=new Set([i])),i.add(t)},Pa=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},Be=(r,e,t)=>{let i=r[e];i instanceof Set?i.delete(t):i===t&&delete r[e]},ks=r=>r instanceof Set?r.size===0:!r,vt=new Map;function js(r,e,t,i,s){let n=(o,a)=>{t(r),s(o,a,{watchedPath:r}),a&&r!==a&&Nt(F.resolve(r,a),Te,F.join(r,a))};try{return ha(r,{persistent:e.persistent},n)}catch(o){i(o);return}}var Nt=(r,e,t,i,s)=>{let n=vt.get(r);n&&pr(n[e],o=>{o(t,i,s)})},$a=(r,e,t,i)=>{let{listener:s,errHandler:n,rawEmitter:o}=i,a=vt.get(e),u;if(!t.persistent)return u=js(r,t,s,n,o),u?u.close.bind(u):void 0;if(a)Ke(a,Te,s),Ke(a,xt,n),Ke(a,Ie,o);else{if(u=js(r,t,Nt.bind(null,e,Te),n,Nt.bind(null,e,Ie)),!u)return;u.on(ne.ERROR,async m=>{let c=Nt.bind(null,e,xt);if(a&&(a.watcherUnusable=!0),yr&&m.code==="EPERM")try{await(await pa(r,"r")).close(),c(m)}catch{}else c(m)}),a={listeners:s,errHandlers:n,rawEmitters:o,watcher:u},vt.set(e,a)}return()=>{Be(a,Te,s),Be(a,xt,n),Be(a,Ie,o),ks(a.listeners)&&(a.watcher.close(),vt.delete(e),Na.forEach(Pa(a)),a.watcher=void 0,Object.freeze(a))}},hr=new Map,Ea=(r,e,t,i)=>{let{listener:s,rawEmitter:n}=i,o=hr.get(e),a=o&&o.options;return a&&(a.persistent<t.persistent||a.interval>t.interval)&&(qs(e),o=void 0),o?(Ke(o,Te,s),Ke(o,Ie,n)):(o={listeners:s,rawEmitters:n,options:t,watcher:da(e,t,(u,m)=>{pr(o.rawEmitters,h=>{h(ne.CHANGE,e,{curr:u,prev:m})});let c=u.mtimeMs;(u.size!==m.size||c>m.mtimeMs||c===0)&&pr(o.listeners,h=>h(r,u))})},hr.set(e,o)),()=>{Be(o,Te,s),Be(o,Ie,n),ks(o.listeners)&&(hr.delete(e),qs(e),o.options=o.watcher=void 0,Object.freeze(o))}},Tt=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let i=this.fsw.options,s=F.dirname(e),n=F.basename(e);this.fsw._getWatchedDir(s).add(n);let a=F.resolve(e),u={persistent:i.persistent};t||(t=Ct);let m;if(i.usePolling){let c=i.interval!==i.binaryInterval;u.interval=c&&Ca(n)?i.binaryInterval:i.interval,m=Ea(e,a,u,{listener:t,rawEmitter:this.fsw._emitRaw})}else m=$a(e,a,u,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return m}_handleFile(e,t,i){if(this.fsw.closed)return;let s=F.dirname(e),n=F.basename(e),o=this.fsw._getWatchedDir(s),a=t;if(o.has(n))return;let u=async(c,h)=>{if(this.fsw._throttle(xa,e,5)){if(!h||h.mtimeMs===0)try{let p=await zs(e);if(this.fsw.closed)return;let S=p.atimeMs,x=p.mtimeMs;if((!S||S<=x||x!==a.mtimeMs)&&this.fsw._emit(ne.CHANGE,e,p),(ba||_a||Sa)&&a.ino!==p.ino){this.fsw._closeFile(c),a=p;let $=this._watchWithNodeFs(e,u);$&&this.fsw._addPathCloser(c,$)}else a=p}catch{this.fsw._remove(s,n)}else if(o.has(n)){let p=h.atimeMs,S=h.mtimeMs;(!p||p<=S||S!==a.mtimeMs)&&this.fsw._emit(ne.CHANGE,e,h),a=h}}},m=this._watchWithNodeFs(e,u);if(!(i&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(ne.ADD,e,0))return;this.fsw._emit(ne.ADD,e,t)}return m}async _handleSymlink(e,t,i,s){if(this.fsw.closed)return;let n=e.fullPath,o=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await dr(i)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(o.has(s)?this.fsw._symlinkPaths.get(n)!==a&&(this.fsw._symlinkPaths.set(n,a),this.fsw._emit(ne.CHANGE,i,e.stats)):(o.add(s),this.fsw._symlinkPaths.set(n,a),this.fsw._emit(ne.ADD,i,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(n))return!0;this.fsw._symlinkPaths.set(n,!0)}_handleRead(e,t,i,s,n,o,a){if(e=F.join(e,""),a=this.fsw._throttle("readdir",e,1e3),!a)return;let u=this.fsw._getWatchedDir(i.path),m=new Set,c=this.fsw._readdirp(e,{fileFilter:h=>i.filterPath(h),directoryFilter:h=>i.filterDir(h)});if(c)return c.on(wa,async h=>{if(this.fsw.closed){c=void 0;return}let p=h.path,S=F.join(e,p);if(m.add(p),!(h.stats.isSymbolicLink()&&await this._handleSymlink(h,e,S,p))){if(this.fsw.closed){c=void 0;return}(p===s||!s&&!u.has(p))&&(this.fsw._incrReadyCount(),S=F.join(n,F.relative(n,S)),this._addToNodeFs(S,t,i,o+1))}}).on(ne.ERROR,this._boundHandleError),new Promise((h,p)=>{if(!c)return p();c.once(gr,()=>{if(this.fsw.closed){c=void 0;return}let S=a?a.clear():!1;h(void 0),u.getChildren().filter(x=>x!==e&&!m.has(x)).forEach(x=>{this.fsw._remove(e,x)}),c=void 0,S&&this._handleRead(e,!1,i,s,n,o,a)})})}async _handleDir(e,t,i,s,n,o,a){let u=this.fsw._getWatchedDir(F.dirname(e)),m=u.has(F.basename(e));!(i&&this.fsw.options.ignoreInitial)&&!n&&!m&&this.fsw._emit(ne.ADD_DIR,e,t),u.add(F.basename(e)),this.fsw._getWatchedDir(e);let c,h,p=this.fsw.options.depth;if((p==null||s<=p)&&!this.fsw._symlinkPaths.has(a)){if(!n&&(await this._handleRead(e,i,o,n,e,s,c),this.fsw.closed))return;h=this._watchWithNodeFs(e,(S,x)=>{x&&x.mtimeMs===0||this._handleRead(S,!1,o,n,e,s,c)})}return h}async _addToNodeFs(e,t,i,s,n){let o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return o(),!1;let a=this.fsw._getWatchHelpers(e);i&&(a.filterPath=u=>i.filterPath(u),a.filterDir=u=>i.filterDir(u));try{let u=await va[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,u))return o(),!1;let m=this.fsw.options.followSymlinks,c;if(u.isDirectory()){let h=F.resolve(e),p=m?await dr(e):e;if(this.fsw.closed||(c=await this._handleDir(a.watchPath,u,t,s,n,a,p),this.fsw.closed))return;h!==p&&p!==void 0&&this.fsw._symlinkPaths.set(h,p)}else if(u.isSymbolicLink()){let h=m?await dr(e):e;if(this.fsw.closed)return;let p=F.dirname(a.watchPath);if(this.fsw._getWatchedDir(p).add(a.watchPath),this.fsw._emit(ne.ADD,a.watchPath,u),c=await this._handleDir(p,u,t,s,e,a,h),this.fsw.closed)return;h!==void 0&&this.fsw._symlinkPaths.set(F.resolve(e),h)}else c=this._handleFile(a.watchPath,u,t);return o(),c&&this.fsw._addPathCloser(e,c),!1}catch(u){if(this.fsw._handleError(u))return o(),e}}};var wr="/",Fa="//",Us=".",Oa="..",qa="string",ja=/\\/g,Vs=/\/\//,za=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,Ra=/^\.[/\\]/;function $t(r){return Array.isArray(r)?r:[r]}var br=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function Qa(r){return typeof r=="function"?r:typeof r=="string"?e=>r===e:r instanceof RegExp?e=>r.test(e):typeof r=="object"&&r!==null?e=>{if(r.path===e)return!0;if(r.recursive){let t=T.relative(r.path,e);return t?!t.startsWith("..")&&!T.isAbsolute(t):!1}return!1}:()=>!1}function ka(r){if(typeof r!="string")throw new Error("string expected");r=T.normalize(r),r=r.replace(/\\/g,"/");let e=!1;r.startsWith("//")&&(e=!0);let t=/\/\//;for(;r.match(t);)r=r.replace(t,"/");return e&&(r="/"+r),r}function Ks(r,e,t){let i=ka(e);for(let s=0;s<r.length;s++){let n=r[s];if(n(i,t))return!0}return!1}function Va(r,e){if(r==null)throw new TypeError("anymatch: specify first argument");let i=$t(r).map(s=>Qa(s));return e==null?(s,n)=>Ks(i,s,n):Ks(i,e)}var Bs=r=>{let e=$t(r).flat();if(!e.every(t=>typeof t===qa))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Js)},Ms=r=>{let e=r.replace(ja,wr),t=!1;for(e.startsWith(Fa)&&(t=!0);e.match(Vs);)e=e.replace(Vs,wr);return t&&(e=wr+e),e},Js=r=>Ms(T.normalize(Ms(r))),Ws=(r="")=>e=>typeof e=="string"?Js(T.isAbsolute(e)?e:T.join(r,e)):e,Ka=(r,e)=>T.isAbsolute(r)?r:T.join(e,r),Ba=Object.freeze(new Set),_r=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Us&&e!==Oa&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let i=this.path;try{await Ia(i)}catch{this._removeWatcher&&this._removeWatcher(T.dirname(i),T.basename(i))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=Ct,this.items=Ba,Object.freeze(this)}},Ma="stat",Wa="lstat",Sr=class{constructor(e,t,i){this.fsw=i;let s=e;this.path=e=e.replace(Ra,""),this.watchPath=s,this.fullWatchPath=T.resolve(s),this.dirParts=[],this.dirParts.forEach(n=>{n.length>1&&n.pop()}),this.followSymlinks=t,this.statMethod=t?Ma:Wa}entryPath(e){return T.join(this.watchPath,T.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let i=this.entryPath(e);return this.fsw._isntIgnored(i,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},Et=class extends La{constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,i={stabilityThreshold:2e3,pollInterval:100},s={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?$t(e.ignored):$t([]),awaitWriteFinish:t===!0?i:typeof t=="object"?{...i,...t}:!1};Qs&&(s.usePolling=!0),s.atomic===void 0&&(s.atomic=!s.usePolling);let n=process.env.CHOKIDAR_USEPOLLING;if(n!==void 0){let u=n.toLowerCase();u==="false"||u==="0"?s.usePolling=!1:u==="true"||u==="1"?s.usePolling=!0:s.usePolling=!!u}let o=process.env.CHOKIDAR_INTERVAL;o&&(s.interval=Number.parseInt(o,10));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=Ct,this._readyEmitted=!0,process.nextTick(()=>this.emit(q.READY)))},this._emitRaw=(...u)=>this.emit(q.RAW,...u),this._boundRemove=this._remove.bind(this),this.options=s,this._nodeFsHandler=new Tt(this),Object.freeze(s)}_addIgnoredPath(e){if(br(e)){for(let t of this._ignoredPaths)if(br(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let t of this._ignoredPaths)br(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,i){let{cwd:s}=this.options;this.closed=!1,this._closePromise=void 0;let n=Bs(e);return s&&(n=n.map(o=>Ka(o,s))),n.forEach(o=>{this._removeIgnoredPath(o)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=n.length,Promise.all(n.map(async o=>{let a=await this._nodeFsHandler._addToNodeFs(o,!i,void 0,0,t);return a&&this._emitReady(),a})).then(o=>{this.closed||o.forEach(a=>{a&&this.add(T.dirname(a),T.basename(t||a))})}),this}unwatch(e){if(this.closed)return this;let t=Bs(e),{cwd:i}=this.options;return t.forEach(s=>{!T.isAbsolute(s)&&!this._closers.has(s)&&(i&&(s=T.join(i,s)),s=T.resolve(s)),this._closePath(s),this._addIgnoredPath(s),this._watched.has(s)&&this._addIgnoredPath({path:s,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(i=>{let s=i();s instanceof Promise&&e.push(s)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,i)=>{let n=(this.options.cwd?T.relative(this.options.cwd,i):i)||Us;e[n]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==q.ERROR&&this.emit(q.ALL,e,...t)}async _emit(e,t,i){if(this.closed)return;let s=this.options;yr&&(t=T.normalize(t)),s.cwd&&(t=T.relative(s.cwd,t));let n=[t];i!=null&&n.push(i);let o=s.awaitWriteFinish,a;if(o&&(a=this._pendingWrites.get(t)))return a.lastChange=new Date,this;if(s.atomic){if(e===q.UNLINK)return this._pendingUnlinks.set(t,[e,...n]),setTimeout(()=>{this._pendingUnlinks.forEach((u,m)=>{this.emit(...u),this.emit(q.ALL,...u),this._pendingUnlinks.delete(m)})},typeof s.atomic=="number"?s.atomic:100),this;e===q.ADD&&this._pendingUnlinks.has(t)&&(e=q.CHANGE,this._pendingUnlinks.delete(t))}if(o&&(e===q.ADD||e===q.CHANGE)&&this._readyEmitted){let u=(m,c)=>{m?(e=q.ERROR,n[0]=m,this.emitWithAll(e,n)):c&&(n.length>1?n[1]=c:n.push(c),this.emitWithAll(e,n))};return this._awaitWriteFinish(t,o.stabilityThreshold,e,u),this}if(e===q.CHANGE&&!this._throttle(q.CHANGE,t,50))return this;if(s.alwaysStat&&i===void 0&&(e===q.ADD||e===q.ADD_DIR||e===q.CHANGE)){let u=s.cwd?T.join(s.cwd,t):t,m;try{m=await Aa(u)}catch{}if(!m||this.closed)return;n.push(m)}return this.emitWithAll(e,n),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(q.ERROR,e),e||this.closed}_throttle(e,t,i){this._throttled.has(e)||this._throttled.set(e,new Map);let s=this._throttled.get(e);if(!s)throw new Error("invalid throttle");let n=s.get(t);if(n)return n.count++,!1;let o,a=()=>{let m=s.get(t),c=m?m.count:0;return s.delete(t),clearTimeout(o),m&&clearTimeout(m.timeoutObject),c};o=setTimeout(a,i);let u={timeoutObject:o,clear:a,count:0};return s.set(t,u),u}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,i,s){let n=this.options.awaitWriteFinish;if(typeof n!="object")return;let o=n.pollInterval,a,u=e;this.options.cwd&&!T.isAbsolute(e)&&(u=T.join(this.options.cwd,e));let m=new Date,c=this._pendingWrites;function h(p){Da(u,(S,x)=>{if(S||!c.has(e)){S&&S.code!=="ENOENT"&&s(S);return}let $=Number(new Date);p&&x.size!==p.size&&(c.get(e).lastChange=$);let L=c.get(e);$-L.lastChange>=t?(c.delete(e),s(void 0,x)):a=setTimeout(h,o,x)})}c.has(e)||(c.set(e,{lastChange:m,cancelWait:()=>(c.delete(e),clearTimeout(a),i)}),a=setTimeout(h,o))}_isIgnored(e,t){if(this.options.atomic&&za.test(e))return!0;if(!this._userIgnored){let{cwd:i}=this.options,n=(this.options.ignored||[]).map(Ws(i)),a=[...[...this._ignoredPaths].map(Ws(i)),...n];this._userIgnored=Va(a,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new Sr(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=T.resolve(e);return this._watched.has(t)||this._watched.set(t,new _r(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,i){let s=T.join(e,t),n=T.resolve(s);if(i=i??(this._watched.has(s)||this._watched.has(n)),!this._throttle("remove",s,100))return;!i&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(s).getChildren().forEach(p=>this._remove(s,p));let u=this._getWatchedDir(e),m=u.has(t);u.remove(t),this._symlinkPaths.has(n)&&this._symlinkPaths.delete(n);let c=s;if(this.options.cwd&&(c=T.relative(this.options.cwd,s)),this.options.awaitWriteFinish&&this._pendingWrites.has(c)&&this._pendingWrites.get(c).cancelWait()===q.ADD)return;this._watched.delete(s),this._watched.delete(n);let h=i?q.UNLINK_DIR:q.UNLINK;m&&!this._isIgnored(s)&&this._emit(h,s),this._closePath(s)}_closePath(e){this._closeFile(e);let t=T.dirname(e);this._getWatchedDir(t).remove(T.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(i=>i()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let i=this._closers.get(e);i||(i=[],this._closers.set(e,i)),i.push(t)}_readdirp(e,t){if(this.closed)return;let i={type:q.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},s=Os(e,i);return this._streams.add(s),s.once(Rs,()=>{s=void 0}),s.once(gr,()=>{s&&(this._streams.delete(s),s=void 0)}),s}};function Ua(r,e={}){let t=new Et(e);return t.add(r),t}var Ys={watch:Ua,FSWatcher:Et};import{existsSync as Ce,mkdirSync as sl,readFileSync as nl,unlinkSync as ol}from"fs";import{basename as en,join as ae,relative as tn}from"path";import{copyFileSync as Ja,existsSync as oe,mkdirSync as Ya,readdirSync as Zs,readFileSync as Ha,writeFileSync as Ga}from"fs";import{basename as Hs,dirname as xr,extname as Za,join as ue,normalize as Xa,relative as Le,sep as el}from"path";var tl=/import\s+(?:(?:{[^}]*})|(?:[^{}\s,]*))?\s*(?:,\s*(?:{[^}]*}))?\s*from\s+['"]([./]+[^'"]*)['"]/g,rl=/import\s+(?:(?:{[^}]*})|(?:[^{}\s,]*))?\s*(?:,\s*(?:{[^}]*}))?\s*from\s+['"](@\/[^'"]*)['"]/g,Gs=/\.(js|jsx|ts|tsx)$/,vr=/^page\.(tsx|ts|jsx|js)$/i,Me=(r,e)=>{let i=Le(e,r).split(el);i.pop();let s=i.filter(n=>!n.startsWith("("));return Xa(s.join("/"))},Dt=r=>{let e=new Map,t=i=>{if(oe(i))for(let s of Zs(i,{withFileTypes:!0})){let n=ue(i,s.name);if(s.isDirectory()){t(n);continue}if(vr.test(s.name)){let o=Me(n,r);e.set(o,n)}}};return t(r),e},il=(r,e)=>{let t=r.replace(tl,(i,s)=>{if(s.startsWith(".")){let o=s.replace(Gs,"").replace(/^(?:\.\.\/)+/,"");return i.replace(s,`${e}/${o}`)}return i});return t=t.replace(rl,(i,s)=>{let n=s.replace(/^@\//,"").replace(Gs,"");return i.replace(s,`${e}/${n}`)}),t};function At(r){let e=r;for(;e!==xr(e);){if(oe(ue(e,"turbo.json"))||oe(ue(e,"pnpm-workspace.yaml"))||oe(ue(e,".git"))||oe(ue(e,"package.json")))return e;e=xr(e)}throw new Error("\u274C Could not locate project root")}function It(r){let e=ue(r,"src","app","[locale]");if(oe(e))return e;let t=ue(r,"apps","web","src","app","[locale]");return oe(t),t}var We=r=>{let e=[];if(!oe(r))return e;let t=Zs(r,{withFileTypes:!0});for(let i of t){let s=ue(r,i.name);i.isDirectory()?e.push(...We(s)):e.push(s)}return e},Ue=r=>oe(r)?We(r).length===0:!0,Nr=(r,e,t,i,s,n,o=!0)=>{let a=Hs(r);if(vr.test(a)){let u=Me(e,s),m=i.get(u);if(m&&m!==e){o&&console.log(`\x1B[31mSkipped duplicate page:\x1B[0m ${Le(n,e)} (collides with ${Le(n,m)})`);return}}try{let u=xr(e);oe(u)||Ya(u,{recursive:!0});let m=Za(r);if(t&&[".js",".jsx",".ts",".tsx"].includes(m)){let c=Ha(r,"utf-8"),h=il(c,t);Ga(e,h)}else Ja(r,e);if(o){let c=r.indexOf(ue("src","app")),h=c!==-1?r.substring(c):r.startsWith(n)?Le(n,r):r,p=e.startsWith(n)?Le(n,e):e;console.log(`\x1B[32mCopied:\x1B[0m ${h} \u2192 ${p}`)}if(vr.test(Hs(e))){let c=Me(e,s);i.set(c,e)}}catch(u){console.error(`\x1B[31mError copying file:\x1B[0m ${r}`,u)}},Xs=(r,e,t,i,s,n,o=!0)=>{if(!oe(r)||Ue(r))return;let a=We(r);for(let u of a){let m=Le(r,u),c=ue(e,m);Nr(u,c,t,i,s,n,o)}};var rn=({initMessage:r})=>{let e=process.cwd(),t=At(e),i=It(t),s=Dt(i),n=en(e);try{let w=ae(e,"package.json");Ce(w)&&(n=JSON.parse(nl(w,"utf-8")).name??"")}catch(w){console.error("\x1B[31mError reading package.json:\x1B[0m",w);return}let o=n.replace(/\//g,"-").replace(/@/g,""),a=ae(t,"apps","web","src","app","[locale]","(main)",ae("(plugins)",`(${o})`)),u=ae(t,"apps","web","src","app","[locale]","admin","(auth)",ae("(plugins)",`(${o})`)),m=ae(t,"apps","web","src","locales",n),c=[{sourceDir:ae(e,"src","app_admin"),destinationDir:u},{sourceDir:ae(e,"src","app"),destinationDir:a},{sourceDir:ae(e,"src","locales"),destinationDir:m}];for(let{sourceDir:w,destinationDir:v}of c)Ce(w)&&!Ue(w)&&!Ce(v)&&sl(v,{recursive:!0});let h=(w,v)=>{Nr(w,v,n,s,i,t)},p=w=>{try{if(Ce(w)&&(ol(w),console.log(`\x1B[33mRemoved:\x1B[0m ${w}`),/^page\.(tsx|ts|jsx|js)$/i.test(en(w)))){let v=Me(w,i);s.get(v)===w&&s.delete(v)}}catch(v){console.error(`\x1B[31mError removing file:\x1B[0m ${w}`,v)}},S=(w,v)=>{if(!Ce(v))return;let Q=We(v);for(let O of Q){let Y=tn(v,O),R=ae(w,Y);Ce(R)||p(O)}};for(let{sourceDir:w,destinationDir:v}of c)S(w,v);console.log(`${r} \x1B[34mWatching for changes in plugins...\x1B[0m`);let x=c.map(w=>w.sourceDir).filter(w=>Ce(w)),$=Ys.watch(x,{ignoreInitial:!1,persistent:!0}),L=w=>{let v=c.filter(({sourceDir:Y})=>w.startsWith(Y));if(v.length===0)throw new Error(`No matching source directory for: ${w}`);let Q=v.reduce((Y,R)=>R.sourceDir.length>Y.sourceDir.length?R:Y),O=tn(Q.sourceDir,w);return ae(Q.destinationDir,O)};$.on("add",w=>{let v=L(w);h(w,v)}).on("change",w=>{let v=L(w);h(w,v)}).on("unlink",w=>{let v=L(w);p(v)}).on("error",w=>{console.error("\x1B[31mWatcher error:\x1B[0m",w)})};var Vo=ea(cn(),1);var l=Symbol.for("drizzle:entityKind"),yc=Symbol.for("drizzle:hasOwnEntityKind");function d(r,e){if(!r||typeof r!="object")return!1;if(r instanceof e)return!0;if(!Object.prototype.hasOwnProperty.call(e,l))throw new Error(`Class "${e.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let t=Object.getPrototypeOf(r).constructor;if(t)for(;t;){if(l in t&&t[l]===e[l])return!0;t=Object.getPrototypeOf(t)}return!1}var D=class{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[l]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}};var Lt=class{static[l]="ColumnBuilder";config;constructor(e,t,i){this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:i,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){this.config.name===""&&(this.config.name=e)}};var le=Symbol.for("drizzle:Name");var Ft=class{static[l]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){this.reference=()=>{let{name:i,columns:s,foreignColumns:n}=e();return{name:i,columns:s,foreignTable:n[0].table,foreignColumns:n}},t&&(this._onUpdate=t.onUpdate,this._onDelete=t.onDelete)}onUpdate(e){return this._onUpdate=e===void 0?"no action":e,this}onDelete(e){return this._onDelete=e===void 0?"no action":e,this}build(e){return new Pr(e,this)}},Pr=class{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[l]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:i}=this.reference(),s=t.map(a=>a.name),n=i.map(a=>a.name),o=[this.table[le],...s,i[0].table[le],...n];return e??`${o.join("_")}_fk`}};function Ot(r,...e){return r(...e)}function Dr(r,e){return`${r[le]}_${e.join("_")}_unique`}var $r=class{constructor(e,t){this.name=t,this.columns=e}static[l]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new Er(e,this.columns,this.nullsNotDistinctConfig,this.name)}},un=class{static[l]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new $r(e,this.name)}},Er=class{constructor(e,t,i,s){this.table=e,this.columns=t,this.name=s??Dr(this.table,this.columns.map(n=>n.name)),this.nullsNotDistinct=i}static[l]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}};function fn(r,e,t){for(let i=e;i<r.length;i++){let s=r[i];if(s==="\\"){i++;continue}if(s==='"')return[r.slice(e,i).replace(/\\/g,""),i+1];if(!t&&(s===","||s==="}"))return[r.slice(e,i).replace(/\\/g,""),i]}return[r.slice(e).replace(/\\/g,""),r.length]}function mn(r,e=0){let t=[],i=e,s=!1;for(;i<r.length;){let n=r[i];if(n===","){(s||i===e)&&t.push(""),s=!0,i++;continue}if(s=!1,n==="\\"){i+=2;continue}if(n==='"'){let[u,m]=fn(r,i+1,!0);t.push(u),i=m;continue}if(n==="}")return[t,i+1];if(n==="{"){let[u,m]=mn(r,i+1);t.push(u),i=m;continue}let[o,a]=fn(r,i,!1);t.push(o),i=a}return[t,i]}function dn(r){let[e]=mn(r,1);return e}function Ar(r){return`{${r.map(e=>Array.isArray(e)?Ar(e):typeof e=="string"?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:`${e}`).join(",")}}`}var _=class extends Lt{foreignKeyConfigs=[];static[l]="PgColumnBuilder";array(e){return new Lr(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:i,actions:s})=>Ot((n,o)=>{let a=new Ft(()=>{let u=n();return{columns:[e],foreignColumns:[u]}});return o.onUpdate&&a.onUpdate(o.onUpdate),o.onDelete&&a.onDelete(o.onDelete),a.build(t)},i,s))}buildExtraConfigColumn(e){return new Ir(e,this.config)}},g=class extends D{constructor(e,t){t.uniqueName||(t.uniqueName=Dr(e,[t.name])),super(e,t),this.table=e}static[l]="PgColumn"},Ir=class extends g{static[l]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}},Fe=class{static[l]="IndexedColumn";constructor(e,t,i,s){this.name=e,this.keyAsName=t,this.type=i,this.indexConfig=s}name;keyAsName;type;indexConfig},Lr=class extends _{static[l]="PgArrayBuilder";constructor(e,t,i){super(e,"array","PgArray"),this.config.baseBuilder=t,this.config.size=i}build(e){let t=this.config.baseBuilder.build(e);return new Fr(e,this.config,t)}},Fr=class r extends g{constructor(e,t,i,s){super(e,t),this.baseColumn=i,this.range=s,this.size=t.size}size;static[l]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size=="number"?this.size:""}]`}mapFromDriverValue(e){return typeof e=="string"&&(e=dn(e)),e.map(t=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let i=e.map(s=>s===null?null:d(this.baseColumn,r)?this.baseColumn.mapToDriverValue(s,!0):this.baseColumn.mapToDriverValue(s));return t?i:Ar(i)}};var hn=class extends _{static[l]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn"),this.config.enum=t}build(e){return new Or(e,this.config)}},Or=class extends g{static[l]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}},pn=Symbol.for("drizzle:isPgEnum");function yn(r){return!!r&&typeof r=="function"&&pn in r&&r[pn]===!0}var gn=class extends _{static[l]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn"),this.config.enum=t}build(e){return new qr(e,this.config)}},qr=class extends g{static[l]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}};var j=class{static[l]="Subquery";constructor(e,t,i,s=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:i,isWith:s,usedTables:n}}},Oe=class extends j{static[l]="WithSubquery"};var wn="0.44.2";var jr,zr,A={startActiveSpan(r,e){return jr?(zr||(zr=jr.trace.getTracer("drizzle-orm",wn)),Ot((t,i)=>i.startActiveSpan(r,s=>{try{return e(s)}catch(n){throw s.setStatus({code:t.SpanStatusCode.ERROR,message:n instanceof Error?n.message:"Unknown error"}),n}finally{s.end()}}),jr,zr)):e()}};var I=Symbol.for("drizzle:ViewBaseConfig");var Pe=Symbol.for("drizzle:Schema"),qt=Symbol.for("drizzle:Columns"),bn=Symbol.for("drizzle:ExtraConfigColumns"),Rr=Symbol.for("drizzle:OriginalName"),Qr=Symbol.for("drizzle:BaseName"),Ye=Symbol.for("drizzle:IsAlias"),_n=Symbol.for("drizzle:ExtraConfigBuilder"),Sl=Symbol.for("drizzle:IsDrizzleTable"),y=class{static[l]="Table";static Symbol={Name:le,Schema:Pe,OriginalName:Rr,Columns:qt,ExtraConfigColumns:bn,BaseName:Qr,IsAlias:Ye,ExtraConfigBuilder:_n};[le];[Rr];[Pe];[qt];[bn];[Qr];[Ye]=!1;[Sl]=!0;[_n]=void 0;constructor(e,t,i){this[le]=this[Rr]=e,this[Pe]=t,this[Qr]=i}};function X(r){return r[le]}function $e(r){return`${r[Pe]??"public"}.${r[le]}`}var Sn=class{static[l]="FakePrimitiveParam"};function kr(r){return r!=null&&typeof r.getSQL=="function"}function xl(r){let e={sql:"",params:[]};for(let t of r)e.sql+=t.sql,e.params.push(...t.params),t.typings?.length&&(e.typings||(e.typings=[]),e.typings.push(...t.typings));return e}var k=class{static[l]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new b([this])}},b=class r{constructor(e){this.queryChunks=e;for(let t of e)if(d(t,y)){let i=t[y.Symbol.Schema];this.usedTables.push(i===void 0?t[y.Symbol.Name]:i+"."+t[y.Symbol.Name])}}static[l]="SQL";decoder=vn;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return A.startActiveSpan("drizzle.buildSQL",t=>{let i=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":i.sql,"drizzle.query.params":JSON.stringify(i.params)}),i})}buildQueryFromSourceParams(e,t){let i=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:s,escapeName:n,escapeParam:o,prepareTyping:a,inlineParams:u,paramStartIndex:m}=i;return xl(e.map(c=>{if(d(c,k))return{sql:c.value.join(""),params:[]};if(d(c,He))return{sql:n(c.value),params:[]};if(c===void 0)return{sql:"",params:[]};if(Array.isArray(c)){let h=[new k("(")];for(let[p,S]of c.entries())h.push(S),p<c.length-1&&h.push(new k(", "));return h.push(new k(")")),this.buildQueryFromSourceParams(h,i)}if(d(c,r))return this.buildQueryFromSourceParams(c.queryChunks,{...i,inlineParams:u||c.shouldInlineParams});if(d(c,y)){let h=c[y.Symbol.Schema],p=c[y.Symbol.Name];return{sql:h===void 0||c[Ye]?n(p):n(h)+"."+n(p),params:[]}}if(d(c,D)){let h=s.getColumnCasing(c);if(t.invokeSource==="indexes")return{sql:n(h),params:[]};let p=c.table[y.Symbol.Schema];return{sql:c.table[Ye]||p===void 0?n(c.table[y.Symbol.Name])+"."+n(h):n(p)+"."+n(c.table[y.Symbol.Name])+"."+n(h),params:[]}}if(d(c,H)){let h=c[I].schema,p=c[I].name;return{sql:h===void 0||c[I].isAlias?n(p):n(h)+"."+n(p),params:[]}}if(d(c,ee)){if(d(c.value,ye))return{sql:o(m.value++,c),params:[c],typings:["none"]};let h=c.value===null?null:c.encoder.mapToDriverValue(c.value);if(d(h,r))return this.buildQueryFromSourceParams([h],i);if(u)return{sql:this.mapInlineParam(h,i),params:[]};let p=["none"];return a&&(p=[a(c.encoder)]),{sql:o(m.value++,h),params:[h],typings:p}}return d(c,ye)?{sql:o(m.value++,c),params:[c],typings:["none"]}:d(c,r.Aliased)&&c.fieldAlias!==void 0?{sql:n(c.fieldAlias),params:[]}:d(c,j)?c._.isWith?{sql:n(c._.alias),params:[]}:this.buildQueryFromSourceParams([new k("("),c._.sql,new k(") "),new He(c._.alias)],i):yn(c)?c.schema?{sql:n(c.schema)+"."+n(c.enumName),params:[]}:{sql:n(c.enumName),params:[]}:kr(c)?c.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([c.getSQL()],i):this.buildQueryFromSourceParams([new k("("),c.getSQL(),new k(")")],i):u?{sql:this.mapInlineParam(c,i),params:[]}:{sql:o(m.value++,c),params:[c],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="string")return t(e);if(typeof e=="object"){let i=e.toString();return t(i==="[object Object]"?JSON.stringify(e):i)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return e===void 0?this:new r.Aliased(this,e)}mapWith(e){return this.decoder=typeof e=="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}},He=class{constructor(e){this.value=e}static[l]="Name";brand;getSQL(){return new b([this])}};function xn(r){return typeof r=="object"&&r!==null&&"mapToDriverValue"in r&&typeof r.mapToDriverValue=="function"}var vn={mapFromDriverValue:r=>r},Nn={mapToDriverValue:r=>r},ou={...vn,...Nn},ee=class{constructor(e,t=Nn){this.value=e,this.encoder=t}static[l]="Param";brand;getSQL(){return new b([this])}};function f(r,...e){let t=[];(e.length>0||r.length>0&&r[0]!=="")&&t.push(new k(r[0]));for(let[i,s]of e.entries())t.push(s,new k(r[i+1]));return new b(t)}(r=>{function e(){return new b([])}r.empty=e;function t(u){return new b(u)}r.fromList=t;function i(u){return new b([new k(u)])}r.raw=i;function s(u,m){let c=[];for(let[h,p]of u.entries())h>0&&m!==void 0&&c.push(m),c.push(p);return new b(c)}r.join=s;function n(u){return new He(u)}r.identifier=n;function o(u){return new ye(u)}r.placeholder=o;function a(u,m){return new ee(u,m)}r.param=a})(f||(f={}));(r=>{class e{constructor(i,s){this.sql=i,this.fieldAlias=s}static[l]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new e(this.sql,this.fieldAlias)}}r.Aliased=e})(b||(b={}));var ye=class{constructor(e){this.name=e}static[l]="Placeholder";getSQL(){return new b([this])}};function Vr(r,e){return r.map(t=>{if(d(t,ye)){if(!(t.name in e))throw new Error(`No value for placeholder "${t.name}" was provided`);return e[t.name]}if(d(t,ee)&&d(t.value,ye)){if(!(t.value.name in e))throw new Error(`No value for placeholder "${t.value.name}" was provided`);return t.encoder.mapToDriverValue(e[t.value.name])}return t})}var vl=Symbol.for("drizzle:IsDrizzleView"),H=class{static[l]="View";[I];[vl]=!0;constructor({name:e,schema:t,selectedFields:i,query:s}){this[I]={name:e,originalName:e,schema:t,selectedFields:i,query:s,isExisting:!s,isAlias:!1}}getSQL(){return new b([this])}};D.prototype.getSQL=function(){return new b([this])};y.prototype.getSQL=function(){return new b([this])};j.prototype.getSQL=function(){return new b([this])};var Ee=class{constructor(e){this.table=e}static[l]="ColumnAliasProxyHandler";get(e,t){return t==="table"?this.table:e[t]}},qe=class{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[l]="TableAliasProxyHandler";get(e,t){if(t===y.Symbol.IsAlias)return!0;if(t===y.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===y.Symbol.OriginalName)return this.alias;if(t===I)return{...e[I],name:this.alias,isAlias:!0};if(t===y.Symbol.Columns){let s=e[y.Symbol.Columns];if(!s)return s;let n={};return Object.keys(s).map(o=>{n[o]=new Proxy(s[o],new Ee(new Proxy(e,this)))}),n}let i=e[t];return d(i,D)?new Proxy(i,new Ee(new Proxy(e,this))):i}},Tn=class{constructor(e){this.alias=e}static[l]="RelationTableAliasProxyHandler";get(e,t){return t==="sourceTable"?Ge(e.sourceTable,this.alias):e[t]}};function Ge(r,e){return new Proxy(r,new qe(e,!1))}function fe(r,e){return new Proxy(r,new Ee(new Proxy(r.table,new qe(e,!1))))}function Kr(r,e){return new b.Aliased(Ze(r.sql,e),r.fieldAlias)}function Ze(r,e){return f.join(r.queryChunks.map(t=>d(t,D)?fe(t,e):d(t,b)?Ze(t,e):d(t,b.Aliased)?Kr(t,e):t))}var Xe=class extends Error{static[l]="DrizzleError";constructor({message:e,cause:t}){super(e),this.name="DrizzleError",this.cause=t}},jt=class extends Xe{static[l]="TransactionRollbackError";constructor(){super({message:"Rollback"})}};var Br=class{static[l]="ConsoleLogWriter";write(e){console.log(e)}},zt=class{static[l]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new Br}logQuery(e,t){let i=t.map(n=>{try{return JSON.stringify(n)}catch{return String(n)}}),s=i.length?` -- params: [${i.join(", ")}]`:"";this.writer.write(`Query: ${e}${s}`)}},Rt=class{static[l]="NoopLogger";logQuery(){}};var W=class{static[l]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}};function Cn(r,e,t){let i={},s=r.reduce((n,{path:o,field:a},u)=>{let m;d(a,D)?m=a:d(a,b)?m=a.decoder:m=a.sql.decoder;let c=n;for(let[h,p]of o.entries())if(h<o.length-1)p in c||(c[p]={}),c=c[p];else{let S=e[u],x=c[p]=S===null?null:m.mapFromDriverValue(S);if(t&&d(a,D)&&o.length===2){let $=o[0];$ in i?typeof i[$]=="string"&&i[$]!==X(a.table)&&(i[$]=!1):i[$]=x===null?X(a.table):!1}}return n},{});if(t&&Object.keys(i).length>0)for(let[n,o]of Object.entries(i))typeof o=="string"&&!t[o]&&(s[n]=null);return s}function se(r,e){return Object.entries(r).reduce((t,[i,s])=>{if(typeof i!="string")return t;let n=e?[...e,i]:[i];return d(s,D)||d(s,b)||d(s,b.Aliased)?t.push({path:n,field:s}):d(s,y)?t.push(...se(s[y.Symbol.Columns],n)):t.push(...se(s,n)),t},[])}function et(r,e){let t=Object.keys(r),i=Object.keys(e);if(t.length!==i.length)return!1;for(let[s,n]of t.entries())if(n!==i[s])return!1;return!0}function Qt(r,e){let t=Object.entries(e).filter(([,i])=>i!==void 0).map(([i,s])=>d(s,b)||d(s,D)?[i,s]:[i,new ee(s,r[y.Symbol.Columns][i])]);if(t.length===0)throw new Error("No values to set");return Object.fromEntries(t)}function Pn(r,e){for(let t of e)for(let i of Object.getOwnPropertyNames(t.prototype))i!=="constructor"&&Object.defineProperty(r.prototype,i,Object.getOwnPropertyDescriptor(t.prototype,i)||Object.create(null))}function $n(r){return r[y.Symbol.Columns]}function we(r){return d(r,j)?r._.alias:d(r,H)?r[I].name:d(r,b)?void 0:r[y.Symbol.IsAlias]?r[y.Symbol.Name]:r[y.Symbol.BaseName]}function C(r,e){return{name:typeof r=="string"&&r.length>0?r:"",config:typeof r=="object"?r:e}}function En(r){if(typeof r!="object"||r===null||r.constructor.name!=="Object")return!1;if("logger"in r){let e=typeof r.logger;return!(e!=="boolean"&&(e!=="object"||typeof r.logger.logQuery!="function")&&e!=="undefined")}if("schema"in r){let e=typeof r.schema;return!(e!=="object"&&e!=="undefined")}if("casing"in r){let e=typeof r.casing;return!(e!=="string"&&e!=="undefined")}if("mode"in r)return!(r.mode!=="default"||r.mode!=="planetscale"||r.mode!==void 0);if("connection"in r){let e=typeof r.connection;return!(e!=="string"&&e!=="object"&&e!=="undefined")}if("client"in r){let e=typeof r.client;return!(e!=="object"&&e!=="function"&&e!=="undefined")}return Object.keys(r).length===0}var be=class extends _{static[l]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(e){if(e){let{name:t,...i}=e;this.config.generatedIdentity={type:"always",sequenceName:t,sequenceOptions:i}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(e){if(e){let{name:t,...i}=e;this.config.generatedIdentity={type:"byDefault",sequenceName:t,sequenceOptions:i}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}};var Mr=class extends be{static[l]="PgBigInt53Builder";constructor(e){super(e,"number","PgBigInt53")}build(e){return new Wr(e,this.config)}},Wr=class extends g{static[l]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(e){return typeof e=="number"?e:Number(e)}},Ur=class extends be{static[l]="PgBigInt64Builder";constructor(e){super(e,"bigint","PgBigInt64")}build(e){return new Jr(e,this.config)}},Jr=class extends g{static[l]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(e){return BigInt(e)}};function Dn(r,e){let{name:t,config:i}=C(r,e);return i.mode==="number"?new Mr(t):new Ur(t)}var Yr=class extends _{static[l]="PgBigSerial53Builder";constructor(e){super(e,"number","PgBigSerial53"),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new Hr(e,this.config)}},Hr=class extends g{static[l]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(e){return typeof e=="number"?e:Number(e)}},Gr=class extends _{static[l]="PgBigSerial64Builder";constructor(e){super(e,"bigint","PgBigSerial64"),this.config.hasDefault=!0}build(e){return new Zr(e,this.config)}},Zr=class extends g{static[l]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(e){return BigInt(e)}};function An(r,e){let{name:t,config:i}=C(r,e);return i.mode==="number"?new Yr(t):new Gr(t)}var Xr=class extends _{static[l]="PgBooleanBuilder";constructor(e){super(e,"boolean","PgBoolean")}build(e){return new ei(e,this.config)}},ei=class extends g{static[l]="PgBoolean";getSQLType(){return"boolean"}};function In(r){return new Xr(r??"")}var ti=class extends _{static[l]="PgCharBuilder";constructor(e,t){super(e,"string","PgChar"),this.config.length=t.length,this.config.enumValues=t.enum}build(e){return new ri(e,this.config)}},ri=class extends g{static[l]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}};function Ln(r,e={}){let{name:t,config:i}=C(r,e);return new ti(t,i)}var ii=class extends _{static[l]="PgCidrBuilder";constructor(e){super(e,"string","PgCidr")}build(e){return new si(e,this.config)}},si=class extends g{static[l]="PgCidr";getSQLType(){return"cidr"}};function Fn(r){return new ii(r??"")}var ni=class extends _{static[l]="PgCustomColumnBuilder";constructor(e,t,i){super(e,"custom","PgCustomColumn"),this.config.fieldConfig=t,this.config.customTypeParams=i}build(e){return new oi(e,this.config)}},oi=class extends g{static[l]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(e,t){super(e,t),this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom=="function"?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo=="function"?this.mapTo(e):e}};function On(r){return(e,t)=>{let{name:i,config:s}=C(e,t);return new ni(i,s,r)}}var me=class extends _{static[l]="PgDateColumnBaseBuilder";defaultNow(){return this.default(f`now()`)}};var ai=class extends me{static[l]="PgDateBuilder";constructor(e){super(e,"date","PgDate")}build(e){return new tt(e,this.config)}},tt=class extends g{static[l]="PgDate";getSQLType(){return"date"}mapFromDriverValue(e){return new Date(e)}mapToDriverValue(e){return e.toISOString()}},li=class extends me{static[l]="PgDateStringBuilder";constructor(e){super(e,"string","PgDateString")}build(e){return new rt(e,this.config)}},rt=class extends g{static[l]="PgDateString";getSQLType(){return"date"}};function qn(r,e){let{name:t,config:i}=C(r,e);return i?.mode==="date"?new ai(t):new li(t)}var ci=class extends _{static[l]="PgDoublePrecisionBuilder";constructor(e){super(e,"number","PgDoublePrecision")}build(e){return new ui(e,this.config)}},ui=class extends g{static[l]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(e){return typeof e=="string"?Number.parseFloat(e):e}};function jn(r){return new ci(r??"")}var fi=class extends _{static[l]="PgInetBuilder";constructor(e){super(e,"string","PgInet")}build(e){return new mi(e,this.config)}},mi=class extends g{static[l]="PgInet";getSQLType(){return"inet"}};function zn(r){return new fi(r??"")}var di=class extends be{static[l]="PgIntegerBuilder";constructor(e){super(e,"number","PgInteger")}build(e){return new hi(e,this.config)}},hi=class extends g{static[l]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(e){return typeof e=="string"?Number.parseInt(e):e}};function Rn(r){return new di(r??"")}var pi=class extends _{static[l]="PgIntervalBuilder";constructor(e,t){super(e,"string","PgInterval"),this.config.intervalConfig=t}build(e){return new gi(e,this.config)}},gi=class extends g{static[l]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let e=this.fields?` ${this.fields}`:"",t=this.precision?`(${this.precision})`:"";return`interval${e}${t}`}};function Qn(r,e={}){let{name:t,config:i}=C(r,e);return new pi(t,i)}var yi=class extends _{static[l]="PgJsonBuilder";constructor(e){super(e,"json","PgJson")}build(e){return new it(e,this.config)}},it=class extends g{static[l]="PgJson";constructor(e,t){super(e,t)}getSQLType(){return"json"}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}};function kn(r){return new yi(r??"")}var wi=class extends _{static[l]="PgJsonbBuilder";constructor(e){super(e,"json","PgJsonb")}build(e){return new st(e,this.config)}},st=class extends g{static[l]="PgJsonb";constructor(e,t){super(e,t)}getSQLType(){return"jsonb"}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}};function Vn(r){return new wi(r??"")}var bi=class extends _{static[l]="PgLineBuilder";constructor(e){super(e,"array","PgLine")}build(e){return new _i(e,this.config)}},_i=class extends g{static[l]="PgLine";getSQLType(){return"line"}mapFromDriverValue(e){let[t,i,s]=e.slice(1,-1).split(",");return[Number.parseFloat(t),Number.parseFloat(i),Number.parseFloat(s)]}mapToDriverValue(e){return`{${e[0]},${e[1]},${e[2]}}`}},Si=class extends _{static[l]="PgLineABCBuilder";constructor(e){super(e,"json","PgLineABC")}build(e){return new xi(e,this.config)}},xi=class extends g{static[l]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(e){let[t,i,s]=e.slice(1,-1).split(",");return{a:Number.parseFloat(t),b:Number.parseFloat(i),c:Number.parseFloat(s)}}mapToDriverValue(e){return`{${e.a},${e.b},${e.c}}`}};function Kn(r,e){let{name:t,config:i}=C(r,e);return!i?.mode||i.mode==="tuple"?new bi(t):new Si(t)}var vi=class extends _{static[l]="PgMacaddrBuilder";constructor(e){super(e,"string","PgMacaddr")}build(e){return new Ni(e,this.config)}},Ni=class extends g{static[l]="PgMacaddr";getSQLType(){return"macaddr"}};function Bn(r){return new vi(r??"")}var Ti=class extends _{static[l]="PgMacaddr8Builder";constructor(e){super(e,"string","PgMacaddr8")}build(e){return new Ci(e,this.config)}},Ci=class extends g{static[l]="PgMacaddr8";getSQLType(){return"macaddr8"}};function Mn(r){return new Ti(r??"")}var Pi=class extends _{static[l]="PgNumericBuilder";constructor(e,t,i){super(e,"string","PgNumeric"),this.config.precision=t,this.config.scale=i}build(e){return new nt(e,this.config)}},nt=class extends g{static[l]="PgNumeric";precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue(e){return typeof e=="string"?e:String(e)}getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?"numeric":`numeric(${this.precision})`}},$i=class extends _{static[l]="PgNumericNumberBuilder";constructor(e,t,i){super(e,"number","PgNumericNumber"),this.config.precision=t,this.config.scale=i}build(e){return new Ei(e,this.config)}},Ei=class extends g{static[l]="PgNumericNumber";precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue(e){return typeof e=="number"?e:Number(e)}mapToDriverValue=String;getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?"numeric":`numeric(${this.precision})`}},Di=class extends _{static[l]="PgNumericBigIntBuilder";constructor(e,t,i){super(e,"bigint","PgNumericBigInt"),this.config.precision=t,this.config.scale=i}build(e){return new Ai(e,this.config)}},Ai=class extends g{static[l]="PgNumericBigInt";precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?"numeric":`numeric(${this.precision})`}};function Wn(r,e){let{name:t,config:i}=C(r,e),s=i?.mode;return s==="number"?new $i(t,i?.precision,i?.scale):s==="bigint"?new Di(t,i?.precision,i?.scale):new Pi(t,i?.precision,i?.scale)}var Ii=class extends _{static[l]="PgPointTupleBuilder";constructor(e){super(e,"array","PgPointTuple")}build(e){return new Li(e,this.config)}},Li=class extends g{static[l]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(e){if(typeof e=="string"){let[t,i]=e.slice(1,-1).split(",");return[Number.parseFloat(t),Number.parseFloat(i)]}return[e.x,e.y]}mapToDriverValue(e){return`(${e[0]},${e[1]})`}},Fi=class extends _{static[l]="PgPointObjectBuilder";constructor(e){super(e,"json","PgPointObject")}build(e){return new Oi(e,this.config)}},Oi=class extends g{static[l]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(e){if(typeof e=="string"){let[t,i]=e.slice(1,-1).split(",");return{x:Number.parseFloat(t),y:Number.parseFloat(i)}}return e}mapToDriverValue(e){return`(${e.x},${e.y})`}};function Un(r,e){let{name:t,config:i}=C(r,e);return!i?.mode||i.mode==="tuple"?new Ii(t):new Fi(t)}function Nl(r){let e=[];for(let t=0;t<r.length;t+=2)e.push(Number.parseInt(r.slice(t,t+2),16));return new Uint8Array(e)}function Jn(r,e){let t=new ArrayBuffer(8),i=new DataView(t);for(let s=0;s<8;s++)i.setUint8(s,r[e+s]);return i.getFloat64(0,!0)}function qi(r){let e=Nl(r),t=0,i=e[t];t+=1;let s=new DataView(e.buffer),n=s.getUint32(t,i===1);t+=4;let o;if(n&536870912&&(o=s.getUint32(t,i===1),t+=4),(n&65535)===1){let a=Jn(e,t);t+=8;let u=Jn(e,t);return t+=8,[a,u]}throw new Error("Unsupported geometry type")}var ji=class extends _{static[l]="PgGeometryBuilder";constructor(e){super(e,"array","PgGeometry")}build(e){return new zi(e,this.config)}},zi=class extends g{static[l]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(e){return qi(e)}mapToDriverValue(e){return`point(${e[0]} ${e[1]})`}},Ri=class extends _{static[l]="PgGeometryObjectBuilder";constructor(e){super(e,"json","PgGeometryObject")}build(e){return new Qi(e,this.config)}},Qi=class extends g{static[l]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(e){let t=qi(e);return{x:t[0],y:t[1]}}mapToDriverValue(e){return`point(${e.x} ${e.y})`}};function Yn(r,e){let{name:t,config:i}=C(r,e);return!i?.mode||i.mode==="tuple"?new ji(t):new Ri(t)}var ki=class extends _{static[l]="PgRealBuilder";constructor(e,t){super(e,"number","PgReal"),this.config.length=t}build(e){return new Vi(e,this.config)}},Vi=class extends g{static[l]="PgReal";constructor(e,t){super(e,t)}getSQLType(){return"real"}mapFromDriverValue=e=>typeof e=="string"?Number.parseFloat(e):e};function Hn(r){return new ki(r??"")}var Ki=class extends _{static[l]="PgSerialBuilder";constructor(e){super(e,"number","PgSerial"),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new Bi(e,this.config)}},Bi=class extends g{static[l]="PgSerial";getSQLType(){return"serial"}};function Gn(r){return new Ki(r??"")}var Mi=class extends be{static[l]="PgSmallIntBuilder";constructor(e){super(e,"number","PgSmallInt")}build(e){return new Wi(e,this.config)}},Wi=class extends g{static[l]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=e=>typeof e=="string"?Number(e):e};function Zn(r){return new Mi(r??"")}var Ui=class extends _{static[l]="PgSmallSerialBuilder";constructor(e){super(e,"number","PgSmallSerial"),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new Ji(e,this.config)}},Ji=class extends g{static[l]="PgSmallSerial";getSQLType(){return"smallserial"}};function Xn(r){return new Ui(r??"")}var Yi=class extends _{static[l]="PgTextBuilder";constructor(e,t){super(e,"string","PgText"),this.config.enumValues=t.enum}build(e){return new Hi(e,this.config)}},Hi=class extends g{static[l]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}};function eo(r,e={}){let{name:t,config:i}=C(r,e);return new Yi(t,i)}var Gi=class extends me{constructor(e,t,i){super(e,"string","PgTime"),this.withTimezone=t,this.precision=i,this.config.withTimezone=t,this.config.precision=i}static[l]="PgTimeBuilder";build(e){return new ot(e,this.config)}},ot=class extends g{static[l]="PgTime";withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}};function to(r,e={}){let{name:t,config:i}=C(r,e);return new Gi(t,i.withTimezone??!1,i.precision)}var Zi=class extends me{static[l]="PgTimestampBuilder";constructor(e,t,i){super(e,"date","PgTimestamp"),this.config.withTimezone=t,this.config.precision=i}build(e){return new at(e,this.config)}},at=class extends g{static[l]="PgTimestamp";withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=e=>new Date(this.withTimezone?e:e+"+0000");mapToDriverValue=e=>e.toISOString()},Xi=class extends me{static[l]="PgTimestampStringBuilder";constructor(e,t,i){super(e,"string","PgTimestampString"),this.config.withTimezone=t,this.config.precision=i}build(e){return new lt(e,this.config)}},lt=class extends g{static[l]="PgTimestampString";withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}};function ro(r,e={}){let{name:t,config:i}=C(r,e);return i?.mode==="string"?new Xi(t,i.withTimezone??!1,i.precision):new Zi(t,i?.withTimezone??!1,i?.precision)}var es=class extends _{static[l]="PgUUIDBuilder";constructor(e){super(e,"string","PgUUID")}defaultRandom(){return this.default(f`gen_random_uuid()`)}build(e){return new ct(e,this.config)}},ct=class extends g{static[l]="PgUUID";getSQLType(){return"uuid"}};function io(r){return new es(r??"")}var ts=class extends _{static[l]="PgVarcharBuilder";constructor(e,t){super(e,"string","PgVarchar"),this.config.length=t.length,this.config.enumValues=t.enum}build(e){return new rs(e,this.config)}},rs=class extends g{static[l]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}};function so(r,e={}){let{name:t,config:i}=C(r,e);return new ts(t,i)}var is=class extends _{static[l]="PgBinaryVectorBuilder";constructor(e,t){super(e,"string","PgBinaryVector"),this.config.dimensions=t.dimensions}build(e){return new ss(e,this.config)}},ss=class extends g{static[l]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}};function no(r,e){let{name:t,config:i}=C(r,e);return new is(t,i)}var ns=class extends _{static[l]="PgHalfVectorBuilder";constructor(e,t){super(e,"array","PgHalfVector"),this.config.dimensions=t.dimensions}build(e){return new os(e,this.config)}},os=class extends g{static[l]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){return e.slice(1,-1).split(",").map(t=>Number.parseFloat(t))}};function oo(r,e){let{name:t,config:i}=C(r,e);return new ns(t,i)}var as=class extends _{static[l]="PgSparseVectorBuilder";constructor(e,t){super(e,"string","PgSparseVector"),this.config.dimensions=t.dimensions}build(e){return new ls(e,this.config)}},ls=class extends g{static[l]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}};function ao(r,e){let{name:t,config:i}=C(r,e);return new as(t,i)}var cs=class extends _{static[l]="PgVectorBuilder";constructor(e,t){super(e,"array","PgVector"),this.config.dimensions=t.dimensions}build(e){return new us(e,this.config)}},us=class extends g{static[l]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){return e.slice(1,-1).split(",").map(t=>Number.parseFloat(t))}};function lo(r,e){let{name:t,config:i}=C(r,e);return new cs(t,i)}function co(){return{bigint:Dn,bigserial:An,boolean:In,char:Ln,cidr:Fn,customType:On,date:qn,doublePrecision:jn,inet:zn,integer:Rn,interval:Qn,json:kn,jsonb:Vn,line:Kn,macaddr:Bn,macaddr8:Mn,numeric:Wn,point:Un,geometry:Yn,real:Hn,serial:Gn,smallint:Zn,smallserial:Xn,text:eo,time:to,timestamp:ro,uuid:io,varchar:so,bit:no,halfvec:oo,sparsevec:ao,vector:lo}}var fs=Symbol.for("drizzle:PgInlineForeignKeys"),uo=Symbol.for("drizzle:EnableRLS"),V=class extends y{static[l]="PgTable";static Symbol=Object.assign({},y.Symbol,{InlineForeignKeys:fs,EnableRLS:uo});[fs]=[];[uo]=!1;[y.Symbol.ExtraConfigBuilder]=void 0;[y.Symbol.ExtraConfigColumns]={}};function Tl(r,e,t,i,s=r){let n=new V(r,i,s),o=typeof e=="function"?e(co()):e,a=Object.fromEntries(Object.entries(o).map(([c,h])=>{let p=h;p.setName(c);let S=p.build(n);return n[fs].push(...p.buildForeignKeys(S,n)),[c,S]})),u=Object.fromEntries(Object.entries(o).map(([c,h])=>{let p=h;p.setName(c);let S=p.buildExtraConfigColumn(n);return[c,S]})),m=Object.assign(n,a);return m[y.Symbol.Columns]=a,m[y.Symbol.ExtraConfigColumns]=u,t&&(m[V.Symbol.ExtraConfigBuilder]=t),Object.assign(m,{enableRLS:()=>(m[V.Symbol.EnableRLS]=!0,m)})}var M=(r,e,t)=>Tl(r,e,t,void 0);var kt=class{static[l]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new ms(e,this.columns,this.name)}},ms=class{constructor(e,t,i){this.table=e,this.columns=t,this.name=i}static[l]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[V.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}};function te(r,e){return xn(e)&&!kr(r)&&!d(r,ee)&&!d(r,ye)&&!d(r,D)&&!d(r,y)&&!d(r,H)?new ee(r,e):r}var Vt=(r,e)=>f`${r} = ${te(e,r)}`,fo=(r,e)=>f`${r} <> ${te(e,r)}`;function ut(...r){let e=r.filter(t=>t!==void 0);if(e.length!==0)return e.length===1?new b(e):new b([new k("("),f.join(e,new k(" and ")),new k(")")])}function mo(...r){let e=r.filter(t=>t!==void 0);if(e.length!==0)return e.length===1?new b(e):new b([new k("("),f.join(e,new k(" or ")),new k(")")])}function ho(r){return f`not ${r}`}var po=(r,e)=>f`${r} > ${te(e,r)}`,go=(r,e)=>f`${r} >= ${te(e,r)}`,yo=(r,e)=>f`${r} < ${te(e,r)}`,wo=(r,e)=>f`${r} <= ${te(e,r)}`;function bo(r,e){return Array.isArray(e)?e.length===0?f`false`:f`${r} in ${e.map(t=>te(t,r))}`:f`${r} in ${te(e,r)}`}function _o(r,e){return Array.isArray(e)?e.length===0?f`true`:f`${r} not in ${e.map(t=>te(t,r))}`:f`${r} not in ${te(e,r)}`}function So(r){return f`${r} is null`}function xo(r){return f`${r} is not null`}function vo(r){return f`exists ${r}`}function No(r){return f`not exists ${r}`}function To(r,e,t){return f`${r} between ${te(e,r)} and ${te(t,r)}`}function Co(r,e,t){return f`${r} not between ${te(e,r)} and ${te(t,r)}`}function Po(r,e){return f`${r} like ${e}`}function $o(r,e){return f`${r} not like ${e}`}function Eo(r,e){return f`${r} ilike ${e}`}function Do(r,e){return f`${r} not ilike ${e}`}function Ao(r){return f`${r} asc`}function Io(r){return f`${r} desc`}var Kt=class{constructor(e,t,i){this.sourceTable=e,this.referencedTable=t,this.relationName=i,this.referencedTableName=t[y.Symbol.Name]}static[l]="Relation";referencedTableName;fieldName},Bt=class{constructor(e,t){this.table=e,this.config=t}static[l]="Relations"},ve=class r extends Kt{constructor(e,t,i,s){super(e,t,i?.relationName),this.config=i,this.isNullable=s}static[l]="One";withFieldName(e){let t=new r(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}},ft=class r extends Kt{constructor(e,t,i){super(e,t,i?.relationName),this.config=i}static[l]="Many";withFieldName(e){let t=new r(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}};function Lo(){return{and:ut,between:To,eq:Vt,exists:vo,gt:po,gte:go,ilike:Eo,inArray:bo,isNull:So,isNotNull:xo,like:Po,lt:yo,lte:wo,ne:fo,not:ho,notBetween:Co,notExists:No,notLike:$o,notIlike:Do,notInArray:_o,or:mo,sql:f}}function Fo(){return{sql:f,asc:Ao,desc:Io}}function Oo(r,e){Object.keys(r).length===1&&"default"in r&&!d(r.default,y)&&(r=r.default);let t={},i={},s={};for(let[n,o]of Object.entries(r))if(d(o,y)){let a=$e(o),u=i[a];t[a]=n,s[n]={tsName:n,dbName:o[y.Symbol.Name],schema:o[y.Symbol.Schema],columns:o[y.Symbol.Columns],relations:u?.relations??{},primaryKey:u?.primaryKey??[]};for(let c of Object.values(o[y.Symbol.Columns]))c.primary&&s[n].primaryKey.push(c);let m=o[y.Symbol.ExtraConfigBuilder]?.(o[y.Symbol.ExtraConfigColumns]);if(m)for(let c of Object.values(m))d(c,kt)&&s[n].primaryKey.push(...c.columns)}else if(d(o,Bt)){let a=$e(o.table),u=t[a],m=o.config(e(o.table)),c;for(let[h,p]of Object.entries(m))if(u){let S=s[u];S.relations[h]=p,c&&S.primaryKey.push(...c)}else a in i||(i[a]={relations:{},primaryKey:c}),i[a].relations[h]=p}return{tables:s,tableNamesMap:t}}function G(r,e){return new Bt(r,t=>Object.fromEntries(Object.entries(e(t)).map(([i,s])=>[i,s.withFieldName(i)])))}function Cl(r){return function(t,i){return new ve(r,t,i,i?.fields.reduce((s,n)=>s&&n.notNull,!0)??!1)}}function Pl(r){return function(t,i){return new ft(r,t,i)}}function qo(r,e,t){if(d(t,ve)&&t.config)return{fields:t.config.fields,references:t.config.references};let i=e[$e(t.referencedTable)];if(!i)throw new Error(`Table "${t.referencedTable[y.Symbol.Name]}" not found in schema`);let s=r[i];if(!s)throw new Error(`Table "${i}" not found in schema`);let n=t.sourceTable,o=e[$e(n)];if(!o)throw new Error(`Table "${n[y.Symbol.Name]}" not found in schema`);let a=[];for(let u of Object.values(s.relations))(t.relationName&&t!==u&&u.relationName===t.relationName||!t.relationName&&u.referencedTable===t.sourceTable)&&a.push(u);if(a.length>1)throw t.relationName?new Error(`There are multiple relations with name "${t.relationName}" in table "${i}"`):new Error(`There are multiple relations between "${i}" and "${t.sourceTable[y.Symbol.Name]}". Please specify relation name`);if(a[0]&&d(a[0],ve)&&a[0].config)return{fields:a[0].config.references,references:a[0].config.fields};throw new Error(`There is not enough information to infer relation "${o}.${t.fieldName}"`)}function jo(r){return{one:Cl(r),many:Pl(r)}}function Mt(r,e,t,i,s=n=>n){let n={};for(let[o,a]of i.entries())if(a.isJson){let u=e.relations[a.tsKey],m=t[o],c=typeof m=="string"?JSON.parse(m):m;n[a.tsKey]=d(u,ve)?c&&Mt(r,r[a.relationTableTsKey],c,a.selection,s):c.map(h=>Mt(r,r[a.relationTableTsKey],h,a.selection,s))}else{let u=s(t[o]),m=a.field,c;d(m,D)?c=m:d(m,b)?c=m.decoder:c=m.sql.decoder,n[a.tsKey]=u===null?null:c.mapFromDriverValue(u)}return n}function ds(r){return f`count(${r||f.raw("*")})`.mapWith(Number)}import xs from"postgres";var z=class r{static[l]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===I)return{...e[I],selectedFields:new Proxy(e[I].selectedFields,this)};if(typeof t=="symbol")return e[t];let s=(d(e,j)?e._.selectedFields:d(e,H)?e[I].selectedFields:e)[t];if(d(s,b.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!s.isSelectionField)return s.sql;let n=s.clone();return n.isSelectionField=!0,n}if(d(s,b)){if(this.config.sqlBehavior==="sql")return s;throw new Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return d(s,D)?this.config.alias?new Proxy(s,new Ee(new Proxy(s.table,new qe(this.config.alias,this.config.replaceOriginalName??!1)))):s:typeof s!="object"||s===null?s:new Proxy(s,new r(this.config))}};var hs=class{constructor(e,t){this.unique=e,this.name=t}static[l]="PgIndexBuilderOn";on(...e){return new mt(e.map(t=>{if(d(t,b))return t;t=t;let i=new Fe(t.name,!!t.keyAsName,t.columnType,t.indexConfig);return t.indexConfig=JSON.parse(JSON.stringify(t.defaultConfig)),i}),this.unique,!1,this.name)}onOnly(...e){return new mt(e.map(t=>{if(d(t,b))return t;t=t;let i=new Fe(t.name,!!t.keyAsName,t.columnType,t.indexConfig);return t.indexConfig=t.defaultConfig,i}),this.unique,!0,this.name)}using(e,...t){return new mt(t.map(i=>{if(d(i,b))return i;i=i;let s=new Fe(i.name,!!i.keyAsName,i.columnType,i.indexConfig);return i.indexConfig=JSON.parse(JSON.stringify(i.defaultConfig)),s}),this.unique,!0,this.name,e)}},mt=class{static[l]="PgIndexBuilder";config;constructor(e,t,i,s,n="btree"){this.config={name:s,columns:e,unique:t,only:i,method:n}}concurrently(){return this.config.concurrently=!0,this}with(e){return this.config.with=e,this}where(e){return this.config.where=e,this}build(e){return new ps(this.config,e)}},ps=class{static[l]="PgIndex";config;constructor(e,t){this.config={...e,table:t}}};function K(r){return new hs(!1,r)}function $l(r){return(r.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(t=>t.toLowerCase()).join("_")}function El(r){return(r.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((t,i,s)=>{let n=s===0?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`;return t+n},"")}function Dl(r){return r}var Wt=class{static[l]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?$l:e==="camelCase"?El:Dl}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[y.Symbol.Schema]??"public",i=e.table[y.Symbol.OriginalName],s=`${t}.${i}.${e.name}`;return this.cache[s]||this.cacheTable(e.table),this.cache[s]}cacheTable(e){let t=e[y.Symbol.Schema]??"public",i=e[y.Symbol.OriginalName],s=`${t}.${i}`;if(!this.cachedTables[s]){for(let n of Object.values(e[y.Symbol.Columns])){let o=`${s}.${n.name}`;this.cache[o]=this.convert(n.name)}this.cachedTables[s]=!0}}clearCache(){this.cache={},this.cachedTables={}}};var je=class extends H{static[l]="PgViewBase"};var Ne=class{static[l]="PgDialect";casing;constructor(e){this.casing=new Wt(e?.casing)}async migrate(e,t,i){let s=typeof i=="string"?"__drizzle_migrations":i.migrationsTable??"__drizzle_migrations",n=typeof i=="string"?"drizzle":i.migrationsSchema??"drizzle",o=f`
9
- CREATE TABLE IF NOT EXISTS ${f.identifier(n)}.${f.identifier(s)} (
6
+ import{stat as ca}from"fs";import{stat as ua,readdir as ma}from"fs/promises";import{EventEmitter as fa}from"events";import*as v from"path";import{stat as Lo,lstat as xs,readdir as Io,realpath as jo}from"fs/promises";import{Readable as zo}from"stream";import{resolve as _s,relative as Oo,join as Qo,sep as Ro}from"path";var re={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},lr={root:".",fileFilter:r=>!0,directoryFilter:r=>!0,type:re.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(lr);var Ps="READDIRP_RECURSIVE_ERROR",ko=new Set(["ENOENT","EPERM","EACCES","ELOOP",Ps]),Ns=[re.DIR_TYPE,re.EVERYTHING_TYPE,re.FILE_DIR_TYPE,re.FILE_TYPE],Bo=new Set([re.DIR_TYPE,re.EVERYTHING_TYPE,re.FILE_DIR_TYPE]),Ko=new Set([re.EVERYTHING_TYPE,re.FILE_DIR_TYPE,re.FILE_TYPE]),Vo=r=>ko.has(r.code),Mo=process.platform==="win32",Cs=r=>!0,vs=r=>{if(r===void 0)return Cs;if(typeof r=="function")return r;if(typeof r=="string"){let e=r.trim();return t=>t.basename===e}if(Array.isArray(r)){let e=r.map(t=>t.trim());return t=>e.some(i=>t.basename===i)}return Cs},cr=class extends zo{constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark});let t={...lr,...e},{root:i,type:s}=t;this._fileFilter=vs(t.fileFilter),this._directoryFilter=vs(t.directoryFilter);let n=t.lstat?xs:Lo;Mo?this._stat=o=>n(o,{bigint:!0}):this._stat=n,this._maxDepth=t.depth??lr.depth,this._wantsDir=s?Bo.has(s):!1,this._wantsFile=s?Ko.has(s):!1,this._wantsEverything=s===re.EVERYTHING_TYPE,this._root=_s(i),this._isDirent=!t.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(i,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let t=this.parent,i=t&&t.files;if(i&&i.length>0){let{path:s,depth:n}=t,o=i.splice(0,e).map(m=>this._formatEntry(m,s)),a=await Promise.all(o);for(let m of a){if(!m)continue;if(this.destroyed)return;let f=await this._getEntryType(m);f==="directory"&&this._directoryFilter(m)?(n<=this._maxDepth&&this.parents.push(this._exploreDir(m.fullPath,n+1)),this._wantsDir&&(this.push(m),e--)):(f==="file"||this._includeAsFile(m))&&this._fileFilter(m)&&this._wantsFile&&(this.push(m),e--)}}else{let s=this.parents.pop();if(!s){this.push(null);break}if(this.parent=await s,this.destroyed)return}}}catch(t){this.destroy(t)}finally{this.reading=!1}}}async _exploreDir(e,t){let i;try{i=await Io(e,this._rdOptions)}catch(s){this._onError(s)}return{files:i,depth:t,path:e}}async _formatEntry(e,t){let i,s=this._isDirent?e.name:e;try{let n=_s(Qo(t,s));i={path:Oo(this._root,n),fullPath:n,basename:s},i[this._statsProp]=this._isDirent?e:await this._stat(n)}catch(n){this._onError(n);return}return i}_onError(e){Vo(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){if(!e&&this._statsProp in e)return"";let t=e[this._statsProp];if(t.isFile())return"file";if(t.isDirectory())return"directory";if(t&&t.isSymbolicLink()){let i=e.fullPath;try{let s=await jo(i),n=await xs(s);if(n.isFile())return"file";if(n.isDirectory()){let o=s.length;if(i.startsWith(s)&&i.substr(o,1)===Ro){let a=new Error(`Circular symlink detected: "${i}" points to "${s}"`);return a.code=Ps,this._onError(a)}return"directory"}}catch(s){return this._onError(s),""}}}_includeAsFile(e){let t=e&&e[this._statsProp];return t&&this._wantsEverything&&!t.isDirectory()}};function Ts(r,e={}){let t=e.entryType||e.type;if(t==="both"&&(t=re.FILE_DIR_TYPE),t&&(e.type=t),r){if(typeof r!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(t&&!Ns.includes(t))throw new Error(`readdirp: Invalid type passed. Use one of ${Ns.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=r,new cr(e)}import{watchFile as Wo,unwatchFile as $s,watch as Uo}from"fs";import{open as Jo,stat as Es,lstat as Ho,realpath as ur}from"fs/promises";import*as L from"path";import{type as Yo}from"os";var Go="data",dr="end",As="close",_t=()=>{};var Nt=process.platform,hr=Nt==="win32",Zo=Nt==="darwin",Xo=Nt==="linux",ea=Nt==="freebsd",Fs=Yo()==="OS400",j={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},se=j,ta="watch",ra={lstat:Ho,stat:Es},Ne="listeners",wt="errHandlers",Ee="rawEmitters",ia=[Ne,wt,Ee],sa=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),na=r=>sa.has(L.extname(r).slice(1).toLowerCase()),fr=(r,e)=>{r instanceof Set?r.forEach(e):e(r)},ke=(r,e,t)=>{let i=r[e];i instanceof Set||(r[e]=i=new Set([i])),i.add(t)},oa=r=>e=>{let t=r[e];t instanceof Set?t.clear():delete r[e]},Be=(r,e,t)=>{let i=r[e];i instanceof Set?i.delete(t):i===t&&delete r[e]},qs=r=>r instanceof Set?r.size===0:!r,bt=new Map;function Ds(r,e,t,i,s){let n=(o,a)=>{t(r),s(o,a,{watchedPath:r}),a&&r!==a&&St(L.resolve(r,a),Ne,L.join(r,a))};try{return Uo(r,{persistent:e.persistent},n)}catch(o){i(o);return}}var St=(r,e,t,i,s)=>{let n=bt.get(r);n&&fr(n[e],o=>{o(t,i,s)})},aa=(r,e,t,i)=>{let{listener:s,errHandler:n,rawEmitter:o}=i,a=bt.get(e),m;if(!t.persistent)return m=Ds(r,t,s,n,o),m?m.close.bind(m):void 0;if(a)ke(a,Ne,s),ke(a,wt,n),ke(a,Ee,o);else{if(m=Ds(r,t,St.bind(null,e,Ne),n,St.bind(null,e,Ee)),!m)return;m.on(se.ERROR,async f=>{let u=St.bind(null,e,wt);if(a&&(a.watcherUnusable=!0),hr&&f.code==="EPERM")try{await(await Jo(r,"r")).close(),u(f)}catch{}else u(f)}),a={listeners:s,errHandlers:n,rawEmitters:o,watcher:m},bt.set(e,a)}return()=>{Be(a,Ne,s),Be(a,wt,n),Be(a,Ee,o),qs(a.listeners)&&(a.watcher.close(),bt.delete(e),ia.forEach(oa(a)),a.watcher=void 0,Object.freeze(a))}},mr=new Map,la=(r,e,t,i)=>{let{listener:s,rawEmitter:n}=i,o=mr.get(e),a=o&&o.options;return a&&(a.persistent<t.persistent||a.interval>t.interval)&&($s(e),o=void 0),o?(ke(o,Ne,s),ke(o,Ee,n)):(o={listeners:s,rawEmitters:n,options:t,watcher:Wo(e,t,(m,f)=>{fr(o.rawEmitters,h=>{h(se.CHANGE,e,{curr:m,prev:f})});let u=m.mtimeMs;(m.size!==f.size||u>f.mtimeMs||u===0)&&fr(o.listeners,h=>h(r,m))})},mr.set(e,o)),()=>{Be(o,Ne,s),Be(o,Ee,n),qs(o.listeners)&&(mr.delete(e),$s(e),o.options=o.watcher=void 0,Object.freeze(o))}},xt=class{constructor(e){this.fsw=e,this._boundHandleError=t=>e._handleError(t)}_watchWithNodeFs(e,t){let i=this.fsw.options,s=L.dirname(e),n=L.basename(e);this.fsw._getWatchedDir(s).add(n);let a=L.resolve(e),m={persistent:i.persistent};t||(t=_t);let f;if(i.usePolling){let u=i.interval!==i.binaryInterval;m.interval=u&&na(n)?i.binaryInterval:i.interval,f=la(e,a,m,{listener:t,rawEmitter:this.fsw._emitRaw})}else f=aa(e,a,m,{listener:t,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return f}_handleFile(e,t,i){if(this.fsw.closed)return;let s=L.dirname(e),n=L.basename(e),o=this.fsw._getWatchedDir(s),a=t;if(o.has(n))return;let m=async(u,h)=>{if(this.fsw._throttle(ta,e,5)){if(!h||h.mtimeMs===0)try{let p=await Es(e);if(this.fsw.closed)return;let x=p.atimeMs,_=p.mtimeMs;if((!x||x<=_||_!==a.mtimeMs)&&this.fsw._emit(se.CHANGE,e,p),(Zo||Xo||ea)&&a.ino!==p.ino){this.fsw._closeFile(u),a=p;let $=this._watchWithNodeFs(e,m);$&&this.fsw._addPathCloser(u,$)}else a=p}catch{this.fsw._remove(s,n)}else if(o.has(n)){let p=h.atimeMs,x=h.mtimeMs;(!p||p<=x||x!==a.mtimeMs)&&this.fsw._emit(se.CHANGE,e,h),a=h}}},f=this._watchWithNodeFs(e,m);if(!(i&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(se.ADD,e,0))return;this.fsw._emit(se.ADD,e,t)}return f}async _handleSymlink(e,t,i,s){if(this.fsw.closed)return;let n=e.fullPath,o=this.fsw._getWatchedDir(t);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await ur(i)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(o.has(s)?this.fsw._symlinkPaths.get(n)!==a&&(this.fsw._symlinkPaths.set(n,a),this.fsw._emit(se.CHANGE,i,e.stats)):(o.add(s),this.fsw._symlinkPaths.set(n,a),this.fsw._emit(se.ADD,i,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(n))return!0;this.fsw._symlinkPaths.set(n,!0)}_handleRead(e,t,i,s,n,o,a){if(e=L.join(e,""),a=this.fsw._throttle("readdir",e,1e3),!a)return;let m=this.fsw._getWatchedDir(i.path),f=new Set,u=this.fsw._readdirp(e,{fileFilter:h=>i.filterPath(h),directoryFilter:h=>i.filterDir(h)});if(u)return u.on(Go,async h=>{if(this.fsw.closed){u=void 0;return}let p=h.path,x=L.join(e,p);if(f.add(p),!(h.stats.isSymbolicLink()&&await this._handleSymlink(h,e,x,p))){if(this.fsw.closed){u=void 0;return}(p===s||!s&&!m.has(p))&&(this.fsw._incrReadyCount(),x=L.join(n,L.relative(n,x)),this._addToNodeFs(x,t,i,o+1))}}).on(se.ERROR,this._boundHandleError),new Promise((h,p)=>{if(!u)return p();u.once(dr,()=>{if(this.fsw.closed){u=void 0;return}let x=a?a.clear():!1;h(void 0),m.getChildren().filter(_=>_!==e&&!f.has(_)).forEach(_=>{this.fsw._remove(e,_)}),u=void 0,x&&this._handleRead(e,!1,i,s,n,o,a)})})}async _handleDir(e,t,i,s,n,o,a){let m=this.fsw._getWatchedDir(L.dirname(e)),f=m.has(L.basename(e));!(i&&this.fsw.options.ignoreInitial)&&!n&&!f&&this.fsw._emit(se.ADD_DIR,e,t),m.add(L.basename(e)),this.fsw._getWatchedDir(e);let u,h,p=this.fsw.options.depth;if((p==null||s<=p)&&!this.fsw._symlinkPaths.has(a)){if(!n&&(await this._handleRead(e,i,o,n,e,s,u),this.fsw.closed))return;h=this._watchWithNodeFs(e,(x,_)=>{_&&_.mtimeMs===0||this._handleRead(x,!1,o,n,e,s,u)})}return h}async _addToNodeFs(e,t,i,s,n){let o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return o(),!1;let a=this.fsw._getWatchHelpers(e);i&&(a.filterPath=m=>i.filterPath(m),a.filterDir=m=>i.filterDir(m));try{let m=await ra[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,m))return o(),!1;let f=this.fsw.options.followSymlinks,u;if(m.isDirectory()){let h=L.resolve(e),p=f?await ur(e):e;if(this.fsw.closed||(u=await this._handleDir(a.watchPath,m,t,s,n,a,p),this.fsw.closed))return;h!==p&&p!==void 0&&this.fsw._symlinkPaths.set(h,p)}else if(m.isSymbolicLink()){let h=f?await ur(e):e;if(this.fsw.closed)return;let p=L.dirname(a.watchPath);if(this.fsw._getWatchedDir(p).add(a.watchPath),this.fsw._emit(se.ADD,a.watchPath,m),u=await this._handleDir(p,m,t,s,e,a,h),this.fsw.closed)return;h!==void 0&&this.fsw._symlinkPaths.set(L.resolve(e),h)}else u=this._handleFile(a.watchPath,m,t);return o(),u&&this.fsw._addPathCloser(e,u),!1}catch(m){if(this.fsw._handleError(m))return o(),e}}};var pr="/",da="//",Qs=".",ha="..",pa="string",ga=/\\/g,Ls=/\/\//,ya=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,wa=/^\.[/\\]/;function Ct(r){return Array.isArray(r)?r:[r]}var gr=r=>typeof r=="object"&&r!==null&&!(r instanceof RegExp);function ba(r){return typeof r=="function"?r:typeof r=="string"?e=>r===e:r instanceof RegExp?e=>r.test(e):typeof r=="object"&&r!==null?e=>{if(r.path===e)return!0;if(r.recursive){let t=v.relative(r.path,e);return t?!t.startsWith("..")&&!v.isAbsolute(t):!1}return!1}:()=>!1}function Sa(r){if(typeof r!="string")throw new Error("string expected");r=v.normalize(r),r=r.replace(/\\/g,"/");let e=!1;r.startsWith("//")&&(e=!0);let t=/\/\//;for(;r.match(t);)r=r.replace(t,"/");return e&&(r="/"+r),r}function Is(r,e,t){let i=Sa(e);for(let s=0;s<r.length;s++){let n=r[s];if(n(i,t))return!0}return!1}function xa(r,e){if(r==null)throw new TypeError("anymatch: specify first argument");let i=Ct(r).map(s=>ba(s));return e==null?(s,n)=>Is(i,s,n):Is(i,e)}var js=r=>{let e=Ct(r).flat();if(!e.every(t=>typeof t===pa))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Rs)},zs=r=>{let e=r.replace(ga,pr),t=!1;for(e.startsWith(da)&&(t=!0);e.match(Ls);)e=e.replace(Ls,pr);return t&&(e=pr+e),e},Rs=r=>zs(v.normalize(zs(r))),Os=(r="")=>e=>typeof e=="string"?Rs(v.isAbsolute(e)?e:v.join(r,e)):e,_a=(r,e)=>v.isAbsolute(r)?r:v.join(e,r),Na=Object.freeze(new Set),yr=class{constructor(e,t){this.path=e,this._removeWatcher=t,this.items=new Set}add(e){let{items:t}=this;t&&e!==Qs&&e!==ha&&t.add(e)}async remove(e){let{items:t}=this;if(!t||(t.delete(e),t.size>0))return;let i=this.path;try{await ma(i)}catch{this._removeWatcher&&this._removeWatcher(v.dirname(i),v.basename(i))}}has(e){let{items:t}=this;if(t)return t.has(e)}getChildren(){let{items:e}=this;return e?[...e.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=_t,this.items=Na,Object.freeze(this)}},Ca="stat",va="lstat",wr=class{constructor(e,t,i){this.fsw=i;let s=e;this.path=e=e.replace(wa,""),this.watchPath=s,this.fullWatchPath=v.resolve(s),this.dirParts=[],this.dirParts.forEach(n=>{n.length>1&&n.pop()}),this.followSymlinks=t,this.statMethod=t?Ca:va}entryPath(e){return v.join(this.watchPath,v.relative(this.watchPath,e.fullPath))}filterPath(e){let{stats:t}=e;if(t&&t.isSymbolicLink())return this.filterDir(e);let i=this.entryPath(e);return this.fsw._isntIgnored(i,t)&&this.fsw._hasReadPermissions(t)}filterDir(e){return this.fsw._isntIgnored(this.entryPath(e),e.stats)}},vt=class extends fa{constructor(e={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let t=e.awaitWriteFinish,i={stabilityThreshold:2e3,pollInterval:100},s={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...e,ignored:e.ignored?Ct(e.ignored):Ct([]),awaitWriteFinish:t===!0?i:typeof t=="object"?{...i,...t}:!1};Fs&&(s.usePolling=!0),s.atomic===void 0&&(s.atomic=!s.usePolling);let n=process.env.CHOKIDAR_USEPOLLING;if(n!==void 0){let m=n.toLowerCase();m==="false"||m==="0"?s.usePolling=!1:m==="true"||m==="1"?s.usePolling=!0:s.usePolling=!!m}let o=process.env.CHOKIDAR_INTERVAL;o&&(s.interval=Number.parseInt(o,10));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=_t,this._readyEmitted=!0,process.nextTick(()=>this.emit(j.READY)))},this._emitRaw=(...m)=>this.emit(j.RAW,...m),this._boundRemove=this._remove.bind(this),this.options=s,this._nodeFsHandler=new xt(this),Object.freeze(s)}_addIgnoredPath(e){if(gr(e)){for(let t of this._ignoredPaths)if(gr(t)&&t.path===e.path&&t.recursive===e.recursive)return}this._ignoredPaths.add(e)}_removeIgnoredPath(e){if(this._ignoredPaths.delete(e),typeof e=="string")for(let t of this._ignoredPaths)gr(t)&&t.path===e&&this._ignoredPaths.delete(t)}add(e,t,i){let{cwd:s}=this.options;this.closed=!1,this._closePromise=void 0;let n=js(e);return s&&(n=n.map(o=>_a(o,s))),n.forEach(o=>{this._removeIgnoredPath(o)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=n.length,Promise.all(n.map(async o=>{let a=await this._nodeFsHandler._addToNodeFs(o,!i,void 0,0,t);return a&&this._emitReady(),a})).then(o=>{this.closed||o.forEach(a=>{a&&this.add(v.dirname(a),v.basename(t||a))})}),this}unwatch(e){if(this.closed)return this;let t=js(e),{cwd:i}=this.options;return t.forEach(s=>{!v.isAbsolute(s)&&!this._closers.has(s)&&(i&&(s=v.join(i,s)),s=v.resolve(s)),this._closePath(s),this._addIgnoredPath(s),this._watched.has(s)&&this._addIgnoredPath({path:s,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(t=>t.forEach(i=>{let s=i();s instanceof Promise&&e.push(s)})),this._streams.forEach(t=>t.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(t=>t.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((t,i)=>{let n=(this.options.cwd?v.relative(this.options.cwd,i):i)||Qs;e[n]=t.getChildren().sort()}),e}emitWithAll(e,t){this.emit(e,...t),e!==j.ERROR&&this.emit(j.ALL,e,...t)}async _emit(e,t,i){if(this.closed)return;let s=this.options;hr&&(t=v.normalize(t)),s.cwd&&(t=v.relative(s.cwd,t));let n=[t];i!=null&&n.push(i);let o=s.awaitWriteFinish,a;if(o&&(a=this._pendingWrites.get(t)))return a.lastChange=new Date,this;if(s.atomic){if(e===j.UNLINK)return this._pendingUnlinks.set(t,[e,...n]),setTimeout(()=>{this._pendingUnlinks.forEach((m,f)=>{this.emit(...m),this.emit(j.ALL,...m),this._pendingUnlinks.delete(f)})},typeof s.atomic=="number"?s.atomic:100),this;e===j.ADD&&this._pendingUnlinks.has(t)&&(e=j.CHANGE,this._pendingUnlinks.delete(t))}if(o&&(e===j.ADD||e===j.CHANGE)&&this._readyEmitted){let m=(f,u)=>{f?(e=j.ERROR,n[0]=f,this.emitWithAll(e,n)):u&&(n.length>1?n[1]=u:n.push(u),this.emitWithAll(e,n))};return this._awaitWriteFinish(t,o.stabilityThreshold,e,m),this}if(e===j.CHANGE&&!this._throttle(j.CHANGE,t,50))return this;if(s.alwaysStat&&i===void 0&&(e===j.ADD||e===j.ADD_DIR||e===j.CHANGE)){let m=s.cwd?v.join(s.cwd,t):t,f;try{f=await ua(m)}catch{}if(!f||this.closed)return;n.push(f)}return this.emitWithAll(e,n),this}_handleError(e){let t=e&&e.code;return e&&t!=="ENOENT"&&t!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||t!=="EPERM"&&t!=="EACCES")&&this.emit(j.ERROR,e),e||this.closed}_throttle(e,t,i){this._throttled.has(e)||this._throttled.set(e,new Map);let s=this._throttled.get(e);if(!s)throw new Error("invalid throttle");let n=s.get(t);if(n)return n.count++,!1;let o,a=()=>{let f=s.get(t),u=f?f.count:0;return s.delete(t),clearTimeout(o),f&&clearTimeout(f.timeoutObject),u};o=setTimeout(a,i);let m={timeoutObject:o,clear:a,count:0};return s.set(t,m),m}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,t,i,s){let n=this.options.awaitWriteFinish;if(typeof n!="object")return;let o=n.pollInterval,a,m=e;this.options.cwd&&!v.isAbsolute(e)&&(m=v.join(this.options.cwd,e));let f=new Date,u=this._pendingWrites;function h(p){ca(m,(x,_)=>{if(x||!u.has(e)){x&&x.code!=="ENOENT"&&s(x);return}let $=Number(new Date);p&&_.size!==p.size&&(u.get(e).lastChange=$);let q=u.get(e);$-q.lastChange>=t?(u.delete(e),s(void 0,_)):a=setTimeout(h,o,_)})}u.has(e)||(u.set(e,{lastChange:f,cancelWait:()=>(u.delete(e),clearTimeout(a),i)}),a=setTimeout(h,o))}_isIgnored(e,t){if(this.options.atomic&&ya.test(e))return!0;if(!this._userIgnored){let{cwd:i}=this.options,n=(this.options.ignored||[]).map(Os(i)),a=[...[...this._ignoredPaths].map(Os(i)),...n];this._userIgnored=xa(a,void 0)}return this._userIgnored(e,t)}_isntIgnored(e,t){return!this._isIgnored(e,t)}_getWatchHelpers(e){return new wr(e,this.options.followSymlinks,this)}_getWatchedDir(e){let t=v.resolve(e);return this._watched.has(t)||this._watched.set(t,new yr(t,this._boundRemove)),this._watched.get(t)}_hasReadPermissions(e){return this.options.ignorePermissionErrors?!0:!!(Number(e.mode)&256)}_remove(e,t,i){let s=v.join(e,t),n=v.resolve(s);if(i=i??(this._watched.has(s)||this._watched.has(n)),!this._throttle("remove",s,100))return;!i&&this._watched.size===1&&this.add(e,t,!0),this._getWatchedDir(s).getChildren().forEach(p=>this._remove(s,p));let m=this._getWatchedDir(e),f=m.has(t);m.remove(t),this._symlinkPaths.has(n)&&this._symlinkPaths.delete(n);let u=s;if(this.options.cwd&&(u=v.relative(this.options.cwd,s)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)&&this._pendingWrites.get(u).cancelWait()===j.ADD)return;this._watched.delete(s),this._watched.delete(n);let h=i?j.UNLINK_DIR:j.UNLINK;f&&!this._isIgnored(s)&&this._emit(h,s),this._closePath(s)}_closePath(e){this._closeFile(e);let t=v.dirname(e);this._getWatchedDir(t).remove(v.basename(e))}_closeFile(e){let t=this._closers.get(e);t&&(t.forEach(i=>i()),this._closers.delete(e))}_addPathCloser(e,t){if(!t)return;let i=this._closers.get(e);i||(i=[],this._closers.set(e,i)),i.push(t)}_readdirp(e,t){if(this.closed)return;let i={type:j.ALL,alwaysStat:!0,lstat:!0,...t,depth:0},s=Ts(e,i);return this._streams.add(s),s.once(As,()=>{s=void 0}),s.once(dr,()=>{s&&(this._streams.delete(s),s=void 0)}),s}};function Pa(r,e={}){let t=new vt(e);return t.add(r),t}var ks={watch:Pa,FSWatcher:vt};import{existsSync as Ce,mkdirSync as za,readFileSync as Oa,unlinkSync as Qa}from"fs";import{basename as Ws,join as ne,relative as Us}from"path";import{copyFileSync as Ta,existsSync as le,mkdirSync as $a,readdirSync as Vs,readFileSync as Da,writeFileSync as Ea}from"fs";import{basename as Bs,dirname as Pt,extname as Aa,join as he,normalize as Fa,relative as Ae,sep as qa}from"path";var La=/import\s+(?:(?:{[^}]*})|(?:[^{}\s,]*))?\s*(?:,\s*(?:{[^}]*}))?\s*from\s+['"]([./]+[^'"]*)['"]/g,Ia=/import\s+(?:(?:{[^}]*})|(?:[^{}\s,]*))?\s*(?:,\s*(?:{[^}]*}))?\s*from\s+['"](@\/[^'"]*)['"]/g,Ks=/\.(js|jsx|ts|tsx)$/,br=/^page\.(tsx|ts|jsx|js)$/i,Ke=(r,e)=>{let i=Ae(e,r).split(qa);i.pop();let s=i.filter(n=>!n.startsWith("("));return Fa(s.join("/"))},Tt=r=>{let e=new Map,t=i=>{if(le(i))for(let s of Vs(i,{withFileTypes:!0})){let n=he(i,s.name);if(s.isDirectory()){t(n);continue}if(br.test(s.name)){let o=Ke(n,r);e.set(o,n)}}};return t(r),e},ja=(r,e)=>{let t=r.replace(La,(i,s)=>{if(s.startsWith(".")){let o=s.replace(Ks,"").replace(/^(?:\.\.\/)+/,"");return i.replace(s,`${e}/${o}`)}return i});return t=t.replace(Ia,(i,s)=>{let n=s.replace(/^@\//,"").replace(Ks,"");return i.replace(s,`${e}/${n}`)}),t};function $t(r){let e=r;for(;e!==Pt(e);){if(le(he(e,"turbo.json"))||le(he(e,".git")))return e;e=Pt(e)}let t=he(r,"package.json");if(le(t))return Pt(t);throw new Error("\u274C Could not locate project root")}function Dt(r){let e=he(r,"src","app","[locale]");if(le(e))return e;let t=he(r,"apps","web","src","app","[locale]");return le(t),t}var Ve=r=>{let e=[];if(!le(r))return e;let t=Vs(r,{withFileTypes:!0});for(let i of t){let s=he(r,i.name);i.isDirectory()?e.push(...Ve(s)):e.push(s)}return e},Me=r=>le(r)?Ve(r).length===0:!0,Sr=(r,e,t,i,s,n,o=!0)=>{let a=Bs(r);if(br.test(a)){let m=Ke(e,s),f=i.get(m);if(f&&f!==e){o&&console.log(`\x1B[31mSkipped duplicate page:\x1B[0m ${Ae(n,e)} (collides with ${Ae(n,f)})`);return}}try{let m=Pt(e);le(m)||$a(m,{recursive:!0});let f=Aa(r);if(t&&[".js",".jsx",".ts",".tsx"].includes(f)){let u=Da(r,"utf-8"),h=ja(u,t);Ea(e,h)}else Ta(r,e);if(o){let u=r.indexOf(he("src","app")),h=u!==-1?r.substring(u):r.startsWith(n)?Ae(n,r):r,p=e.startsWith(n)?Ae(n,e):e;console.log(`\x1B[32mCopied:\x1B[0m ${h} \u2192 ${p}`)}if(br.test(Bs(e))){let u=Ke(e,s);i.set(u,e)}}catch(m){console.error(`\x1B[31mError copying file:\x1B[0m ${r}`,m)}},Ms=(r,e,t,i,s,n,o=!0)=>{if(!le(r)||Me(r))return;let a=Ve(r);for(let m of a){let f=Ae(r,m),u=he(e,f);Sr(m,u,t,i,s,n,o)}};var Js=({initMessage:r})=>{let e=process.cwd(),t=$t(e),i=Dt(t),s=Tt(i),n=Ws(e);try{let w=ne(e,"package.json");Ce(w)&&(n=JSON.parse(Oa(w,"utf-8")).name??"")}catch(w){console.error("\x1B[31mError reading package.json:\x1B[0m",w);return}let o=n.replace(/\//g,"-").replace(/@/g,""),a=ne(t,"apps","web","src","app","[locale]","(main)",ne("(plugins)",`(${o})`)),m=ne(t,"apps","web","src","app","[locale]","admin","(auth)",ne("(plugins)",`(${o})`)),f=ne(t,"apps","web","src","locales",n),u=[{sourceDir:ne(e,"src","app_admin"),destinationDir:m},{sourceDir:ne(e,"src","app"),destinationDir:a},{sourceDir:ne(e,"src","locales"),destinationDir:f}];for(let{sourceDir:w,destinationDir:N}of u)Ce(w)&&!Me(w)&&!Ce(N)&&za(N,{recursive:!0});let h=(w,N)=>{Sr(w,N,n,s,i,t)},p=w=>{try{if(Ce(w)&&(Qa(w),console.log(`\x1B[33mRemoved:\x1B[0m ${w}`),/^page\.(tsx|ts|jsx|js)$/i.test(Ws(w)))){let N=Ke(w,i);s.get(N)===w&&s.delete(N)}}catch(N){console.error(`\x1B[31mError removing file:\x1B[0m ${w}`,N)}},x=(w,N)=>{if(!Ce(N))return;let R=Ve(N);for(let I of R){let J=Us(N,I),Q=ne(w,J);Ce(Q)||p(I)}};for(let{sourceDir:w,destinationDir:N}of u)x(w,N);console.log(`${r} \x1B[34mWatching for changes in plugins...\x1B[0m`);let _=u.map(w=>w.sourceDir).filter(w=>Ce(w)),$=ks.watch(_,{ignoreInitial:!1,persistent:!0}),q=w=>{let N=u.filter(({sourceDir:J})=>w.startsWith(J));if(N.length===0)throw new Error(`No matching source directory for: ${w}`);let R=N.reduce((J,Q)=>Q.sourceDir.length>J.sourceDir.length?Q:J),I=Us(R.sourceDir,w);return ne(R.destinationDir,I)};$.on("add",w=>{let N=q(w);h(w,N)}).on("change",w=>{let N=q(w);h(w,N)}).on("unlink",w=>{let N=q(w);p(N)}).on("error",w=>{console.error("\x1B[31mWatcher error:\x1B[0m",w)})};import*as $o from"dotenv";var l=Symbol.for("drizzle:entityKind"),ql=Symbol.for("drizzle:hasOwnEntityKind");function d(r,e){if(!r||typeof r!="object")return!1;if(r instanceof e)return!0;if(!Object.prototype.hasOwnProperty.call(e,l))throw new Error(`Class "${e.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let t=Object.getPrototypeOf(r).constructor;if(t)for(;t;){if(l in t&&t[l]===e[l])return!0;t=Object.getPrototypeOf(t)}return!1}var E=class{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[l]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}};var Et=class{static[l]="ColumnBuilder";config;constructor(e,t,i){this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:i,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){this.config.name===""&&(this.config.name=e)}};var oe=Symbol.for("drizzle:Name");var At=class{static[l]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){this.reference=()=>{let{name:i,columns:s,foreignColumns:n}=e();return{name:i,columns:s,foreignTable:n[0].table,foreignColumns:n}},t&&(this._onUpdate=t.onUpdate,this._onDelete=t.onDelete)}onUpdate(e){return this._onUpdate=e===void 0?"no action":e,this}onDelete(e){return this._onDelete=e===void 0?"no action":e,this}build(e){return new xr(e,this)}},xr=class{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[l]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:i}=this.reference(),s=t.map(a=>a.name),n=i.map(a=>a.name),o=[this.table[oe],...s,i[0].table[oe],...n];return e??`${o.join("_")}_fk`}};function Ft(r,...e){return r(...e)}function Cr(r,e){return`${r[oe]}_${e.join("_")}_unique`}var _r=class{constructor(e,t){this.name=t,this.columns=e}static[l]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new Nr(e,this.columns,this.nullsNotDistinctConfig,this.name)}},Hs=class{static[l]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new _r(e,this.name)}},Nr=class{constructor(e,t,i,s){this.table=e,this.columns=t,this.name=s??Cr(this.table,this.columns.map(n=>n.name)),this.nullsNotDistinct=i}static[l]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}};function Ys(r,e,t){for(let i=e;i<r.length;i++){let s=r[i];if(s==="\\"){i++;continue}if(s==='"')return[r.slice(e,i).replace(/\\/g,""),i+1];if(!t&&(s===","||s==="}"))return[r.slice(e,i).replace(/\\/g,""),i]}return[r.slice(e).replace(/\\/g,""),r.length]}function Gs(r,e=0){let t=[],i=e,s=!1;for(;i<r.length;){let n=r[i];if(n===","){(s||i===e)&&t.push(""),s=!0,i++;continue}if(s=!1,n==="\\"){i+=2;continue}if(n==='"'){let[m,f]=Ys(r,i+1,!0);t.push(m),i=f;continue}if(n==="}")return[t,i+1];if(n==="{"){let[m,f]=Gs(r,i+1);t.push(m),i=f;continue}let[o,a]=Ys(r,i,!1);t.push(o),i=a}return[t,i]}function Zs(r){let[e]=Gs(r,1);return e}function vr(r){return`{${r.map(e=>Array.isArray(e)?vr(e):typeof e=="string"?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:`${e}`).join(",")}}`}var S=class extends Et{foreignKeyConfigs=[];static[l]="PgColumnBuilder";array(e){return new Tr(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:i,actions:s})=>Ft((n,o)=>{let a=new At(()=>{let m=n();return{columns:[e],foreignColumns:[m]}});return o.onUpdate&&a.onUpdate(o.onUpdate),o.onDelete&&a.onDelete(o.onDelete),a.build(t)},i,s))}buildExtraConfigColumn(e){return new Pr(e,this.config)}},g=class extends E{constructor(e,t){t.uniqueName||(t.uniqueName=Cr(e,[t.name])),super(e,t),this.table=e}static[l]="PgColumn"},Pr=class extends g{static[l]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}},Fe=class{static[l]="IndexedColumn";constructor(e,t,i,s){this.name=e,this.keyAsName=t,this.type=i,this.indexConfig=s}name;keyAsName;type;indexConfig},Tr=class extends S{static[l]="PgArrayBuilder";constructor(e,t,i){super(e,"array","PgArray"),this.config.baseBuilder=t,this.config.size=i}build(e){let t=this.config.baseBuilder.build(e);return new $r(e,this.config,t)}},$r=class r extends g{constructor(e,t,i,s){super(e,t),this.baseColumn=i,this.range=s,this.size=t.size}size;static[l]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size=="number"?this.size:""}]`}mapFromDriverValue(e){return typeof e=="string"&&(e=Zs(e)),e.map(t=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let i=e.map(s=>s===null?null:d(this.baseColumn,r)?this.baseColumn.mapToDriverValue(s,!0):this.baseColumn.mapToDriverValue(s));return t?i:vr(i)}};var Xs=class extends S{static[l]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn"),this.config.enum=t}build(e){return new Dr(e,this.config)}},Dr=class extends g{static[l]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}},en=Symbol.for("drizzle:isPgEnum");function rn(r){return!!r&&typeof r=="function"&&en in r&&r[en]===!0}var tn=class extends S{static[l]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn"),this.config.enum=t}build(e){return new Er(e,this.config)}},Er=class extends g{static[l]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}};var z=class{static[l]="Subquery";constructor(e,t,i,s=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:i,isWith:s,usedTables:n}}},qe=class extends z{static[l]="WithSubquery"};var sn="0.44.2";var Ar,Fr,A={startActiveSpan(r,e){return Ar?(Fr||(Fr=Ar.trace.getTracer("drizzle-orm",sn)),Ft((t,i)=>i.startActiveSpan(r,s=>{try{return e(s)}catch(n){throw s.setStatus({code:t.SpanStatusCode.ERROR,message:n instanceof Error?n.message:"Unknown error"}),n}finally{s.end()}}),Ar,Fr)):e()}};var F=Symbol.for("drizzle:ViewBaseConfig");var ve=Symbol.for("drizzle:Schema"),qt=Symbol.for("drizzle:Columns"),nn=Symbol.for("drizzle:ExtraConfigColumns"),qr=Symbol.for("drizzle:OriginalName"),Lr=Symbol.for("drizzle:BaseName"),We=Symbol.for("drizzle:IsAlias"),on=Symbol.for("drizzle:ExtraConfigBuilder"),Ra=Symbol.for("drizzle:IsDrizzleTable"),y=class{static[l]="Table";static Symbol={Name:oe,Schema:ve,OriginalName:qr,Columns:qt,ExtraConfigColumns:nn,BaseName:Lr,IsAlias:We,ExtraConfigBuilder:on};[oe];[qr];[ve];[qt];[nn];[Lr];[We]=!1;[Ra]=!0;[on]=void 0;constructor(e,t,i){this[oe]=this[qr]=e,this[ve]=t,this[Lr]=i}};function Z(r){return r[oe]}function Pe(r){return`${r[ve]??"public"}.${r[oe]}`}var an=class{static[l]="FakePrimitiveParam"};function Ir(r){return r!=null&&typeof r.getSQL=="function"}function ka(r){let e={sql:"",params:[]};for(let t of r)e.sql+=t.sql,e.params.push(...t.params),t.typings?.length&&(e.typings||(e.typings=[]),e.typings.push(...t.typings));return e}var k=class{static[l]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new b([this])}},b=class r{constructor(e){this.queryChunks=e;for(let t of e)if(d(t,y)){let i=t[y.Symbol.Schema];this.usedTables.push(i===void 0?t[y.Symbol.Name]:i+"."+t[y.Symbol.Name])}}static[l]="SQL";decoder=cn;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return A.startActiveSpan("drizzle.buildSQL",t=>{let i=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":i.sql,"drizzle.query.params":JSON.stringify(i.params)}),i})}buildQueryFromSourceParams(e,t){let i=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:s,escapeName:n,escapeParam:o,prepareTyping:a,inlineParams:m,paramStartIndex:f}=i;return ka(e.map(u=>{if(d(u,k))return{sql:u.value.join(""),params:[]};if(d(u,Ue))return{sql:n(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){let h=[new k("(")];for(let[p,x]of u.entries())h.push(x),p<u.length-1&&h.push(new k(", "));return h.push(new k(")")),this.buildQueryFromSourceParams(h,i)}if(d(u,r))return this.buildQueryFromSourceParams(u.queryChunks,{...i,inlineParams:m||u.shouldInlineParams});if(d(u,y)){let h=u[y.Symbol.Schema],p=u[y.Symbol.Name];return{sql:h===void 0||u[We]?n(p):n(h)+"."+n(p),params:[]}}if(d(u,E)){let h=s.getColumnCasing(u);if(t.invokeSource==="indexes")return{sql:n(h),params:[]};let p=u.table[y.Symbol.Schema];return{sql:u.table[We]||p===void 0?n(u.table[y.Symbol.Name])+"."+n(h):n(p)+"."+n(u.table[y.Symbol.Name])+"."+n(h),params:[]}}if(d(u,H)){let h=u[F].schema,p=u[F].name;return{sql:h===void 0||u[F].isAlias?n(p):n(h)+"."+n(p),params:[]}}if(d(u,X)){if(d(u.value,pe))return{sql:o(f.value++,u),params:[u],typings:["none"]};let h=u.value===null?null:u.encoder.mapToDriverValue(u.value);if(d(h,r))return this.buildQueryFromSourceParams([h],i);if(m)return{sql:this.mapInlineParam(h,i),params:[]};let p=["none"];return a&&(p=[a(u.encoder)]),{sql:o(f.value++,h),params:[h],typings:p}}return d(u,pe)?{sql:o(f.value++,u),params:[u],typings:["none"]}:d(u,r.Aliased)&&u.fieldAlias!==void 0?{sql:n(u.fieldAlias),params:[]}:d(u,z)?u._.isWith?{sql:n(u._.alias),params:[]}:this.buildQueryFromSourceParams([new k("("),u._.sql,new k(") "),new Ue(u._.alias)],i):rn(u)?u.schema?{sql:n(u.schema)+"."+n(u.enumName),params:[]}:{sql:n(u.enumName),params:[]}:Ir(u)?u.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([u.getSQL()],i):this.buildQueryFromSourceParams([new k("("),u.getSQL(),new k(")")],i):m?{sql:this.mapInlineParam(u,i),params:[]}:{sql:o(f.value++,u),params:[u],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="string")return t(e);if(typeof e=="object"){let i=e.toString();return t(i==="[object Object]"?JSON.stringify(e):i)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return e===void 0?this:new r.Aliased(this,e)}mapWith(e){return this.decoder=typeof e=="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}},Ue=class{constructor(e){this.value=e}static[l]="Name";brand;getSQL(){return new b([this])}};function ln(r){return typeof r=="object"&&r!==null&&"mapToDriverValue"in r&&typeof r.mapToDriverValue=="function"}var cn={mapFromDriverValue:r=>r},un={mapToDriverValue:r=>r},_c={...cn,...un},X=class{constructor(e,t=un){this.value=e,this.encoder=t}static[l]="Param";brand;getSQL(){return new b([this])}};function c(r,...e){let t=[];(e.length>0||r.length>0&&r[0]!=="")&&t.push(new k(r[0]));for(let[i,s]of e.entries())t.push(s,new k(r[i+1]));return new b(t)}(r=>{function e(){return new b([])}r.empty=e;function t(m){return new b(m)}r.fromList=t;function i(m){return new b([new k(m)])}r.raw=i;function s(m,f){let u=[];for(let[h,p]of m.entries())h>0&&f!==void 0&&u.push(f),u.push(p);return new b(u)}r.join=s;function n(m){return new Ue(m)}r.identifier=n;function o(m){return new pe(m)}r.placeholder=o;function a(m,f){return new X(m,f)}r.param=a})(c||(c={}));(r=>{class e{constructor(i,s){this.sql=i,this.fieldAlias=s}static[l]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new e(this.sql,this.fieldAlias)}}r.Aliased=e})(b||(b={}));var pe=class{constructor(e){this.name=e}static[l]="Placeholder";getSQL(){return new b([this])}};function jr(r,e){return r.map(t=>{if(d(t,pe)){if(!(t.name in e))throw new Error(`No value for placeholder "${t.name}" was provided`);return e[t.name]}if(d(t,X)&&d(t.value,pe)){if(!(t.value.name in e))throw new Error(`No value for placeholder "${t.value.name}" was provided`);return t.encoder.mapToDriverValue(e[t.value.name])}return t})}var Ba=Symbol.for("drizzle:IsDrizzleView"),H=class{static[l]="View";[F];[Ba]=!0;constructor({name:e,schema:t,selectedFields:i,query:s}){this[F]={name:e,originalName:e,schema:t,selectedFields:i,query:s,isExisting:!s,isAlias:!1}}getSQL(){return new b([this])}};E.prototype.getSQL=function(){return new b([this])};y.prototype.getSQL=function(){return new b([this])};z.prototype.getSQL=function(){return new b([this])};var Te=class{constructor(e){this.table=e}static[l]="ColumnAliasProxyHandler";get(e,t){return t==="table"?this.table:e[t]}},Le=class{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[l]="TableAliasProxyHandler";get(e,t){if(t===y.Symbol.IsAlias)return!0;if(t===y.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===y.Symbol.OriginalName)return this.alias;if(t===F)return{...e[F],name:this.alias,isAlias:!0};if(t===y.Symbol.Columns){let s=e[y.Symbol.Columns];if(!s)return s;let n={};return Object.keys(s).map(o=>{n[o]=new Proxy(s[o],new Te(new Proxy(e,this)))}),n}let i=e[t];return d(i,E)?new Proxy(i,new Te(new Proxy(e,this))):i}},mn=class{constructor(e){this.alias=e}static[l]="RelationTableAliasProxyHandler";get(e,t){return t==="sourceTable"?Je(e.sourceTable,this.alias):e[t]}};function Je(r,e){return new Proxy(r,new Le(e,!1))}function ce(r,e){return new Proxy(r,new Te(new Proxy(r.table,new Le(e,!1))))}function zr(r,e){return new b.Aliased(He(r.sql,e),r.fieldAlias)}function He(r,e){return c.join(r.queryChunks.map(t=>d(t,E)?ce(t,e):d(t,b)?He(t,e):d(t,b.Aliased)?zr(t,e):t))}var Ye=class extends Error{static[l]="DrizzleError";constructor({message:e,cause:t}){super(e),this.name="DrizzleError",this.cause=t}},Lt=class extends Ye{static[l]="TransactionRollbackError";constructor(){super({message:"Rollback"})}};var Or=class{static[l]="ConsoleLogWriter";write(e){console.log(e)}},It=class{static[l]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new Or}logQuery(e,t){let i=t.map(n=>{try{return JSON.stringify(n)}catch{return String(n)}}),s=i.length?` -- params: [${i.join(", ")}]`:"";this.writer.write(`Query: ${e}${s}`)}},jt=class{static[l]="NoopLogger";logQuery(){}};var M=class{static[l]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}};function fn(r,e,t){let i={},s=r.reduce((n,{path:o,field:a},m)=>{let f;d(a,E)?f=a:d(a,b)?f=a.decoder:f=a.sql.decoder;let u=n;for(let[h,p]of o.entries())if(h<o.length-1)p in u||(u[p]={}),u=u[p];else{let x=e[m],_=u[p]=x===null?null:f.mapFromDriverValue(x);if(t&&d(a,E)&&o.length===2){let $=o[0];$ in i?typeof i[$]=="string"&&i[$]!==Z(a.table)&&(i[$]=!1):i[$]=_===null?Z(a.table):!1}}return n},{});if(t&&Object.keys(i).length>0)for(let[n,o]of Object.entries(i))typeof o=="string"&&!t[o]&&(s[n]=null);return s}function ie(r,e){return Object.entries(r).reduce((t,[i,s])=>{if(typeof i!="string")return t;let n=e?[...e,i]:[i];return d(s,E)||d(s,b)||d(s,b.Aliased)?t.push({path:n,field:s}):d(s,y)?t.push(...ie(s[y.Symbol.Columns],n)):t.push(...ie(s,n)),t},[])}function Ge(r,e){let t=Object.keys(r),i=Object.keys(e);if(t.length!==i.length)return!1;for(let[s,n]of t.entries())if(n!==i[s])return!1;return!0}function zt(r,e){let t=Object.entries(e).filter(([,i])=>i!==void 0).map(([i,s])=>d(s,b)||d(s,E)?[i,s]:[i,new X(s,r[y.Symbol.Columns][i])]);if(t.length===0)throw new Error("No values to set");return Object.fromEntries(t)}function dn(r,e){for(let t of e)for(let i of Object.getOwnPropertyNames(t.prototype))i!=="constructor"&&Object.defineProperty(r.prototype,i,Object.getOwnPropertyDescriptor(t.prototype,i)||Object.create(null))}function hn(r){return r[y.Symbol.Columns]}function ge(r){return d(r,z)?r._.alias:d(r,H)?r[F].name:d(r,b)?void 0:r[y.Symbol.IsAlias]?r[y.Symbol.Name]:r[y.Symbol.BaseName]}function P(r,e){return{name:typeof r=="string"&&r.length>0?r:"",config:typeof r=="object"?r:e}}function pn(r){if(typeof r!="object"||r===null||r.constructor.name!=="Object")return!1;if("logger"in r){let e=typeof r.logger;return!(e!=="boolean"&&(e!=="object"||typeof r.logger.logQuery!="function")&&e!=="undefined")}if("schema"in r){let e=typeof r.schema;return!(e!=="object"&&e!=="undefined")}if("casing"in r){let e=typeof r.casing;return!(e!=="string"&&e!=="undefined")}if("mode"in r)return!(r.mode!=="default"||r.mode!=="planetscale"||r.mode!==void 0);if("connection"in r){let e=typeof r.connection;return!(e!=="string"&&e!=="object"&&e!=="undefined")}if("client"in r){let e=typeof r.client;return!(e!=="object"&&e!=="function"&&e!=="undefined")}return Object.keys(r).length===0}var ye=class extends S{static[l]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(e){if(e){let{name:t,...i}=e;this.config.generatedIdentity={type:"always",sequenceName:t,sequenceOptions:i}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(e){if(e){let{name:t,...i}=e;this.config.generatedIdentity={type:"byDefault",sequenceName:t,sequenceOptions:i}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}};var Qr=class extends ye{static[l]="PgBigInt53Builder";constructor(e){super(e,"number","PgBigInt53")}build(e){return new Rr(e,this.config)}},Rr=class extends g{static[l]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(e){return typeof e=="number"?e:Number(e)}},kr=class extends ye{static[l]="PgBigInt64Builder";constructor(e){super(e,"bigint","PgBigInt64")}build(e){return new Br(e,this.config)}},Br=class extends g{static[l]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(e){return BigInt(e)}};function gn(r,e){let{name:t,config:i}=P(r,e);return i.mode==="number"?new Qr(t):new kr(t)}var Kr=class extends S{static[l]="PgBigSerial53Builder";constructor(e){super(e,"number","PgBigSerial53"),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new Vr(e,this.config)}},Vr=class extends g{static[l]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(e){return typeof e=="number"?e:Number(e)}},Mr=class extends S{static[l]="PgBigSerial64Builder";constructor(e){super(e,"bigint","PgBigSerial64"),this.config.hasDefault=!0}build(e){return new Wr(e,this.config)}},Wr=class extends g{static[l]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(e){return BigInt(e)}};function yn(r,e){let{name:t,config:i}=P(r,e);return i.mode==="number"?new Kr(t):new Mr(t)}var Ur=class extends S{static[l]="PgBooleanBuilder";constructor(e){super(e,"boolean","PgBoolean")}build(e){return new Jr(e,this.config)}},Jr=class extends g{static[l]="PgBoolean";getSQLType(){return"boolean"}};function wn(r){return new Ur(r??"")}var Hr=class extends S{static[l]="PgCharBuilder";constructor(e,t){super(e,"string","PgChar"),this.config.length=t.length,this.config.enumValues=t.enum}build(e){return new Yr(e,this.config)}},Yr=class extends g{static[l]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}};function bn(r,e={}){let{name:t,config:i}=P(r,e);return new Hr(t,i)}var Gr=class extends S{static[l]="PgCidrBuilder";constructor(e){super(e,"string","PgCidr")}build(e){return new Zr(e,this.config)}},Zr=class extends g{static[l]="PgCidr";getSQLType(){return"cidr"}};function Sn(r){return new Gr(r??"")}var Xr=class extends S{static[l]="PgCustomColumnBuilder";constructor(e,t,i){super(e,"custom","PgCustomColumn"),this.config.fieldConfig=t,this.config.customTypeParams=i}build(e){return new ei(e,this.config)}},ei=class extends g{static[l]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(e,t){super(e,t),this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom=="function"?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo=="function"?this.mapTo(e):e}};function xn(r){return(e,t)=>{let{name:i,config:s}=P(e,t);return new Xr(i,s,r)}}var ue=class extends S{static[l]="PgDateColumnBaseBuilder";defaultNow(){return this.default(c`now()`)}};var ti=class extends ue{static[l]="PgDateBuilder";constructor(e){super(e,"date","PgDate")}build(e){return new Ze(e,this.config)}},Ze=class extends g{static[l]="PgDate";getSQLType(){return"date"}mapFromDriverValue(e){return new Date(e)}mapToDriverValue(e){return e.toISOString()}},ri=class extends ue{static[l]="PgDateStringBuilder";constructor(e){super(e,"string","PgDateString")}build(e){return new Xe(e,this.config)}},Xe=class extends g{static[l]="PgDateString";getSQLType(){return"date"}};function _n(r,e){let{name:t,config:i}=P(r,e);return i?.mode==="date"?new ti(t):new ri(t)}var ii=class extends S{static[l]="PgDoublePrecisionBuilder";constructor(e){super(e,"number","PgDoublePrecision")}build(e){return new si(e,this.config)}},si=class extends g{static[l]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(e){return typeof e=="string"?Number.parseFloat(e):e}};function Nn(r){return new ii(r??"")}var ni=class extends S{static[l]="PgInetBuilder";constructor(e){super(e,"string","PgInet")}build(e){return new oi(e,this.config)}},oi=class extends g{static[l]="PgInet";getSQLType(){return"inet"}};function Cn(r){return new ni(r??"")}var ai=class extends ye{static[l]="PgIntegerBuilder";constructor(e){super(e,"number","PgInteger")}build(e){return new li(e,this.config)}},li=class extends g{static[l]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(e){return typeof e=="string"?Number.parseInt(e):e}};function vn(r){return new ai(r??"")}var ci=class extends S{static[l]="PgIntervalBuilder";constructor(e,t){super(e,"string","PgInterval"),this.config.intervalConfig=t}build(e){return new ui(e,this.config)}},ui=class extends g{static[l]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){let e=this.fields?` ${this.fields}`:"",t=this.precision?`(${this.precision})`:"";return`interval${e}${t}`}};function Pn(r,e={}){let{name:t,config:i}=P(r,e);return new ci(t,i)}var mi=class extends S{static[l]="PgJsonBuilder";constructor(e){super(e,"json","PgJson")}build(e){return new et(e,this.config)}},et=class extends g{static[l]="PgJson";constructor(e,t){super(e,t)}getSQLType(){return"json"}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}};function Tn(r){return new mi(r??"")}var fi=class extends S{static[l]="PgJsonbBuilder";constructor(e){super(e,"json","PgJsonb")}build(e){return new tt(e,this.config)}},tt=class extends g{static[l]="PgJsonb";constructor(e,t){super(e,t)}getSQLType(){return"jsonb"}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}};function $n(r){return new fi(r??"")}var di=class extends S{static[l]="PgLineBuilder";constructor(e){super(e,"array","PgLine")}build(e){return new hi(e,this.config)}},hi=class extends g{static[l]="PgLine";getSQLType(){return"line"}mapFromDriverValue(e){let[t,i,s]=e.slice(1,-1).split(",");return[Number.parseFloat(t),Number.parseFloat(i),Number.parseFloat(s)]}mapToDriverValue(e){return`{${e[0]},${e[1]},${e[2]}}`}},pi=class extends S{static[l]="PgLineABCBuilder";constructor(e){super(e,"json","PgLineABC")}build(e){return new gi(e,this.config)}},gi=class extends g{static[l]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(e){let[t,i,s]=e.slice(1,-1).split(",");return{a:Number.parseFloat(t),b:Number.parseFloat(i),c:Number.parseFloat(s)}}mapToDriverValue(e){return`{${e.a},${e.b},${e.c}}`}};function Dn(r,e){let{name:t,config:i}=P(r,e);return!i?.mode||i.mode==="tuple"?new di(t):new pi(t)}var yi=class extends S{static[l]="PgMacaddrBuilder";constructor(e){super(e,"string","PgMacaddr")}build(e){return new wi(e,this.config)}},wi=class extends g{static[l]="PgMacaddr";getSQLType(){return"macaddr"}};function En(r){return new yi(r??"")}var bi=class extends S{static[l]="PgMacaddr8Builder";constructor(e){super(e,"string","PgMacaddr8")}build(e){return new Si(e,this.config)}},Si=class extends g{static[l]="PgMacaddr8";getSQLType(){return"macaddr8"}};function An(r){return new bi(r??"")}var xi=class extends S{static[l]="PgNumericBuilder";constructor(e,t,i){super(e,"string","PgNumeric"),this.config.precision=t,this.config.scale=i}build(e){return new rt(e,this.config)}},rt=class extends g{static[l]="PgNumeric";precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue(e){return typeof e=="string"?e:String(e)}getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?"numeric":`numeric(${this.precision})`}},_i=class extends S{static[l]="PgNumericNumberBuilder";constructor(e,t,i){super(e,"number","PgNumericNumber"),this.config.precision=t,this.config.scale=i}build(e){return new Ni(e,this.config)}},Ni=class extends g{static[l]="PgNumericNumber";precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue(e){return typeof e=="number"?e:Number(e)}mapToDriverValue=String;getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?"numeric":`numeric(${this.precision})`}},Ci=class extends S{static[l]="PgNumericBigIntBuilder";constructor(e,t,i){super(e,"bigint","PgNumericBigInt"),this.config.precision=t,this.config.scale=i}build(e){return new vi(e,this.config)}},vi=class extends g{static[l]="PgNumericBigInt";precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?"numeric":`numeric(${this.precision})`}};function Fn(r,e){let{name:t,config:i}=P(r,e),s=i?.mode;return s==="number"?new _i(t,i?.precision,i?.scale):s==="bigint"?new Ci(t,i?.precision,i?.scale):new xi(t,i?.precision,i?.scale)}var Pi=class extends S{static[l]="PgPointTupleBuilder";constructor(e){super(e,"array","PgPointTuple")}build(e){return new Ti(e,this.config)}},Ti=class extends g{static[l]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(e){if(typeof e=="string"){let[t,i]=e.slice(1,-1).split(",");return[Number.parseFloat(t),Number.parseFloat(i)]}return[e.x,e.y]}mapToDriverValue(e){return`(${e[0]},${e[1]})`}},$i=class extends S{static[l]="PgPointObjectBuilder";constructor(e){super(e,"json","PgPointObject")}build(e){return new Di(e,this.config)}},Di=class extends g{static[l]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(e){if(typeof e=="string"){let[t,i]=e.slice(1,-1).split(",");return{x:Number.parseFloat(t),y:Number.parseFloat(i)}}return e}mapToDriverValue(e){return`(${e.x},${e.y})`}};function qn(r,e){let{name:t,config:i}=P(r,e);return!i?.mode||i.mode==="tuple"?new Pi(t):new $i(t)}function Ka(r){let e=[];for(let t=0;t<r.length;t+=2)e.push(Number.parseInt(r.slice(t,t+2),16));return new Uint8Array(e)}function Ln(r,e){let t=new ArrayBuffer(8),i=new DataView(t);for(let s=0;s<8;s++)i.setUint8(s,r[e+s]);return i.getFloat64(0,!0)}function Ei(r){let e=Ka(r),t=0,i=e[t];t+=1;let s=new DataView(e.buffer),n=s.getUint32(t,i===1);t+=4;let o;if(n&536870912&&(o=s.getUint32(t,i===1),t+=4),(n&65535)===1){let a=Ln(e,t);t+=8;let m=Ln(e,t);return t+=8,[a,m]}throw new Error("Unsupported geometry type")}var Ai=class extends S{static[l]="PgGeometryBuilder";constructor(e){super(e,"array","PgGeometry")}build(e){return new Fi(e,this.config)}},Fi=class extends g{static[l]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(e){return Ei(e)}mapToDriverValue(e){return`point(${e[0]} ${e[1]})`}},qi=class extends S{static[l]="PgGeometryObjectBuilder";constructor(e){super(e,"json","PgGeometryObject")}build(e){return new Li(e,this.config)}},Li=class extends g{static[l]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(e){let t=Ei(e);return{x:t[0],y:t[1]}}mapToDriverValue(e){return`point(${e.x} ${e.y})`}};function In(r,e){let{name:t,config:i}=P(r,e);return!i?.mode||i.mode==="tuple"?new Ai(t):new qi(t)}var Ii=class extends S{static[l]="PgRealBuilder";constructor(e,t){super(e,"number","PgReal"),this.config.length=t}build(e){return new ji(e,this.config)}},ji=class extends g{static[l]="PgReal";constructor(e,t){super(e,t)}getSQLType(){return"real"}mapFromDriverValue=e=>typeof e=="string"?Number.parseFloat(e):e};function jn(r){return new Ii(r??"")}var zi=class extends S{static[l]="PgSerialBuilder";constructor(e){super(e,"number","PgSerial"),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new Oi(e,this.config)}},Oi=class extends g{static[l]="PgSerial";getSQLType(){return"serial"}};function zn(r){return new zi(r??"")}var Qi=class extends ye{static[l]="PgSmallIntBuilder";constructor(e){super(e,"number","PgSmallInt")}build(e){return new Ri(e,this.config)}},Ri=class extends g{static[l]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=e=>typeof e=="string"?Number(e):e};function On(r){return new Qi(r??"")}var ki=class extends S{static[l]="PgSmallSerialBuilder";constructor(e){super(e,"number","PgSmallSerial"),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new Bi(e,this.config)}},Bi=class extends g{static[l]="PgSmallSerial";getSQLType(){return"smallserial"}};function Qn(r){return new ki(r??"")}var Ki=class extends S{static[l]="PgTextBuilder";constructor(e,t){super(e,"string","PgText"),this.config.enumValues=t.enum}build(e){return new Vi(e,this.config)}},Vi=class extends g{static[l]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}};function Rn(r,e={}){let{name:t,config:i}=P(r,e);return new Ki(t,i)}var Mi=class extends ue{constructor(e,t,i){super(e,"string","PgTime"),this.withTimezone=t,this.precision=i,this.config.withTimezone=t,this.config.precision=i}static[l]="PgTimeBuilder";build(e){return new it(e,this.config)}},it=class extends g{static[l]="PgTime";withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}};function kn(r,e={}){let{name:t,config:i}=P(r,e);return new Mi(t,i.withTimezone??!1,i.precision)}var Wi=class extends ue{static[l]="PgTimestampBuilder";constructor(e,t,i){super(e,"date","PgTimestamp"),this.config.withTimezone=t,this.config.precision=i}build(e){return new st(e,this.config)}},st=class extends g{static[l]="PgTimestamp";withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=e=>new Date(this.withTimezone?e:e+"+0000");mapToDriverValue=e=>e.toISOString()},Ui=class extends ue{static[l]="PgTimestampStringBuilder";constructor(e,t,i){super(e,"string","PgTimestampString"),this.config.withTimezone=t,this.config.precision=i}build(e){return new nt(e,this.config)}},nt=class extends g{static[l]="PgTimestampString";withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}};function Bn(r,e={}){let{name:t,config:i}=P(r,e);return i?.mode==="string"?new Ui(t,i.withTimezone??!1,i.precision):new Wi(t,i?.withTimezone??!1,i?.precision)}var Ji=class extends S{static[l]="PgUUIDBuilder";constructor(e){super(e,"string","PgUUID")}defaultRandom(){return this.default(c`gen_random_uuid()`)}build(e){return new ot(e,this.config)}},ot=class extends g{static[l]="PgUUID";getSQLType(){return"uuid"}};function Kn(r){return new Ji(r??"")}var Hi=class extends S{static[l]="PgVarcharBuilder";constructor(e,t){super(e,"string","PgVarchar"),this.config.length=t.length,this.config.enumValues=t.enum}build(e){return new Yi(e,this.config)}},Yi=class extends g{static[l]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}};function Vn(r,e={}){let{name:t,config:i}=P(r,e);return new Hi(t,i)}var Gi=class extends S{static[l]="PgBinaryVectorBuilder";constructor(e,t){super(e,"string","PgBinaryVector"),this.config.dimensions=t.dimensions}build(e){return new Zi(e,this.config)}},Zi=class extends g{static[l]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}};function Mn(r,e){let{name:t,config:i}=P(r,e);return new Gi(t,i)}var Xi=class extends S{static[l]="PgHalfVectorBuilder";constructor(e,t){super(e,"array","PgHalfVector"),this.config.dimensions=t.dimensions}build(e){return new es(e,this.config)}},es=class extends g{static[l]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){return e.slice(1,-1).split(",").map(t=>Number.parseFloat(t))}};function Wn(r,e){let{name:t,config:i}=P(r,e);return new Xi(t,i)}var ts=class extends S{static[l]="PgSparseVectorBuilder";constructor(e,t){super(e,"string","PgSparseVector"),this.config.dimensions=t.dimensions}build(e){return new rs(e,this.config)}},rs=class extends g{static[l]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}};function Un(r,e){let{name:t,config:i}=P(r,e);return new ts(t,i)}var is=class extends S{static[l]="PgVectorBuilder";constructor(e,t){super(e,"array","PgVector"),this.config.dimensions=t.dimensions}build(e){return new ss(e,this.config)}},ss=class extends g{static[l]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){return e.slice(1,-1).split(",").map(t=>Number.parseFloat(t))}};function Jn(r,e){let{name:t,config:i}=P(r,e);return new is(t,i)}function Hn(){return{bigint:gn,bigserial:yn,boolean:wn,char:bn,cidr:Sn,customType:xn,date:_n,doublePrecision:Nn,inet:Cn,integer:vn,interval:Pn,json:Tn,jsonb:$n,line:Dn,macaddr:En,macaddr8:An,numeric:Fn,point:qn,geometry:In,real:jn,serial:zn,smallint:On,smallserial:Qn,text:Rn,time:kn,timestamp:Bn,uuid:Kn,varchar:Vn,bit:Mn,halfvec:Wn,sparsevec:Un,vector:Jn}}var ns=Symbol.for("drizzle:PgInlineForeignKeys"),Yn=Symbol.for("drizzle:EnableRLS"),B=class extends y{static[l]="PgTable";static Symbol=Object.assign({},y.Symbol,{InlineForeignKeys:ns,EnableRLS:Yn});[ns]=[];[Yn]=!1;[y.Symbol.ExtraConfigBuilder]=void 0;[y.Symbol.ExtraConfigColumns]={}};function Va(r,e,t,i,s=r){let n=new B(r,i,s),o=typeof e=="function"?e(Hn()):e,a=Object.fromEntries(Object.entries(o).map(([u,h])=>{let p=h;p.setName(u);let x=p.build(n);return n[ns].push(...p.buildForeignKeys(x,n)),[u,x]})),m=Object.fromEntries(Object.entries(o).map(([u,h])=>{let p=h;p.setName(u);let x=p.buildExtraConfigColumn(n);return[u,x]})),f=Object.assign(n,a);return f[y.Symbol.Columns]=a,f[y.Symbol.ExtraConfigColumns]=m,t&&(f[B.Symbol.ExtraConfigBuilder]=t),Object.assign(f,{enableRLS:()=>(f[B.Symbol.EnableRLS]=!0,f)})}var V=(r,e,t)=>Va(r,e,t,void 0);var Ot=class{static[l]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new os(e,this.columns,this.name)}},os=class{constructor(e,t,i){this.table=e,this.columns=t,this.name=i}static[l]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[B.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}};function ee(r,e){return ln(e)&&!Ir(r)&&!d(r,X)&&!d(r,pe)&&!d(r,E)&&!d(r,y)&&!d(r,H)?new X(r,e):r}var Qt=(r,e)=>c`${r} = ${ee(e,r)}`,Gn=(r,e)=>c`${r} <> ${ee(e,r)}`;function at(...r){let e=r.filter(t=>t!==void 0);if(e.length!==0)return e.length===1?new b(e):new b([new k("("),c.join(e,new k(" and ")),new k(")")])}function Zn(...r){let e=r.filter(t=>t!==void 0);if(e.length!==0)return e.length===1?new b(e):new b([new k("("),c.join(e,new k(" or ")),new k(")")])}function Xn(r){return c`not ${r}`}var eo=(r,e)=>c`${r} > ${ee(e,r)}`,to=(r,e)=>c`${r} >= ${ee(e,r)}`,ro=(r,e)=>c`${r} < ${ee(e,r)}`,io=(r,e)=>c`${r} <= ${ee(e,r)}`;function so(r,e){return Array.isArray(e)?e.length===0?c`false`:c`${r} in ${e.map(t=>ee(t,r))}`:c`${r} in ${ee(e,r)}`}function no(r,e){return Array.isArray(e)?e.length===0?c`true`:c`${r} not in ${e.map(t=>ee(t,r))}`:c`${r} not in ${ee(e,r)}`}function oo(r){return c`${r} is null`}function ao(r){return c`${r} is not null`}function lo(r){return c`exists ${r}`}function co(r){return c`not exists ${r}`}function uo(r,e,t){return c`${r} between ${ee(e,r)} and ${ee(t,r)}`}function mo(r,e,t){return c`${r} not between ${ee(e,r)} and ${ee(t,r)}`}function fo(r,e){return c`${r} like ${e}`}function ho(r,e){return c`${r} not like ${e}`}function po(r,e){return c`${r} ilike ${e}`}function go(r,e){return c`${r} not ilike ${e}`}function yo(r){return c`${r} asc`}function wo(r){return c`${r} desc`}var Rt=class{constructor(e,t,i){this.sourceTable=e,this.referencedTable=t,this.relationName=i,this.referencedTableName=t[y.Symbol.Name]}static[l]="Relation";referencedTableName;fieldName},kt=class{constructor(e,t){this.table=e,this.config=t}static[l]="Relations"},xe=class r extends Rt{constructor(e,t,i,s){super(e,t,i?.relationName),this.config=i,this.isNullable=s}static[l]="One";withFieldName(e){let t=new r(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}},lt=class r extends Rt{constructor(e,t,i){super(e,t,i?.relationName),this.config=i}static[l]="Many";withFieldName(e){let t=new r(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}};function bo(){return{and:at,between:uo,eq:Qt,exists:lo,gt:eo,gte:to,ilike:po,inArray:so,isNull:oo,isNotNull:ao,like:fo,lt:ro,lte:io,ne:Gn,not:Xn,notBetween:mo,notExists:co,notLike:ho,notIlike:go,notInArray:no,or:Zn,sql:c}}function So(){return{sql:c,asc:yo,desc:wo}}function xo(r,e){Object.keys(r).length===1&&"default"in r&&!d(r.default,y)&&(r=r.default);let t={},i={},s={};for(let[n,o]of Object.entries(r))if(d(o,y)){let a=Pe(o),m=i[a];t[a]=n,s[n]={tsName:n,dbName:o[y.Symbol.Name],schema:o[y.Symbol.Schema],columns:o[y.Symbol.Columns],relations:m?.relations??{},primaryKey:m?.primaryKey??[]};for(let u of Object.values(o[y.Symbol.Columns]))u.primary&&s[n].primaryKey.push(u);let f=o[y.Symbol.ExtraConfigBuilder]?.(o[y.Symbol.ExtraConfigColumns]);if(f)for(let u of Object.values(f))d(u,Ot)&&s[n].primaryKey.push(...u.columns)}else if(d(o,kt)){let a=Pe(o.table),m=t[a],f=o.config(e(o.table)),u;for(let[h,p]of Object.entries(f))if(m){let x=s[m];x.relations[h]=p,u&&x.primaryKey.push(...u)}else a in i||(i[a]={relations:{},primaryKey:u}),i[a].relations[h]=p}return{tables:s,tableNamesMap:t}}function Y(r,e){return new kt(r,t=>Object.fromEntries(Object.entries(e(t)).map(([i,s])=>[i,s.withFieldName(i)])))}function Ma(r){return function(t,i){return new xe(r,t,i,i?.fields.reduce((s,n)=>s&&n.notNull,!0)??!1)}}function Wa(r){return function(t,i){return new lt(r,t,i)}}function _o(r,e,t){if(d(t,xe)&&t.config)return{fields:t.config.fields,references:t.config.references};let i=e[Pe(t.referencedTable)];if(!i)throw new Error(`Table "${t.referencedTable[y.Symbol.Name]}" not found in schema`);let s=r[i];if(!s)throw new Error(`Table "${i}" not found in schema`);let n=t.sourceTable,o=e[Pe(n)];if(!o)throw new Error(`Table "${n[y.Symbol.Name]}" not found in schema`);let a=[];for(let m of Object.values(s.relations))(t.relationName&&t!==m&&m.relationName===t.relationName||!t.relationName&&m.referencedTable===t.sourceTable)&&a.push(m);if(a.length>1)throw t.relationName?new Error(`There are multiple relations with name "${t.relationName}" in table "${i}"`):new Error(`There are multiple relations between "${i}" and "${t.sourceTable[y.Symbol.Name]}". Please specify relation name`);if(a[0]&&d(a[0],xe)&&a[0].config)return{fields:a[0].config.references,references:a[0].config.fields};throw new Error(`There is not enough information to infer relation "${o}.${t.fieldName}"`)}function No(r){return{one:Ma(r),many:Wa(r)}}function Bt(r,e,t,i,s=n=>n){let n={};for(let[o,a]of i.entries())if(a.isJson){let m=e.relations[a.tsKey],f=t[o],u=typeof f=="string"?JSON.parse(f):f;n[a.tsKey]=d(m,xe)?u&&Bt(r,r[a.relationTableTsKey],u,a.selection,s):u.map(h=>Bt(r,r[a.relationTableTsKey],h,a.selection,s))}else{let m=s(t[o]),f=a.field,u;d(f,E)?u=f:d(f,b)?u=f.decoder:u=f.sql.decoder,n[a.tsKey]=m===null?null:u.mapFromDriverValue(m)}return n}function as(r){return c`count(${r||c.raw("*")})`.mapWith(Number)}import gs from"postgres";var O=class r{static[l]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===F)return{...e[F],selectedFields:new Proxy(e[F].selectedFields,this)};if(typeof t=="symbol")return e[t];let s=(d(e,z)?e._.selectedFields:d(e,H)?e[F].selectedFields:e)[t];if(d(s,b.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!s.isSelectionField)return s.sql;let n=s.clone();return n.isSelectionField=!0,n}if(d(s,b)){if(this.config.sqlBehavior==="sql")return s;throw new Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return d(s,E)?this.config.alias?new Proxy(s,new Te(new Proxy(s.table,new Le(this.config.alias,this.config.replaceOriginalName??!1)))):s:typeof s!="object"||s===null?s:new Proxy(s,new r(this.config))}};var ls=class{constructor(e,t){this.unique=e,this.name=t}static[l]="PgIndexBuilderOn";on(...e){return new ct(e.map(t=>{if(d(t,b))return t;t=t;let i=new Fe(t.name,!!t.keyAsName,t.columnType,t.indexConfig);return t.indexConfig=JSON.parse(JSON.stringify(t.defaultConfig)),i}),this.unique,!1,this.name)}onOnly(...e){return new ct(e.map(t=>{if(d(t,b))return t;t=t;let i=new Fe(t.name,!!t.keyAsName,t.columnType,t.indexConfig);return t.indexConfig=t.defaultConfig,i}),this.unique,!0,this.name)}using(e,...t){return new ct(t.map(i=>{if(d(i,b))return i;i=i;let s=new Fe(i.name,!!i.keyAsName,i.columnType,i.indexConfig);return i.indexConfig=JSON.parse(JSON.stringify(i.defaultConfig)),s}),this.unique,!0,this.name,e)}},ct=class{static[l]="PgIndexBuilder";config;constructor(e,t,i,s,n="btree"){this.config={name:s,columns:e,unique:t,only:i,method:n}}concurrently(){return this.config.concurrently=!0,this}with(e){return this.config.with=e,this}where(e){return this.config.where=e,this}build(e){return new cs(this.config,e)}},cs=class{static[l]="PgIndex";config;constructor(e,t){this.config={...e,table:t}}};function K(r){return new ls(!1,r)}function Ua(r){return(r.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(t=>t.toLowerCase()).join("_")}function Ja(r){return(r.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((t,i,s)=>{let n=s===0?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`;return t+n},"")}function Ha(r){return r}var Kt=class{static[l]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Ua:e==="camelCase"?Ja:Ha}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[y.Symbol.Schema]??"public",i=e.table[y.Symbol.OriginalName],s=`${t}.${i}.${e.name}`;return this.cache[s]||this.cacheTable(e.table),this.cache[s]}cacheTable(e){let t=e[y.Symbol.Schema]??"public",i=e[y.Symbol.OriginalName],s=`${t}.${i}`;if(!this.cachedTables[s]){for(let n of Object.values(e[y.Symbol.Columns])){let o=`${s}.${n.name}`;this.cache[o]=this.convert(n.name)}this.cachedTables[s]=!0}}clearCache(){this.cache={},this.cachedTables={}}};var Ie=class extends H{static[l]="PgViewBase"};var _e=class{static[l]="PgDialect";casing;constructor(e){this.casing=new Kt(e?.casing)}async migrate(e,t,i){let s=typeof i=="string"?"__drizzle_migrations":i.migrationsTable??"__drizzle_migrations",n=typeof i=="string"?"drizzle":i.migrationsSchema??"drizzle",o=c`
7
+ CREATE TABLE IF NOT EXISTS ${c.identifier(n)}.${c.identifier(s)} (
10
8
  id SERIAL PRIMARY KEY,
11
9
  hash text NOT NULL,
12
10
  created_at bigint
13
11
  )
14
- `;await t.execute(f`CREATE SCHEMA IF NOT EXISTS ${f.identifier(n)}`),await t.execute(o);let u=(await t.all(f`select id, hash, created_at from ${f.identifier(n)}.${f.identifier(s)} order by created_at desc limit 1`))[0];await t.transaction(async m=>{for await(let c of e)if(!u||Number(u.created_at)<c.folderMillis){for(let h of c.sql)await m.execute(f.raw(h));await m.execute(f`insert into ${f.identifier(n)}.${f.identifier(s)} ("hash", "created_at") values(${c.hash}, ${c.folderMillis})`)}})}escapeName(e){return`"${e}"`}escapeParam(e){return`$${e+1}`}escapeString(e){return`'${e.replace(/'/g,"''")}'`}buildWithCTE(e){if(!e?.length)return;let t=[f`with `];for(let[i,s]of e.entries())t.push(f`${f.identifier(s._.alias)} as (${s._.sql})`),i<e.length-1&&t.push(f`, `);return t.push(f` `),f.join(t)}buildDeleteQuery({table:e,where:t,returning:i,withList:s}){let n=this.buildWithCTE(s),o=i?f` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,a=t?f` where ${t}`:void 0;return f`${n}delete from ${e}${a}${o}`}buildUpdateSet(e,t){let i=e[y.Symbol.Columns],s=Object.keys(i).filter(o=>t[o]!==void 0||i[o]?.onUpdateFn!==void 0),n=s.length;return f.join(s.flatMap((o,a)=>{let u=i[o],m=t[o]??f.param(u.onUpdateFn(),u),c=f`${f.identifier(this.casing.getColumnCasing(u))} = ${m}`;return a<n-1?[c,f.raw(", ")]:[c]}))}buildUpdateQuery({table:e,set:t,where:i,returning:s,withList:n,from:o,joins:a}){let u=this.buildWithCTE(n),m=e[V.Symbol.Name],c=e[V.Symbol.Schema],h=e[V.Symbol.OriginalName],p=m===h?void 0:m,S=f`${c?f`${f.identifier(c)}.`:void 0}${f.identifier(h)}${p&&f` ${f.identifier(p)}`}`,x=this.buildUpdateSet(e,t),$=o&&f.join([f.raw(" from "),this.buildFromTable(o)]),L=this.buildJoins(a),w=s?f` returning ${this.buildSelection(s,{isSingleTable:!o})}`:void 0,v=i?f` where ${i}`:void 0;return f`${u}update ${S} set ${x}${$}${L}${v}${w}`}buildSelection(e,{isSingleTable:t=!1}={}){let i=e.length,s=e.flatMap(({field:n},o)=>{let a=[];if(d(n,b.Aliased)&&n.isSelectionField)a.push(f.identifier(n.fieldAlias));else if(d(n,b.Aliased)||d(n,b)){let u=d(n,b.Aliased)?n.sql:n;t?a.push(new b(u.queryChunks.map(m=>d(m,g)?f.identifier(this.casing.getColumnCasing(m)):m))):a.push(u),d(n,b.Aliased)&&a.push(f` as ${f.identifier(n.fieldAlias)}`)}else d(n,D)&&(t?a.push(f.identifier(this.casing.getColumnCasing(n))):a.push(n));return o<i-1&&a.push(f`, `),a});return f.join(s)}buildJoins(e){if(!e||e.length===0)return;let t=[];for(let[i,s]of e.entries()){i===0&&t.push(f` `);let n=s.table,o=s.lateral?f` lateral`:void 0,a=s.on?f` on ${s.on}`:void 0;if(d(n,V)){let u=n[V.Symbol.Name],m=n[V.Symbol.Schema],c=n[V.Symbol.OriginalName],h=u===c?void 0:s.alias;t.push(f`${f.raw(s.joinType)} join${o} ${m?f`${f.identifier(m)}.`:void 0}${f.identifier(c)}${h&&f` ${f.identifier(h)}`}${a}`)}else if(d(n,H)){let u=n[I].name,m=n[I].schema,c=n[I].originalName,h=u===c?void 0:s.alias;t.push(f`${f.raw(s.joinType)} join${o} ${m?f`${f.identifier(m)}.`:void 0}${f.identifier(c)}${h&&f` ${f.identifier(h)}`}${a}`)}else t.push(f`${f.raw(s.joinType)} join${o} ${n}${a}`);i<e.length-1&&t.push(f` `)}return f.join(t)}buildFromTable(e){if(d(e,y)&&e[y.Symbol.IsAlias]){let t=f`${f.identifier(e[y.Symbol.OriginalName])}`;return e[y.Symbol.Schema]&&(t=f`${f.identifier(e[y.Symbol.Schema])}.${t}`),f`${t} ${f.identifier(e[y.Symbol.Name])}`}return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:i,where:s,having:n,table:o,joins:a,orderBy:u,groupBy:m,limit:c,offset:h,lockingClause:p,distinct:S,setOperators:x}){let $=i??se(t);for(let re of $)if(d(re.field,D)&&X(re.field.table)!==(d(o,j)?o._.alias:d(o,je)?o[I].name:d(o,b)?void 0:X(o))&&!(pe=>a?.some(({alias:ur})=>ur===(pe[y.Symbol.IsAlias]?X(pe):pe[y.Symbol.BaseName])))(re.field.table)){let pe=X(re.field.table);throw new Error(`Your "${re.path.join("->")}" field references a column "${pe}"."${re.field.name}", but the table "${pe}" is not part of the query! Did you forget to join it?`)}let L=!a||a.length===0,w=this.buildWithCTE(e),v;S&&(v=S===!0?f` distinct`:f` distinct on (${f.join(S.on,f`, `)})`);let Q=this.buildSelection($,{isSingleTable:L}),O=this.buildFromTable(o),Y=this.buildJoins(a),R=s?f` where ${s}`:void 0,N=n?f` having ${n}`:void 0,P;u&&u.length>0&&(P=f` order by ${f.join(u,f`, `)}`);let Z;m&&m.length>0&&(Z=f` group by ${f.join(m,f`, `)}`);let _t=typeof c=="object"||typeof c=="number"&&c>=0?f` limit ${c}`:void 0,cr=h?f` offset ${h}`:void 0,Ae=f.empty();if(p){let re=f` for ${f.raw(p.strength)}`;p.config.of&&re.append(f` of ${f.join(Array.isArray(p.config.of)?p.config.of:[p.config.of],f`, `)}`),p.config.noWait?re.append(f` nowait`):p.config.skipLocked&&re.append(f` skip locked`),Ae.append(re)}let xe=f`${w}select${v} ${Q} from ${O}${Y}${R}${Z}${N}${P}${_t}${cr}${Ae}`;return x.length>0?this.buildSetOperations(xe,x):xe}buildSetOperations(e,t){let[i,...s]=t;if(!i)throw new Error("Cannot pass undefined values to any set operator");return s.length===0?this.buildSetOperationQuery({leftSelect:e,setOperator:i}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:i}),s)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:i,rightSelect:s,limit:n,orderBy:o,offset:a}}){let u=f`(${e.getSQL()}) `,m=f`(${s.getSQL()})`,c;if(o&&o.length>0){let x=[];for(let $ of o)if(d($,g))x.push(f.identifier($.name));else if(d($,b)){for(let L=0;L<$.queryChunks.length;L++){let w=$.queryChunks[L];d(w,g)&&($.queryChunks[L]=f.identifier(w.name))}x.push(f`${$}`)}else x.push(f`${$}`);c=f` order by ${f.join(x,f`, `)} `}let h=typeof n=="object"||typeof n=="number"&&n>=0?f` limit ${n}`:void 0,p=f.raw(`${t} ${i?"all ":""}`),S=a?f` offset ${a}`:void 0;return f`${u}${p}${m}${c}${h}${S}`}buildInsertQuery({table:e,values:t,onConflict:i,returning:s,withList:n,select:o,overridingSystemValue_:a}){let u=[],m=e[y.Symbol.Columns],c=Object.entries(m).filter(([w,v])=>!v.shouldDisableInsert()),h=c.map(([,w])=>f.identifier(this.casing.getColumnCasing(w)));if(o){let w=t;d(w,b)?u.push(w):u.push(w.getSQL())}else{let w=t;u.push(f.raw("values "));for(let[v,Q]of w.entries()){let O=[];for(let[Y,R]of c){let N=Q[Y];if(N===void 0||d(N,ee)&&N.value===void 0)if(R.defaultFn!==void 0){let P=R.defaultFn(),Z=d(P,b)?P:f.param(P,R);O.push(Z)}else if(!R.default&&R.onUpdateFn!==void 0){let P=R.onUpdateFn(),Z=d(P,b)?P:f.param(P,R);O.push(Z)}else O.push(f`default`);else O.push(N)}u.push(O),v<w.length-1&&u.push(f`, `)}}let p=this.buildWithCTE(n),S=f.join(u),x=s?f` returning ${this.buildSelection(s,{isSingleTable:!0})}`:void 0,$=i?f` on conflict ${i}`:void 0,L=a===!0?f`overriding system value `:void 0;return f`${p}insert into ${e} ${h} ${L}${S}${$}${x}`}buildRefreshMaterializedViewQuery({view:e,concurrently:t,withNoData:i}){let s=t?f` concurrently`:void 0,n=i?f` with no data`:void 0;return f`refresh materialized view${s} ${e}${n}`}prepareTyping(e){return d(e,st)||d(e,it)?"json":d(e,nt)?"decimal":d(e,ot)?"time":d(e,at)||d(e,lt)?"timestamp":d(e,tt)||d(e,rt)?"date":d(e,ct)?"uuid":"none"}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:t})}buildRelationalQueryWithoutPK({fullSchema:e,schema:t,tableNamesMap:i,table:s,tableConfig:n,queryConfig:o,tableAlias:a,nestedQueryRelation:u,joinOn:m}){let c=[],h,p,S=[],x,$=[];if(o===!0)c=Object.entries(n.columns).map(([v,Q])=>({dbKey:Q.name,tsKey:v,field:fe(Q,a),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let w=Object.fromEntries(Object.entries(n.columns).map(([N,P])=>[N,fe(P,a)]));if(o.where){let N=typeof o.where=="function"?o.where(w,Lo()):o.where;x=N&&Ze(N,a)}let v=[],Q=[];if(o.columns){let N=!1;for(let[P,Z]of Object.entries(o.columns))Z!==void 0&&P in n.columns&&(!N&&Z===!0&&(N=!0),Q.push(P));Q.length>0&&(Q=N?Q.filter(P=>o.columns?.[P]===!0):Object.keys(n.columns).filter(P=>!Q.includes(P)))}else Q=Object.keys(n.columns);for(let N of Q){let P=n.columns[N];v.push({tsKey:N,value:P})}let O=[];o.with&&(O=Object.entries(o.with).filter(N=>!!N[1]).map(([N,P])=>({tsKey:N,queryConfig:P,relation:n.relations[N]})));let Y;if(o.extras){Y=typeof o.extras=="function"?o.extras(w,{sql:f}):o.extras;for(let[N,P]of Object.entries(Y))v.push({tsKey:N,value:Kr(P,a)})}for(let{tsKey:N,value:P}of v)c.push({dbKey:d(P,b.Aliased)?P.fieldAlias:n.columns[N].name,tsKey:N,field:d(P,D)?fe(P,a):P,relationTableTsKey:void 0,isJson:!1,selection:[]});let R=typeof o.orderBy=="function"?o.orderBy(w,Fo()):o.orderBy??[];Array.isArray(R)||(R=[R]),S=R.map(N=>d(N,D)?fe(N,a):Ze(N,a)),h=o.limit,p=o.offset;for(let{tsKey:N,queryConfig:P,relation:Z}of O){let _t=qo(t,i,Z),cr=$e(Z.referencedTable),Ae=i[cr],xe=`${a}_${N}`,re=ut(..._t.fields.map((Wo,Uo)=>Vt(fe(_t.references[Uo],xe),fe(Wo,a)))),pe=this.buildRelationalQueryWithoutPK({fullSchema:e,schema:t,tableNamesMap:i,table:e[Ae],tableConfig:t[Ae],queryConfig:d(Z,ve)?P===!0?{limit:1}:{...P,limit:1}:P,tableAlias:xe,joinOn:re,nestedQueryRelation:Z}),ur=f`${f.identifier(xe)}.${f.identifier("data")}`.as(N);$.push({on:f`true`,table:new j(pe.sql,{},xe),alias:xe,joinType:"left",lateral:!0}),c.push({dbKey:N,tsKey:N,field:ur,relationTableTsKey:Ae,isJson:!0,selection:pe.selection})}}if(c.length===0)throw new Xe({message:`No fields selected for table "${n.tsName}" ("${a}")`});let L;if(x=ut(m,x),u){let w=f`json_build_array(${f.join(c.map(({field:O,tsKey:Y,isJson:R})=>R?f`${f.identifier(`${a}_${Y}`)}.${f.identifier("data")}`:d(O,b.Aliased)?O.sql:O),f`, `)})`;d(u,ft)&&(w=f`coalesce(json_agg(${w}${S.length>0?f` order by ${f.join(S,f`, `)}`:void 0}), '[]'::json)`);let v=[{dbKey:"data",tsKey:"data",field:w.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:c}];h!==void 0||p!==void 0||S.length>0?(L=this.buildSelectQuery({table:Ge(s,a),fields:{},fieldsFlat:[{path:[],field:f.raw("*")}],where:x,limit:h,offset:p,orderBy:S,setOperators:[]}),x=void 0,h=void 0,p=void 0,S=[]):L=Ge(s,a),L=this.buildSelectQuery({table:d(L,V)?L:new j(L,{},a),fields:{},fieldsFlat:v.map(({field:O})=>({path:[],field:d(O,D)?fe(O,a):O})),joins:$,where:x,limit:h,offset:p,orderBy:S,setOperators:[]})}else L=this.buildSelectQuery({table:Ge(s,a),fields:{},fieldsFlat:c.map(({field:w})=>({path:[],field:d(w,D)?fe(w,a):w})),joins:$,where:x,limit:h,offset:p,orderBy:S,setOperators:[]});return{tableTsKey:n.tsName,sql:L,selection:c}}};var Ut=class{static[l]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}};var U=class{static[l]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,e.withList&&(this.withList=e.withList),this.distinct=e.distinct}authToken;setToken(e){return this.authToken=e,this}from(e){let t=!!this.fields,i=e,s;return this.fields?s=this.fields:d(i,j)?s=Object.fromEntries(Object.keys(i._.selectedFields).map(n=>[n,i[n]])):d(i,je)?s=i[I].selectedFields:d(i,b)?s={}:s=$n(i),new Jt({table:i,fields:s,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}},gs=class extends Ut{static[l]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:i,session:s,dialect:n,withList:o,distinct:a}){super(),this.config={withList:o,table:e,fields:{...t},distinct:a,setOperators:[]},this.isPartialSelect=i,this.session=s,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=we(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{};for(let u of ce(e))this.usedTables.add(u)}getUsedTables(){return[...this.usedTables]}createJoin(e,t){return(i,s)=>{let n=this.tableName,o=we(i);for(let a of ce(i))this.usedTables.add(a);if(typeof o=="string"&&this.config.joins?.some(a=>a.alias===o))throw new Error(`Alias "${o}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof n=="string"&&(this.config.fields={[n]:this.config.fields}),typeof o=="string"&&!d(i,b))){let a=d(i,j)?i._.selectedFields:d(i,H)?i[I].selectedFields:i[y.Symbol.Columns];this.config.fields[o]=a}if(typeof s=="function"&&(s=s(new Proxy(this.config.fields,new z({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:s,table:i,joinType:e,alias:o,lateral:t}),typeof o=="string")switch(e){case"left":{this.joinsNotNullableMap[o]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[o]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[o]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[o]=!1;break}}return this}}leftJoin=this.createJoin("left",!1);leftJoinLateral=this.createJoin("left",!0);rightJoin=this.createJoin("right",!1);innerJoin=this.createJoin("inner",!1);innerJoinLateral=this.createJoin("inner",!0);fullJoin=this.createJoin("full",!1);crossJoin=this.createJoin("cross",!1);crossJoinLateral=this.createJoin("cross",!0);createSetOperator(e,t){return i=>{let s=typeof i=="function"?i(Al()):i;if(!et(this.getSelectedFields(),s.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:t,rightSelect:s}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new z({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new z({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){let t=e[0](new Proxy(this.config.fields,new z({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){let t=e[0](new Proxy(this.config.fields,new z({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),i=Array.isArray(t)?t:[t];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=i:this.config.orderBy=i}else{let t=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=t:this.config.orderBy=t}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}for(e,t={}){return this.config.lockingClause={strength:e,config:t},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...ce(this.config.table)),this.config.joins)for(let i of this.config.joins)t.push(...ce(i.table));return new Proxy(new j(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new z({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new z({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}},Jt=class extends gs{static[l]="PgSelect";_prepare(e){let{session:t,config:i,dialect:s,joinsNotNullableMap:n,authToken:o,cacheConfig:a,usedTables:u}=this;if(!t)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");let{fields:m}=i;return A.startActiveSpan("drizzle.prepareQuery",()=>{let c=se(m),h=t.prepareQuery(s.sqlToQuery(this.getSQL()),c,e,!0,void 0,{type:"select",tables:[...u]},a);return h.joinsNotNullableMap=n,h.setToken(o)})}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>A.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken))};Pn(Jt,[W]);function ze(r,e){return(t,i,...s)=>{let n=[i,...s].map(o=>({type:r,isAll:e,rightSelect:o}));for(let o of n)if(!et(t.getSelectedFields(),o.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return t.addSetOperators(n)}}var Al=()=>({union:Il,unionAll:Ll,intersect:Fl,intersectAll:Ol,except:ql,exceptAll:jl}),Il=ze("union",!1),Ll=ze("union",!0),Fl=ze("intersect",!1),Ol=ze("intersect",!0),ql=ze("except",!1),jl=ze("except",!0);var Re=class{static[l]="PgQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=d(e,Ne)?e:void 0,this.dialectConfig=d(e,Ne)?void 0:e}$with=(e,t)=>{let i=this;return{as:n=>(typeof n=="function"&&(n=n(i)),new Proxy(new Oe(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new z({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};with(...e){let t=this;function i(o){return new U({fields:o??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function s(o){return new U({fields:o??void 0,session:void 0,dialect:t.getDialect(),distinct:!0})}function n(o,a){return new U({fields:a??void 0,session:void 0,dialect:t.getDialect(),distinct:{on:o}})}return{select:i,selectDistinct:s,selectDistinctOn:n}}select(e){return new U({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new U({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(e,t){return new U({fields:t??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:e}})}getDialect(){return this.dialect||(this.dialect=new Ne(this.dialectConfig)),this.dialect}};function ce(r){return d(r,V)?[r[Pe]?`${r[Pe]}.${r[y.Symbol.BaseName]}`:r[y.Symbol.BaseName]]:d(r,j)?r._.usedTables??[]:d(r,b)?r.usedTables??[]:[]}var dt=class extends W{constructor(e,t,i,s){super(),this.session=t,this.dialect=i,this.config={table:e,withList:s}}static[l]="PgDelete";config;cacheConfig;where(e){return this.config.where=e,this}returning(e=this.config.table[y.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=se(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return A.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:"delete",tables:ce(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>A.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new z({alias:X(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}};var ht=class{constructor(e,t,i,s,n){this.table=e,this.session=t,this.dialect=i,this.withList=s,this.overridingSystemValue_=n}static[l]="PgInsertBuilder";authToken;setToken(e){return this.authToken=e,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw new Error("values() must be called with at least one value");let t=e.map(i=>{let s={},n=this.table[y.Symbol.Columns];for(let o of Object.keys(i)){let a=i[o];s[o]=d(a,b)?a:new ee(a,n[o])}return s});return new Yt(this.table,t,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(e){let t=typeof e=="function"?e(new Re):e;if(!d(t,b)&&!et(this.table[qt],t._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new Yt(this.table,t,this.session,this.dialect,this.withList,!0)}},Yt=class extends W{constructor(e,t,i,s,n,o,a){super(),this.session=i,this.dialect=s,this.config={table:e,values:t,withList:n,select:o,overridingSystemValue_:a}}static[l]="PgInsert";config;cacheConfig;returning(e=this.config.table[y.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=se(e),this}onConflictDoNothing(e={}){if(e.target===void 0)this.config.onConflict=f`do nothing`;else{let t="";t=Array.isArray(e.target)?e.target.map(s=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(s))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target));let i=e.where?f` where ${e.where}`:void 0;this.config.onConflict=f`(${f.raw(t)})${i} do nothing`}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let t=e.where?f` where ${e.where}`:void 0,i=e.targetWhere?f` where ${e.targetWhere}`:void 0,s=e.setWhere?f` where ${e.setWhere}`:void 0,n=this.dialect.buildUpdateSet(this.config.table,Qt(this.config.table,e.set)),o="";return o=Array.isArray(e.target)?e.target.map(a=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(a))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target)),this.config.onConflict=f`(${f.raw(o)})${i} do update set ${n}${t}${s}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return A.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:"insert",tables:ce(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>A.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new z({alias:X(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}};var Ht=class extends W{constructor(e,t,i){super(),this.session=t,this.dialect=i,this.config={view:e}}static[l]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return A.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,e,!0))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>A.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken))};var pt=class{constructor(e,t,i,s){this.table=e,this.session=t,this.dialect=i,this.withList=s}static[l]="PgUpdateBuilder";authToken;setToken(e){return this.authToken=e,this}set(e){return new ys(this.table,Qt(this.table,e),this.session,this.dialect,this.withList).setToken(this.authToken)}},ys=class extends W{constructor(e,t,i,s,n){super(),this.session=i,this.dialect=s,this.config={set:t,table:e,withList:n,joins:[]},this.tableName=we(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}static[l]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(e){let t=e,i=we(t);return typeof i=="string"&&(this.joinsNotNullableMap[i]=!0),this.config.from=t,this}getTableLikeFields(e){return d(e,V)?e[y.Symbol.Columns]:d(e,j)?e._.selectedFields:e[I].selectedFields}createJoin(e){return(t,i)=>{let s=we(t);if(typeof s=="string"&&this.config.joins.some(n=>n.alias===s))throw new Error(`Alias "${s}" is already used in this query`);if(typeof i=="function"){let n=this.config.from&&!d(this.config.from,b)?this.getTableLikeFields(this.config.from):void 0;i=i(new Proxy(this.config.table[y.Symbol.Columns],new z({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new z({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:i,table:t,joinType:e,alias:s}),typeof s=="string")switch(e){case"left":{this.joinsNotNullableMap[s]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([n])=>[n,!1])),this.joinsNotNullableMap[s]=!0;break}case"inner":{this.joinsNotNullableMap[s]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([n])=>[n,!1])),this.joinsNotNullableMap[s]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}returning(e){if(!e&&(e=Object.assign({},this.config.table[y.Symbol.Columns]),this.config.from)){let t=we(this.config.from);if(typeof t=="string"&&this.config.from&&!d(this.config.from,b)){let i=this.getTableLikeFields(this.config.from);e[t]=i}for(let i of this.config.joins){let s=we(i.table);if(typeof s=="string"&&!d(i.table,b)){let n=this.getTableLikeFields(i.table);e[s]=n}}}return this.config.returningFields=e,this.config.returning=se(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){let t=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:"insert",tables:ce(this.config.table)},this.cacheConfig);return t.joinsNotNullableMap=this.joinsNotNullableMap,t}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>this._prepare().execute(e,this.authToken);getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new z({alias:X(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}};var Gt=class r extends b{constructor(e){super(r.buildEmbeddedCount(e.source,e.filters).queryChunks),this.params=e,this.mapWith(Number),this.session=e.session,this.sql=r.buildCount(e.source,e.filters)}sql;token;static[l]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(e,t){return f`(select count(*) from ${e}${f.raw(" where ").if(t)}${t})`}static buildCount(e,t){return f`select count(*) as count from ${e}${f.raw(" where ").if(t)}${t};`}setToken(e){return this.token=e,this}then(e,t){return Promise.resolve(this.session.count(this.sql,this.token)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}};var Zt=class{constructor(e,t,i,s,n,o,a){this.fullSchema=e,this.schema=t,this.tableNamesMap=i,this.table=s,this.tableConfig=n,this.dialect=o,this.session=a}static[l]="PgRelationalQueryBuilder";findMany(e){return new Xt(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},"many")}findFirst(e){return new Xt(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}},Xt=class extends W{constructor(e,t,i,s,n,o,a,u,m){super(),this.fullSchema=e,this.schema=t,this.tableNamesMap=i,this.table=s,this.tableConfig=n,this.dialect=o,this.session=a,this.config=u,this.mode=m}static[l]="PgRelationalQuery";_prepare(e){return A.startActiveSpan("drizzle.prepareQuery",()=>{let{query:t,builtQuery:i}=this._toSQL();return this.session.prepareQuery(i,void 0,e,!0,(s,n)=>{let o=s.map(a=>Mt(this.schema,this.tableConfig,a,t.selection,n));return this.mode==="first"?o[0]:o})})}prepare(e){return this._prepare(e)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let e=this._getQuery(),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(e){return this.authToken=e,this}execute(){return A.startActiveSpan("drizzle.operation",()=>this._prepare().execute(void 0,this.authToken))}};var er=class extends W{constructor(e,t,i,s){super(),this.execute=e,this.sql=t,this.query=i,this.mapBatchResult=s}static[l]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}};var Qe=class{constructor(e,t,i){if(this.dialect=e,this.session=t,this._=i?{schema:i.schema,fullSchema:i.fullSchema,tableNamesMap:i.tableNamesMap,session:t}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:t},this.query={},this._.schema)for(let[s,n]of Object.entries(this._.schema))this.query[s]=new Zt(i.fullSchema,this._.schema,this._.tableNamesMap,i.fullSchema[s],n,e,t);this.$cache={invalidate:async s=>{}}}static[l]="PgDatabase";query;$with=(e,t)=>{let i=this;return{as:n=>(typeof n=="function"&&(n=n(new Re(i.dialect))),new Proxy(new Oe(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new z({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};$count(e,t){return new Gt({source:e,filters:t,session:this.session})}$cache;with(...e){let t=this;function i(m){return new U({fields:m??void 0,session:t.session,dialect:t.dialect,withList:e})}function s(m){return new U({fields:m??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(m,c){return new U({fields:c??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:{on:m}})}function o(m){return new pt(m,t.session,t.dialect,e)}function a(m){return new ht(m,t.session,t.dialect,e)}function u(m){return new dt(m,t.session,t.dialect,e)}return{select:i,selectDistinct:s,selectDistinctOn:n,update:o,insert:a,delete:u}}select(e){return new U({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new U({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(e,t){return new U({fields:t??void 0,session:this.session,dialect:this.dialect,distinct:{on:e}})}update(e){return new pt(e,this.session,this.dialect)}insert(e){return new ht(e,this.session,this.dialect)}delete(e){return new dt(e,this.session,this.dialect)}refreshMaterializedView(e){return new Ht(e,this.session,this.dialect)}authToken;execute(e){let t=typeof e=="string"?f.raw(e):e.getSQL(),i=this.dialect.sqlToQuery(t),s=this.session.prepareQuery(i,void 0,void 0,!1);return new er(()=>s.execute(void 0,this.authToken),t,i,n=>s.mapResult(n,!0))}transaction(e,t){return this.session.transaction(e,t)}};var ws=class{static[l]="Cache"},ke=class extends ws{strategy(){return"all"}static[l]="NoopCache";async get(e){}async put(e,t,i,s){}async onMutate(e){}};async function bs(r,e){let t=`${r}-${JSON.stringify(e)}`,s=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",s);return[...new Uint8Array(n)].map(u=>u.toString(16).padStart(2,"0")).join("")}var _e=class r extends Error{constructor(e,t,i){super(`Failed query: ${e}
15
- params: ${t}`),this.query=e,this.params=t,this.cause=i,Error.captureStackTrace(this,r),i&&(this.cause=i)}};var tr=class{constructor(e,t,i,s){this.query=e,this.cache=t,this.queryMetadata=i,this.cacheConfig=s,t&&t.strategy()==="all"&&s===void 0&&(this.cacheConfig={enable:!0,autoInvalidate:!0}),this.cacheConfig?.enable||(this.cacheConfig=void 0)}authToken;getQuery(){return this.query}mapResult(e,t){return e}setToken(e){return this.authToken=e,this}static[l]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,i){if(this.cache===void 0||d(this.cache,ke)||this.queryMetadata===void 0)try{return await i()}catch(s){throw new _e(e,t,s)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await i()}catch(s){throw new _e(e,t,s)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[s]=await Promise.all([i(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return s}catch(s){throw new _e(e,t,s)}if(!this.cacheConfig)try{return await i()}catch(s){throw new _e(e,t,s)}if(this.queryMetadata.type==="select"){let s=await this.cache.get(this.cacheConfig.tag??await bs(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(s===void 0){let n;try{n=await i()}catch(o){throw new _e(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await bs(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return s}try{return await i()}catch(s){throw new _e(e,t,s)}}},rr=class{constructor(e){this.dialect=e}static[l]="PgSession";execute(e,t){return A.startActiveSpan("drizzle.operation",()=>A.startActiveSpan("drizzle.prepareQuery",()=>this.prepareQuery(this.dialect.sqlToQuery(e),void 0,void 0,!1)).setToken(t).execute(void 0,t))}all(e){return this.prepareQuery(this.dialect.sqlToQuery(e),void 0,void 0,!1).all()}async count(e,t){let i=await this.execute(e,t);return Number(i[0].count)}},ir=class extends Qe{constructor(e,t,i,s=0){super(e,t,i),this.schema=i,this.nestedIndex=s}static[l]="PgTransaction";rollback(){throw new jt}getTransactionConfigSQL(e){let t=[];return e.isolationLevel&&t.push(`isolation level ${e.isolationLevel}`),e.accessMode&&t.push(e.accessMode),typeof e.deferrable=="boolean"&&t.push(e.deferrable?"deferrable":"not deferrable"),f.raw(t.join(" "))}setTransaction(e){return this.session.execute(f`set transaction ${this.getTransactionConfigSQL(e)}`)}};var _s=class extends tr{constructor(e,t,i,s,n,o,a,u,m,c){super({sql:t,params:i},n,o,a),this.client=e,this.queryString=t,this.params=i,this.logger=s,this.fields=u,this._isResponseInArrayMode=m,this.customResultMapper=c}static[l]="PostgresJsPreparedQuery";async execute(e={}){return A.startActiveSpan("drizzle.execute",async t=>{let i=Vr(this.params,e);t?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(i)}),this.logger.logQuery(this.queryString,i);let{fields:s,queryString:n,client:o,joinsNotNullableMap:a,customResultMapper:u}=this;if(!s&&!u)return A.startActiveSpan("drizzle.driver.execute",()=>this.queryWithCache(n,i,async()=>await o.unsafe(n,i)));let m=await A.startActiveSpan("drizzle.driver.execute",()=>(t?.setAttributes({"drizzle.query.text":n,"drizzle.query.params":JSON.stringify(i)}),this.queryWithCache(n,i,async()=>await o.unsafe(n,i).values())));return A.startActiveSpan("drizzle.mapResponse",()=>u?u(m):m.map(c=>Cn(s,c,a)))})}all(e={}){return A.startActiveSpan("drizzle.execute",async t=>{let i=Vr(this.params,e);return t?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(i)}),this.logger.logQuery(this.queryString,i),A.startActiveSpan("drizzle.driver.execute",()=>(t?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(i)}),this.queryWithCache(this.queryString,i,async()=>this.client.unsafe(this.queryString,i))))})}isResponseInArrayMode(){return this._isResponseInArrayMode}},gt=class r extends rr{constructor(e,t,i,s={}){super(t),this.client=e,this.schema=i,this.options=s,this.logger=s.logger??new Rt,this.cache=s.cache??new ke}static[l]="PostgresJsSession";logger;cache;prepareQuery(e,t,i,s,n,o,a){return new _s(this.client,e.sql,e.params,this.logger,this.cache,o,a,t,s,n)}query(e,t){return this.logger.logQuery(e,t),this.client.unsafe(e,t).values()}queryObjects(e,t){return this.client.unsafe(e,t)}transaction(e,t){return this.client.begin(async i=>{let s=new r(i,this.dialect,this.schema,this.options),n=new Ss(this.dialect,s,this.schema);return t&&await n.setTransaction(t),e(n)})}},Ss=class r extends ir{constructor(e,t,i,s=0){super(e,t,i,s),this.session=t}static[l]="PostgresJsTransaction";transaction(e){return this.session.client.savepoint(t=>{let i=new gt(t,this.dialect,this.schema,this.session.options),s=new r(this.dialect,i,this.schema);return e(s)})}};var vs=class extends Qe{static[l]="PostgresJsDatabase"};function Ve(r,e={}){let t=u=>u;for(let u of["1184","1082","1083","1114","1182","1185","1115","1231"])r.options.parsers[u]=t,r.options.serializers[u]=t;r.options.serializers[114]=t,r.options.serializers[3802]=t;let i=new Ne({casing:e.casing}),s;e.logger===!0?s=new zt:e.logger!==!1&&(s=e.logger);let n;if(e.schema){let u=Oo(e.schema,jo);n={fullSchema:e.schema,schema:u.tables,tableNamesMap:u.tableNamesMap}}let o=new gt(r,i,n,{logger:s,cache:e.cache}),a=new vs(i,o,n);return a.$client=r,a.$cache=e.cache,a.$cache&&(a.$cache.invalidate=e.cache?.onMutate),a}function sr(...r){if(typeof r[0]=="string"){let e=xs(r[0]);return Ve(e,r[1])}if(En(r[0])){let{connection:e,client:t,...i}=r[0];if(t)return Ve(t,i);if(typeof e=="object"&&e.url!==void 0){let{url:n,...o}=e,a=xs(n,o);return Ve(a,i)}let s=xs(e);return Ve(s,i)}return Ve(r[0],r[1])}(r=>{function e(t){return Ve({options:{parsers:{},serializers:{}}},t)}r.mock=e})(sr||(sr={}));import{join as Vl}from"path";var J=M("core_roles",r=>({id:r.serial().primaryKey(),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date),protected:r.boolean().notNull().default(!1),default:r.boolean().notNull().default(!1),root:r.boolean().notNull().default(!1),guest:r.boolean().notNull().default(!1),color:r.varchar({length:19})})).enableRLS();var de=M("core_languages",r=>({id:r.serial().primaryKey(),code:r.varchar({length:32}).notNull().unique(),name:r.varchar({length:255}).notNull(),timezone:r.varchar({length:255}).notNull().default("UTC"),protected:r.boolean().notNull().default(!1),default:r.boolean().notNull().default(!1),enabled:r.boolean().notNull().default(!0),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date),time24:r.boolean().notNull().default(!1)}),r=>[K("core_languages_code_idx").on(r.code),K("core_languages_name_idx").on(r.name)]).enableRLS(),nr=M("core_languages_words",r=>({id:r.serial().primaryKey(),languageCode:r.varchar().notNull().references(()=>de.code,{onDelete:"cascade"}),pluginCode:r.varchar({length:50}).notNull(),itemId:r.integer().notNull(),value:r.text().notNull(),tableName:r.varchar({length:255}).notNull(),variable:r.varchar({length:255}).notNull()}),r=>[K("core_languages_words_lang_code_idx").on(r.languageCode)]).enableRLS(),zg=G(nr,({one:r})=>({language:r(de,{fields:[nr.languageCode],references:[de.code]})}));var E=M("core_users",r=>({id:r.serial().primaryKey(),nameCode:r.varchar({length:255}).notNull().unique(),name:r.varchar({length:255}).notNull().unique(),email:r.varchar({length:255}).notNull().unique(),password:r.varchar(),createdAt:r.timestamp().notNull().defaultNow(),newsletter:r.boolean().notNull().default(!1),avatarColor:r.varchar({length:6}).notNull(),emailVerified:r.boolean().notNull().default(!1),roleId:r.integer().references(()=>J.id).notNull(),birthday:r.timestamp(),ipAddress:r.varchar({length:40}).notNull(),language:r.varchar({length:32}).notNull().default("en").references(()=>de.code,{onDelete:"set default"})}),r=>[K("core_users_name_code_idx").on(r.nameCode),K("core_users_name_idx").on(r.name),K("core_users_email_idx").on(r.email)]).enableRLS(),Bg=G(E,({one:r,many:e})=>({group:r(J,{fields:[E.roleId],references:[J.id]}),language:r(de,{fields:[E.language],references:[de.code]}),confirm_email:r(or,{fields:[E.id],references:[or.userId]}),sso:e(Ns),forgot_password:r(ar,{fields:[E.id],references:[ar.userId]})})),Ns=M("core_users_sso",r=>({userId:r.integer().references(()=>E.id,{onDelete:"cascade"}).notNull(),providerId:r.varchar({length:255}).notNull(),providerAccountId:r.varchar({length:255}).notNull(),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date)}),r=>[K("core_users_sso_user_id_idx").on(r.userId)]).enableRLS(),Mg=G(Ns,({one:r})=>({user:r(E,{fields:[Ns.userId],references:[E.id]})})),or=M("core_users_confirm_emails",r=>({id:r.serial().primaryKey(),userId:r.integer().references(()=>E.id,{onDelete:"cascade"}).notNull(),token:r.varchar({length:100}).notNull().unique(),createdAt:r.timestamp().notNull().defaultNow(),expires:r.timestamp().notNull()})).enableRLS(),Wg=G(or,({one:r})=>({user:r(E,{fields:[or.userId],references:[E.id]})})),ar=M("core_users_forgot_password",r=>({id:r.serial().primaryKey(),userId:r.integer().references(()=>E.id,{onDelete:"cascade"}).notNull().unique(),token:r.varchar({length:100}).notNull().unique(),ip_address:r.varchar({length:40}).notNull(),createdAt:r.timestamp().notNull().defaultNow(),expiresAt:r.timestamp().notNull()})).enableRLS(),Ug=G(ar,({one:r})=>({user:r(E,{fields:[ar.userId],references:[E.id]})}));var yt=M("core_sessions",r=>({id:r.serial().primaryKey(),token:r.varchar({length:255}).notNull().unique(),userId:r.integer().notNull().references(()=>E.id,{onDelete:"cascade"}),createdAt:r.timestamp().notNull().defaultNow(),expiresAt:r.timestamp().notNull(),deviceId:r.integer().references(()=>Se.id,{onDelete:"cascade"}).notNull()}),r=>[K("core_sessions_user_id_idx").on(r.userId)]).enableRLS(),Zg=G(yt,({one:r})=>({user:r(E,{fields:[yt.userId],references:[E.id]}),device:r(Se,{fields:[yt.deviceId],references:[Se.id]})})),Se=M("core_sessions_known_devices",r=>({id:r.serial().primaryKey(),ipAddress:r.varchar({length:40}).notNull(),userAgent:r.text().notNull(),lastSeen:r.timestamp().notNull().defaultNow()}),r=>[K("core_sessions_known_devices_ip_address_idx").on(r.ipAddress)]).enableRLS(),Xg=G(Se,({one:r})=>({session:r(yt,{fields:[Se.id],references:[yt.deviceId]})}));var wt=M("core_admin_permissions",r=>({id:r.serial().primaryKey(),roleId:r.integer().references(()=>J.id,{onDelete:"cascade"}),userId:r.integer().references(()=>E.id,{onDelete:"cascade"}),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date),protected:r.boolean().notNull().default(!1)}),r=>[K("core_admin_permissions_role_id_idx").on(r.roleId),K("core_admin_permissions_user_id_idx").on(r.userId)]).enableRLS(),oy=G(wt,({one:r})=>({group:r(J,{fields:[wt.roleId],references:[J.id]}),user:r(E,{fields:[wt.userId],references:[E.id]})})),Ts=M("core_admin_sessions",r=>({id:r.serial().primaryKey(),token:r.varchar({length:255}).notNull().unique(),userId:r.integer().notNull().references(()=>E.id,{onDelete:"cascade"}),createdAt:r.timestamp().notNull().defaultNow(),lastSeen:r.timestamp().notNull().defaultNow(),expiresAt:r.timestamp().notNull(),deviceId:r.integer().references(()=>Se.id,{onDelete:"cascade"}).notNull()}),r=>[K("core_admin_sessions_token_idx").on(r.token),K("core_admin_sessions_user_id_idx").on(r.userId)]).enableRLS(),ay=G(Ts,({one:r})=>({user:r(E,{fields:[Ts.userId],references:[E.id]}),device:r(Se,{fields:[Ts.deviceId],references:[Se.id]})}));var bt=M("core_moderators_permissions",r=>({id:r.serial().primaryKey(),roleId:r.integer().references(()=>J.id,{onDelete:"cascade"}),userId:r.integer().references(()=>E.id,{onDelete:"cascade"}),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date),protected:r.boolean().notNull().default(!1)}),r=>[K("core_moderators_permissions_role_id_idx").on(r.roleId),K("core_moderators_permissions_user_id_idx").on(r.userId)]).enableRLS(),dy=G(bt,({one:r})=>({group:r(J,{fields:[bt.roleId],references:[J.id]}),user:r(E,{fields:[bt.userId],references:[E.id]})}));import{existsSync as Ro}from"fs";import{readFile as Ql}from"fs/promises";import{join as he,relative as Qo}from"path";import{join as zl}from"path";import{pathToFileURL as Rl}from"url";var zo=async()=>{let r=zl(process.cwd(),"src","vitnode.config.ts");try{return(await import(Rl(r).href)).vitNodeConfig}catch(e){console.error("Failed to load config:",e),process.exit(1)}};var ko=async()=>{let e=[...(await zo()).plugins.map(n=>n.pluginId),"vitnode"],t=At(process.cwd()),i=It(t),s=Dt(i);await Promise.all(e.map(async n=>{let o=he(process.cwd(),"node_modules",n),a="";try{let S=he(o,"package.json");Ro(S)&&(a=JSON.parse(await Ql(S,"utf-8")).name??"")}catch(S){console.error(`\x1B[31mError reading package.json for ${n}:\x1B[0m`,S);return}let u=n.replace(/\//g,"-").replace(/@/g,""),m=he(t,"apps","web","src","app","[locale]","(main)",he("(plugins)",`(${u})`)),c=he(t,"apps","web","src","app","[locale]","admin","(auth)",he("(plugins)",`(${u})`)),h=he(t,"apps","web","src","locales",n),p=[{sourceDir:he(o,"src","app_admin"),destinationDir:c},{sourceDir:he(o,"src","app"),destinationDir:m},{sourceDir:he(o,"src","locales"),destinationDir:h}];for(let{sourceDir:S,destinationDir:x}of p)Ro(S)&&!Ue(S)&&(console.log(`\x1B[36mCopying ${n}:\x1B[0m ${Qo(t,S)} \u2192 ${Qo(t,x)}`),Xs(S,x,a,s,i,t,!1))}))};import{spawn as kl}from"child_process";var lr=async(r,e=[])=>new Promise((t,i)=>{let s=kl(r,e,{stdio:"inherit",shell:!0});s.on("error",n=>{i(n)}),s.on("close",n=>{n!==0?i(new Error(`Command failed with exit code ${n}`)):t(!0)})});Vo.config({path:Vl(process.cwd(),"..","..",".env")});var De=sr({connection:process.env.POSTGRES_URL??"postgresql://root:root@localhost:5432/vitnode",casing:"camelCase"}),Kl=async()=>{try{await lr("npm",["run","drizzle-kit","up"]),await lr("npm",["run","drizzle-kit","generate"])}catch(r){console.error("\x1B[31m%s\x1B[0m",r),process.exit(1)}},Bl=async()=>{try{await lr("npm",["run","drizzle-kit","migrate"])}catch(r){console.error("\x1B[31m%s\x1B[0m",r),process.exit(1)}},Ml=async()=>{let[r]=await De.select({count:ds()}).from(J).limit(1),[e]=await De.select({count:ds()}).from(de);if(e.count===0&&await De.insert(de).values([{code:"en",name:"English (USA)",default:!0,protected:!0,timezone:"America/New_York"}]),r.count===0){let t=await De.insert(J).values([{protected:!0,guest:!0},{protected:!0,default:!0},{protected:!0,color:"hsl(122, 80%, 45%)"},{protected:!0,root:!0,color:"hsl(0, 100%, 50%)"}]).returning({id:J.id});await De.insert(nr).values([{languageCode:"en",pluginCode:"core",itemId:t[0].id,value:"Guest",tableName:"core_roles",variable:"name"},{languageCode:"en",pluginCode:"core",itemId:t[1].id,value:"Member",tableName:"core_roles",variable:"name"},{languageCode:"en",pluginCode:"core",itemId:t[2].id,value:"Moderator",tableName:"core_roles",variable:"name"},{languageCode:"en",pluginCode:"core",itemId:t[3].id,value:"Administrator",tableName:"core_roles",variable:"name"}]),await Promise.all([await De.insert(bt).values({roleId:t[2].id,protected:!0}),await De.insert(wt).values({roleId:t[3].id,protected:!0})])}},Ko=async({initMessage:r})=>{console.log(`${r} [1/4] Prepare plugins files...`),await ko(),console.log(`${r} [2/4] Generate migrations...`),await Kl(),console.log(`${r} [3/4] Run migrations...`),await Bl(),console.log(`
16
- ${r} [4/4] Insert initial data...`),await Ml(),console.log(`${r} \x1B[32mDatabase prepared successfully.\x1B[0m`),process.exit(0)};var Cs="\x1B[34m[VitNode]\x1B[0m",Bo=process.argv[2],Mo=process.argv[3];switch(Bo){case"init":Ko({initMessage:Cs});break;case"plugin":(Mo==="--w"||Mo==="--watch")&&rn({initMessage:Cs});break;default:console.log(`${Cs} \x1B[31mCommand not found: "${Bo??""}"\x1B[0m`),process.exit(1)}
12
+ `;await t.execute(c`CREATE SCHEMA IF NOT EXISTS ${c.identifier(n)}`),await t.execute(o);let m=(await t.all(c`select id, hash, created_at from ${c.identifier(n)}.${c.identifier(s)} order by created_at desc limit 1`))[0];await t.transaction(async f=>{for await(let u of e)if(!m||Number(m.created_at)<u.folderMillis){for(let h of u.sql)await f.execute(c.raw(h));await f.execute(c`insert into ${c.identifier(n)}.${c.identifier(s)} ("hash", "created_at") values(${u.hash}, ${u.folderMillis})`)}})}escapeName(e){return`"${e}"`}escapeParam(e){return`$${e+1}`}escapeString(e){return`'${e.replace(/'/g,"''")}'`}buildWithCTE(e){if(!e?.length)return;let t=[c`with `];for(let[i,s]of e.entries())t.push(c`${c.identifier(s._.alias)} as (${s._.sql})`),i<e.length-1&&t.push(c`, `);return t.push(c` `),c.join(t)}buildDeleteQuery({table:e,where:t,returning:i,withList:s}){let n=this.buildWithCTE(s),o=i?c` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,a=t?c` where ${t}`:void 0;return c`${n}delete from ${e}${a}${o}`}buildUpdateSet(e,t){let i=e[y.Symbol.Columns],s=Object.keys(i).filter(o=>t[o]!==void 0||i[o]?.onUpdateFn!==void 0),n=s.length;return c.join(s.flatMap((o,a)=>{let m=i[o],f=t[o]??c.param(m.onUpdateFn(),m),u=c`${c.identifier(this.casing.getColumnCasing(m))} = ${f}`;return a<n-1?[u,c.raw(", ")]:[u]}))}buildUpdateQuery({table:e,set:t,where:i,returning:s,withList:n,from:o,joins:a}){let m=this.buildWithCTE(n),f=e[B.Symbol.Name],u=e[B.Symbol.Schema],h=e[B.Symbol.OriginalName],p=f===h?void 0:f,x=c`${u?c`${c.identifier(u)}.`:void 0}${c.identifier(h)}${p&&c` ${c.identifier(p)}`}`,_=this.buildUpdateSet(e,t),$=o&&c.join([c.raw(" from "),this.buildFromTable(o)]),q=this.buildJoins(a),w=s?c` returning ${this.buildSelection(s,{isSingleTable:!o})}`:void 0,N=i?c` where ${i}`:void 0;return c`${m}update ${x} set ${_}${$}${q}${N}${w}`}buildSelection(e,{isSingleTable:t=!1}={}){let i=e.length,s=e.flatMap(({field:n},o)=>{let a=[];if(d(n,b.Aliased)&&n.isSelectionField)a.push(c.identifier(n.fieldAlias));else if(d(n,b.Aliased)||d(n,b)){let m=d(n,b.Aliased)?n.sql:n;t?a.push(new b(m.queryChunks.map(f=>d(f,g)?c.identifier(this.casing.getColumnCasing(f)):f))):a.push(m),d(n,b.Aliased)&&a.push(c` as ${c.identifier(n.fieldAlias)}`)}else d(n,E)&&(t?a.push(c.identifier(this.casing.getColumnCasing(n))):a.push(n));return o<i-1&&a.push(c`, `),a});return c.join(s)}buildJoins(e){if(!e||e.length===0)return;let t=[];for(let[i,s]of e.entries()){i===0&&t.push(c` `);let n=s.table,o=s.lateral?c` lateral`:void 0,a=s.on?c` on ${s.on}`:void 0;if(d(n,B)){let m=n[B.Symbol.Name],f=n[B.Symbol.Schema],u=n[B.Symbol.OriginalName],h=m===u?void 0:s.alias;t.push(c`${c.raw(s.joinType)} join${o} ${f?c`${c.identifier(f)}.`:void 0}${c.identifier(u)}${h&&c` ${c.identifier(h)}`}${a}`)}else if(d(n,H)){let m=n[F].name,f=n[F].schema,u=n[F].originalName,h=m===u?void 0:s.alias;t.push(c`${c.raw(s.joinType)} join${o} ${f?c`${c.identifier(f)}.`:void 0}${c.identifier(u)}${h&&c` ${c.identifier(h)}`}${a}`)}else t.push(c`${c.raw(s.joinType)} join${o} ${n}${a}`);i<e.length-1&&t.push(c` `)}return c.join(t)}buildFromTable(e){if(d(e,y)&&e[y.Symbol.IsAlias]){let t=c`${c.identifier(e[y.Symbol.OriginalName])}`;return e[y.Symbol.Schema]&&(t=c`${c.identifier(e[y.Symbol.Schema])}.${t}`),c`${t} ${c.identifier(e[y.Symbol.Name])}`}return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:i,where:s,having:n,table:o,joins:a,orderBy:m,groupBy:f,limit:u,offset:h,lockingClause:p,distinct:x,setOperators:_}){let $=i??ie(t);for(let te of $)if(d(te.field,E)&&Z(te.field.table)!==(d(o,z)?o._.alias:d(o,Ie)?o[F].name:d(o,b)?void 0:Z(o))&&!(de=>a?.some(({alias:ar})=>ar===(de[y.Symbol.IsAlias]?Z(de):de[y.Symbol.BaseName])))(te.field.table)){let de=Z(te.field.table);throw new Error(`Your "${te.path.join("->")}" field references a column "${de}"."${te.field.name}", but the table "${de}" is not part of the query! Did you forget to join it?`)}let q=!a||a.length===0,w=this.buildWithCTE(e),N;x&&(N=x===!0?c` distinct`:c` distinct on (${c.join(x.on,c`, `)})`);let R=this.buildSelection($,{isSingleTable:q}),I=this.buildFromTable(o),J=this.buildJoins(a),Q=s?c` where ${s}`:void 0,C=n?c` having ${n}`:void 0,T;m&&m.length>0&&(T=c` order by ${c.join(m,c`, `)}`);let G;f&&f.length>0&&(G=c` group by ${c.join(f,c`, `)}`);let yt=typeof u=="object"||typeof u=="number"&&u>=0?c` limit ${u}`:void 0,or=h?c` offset ${h}`:void 0,De=c.empty();if(p){let te=c` for ${c.raw(p.strength)}`;p.config.of&&te.append(c` of ${c.join(Array.isArray(p.config.of)?p.config.of:[p.config.of],c`, `)}`),p.config.noWait?te.append(c` nowait`):p.config.skipLocked&&te.append(c` skip locked`),De.append(te)}let Se=c`${w}select${N} ${R} from ${I}${J}${Q}${G}${C}${T}${yt}${or}${De}`;return _.length>0?this.buildSetOperations(Se,_):Se}buildSetOperations(e,t){let[i,...s]=t;if(!i)throw new Error("Cannot pass undefined values to any set operator");return s.length===0?this.buildSetOperationQuery({leftSelect:e,setOperator:i}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:i}),s)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:i,rightSelect:s,limit:n,orderBy:o,offset:a}}){let m=c`(${e.getSQL()}) `,f=c`(${s.getSQL()})`,u;if(o&&o.length>0){let _=[];for(let $ of o)if(d($,g))_.push(c.identifier($.name));else if(d($,b)){for(let q=0;q<$.queryChunks.length;q++){let w=$.queryChunks[q];d(w,g)&&($.queryChunks[q]=c.identifier(w.name))}_.push(c`${$}`)}else _.push(c`${$}`);u=c` order by ${c.join(_,c`, `)} `}let h=typeof n=="object"||typeof n=="number"&&n>=0?c` limit ${n}`:void 0,p=c.raw(`${t} ${i?"all ":""}`),x=a?c` offset ${a}`:void 0;return c`${m}${p}${f}${u}${h}${x}`}buildInsertQuery({table:e,values:t,onConflict:i,returning:s,withList:n,select:o,overridingSystemValue_:a}){let m=[],f=e[y.Symbol.Columns],u=Object.entries(f).filter(([w,N])=>!N.shouldDisableInsert()),h=u.map(([,w])=>c.identifier(this.casing.getColumnCasing(w)));if(o){let w=t;d(w,b)?m.push(w):m.push(w.getSQL())}else{let w=t;m.push(c.raw("values "));for(let[N,R]of w.entries()){let I=[];for(let[J,Q]of u){let C=R[J];if(C===void 0||d(C,X)&&C.value===void 0)if(Q.defaultFn!==void 0){let T=Q.defaultFn(),G=d(T,b)?T:c.param(T,Q);I.push(G)}else if(!Q.default&&Q.onUpdateFn!==void 0){let T=Q.onUpdateFn(),G=d(T,b)?T:c.param(T,Q);I.push(G)}else I.push(c`default`);else I.push(C)}m.push(I),N<w.length-1&&m.push(c`, `)}}let p=this.buildWithCTE(n),x=c.join(m),_=s?c` returning ${this.buildSelection(s,{isSingleTable:!0})}`:void 0,$=i?c` on conflict ${i}`:void 0,q=a===!0?c`overriding system value `:void 0;return c`${p}insert into ${e} ${h} ${q}${x}${$}${_}`}buildRefreshMaterializedViewQuery({view:e,concurrently:t,withNoData:i}){let s=t?c` concurrently`:void 0,n=i?c` with no data`:void 0;return c`refresh materialized view${s} ${e}${n}`}prepareTyping(e){return d(e,tt)||d(e,et)?"json":d(e,rt)?"decimal":d(e,it)?"time":d(e,st)||d(e,nt)?"timestamp":d(e,Ze)||d(e,Xe)?"date":d(e,ot)?"uuid":"none"}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:t})}buildRelationalQueryWithoutPK({fullSchema:e,schema:t,tableNamesMap:i,table:s,tableConfig:n,queryConfig:o,tableAlias:a,nestedQueryRelation:m,joinOn:f}){let u=[],h,p,x=[],_,$=[];if(o===!0)u=Object.entries(n.columns).map(([N,R])=>({dbKey:R.name,tsKey:N,field:ce(R,a),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let w=Object.fromEntries(Object.entries(n.columns).map(([C,T])=>[C,ce(T,a)]));if(o.where){let C=typeof o.where=="function"?o.where(w,bo()):o.where;_=C&&He(C,a)}let N=[],R=[];if(o.columns){let C=!1;for(let[T,G]of Object.entries(o.columns))G!==void 0&&T in n.columns&&(!C&&G===!0&&(C=!0),R.push(T));R.length>0&&(R=C?R.filter(T=>o.columns?.[T]===!0):Object.keys(n.columns).filter(T=>!R.includes(T)))}else R=Object.keys(n.columns);for(let C of R){let T=n.columns[C];N.push({tsKey:C,value:T})}let I=[];o.with&&(I=Object.entries(o.with).filter(C=>!!C[1]).map(([C,T])=>({tsKey:C,queryConfig:T,relation:n.relations[C]})));let J;if(o.extras){J=typeof o.extras=="function"?o.extras(w,{sql:c}):o.extras;for(let[C,T]of Object.entries(J))N.push({tsKey:C,value:zr(T,a)})}for(let{tsKey:C,value:T}of N)u.push({dbKey:d(T,b.Aliased)?T.fieldAlias:n.columns[C].name,tsKey:C,field:d(T,E)?ce(T,a):T,relationTableTsKey:void 0,isJson:!1,selection:[]});let Q=typeof o.orderBy=="function"?o.orderBy(w,So()):o.orderBy??[];Array.isArray(Q)||(Q=[Q]),x=Q.map(C=>d(C,E)?ce(C,a):He(C,a)),h=o.limit,p=o.offset;for(let{tsKey:C,queryConfig:T,relation:G}of I){let yt=_o(t,i,G),or=Pe(G.referencedTable),De=i[or],Se=`${a}_${C}`,te=at(...yt.fields.map((Fo,qo)=>Qt(ce(yt.references[qo],Se),ce(Fo,a)))),de=this.buildRelationalQueryWithoutPK({fullSchema:e,schema:t,tableNamesMap:i,table:e[De],tableConfig:t[De],queryConfig:d(G,xe)?T===!0?{limit:1}:{...T,limit:1}:T,tableAlias:Se,joinOn:te,nestedQueryRelation:G}),ar=c`${c.identifier(Se)}.${c.identifier("data")}`.as(C);$.push({on:c`true`,table:new z(de.sql,{},Se),alias:Se,joinType:"left",lateral:!0}),u.push({dbKey:C,tsKey:C,field:ar,relationTableTsKey:De,isJson:!0,selection:de.selection})}}if(u.length===0)throw new Ye({message:`No fields selected for table "${n.tsName}" ("${a}")`});let q;if(_=at(f,_),m){let w=c`json_build_array(${c.join(u.map(({field:I,tsKey:J,isJson:Q})=>Q?c`${c.identifier(`${a}_${J}`)}.${c.identifier("data")}`:d(I,b.Aliased)?I.sql:I),c`, `)})`;d(m,lt)&&(w=c`coalesce(json_agg(${w}${x.length>0?c` order by ${c.join(x,c`, `)}`:void 0}), '[]'::json)`);let N=[{dbKey:"data",tsKey:"data",field:w.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:u}];h!==void 0||p!==void 0||x.length>0?(q=this.buildSelectQuery({table:Je(s,a),fields:{},fieldsFlat:[{path:[],field:c.raw("*")}],where:_,limit:h,offset:p,orderBy:x,setOperators:[]}),_=void 0,h=void 0,p=void 0,x=[]):q=Je(s,a),q=this.buildSelectQuery({table:d(q,B)?q:new z(q,{},a),fields:{},fieldsFlat:N.map(({field:I})=>({path:[],field:d(I,E)?ce(I,a):I})),joins:$,where:_,limit:h,offset:p,orderBy:x,setOperators:[]})}else q=this.buildSelectQuery({table:Je(s,a),fields:{},fieldsFlat:u.map(({field:w})=>({path:[],field:d(w,E)?ce(w,a):w})),joins:$,where:_,limit:h,offset:p,orderBy:x,setOperators:[]});return{tableTsKey:n.tsName,sql:q,selection:u}}};var Vt=class{static[l]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}};var W=class{static[l]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,e.withList&&(this.withList=e.withList),this.distinct=e.distinct}authToken;setToken(e){return this.authToken=e,this}from(e){let t=!!this.fields,i=e,s;return this.fields?s=this.fields:d(i,z)?s=Object.fromEntries(Object.keys(i._.selectedFields).map(n=>[n,i[n]])):d(i,Ie)?s=i[F].selectedFields:d(i,b)?s={}:s=hn(i),new Mt({table:i,fields:s,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}},us=class extends Vt{static[l]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:i,session:s,dialect:n,withList:o,distinct:a}){super(),this.config={withList:o,table:e,fields:{...t},distinct:a,setOperators:[]},this.isPartialSelect=i,this.session=s,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=ge(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{};for(let m of ae(e))this.usedTables.add(m)}getUsedTables(){return[...this.usedTables]}createJoin(e,t){return(i,s)=>{let n=this.tableName,o=ge(i);for(let a of ae(i))this.usedTables.add(a);if(typeof o=="string"&&this.config.joins?.some(a=>a.alias===o))throw new Error(`Alias "${o}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof n=="string"&&(this.config.fields={[n]:this.config.fields}),typeof o=="string"&&!d(i,b))){let a=d(i,z)?i._.selectedFields:d(i,H)?i[F].selectedFields:i[y.Symbol.Columns];this.config.fields[o]=a}if(typeof s=="function"&&(s=s(new Proxy(this.config.fields,new O({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:s,table:i,joinType:e,alias:o,lateral:t}),typeof o=="string")switch(e){case"left":{this.joinsNotNullableMap[o]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[o]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[o]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,!1])),this.joinsNotNullableMap[o]=!1;break}}return this}}leftJoin=this.createJoin("left",!1);leftJoinLateral=this.createJoin("left",!0);rightJoin=this.createJoin("right",!1);innerJoin=this.createJoin("inner",!1);innerJoinLateral=this.createJoin("inner",!0);fullJoin=this.createJoin("full",!1);crossJoin=this.createJoin("cross",!1);crossJoinLateral=this.createJoin("cross",!0);createSetOperator(e,t){return i=>{let s=typeof i=="function"?i(Ya()):i;if(!Ge(this.getSelectedFields(),s.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:t,rightSelect:s}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);intersectAll=this.createSetOperator("intersect",!0);except=this.createSetOperator("except",!1);exceptAll=this.createSetOperator("except",!0);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new O({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new O({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){let t=e[0](new Proxy(this.config.fields,new O({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){let t=e[0](new Proxy(this.config.fields,new O({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),i=Array.isArray(t)?t:[t];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=i:this.config.orderBy=i}else{let t=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=t:this.config.orderBy=t}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}for(e,t={}){return this.config.lockingClause={strength:e,config:t},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...ae(this.config.table)),this.config.joins)for(let i of this.config.joins)t.push(...ae(i.table));return new Proxy(new z(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new O({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new O({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}},Mt=class extends us{static[l]="PgSelect";_prepare(e){let{session:t,config:i,dialect:s,joinsNotNullableMap:n,authToken:o,cacheConfig:a,usedTables:m}=this;if(!t)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");let{fields:f}=i;return A.startActiveSpan("drizzle.prepareQuery",()=>{let u=ie(f),h=t.prepareQuery(s.sqlToQuery(this.getSQL()),u,e,!0,void 0,{type:"select",tables:[...m]},a);return h.joinsNotNullableMap=n,h.setToken(o)})}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>A.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken))};dn(Mt,[M]);function je(r,e){return(t,i,...s)=>{let n=[i,...s].map(o=>({type:r,isAll:e,rightSelect:o}));for(let o of n)if(!Ge(t.getSelectedFields(),o.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return t.addSetOperators(n)}}var Ya=()=>({union:Ga,unionAll:Za,intersect:Xa,intersectAll:el,except:tl,exceptAll:rl}),Ga=je("union",!1),Za=je("union",!0),Xa=je("intersect",!1),el=je("intersect",!0),tl=je("except",!1),rl=je("except",!0);var ze=class{static[l]="PgQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=d(e,_e)?e:void 0,this.dialectConfig=d(e,_e)?void 0:e}$with=(e,t)=>{let i=this;return{as:n=>(typeof n=="function"&&(n=n(i)),new Proxy(new qe(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new O({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};with(...e){let t=this;function i(o){return new W({fields:o??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function s(o){return new W({fields:o??void 0,session:void 0,dialect:t.getDialect(),distinct:!0})}function n(o,a){return new W({fields:a??void 0,session:void 0,dialect:t.getDialect(),distinct:{on:o}})}return{select:i,selectDistinct:s,selectDistinctOn:n}}select(e){return new W({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new W({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(e,t){return new W({fields:t??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:e}})}getDialect(){return this.dialect||(this.dialect=new _e(this.dialectConfig)),this.dialect}};function ae(r){return d(r,B)?[r[ve]?`${r[ve]}.${r[y.Symbol.BaseName]}`:r[y.Symbol.BaseName]]:d(r,z)?r._.usedTables??[]:d(r,b)?r.usedTables??[]:[]}var ut=class extends M{constructor(e,t,i,s){super(),this.session=t,this.dialect=i,this.config={table:e,withList:s}}static[l]="PgDelete";config;cacheConfig;where(e){return this.config.where=e,this}returning(e=this.config.table[y.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=ie(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return A.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:"delete",tables:ae(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>A.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new O({alias:Z(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}};var mt=class{constructor(e,t,i,s,n){this.table=e,this.session=t,this.dialect=i,this.withList=s,this.overridingSystemValue_=n}static[l]="PgInsertBuilder";authToken;setToken(e){return this.authToken=e,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw new Error("values() must be called with at least one value");let t=e.map(i=>{let s={},n=this.table[y.Symbol.Columns];for(let o of Object.keys(i)){let a=i[o];s[o]=d(a,b)?a:new X(a,n[o])}return s});return new Wt(this.table,t,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(e){let t=typeof e=="function"?e(new ze):e;if(!d(t,b)&&!Ge(this.table[qt],t._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new Wt(this.table,t,this.session,this.dialect,this.withList,!0)}},Wt=class extends M{constructor(e,t,i,s,n,o,a){super(),this.session=i,this.dialect=s,this.config={table:e,values:t,withList:n,select:o,overridingSystemValue_:a}}static[l]="PgInsert";config;cacheConfig;returning(e=this.config.table[y.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=ie(e),this}onConflictDoNothing(e={}){if(e.target===void 0)this.config.onConflict=c`do nothing`;else{let t="";t=Array.isArray(e.target)?e.target.map(s=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(s))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target));let i=e.where?c` where ${e.where}`:void 0;this.config.onConflict=c`(${c.raw(t)})${i} do nothing`}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');let t=e.where?c` where ${e.where}`:void 0,i=e.targetWhere?c` where ${e.targetWhere}`:void 0,s=e.setWhere?c` where ${e.setWhere}`:void 0,n=this.dialect.buildUpdateSet(this.config.table,zt(this.config.table,e.set)),o="";return o=Array.isArray(e.target)?e.target.map(a=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(a))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target)),this.config.onConflict=c`(${c.raw(o)})${i} do update set ${n}${t}${s}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return A.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:"insert",tables:ae(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>A.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new O({alias:Z(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}};var Ut=class extends M{constructor(e,t,i){super(),this.session=t,this.dialect=i,this.config={view:e}}static[l]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return A.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,e,!0))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>A.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken))};var ft=class{constructor(e,t,i,s){this.table=e,this.session=t,this.dialect=i,this.withList=s}static[l]="PgUpdateBuilder";authToken;setToken(e){return this.authToken=e,this}set(e){return new ms(this.table,zt(this.table,e),this.session,this.dialect,this.withList).setToken(this.authToken)}},ms=class extends M{constructor(e,t,i,s,n){super(),this.session=i,this.dialect=s,this.config={set:t,table:e,withList:n,joins:[]},this.tableName=ge(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:!0}:{}}static[l]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(e){let t=e,i=ge(t);return typeof i=="string"&&(this.joinsNotNullableMap[i]=!0),this.config.from=t,this}getTableLikeFields(e){return d(e,B)?e[y.Symbol.Columns]:d(e,z)?e._.selectedFields:e[F].selectedFields}createJoin(e){return(t,i)=>{let s=ge(t);if(typeof s=="string"&&this.config.joins.some(n=>n.alias===s))throw new Error(`Alias "${s}" is already used in this query`);if(typeof i=="function"){let n=this.config.from&&!d(this.config.from,b)?this.getTableLikeFields(this.config.from):void 0;i=i(new Proxy(this.config.table[y.Symbol.Columns],new O({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new O({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}if(this.config.joins.push({on:i,table:t,joinType:e,alias:s}),typeof s=="string")switch(e){case"left":{this.joinsNotNullableMap[s]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([n])=>[n,!1])),this.joinsNotNullableMap[s]=!0;break}case"inner":{this.joinsNotNullableMap[s]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([n])=>[n,!1])),this.joinsNotNullableMap[s]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}returning(e){if(!e&&(e=Object.assign({},this.config.table[y.Symbol.Columns]),this.config.from)){let t=ge(this.config.from);if(typeof t=="string"&&this.config.from&&!d(this.config.from,b)){let i=this.getTableLikeFields(this.config.from);e[t]=i}for(let i of this.config.joins){let s=ge(i.table);if(typeof s=="string"&&!d(i.table,b)){let n=this.getTableLikeFields(i.table);e[s]=n}}}return this.config.returningFields=e,this.config.returning=ie(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){let t=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:"insert",tables:ae(this.config.table)},this.cacheConfig);return t.joinsNotNullableMap=this.joinsNotNullableMap,t}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>this._prepare().execute(e,this.authToken);getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new O({alias:Z(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}};var Jt=class r extends b{constructor(e){super(r.buildEmbeddedCount(e.source,e.filters).queryChunks),this.params=e,this.mapWith(Number),this.session=e.session,this.sql=r.buildCount(e.source,e.filters)}sql;token;static[l]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(e,t){return c`(select count(*) from ${e}${c.raw(" where ").if(t)}${t})`}static buildCount(e,t){return c`select count(*) as count from ${e}${c.raw(" where ").if(t)}${t};`}setToken(e){return this.token=e,this}then(e,t){return Promise.resolve(this.session.count(this.sql,this.token)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}};var Ht=class{constructor(e,t,i,s,n,o,a){this.fullSchema=e,this.schema=t,this.tableNamesMap=i,this.table=s,this.tableConfig=n,this.dialect=o,this.session=a}static[l]="PgRelationalQueryBuilder";findMany(e){return new Yt(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},"many")}findFirst(e){return new Yt(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}},Yt=class extends M{constructor(e,t,i,s,n,o,a,m,f){super(),this.fullSchema=e,this.schema=t,this.tableNamesMap=i,this.table=s,this.tableConfig=n,this.dialect=o,this.session=a,this.config=m,this.mode=f}static[l]="PgRelationalQuery";_prepare(e){return A.startActiveSpan("drizzle.prepareQuery",()=>{let{query:t,builtQuery:i}=this._toSQL();return this.session.prepareQuery(i,void 0,e,!0,(s,n)=>{let o=s.map(a=>Bt(this.schema,this.tableConfig,a,t.selection,n));return this.mode==="first"?o[0]:o})})}prepare(e){return this._prepare(e)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let e=this._getQuery(),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(e){return this.authToken=e,this}execute(){return A.startActiveSpan("drizzle.operation",()=>this._prepare().execute(void 0,this.authToken))}};var Gt=class extends M{constructor(e,t,i,s){super(),this.execute=e,this.sql=t,this.query=i,this.mapBatchResult=s}static[l]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}};var Oe=class{constructor(e,t,i){if(this.dialect=e,this.session=t,this._=i?{schema:i.schema,fullSchema:i.fullSchema,tableNamesMap:i.tableNamesMap,session:t}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:t},this.query={},this._.schema)for(let[s,n]of Object.entries(this._.schema))this.query[s]=new Ht(i.fullSchema,this._.schema,this._.tableNamesMap,i.fullSchema[s],n,e,t);this.$cache={invalidate:async s=>{}}}static[l]="PgDatabase";query;$with=(e,t)=>{let i=this;return{as:n=>(typeof n=="function"&&(n=n(new ze(i.dialect))),new Proxy(new qe(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new O({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};$count(e,t){return new Jt({source:e,filters:t,session:this.session})}$cache;with(...e){let t=this;function i(f){return new W({fields:f??void 0,session:t.session,dialect:t.dialect,withList:e})}function s(f){return new W({fields:f??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(f,u){return new W({fields:u??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:{on:f}})}function o(f){return new ft(f,t.session,t.dialect,e)}function a(f){return new mt(f,t.session,t.dialect,e)}function m(f){return new ut(f,t.session,t.dialect,e)}return{select:i,selectDistinct:s,selectDistinctOn:n,update:o,insert:a,delete:m}}select(e){return new W({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new W({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(e,t){return new W({fields:t??void 0,session:this.session,dialect:this.dialect,distinct:{on:e}})}update(e){return new ft(e,this.session,this.dialect)}insert(e){return new mt(e,this.session,this.dialect)}delete(e){return new ut(e,this.session,this.dialect)}refreshMaterializedView(e){return new Ut(e,this.session,this.dialect)}authToken;execute(e){let t=typeof e=="string"?c.raw(e):e.getSQL(),i=this.dialect.sqlToQuery(t),s=this.session.prepareQuery(i,void 0,void 0,!1);return new Gt(()=>s.execute(void 0,this.authToken),t,i,n=>s.mapResult(n,!0))}transaction(e,t){return this.session.transaction(e,t)}};var fs=class{static[l]="Cache"},Qe=class extends fs{strategy(){return"all"}static[l]="NoopCache";async get(e){}async put(e,t,i,s){}async onMutate(e){}};async function ds(r,e){let t=`${r}-${JSON.stringify(e)}`,s=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",s);return[...new Uint8Array(n)].map(m=>m.toString(16).padStart(2,"0")).join("")}var we=class r extends Error{constructor(e,t,i){super(`Failed query: ${e}
13
+ params: ${t}`),this.query=e,this.params=t,this.cause=i,Error.captureStackTrace(this,r),i&&(this.cause=i)}};var Zt=class{constructor(e,t,i,s){this.query=e,this.cache=t,this.queryMetadata=i,this.cacheConfig=s,t&&t.strategy()==="all"&&s===void 0&&(this.cacheConfig={enable:!0,autoInvalidate:!0}),this.cacheConfig?.enable||(this.cacheConfig=void 0)}authToken;getQuery(){return this.query}mapResult(e,t){return e}setToken(e){return this.authToken=e,this}static[l]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,i){if(this.cache===void 0||d(this.cache,Qe)||this.queryMetadata===void 0)try{return await i()}catch(s){throw new we(e,t,s)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await i()}catch(s){throw new we(e,t,s)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[s]=await Promise.all([i(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return s}catch(s){throw new we(e,t,s)}if(!this.cacheConfig)try{return await i()}catch(s){throw new we(e,t,s)}if(this.queryMetadata.type==="select"){let s=await this.cache.get(this.cacheConfig.tag??await ds(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(s===void 0){let n;try{n=await i()}catch(o){throw new we(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await ds(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return s}try{return await i()}catch(s){throw new we(e,t,s)}}},Xt=class{constructor(e){this.dialect=e}static[l]="PgSession";execute(e,t){return A.startActiveSpan("drizzle.operation",()=>A.startActiveSpan("drizzle.prepareQuery",()=>this.prepareQuery(this.dialect.sqlToQuery(e),void 0,void 0,!1)).setToken(t).execute(void 0,t))}all(e){return this.prepareQuery(this.dialect.sqlToQuery(e),void 0,void 0,!1).all()}async count(e,t){let i=await this.execute(e,t);return Number(i[0].count)}},er=class extends Oe{constructor(e,t,i,s=0){super(e,t,i),this.schema=i,this.nestedIndex=s}static[l]="PgTransaction";rollback(){throw new Lt}getTransactionConfigSQL(e){let t=[];return e.isolationLevel&&t.push(`isolation level ${e.isolationLevel}`),e.accessMode&&t.push(e.accessMode),typeof e.deferrable=="boolean"&&t.push(e.deferrable?"deferrable":"not deferrable"),c.raw(t.join(" "))}setTransaction(e){return this.session.execute(c`set transaction ${this.getTransactionConfigSQL(e)}`)}};var hs=class extends Zt{constructor(e,t,i,s,n,o,a,m,f,u){super({sql:t,params:i},n,o,a),this.client=e,this.queryString=t,this.params=i,this.logger=s,this.fields=m,this._isResponseInArrayMode=f,this.customResultMapper=u}static[l]="PostgresJsPreparedQuery";async execute(e={}){return A.startActiveSpan("drizzle.execute",async t=>{let i=jr(this.params,e);t?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(i)}),this.logger.logQuery(this.queryString,i);let{fields:s,queryString:n,client:o,joinsNotNullableMap:a,customResultMapper:m}=this;if(!s&&!m)return A.startActiveSpan("drizzle.driver.execute",()=>this.queryWithCache(n,i,async()=>await o.unsafe(n,i)));let f=await A.startActiveSpan("drizzle.driver.execute",()=>(t?.setAttributes({"drizzle.query.text":n,"drizzle.query.params":JSON.stringify(i)}),this.queryWithCache(n,i,async()=>await o.unsafe(n,i).values())));return A.startActiveSpan("drizzle.mapResponse",()=>m?m(f):f.map(u=>fn(s,u,a)))})}all(e={}){return A.startActiveSpan("drizzle.execute",async t=>{let i=jr(this.params,e);return t?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(i)}),this.logger.logQuery(this.queryString,i),A.startActiveSpan("drizzle.driver.execute",()=>(t?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(i)}),this.queryWithCache(this.queryString,i,async()=>this.client.unsafe(this.queryString,i))))})}isResponseInArrayMode(){return this._isResponseInArrayMode}},dt=class r extends Xt{constructor(e,t,i,s={}){super(t),this.client=e,this.schema=i,this.options=s,this.logger=s.logger??new jt,this.cache=s.cache??new Qe}static[l]="PostgresJsSession";logger;cache;prepareQuery(e,t,i,s,n,o,a){return new hs(this.client,e.sql,e.params,this.logger,this.cache,o,a,t,s,n)}query(e,t){return this.logger.logQuery(e,t),this.client.unsafe(e,t).values()}queryObjects(e,t){return this.client.unsafe(e,t)}transaction(e,t){return this.client.begin(async i=>{let s=new r(i,this.dialect,this.schema,this.options),n=new ps(this.dialect,s,this.schema);return t&&await n.setTransaction(t),e(n)})}},ps=class r extends er{constructor(e,t,i,s=0){super(e,t,i,s),this.session=t}static[l]="PostgresJsTransaction";transaction(e){return this.session.client.savepoint(t=>{let i=new dt(t,this.dialect,this.schema,this.session.options),s=new r(this.dialect,i,this.schema);return e(s)})}};var ys=class extends Oe{static[l]="PostgresJsDatabase"};function Re(r,e={}){let t=m=>m;for(let m of["1184","1082","1083","1114","1182","1185","1115","1231"])r.options.parsers[m]=t,r.options.serializers[m]=t;r.options.serializers[114]=t,r.options.serializers[3802]=t;let i=new _e({casing:e.casing}),s;e.logger===!0?s=new It:e.logger!==!1&&(s=e.logger);let n;if(e.schema){let m=xo(e.schema,No);n={fullSchema:e.schema,schema:m.tables,tableNamesMap:m.tableNamesMap}}let o=new dt(r,i,n,{logger:s,cache:e.cache}),a=new ys(i,o,n);return a.$client=r,a.$cache=e.cache,a.$cache&&(a.$cache.invalidate=e.cache?.onMutate),a}function tr(...r){if(typeof r[0]=="string"){let e=gs(r[0]);return Re(e,r[1])}if(pn(r[0])){let{connection:e,client:t,...i}=r[0];if(t)return Re(t,i);if(typeof e=="object"&&e.url!==void 0){let{url:n,...o}=e,a=gs(n,o);return Re(a,i)}let s=gs(e);return Re(s,i)}return Re(r[0],r[1])}(r=>{function e(t){return Re({options:{parsers:{},serializers:{}}},t)}r.mock=e})(tr||(tr={}));import{join as al}from"path";var U=V("core_roles",r=>({id:r.serial().primaryKey(),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date),protected:r.boolean().notNull().default(!1),default:r.boolean().notNull().default(!1),root:r.boolean().notNull().default(!1),guest:r.boolean().notNull().default(!1),color:r.varchar({length:19})})).enableRLS();var me=V("core_languages",r=>({id:r.serial().primaryKey(),code:r.varchar({length:32}).notNull().unique(),name:r.varchar({length:255}).notNull(),timezone:r.varchar({length:255}).notNull().default("UTC"),protected:r.boolean().notNull().default(!1),default:r.boolean().notNull().default(!1),enabled:r.boolean().notNull().default(!0),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date),time24:r.boolean().notNull().default(!1)}),r=>[K("core_languages_code_idx").on(r.code),K("core_languages_name_idx").on(r.name)]).enableRLS(),rr=V("core_languages_words",r=>({id:r.serial().primaryKey(),languageCode:r.varchar().notNull().references(()=>me.code,{onDelete:"cascade"}),pluginCode:r.varchar({length:50}).notNull(),itemId:r.integer().notNull(),value:r.text().notNull(),tableName:r.varchar({length:255}).notNull(),variable:r.varchar({length:255}).notNull()}),r=>[K("core_languages_words_lang_code_idx").on(r.languageCode)]).enableRLS(),eg=Y(rr,({one:r})=>({language:r(me,{fields:[rr.languageCode],references:[me.code]})}));var D=V("core_users",r=>({id:r.serial().primaryKey(),nameCode:r.varchar({length:255}).notNull().unique(),name:r.varchar({length:255}).notNull().unique(),email:r.varchar({length:255}).notNull().unique(),password:r.varchar(),createdAt:r.timestamp().notNull().defaultNow(),newsletter:r.boolean().notNull().default(!1),avatarColor:r.varchar({length:6}).notNull(),emailVerified:r.boolean().notNull().default(!1),roleId:r.integer().references(()=>U.id).notNull(),birthday:r.timestamp(),ipAddress:r.varchar({length:40}).notNull(),language:r.varchar({length:32}).notNull().default("en").references(()=>me.code,{onDelete:"set default"})}),r=>[K("core_users_name_code_idx").on(r.nameCode),K("core_users_name_idx").on(r.name),K("core_users_email_idx").on(r.email)]).enableRLS(),og=Y(D,({one:r,many:e})=>({group:r(U,{fields:[D.roleId],references:[U.id]}),language:r(me,{fields:[D.language],references:[me.code]}),confirm_email:r(ir,{fields:[D.id],references:[ir.userId]}),sso:e(ws),forgot_password:r(sr,{fields:[D.id],references:[sr.userId]})})),ws=V("core_users_sso",r=>({userId:r.integer().references(()=>D.id,{onDelete:"cascade"}).notNull(),providerId:r.varchar({length:255}).notNull(),providerAccountId:r.varchar({length:255}).notNull(),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date)}),r=>[K("core_users_sso_user_id_idx").on(r.userId)]).enableRLS(),ag=Y(ws,({one:r})=>({user:r(D,{fields:[ws.userId],references:[D.id]})})),ir=V("core_users_confirm_emails",r=>({id:r.serial().primaryKey(),userId:r.integer().references(()=>D.id,{onDelete:"cascade"}).notNull(),token:r.varchar({length:100}).notNull().unique(),createdAt:r.timestamp().notNull().defaultNow(),expires:r.timestamp().notNull()})).enableRLS(),lg=Y(ir,({one:r})=>({user:r(D,{fields:[ir.userId],references:[D.id]})})),sr=V("core_users_forgot_password",r=>({id:r.serial().primaryKey(),userId:r.integer().references(()=>D.id,{onDelete:"cascade"}).notNull().unique(),token:r.varchar({length:100}).notNull().unique(),ip_address:r.varchar({length:40}).notNull(),createdAt:r.timestamp().notNull().defaultNow(),expiresAt:r.timestamp().notNull()})).enableRLS(),cg=Y(sr,({one:r})=>({user:r(D,{fields:[sr.userId],references:[D.id]})}));var ht=V("core_sessions",r=>({id:r.serial().primaryKey(),token:r.varchar({length:255}).notNull().unique(),userId:r.integer().notNull().references(()=>D.id,{onDelete:"cascade"}),createdAt:r.timestamp().notNull().defaultNow(),expiresAt:r.timestamp().notNull(),deviceId:r.integer().references(()=>be.id,{onDelete:"cascade"}).notNull()}),r=>[K("core_sessions_user_id_idx").on(r.userId)]).enableRLS(),hg=Y(ht,({one:r})=>({user:r(D,{fields:[ht.userId],references:[D.id]}),device:r(be,{fields:[ht.deviceId],references:[be.id]})})),be=V("core_sessions_known_devices",r=>({id:r.serial().primaryKey(),ipAddress:r.varchar({length:40}).notNull(),userAgent:r.text().notNull(),lastSeen:r.timestamp().notNull().defaultNow()}),r=>[K("core_sessions_known_devices_ip_address_idx").on(r.ipAddress)]).enableRLS(),pg=Y(be,({one:r})=>({session:r(ht,{fields:[be.id],references:[ht.deviceId]})}));var pt=V("core_admin_permissions",r=>({id:r.serial().primaryKey(),roleId:r.integer().references(()=>U.id,{onDelete:"cascade"}),userId:r.integer().references(()=>D.id,{onDelete:"cascade"}),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date),protected:r.boolean().notNull().default(!1)}),r=>[K("core_admin_permissions_role_id_idx").on(r.roleId),K("core_admin_permissions_user_id_idx").on(r.userId)]).enableRLS(),_g=Y(pt,({one:r})=>({group:r(U,{fields:[pt.roleId],references:[U.id]}),user:r(D,{fields:[pt.userId],references:[D.id]})})),bs=V("core_admin_sessions",r=>({id:r.serial().primaryKey(),token:r.varchar({length:255}).notNull().unique(),userId:r.integer().notNull().references(()=>D.id,{onDelete:"cascade"}),createdAt:r.timestamp().notNull().defaultNow(),lastSeen:r.timestamp().notNull().defaultNow(),expiresAt:r.timestamp().notNull(),deviceId:r.integer().references(()=>be.id,{onDelete:"cascade"}).notNull()}),r=>[K("core_admin_sessions_token_idx").on(r.token),K("core_admin_sessions_user_id_idx").on(r.userId)]).enableRLS(),Ng=Y(bs,({one:r})=>({user:r(D,{fields:[bs.userId],references:[D.id]}),device:r(be,{fields:[bs.deviceId],references:[be.id]})}));var gt=V("core_moderators_permissions",r=>({id:r.serial().primaryKey(),roleId:r.integer().references(()=>U.id,{onDelete:"cascade"}),userId:r.integer().references(()=>D.id,{onDelete:"cascade"}),createdAt:r.timestamp().notNull().defaultNow(),updatedAt:r.timestamp().notNull().$onUpdate(()=>new Date),protected:r.boolean().notNull().default(!1)}),r=>[K("core_moderators_permissions_role_id_idx").on(r.roleId),K("core_moderators_permissions_user_id_idx").on(r.userId)]).enableRLS(),Dg=Y(gt,({one:r})=>({group:r(U,{fields:[gt.roleId],references:[U.id]}),user:r(D,{fields:[gt.userId],references:[D.id]})}));import{existsSync as vo}from"fs";import{readFile as nl}from"fs/promises";import{join as fe,relative as Po}from"path";import{join as il}from"path";import{pathToFileURL as sl}from"url";var Co=async()=>{let r=il(process.cwd(),"src","vitnode.config.ts");try{return(await import(sl(r).href)).vitNodeConfig}catch(e){console.error("Failed to load config:",e),process.exit(1)}};var To=async()=>{let e=[...(await Co()).plugins.map(n=>n.pluginId),"vitnode"],t=$t(process.cwd()),i=Dt(t),s=Tt(i);await Promise.all(e.map(async n=>{let o=fe(process.cwd(),"node_modules",n),a="";try{let x=fe(o,"package.json");vo(x)&&(a=JSON.parse(await nl(x,"utf-8")).name??"")}catch(x){console.error(`\x1B[31mError reading package.json for ${n}:\x1B[0m`,x);return}let m=n.replace(/\//g,"-").replace(/@/g,""),f=fe(t,"apps","web","src","app","[locale]","(main)",fe("(plugins)",`(${m})`)),u=fe(t,"apps","web","src","app","[locale]","admin","(auth)",fe("(plugins)",`(${m})`)),h=fe(t,"apps","web","src","locales",n),p=[{sourceDir:fe(o,"src","app_admin"),destinationDir:u},{sourceDir:fe(o,"src","app"),destinationDir:f},{sourceDir:fe(o,"src","locales"),destinationDir:h}];for(let{sourceDir:x,destinationDir:_}of p)vo(x)&&!Me(x)&&(console.log(`\x1B[36mCopying ${n}:\x1B[0m ${Po(t,x)} \u2192 ${Po(t,_)}`),Ms(x,_,a,s,i,t,!1))}))};import{spawn as ol}from"child_process";var nr=async(r,e=[])=>new Promise((t,i)=>{let s=ol(r,e,{stdio:"inherit",shell:!0});s.on("error",n=>{i(n)}),s.on("close",n=>{n!==0?i(new Error(`Command failed with exit code ${n}`)):t(!0)})});$o.config({path:al(process.cwd(),"..","..",".env")});var $e=tr({connection:process.env.POSTGRES_URL??"postgresql://root:root@localhost:5432/vitnode",casing:"camelCase"}),ll=async()=>{try{await nr("npm",["run","drizzle-kit","up"]),await nr("npm",["run","drizzle-kit","generate"])}catch(r){console.error("\x1B[31m%s\x1B[0m",r),process.exit(1)}},cl=async()=>{try{await nr("npm",["run","drizzle-kit","migrate"])}catch(r){console.error("\x1B[31m%s\x1B[0m",r),process.exit(1)}},ul=async()=>{let[r]=await $e.select({count:as()}).from(U).limit(1),[e]=await $e.select({count:as()}).from(me);if(e.count===0&&await $e.insert(me).values([{code:"en",name:"English (USA)",default:!0,protected:!0,timezone:"America/New_York"}]),r.count===0){let t=await $e.insert(U).values([{protected:!0,guest:!0},{protected:!0,default:!0},{protected:!0,color:"hsl(122, 80%, 45%)"},{protected:!0,root:!0,color:"hsl(0, 100%, 50%)"}]).returning({id:U.id});await $e.insert(rr).values([{languageCode:"en",pluginCode:"core",itemId:t[0].id,value:"Guest",tableName:"core_roles",variable:"name"},{languageCode:"en",pluginCode:"core",itemId:t[1].id,value:"Member",tableName:"core_roles",variable:"name"},{languageCode:"en",pluginCode:"core",itemId:t[2].id,value:"Moderator",tableName:"core_roles",variable:"name"},{languageCode:"en",pluginCode:"core",itemId:t[3].id,value:"Administrator",tableName:"core_roles",variable:"name"}]),await Promise.all([await $e.insert(gt).values({roleId:t[2].id,protected:!0}),await $e.insert(pt).values({roleId:t[3].id,protected:!0})])}},Do=async({initMessage:r})=>{console.log(`${r} [1/4] Prepare plugins files...`),await To(),console.log(`${r} [2/4] Generate migrations...`),await ll(),console.log(`${r} [3/4] Run migrations...`),await cl(),console.log(`
14
+ ${r} [4/4] Insert initial data...`),await ul(),console.log(`${r} \x1B[32mDatabase prepared successfully.\x1B[0m`),process.exit(0)};var Ss="\x1B[34m[VitNode]\x1B[0m",Eo=process.argv[2],Ao=process.argv[3];switch(Eo){case"init":Do({initMessage:Ss});break;case"plugin":(Ao==="--w"||Ao==="--watch")&&Js({initMessage:Ss});break;default:console.log(`${Ss} \x1B[31mCommand not found: "${Eo??""}"\x1B[0m`),process.exit(1)}
17
15
  /*! Bundled license information:
18
16
 
19
17
  chokidar/esm/index.js: