tempest.games 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,29 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var Si=Object.create;var{getPrototypeOf:Ti,defineProperty:et,getOwnPropertyNames:ki}=Object;var bi=Object.prototype.hasOwnProperty;var Mi=(n,e,o)=>{o=n!=null?Si(Ti(n)):{};const t=e||!n||!n.__esModule?et(o,"default",{value:n,enumerable:!0}):o;for(let i of ki(n))if(!bi.call(t,i))et(t,i,{get:()=>n[i],enumerable:!0});return t};var ot=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var ti=ot((rR,Hr)=>{Hr.exports={name:"dotenv",version:"16.4.5",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","lint-readme":"standard-markdown",pretest:"npm run lint && npm run dts-check",test:"tap tests/*.js --100 -Rspec","test:coverage":"tap --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@definitelytyped/dtslint":"^0.0.133","@types/node":"^18.11.3",decache:"^4.6.1",sinon:"^14.0.1",standard:"^17.0.0","standard-markdown":"^7.1.0","standard-version":"^9.5.0",tap:"^16.3.0",tar:"^6.1.11",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var mi=ot((lR,jn)=>{function Er(n){const e={};let o=n.toString();o=o.replace(/\r\n?/mg,"\n");let t;while((t=Gr.exec(o))!=null){const i=t[1];let r=t[2]||"";r=r.trim();const l=r[0];if(r=r.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),l==='"')r=r.replace(/\\n/g,"\n"),r=r.replace(/\\r/g,"\r");e[i]=r}return e}function pr(n){const e=li(n),o=P.configDotenv({path:e});if(!o.parsed){const l=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw l.code="MISSING_DATA",l}const t=ri(n).split(","),i=t.length;let r;for(let l=0;l<i;l++)try{const m=t[l].trim(),f=Ur(o,m);r=P.decrypt(f.ciphertext,f.key);break}catch(m){if(l+1>=i)throw m}return P.parse(r)}function Lr(n){console.log(`[dotenv@${Do}][INFO] ${n}`)}function Vr(n){console.log(`[dotenv@${Do}][WARN] ${n}`)}function yo(n){console.log(`[dotenv@${Do}][DEBUG] ${n}`)}function ri(n){if(n&&n.DOTENV_KEY&&n.DOTENV_KEY.length>0)return n.DOTENV_KEY;if(process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0)return process.env.DOTENV_KEY;return""}function Ur(n,e){let o;try{o=new URL(e)}catch(m){if(m.code==="ERR_INVALID_URL"){const f=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 f.code="INVALID_DOTENV_KEY",f}throw m}const t=o.password;if(!t){const m=new Error("INVALID_DOTENV_KEY: Missing key part");throw m.code="INVALID_DOTENV_KEY",m}const i=o.searchParams.get("environment");if(!i){const m=new Error("INVALID_DOTENV_KEY: Missing environment part");throw m.code="INVALID_DOTENV_KEY",m}const r=`DOTENV_VAULT_${i.toUpperCase()}`,l=n.parsed[r];if(!l){const m=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${r} in your .env.vault file.`);throw m.code="NOT_FOUND_DOTENV_ENVIRONMENT",m}return{ciphertext:l,key:t}}function li(n){let e=null;if(n&&n.path&&n.path.length>0)if(Array.isArray(n.path)){for(let o of n.path)if(Uo.existsSync(o))e=o.endsWith(".vault")?o:`${o}.vault`}else e=n.path.endsWith(".vault")?n.path:`${n.path}.vault`;else e=ho.resolve(process.cwd(),".env.vault");if(Uo.existsSync(e))return e;return null}function ii(n){return n[0]==="~"?ho.join(qr.homedir(),n.slice(1)):n}function hr(n){Lr("Loading env from encrypted .env.vault");const e=P._parseVault(n);let o=process.env;if(n&&n.processEnv!=null)o=n.processEnv;return P.populate(o,e,n),{parsed:e}}function Dr(n){const e=ho.resolve(process.cwd(),".env");let o="utf8";const t=Boolean(n&&n.debug);if(n&&n.encoding)o=n.encoding;else if(t)yo("No encoding is specified. UTF-8 is used by default");let i=[e];if(n&&n.path)if(!Array.isArray(n.path))i=[ii(n.path)];else{i=[];for(let f of n.path)i.push(ii(f))}let r;const l={};for(let f of i)try{const y=P.parse(Uo.readFileSync(f,{encoding:o}));P.populate(l,y,n)}catch(y){if(t)yo(`Failed to load ${f} ${y.message}`);r=y}let m=process.env;if(n&&n.processEnv!=null)m=n.processEnv;if(P.populate(m,l,n),r)return{parsed:l,error:r};else return{parsed:l}}function Ir(n){if(ri(n).length===0)return P.configDotenv(n);const e=li(n);if(!e)return Vr(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),P.configDotenv(n);return P._configVault(n)}function Nr(n,e){const o=Buffer.from(e.slice(-64),"hex");let t=Buffer.from(n,"base64");const i=t.subarray(0,12),r=t.subarray(-16);t=t.subarray(12,-16);try{const l=Qr.createDecipheriv("aes-256-gcm",o,i);return l.setAuthTag(r),`${l.update(t)}${l.final()}`}catch(l){const m=l instanceof RangeError,f=l.message==="Invalid key length",y=l.message==="Unsupported state or unable to authenticate data";if(m||f){const c=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw c.code="INVALID_DOTENV_KEY",c}else if(y){const c=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw c.code="DECRYPTION_FAILED",c}else throw l}}function vr(n,e,o={}){const t=Boolean(o&&o.debug),i=Boolean(o&&o.override);if(typeof e!=="object"){const r=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw r.code="OBJECT_REQUIRED",r}for(let r of Object.keys(e))if(Object.prototype.hasOwnProperty.call(n,r)){if(i===!0)n[r]=e[r];if(t)if(i===!0)yo(`"${r}" is already defined and WAS overwritten`);else yo(`"${r}" is already defined and was NOT overwritten`)}else n[r]=e[r]}var Uo=import.meta.require("fs"),ho=import.meta.require("path"),qr=import.meta.require("os"),Qr=import.meta.require("crypto"),Yr=ti(),Do=Yr.version,Gr=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg,P={configDotenv:Dr,_configVault:hr,_parseVault:pr,config:Ir,decrypt:Nr,parse:Er,populate:vr};lR.configDotenv=P.configDotenv;lR._configVault=P._configVault;lR._parseVault=P._parseVault;lR.config=P.config;lR.decrypt=P.decrypt;lR.parse=P.parse;lR.populate=P.populate;jn.exports=P});import{join as il,normalize as rl,resolve as ci}from"path";function Nn(n=Math.random){return n().toString(36).slice(2)}class Fe extends Promise{fate;resolve;reject;done=!1;constructor(n){let e,o;super((t,i)=>{e=t,o=i});this.resolve=e,this.reject=o,this.use(n instanceof Promise?n:new Promise(n))}pass(n,e){if(n===this.fate)this.resolve(e),this.done=!0}fail(n,e){if(n===this.fate)this.reject(e),this.done=!0}use(n){if(n instanceof Promise){const e=n;this.fate=e,e.then((o)=>{this.pass(e,o)},(o)=>{this.fail(e,o)})}else this.resolve(n),this.fate=void 0}}var tt=(n,e,o=X.STORE)=>{return Mn(o,{key:`${n.key}:JSON`,get:({get:t})=>e.toJson(t(n)),set:({set:t},i)=>{t(n,e.fromJson(i))}})};function S(n){while(n.child!==null)n=n.child;return n}function it(n){while(n.parent!==null)n=n.parent;return n}class W{Subscriber;subscribers=new Map;subscribe(n,e){return this.subscribers.set(n,e),()=>{this.unsubscribe(n)}}unsubscribe(n){this.subscribers.delete(n)}next(n){const e=this.subscribers.values();for(let o of e)o(n)}}class co extends W{state;constructor(n){super();this.state=n}next(n){this.state=n,super.next(n)}}function wn(n,e,o){const t={key:e.key,type:"atom_family"},i=n.families.get(e.key);if(i)n.logger.error("\u2757","atom_family",e.key,`Overwriting an existing ${Rn(i)} "${i.key}" in store "${n.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new W,m=Object.assign((f)=>{const y=J(f),c={key:e.key,subKey:y},T=`${e.key}(${y})`,F=S(n),u=e.default,G={key:T,default:u instanceof Function?u(f):u};if(e.effects)G.effects=e.effects(f);const Sn=ln(F,G,c);return r.next({type:"state_creation",token:Sn}),Sn},t,{subject:r,install:(f)=>wn(f,e),internalRoles:o});return n.families.set(e.key,m),n.defaults.set(e.key,e.default),t}function rt(n,e){if("mutable"in e)return ge(n,e);return wn(n,e)}function Wn(n,e,o){const t={key:e.key,type:"readonly_selector_family"},i=n.families.get(e.key);if(i)n.logger.error("\u2757","readonly_selector_family",e.key,`Overwriting an existing ${Rn(i)} "${i.key}" in store "${n.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new W,m=Object.assign((f)=>{const y=J(f),c={key:e.key,subKey:y},T=`${e.key}(${y})`,F=S(n),u=Je(F,{key:T,get:e.get(f)},c);return r.next({type:"state_creation",token:u}),u},t,{internalRoles:o,subject:r,install:(f)=>Wn(f,e),default:(f)=>{return e.get(f)({get:(...c)=>V(n,...c),find:(c,T)=>Y(n,c,T),seek:(c,T)=>L(n,c,T),json:(c)=>Z(n,c)})}});return n.families.set(e.key,m),t}function $e(n,e){if("set"in e)return Ke(n,e);return Wn(n,e)}function vn(n,e){const o=J(e),t=`${n.key}(${o})`,i=Ri[n.type],r={key:t,type:i};if(i==="molecule")Object.assign(r,{key:e,family:n});else Object.assign(r,{family:{key:n.key,subKey:o}});return Object.assign(r,{counterfeit:!0}),r}var Ri={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function nn(n){const e={key:n.key,type:n.type};if("family"in n)e.family=n.family;return e}function Pn(n){return lt(X.STORE,n)}function Ln(n){return rt(X.STORE,n)}function ao(...n){if(n.length===2)return V(X.STORE,...n);return V(X.STORE,...n)}var So=(n)=>(e,o,t,i,...r)=>{console[n](`${e} ${o} "${t}" ${i}`,...r)},Ai={error:So("error"),info:So("info"),warn:So("warn")};class To{n;e;o;constructor(n,e,o=Ai){this.logLevel=n;this.filter=e;this.logger=o}error=(...n)=>{if((this.filter?.(...n)??!0)&&this.logLevel!==null)this.logger.error(...n)};info=(...n)=>{if((this.filter?.(...n)??!0)&&this.logLevel==="info")this.logger.info(...n)};warn=(...n)=>{if((this.filter?.(...n)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...n)}}function pe(n){return $e(X.STORE,n)}function we(n){return ko(n,X.STORE)}class yn{a;b;cardinality;relations=new Map;contents=new Map;isContent;makeContentKey=(n,e)=>`${n}:${e}`;warn;getRelatedKeys(n){return this.relations.get(n)}addRelation(n,e){let o=this.relations.get(n),t=this.relations.get(e);if(o)o.add(e);else o=new Set([e]),this.relations.set(n,o);if(t)t.add(n);else t=new Set([n]),this.relations.set(e,t)}deleteRelation(n,e){const o=this.relations.get(n);if(o){if(o.delete(e),o.size===0)this.relations.delete(n);const t=this.relations.get(e);if(t){if(t.delete(n),t.size===0)this.relations.delete(e)}}}replaceRelationsUnsafely(n,e){this.relations.set(n,new Set(e));for(let o of e){const t=new Set([n]);this.relations.set(o,t)}}replaceRelationsSafely(n,e){const o=this.relations.get(n);if(o)for(let t of o){const i=this.relations.get(t);if(i){if(i.size===1)this.relations.delete(t);else i.delete(n);this.contents.delete(this.makeContentKey(n,t))}}this.relations.set(n,new Set(e));for(let t of e){let i=this.relations.get(t);if(i)i.add(n);else i=new Set([n]),this.relations.set(t,i)}}getContentInternal(n){return this.contents.get(n)}setContent(n,e){this.contents.set(n,e)}deleteContent(n){this.contents.delete(n)}constructor(n,e){if(this.a=n.between[0],this.b=n.between[1],this.cardinality=n.cardinality,!e?.externalStore)this.relations=new Map(n.relations?.map(([o,t])=>[o,new Set(t)])),this.contents=new Map(n.contents);if(this.isContent=e?.isContent??null,e?.makeContentKey)this.makeContentKey=e.makeContentKey;if(e?.externalStore){const o=e.externalStore;if(this.has=(t,i)=>o.has(t,i),this.addRelation=(t,i)=>{o.addRelation(t,i)},this.deleteRelation=(t,i)=>{o.deleteRelation(t,i)},this.replaceRelationsSafely=(t,i)=>{o.replaceRelationsSafely(t,i)},this.replaceRelationsUnsafely=(t,i)=>{o.replaceRelationsUnsafely(t,i)},this.getRelatedKeys=(t)=>o.getRelatedKeys(t),o.getContent)this.getContentInternal=(t)=>{return o.getContent(t)},this.setContent=(t,i)=>{o.setContent(t,i)},this.deleteContent=(t)=>{o.deleteContent(t)};for(let[t,i]of n.relations??[])for(let r of i)this.addRelation(t,r);for(let[t,i]of n.contents??[])this.setContent(t,i)}if(e?.warn)this.warn=e.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([n,e])=>[n,[...e]]),contents:[...this.contents.entries()]}}set(n,...e){const o=typeof e[0]==="string"?e[0]:n[this.b],t=e[1]??typeof e[0]==="string"?void 0:e[0];switch(n=typeof n==="string"?n:n[this.a],this.cardinality){case"1:1":{const i=this.getRelatedKey(n);if(i&&i!==o)this.delete(i,n)}case"1:n":{const i=this.getRelatedKey(o);if(i&&i!==n)this.delete(i,o)}}if(t){const i=this.makeContentKey(n,o);this.setContent(i,t)}return this.addRelation(n,o),this}delete(n,e){e=typeof e==="string"?e:n[this.b];const o=typeof n==="string"?n:n[this.a];if(o===void 0&&typeof e==="string"){const t=this.getRelatedKeys(e);if(t)for(let i of t)this.delete(i,e)}if(typeof o==="string"&&e===void 0){const t=this.getRelatedKeys(o);if(t)for(let i of t)this.delete(o,i)}if(typeof o==="string"&&typeof e==="string"){this.deleteRelation(o,e);const t=this.makeContentKey(o,e);this.deleteContent(t)}return this}getRelatedKey(n){const e=this.getRelatedKeys(n);if(e){if(e.size>1)this.warn?.(`${e.size} related keys were found for key "${n}": (${[...e].map((o)=>`"${o}"`).join(", ")}). Only one related key was expected.`);for(let o of e)return o}}replaceRelations(n,e,o){const t=!Array.isArray(e),i=t?Object.keys(e):e;if(o?.reckless)this.replaceRelationsUnsafely(n,i);else this.replaceRelationsSafely(n,i);if(t)for(let r of i){const l=this.makeContentKey(n,r),m=e[r];this.setContent(l,m)}return this}getContent(n,e){const o=this.makeContentKey(n,e);return this.getContentInternal(o)}getRelationEntries(n){const e=n[this.a],o=n[this.b];if(e!==void 0&&o===void 0){const t=this.getRelatedKeys(e);if(t)return[...t].map((i)=>{return[i,this.getContent(e,i)??null]})}if(e===void 0&&o!==void 0){const t=this.getRelatedKeys(o);if(t)return[...t].map((i)=>{return[i,this.getContent(i,o)??null]})}return[]}has(n,e){if(e)return this.getRelatedKeys(n)?.has(e)??!1;return this.relations.has(n)}}function d(n){return"epoch"in n.transactionMeta}function _(n){return"phase"in n.transactionMeta}var ft=(n)=>{const e=S(n);if(!_(e)){n.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}n.logger.info("\uD83E\uDE82","transaction",e.transactionMeta.update.key,"Aborting transaction"),e.parent.child=null};function Rn(n){return n.type.split("_").map(Fi).join(" ")}var Fi=(n)=>n[0].toUpperCase()+n.slice(1);class mn extends Error{constructor(...n){const e=n[0],o=n.length===2?n[1]:n[2];if(n.length===2)super(`${Rn(e)} ${J(e.key)} not found in store "${o.config.name}".`);else{const t=n[1];super(`${Rn(e)} "${e.key}" member ${J(t)} not found in store "${o.config.name}".`)}}}function Vn(n,e,o){return(...t)=>{const i=C(n,o);if(i)return i.run(t,e);throw new mn(n,o)}}var Le=(n)=>(e)=>n instanceof Function?n(e):n;var Xn=(n,e)=>{if(e.valueMap.has(n.key))return e.logger.info("\uD83D\uDCD6",n.type,n.key,"reading cached value"),yt(n,e);if(n.type==="selector"||n.type==="readonly_selector")return e.logger.info("\uD83E\uDDEE",n.type,n.key,"computing value"),n.get();const o=n.default instanceof Function?n.default():n.default;return e.logger.info("\uD83D\uDC81","atom",n.key,"could not find cached value; using default",o),n.default instanceof Function?n.default():n.default};var ct=(n,e)=>{if(n.operation.open){const o=performance.now();return n.logger.info("\u2757",e.type,e.key,`deferring setState at T-${o} until setState for "${n.operation.token.key}" is done`),o}n.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:e},n.logger.info("\u2B55",e.type,e.key,`operation start in store "${n.config.name}"${!_(n)?"":` ${n.transactionMeta.phase} "${n.transactionMeta.update.key}"`}`)},at=(n)=>{if(n.operation.open)n.logger.info("\uD83D\uDD34",n.operation.token.type,n.operation.token.key,`operation done in store "${n.config.name}"`);n.operation={open:!1},n.on.operationClose.next(n.operation)},St=(n,e)=>{if(!n.operation.open)return n.logger.error("\uD83D\uDC1E","unknown",e,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return n.operation.done.has(e)},dn=(n,e)=>{if(!n.operation.open){n.logger.error("\uD83D\uDC1E","unknown",e,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}n.operation.done.add(e)};var Tt=(n,e,o)=>{switch(n.type){case"mutable_atom":o.logger.info("\uD83D\uDCE2",n.type,n.key,"is now (",e.newValue,") subscribers:",n.subject.subscribers);break;default:o.logger.info("\uD83D\uDCE2",n.type,n.key,"went (",e.oldValue,"->",e.newValue,") subscribers:",n.subject.subscribers)}n.subject.next(e)};var bo=(n,e)=>{const o=S(e),t=o.selectorAtoms.getRelatedKeys(n.key);if(o.logger.info("\uD83E\uDDF9",n.type,n.key,t?`evicting ${t.size} states downstream:`:"no downstream states",t??"to evict"),t){if(o.operation.open)o.logger.info("\uD83E\uDDF9",n.type,n.key,`[ ${[...o.operation.done].join(", ")} ] already done`);for(let i of t){if(St(o,i))continue;kt(i,o),dn(o,i)}}};function gi(n,e){if(Mt(e.newValue))return!1;if(n.includes("\uD83D\uDD0D"))return!1;return!0}var bt=(n,e,o)=>{const{key:t}=n,i=S(o);if(!_(i)||i.transactionMeta.phase!=="building"){o.logger.error("\uD83D\uDC1E","atom",t,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!gi(t,e))return;const l={type:"atom_update",key:t,...e};if(n.family)l.family=n.family;i.transactionMeta.update.updates.push(l),o.logger.info("\uD83D\uDCC1","atom",t,"stowed (",e.oldValue,"->",e.newValue,")")};var Rt=(n,e,o)=>{const t=Xn(n,o);let i=t;if(n.type==="mutable_atom"&&_(o)){const{parent:l}=o;i=Ce(n,l,o)}if(i=Le(e)(i),o.logger.info("\uD83D\uDCDD","atom",n.key,"set to",i),i=Tn(n.key,i,n.subject,o),At(n.key,o))Ft(n.key,o);dn(o,n.key),bo(n,o);const r={oldValue:t,newValue:i};if(d(o))Tt(n,r,o);else if(o.parent){if(o.on.transactionApplying.state===null)bt(n,r,o);else if(n.key.startsWith("*")){const l=n.key.slice(1),m=o.atoms.get(l);let f=o.valueMap.get(l);if(m.type==="mutable_atom"&&_(o)){const{parent:c}=o;f=Ce(m,c,o)}if(f.do(r.newValue)===null)bo(m,o)}}};var Ve=(n,e,o)=>{switch(n.type){case"atom":case"mutable_atom":Rt(n,e,o);break;case"selector":n.set(e);break}};function Ue(n,e){if(e.family){const o=n.families.get(e.family.key);if(o)return o}}function I(n,...e){let o,t,i,r;if(e.length===2){if(o=e[0],r=e[1],t=Ue(n,o)??null,t)i=o.family?D(o.family.subKey):null,o=Y(n,t,i)}else t=e[0],i=e[1],r=e[2],o=Y(n,t,i);if("counterfeit"in o){const f=n.disposalTraces.buffer.find((y)=>y?.key===o.key);n.logger.error("\u274C",o.type,o.key,`could not be set because it was not found in the store "${n.config.name}".`,f?`This state was previously disposed:\n${f.trace}`:"No previous disposal trace was found.");return}const l=ct(n,o);if(l){const f=n.on.operationClose.subscribe(`waiting to set "${o.key}" at T-${l}`,()=>{f(),n.logger.info("\uD83D\uDFE2",o.type,o.key,`resuming deferred setState from T-${l}`),I(n,o,r)});return}const m=C(o,n);Ve(m,r,n),at(n)}function he(n,e,o){const{key:t,newValue:i,oldValue:r}=e,l=n==="newValue"?i:r,m={key:t,type:"atom"};if(e.family)Object.assign(m,{family:e.family});I(o,m,l)}function Mo(n,e,o){const t=J(o);try{const i=[];let r;if(e==="root")i.push(n.molecules.get('"root"')),r="all";else if(e[0][0]===gt){r="any";const c=J(e),T=n.molecules.get(c);if(!T)throw new Error(`Molecule ${c} not found in store "${n.config.name}"`);i.push(T)}else if(o[0][0]===gt){r="all";for(let T of e){const F=J(T),u=n.molecules.get(F);if(!u)throw new Error(`Molecule ${F} not found in store "${n.config.name}"`);i.push(u)}}else{r="any";const T=J(e),F=n.molecules.get(T);if(!F)throw new Error(`Molecule ${T} not found in store "${n.config.name}"`);i.push(F)}const l=new Zn(i,o);l._dependsOn=r,n.molecules.set(t,l);for(let c of i)c.below.set(l.stringKey,l);const m={type:"molecule_creation",subType:"modern",key:l.key,provenance:e},f=S(n);if(_(f)&&f.transactionMeta.phase==="building")f.transactionMeta.update.updates.push(m);else f.on.moleculeCreationStart.next(m)}catch(i){if(i instanceof Error)n.logger.error("\u274C","molecule",t,"allocation failed:",i.message)}return o}function Oe(n,e){const o=J(e),t=n.molecules.get(o);if(!t)throw new Error(`Molecule ${o} not found in store "${n.config.name}"`);for(let y of t.joins.values())y.relations.delete(t.key),y.molecules.delete(t.stringKey);let i;if(t.above.size===1)i=t.above.values().next().value.key;else i=[...t.above.values()].map(({key:y})=>y);const r=[];for(let y of t.tokens.values()){const c=y.family;r.push([c.key,n.valueMap.get(y.key)])}for(let y of t.tokens.values())on(n,y);for(let y of t.below.values())if(y.dependsOn==="all")Oe(n,y.key);else if(y.above.delete(t.stringKey),y.above.size===0)Oe(n,y.key);t.below.clear();const l={type:"molecule_disposal",subType:"modern",key:t.key,values:r,provenance:i},m=S(n);if(_(m)&&m.transactionMeta.phase==="building")m.transactionMeta.update.updates.push(l);else m.on.moleculeDisposal.next(l);m.molecules.delete(t.stringKey);for(let y of t.above.values())y.below.delete(t.stringKey)}var hm=Symbol("provenance"),gt="T$";function Jt(n,e){const o=new W,t={type:"molecule_family",key:e.key,dependsOn:e.dependsOn??"all"},i={...t,subject:o,new:e.new};return n.moleculeFamilies.set(e.key,i),t}function An(n,e,o){const t=xn(o,e,n.key);n.tokens.set(t.key,t);const i=_(o)&&o.transactionMeta.phase==="building",r=o.moleculeInProgress===n.key;if(!i&&!r)n.subject.next({type:"state_creation",token:t});return t}class v extends Set{mode="record";subject=new W;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(n,e=0){super(n);if(n instanceof v)this.parent=n,this.cacheUpdateNumber=n.cacheUpdateNumber;if(e)this.cacheLimit=e,this.cache=new Array(e),this.subscribe("auto cache",(o)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=o})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(n){const e=new v(n.members,n.cacheLimit);return e.cache=n.cache,e.cacheIdx=n.cacheIdx,e.cacheUpdateNumber=n.cacheUpdateNumber,e}add(n){const e=super.add(n);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${J(n)}`);return e}clear(){const n=this.mode==="record"?[...this]:null;if(super.clear(),n)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(n)}`)}delete(n){const e=super.delete(n);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${J(n)}`);return e}parent;child=null;transactionUpdates=null;transaction(n){this.mode="transaction",this.transactionUpdates=[],this.child=new v(this);const e=this.child._subscribe("transaction",(o)=>{this.transactionUpdates?.push(o)});try{if(n(this.child)){for(let t of this.transactionUpdates)this.doStep(t);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(o){throw console.error("Failed to apply transaction to SetRTX:",o),o}finally{e(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(n,e){return this.subject.subscribe(n,e)}subscribe(n,e){return this.subject.subscribe(n,(o)=>{e(`${this.cacheUpdateNumber}=${o}`)})}emit(n){this.subject.next(n)}doStep(n){const e=n.indexOf(":"),o=n.substring(0,e),t=n.substring(e+1);switch(o){case"add":this.add(JSON.parse(t));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(t));break;case"tx":for(let i of t.split(";"))this.doStep(i)}}getUpdateNumber(n){const e=n.indexOf("=");return Number(n.substring(0,e))}do(n){const e=n.indexOf("="),o=Number(n.substring(0,e)),t=o-this.cacheUpdateNumber;if(t>0){if(t===1){this.mode="playback";const r=n.substring(e+1);return this.doStep(r),this.mode="record",this.cacheUpdateNumber=o,null}return this.cacheUpdateNumber+1}if(Math.abs(t)<this.cacheLimit){const r=this.cacheIdx+t;if(this.cache[r]===n)return null;this.mode="playback";let m=!1;while(!m){this.cacheIdx%=this.cacheLimit;const y=this.cache[this.cacheIdx];if(this.cacheIdx--,!y)return"OUT_OF_RANGE";this.undo(y),m=this.cacheIdx===r-1}const f=n.substring(e+1);return this.doStep(f),this.mode="record",this.cacheUpdateNumber=o,null}return"OUT_OF_RANGE"}undoStep(n){const e=n.indexOf(":"),o=n.substring(0,e),t=n.substring(e+1);switch(o){case"add":this.delete(JSON.parse(t));break;case"del":this.add(JSON.parse(t));break;case"clear":{const i=JSON.parse(t);for(let r of i)this.add(r);break}case"tx":{const i=t.split(";");for(let r=i.length-1;r>=0;r--)this.undoStep(i[r])}}}undo(n){const e=n.indexOf("=");if(Number(n.substring(0,e))===this.cacheUpdateNumber){this.mode="playback";const t=n.substring(e+1);return this.undoStep(t),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function U(n){return n[0].toUpperCase()+n.slice(1)}function De(n,e,o=X.STORE){return Ro(o).set(n.key,new Fo(n,e,o)),{key:n.key,type:"join",a:n.between[0],b:n.between[1],cardinality:n.cardinality}}function Ro(n){if("joins"in n&&n.joins instanceof Map)return n.joins;const e=new Map;return n.joins=e,e}function We(n,e){const o=Ro(e);let t=o.get(n.key);if(t===void 0){if(t=Ro(X.STORE).get(n.key)?.in(e),t===void 0)throw new Error(`Join "${n.key}" not found in store "${e.config.name}"`);o.set(n.key,t)}return t}function $t(n,e,o){const t=We(n,o);let i;switch(n.cardinality){case"1:1":{const r=`${n.a}KeyOf${U(n.b)}`,l=`${n.b}KeyOf${U(n.a)}`;i={get[r](){const f=t.states[r];return t.retrieve(f,e)},get[l](){const f=t.states[l];return t.retrieve(f,e)}};const m=`${n.a}EntryOf${U(n.b)}`;if(m in t.states){const f=`${n.b}EntryOf${U(n.a)}`;Object.assign(i,{get[m](){const y=t.states[m];return t.retrieve(y,e)},get[f](){const y=t.states[f];return t.retrieve(y,e)}})}break}case"1:n":{const r=`${n.a}KeyOf${U(n.b)}`,l=`${n.b}KeysOf${U(n.a)}`;i={get[r](){const f=t.states[r];return t.retrieve(f,e)},get[l](){const f=t.states[l];return t.retrieve(f,e)}};const m=`${n.a}EntryOf${U(n.b)}`;if(m in t.states){const f=`${n.b}EntriesOf${U(n.a)}`;Object.assign(i,{get[m](){const y=t.states[m];return t.retrieve(y,e)},get[f](){const y=t.states[f];return t.retrieve(y,e)}})}break}case"n:n":{const r=`${n.a}KeysOf${U(n.b)}`,l=`${n.b}KeysOf${U(n.a)}`;i={get[r](){const f=t.states[r];return t.retrieve(f,e)},get[l](){const f=t.states[l];return t.retrieve(f,e)}};const m=`${n.a}EntriesOf${U(n.b)}`;if(m in t.states){const f=`${n.b}EntriesOf${U(n.a)}`;Object.assign(i,{get[m](){const y=t.states[m];return t.retrieve(y,e)},get[f](){const y=t.states[f];return t.retrieve(y,e)}})}}}return i}function Kt(n,e){return $t(n,e,X.STORE)}function Ie(n,e,o){const t=We(n,o),i=S(o);if(_(i)){const{toolkit:r}=i.transactionMeta;t.transact(r,({relations:l})=>{e(l)})}else e(t.relations)}function Ji(n,e){return We(n,e).core.findRelatedKeysState}function wt(n){return Ji(n,X.STORE)}class Fo{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(n,e){const o=this.toolkit;this.toolkit=n,e(this),this.toolkit=o}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(n){const e=n.config.name,o=this.alternates.get(e);if(o)return o;const t=new Fo(this.options,this.defaultContent,n);return this.alternates.set(e,t),t.alternates=this.alternates,t}constructor(n,e,o=X.STORE){this.store=o,this.options=n,this.defaultContent=e,this.alternates=new Map,this.alternates.set(o.config.name,this),this.store.miscResources.set(`join:${n.key}`,this),this.retrieve=(M,k)=>{const g=this.toolkit.seek(M,k);if(g)return g;const B=this.molecules.get(J(k));if(B){const j=C(M,o);return An(B,j,o)}if(o.config.lifespan==="immortal")throw new mn(M,k,o);return xn(o,M,k)},this.toolkit={get:(...M)=>V(o,...M),set:(...M)=>{I(o,...M)},find:this.retrieve,seek:(...M)=>L(o,...M),json:(M)=>Z(o,M),dispose:(...M)=>{on(o,...M)}};const t=n.between[0],i=n.between[1],r=ge(o,{key:`${n.key}/relatedKeys`,default:()=>new v,mutable:!0,fromJson:(M)=>v.fromJSON(M),toJson:(M)=>M.toJSON()},["join","relations"]);this.core={findRelatedKeysState:r};const l=({get:M},k)=>M(this.retrieve(r,k)),m=(M,k,g)=>{const{set:B}=M,j=this.retrieve(r,k),w=this.retrieve(r,g);B(j,(z)=>z.add(g)),B(w,(z)=>z.add(k))},f=(M,k,g)=>{const{set:B}=M,j=this.retrieve(r,k),w=this.retrieve(r,g);let z,Q;B(j,(N)=>{if(N.delete(g),N.size===0)z=`"${k}"`;return N}),B(w,(N)=>{if(N.delete(k),N.size===0)Q=`"${g}"`;return N})},y=(M,k,g)=>{const{get:B,set:j}=M,w=this.retrieve(r,k),z=B(w);for(let Q of z){if(g.includes(Q))continue;const zn=this.retrieve(r,Q);j(zn,(Kn)=>{return Kn.delete(k),Kn})}j(w,(Q)=>{return Q.transaction((N)=>{N.clear();for(let zn of g){const Kn=l(M,zn),Zo=Kn.has(k);if(this.relations.cardinality==="1:n"){const nt=[];for(let Re of Kn){if(Re===k)continue;const Ae=l(M,Re);if(Ae.delete(zn),Ae.size===0)nt.push(Re)}if(!Zo&&Kn.size>0)Kn.clear();for(let Re of nt){const Ae=[zn,Re].sort(),ai=`"${Ae[0]}:${Ae[1]}"`;this.molecules.delete(ai)}}if(!Zo)Kn.add(k);N.add(zn)}return!0}),Q})},c=(M,k,g)=>{const{set:B}=M,j=this.retrieve(r,k);B(j,(w)=>{return w.transaction((z)=>{for(let Q of g)z.add(Q);return!0}),w});for(let w of g){const z=this.retrieve(r,w);B(z,(Q)=>{return Q.add(k),Q})}return!0},T=(M,k,g)=>{const B=l(M,k);return g?B.has(g):B.size>0},F={getRelatedKeys:(M)=>l(this.toolkit,M),addRelation:(M,k)=>{m(this.toolkit,M,k)},deleteRelation:(M,k)=>{f(this.toolkit,M,k)},replaceRelationsSafely:(M,k)=>{y(this.toolkit,M,k)},replaceRelationsUnsafely:(M,k)=>{c(this.toolkit,M,k)},has:(M,k)=>T(this.toolkit,M,k)};let u,G,Sn;if(e){G=wn(o,{key:`${n.key}/content`,default:e},["join","content"]);const M={key:n.key,type:"join",a:n.between[0],b:n.between[1],cardinality:n.cardinality};Sn=Jt(o,{key:`${n.key}/content-molecules`,new:class w{Q;constructor(z,Q){this.key=Q}}});const k=({get:w},z)=>w(this.retrieve(G,z)),g=({set:w},z,Q)=>{w(this.retrieve(G,z),Q)},B=(w,z)=>{const Q=o.molecules.get(`"${z}"`);if(Q)this.toolkit.dispose(Q),this.molecules.delete(`"${z}"`)};u=Object.assign(F,{getContent:(w)=>{return k(this.toolkit,w)},setContent:(w,z)=>{g(this.toolkit,w,z)},deleteContent:(w)=>{B(this.toolkit,w)}})}else u=F;const O=new yn(n,{externalStore:u,makeContentKey:(...M)=>{const k=M.sort(),g=`${k[0]}:${k[1]}`,[B,j]=k.map((w)=>this.molecules.get(J(w)));if(o.config.lifespan==="immortal"&&B&&j){const w=S(o),z=sn(w,[B,j],Sn,g);this.molecules.set(`"${g}"`,C(z,w))}return g}}),E=()=>Wn(o,{key:`${n.key}/singleRelatedKey`,get:(M)=>({get:k})=>{const g=this.retrieve(r,M),B=k(g);for(let j of B)return j;return null}},["join","keys"]),p=()=>{return Wn(o,{key:`${n.key}/multipleRelatedKeys`,get:(M)=>({get:k})=>{const g=Ao(r,o),B=this.retrieve(g,M);return k(B).members}},["join","keys"])},q=()=>Wn(o,{key:`${n.key}/singleRelatedEntry`,get:(M)=>({get:k})=>{const g=this.retrieve(r,M),B=k(g);for(let j of B){const w=O.makeContentKey(M,j),z=this.retrieve(G,w),Q=k(z);return[j,Q]}return null}},["join","entries"]),fn=()=>Wn(o,{key:`${n.key}/multipleRelatedEntries`,get:(M)=>({get:k})=>{const g=Ao(r,o),B=this.retrieve(g,M);return k(B).members.map((w)=>{const z=O.makeContentKey(M,w),Q=this.retrieve(G,z),N=k(Q);return[w,N]})}},["join","entries"]);switch(n.cardinality){case"1:1":{const M=E(),k=`${t}KeyOf${U(i)}`,g=`${i}KeyOf${U(t)}`,B={[k]:M,[g]:M};let j;if(e){const w=q(),z=`${t}EntryOf${U(i)}`,Q=`${i}EntryOf${U(t)}`,N={[z]:w,[Q]:w};j=Object.assign(B,N)}else j=B;this.relations=O,this.states=j;break}case"1:n":{const M=E(),k=p(),g=`${t}KeyOf${U(i)}`,B=`${i}KeysOf${U(t)}`,j={[g]:M,[B]:k};let w;if(e){const z=q(),Q=fn(),N=`${t}EntryOf${U(i)}`,zn=`${i}EntriesOf${U(t)}`,Kn={[N]:z,[zn]:Q};w=Object.assign(j,Kn)}else w=j;this.relations=O,this.states=w;break}default:{const M=p(),k=`${t}KeysOf${U(i)}`,g=`${i}KeysOf${U(t)}`,B={[k]:M,[g]:M};let j;if(e){const w=fn(),z=`${t}EntriesOf${U(i)}`,Q=`${i}EntriesOf${U(t)}`,N={[z]:w,[Q]:w};j=Object.assign(B,N)}else j=B;this.relations=O,this.states=j}}}}function Ne(n){return{store:n}}function V(n,...e){let o,t,i;if(e.length===1){if(o=e[0],o.type!=="molecule"){if(t=Ue(n,o)??null,t)i=o.family?D(o.family.subKey):null,o=Y(n,t,i)}}else{t=e[0],i=e[1];let r;if(t.type==="molecule_family")r=L(n,t,i)??vn(t,i);else r=Y(n,t,i);o=r}if("counterfeit"in o&&"family"in o){t=o.type==="molecule"?C(o.family,n):n.families.get(o.family.key);const r=o.type==="molecule"?o.key:o.family.subKey,l=n.disposalTraces.buffer.find((m)=>m?.key===o.key);switch(n.logger.error("\u274C",o.type,o.key,`could not be retrieved because it was not found in the store "${n.config.name}".`,l?`This state was previously disposed:\n${l.trace}`:"No previous disposal trace was found."),t.type){case"atom_family":case"mutable_atom_family":return n.defaults.get(t.key);case"selector_family":case"readonly_selector_family":{if(n.defaults.has(t.key))return n.defaults.get(o.family.key);const m=C(t,n).default(r);return n.defaults.set(t.key,m),m}case"molecule_family":throw new mn(t,r,n)}}switch(o.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return Xn(C(o,n),n);case"molecule":return C(o,n).instance}}class Zn{e;type="molecule";stringKey;family;_dependsOn;get dependsOn(){if(this.family)return this.family.dependsOn;return this._dependsOn}subject=new W;tokens=new Map;above=new Map;below=new Map;joins=new Map;instance;constructor(n,e,o){this.key=e;if(this.stringKey=J(e),o)this.family=o,this._dependsOn=o.dependsOn;if(n)for(let t of n)this.above.set(t.stringKey,t)}}function Ct(n){return n[0].toUpperCase()+n.slice(1)}function sn(n,e,o,t,...i){const r=it(n),l=S(n),m=J(t);l.moleculeInProgress=m;const f=Array.isArray(e)?e:[e],y=f.map((O)=>{if(O instanceof Zn)return O;const E=J(O.key),p=n.molecules.get(E);if(!p)throw new Error(`Molecule ${E} not found in store "${n.config.name}"`);return p}),c=new Zn(y,t,o);l.molecules.set(m,c);for(let O of y)O.below.set(c.stringKey,c);const T={get:(...O)=>V(S(r),...O),set:(...O)=>{I(S(r),...O)},seek:(O,E)=>L(S(r),O,E),json:(O)=>Z(S(r),O),run:(O,E=Nn())=>Vn(O,E,S(n)),make:(O,E,p,...q)=>sn(S(r),O,E,p,...q),dispose:(O)=>{on(S(r),O)},env:()=>Ne(S(r)),bond:(O,E)=>{if(O.type==="join"){const{as:p}=E,q=We(O,r);q.molecules.set(m,c),c.joins.set(O.key,q);const fn=F.subject.subscribe(`join:${O.key}-${m}`,(w)=>{if(w.type==="molecule_disposal"){if(J(w.token.key)===m)fn(),q.molecules.delete(m)}});if(p===null)return;const M=O.a===p?O.b:O.a,k=Kt(O,t),g=k[`${M}KeysOf${Ct(p)}`],B=k[`${M}EntriesOf${Ct(p)}`];let j={relatedKeys:g};if(B)j=Object.assign(j,{relatedEntries:B});return j}return An(c,C(O,r),S(r))},claim:(O,E)=>{const{exclusive:p}=E,q=S(n).molecules.get(J(O.key));if(q)if(p){for(let fn of q.above.values())fn.below.delete(q.stringKey);q.above.clear(),q.above.set(c.stringKey,c),c.below.set(q.stringKey,q)}else q.above.set(c.stringKey,c),c.below.set(q.stringKey,q)},spawn:(O,E,...p)=>sn(S(n),[c],C(O,n),E,...p)},F=C(o,n),u=F.new;c.instance=new u(T,t,...i);const G={type:"molecule",key:t,family:o},Sn={type:"molecule_creation",subType:"classic",token:G,family:o,context:f,params:i};if(d(l))F.subject.next(Sn);else if(_(l)&&l.on.transactionApplying.state===null)l.transactionMeta.update.updates.push(Sn);return l.moleculeInProgress=null,G}function go(n,e,o){switch(e){case"newValue":{Ot(n,o);break}case"oldValue":{on(o,n.token);break}}}function Jo(n,e,o){switch(e){case"newValue":{on(o,n.token);break}case"oldValue":{Ot(n,o),o.valueMap.set(n.token.key,n.value);break}}}function Ot(n,e){const{family:o}=n.token;if(o){const t=e.families.get(o.key);if(t)Y(e,t,D(o.subKey))}}function $o(n,e,o){switch(e){case"newValue":switch(n.subType){case"classic":sn(o,n.context,n.family,n.token.key,...n.params);break;case"modern":Mo(o,n.provenance,n.key);break}break;case"oldValue":switch(n.subType){case"classic":on(o,n.token);break;case"modern":Oe(o,n.key);break}break}}function Ko(n,e,o){switch(e){case"newValue":switch(n.subType){case"classic":on(o,n.token);break;case"modern":Oe(o,n.key);break}break;case"oldValue":switch(n.subType){case"classic":{const t=sn(o,n.context,n.family,n.token.key);for(let[i,r]of n.values){const l=`${i}(${J(t.key)})`,m=C(t,o),f=m.tokens.has(l),y=o.families.get(i);if(y&&!f)An(m,y,o);o.valueMap.set(l,r)}}break;case"modern":{Mo(o,n.provenance,n.key);for(let[t,i]of n.values){const r=o.families.get(t);if(r){Y(o,r,n.key);const l=`${t}(${J(n.key)})`;o.valueMap.set(l,i)}}}}break}}function ve(n,e,o){const t=n==="newValue"?e.updates:[...e.updates].reverse();for(let i of t)switch(i.type){case"atom_update":case"selector_update":he(n,i,o);break;case"state_creation":go(i,n,o);break;case"state_disposal":Jo(i,n,o);break;case"molecule_creation":$o(i,n,o);break;case"molecule_disposal":Ko(i,n,o);break;case"transaction_update":ve(n,i,o);break}}function Wt(n,e,o){if(!d(o))return;const i=o.transactionMeta.actionContinuities.getRelatedKey(n);if(i!==void 0)o.transactionMeta.epoch.set(i,e)}var xt=(n,e)=>{const o=S(e),{parent:t}=o;if(t===null||!_(o)||o.transactionMeta?.phase!=="building"){e.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}o.transactionMeta.phase="applying",o.transactionMeta.update.output=n,t.child=null,t.on.transactionApplying.next(o.transactionMeta);const{updates:i}=o.transactionMeta.update;if(e.logger.info("\uD83D\uDEC4","transaction",o.transactionMeta.update.key,`Applying transaction with ${i.length} updates:`,i),ve("newValue",o.transactionMeta.update,t),d(t))Wt(o.transactionMeta.update.key,o.transactionMeta.update.epoch,t),C({key:o.transactionMeta.update.key,type:"transaction"},e)?.subject.next(o.transactionMeta.update),e.logger.info("\uD83D\uDEEC","transaction",o.transactionMeta.update.key,"Finished applying transaction.");else if(_(t))t.transactionMeta.update.updates.push(o.transactionMeta.update);t.on.transactionApplying.next(null)};class kn extends Map{n;deleted=new Set;constructor(n){super();this.source=n}get(n){if(super.has(n))return super.get(n);if(!this.deleted.has(n)&&this.source.has(n))return this.source.get(n);return}set(n,e){return this.deleted.delete(n),super.set(n,e)}hasOwn(n){return super.has(n)}has(n){return!this.deleted.has(n)&&(super.has(n)||this.source.has(n))}delete(n){return this.deleted.add(n),super.delete(n)}}var st=(n,e,o,t)=>{const i=S(o),r={parent:i,child:null,on:i.on,loggers:i.loggers,logger:i.logger,config:i.config,atoms:new kn(i.atoms),atomsThatAreDefault:new Set(i.atomsThatAreDefault),families:new kn(i.families),operation:{open:!1},readonlySelectors:new kn(i.readonlySelectors),timelines:new kn(i.timelines),timelineTopics:new yn(i.timelineTopics.toJSON()),trackers:new Map,transactions:new kn(i.transactions),selectorAtoms:new yn(i.selectorAtoms.toJSON()),selectorGraph:new yn(i.selectorGraph.toJSON(),{makeContentKey:(...y)=>y.sort().join(":")}),selectors:new kn(i.selectors),valueMap:new kn(i.valueMap),defaults:i.defaults,disposalTraces:o.disposalTraces.copy(),molecules:new kn(i.molecules),moleculeFamilies:new kn(i.moleculeFamilies),moleculeInProgress:i.moleculeInProgress,miscResources:new kn(i.miscResources)},l=Bt(n,o),m={phase:"building",update:{type:"transaction_update",key:n,id:t,epoch:l===void 0?Number.NaN:l+1,updates:[],params:e,output:void 0},toolkit:{get:(...y)=>V(f,...y),set:(...y)=>{I(f,...y)},run:(y,c=Nn())=>Vn(y,c,f),find:(y,c)=>Y(f,y,c),seek:(y,c)=>L(f,y,c),json:(y)=>Z(f,y),make:(y,c,T,...F)=>sn(f,y,c,T,...F),dispose:(...y)=>{on(f,...y)},env:()=>Ne(f)}},f=Object.assign(r,{transactionMeta:m});return i.child=f,o.logger.info("\uD83D\uDEEB","transaction",n,"Building transaction with params:",e),f};function ko(n,e){const o={key:n.key,type:"transaction",run:(r,l)=>{const m=st(n.key,r,e,l);try{const f=S(e),{toolkit:y}=m.transactionMeta,c=n.do(y,...r);return xt(c,f),c}catch(f){throw ft(t),e.logger.warn("\uD83D\uDCA5","transaction",n.key,"caught:",f),f}},install:(r)=>ko(n,r),subject:new W},t=S(e);t.transactions.set(o.key,o);const i=nn(o);return e.on.transactionCreation.next(i),i}function Bt(n,e){const o=d(e),t=o?e.transactionMeta.actionContinuities.getRelatedKey(n):void 0;return o&&t!==void 0?e.transactionMeta.epoch.get(t):void 0}class Pe{_buffer;_index=0;constructor(n){let e;if(typeof n==="number")e=n;else e=n.length;this._buffer=Array.from({length:e})}get buffer(){return this._buffer}get index(){return this._index}add(n){this._buffer[this._index]=n,this._index=(this._index+1)%this._buffer.length}copy(){const n=new Pe([...this._buffer]);return n._index=this._index,n}}class ut{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new yn({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new yn({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...n)=>n.sort().join(":")});trackers=new Map;families=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new yn({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new yn({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new Pe(100);molecules=new Map;moleculeFamilies=new Map;moleculeInProgress=null;miscResources=new Map;on={atomCreation:new W,atomDisposal:new W,selectorCreation:new W,selectorDisposal:new W,timelineCreation:new W,transactionCreation:new W,transactionApplying:new co(null),operationClose:new W,moleculeCreationStart:new W,moleculeCreationDone:new W,moleculeDisposal:new W};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new To("warn",(n,e,o)=>!o.includes("\uD83D\uDD0D"))];logger={error:(...n)=>{for(let e of this.loggers)e.error(...n)},info:(...n)=>{for(let e of this.loggers)e.info(...n)},warn:(...n)=>{for(let e of this.loggers)e.warn(...n)}};constructor(n,e=null){if(this.config={...e?.config,...n},e!==null){if(this.valueMap=new Map(e?.valueMap),this.operation={...e?.operation},d(e))this.transactionMeta={epoch:new Map(e?.transactionMeta.epoch),actionContinuities:new yn(e?.transactionMeta.actionContinuities.toJSON())};for(let[,t]of e.families){if(t.internalRoles?.includes("mutable")||t.internalRoles?.includes("join"))continue;t.install(this)}const o=new Set;for(let[,t]of e.atoms){if(o.has(t.key))continue;if(t.install(this),t.type==="mutable_atom"){const i=Z(e,t),r=Hn(t);o.add(i.key),o.add(r.key)}}for(let[,t]of e.readonlySelectors)t.install(this);for(let[,t]of e.selectors){if(o.has(t.key))continue;t.install(this)}for(let[,t]of e.transactions)t.install(this);for(let[,t]of e.timelines)t.install(this)}}}var X={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new ut({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function C(n,e){let o,t=e;while(t!==null){switch(n.type){case"atom":case"mutable_atom":o=t.atoms.get(n.key);break;case"selector":o=t.selectors.get(n.key);break;case"readonly_selector":o=t.readonlySelectors.get(n.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":o=t.families.get(n.key);break;case"timeline":o=t.timelines.get(n.key);break;case"transaction":o=t.transactions.get(n.key);break;case"molecule":o=t.molecules.get(J(n.key));break;case"molecule_family":o=t.moleculeFamilies.get(n.key);break}if(o)return o;t=t.child}throw new mn(n,e)}function de(n,e){let o;o=C(n,e);const{family:t}=n;for(let l of o.joins.values())l.relations.delete(o.key),l.molecules.delete(o.stringKey);const i=[];for(let l of o.above.values())i.push(nn(l));const r=[];for(let l of o.tokens.values()){const m=l.family;r.push([m.key,e.valueMap.get(l.key)])}if(t){const l=C(t,e),m={type:"molecule_disposal",subType:"classic",token:n,family:t,context:i,values:r};if(n.family)m.family=n.family;for(let y of o.tokens.values())on(e,y);for(let y of o.below.values())if(y.dependsOn==="all")de(y,e);else if(y.above.delete(o.stringKey),y.above.size===0)de(y,e);if(o.below.clear(),_(e)&&e.transactionMeta.phase==="building")e.transactionMeta.update.updates.push(m);else l.subject.next(m);e.molecules.delete(o.stringKey)}for(let l of o.above.values())l.below.delete(o.stringKey)}function xn(n,e,o){const t=n.families.get(e.key);if(t===void 0)throw new mn(e,n);const i=t(o),r=S(n);if(i.family&&r.moleculeInProgress===null){if(d(r))switch(i.type){case"atom":case"mutable_atom":n.on.atomCreation.next(i);break;case"selector":case"readonly_selector":n.on.selectorCreation.next(i);break}else if(_(r)&&r.on.transactionApplying.state===null)r.transactionMeta.update.updates.push({type:"state_creation",token:i})}return i}function L(n,e,o){const t=J(o),i=`${e.key}(${t})`,r=S(n);let l;switch(e.type){case"atom_family":case"mutable_atom_family":l=r.atoms.get(i);break;case"selector_family":l=r.selectors.get(i);break;case"readonly_selector_family":l=r.readonlySelectors.get(i);break;case"molecule_family":l=r.molecules.get(J(o))}if(l)return nn(l);return l}function Y(n,e,o){let t=L(n,e,o);if(t)return t;const i=n.molecules.get(J(o));if(i)return An(i,e,n);if(n.config.lifespan==="immortal"){const r=vn(e,o);return n.logger.error("\u274C",r.type,r.key,`was not found in store "${n.config.name}"; returned a counterfeit token.`),r}return t=xn(n,e,o),t}function on(n,...e){let o,t;if(e.length===1)o=e[0],t=o.key;else{const r=e[0],l=e[1];o=r.type==="molecule_family"?L(n,r,l)??vn(r,l):Y(n,r,l)}try{C(o,n)}catch(r){const l=n.disposalTraces.buffer.find((m)=>m?.key===o.key);n.logger.error("\u274C",o.type,o.key,`could not be disposed because it was not found in the store "${n.config.name}".`,l?`\n This state was most recently disposed\n${l.trace}`:"No previous disposal trace was found.");return}switch(o.type){case"atom":case"mutable_atom":wo(o,n);break;case"selector":case"readonly_selector":jt(o,n);break;case"molecule":de(o,n);break}const{stack:i}=new Error;if(i){const r=i?.split("\n")?.slice(3)?.join("\n");n.disposalTraces.add({key:o.key,trace:r})}}var Ze=(n,e)=>S(e).atoms.has(n),$i=(n,e)=>S(e).selectors.has(n),Ki=(n,e)=>S(e).readonlySelectors.has(n),_t=(n,e)=>Ze(n,e)||$i(n,e)||Ki(n,e);var no=(n,e)=>{return S(e).selectorGraph.getRelationEntries({downstreamSelectorKey:n}).filter(([t,{source:i}])=>i!==n).map(([t,{source:i}])=>i).filter((t)=>_t(t,e))};var Co=(n,e,o)=>{const t=[],i=no(n,o);while(i.length>0){const r=i.shift();if(e.has(r))continue;if(e.add(r),!Ze(r,o))i.push(...no(r,o));else if(!t.includes(r))t.push(r)}return t},zt=(n,e)=>{const o=n.key,t=no(o,e),i=new Set;return t.flatMap((r)=>Ze(r,e)?r:Co(r,i,e))};var Xt=(n,e,o,t)=>{const i=S(t);if(e.type==="atom"||e.type==="mutable_atom")i.selectorAtoms.set({selectorKey:n,atomKey:e.key}),t.logger.info("\uD83D\uDD0D","selector",n,`discovers root atom "${e.key}"`);else{const r=Co(e.key,o,t);t.logger.info("\uD83D\uDD0D","selector",n,`discovers root atoms: [ ${r.map((l)=>`"${l}"`).join(", ")} ]`);for(let l of r)i.selectorAtoms=i.selectorAtoms.set({selectorKey:n,atomKey:l})}o.add(e.key)};var eo=(n,e,o)=>({get:(...t)=>{const i=S(o);let r;if(t.length===2){const[f,y]=t;switch(f.type){case"molecule_family":return V(o,f,y);default:if(o.config.lifespan==="ephemeral")r=Y(o,f,y);else{const c=L(o,f,y);if(c)r=c;else throw new mn(f,y,o)}}}else[r]=t;if(r.type==="molecule")return V(o,r);const l=C(r,o),m=Xn(l,o);return o.logger.info("\uD83D\uDD0C","selector",n,`registers dependency ( "${r.key}" =`,m,")"),i.selectorGraph.set({upstreamSelectorKey:r.key,downstreamSelectorKey:n},{source:r.key}),Xt(n,r,e,o),m},set:(...t)=>{let i,r;if(t.length===2)i=t[0],r=t[1];else{const f=t[0],y=t[1];r=t[2];const c=o.config.lifespan==="ephemeral"?Y(o,f,y):L(o,f,y);if(!c)throw new mn(f,y,o);i=c}const l=S(o),m=C(i,l);Ve(m,r,l)},find:(t,i)=>Y(o,t,i),seek:(t,i)=>L(o,t,i),json:(t)=>Z(o,t)});var Je=(n,e,o)=>{const t=S(n),i=new W,r=new Set,{get:l,find:m,seek:f,json:y}=eo(e.key,r,t),c=()=>{const G=e.get({get:l,find:m,seek:f,json:y});return Tn(e.key,G,i,S(n)),r.clear(),G},T={...e,subject:i,install:(G)=>Je(G,e,o),get:c,type:"readonly_selector",...o&&{family:o}};t.readonlySelectors.set(e.key,T);const F=c();n.logger.info("\u2728",T.type,T.key,"=",F);const u={key:e.key,type:"readonly_selector"};if(o)u.family=o;return u};var xe=(n,e,o)=>{const t=S(n),i=new W,r=new Set,l=eo(e.key,r,t),{find:m,get:f,seek:y,json:c}=l,T={find:m,get:f,seek:y,json:c},F=(E=e.get,p=S(n))=>{const q=E(T);return Tn(e.key,q,i,p),r.clear(),q},G={...e,subject:i,install:(E)=>xe(E,e,o),get:F,set:(E)=>{const p=S(n),q=F(e.get,p),fn=Le(E)(q);if(n.logger.info("\uD83D\uDCDD","selector",e.key,"set (",q,"->",fn,")"),Tn(e.key,fn,i,p),dn(p,e.key),d(p))i.next({newValue:fn,oldValue:q});e.set(l,fn)},type:"selector",...o&&{family:o}};t.selectors.set(e.key,G);const Sn=F();n.logger.info("\u2728",G.type,G.key,"=",Sn);const O={key:e.key,type:"selector"};if(o)O.family=o;return O};function Mn(n,e){if("set"in e){const i=xe(n,e,void 0);return n.on.selectorCreation.next(i),i}const t=Je(n,e,void 0);return n.on.selectorCreation.next(t),t}function jt(n,e){const o=S(e),{key:t}=n,i=C(n,o);if(!i.family)e.logger.error("\u274C","selector",t,"Standalone selectors cannot be disposed.");else{const r=o.molecules.get(i.family.subKey);if(r)r.tokens.delete(t);switch(n.type){case"selector":o.selectors.delete(t),C({key:i.family.key,type:"selector_family"},e).subject.next({type:"state_disposal",token:n});break;case"readonly_selector":o.readonlySelectors.delete(t),C({key:i.family.key,type:"readonly_selector_family"},e).subject.next({type:"state_disposal",token:n});break}if(o.valueMap.delete(t),o.selectorAtoms.delete(t),o.selectorGraph.delete(t),e.logger.info("\uD83D\uDD25",n.type,t,"deleted"),_(o)&&o.transactionMeta.phase==="building")o.transactionMeta.update.updates.push({type:"state_disposal",token:n});else e.on.selectorDisposal.next(n)}}function Ke(n,e,o){const t={key:e.key,type:"selector_family"},i=n.families.get(e.key);if(i)n.logger.error("\u2757","selector_family",e.key,`Overwriting an existing ${Rn(i)} "${i.key}" in store "${n.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new W,m=Object.assign((f)=>{const y=J(f),c={key:e.key,subKey:y},T=`${e.key}(${y})`,F=S(n),u=xe(F,{key:T,get:e.get(f),set:e.set(f)},c);return r.next({type:"state_creation",token:u}),u},t,{internalRoles:o,subject:r,install:(f)=>Ke(f,e),default:(f)=>{return e.get(f)({get:(...c)=>V(n,...c),find:(c,T)=>Y(n,c,T),seek:(c,T)=>L(n,c,T),json:(c)=>Z(n,c)})}});return n.families.set(e.key,m),t}function Ht(n,e,o=X.STORE){const t=Ke(o,{key:`${n.key}:JSON`,get:(r)=>({seek:l,get:m})=>{const f=l(n,r);if(f)return e.toJson(m(f));const y=J(r),c=o.molecules.get(y);if(c){const F=An(c,n,o);return e.toJson(m(F))}if(o.config.lifespan==="immortal")throw new Error(`No molecule found for key "${y}"`);const T=xn(o,n,r);return e.toJson(m(T))},set:(r)=>({seek:l,set:m},f)=>{const y=l(n,r);if(y)m(y,e.fromJson(f));else{const c=J(r),T=o.molecules.get(c);if(T){const F=An(T,n,o);m(F,e.fromJson(f))}else{if(o.config.lifespan==="immortal")throw new Error(`No molecule found for key "${c}"`);m(xn(o,n,r),e.fromJson(f))}}}},["mutable","json"]);return C(n,o).subject.subscribe(`store=${o.config.name}::json-selector-family`,(r)=>{if(r.token.family)L(o,t,D(r.token.family.subKey))}),t}var D=(n)=>JSON.parse(n),J=(n)=>JSON.stringify(n),lS=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var qt=(n,e)=>{const o=S(e);if(o.operation.open)return o.operation.prev.get(n.key);return o.valueMap.get(n.key)};var Wo=(n,e)=>{const o=S(e);return zt(n,e).map((i)=>{const r=o.atoms.get(i);if(r===void 0)throw new Error(`Atom "${i}", a dependency of selector "${n.key}", not found in store "${e.config.name}".`);return r.subject.subscribe(`${n.type}:${n.key}`,(l)=>{e.logger.info("\uD83D\uDCE2",n.type,n.key,"root",i,"went",l.oldValue,"->",l.newValue);const m=qt(n,o),f=Xn(n,o);e.logger.info("\u2728",n.type,n.key,"went",m,"->",f),n.subject.next({newValue:f,oldValue:m})})})};function cn(n,e,o,t){function i(T){if(t.operation.open){const F=t.on.operationClose.subscribe(`state subscription ${o}`,()=>{F(),e(T)})}else e(T)}const r=C(n,t);t.logger.info("\uD83D\uDC40",r.type,r.key,`Adding subscription "${o}"`);const l=r.type==="selector"||r.type==="readonly_selector";let m=null,f=i;if(l)m=Wo(r,t),f=(T)=>{if(m)m.length=0,m.push(...Wo(r,t));i(T)};const y=r.subject.subscribe(o,f);return()=>{if(t.logger.info("\uD83D\uDE48",r.type,r.key,`Removing subscription "${o}"`),y(),m)for(let T of m)T()}}var Oo=(n,e,o,t)=>{const i=C(n,t);t.logger.info("\uD83D\uDC40","timeline",n.key,`Adding subscription "${o}"`);const r=i.subject.subscribe(o,e);return()=>{t.logger.info("\uD83D\uDE48","timeline",n.key,`Removing subscription "${o}" from timeline`),r()}};class qn{Update;initializeState(n,e){const o=`*${n.key}`;e.atoms.delete(o),e.valueMap.delete(o);const t=n.family?{key:`*${n.family.key}`,subKey:n.family.subKey}:void 0,i=ln(e,{key:o,default:null},t);if(e.parent?.valueMap.has(o)){const r=e.parent.valueMap.get(o);e.valueMap.set(o,r)}return i}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(n,e,o){const t=`tracker:${o.config.name}:${_(o)?o.transactionMeta.update.key:"main"}:${n.key}`,i=V(o,n);this.unsubscribeFromInnerValue=i.subscribe(t,(r)=>{I(o,e,r)}),this.unsubscribeFromState=cn(n,(r)=>{if(r.newValue!==r.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=r.newValue.subscribe(t,(l)=>{I(o,e,l)})},t,o)}updateCore(n,e,o){const t=`tracker:${o.config.name}:${_(o)?o.transactionMeta.update.key:"main"}:${n.key}`;cn(e,({newValue:i,oldValue:r})=>{const l=o.timelineTopics.getRelatedKey(e.key);if(l){if(o.timelines.get(l)?.timeTraveling){const y=Oo({key:l,type:"timeline"},(c)=>{y(),I(o,n,(T)=>{if(c==="redo"&&i)T.do(i);else if(c==="undo"&&r)T.undo(r);return T})},t,o);return}}const m=o.on.operationClose.subscribe(t,()=>{m();const f=V(o,n),y=i===null?-1:f.getUpdateNumber(i),c=y-f.cacheUpdateNumber;if(i&&c===1)I(o,n,(T)=>(T.do(i),T));else o.logger.info("\u274C","mutable_atom",n.key,`could not be updated. Expected update number ${f.cacheUpdateNumber+1}, but got ${y}`)})},t,o)}mutableState;latestUpdateState;dispose;constructor(n,e){this.mutableState=n;const o=S(e);this.latestUpdateState=this.initializeState(n,o),this.observeCore(n,this.latestUpdateState,o),this.updateCore(n,this.latestUpdateState,o),o.trackers.set(n.key,this),this.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),o.trackers.delete(n.key)}}}function se(n,e,o){n.logger.info("\uD83D\uDD28","atom",e.key,`creating in store "${n.config.name}"`);const t=S(n),i=t.atoms.get(e.key);if(i&&i.type==="mutable_atom")return n.logger.error("\u274C","atom",e.key,"Tried to create atom, but it already exists in the store."),nn(i);const r=new W,l={...e,type:"mutable_atom",install:(y)=>{return y.logger.info("\uD83D\uDEE0\uFE0F","atom",e.key,`installing in store "${y.config.name}"`),se(y,e,o)},subject:r};if(o)l.family=o;const m=e.default();t.atoms.set(l.key,l),oo(e.key,n),Tn(e.key,m,r,t);const f=nn(l);if(e.effects){let y=0;const c=[];for(let T of e.effects){const F=T({setSelf:(u)=>{I(n,f,u)},onSet:(u)=>cn(f,u,`effect[${y}]`,n)});if(F)c.push(F);++y}l.cleanup=()=>{for(let T of c)T()}}if(new qn(f,n),!o)tt(f,e,n);return f}class xo{Update;latestUpdateAtoms;mutableAtoms;constructor(n,e){const o=wn(e,{key:`*${n.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=C(o,e),this.mutableAtoms=n,this.mutableAtoms.subject.subscribe(`store=${e.config.name}::tracker-atom-family`,(t)=>{if(t.token.family){const i=D(t.token.family.subKey);L(e,this.latestUpdateAtoms,i),new qn(t.token,e)}}),this.latestUpdateAtoms.subject.subscribe(`store=${e.config.name}::tracker-atom-family`,(t)=>{if(t.token.family){const i=D(t.token.family.subKey),r=L(e,this.mutableAtoms,i);if(r)new qn(r,e)}})}}function ge(n,e,o){const t={key:e.key,type:"mutable_atom_family"},i=n.families.get(e.key);if(i)n.logger.error("\u2757","mutable_atom_family",e.key,`Overwriting an existing ${Rn(i)} "${i.key}" in store "${n.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const r=new W,m=Object.assign((f)=>{const y=J(f),c={key:e.key,subKey:y},T=`${e.key}(${y})`,F=S(n),u={key:T,default:()=>e.default(f),toJson:e.toJson,fromJson:e.fromJson,mutable:!0};if(e.effects)u.effects=e.effects(f);const G=se(F,u,c);return r.next({type:"state_creation",token:G}),G},t,{subject:r,install:(f)=>ge(f,e),toJson:e.toJson,fromJson:e.fromJson,internalRoles:o});return n.families.set(e.key,m),Ht(m,e,n),new xo(m,n),t}var Ao=(n,e)=>{const o=S(e),t=`${n.key}:JSON`;return o.families.get(t)};var Z=(n,e)=>{if(e.family){const t=S(n),r={key:`${e.family.key}:JSON`,type:"selector_family"},l=C(r,t),m=JSON.parse(e.family.subKey);return Y(n,l,m)}return{type:"selector",key:`${e.key}:JSON`}};var Hn=(n)=>{const o={type:"atom",key:`*${n.key}`};if(n.family)o.family={key:`*${n.family.key}`,subKey:n.family.subKey};return o};function Mt(n){return typeof n==="object"&&n!==null&&"do"in n&&"undo"in n&&"subscribe"in n}function Ce(n,e,o){const t=e.valueMap.get(n.key),i=o.valueMap.get(n.key);if(t===i){if(t===void 0)return typeof n.default==="function"?n.default():n.default;e.logger.info("\uD83D\uDCC3","atom",n.key,"copying");const r=n.toJson(t),l=n.fromJson(r);return o.valueMap.set(n.key,l),new qn(n,e),l}return i}function Tn(n,e,o,t){const i=t.valueMap.get(n);if(i instanceof Fe)i.use(e);if(e instanceof Promise){const r=new Fe(e);return t.valueMap.set(n,r),r.then((l)=>{Tn(n,l,o,t),o.next({newValue:l,oldValue:r})}).catch((l)=>{t.logger.error("\uD83D\uDCA5","state",n,"rejected:",l)}),r}return t.valueMap.set(n,e),e}var yt=(n,e)=>{let o=e.valueMap.get(n.key);if(n.type==="mutable_atom"&&_(e)){const{parent:t}=e;o=Ce(n,t,e)}return o},kt=(n,e)=>{const o=e.valueMap.get(n);if(o instanceof Fe){const t=o,i=e.selectors.get(n)??e.readonlySelectors.get(n);if(i)t.use(i.get());return}if(e.operation.open)e.operation.prev.set(n,o);e.valueMap.delete(n),e.logger.info("\uD83D\uDDD1","state",n,"evicted")};var At=(n,e)=>{return S(e).atomsThatAreDefault.has(n)},oo=(n,e)=>{const o=S(e);o.atomsThatAreDefault=new Set(o.atomsThatAreDefault).add(n)},Ft=(n,e)=>{const o=S(e);o.atomsThatAreDefault=new Set(S(e).atomsThatAreDefault),o.atomsThatAreDefault.delete(n)};function ln(n,e,o){n.logger.info("\uD83D\uDD28","atom",e.key,`creating in store "${n.config.name}"`);const t=S(n),i=t.atoms.get(e.key);if(i&&i.type==="atom")return n.logger.error("\u274C","atom",e.key,"Tried to create atom, but it already exists in the store."),nn(i);const r=new W,l={...e,type:"atom",install:(y)=>{return y.logger.info("\uD83D\uDEE0\uFE0F","atom",e.key,`installing in store "${y.config.name}"`),ln(y,e,o)},subject:r};if(o)l.family=o;let m=e.default;if(e.default instanceof Function)m=e.default();t.atoms.set(l.key,l),oo(e.key,n),Tn(e.key,m,r,t);const f=nn(l);if(e.effects){let y=0;const c=[];for(let T of e.effects){const F=T({setSelf:(u)=>{I(n,f,u)},onSet:(u)=>cn(f,u,`effect[${y}]`,n)});if(F)c.push(F);++y}l.cleanup=()=>{for(let T of c)T()}}return f}function lt(n,e){if("mutable"in e){const i=se(n,e,void 0);return n.on.atomCreation.next(i),i}const t=ln(n,e,void 0);return n.on.atomCreation.next(t),t}function wo(n,e){const o=S(e),{key:t}=n,i=C(n,o);if(!i.family)e.logger.error("\u274C","atom",t,"Standalone atoms cannot be disposed.");else{i.cleanup?.();const r=e.valueMap.get(i.key);C({key:i.family.key,type:"atom_family"},e).subject.next({type:"state_disposal",token:n,value:r});const m=o.molecules.get(i.family.subKey);if(m)m.tokens.delete(t);if(o.atoms.delete(t),o.valueMap.delete(t),o.selectorAtoms.delete(t),o.atomsThatAreDefault.delete(t),e.timelineTopics.delete(t),n.type==="mutable_atom"){const f=Hn(n);wo(f,e),e.trackers.delete(t)}if(e.logger.info("\uD83D\uDD25","atom",t,"deleted"),_(o)&&o.transactionMeta.phase==="building")o.transactionMeta.update.updates.push({type:"state_disposal",token:n});else e.on.atomDisposal.next(n)}}var so=(n)=>{const e=ln(n,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{const o=new Map;for(let[t,i]of n.atoms)if(!t.includes("\uD83D\uDD0D")){const r=nn(i);if(i.family){let l=o.get(i.family.key);if(!l||!("familyMembers"in l))l={key:i.family.key,familyMembers:new Map},o.set(i.family.key,l);l.familyMembers.set(i.family.subKey,r)}else o.set(t,r)}return o},effects:[({setSelf:o})=>{n.on.atomCreation.subscribe("introspection",(t)=>{if(t.key.includes("\uD83D\uDD0D"))return;o((i)=>{if(t.family){const{key:r,subKey:l}=t.family;let m=i.get(r);if(m===void 0||!("familyMembers"in m))m={key:r,familyMembers:new Map},i.set(r,m);m.familyMembers.set(l,t)}else i.set(t.key,t);return i})}),n.on.atomDisposal.subscribe("introspection",(t)=>{o((i)=>{if(t.family){const{key:r,subKey:l}=t.family,m=i.get(r);if(m&&"familyMembers"in m){if(m.familyMembers.delete(l),m.familyMembers.size===0)i.delete(r)}}else i.delete(t.key);return i})})}]},void 0);return Mn(n,{key:"\uD83D\uDD0D Atom Token Index",get:({get:o})=>o(e)})};var Bo=(n)=>{const e=ln(n,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{const o=new Map;for(let t of[n.readonlySelectors,n.selectors])for(let[i,r]of t)if(!i.includes("\uD83D\uDD0D")){const l=nn(r);if(r.family){let m=o.get(r.family.key);if(!m||!("familyMembers"in m))m={key:r.family.key,familyMembers:new Map},o.set(r.family.key,m);m.familyMembers.set(r.family.subKey,l)}else o.set(i,l)}return o},effects:[({setSelf:o})=>{n.on.selectorCreation.subscribe("introspection",(t)=>{if(t.key.includes("\uD83D\uDD0D"))return;o((i)=>{if(t.family){const{key:r,subKey:l}=t.family;let m=i.get(r);if(m===void 0||!("familyMembers"in m))m={key:r,familyMembers:new Map},i.set(r,m);m.familyMembers.set(l,t)}else i.set(t.key,t);return i})}),n.on.selectorDisposal.subscribe("introspection",(t)=>{o((i)=>{if(t.family){const{key:r,subKey:l}=t.family,m=i.get(r);if(m&&"familyMembers"in m){if(m.familyMembers.delete(l),m.familyMembers.size===0)i.delete(r)}}else i.delete(t.key);return i})})}]},void 0);return Mn(n,{key:"\uD83D\uDD0D Selector Token Index",get:({get:o})=>o(e)})};function jo(n){if(!n)return!1;return Object.getPrototypeOf(n)===Object.prototype}class to{supported;constructor(n){this.supported=n}refine(n){for(let[e,o]of Object.entries(this.supported))try{if(o(n)===!0&&o!==Boolean)return{type:e,data:n}}catch(t){try{if(n instanceof o)return{type:e,data:n}}catch(i){}}return null}}var uo=new to({number:(n)=>typeof n==="number",string:(n)=>typeof n==="string",boolean:(n)=>typeof n==="boolean",null:(n)=>n===null}),_o=new to({object:jo,array:(n)=>Array.isArray(n)}),Ci=new to({...uo.supported,..._o.supported}),ne=(n)=>{if(n===void 0)return"undefined";const e=Ci.refine(n);if(e)return e.type;return Object.getPrototypeOf(n).constructor.name};class Qt{n;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(n=X.STORE){this.store=n;this.atomIndex=so(this.store),this.selectorIndex=Bo(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:e})=>{this.statesCreatedAt.set(e,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:e})=>{this.statesCreatedAt.delete(e)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:e})=>{this.statesCreatedAt.set(e,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:e})=>{this.statesCreatedAt.delete(e)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(n=Qt.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");const e=ao(this.atomIndex),o=ao(this.selectorIndex),t=[...e.values()].filter((m)=>("familyMembers"in m)),i=[...o.values()].filter((m)=>("familyMembers"in m)),r=performance.now(),l=[];if(n.atomFamilies)for(let m of t){const f=m.familyMembers.values();for(let y of f){const T=this.statesCreatedAt.get(y.key)??this.auditorCreatedAt,F=r-T;l.push([y,F])}}if(n.selectorFamilies)for(let m of i){const f=m.familyMembers.values();for(let y of f){const T=this.statesCreatedAt.get(y.key)??this.auditorCreatedAt,F=r-T;l.push([y,F])}}return l}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var zo=(n,e)=>{const o=(t,i)=>{const l=((f,y)=>{const c=e(f,y);if(c)return c;return null})(t,i);if(l?.jobComplete??l?.pathComplete)return l;const m=Array.isArray(i)?i.map((f,y)=>[y,f]):jo(i)?Object.entries(i):[];for(let[f,y]of m){const c=o([...t,f],y);if(c?.jobComplete)return c}return{}};o([],n)};function Oi(n,e){return{summary:`${n<e?"+":"-"}${Math.abs(n-e)} (${n} \u2192 ${e})`}}function Wi(n,e){return{summary:`${n.length<e.length?"+":"-"}${Math.abs(n.length-e.length)} ("${n}" \u2192 "${e}")`}}function xi(n,e){return{summary:`${n} \u2192 ${e}`}}function Yt(n,e,o){let t="";const i=[],r=[],l=[];return zo(n,(m,f)=>{let y;for(y of m){const c=e[y];if(c===void 0)r.push([y,JSON.stringify(f)]);else{const T=o(f,c);if(T.summary!=="No Change")l.push([y,T])}}}),zo(e,(m,f)=>{let y;for(y of m)if(n[y]===void 0)i.push([y,JSON.stringify(f)])}),t=`\uFF5E${l.length} \uFF0B${i.length} \uFF0D${r.length}`,{summary:t,added:i,removed:r,changed:l}}function si(n,e,o){return Yt(n,e,o)}class Gt{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(n,e,o){this.leafRefinery=n,this.treeRefinery=e,this.leafDiffers={},this.treeDiffers={};for(let t of Object.keys(n.supported)){const i=o[t];this.leafDiffers[t]=i}for(let t of Object.keys(e.supported)){const i=o[t];this.treeDiffers[t]=i}}diff(n,e){if(n===e)return{summary:"No Change"};const o=this.leafRefinery.refine(n)??this.treeRefinery.refine(n),t=this.leafRefinery.refine(e)??this.treeRefinery.refine(e);if(o!==null&&t!==null){if(o.type===t.type){if(o.type in this.leafDiffers)return this.leafDiffers[o.type](o.data,t.data);if(o.type in this.treeDiffers)return this.treeDiffers[o.type](o.data,t.data,(m,f)=>this.diff(m,f))}}const i=ne(n),r=ne(e);if(i===r)return{summary:`${i} \u2192 ${r}`};return{summary:`Type change: ${i} \u2192 ${r}`}}}var Rb=new Gt(uo,_o,{number:Oi,string:Wi,boolean:xi,null:()=>({summary:"No Change"}),object:Yt,array:si});class ee{n;listeners;globalListeners;handleEvent(n,...e){for(let t of this.globalListeners)t(n,...e);const o=this.listeners.get(n);if(o)for(let t of o)t(...e)}id="no_id_retrieved";constructor(n){this.emit=n;this.listeners=new Map,this.globalListeners=new Set}on(n,e){const o=this.listeners.get(n);if(o)o.add(e);else this.listeners.set(n,new Set([e]));return this}onAny(n){return this.globalListeners.add(n),this}off(n,e){const o=this.listeners.get(n);if(o)if(e)o.delete(e);else this.listeners.delete(n);return this}offAny(n){return this.globalListeners.delete(n),this}}class Xo extends ee{n;e;o;incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";handleLog(n){if(Array.isArray(n)){const[e,...o]=n;switch(e){case"i":this.logger.info(this.id,this.key,...o);break;case"w":this.logger.warn(this.id,this.key,...o);break;case"e":this.logger.error(this.id,this.key,...o);break}}}constructor(n,e,o=console){super((t,...i)=>{const r=JSON.stringify([t,...i])+"\x03",l=(m)=>{if(m.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",l)};return this.process.stdin.once("error",l),this.process.stdin.write(r),this});this.process=n;this.key=e;this.logger=o;if(this.process=n,this.process.stdout.on("data",(t)=>{const i=t.toString();if(i==="\u2728")return;this.unprocessedEvents.push(...i.split("\x03"));const r=this.unprocessedEvents.shift();this.incompleteData+=r??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let l=D(this.incompleteData);this.handleEvent(...l);while(this.unprocessedEvents.length>0){const m=this.unprocessedEvents.shift();if(m){if(this.unprocessedEvents.length===0)this.incompleteData=m;l=D(m),this.handleEvent(...l)}}this.incompleteData=""}catch(l){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(l)}}),this.process.stderr.on("data",(t)=>{const i=t.toString();this.unprocessedLogs.push(...i.split("\x03"));const r=this.unprocessedLogs.shift();this.incompleteLog+=r??"";try{let l=D(this.incompleteLog);this.handleLog(l);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)l=D(this.incompleteLog),this.handleLog(l)}catch(l){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(l),console.error("\u274C\u274C\u274C\uFE0F")}}),n.pid)this.id=n.pid.toString()}}class Et extends ee{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(n){super((...e)=>{return this.out.next(e),this});this.id=n,this.in=new W,this.out=new W,this.in.subscribe("socket",(e)=>{this.handleEvent(...e)})}dispose(){for(let n of this.disposalFunctions)n()}}class Ho extends ee{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...n){this.process.stderr.write(J(n.map((e)=>e instanceof v?`{ ${e.toJSON().members.join(" | ")} }`:e))+"\x03")}logger={info:(...n)=>{this.log("i",...n)},warn:(...n)=>{this.log("w",...n)},error:(...n)=>{this.log("e",...n)}};constructor(){super((n,...e)=>{const o=JSON.stringify([n,...e]);return this.process.stdout.write(o+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(n)=>{const e=n.toString();this.unprocessedEvents.push(...e.split("\x03"));const o=this.unprocessedEvents.shift();this.incompleteData+=o??"";try{const t=D(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",t),this.handleEvent(...t);while(this.unprocessedEvents.length>0){const i=this.unprocessedEvents.shift();if(i){if(this.unprocessedEvents.length===0)this.incompleteData=i;const r=D(i);this.handleEvent(...r)}}this.incompleteData=""}catch(t){if(t instanceof Error)this.logger.error("\u2757",t.message,t.cause,t.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(n)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${n}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(n)=>{this.logger.info("\uD83D\uDC64","user",n,"joined");const e=new Et(`user:${n}`);this.relays.set(n,e),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let o of this.relayServices){const t=o(e);if(t)e.disposalFunctions.push(t)}this.on(`user:${n}`,(...o)=>{e.in.next(o)}),e.out.subscribe("socket",(o)=>{this.emit(...o)})}),this.on("user-leaves",(n)=>{const e=this.relays.get(n);if(this.off(`relay:${n}`),e)e.dispose(),this.relays.delete(n)}),process.stdout.write("\u2728")}relay(n){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(n)}}class pt extends Map{set(n,e){if(this.has(n))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:n,value:e}),this;return super.set(n,e)}clear(){throw new Error("Cannot clear an InvariantMap")}}class qo{n;type="continuity";globals=[];actions=[];perspectives=[];constructor(n){this.key=n}static existing=new pt;static create(n,e){const o=new qo(n),{type:t,globals:i,actions:r,perspectives:l}=e(o),m={type:t,key:n,globals:i,actions:r,perspectives:l};return qo.existing.set(n,m),m}add(...n){switch(n[0].type){case"atom":case"mutable_atom":this.globals.push(...n);break;case"transaction":this.actions.push(...n);break;case"atom_family":{const[o,t]=n;this.perspectives.push({type:"realtime_perspective",resourceAtoms:o,viewAtoms:t})}break}return this}}var Ib=Pn({key:"usersInRoomIndex",mutable:!0,default:()=>new v,toJson:(n)=>n.toJSON(),fromJson:(n)=>v.fromJSON(n)}),Qo=Pn({key:"roomIndex",default:()=>new v,mutable:!0,toJson:(n)=>n.toJSON(),fromJson:(n)=>v.fromJSON(n)}),Bi={enteredAtEpoch:0},Be=De({key:"usersInRooms",between:["room","user"],cardinality:"1:n"},Bi),Nb=pe({key:"usersInMyRoomView",get:(n)=>({find:e})=>{const o=wt(Be);return[e(o,n)]}});import{spawn as ui}from"child_process";var Yo=Ln({key:"roomArguments",default:["echo",["Hello World!"]]}),Lt=pe({key:"room",get:(n)=>async({get:e,find:o})=>{const t=o(Yo,n),i=e(t),[r,l]=i,m=await new Promise((f)=>{const y=ui(r,l,{env:process.env}),c=(T)=>{if(T.toString()==="\u2728")y.stdout.off("data",c),f(y)};y.stdout.on("data",c)});return new Xo(m,n)}});var yM=we({key:"createRoom",do:({get:n,set:e,find:o},t,i,r)=>{const l=r?[i,r]:[i],m=o(Yo,t);e(m,l),e(Qo,(c)=>c.add(t));const f=o(Lt,t);return n(f)}}),cM=we({key:"joinRoom",do:(n,e,o,t)=>{const i={enteredAtEpoch:t};return Ie(Be,(r)=>{r.set({room:e,user:o},i)},n.env().store),i}}),aM=we({key:"leaveRoom",do:(n,e,o)=>{Ie(Be,(t)=>{t.delete({room:e,user:o})},n.env().store)}}),SM=we({key:"destroyRoom",do:(n,e)=>{Ie(Be,(o)=>{o.delete({room:e})},n.env().store),n.set(Qo,(o)=>(o.delete(e),o))}});var bM=Ln({key:"transactionRedactor",default:{occlude:(n)=>n}}),ji=Ln({key:"unacknowledgedUpdates",default:()=>[]});var _i=Ln({key:"sockets",default:null}),gM=Pn({key:"socketsIndex",mutable:!0,default:()=>new v,toJson:(n)=>n.toJSON(),fromJson:(n)=>v.fromJSON(n)}),JM=Pn({key:"usersIndex",mutable:!0,default:()=>new v,toJson:(n)=>n.toJSON(),fromJson:(n)=>v.fromJSON(n)}),zi=De({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1"});var{file:yi,serve:ll}=globalThis.Bun;function Hi(n){ht=n}function io(){return ht}function b(n,e){const o=io(),t=ro({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,o,o===re?void 0:re].filter((i)=>!!i)});n.common.issues.push(t)}function lo(n,e,o,t){if(o==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof e==="function"?n!==e||!t:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return o==="m"?t:o==="a"?t.call(n):t?t.value:e.get(n)}function Dt(n,e,o,t,i){if(t==="m")throw new TypeError("Private method is not writable");if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e==="function"?n!==e||!i:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t==="a"?i.call(n,o):i?i.value=o:e.set(n,o),o}function x(n){if(!n)return{};const{errorMap:e,invalid_type_error:o,required_error:t,description:i}=n;if(e&&(o||t))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(e)return{errorMap:e,description:i};return{errorMap:(l,m)=>{var f,y;const{message:c}=n;if(l.code==="invalid_enum_value")return{message:c!==null&&c!==void 0?c:m.defaultError};if(typeof m.data==="undefined")return{message:(f=c!==null&&c!==void 0?c:t)!==null&&f!==void 0?f:m.defaultError};if(l.code!=="invalid_type")return{message:m.defaultError};return{message:(y=c!==null&&c!==void 0?c:o)!==null&&y!==void 0?y:m.defaultError}},description:i}}function Nt(n){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(n.precision)e=`${e}\\.\\d{${n.precision}}`;else if(n.precision==null)e=`${e}(\\.\\d+)?`;return e}function vi(n){return new RegExp(`^${Nt(n)}\$`)}function vt(n){let e=`${It}T${Nt(n)}`;const o=[];if(o.push(n.local?"Z?":"Z"),n.offset)o.push("([+-]\\d{2}:?\\d{2})");return e=`${e}(${o.join("|")})`,new RegExp(`^${e}\$`)}function Pi(n,e){if((e==="v4"||!e)&&hi.test(n))return!0;if((e==="v6"||!e)&&Di.test(n))return!0;return!1}function di(n,e){const o=(n.toString().split(".")[1]||"").length,t=(e.toString().split(".")[1]||"").length,i=o>t?o:t,r=parseInt(n.toFixed(i).replace(".","")),l=parseInt(e.toFixed(i).replace(".",""));return r%l/Math.pow(10,i)}function oe(n){if(n instanceof h){const e={};for(let o in n.shape){const t=n.shape[o];e[o]=Jn.create(oe(t))}return new h({...n._def,shape:()=>e})}else if(n instanceof gn)return new gn({...n._def,type:oe(n.element)});else if(n instanceof Jn)return Jn.create(oe(n.unwrap()));else if(n instanceof un)return un.create(oe(n.unwrap()));else if(n instanceof On)return On.create(n.items.map((e)=>oe(e)));else return n}function Vo(n,e){const o=Qn(n),t=Qn(e);if(n===e)return{valid:!0,data:n};else if(o===R.object&&t===R.object){const i=H.objectKeys(e),r=H.objectKeys(n).filter((m)=>i.indexOf(m)!==-1),l={...n,...e};for(let m of r){const f=Vo(n[m],e[m]);if(!f.valid)return{valid:!1};l[m]=f.data}return{valid:!0,data:l}}else if(o===R.array&&t===R.array){if(n.length!==e.length)return{valid:!1};const i=[];for(let r=0;r<n.length;r++){const l=n[r],m=e[r],f=Vo(l,m);if(!f.valid)return{valid:!1};i.push(f.data)}return{valid:!0,data:i}}else if(o===R.date&&t===R.date&&+n===+e)return{valid:!0,data:n};else return{valid:!1}}function Pt(n,e){return new pn({values:n,typeName:$.ZodEnum,...x(e)})}function dt(n,e={},o){if(n)return hn.create().superRefine((t,i)=>{var r,l;if(!n(t)){const m=typeof e==="function"?e(t):typeof e==="string"?{message:e}:e,f=(l=(r=m.fatal)!==null&&r!==void 0?r:o)!==null&&l!==void 0?l:!0,y=typeof m==="string"?{message:m}:m;i.addIssue({code:"custom",...y,fatal:f})}});return hn.create()}var H;(function(n){n.assertEqual=(i)=>i;function e(i){}n.assertIs=e;function o(i){throw new Error}n.assertNever=o,n.arrayToEnum=(i)=>{const r={};for(let l of i)r[l]=l;return r},n.getValidEnumValues=(i)=>{const r=n.objectKeys(i).filter((m)=>typeof i[i[m]]!=="number"),l={};for(let m of r)l[m]=i[m];return n.objectValues(l)},n.objectValues=(i)=>{return n.objectKeys(i).map(function(r){return i[r]})},n.objectKeys=typeof Object.keys==="function"?(i)=>Object.keys(i):(i)=>{const r=[];for(let l in i)if(Object.prototype.hasOwnProperty.call(i,l))r.push(l);return r},n.find=(i,r)=>{for(let l of i)if(r(l))return l;return},n.isInteger=typeof Number.isInteger==="function"?(i)=>Number.isInteger(i):(i)=>typeof i==="number"&&isFinite(i)&&Math.floor(i)===i;function t(i,r=" | "){return i.map((l)=>typeof l==="string"?`'${l}'`:l).join(r)}n.joinValues=t,n.jsonStringifyReplacer=(i,r)=>{if(typeof r==="bigint")return r.toString();return r}})(H||(H={}));var Eo;(function(n){n.mergeShapes=(e,o)=>{return{...e,...o}}})(Eo||(Eo={}));var R=H.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Qn=(n)=>{switch(typeof n){case"undefined":return R.undefined;case"string":return R.string;case"number":return isNaN(n)?R.nan:R.number;case"boolean":return R.boolean;case"function":return R.function;case"bigint":return R.bigint;case"symbol":return R.symbol;case"object":if(Array.isArray(n))return R.array;if(n===null)return R.null;if(n.then&&typeof n.then==="function"&&n.catch&&typeof n.catch==="function")return R.promise;if(typeof Map!=="undefined"&&n instanceof Map)return R.map;if(typeof Set!=="undefined"&&n instanceof Set)return R.set;if(typeof Date!=="undefined"&&n instanceof Date)return R.date;return R.object;default:return R.unknown}},a=H.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Xi=(n)=>{return JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:")};class an extends Error{constructor(n){super();this.issues=[],this.addIssue=(o)=>{this.issues=[...this.issues,o]},this.addIssues=(o=[])=>{this.issues=[...this.issues,...o]};const e=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,e);else this.__proto__=e;this.name="ZodError",this.issues=n}get errors(){return this.issues}format(n){const e=n||function(i){return i.message},o={_errors:[]},t=(i)=>{for(let r of i.issues)if(r.code==="invalid_union")r.unionErrors.map(t);else if(r.code==="invalid_return_type")t(r.returnTypeError);else if(r.code==="invalid_arguments")t(r.argumentsError);else if(r.path.length===0)o._errors.push(e(r));else{let l=o,m=0;while(m<r.path.length){const f=r.path[m];if(m!==r.path.length-1)l[f]=l[f]||{_errors:[]};else l[f]=l[f]||{_errors:[]},l[f]._errors.push(e(r));l=l[f],m++}}};return t(this),o}static assert(n){if(!(n instanceof an))throw new Error(`Not a ZodError: ${n}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,H.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(n=(e)=>e.message){const e={},o=[];for(let t of this.issues)if(t.path.length>0)e[t.path[0]]=e[t.path[0]]||[],e[t.path[0]].push(n(t));else o.push(n(t));return{formErrors:o,fieldErrors:e}}get formErrors(){return this.flatten()}}an.create=(n)=>{return new an(n)};var re=(n,e)=>{let o;switch(n.code){case a.invalid_type:if(n.received===R.undefined)o="Required";else o=`Expected ${n.expected}, received ${n.received}`;break;case a.invalid_literal:o=`Invalid literal value, expected ${JSON.stringify(n.expected,H.jsonStringifyReplacer)}`;break;case a.unrecognized_keys:o=`Unrecognized key(s) in object: ${H.joinValues(n.keys,", ")}`;break;case a.invalid_union:o="Invalid input";break;case a.invalid_union_discriminator:o=`Invalid discriminator value. Expected ${H.joinValues(n.options)}`;break;case a.invalid_enum_value:o=`Invalid enum value. Expected ${H.joinValues(n.options)}, received '${n.received}'`;break;case a.invalid_arguments:o="Invalid function arguments";break;case a.invalid_return_type:o="Invalid function return type";break;case a.invalid_date:o="Invalid date";break;case a.invalid_string:if(typeof n.validation==="object")if("includes"in n.validation){if(o=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position==="number")o=`${o} at one or more positions greater than or equal to ${n.validation.position}`}else if("startsWith"in n.validation)o=`Invalid input: must start with "${n.validation.startsWith}"`;else if("endsWith"in n.validation)o=`Invalid input: must end with "${n.validation.endsWith}"`;else H.assertNever(n.validation);else if(n.validation!=="regex")o=`Invalid ${n.validation}`;else o="Invalid";break;case a.too_small:if(n.type==="array")o=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`;else if(n.type==="string")o=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`;else if(n.type==="number")o=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`;else if(n.type==="date")o=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`;else o="Invalid input";break;case a.too_big:if(n.type==="array")o=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`;else if(n.type==="string")o=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`;else if(n.type==="number")o=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`;else if(n.type==="bigint")o=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`;else if(n.type==="date")o=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`;else o="Invalid input";break;case a.custom:o="Invalid input";break;case a.invalid_intersection_types:o="Intersection results could not be merged";break;case a.not_multiple_of:o=`Number must be a multiple of ${n.multipleOf}`;break;case a.not_finite:o="Number must be finite";break;default:o=e.defaultError,H.assertNever(n)}return{message:o}},ht=re,ro=(n)=>{const{data:e,path:o,errorMaps:t,issueData:i}=n,r=[...o,...i.path||[]],l={...i,path:r};if(i.message!==void 0)return{...i,path:r,message:i.message};let m="";const f=t.filter((y)=>!!y).slice().reverse();for(let y of f)m=y(l,{data:e,defaultError:m}).message;return{...i,path:r,message:m}},qi=[];class en{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(n,e){const o=[];for(let t of e){if(t.status==="aborted")return K;if(t.status==="dirty")n.dirty();o.push(t.value)}return{status:n.value,value:o}}static async mergeObjectAsync(n,e){const o=[];for(let t of e){const i=await t.key,r=await t.value;o.push({key:i,value:r})}return en.mergeObjectSync(n,o)}static mergeObjectSync(n,e){const o={};for(let t of e){const{key:i,value:r}=t;if(i.status==="aborted")return K;if(r.status==="aborted")return K;if(i.status==="dirty")n.dirty();if(r.status==="dirty")n.dirty();if(i.value!=="__proto__"&&(typeof r.value!=="undefined"||t.alwaysSet))o[i.value]=r.value}return{status:n.value,value:o}}}var K=Object.freeze({status:"aborted"}),te=(n)=>({status:"dirty",value:n}),tn=(n)=>({status:"valid",value:n}),po=(n)=>n.status==="aborted",Lo=(n)=>n.status==="dirty",_e=(n)=>n.status==="valid",ze=(n)=>typeof Promise!=="undefined"&&n instanceof Promise;var A;(function(n){n.errToObj=(e)=>typeof e==="string"?{message:e}:e||{},n.toString=(e)=>typeof e==="string"?e:e===null||e===void 0?void 0:e.message})(A||(A={}));var ue,je;class $n{constructor(n,e,o,t){this._cachedPath=[],this.parent=n,this.data=e,this._path=o,this._key=t}get path(){if(!this._cachedPath.length)if(this._key instanceof Array)this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var Vt=(n,e)=>{if(_e(e))return{success:!0,data:e.value};else{if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const o=new an(n.common.issues);return this._error=o,this._error}}}};class s{constructor(n){this.spa=this.safeParseAsync,this._def=n,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(n){return Qn(n.data)}_getOrReturnCtx(n,e){return e||{common:n.parent.common,data:n.data,parsedType:Qn(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}_processInputParams(n){return{status:new en,ctx:{common:n.parent.common,data:n.data,parsedType:Qn(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}}_parseSync(n){const e=this._parse(n);if(ze(e))throw new Error("Synchronous parse encountered promise.");return e}_parseAsync(n){const e=this._parse(n);return Promise.resolve(e)}parse(n,e){const o=this.safeParse(n,e);if(o.success)return o.data;throw o.error}safeParse(n,e){var o;const t={common:{issues:[],async:(o=e===null||e===void 0?void 0:e.async)!==null&&o!==void 0?o:!1,contextualErrorMap:e===null||e===void 0?void 0:e.errorMap},path:(e===null||e===void 0?void 0:e.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Qn(n)},i=this._parseSync({data:n,path:t.path,parent:t});return Vt(t,i)}async parseAsync(n,e){const o=await this.safeParseAsync(n,e);if(o.success)return o.data;throw o.error}async safeParseAsync(n,e){const o={common:{issues:[],contextualErrorMap:e===null||e===void 0?void 0:e.errorMap,async:!0},path:(e===null||e===void 0?void 0:e.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Qn(n)},t=this._parse({data:n,path:o.path,parent:o}),i=await(ze(t)?t:Promise.resolve(t));return Vt(o,i)}refine(n,e){const o=(t)=>{if(typeof e==="string"||typeof e==="undefined")return{message:e};else if(typeof e==="function")return e(t);else return e};return this._refinement((t,i)=>{const r=n(t),l=()=>i.addIssue({code:a.custom,...o(t)});if(typeof Promise!=="undefined"&&r instanceof Promise)return r.then((m)=>{if(!m)return l(),!1;else return!0});if(!r)return l(),!1;else return!0})}refinement(n,e){return this._refinement((o,t)=>{if(!n(o))return t.addIssue(typeof e==="function"?e(o,t):e),!1;else return!0})}_refinement(n){return new bn({schema:this,typeName:$.ZodEffects,effect:{type:"refinement",refinement:n}})}superRefine(n){return this._refinement(n)}optional(){return Jn.create(this,this._def)}nullable(){return un.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return gn.create(this,this._def)}promise(){return In.create(this,this._def)}or(n){return ye.create([this,n],this._def)}and(n){return ce.create(this,n,this._def)}transform(n){return new bn({...x(this._def),schema:this,typeName:$.ZodEffects,effect:{type:"transform",transform:n}})}default(n){const e=typeof n==="function"?n:()=>n;return new ke({...x(this._def),innerType:this,defaultValue:e,typeName:$.ZodDefault})}brand(){return new fo({typeName:$.ZodBranded,type:this,...x(this._def)})}catch(n){const e=typeof n==="function"?n:()=>n;return new be({...x(this._def),innerType:this,catchValue:e,typeName:$.ZodCatch})}describe(n){return new this.constructor({...this._def,description:n})}pipe(n){return Ge.create(this,n)}readonly(){return Me.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var Qi=/^c[^\s-]{8,}$/i,Yi=/^[0-9a-z]+$/,Gi=/^[0-9A-HJKMNP-TV-Z]{26}$/,Ei=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,pi=/^[a-z0-9_-]{21}$/i,Li=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Vi=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Ui="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Go,hi=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Di=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,Ii=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,It="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ni=new RegExp(`^${It}\$`);class Fn extends s{_parse(n){if(this._def.coerce)n.data=String(n.data);if(this._getType(n)!==R.string){const i=this._getOrReturnCtx(n);return b(i,{code:a.invalid_type,expected:R.string,received:i.parsedType}),K}const o=new en;let t=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(n.data.length<i.value)t=this._getOrReturnCtx(n,t),b(t,{code:a.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),o.dirty()}else if(i.kind==="max"){if(n.data.length>i.value)t=this._getOrReturnCtx(n,t),b(t,{code:a.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),o.dirty()}else if(i.kind==="length"){const r=n.data.length>i.value,l=n.data.length<i.value;if(r||l){if(t=this._getOrReturnCtx(n,t),r)b(t,{code:a.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});else if(l)b(t,{code:a.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});o.dirty()}}else if(i.kind==="email"){if(!Vi.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"email",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="emoji"){if(!Go)Go=new RegExp(Ui,"u");if(!Go.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"emoji",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="uuid"){if(!Ei.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"uuid",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="nanoid"){if(!pi.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"nanoid",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="cuid"){if(!Qi.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"cuid",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="cuid2"){if(!Yi.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"cuid2",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="ulid"){if(!Gi.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"ulid",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="url")try{new URL(n.data)}catch(r){t=this._getOrReturnCtx(n,t),b(t,{validation:"url",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="regex"){if(i.regex.lastIndex=0,!i.regex.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"regex",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="trim")n.data=n.data.trim();else if(i.kind==="includes"){if(!n.data.includes(i.value,i.position))t=this._getOrReturnCtx(n,t),b(t,{code:a.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),o.dirty()}else if(i.kind==="toLowerCase")n.data=n.data.toLowerCase();else if(i.kind==="toUpperCase")n.data=n.data.toUpperCase();else if(i.kind==="startsWith"){if(!n.data.startsWith(i.value))t=this._getOrReturnCtx(n,t),b(t,{code:a.invalid_string,validation:{startsWith:i.value},message:i.message}),o.dirty()}else if(i.kind==="endsWith"){if(!n.data.endsWith(i.value))t=this._getOrReturnCtx(n,t),b(t,{code:a.invalid_string,validation:{endsWith:i.value},message:i.message}),o.dirty()}else if(i.kind==="datetime"){if(!vt(i).test(n.data))t=this._getOrReturnCtx(n,t),b(t,{code:a.invalid_string,validation:"datetime",message:i.message}),o.dirty()}else if(i.kind==="date"){if(!Ni.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{code:a.invalid_string,validation:"date",message:i.message}),o.dirty()}else if(i.kind==="time"){if(!vi(i).test(n.data))t=this._getOrReturnCtx(n,t),b(t,{code:a.invalid_string,validation:"time",message:i.message}),o.dirty()}else if(i.kind==="duration"){if(!Li.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"duration",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="ip"){if(!Pi(n.data,i.version))t=this._getOrReturnCtx(n,t),b(t,{validation:"ip",code:a.invalid_string,message:i.message}),o.dirty()}else if(i.kind==="base64"){if(!Ii.test(n.data))t=this._getOrReturnCtx(n,t),b(t,{validation:"base64",code:a.invalid_string,message:i.message}),o.dirty()}else H.assertNever(i);return{status:o.value,value:n.data}}_regex(n,e,o){return this.refinement((t)=>n.test(t),{validation:e,code:a.invalid_string,...A.errToObj(o)})}_addCheck(n){return new Fn({...this._def,checks:[...this._def.checks,n]})}email(n){return this._addCheck({kind:"email",...A.errToObj(n)})}url(n){return this._addCheck({kind:"url",...A.errToObj(n)})}emoji(n){return this._addCheck({kind:"emoji",...A.errToObj(n)})}uuid(n){return this._addCheck({kind:"uuid",...A.errToObj(n)})}nanoid(n){return this._addCheck({kind:"nanoid",...A.errToObj(n)})}cuid(n){return this._addCheck({kind:"cuid",...A.errToObj(n)})}cuid2(n){return this._addCheck({kind:"cuid2",...A.errToObj(n)})}ulid(n){return this._addCheck({kind:"ulid",...A.errToObj(n)})}base64(n){return this._addCheck({kind:"base64",...A.errToObj(n)})}ip(n){return this._addCheck({kind:"ip",...A.errToObj(n)})}datetime(n){var e,o;if(typeof n==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:n});return this._addCheck({kind:"datetime",precision:typeof(n===null||n===void 0?void 0:n.precision)==="undefined"?null:n===null||n===void 0?void 0:n.precision,offset:(e=n===null||n===void 0?void 0:n.offset)!==null&&e!==void 0?e:!1,local:(o=n===null||n===void 0?void 0:n.local)!==null&&o!==void 0?o:!1,...A.errToObj(n===null||n===void 0?void 0:n.message)})}date(n){return this._addCheck({kind:"date",message:n})}time(n){if(typeof n==="string")return this._addCheck({kind:"time",precision:null,message:n});return this._addCheck({kind:"time",precision:typeof(n===null||n===void 0?void 0:n.precision)==="undefined"?null:n===null||n===void 0?void 0:n.precision,...A.errToObj(n===null||n===void 0?void 0:n.message)})}duration(n){return this._addCheck({kind:"duration",...A.errToObj(n)})}regex(n,e){return this._addCheck({kind:"regex",regex:n,...A.errToObj(e)})}includes(n,e){return this._addCheck({kind:"includes",value:n,position:e===null||e===void 0?void 0:e.position,...A.errToObj(e===null||e===void 0?void 0:e.message)})}startsWith(n,e){return this._addCheck({kind:"startsWith",value:n,...A.errToObj(e)})}endsWith(n,e){return this._addCheck({kind:"endsWith",value:n,...A.errToObj(e)})}min(n,e){return this._addCheck({kind:"min",value:n,...A.errToObj(e)})}max(n,e){return this._addCheck({kind:"max",value:n,...A.errToObj(e)})}length(n,e){return this._addCheck({kind:"length",value:n,...A.errToObj(e)})}nonempty(n){return this.min(1,A.errToObj(n))}trim(){return new Fn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Fn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Fn({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((n)=>n.kind==="datetime")}get isDate(){return!!this._def.checks.find((n)=>n.kind==="date")}get isTime(){return!!this._def.checks.find((n)=>n.kind==="time")}get isDuration(){return!!this._def.checks.find((n)=>n.kind==="duration")}get isEmail(){return!!this._def.checks.find((n)=>n.kind==="email")}get isURL(){return!!this._def.checks.find((n)=>n.kind==="url")}get isEmoji(){return!!this._def.checks.find((n)=>n.kind==="emoji")}get isUUID(){return!!this._def.checks.find((n)=>n.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((n)=>n.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((n)=>n.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((n)=>n.kind==="cuid2")}get isULID(){return!!this._def.checks.find((n)=>n.kind==="ulid")}get isIP(){return!!this._def.checks.find((n)=>n.kind==="ip")}get isBase64(){return!!this._def.checks.find((n)=>n.kind==="base64")}get minLength(){let n=null;for(let e of this._def.checks)if(e.kind==="min"){if(n===null||e.value>n)n=e.value}return n}get maxLength(){let n=null;for(let e of this._def.checks)if(e.kind==="max"){if(n===null||e.value<n)n=e.value}return n}}Fn.create=(n)=>{var e;return new Fn({checks:[],typeName:$.ZodString,coerce:(e=n===null||n===void 0?void 0:n.coerce)!==null&&e!==void 0?e:!1,...x(n)})};class Gn extends s{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(n){if(this._def.coerce)n.data=Number(n.data);if(this._getType(n)!==R.number){const i=this._getOrReturnCtx(n);return b(i,{code:a.invalid_type,expected:R.number,received:i.parsedType}),K}let o=void 0;const t=new en;for(let i of this._def.checks)if(i.kind==="int"){if(!H.isInteger(n.data))o=this._getOrReturnCtx(n,o),b(o,{code:a.invalid_type,expected:"integer",received:"float",message:i.message}),t.dirty()}else if(i.kind==="min"){if(i.inclusive?n.data<i.value:n.data<=i.value)o=this._getOrReturnCtx(n,o),b(o,{code:a.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),t.dirty()}else if(i.kind==="max"){if(i.inclusive?n.data>i.value:n.data>=i.value)o=this._getOrReturnCtx(n,o),b(o,{code:a.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),t.dirty()}else if(i.kind==="multipleOf"){if(di(n.data,i.value)!==0)o=this._getOrReturnCtx(n,o),b(o,{code:a.not_multiple_of,multipleOf:i.value,message:i.message}),t.dirty()}else if(i.kind==="finite"){if(!Number.isFinite(n.data))o=this._getOrReturnCtx(n,o),b(o,{code:a.not_finite,message:i.message}),t.dirty()}else H.assertNever(i);return{status:t.value,value:n.data}}gte(n,e){return this.setLimit("min",n,!0,A.toString(e))}gt(n,e){return this.setLimit("min",n,!1,A.toString(e))}lte(n,e){return this.setLimit("max",n,!0,A.toString(e))}lt(n,e){return this.setLimit("max",n,!1,A.toString(e))}setLimit(n,e,o,t){return new Gn({...this._def,checks:[...this._def.checks,{kind:n,value:e,inclusive:o,message:A.toString(t)}]})}_addCheck(n){return new Gn({...this._def,checks:[...this._def.checks,n]})}int(n){return this._addCheck({kind:"int",message:A.toString(n)})}positive(n){return this._addCheck({kind:"min",value:0,inclusive:!1,message:A.toString(n)})}negative(n){return this._addCheck({kind:"max",value:0,inclusive:!1,message:A.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:0,inclusive:!0,message:A.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:0,inclusive:!0,message:A.toString(n)})}multipleOf(n,e){return this._addCheck({kind:"multipleOf",value:n,message:A.toString(e)})}finite(n){return this._addCheck({kind:"finite",message:A.toString(n)})}safe(n){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:A.toString(n)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:A.toString(n)})}get minValue(){let n=null;for(let e of this._def.checks)if(e.kind==="min"){if(n===null||e.value>n)n=e.value}return n}get maxValue(){let n=null;for(let e of this._def.checks)if(e.kind==="max"){if(n===null||e.value<n)n=e.value}return n}get isInt(){return!!this._def.checks.find((n)=>n.kind==="int"||n.kind==="multipleOf"&&H.isInteger(n.value))}get isFinite(){let n=null,e=null;for(let o of this._def.checks)if(o.kind==="finite"||o.kind==="int"||o.kind==="multipleOf")return!0;else if(o.kind==="min"){if(e===null||o.value>e)e=o.value}else if(o.kind==="max"){if(n===null||o.value<n)n=o.value}return Number.isFinite(e)&&Number.isFinite(n)}}Gn.create=(n)=>{return new Gn({checks:[],typeName:$.ZodNumber,coerce:(n===null||n===void 0?void 0:n.coerce)||!1,...x(n)})};class En extends s{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(n){if(this._def.coerce)n.data=BigInt(n.data);if(this._getType(n)!==R.bigint){const i=this._getOrReturnCtx(n);return b(i,{code:a.invalid_type,expected:R.bigint,received:i.parsedType}),K}let o=void 0;const t=new en;for(let i of this._def.checks)if(i.kind==="min"){if(i.inclusive?n.data<i.value:n.data<=i.value)o=this._getOrReturnCtx(n,o),b(o,{code:a.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),t.dirty()}else if(i.kind==="max"){if(i.inclusive?n.data>i.value:n.data>=i.value)o=this._getOrReturnCtx(n,o),b(o,{code:a.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),t.dirty()}else if(i.kind==="multipleOf"){if(n.data%i.value!==BigInt(0))o=this._getOrReturnCtx(n,o),b(o,{code:a.not_multiple_of,multipleOf:i.value,message:i.message}),t.dirty()}else H.assertNever(i);return{status:t.value,value:n.data}}gte(n,e){return this.setLimit("min",n,!0,A.toString(e))}gt(n,e){return this.setLimit("min",n,!1,A.toString(e))}lte(n,e){return this.setLimit("max",n,!0,A.toString(e))}lt(n,e){return this.setLimit("max",n,!1,A.toString(e))}setLimit(n,e,o,t){return new En({...this._def,checks:[...this._def.checks,{kind:n,value:e,inclusive:o,message:A.toString(t)}]})}_addCheck(n){return new En({...this._def,checks:[...this._def.checks,n]})}positive(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:A.toString(n)})}negative(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:A.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:A.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:A.toString(n)})}multipleOf(n,e){return this._addCheck({kind:"multipleOf",value:n,message:A.toString(e)})}get minValue(){let n=null;for(let e of this._def.checks)if(e.kind==="min"){if(n===null||e.value>n)n=e.value}return n}get maxValue(){let n=null;for(let e of this._def.checks)if(e.kind==="max"){if(n===null||e.value<n)n=e.value}return n}}En.create=(n)=>{var e;return new En({checks:[],typeName:$.ZodBigInt,coerce:(e=n===null||n===void 0?void 0:n.coerce)!==null&&e!==void 0?e:!1,...x(n)})};class le extends s{_parse(n){if(this._def.coerce)n.data=Boolean(n.data);if(this._getType(n)!==R.boolean){const o=this._getOrReturnCtx(n);return b(o,{code:a.invalid_type,expected:R.boolean,received:o.parsedType}),K}return tn(n.data)}}le.create=(n)=>{return new le({typeName:$.ZodBoolean,coerce:(n===null||n===void 0?void 0:n.coerce)||!1,...x(n)})};class Un extends s{_parse(n){if(this._def.coerce)n.data=new Date(n.data);if(this._getType(n)!==R.date){const i=this._getOrReturnCtx(n);return b(i,{code:a.invalid_type,expected:R.date,received:i.parsedType}),K}if(isNaN(n.data.getTime())){const i=this._getOrReturnCtx(n);return b(i,{code:a.invalid_date}),K}const o=new en;let t=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(n.data.getTime()<i.value)t=this._getOrReturnCtx(n,t),b(t,{code:a.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),o.dirty()}else if(i.kind==="max"){if(n.data.getTime()>i.value)t=this._getOrReturnCtx(n,t),b(t,{code:a.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),o.dirty()}else H.assertNever(i);return{status:o.value,value:new Date(n.data.getTime())}}_addCheck(n){return new Un({...this._def,checks:[...this._def.checks,n]})}min(n,e){return this._addCheck({kind:"min",value:n.getTime(),message:A.toString(e)})}max(n,e){return this._addCheck({kind:"max",value:n.getTime(),message:A.toString(e)})}get minDate(){let n=null;for(let e of this._def.checks)if(e.kind==="min"){if(n===null||e.value>n)n=e.value}return n!=null?new Date(n):null}get maxDate(){let n=null;for(let e of this._def.checks)if(e.kind==="max"){if(n===null||e.value<n)n=e.value}return n!=null?new Date(n):null}}Un.create=(n)=>{return new Un({checks:[],coerce:(n===null||n===void 0?void 0:n.coerce)||!1,typeName:$.ZodDate,...x(n)})};class Xe extends s{_parse(n){if(this._getType(n)!==R.symbol){const o=this._getOrReturnCtx(n);return b(o,{code:a.invalid_type,expected:R.symbol,received:o.parsedType}),K}return tn(n.data)}}Xe.create=(n)=>{return new Xe({typeName:$.ZodSymbol,...x(n)})};class me extends s{_parse(n){if(this._getType(n)!==R.undefined){const o=this._getOrReturnCtx(n);return b(o,{code:a.invalid_type,expected:R.undefined,received:o.parsedType}),K}return tn(n.data)}}me.create=(n)=>{return new me({typeName:$.ZodUndefined,...x(n)})};class fe extends s{_parse(n){if(this._getType(n)!==R.null){const o=this._getOrReturnCtx(n);return b(o,{code:a.invalid_type,expected:R.null,received:o.parsedType}),K}return tn(n.data)}}fe.create=(n)=>{return new fe({typeName:$.ZodNull,...x(n)})};class hn extends s{constructor(){super(...arguments);this._any=!0}_parse(n){return tn(n.data)}}hn.create=(n)=>{return new hn({typeName:$.ZodAny,...x(n)})};class Yn extends s{constructor(){super(...arguments);this._unknown=!0}_parse(n){return tn(n.data)}}Yn.create=(n)=>{return new Yn({typeName:$.ZodUnknown,...x(n)})};class Cn extends s{_parse(n){const e=this._getOrReturnCtx(n);return b(e,{code:a.invalid_type,expected:R.never,received:e.parsedType}),K}}Cn.create=(n)=>{return new Cn({typeName:$.ZodNever,...x(n)})};class He extends s{_parse(n){if(this._getType(n)!==R.undefined){const o=this._getOrReturnCtx(n);return b(o,{code:a.invalid_type,expected:R.void,received:o.parsedType}),K}return tn(n.data)}}He.create=(n)=>{return new He({typeName:$.ZodVoid,...x(n)})};class gn extends s{_parse(n){const{ctx:e,status:o}=this._processInputParams(n),t=this._def;if(e.parsedType!==R.array)return b(e,{code:a.invalid_type,expected:R.array,received:e.parsedType}),K;if(t.exactLength!==null){const r=e.data.length>t.exactLength.value,l=e.data.length<t.exactLength.value;if(r||l)b(e,{code:r?a.too_big:a.too_small,minimum:l?t.exactLength.value:void 0,maximum:r?t.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:t.exactLength.message}),o.dirty()}if(t.minLength!==null){if(e.data.length<t.minLength.value)b(e,{code:a.too_small,minimum:t.minLength.value,type:"array",inclusive:!0,exact:!1,message:t.minLength.message}),o.dirty()}if(t.maxLength!==null){if(e.data.length>t.maxLength.value)b(e,{code:a.too_big,maximum:t.maxLength.value,type:"array",inclusive:!0,exact:!1,message:t.maxLength.message}),o.dirty()}if(e.common.async)return Promise.all([...e.data].map((r,l)=>{return t.type._parseAsync(new $n(e,r,e.path,l))})).then((r)=>{return en.mergeArray(o,r)});const i=[...e.data].map((r,l)=>{return t.type._parseSync(new $n(e,r,e.path,l))});return en.mergeArray(o,i)}get element(){return this._def.type}min(n,e){return new gn({...this._def,minLength:{value:n,message:A.toString(e)}})}max(n,e){return new gn({...this._def,maxLength:{value:n,message:A.toString(e)}})}length(n,e){return new gn({...this._def,exactLength:{value:n,message:A.toString(e)}})}nonempty(n){return this.min(1,n)}}gn.create=(n,e)=>{return new gn({type:n,minLength:null,maxLength:null,exactLength:null,typeName:$.ZodArray,...x(e)})};class h extends s{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const n=this._def.shape(),e=H.objectKeys(n);return this._cached={shape:n,keys:e}}_parse(n){if(this._getType(n)!==R.object){const f=this._getOrReturnCtx(n);return b(f,{code:a.invalid_type,expected:R.object,received:f.parsedType}),K}const{status:o,ctx:t}=this._processInputParams(n),{shape:i,keys:r}=this._getCached(),l=[];if(!(this._def.catchall instanceof Cn&&this._def.unknownKeys==="strip")){for(let f in t.data)if(!r.includes(f))l.push(f)}const m=[];for(let f of r){const y=i[f],c=t.data[f];m.push({key:{status:"valid",value:f},value:y._parse(new $n(t,c,t.path,f)),alwaysSet:f in t.data})}if(this._def.catchall instanceof Cn){const f=this._def.unknownKeys;if(f==="passthrough")for(let y of l)m.push({key:{status:"valid",value:y},value:{status:"valid",value:t.data[y]}});else if(f==="strict"){if(l.length>0)b(t,{code:a.unrecognized_keys,keys:l}),o.dirty()}else if(f==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const f=this._def.catchall;for(let y of l){const c=t.data[y];m.push({key:{status:"valid",value:y},value:f._parse(new $n(t,c,t.path,y)),alwaysSet:y in t.data})}}if(t.common.async)return Promise.resolve().then(async()=>{const f=[];for(let y of m){const c=await y.key,T=await y.value;f.push({key:c,value:T,alwaysSet:y.alwaysSet})}return f}).then((f)=>{return en.mergeObjectSync(o,f)});else return en.mergeObjectSync(o,m)}get shape(){return this._def.shape()}strict(n){return A.errToObj,new h({...this._def,unknownKeys:"strict",...n!==void 0?{errorMap:(e,o)=>{var t,i,r,l;const m=(r=(i=(t=this._def).errorMap)===null||i===void 0?void 0:i.call(t,e,o).message)!==null&&r!==void 0?r:o.defaultError;if(e.code==="unrecognized_keys")return{message:(l=A.errToObj(n).message)!==null&&l!==void 0?l:m};return{message:m}}}:{}})}strip(){return new h({...this._def,unknownKeys:"strip"})}passthrough(){return new h({...this._def,unknownKeys:"passthrough"})}extend(n){return new h({...this._def,shape:()=>({...this._def.shape(),...n})})}merge(n){return new h({unknownKeys:n._def.unknownKeys,catchall:n._def.catchall,shape:()=>({...this._def.shape(),...n._def.shape()}),typeName:$.ZodObject})}setKey(n,e){return this.augment({[n]:e})}catchall(n){return new h({...this._def,catchall:n})}pick(n){const e={};return H.objectKeys(n).forEach((o)=>{if(n[o]&&this.shape[o])e[o]=this.shape[o]}),new h({...this._def,shape:()=>e})}omit(n){const e={};return H.objectKeys(this.shape).forEach((o)=>{if(!n[o])e[o]=this.shape[o]}),new h({...this._def,shape:()=>e})}deepPartial(){return oe(this)}partial(n){const e={};return H.objectKeys(this.shape).forEach((o)=>{const t=this.shape[o];if(n&&!n[o])e[o]=t;else e[o]=t.optional()}),new h({...this._def,shape:()=>e})}required(n){const e={};return H.objectKeys(this.shape).forEach((o)=>{if(n&&!n[o])e[o]=this.shape[o];else{let i=this.shape[o];while(i instanceof Jn)i=i._def.innerType;e[o]=i}}),new h({...this._def,shape:()=>e})}keyof(){return Pt(H.objectKeys(this.shape))}}h.create=(n,e)=>{return new h({shape:()=>n,unknownKeys:"strip",catchall:Cn.create(),typeName:$.ZodObject,...x(e)})};h.strictCreate=(n,e)=>{return new h({shape:()=>n,unknownKeys:"strict",catchall:Cn.create(),typeName:$.ZodObject,...x(e)})};h.lazycreate=(n,e)=>{return new h({shape:n,unknownKeys:"strip",catchall:Cn.create(),typeName:$.ZodObject,...x(e)})};class ye extends s{_parse(n){const{ctx:e}=this._processInputParams(n),o=this._def.options;function t(i){for(let l of i)if(l.result.status==="valid")return l.result;for(let l of i)if(l.result.status==="dirty")return e.common.issues.push(...l.ctx.common.issues),l.result;const r=i.map((l)=>new an(l.ctx.common.issues));return b(e,{code:a.invalid_union,unionErrors:r}),K}if(e.common.async)return Promise.all(o.map(async(i)=>{const r={...e,common:{...e.common,issues:[]},parent:null};return{result:await i._parseAsync({data:e.data,path:e.path,parent:r}),ctx:r}})).then(t);else{let i=void 0;const r=[];for(let m of o){const f={...e,common:{...e.common,issues:[]},parent:null},y=m._parseSync({data:e.data,path:e.path,parent:f});if(y.status==="valid")return y;else if(y.status==="dirty"&&!i)i={result:y,ctx:f};if(f.common.issues.length)r.push(f.common.issues)}if(i)return e.common.issues.push(...i.ctx.common.issues),i.result;const l=r.map((m)=>new an(m));return b(e,{code:a.invalid_union,unionErrors:l}),K}}get options(){return this._def.options}}ye.create=(n,e)=>{return new ye({options:n,typeName:$.ZodUnion,...x(e)})};var Bn=(n)=>{if(n instanceof ae)return Bn(n.schema);else if(n instanceof bn)return Bn(n.innerType());else if(n instanceof Se)return[n.value];else if(n instanceof pn)return n.options;else if(n instanceof Te)return H.objectValues(n.enum);else if(n instanceof ke)return Bn(n._def.innerType);else if(n instanceof me)return[void 0];else if(n instanceof fe)return[null];else if(n instanceof Jn)return[void 0,...Bn(n.unwrap())];else if(n instanceof un)return[null,...Bn(n.unwrap())];else if(n instanceof fo)return Bn(n.unwrap());else if(n instanceof Me)return Bn(n.unwrap());else if(n instanceof be)return Bn(n._def.innerType);else return[]};class mo extends s{_parse(n){const{ctx:e}=this._processInputParams(n);if(e.parsedType!==R.object)return b(e,{code:a.invalid_type,expected:R.object,received:e.parsedType}),K;const o=this.discriminator,t=e.data[o],i=this.optionsMap.get(t);if(!i)return b(e,{code:a.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[o]}),K;if(e.common.async)return i._parseAsync({data:e.data,path:e.path,parent:e});else return i._parseSync({data:e.data,path:e.path,parent:e})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(n,e,o){const t=new Map;for(let i of e){const r=Bn(i.shape[n]);if(!r.length)throw new Error(`A discriminator value for key \`${n}\` could not be extracted from all schema options`);for(let l of r){if(t.has(l))throw new Error(`Discriminator property ${String(n)} has duplicate value ${String(l)}`);t.set(l,i)}}return new mo({typeName:$.ZodDiscriminatedUnion,discriminator:n,options:e,optionsMap:t,...x(o)})}}class ce extends s{_parse(n){const{status:e,ctx:o}=this._processInputParams(n),t=(i,r)=>{if(po(i)||po(r))return K;const l=Vo(i.value,r.value);if(!l.valid)return b(o,{code:a.invalid_intersection_types}),K;if(Lo(i)||Lo(r))e.dirty();return{status:e.value,value:l.data}};if(o.common.async)return Promise.all([this._def.left._parseAsync({data:o.data,path:o.path,parent:o}),this._def.right._parseAsync({data:o.data,path:o.path,parent:o})]).then(([i,r])=>t(i,r));else return t(this._def.left._parseSync({data:o.data,path:o.path,parent:o}),this._def.right._parseSync({data:o.data,path:o.path,parent:o}))}}ce.create=(n,e,o)=>{return new ce({left:n,right:e,typeName:$.ZodIntersection,...x(o)})};class On extends s{_parse(n){const{status:e,ctx:o}=this._processInputParams(n);if(o.parsedType!==R.array)return b(o,{code:a.invalid_type,expected:R.array,received:o.parsedType}),K;if(o.data.length<this._def.items.length)return b(o,{code:a.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),K;if(!this._def.rest&&o.data.length>this._def.items.length)b(o,{code:a.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),e.dirty();const i=[...o.data].map((r,l)=>{const m=this._def.items[l]||this._def.rest;if(!m)return null;return m._parse(new $n(o,r,o.path,l))}).filter((r)=>!!r);if(o.common.async)return Promise.all(i).then((r)=>{return en.mergeArray(e,r)});else return en.mergeArray(e,i)}get items(){return this._def.items}rest(n){return new On({...this._def,rest:n})}}On.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new On({items:n,typeName:$.ZodTuple,rest:null,...x(e)})};class qe extends s{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){const{status:e,ctx:o}=this._processInputParams(n);if(o.parsedType!==R.object)return b(o,{code:a.invalid_type,expected:R.object,received:o.parsedType}),K;const t=[],i=this._def.keyType,r=this._def.valueType;for(let l in o.data)t.push({key:i._parse(new $n(o,l,o.path,l)),value:r._parse(new $n(o,o.data[l],o.path,l)),alwaysSet:l in o.data});if(o.common.async)return en.mergeObjectAsync(e,t);else return en.mergeObjectSync(e,t)}get element(){return this._def.valueType}static create(n,e,o){if(e instanceof s)return new qe({keyType:n,valueType:e,typeName:$.ZodRecord,...x(o)});return new qe({keyType:Fn.create(),valueType:n,typeName:$.ZodRecord,...x(e)})}}class Qe extends s{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(n){const{status:e,ctx:o}=this._processInputParams(n);if(o.parsedType!==R.map)return b(o,{code:a.invalid_type,expected:R.map,received:o.parsedType}),K;const t=this._def.keyType,i=this._def.valueType,r=[...o.data.entries()].map(([l,m],f)=>{return{key:t._parse(new $n(o,l,o.path,[f,"key"])),value:i._parse(new $n(o,m,o.path,[f,"value"]))}});if(o.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(let m of r){const f=await m.key,y=await m.value;if(f.status==="aborted"||y.status==="aborted")return K;if(f.status==="dirty"||y.status==="dirty")e.dirty();l.set(f.value,y.value)}return{status:e.value,value:l}})}else{const l=new Map;for(let m of r){const{key:f,value:y}=m;if(f.status==="aborted"||y.status==="aborted")return K;if(f.status==="dirty"||y.status==="dirty")e.dirty();l.set(f.value,y.value)}return{status:e.value,value:l}}}}Qe.create=(n,e,o)=>{return new Qe({valueType:e,keyType:n,typeName:$.ZodMap,...x(o)})};class Dn extends s{_parse(n){const{status:e,ctx:o}=this._processInputParams(n);if(o.parsedType!==R.set)return b(o,{code:a.invalid_type,expected:R.set,received:o.parsedType}),K;const t=this._def;if(t.minSize!==null){if(o.data.size<t.minSize.value)b(o,{code:a.too_small,minimum:t.minSize.value,type:"set",inclusive:!0,exact:!1,message:t.minSize.message}),e.dirty()}if(t.maxSize!==null){if(o.data.size>t.maxSize.value)b(o,{code:a.too_big,maximum:t.maxSize.value,type:"set",inclusive:!0,exact:!1,message:t.maxSize.message}),e.dirty()}const i=this._def.valueType;function r(m){const f=new Set;for(let y of m){if(y.status==="aborted")return K;if(y.status==="dirty")e.dirty();f.add(y.value)}return{status:e.value,value:f}}const l=[...o.data.values()].map((m,f)=>i._parse(new $n(o,m,o.path,f)));if(o.common.async)return Promise.all(l).then((m)=>r(m));else return r(l)}min(n,e){return new Dn({...this._def,minSize:{value:n,message:A.toString(e)}})}max(n,e){return new Dn({...this._def,maxSize:{value:n,message:A.toString(e)}})}size(n,e){return this.min(n,e).max(n,e)}nonempty(n){return this.min(1,n)}}Dn.create=(n,e)=>{return new Dn({valueType:n,minSize:null,maxSize:null,typeName:$.ZodSet,...x(e)})};class ie extends s{constructor(){super(...arguments);this.validate=this.implement}_parse(n){const{ctx:e}=this._processInputParams(n);if(e.parsedType!==R.function)return b(e,{code:a.invalid_type,expected:R.function,received:e.parsedType}),K;function o(l,m){return ro({data:l,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,io(),re].filter((f)=>!!f),issueData:{code:a.invalid_arguments,argumentsError:m}})}function t(l,m){return ro({data:l,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,io(),re].filter((f)=>!!f),issueData:{code:a.invalid_return_type,returnTypeError:m}})}const i={errorMap:e.common.contextualErrorMap},r=e.data;if(this._def.returns instanceof In){const l=this;return tn(async function(...m){const f=new an([]),y=await l._def.args.parseAsync(m,i).catch((F)=>{throw f.addIssue(o(m,F)),f}),c=await Reflect.apply(r,this,y);return await l._def.returns._def.type.parseAsync(c,i).catch((F)=>{throw f.addIssue(t(c,F)),f})})}else{const l=this;return tn(function(...m){const f=l._def.args.safeParse(m,i);if(!f.success)throw new an([o(m,f.error)]);const y=Reflect.apply(r,this,f.data),c=l._def.returns.safeParse(y,i);if(!c.success)throw new an([t(y,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...n){return new ie({...this._def,args:On.create(n).rest(Yn.create())})}returns(n){return new ie({...this._def,returns:n})}implement(n){return this.parse(n)}strictImplement(n){return this.parse(n)}static create(n,e,o){return new ie({args:n?n:On.create([]).rest(Yn.create()),returns:e||Yn.create(),typeName:$.ZodFunction,...x(o)})}}class ae extends s{get schema(){return this._def.getter()}_parse(n){const{ctx:e}=this._processInputParams(n);return this._def.getter()._parse({data:e.data,path:e.path,parent:e})}}ae.create=(n,e)=>{return new ae({getter:n,typeName:$.ZodLazy,...x(e)})};class Se extends s{_parse(n){if(n.data!==this._def.value){const e=this._getOrReturnCtx(n);return b(e,{received:e.data,code:a.invalid_literal,expected:this._def.value}),K}return{status:"valid",value:n.data}}get value(){return this._def.value}}Se.create=(n,e)=>{return new Se({value:n,typeName:$.ZodLiteral,...x(e)})};class pn extends s{constructor(){super(...arguments);ue.set(this,void 0)}_parse(n){if(typeof n.data!=="string"){const e=this._getOrReturnCtx(n),o=this._def.values;return b(e,{expected:H.joinValues(o),received:e.parsedType,code:a.invalid_type}),K}if(!lo(this,ue,"f"))Dt(this,ue,new Set(this._def.values),"f");if(!lo(this,ue,"f").has(n.data)){const e=this._getOrReturnCtx(n),o=this._def.values;return b(e,{received:e.data,code:a.invalid_enum_value,options:o}),K}return tn(n.data)}get options(){return this._def.values}get enum(){const n={};for(let e of this._def.values)n[e]=e;return n}get Values(){const n={};for(let e of this._def.values)n[e]=e;return n}get Enum(){const n={};for(let e of this._def.values)n[e]=e;return n}extract(n,e=this._def){return pn.create(n,{...this._def,...e})}exclude(n,e=this._def){return pn.create(this.options.filter((o)=>!n.includes(o)),{...this._def,...e})}}ue=new WeakMap;pn.create=Pt;class Te extends s{constructor(){super(...arguments);je.set(this,void 0)}_parse(n){const e=H.getValidEnumValues(this._def.values),o=this._getOrReturnCtx(n);if(o.parsedType!==R.string&&o.parsedType!==R.number){const t=H.objectValues(e);return b(o,{expected:H.joinValues(t),received:o.parsedType,code:a.invalid_type}),K}if(!lo(this,je,"f"))Dt(this,je,new Set(H.getValidEnumValues(this._def.values)),"f");if(!lo(this,je,"f").has(n.data)){const t=H.objectValues(e);return b(o,{received:o.data,code:a.invalid_enum_value,options:t}),K}return tn(n.data)}get enum(){return this._def.values}}je=new WeakMap;Te.create=(n,e)=>{return new Te({values:n,typeName:$.ZodNativeEnum,...x(e)})};class In extends s{unwrap(){return this._def.type}_parse(n){const{ctx:e}=this._processInputParams(n);if(e.parsedType!==R.promise&&e.common.async===!1)return b(e,{code:a.invalid_type,expected:R.promise,received:e.parsedType}),K;const o=e.parsedType===R.promise?e.data:Promise.resolve(e.data);return tn(o.then((t)=>{return this._def.type.parseAsync(t,{path:e.path,errorMap:e.common.contextualErrorMap})}))}}In.create=(n,e)=>{return new In({type:n,typeName:$.ZodPromise,...x(e)})};class bn extends s{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(n){const{status:e,ctx:o}=this._processInputParams(n),t=this._def.effect||null,i={addIssue:(r)=>{if(b(o,r),r.fatal)e.abort();else e.dirty()},get path(){return o.path}};if(i.addIssue=i.addIssue.bind(i),t.type==="preprocess"){const r=t.transform(o.data,i);if(o.common.async)return Promise.resolve(r).then(async(l)=>{if(e.value==="aborted")return K;const m=await this._def.schema._parseAsync({data:l,path:o.path,parent:o});if(m.status==="aborted")return K;if(m.status==="dirty")return te(m.value);if(e.value==="dirty")return te(m.value);return m});else{if(e.value==="aborted")return K;const l=this._def.schema._parseSync({data:r,path:o.path,parent:o});if(l.status==="aborted")return K;if(l.status==="dirty")return te(l.value);if(e.value==="dirty")return te(l.value);return l}}if(t.type==="refinement"){const r=(l)=>{const m=t.refinement(l,i);if(o.common.async)return Promise.resolve(m);if(m instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(o.common.async===!1){const l=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});if(l.status==="aborted")return K;if(l.status==="dirty")e.dirty();return r(l.value),{status:e.value,value:l.value}}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then((l)=>{if(l.status==="aborted")return K;if(l.status==="dirty")e.dirty();return r(l.value).then(()=>{return{status:e.value,value:l.value}})})}if(t.type==="transform")if(o.common.async===!1){const r=this._def.schema._parseSync({data:o.data,path:o.path,parent:o});if(!_e(r))return r;const l=t.transform(r.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:e.value,value:l}}else return this._def.schema._parseAsync({data:o.data,path:o.path,parent:o}).then((r)=>{if(!_e(r))return r;return Promise.resolve(t.transform(r.value,i)).then((l)=>({status:e.value,value:l}))});H.assertNever(t)}}bn.create=(n,e,o)=>{return new bn({schema:n,typeName:$.ZodEffects,effect:e,...x(o)})};bn.createWithPreprocess=(n,e,o)=>{return new bn({schema:e,effect:{type:"preprocess",transform:n},typeName:$.ZodEffects,...x(o)})};class Jn extends s{_parse(n){if(this._getType(n)===R.undefined)return tn(void 0);return this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}Jn.create=(n,e)=>{return new Jn({innerType:n,typeName:$.ZodOptional,...x(e)})};class un extends s{_parse(n){if(this._getType(n)===R.null)return tn(null);return this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}un.create=(n,e)=>{return new un({innerType:n,typeName:$.ZodNullable,...x(e)})};class ke extends s{_parse(n){const{ctx:e}=this._processInputParams(n);let o=e.data;if(e.parsedType===R.undefined)o=this._def.defaultValue();return this._def.innerType._parse({data:o,path:e.path,parent:e})}removeDefault(){return this._def.innerType}}ke.create=(n,e)=>{return new ke({innerType:n,typeName:$.ZodDefault,defaultValue:typeof e.default==="function"?e.default:()=>e.default,...x(e)})};class be extends s{_parse(n){const{ctx:e}=this._processInputParams(n),o={...e,common:{...e.common,issues:[]}},t=this._def.innerType._parse({data:o.data,path:o.path,parent:{...o}});if(ze(t))return t.then((i)=>{return{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new an(o.common.issues)},input:o.data})}});else return{status:"valid",value:t.status==="valid"?t.value:this._def.catchValue({get error(){return new an(o.common.issues)},input:o.data})}}removeCatch(){return this._def.innerType}}be.create=(n,e)=>{return new be({innerType:n,typeName:$.ZodCatch,catchValue:typeof e.catch==="function"?e.catch:()=>e.catch,...x(e)})};class Ye extends s{_parse(n){if(this._getType(n)!==R.nan){const o=this._getOrReturnCtx(n);return b(o,{code:a.invalid_type,expected:R.nan,received:o.parsedType}),K}return{status:"valid",value:n.data}}}Ye.create=(n)=>{return new Ye({typeName:$.ZodNaN,...x(n)})};var Zi=Symbol("zod_brand");class fo extends s{_parse(n){const{ctx:e}=this._processInputParams(n),o=e.data;return this._def.type._parse({data:o,path:e.path,parent:e})}unwrap(){return this._def.type}}class Ge extends s{_parse(n){const{status:e,ctx:o}=this._processInputParams(n);if(o.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:o.data,path:o.path,parent:o});if(i.status==="aborted")return K;if(i.status==="dirty")return e.dirty(),te(i.value);else return this._def.out._parseAsync({data:i.value,path:o.path,parent:o})})();else{const t=this._def.in._parseSync({data:o.data,path:o.path,parent:o});if(t.status==="aborted")return K;if(t.status==="dirty")return e.dirty(),{status:"dirty",value:t.value};else return this._def.out._parseSync({data:t.value,path:o.path,parent:o})}}static create(n,e){return new Ge({in:n,out:e,typeName:$.ZodPipeline})}}class Me extends s{_parse(n){const e=this._def.innerType._parse(n),o=(t)=>{if(_e(t))t.value=Object.freeze(t.value);return t};return ze(e)?e.then((t)=>o(t)):o(e)}unwrap(){return this._def.innerType}}Me.create=(n,e)=>{return new Me({innerType:n,typeName:$.ZodReadonly,...x(e)})};var nr={object:h.lazycreate},$;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})($||($={}));var er=(n,e={message:`Input not instance of ${n.name}`})=>dt((o)=>o instanceof n,e),Zt=Fn.create,ni=Gn.create,or=Ye.create,tr=En.create,ei=le.create,ir=Un.create,rr=Xe.create,lr=me.create,mr=fe.create,fr=hn.create,yr=Yn.create,cr=Cn.create,ar=He.create,Sr=gn.create,Ee=h.create,Tr=h.strictCreate,kr=ye.create,br=mo.create,Mr=ce.create,Rr=On.create,Ar=qe.create,Fr=Qe.create,gr=Dn.create,Jr=ie.create,$r=ae.create,Kr=Se.create,wr=pn.create,Cr=Te.create,Or=In.create,Ut=bn.create,Wr=Jn.create,xr=un.create,sr=bn.createWithPreprocess,Br=Ge.create,ur=()=>Zt().optional(),jr=()=>ni().optional(),_r=()=>ei().optional(),zr={string:(n)=>Fn.create({...n,coerce:!0}),number:(n)=>Gn.create({...n,coerce:!0}),boolean:(n)=>le.create({...n,coerce:!0}),bigint:(n)=>En.create({...n,coerce:!0}),date:(n)=>Un.create({...n,coerce:!0})},Xr=K,rn=Object.freeze({__proto__:null,defaultErrorMap:re,setErrorMap:Hi,getErrorMap:io,makeIssue:ro,EMPTY_PATH:qi,addIssueToContext:b,ParseStatus:en,INVALID:K,DIRTY:te,OK:tn,isAborted:po,isDirty:Lo,isValid:_e,isAsync:ze,get util(){return H},get objectUtil(){return Eo},ZodParsedType:R,getParsedType:Qn,ZodType:s,datetimeRegex:vt,ZodString:Fn,ZodNumber:Gn,ZodBigInt:En,ZodBoolean:le,ZodDate:Un,ZodSymbol:Xe,ZodUndefined:me,ZodNull:fe,ZodAny:hn,ZodUnknown:Yn,ZodNever:Cn,ZodVoid:He,ZodArray:gn,ZodObject:h,ZodUnion:ye,ZodDiscriminatedUnion:mo,ZodIntersection:ce,ZodTuple:On,ZodRecord:qe,ZodMap:Qe,ZodSet:Dn,ZodFunction:ie,ZodLazy:ae,ZodLiteral:Se,ZodEnum:pn,ZodNativeEnum:Te,ZodPromise:In,ZodEffects:bn,ZodTransformer:bn,ZodOptional:Jn,ZodNullable:un,ZodDefault:ke,ZodCatch:be,ZodNaN:Ye,BRAND:Zi,ZodBranded:fo,ZodPipeline:Ge,ZodReadonly:Me,custom:dt,Schema:s,ZodSchema:s,late:nr,get ZodFirstPartyTypeKind(){return $},coerce:zr,any:fr,array:Sr,bigint:tr,boolean:ei,date:ir,discriminatedUnion:br,effect:Ut,enum:wr,function:Jr,instanceof:er,intersection:Mr,lazy:$r,literal:Kr,map:Fr,nan:or,nativeEnum:Cr,never:cr,null:mr,nullable:xr,number:ni,object:Ee,oboolean:_r,onumber:jr,optional:Wr,ostring:ur,pipeline:Br,preprocess:sr,promise:Or,record:Ar,set:gr,strictObject:Tr,string:Zt,symbol:rr,transformer:Ut,tuple:Rr,undefined:lr,union:kr,unknown:yr,void:ar,NEVER:Xr,ZodIssueCode:a,quotelessJson:Xi,ZodError:an});function oi(n){const e=n.runtimeEnvStrict??n.runtimeEnv??process.env;if(n.emptyStringAsUndefined??!1){for(let[k,g]of Object.entries(e))if(g==="")delete e[k]}if(!!n.skipValidation)return e;const i=typeof n.client==="object"?n.client:{},r=typeof n.server==="object"?n.server:{},l=typeof n.shared==="object"?n.shared:{},m=Ee(i),f=Ee(r),y=Ee(l),c=n.isServer??(typeof window==="undefined"||("Deno"in window)),T=m.merge(y),F=f.merge(y).merge(m),u=c?F.safeParse(e):T.safeParse(e),G=n.onValidationError??((k)=>{throw console.error("\u274C Invalid environment variables:",k.flatten().fieldErrors),new Error("Invalid environment variables")}),Sn=n.onInvalidAccess??((k)=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(u.success===!1)return G(u.error);const O=(k)=>{if(!n.clientPrefix)return!0;return!k.startsWith(n.clientPrefix)&&!(k in y.shape)},E=(k)=>{return c||!O(k)},p=(k)=>{return k==="__esModule"||k==="$$typeof"},q=(n.extends??[]).reduce((k,g)=>{return Object.assign(k,g)},{}),fn=Object.assign(u.data,q);return new Proxy(fn,{get(k,g){if(typeof g!=="string")return;if(p(g))return;if(!E(g))return Sn(g);return Reflect.get(k,g)}})}var fi=Mi(mi(),1);fi.default.config();var Io=oi({isServer:typeof window==="undefined",server:{POSTGRES_USER:rn.string(),POSTGRES_PASSWORD:rn.string(),POSTGRES_DATABASE:rn.string(),POSTGRES_HOST:rn.string(),POSTGRES_PORT:rn.string().transform((n)=>Number.parseInt(n,10)),BACKEND_PORT:rn.string().transform((n)=>Number.parseInt(n,10)),RUN_WORKERS_FROM_SOURCE:rn.union([rn.literal("true"),rn.literal("false")]).optional().transform((n)=>n==="true"),FRONTEND_PORT:rn.string().transform((n)=>Number.parseInt(n,10)),FRONTEND_ORIGINS:rn.string().transform((n)=>D(n)).pipe(rn.array(rn.string()))},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:rn.string()},runtimeEnv:process.env,emptyStringAsUndefined:!0});var No={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};function Po(){_n.logger.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}var _n=new Ho;_n.logger.info(" ready");var vo=ci(import.meta.dir,"..","app");ll({port:Io.FRONTEND_PORT??3333,async fetch(n,e){try{const o=new URL(n.url),t=e.requestIP(n)?.address??"??";if(_n.logger.info(`[${t}]`,n.method,o.pathname),o.pathname==="/")return new Response(Bun.file(ci(vo,"index.html")));if(o.pathname==="/index.html")return Response.redirect("/");const i=il(vo,o.pathname),r=rl(i);if(!r.startsWith(vo))throw 403;if(!await yi(r).exists())throw 404;return new Response(yi(r))}catch(o){if(typeof o==="number")return new Response(No[o],{status:o});if(o instanceof Error)_n.logger.error(o.message);else{const t=ne(o);_n.logger.error("frontend server threw",t)}return new Response(No[500],{status:500})}}});process.on("SIGINT",()=>{_n.logger.info("\u2757 received SIGINT; exiting gracefully"),Po()});process.on("SIGTERM",()=>{_n.logger.info("\u2757 received SIGTERM; exiting gracefully"),Po()});process.on("exit",()=>{_n.logger.info("\u2757 received exit; exiting gracefully"),Po()});_n.logger.info(`\uD83D\uDEEB frontend server running at http://localhost:${Io.FRONTEND_PORT??3333}/`);
3
+ var My=Object.defineProperty;var Fy=(o,n)=>{for(var t in n)My(o,t,{get:n[t],enumerable:!0,configurable:!0,set:(S)=>n[t]=()=>S})};import{join as U0,normalize as V0,resolve as RJ}from"path";function zt(o=Math.random){return o().toString(36).slice(2)}class tS extends Promise{fate;resolve;reject;done=!1;constructor(o){let n,t;super((S,f)=>{n=S,t=f});this.resolve=n,this.reject=t,this.use(o instanceof Promise?o:new Promise(o))}pass(o,n){if(o===this.fate)this.resolve(n),this.done=!0}fail(o,n){if(o===this.fate)this.reject(n),this.done=!0}use(o){if(o instanceof Promise){const n=o;this.fate=n,n.then((t)=>{this.pass(n,t)},(t)=>{this.fail(n,t)})}else this.resolve(o),this.fate=void 0}}function PM(o){return Object.entries(o)}var gM=(o,n,t=ko.STORE)=>{return En(t,{key:`${o.key}:JSON`,get:({get:S})=>n.toJson(S(o)),set:({set:S},f)=>{S(o,n.fromJson(f))}})};function m(o){while(o.child!==null)o=o.child;return o}function lM(o){while(o.parent!==null)o=o.parent;return o}class s{Subscriber;subscribers=new Map;subscribe(o,n){return this.subscribers.set(o,n),()=>{this.unsubscribe(o)}}unsubscribe(o){this.subscribers.delete(o)}next(o){const n=this.subscribers.values();for(let t of n)t(o)}}class af extends s{state;constructor(o){super();this.state=o}next(o){this.state=o,super.next(o)}}function jn(o,n,t){const S={key:n.key,type:"atom_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","atom_family",n.key,`Overwriting an existing ${Gn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const T=new s,F=Object.assign((k)=>{const A=l(k),$={key:n.key,subKey:A},O=`${n.key}(${A})`,w=m(o),G=n.default,r={key:O,default:G instanceof Function?G(k):G};if(n.effects)r.effects=n.effects(k);const H=nn(w,r,$);return T.next({type:"state_creation",token:H}),H},S,{subject:T,install:(k)=>jn(k,n),internalRoles:t});return o.families.set(n.key,F),o.defaults.set(n.key,n.default),S}function eM(o,n){if("mutable"in n)return SS(o,n);return jn(o,n)}function hn(o,n,t){const S={key:n.key,type:"readonly_selector_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","readonly_selector_family",n.key,`Overwriting an existing ${Gn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const T=new s,F=Object.assign((k)=>{const A=l(k),$={key:n.key,subKey:A},O=`${n.key}(${A})`,w=m(o),G=fS(w,{key:O,get:n.get(k)},$);return T.next({type:"state_creation",token:G}),G},S,{internalRoles:t,subject:T,install:(k)=>hn(k,n),default:(k)=>{return n.get(k)({get:(...$)=>Go(o,...$),find:($,O)=>Ro(o,$,O),seek:($,O)=>Eo(o,$,O),json:($)=>ho(o,$)})}});return o.families.set(n.key,F),S}function TS(o,n){if("set"in n)return MS(o,n);return hn(o,n)}function Ht(o,n){const t=l(n),S=`${o.key}(${t})`,f=ky[o.type],T={key:S,type:f};if(f==="molecule")Object.assign(T,{key:n,family:o});else Object.assign(T,{family:{key:o.key,subKey:t}});return Object.assign(T,{counterfeit:!0}),T}var ky={atom_family:"atom",mutable_atom_family:"mutable_atom",selector_family:"selector",readonly_selector_family:"readonly_selector",molecule_family:"molecule"};function Po(o){const n={key:o.key,type:o.type};if("family"in o)n.family=o.family;return n}function mt(o){return dM(ko.STORE,o)}function kt(o){return eM(ko.STORE,o)}function sf(...o){if(o.length===2)return Go(ko.STORE,...o);return Go(ko.STORE,...o)}var oT=(o)=>(n,t,S,f,...T)=>{console[o](`${n} ${t} "${S}" ${f}`,...T)},Ay={error:oT("error"),info:oT("info"),warn:oT("warn")};class nT{o;n;t;constructor(o,n,t=Ay){this.logLevel=o;this.filter=n;this.logger=t}error=(...o)=>{if((this.filter?.(...o)??!0)&&this.logLevel!==null)this.logger.error(...o)};info=(...o)=>{if((this.filter?.(...o)??!0)&&this.logLevel==="info")this.logger.info(...o)};warn=(...o)=>{if((this.filter?.(...o)??!0)&&this.logLevel!=="error"&&this.logLevel!==null)this.logger.warn(...o)}}function ZS(o){return TS(ko.STORE,o)}function FS(o){return tT(o,ko.STORE)}class Fn{a;b;cardinality;relations=new Map;contents=new Map;isContent;makeContentKey=(o,n)=>`${o}:${n}`;warn;getRelatedKeys(o){return this.relations.get(o)}addRelation(o,n){let t=this.relations.get(o),S=this.relations.get(n);if(t)t.add(n);else t=new Set([n]),this.relations.set(o,t);if(S)S.add(o);else S=new Set([o]),this.relations.set(n,S)}deleteRelation(o,n){const t=this.relations.get(o);if(t){if(t.delete(n),t.size===0)this.relations.delete(o);const S=this.relations.get(n);if(S){if(S.delete(o),S.size===0)this.relations.delete(n)}}}replaceRelationsUnsafely(o,n){this.relations.set(o,new Set(n));for(let t of n){const S=new Set([o]);this.relations.set(t,S)}}replaceRelationsSafely(o,n){const t=this.relations.get(o);if(t)for(let S of t){const f=this.relations.get(S);if(f){if(f.size===1)this.relations.delete(S);else f.delete(o);this.contents.delete(this.makeContentKey(o,S))}}this.relations.set(o,new Set(n));for(let S of n){let f=this.relations.get(S);if(f)f.add(o);else f=new Set([o]),this.relations.set(S,f)}}getContentInternal(o){return this.contents.get(o)}setContent(o,n){this.contents.set(o,n)}deleteContent(o){this.contents.delete(o)}constructor(o,n){if(this.a=o.between[0],this.b=o.between[1],this.cardinality=o.cardinality,!n?.externalStore)this.relations=new Map(o.relations?.map(([t,S])=>[t,new Set(S)])),this.contents=new Map(o.contents);if(this.isContent=n?.isContent??null,n?.makeContentKey)this.makeContentKey=n.makeContentKey;if(n?.externalStore){const t=n.externalStore;if(this.has=(S,f)=>t.has(S,f),this.addRelation=(S,f)=>{t.addRelation(S,f)},this.deleteRelation=(S,f)=>{t.deleteRelation(S,f)},this.replaceRelationsSafely=(S,f)=>{t.replaceRelationsSafely(S,f)},this.replaceRelationsUnsafely=(S,f)=>{t.replaceRelationsUnsafely(S,f)},this.getRelatedKeys=(S)=>t.getRelatedKeys(S),t.getContent)this.getContentInternal=(S)=>{return t.getContent(S)},this.setContent=(S,f)=>{t.setContent(S,f)},this.deleteContent=(S)=>{t.deleteContent(S)};for(let[S,f]of o.relations??[])for(let T of f)this.addRelation(S,T);for(let[S,f]of o.contents??[])this.setContent(S,f)}if(n?.warn)this.warn=n.warn}toJSON(){return{between:[this.a,this.b],cardinality:this.cardinality,relations:[...this.relations.entries()].map(([o,n])=>[o,[...n]]),contents:[...this.contents.entries()]}}set(o,...n){const t=typeof n[0]==="string"?n[0]:o[this.b],S=n[1]??typeof n[0]==="string"?void 0:n[0];switch(o=typeof o==="string"?o:o[this.a],this.cardinality){case"1:1":{const f=this.getRelatedKey(o);if(f&&f!==t)this.delete(f,o)}case"1:n":{const f=this.getRelatedKey(t);if(f&&f!==o)this.delete(f,t)}}if(S){const f=this.makeContentKey(o,t);this.setContent(f,S)}return this.addRelation(o,t),this}delete(o,n){n=typeof n==="string"?n:o[this.b];const t=typeof o==="string"?o:o[this.a];if(t===void 0&&typeof n==="string"){const S=this.getRelatedKeys(n);if(S)for(let f of S)this.delete(f,n)}if(typeof t==="string"&&n===void 0){const S=this.getRelatedKeys(t);if(S)for(let f of S)this.delete(t,f)}if(typeof t==="string"&&typeof n==="string"){this.deleteRelation(t,n);const S=this.makeContentKey(t,n);this.deleteContent(S)}return this}getRelatedKey(o){const n=this.getRelatedKeys(o);if(n){if(n.size>1)this.warn?.(`${n.size} related keys were found for key "${o}": (${[...n].map((t)=>`"${t}"`).join(", ")}). Only one related key was expected.`);for(let t of n)return t}}replaceRelations(o,n,t){const S=!Array.isArray(n),f=S?Object.keys(n):n;if(t?.reckless)this.replaceRelationsUnsafely(o,f);else this.replaceRelationsSafely(o,f);if(S)for(let T of f){const M=this.makeContentKey(o,T),F=n[T];this.setContent(M,F)}return this}getContent(o,n){const t=this.makeContentKey(o,n);return this.getContentInternal(t)}getRelationEntries(o){const n=o[this.a],t=o[this.b];if(n!==void 0&&t===void 0){const S=this.getRelatedKeys(n);if(S)return[...S].map((f)=>{return[f,this.getContent(n,f)??null]})}if(n===void 0&&t!==void 0){const S=this.getRelatedKeys(t);if(S)return[...S].map((f)=>{return[f,this.getContent(f,t)??null]})}return[]}has(o,n){if(n)return this.getRelatedKeys(o)?.has(n)??!1;return this.relations.has(o)}}function bo(o){return"epoch"in o.transactionMeta}function Fo(o){return"phase"in o.transactionMeta}var aM=(o)=>{const n=m(o);if(!Fo(n)){o.logger.warn("\uD83D\uDC1E","transaction","???","abortTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}o.logger.info("\uD83E\uDE82","transaction",n.transactionMeta.update.key,"Aborting transaction"),n.parent.child=null};function Gn(o){return o.type.split("_").map($y).join(" ")}var $y=(o)=>o[0].toUpperCase()+o.slice(1);class tn extends Error{constructor(...o){const n=o[0],t=o.length===2?o[1]:o[2];if(o.length===2)super(`${Gn(n)} ${l(n.key)} not found in store "${t.config.name}".`);else{const S=o[1];super(`${Gn(n)} "${n.key}" member ${l(S)} not found in store "${t.config.name}".`)}}}function At(o,n,t){return(...S)=>{const f=u(o,t);if(f)return f.run(S,n);throw new tn(o,t)}}var PS=(o)=>(n)=>o instanceof Function?o(n):o;var en=(o,n)=>{if(n.valueMap.has(o.key))return n.logger.info("\uD83D\uDCD6",o.type,o.key,"reading cached value"),sM(o,n);if(o.type==="selector"||o.type==="readonly_selector")return n.logger.info("\uD83E\uDDEE",o.type,o.key,"computing value"),o.get();const t=o.default instanceof Function?o.default():o.default;return n.logger.info("\uD83D\uDC81","atom",o.key,"could not find cached value; using default",t),o.default instanceof Function?o.default():o.default};var oF=(o,n)=>{if(o.operation.open){const t=performance.now();return o.logger.info("\u2757",n.type,n.key,`deferring setState at T-${t} until setState for "${o.operation.token.key}" is done`),t}o.operation={open:!0,done:new Set,prev:new Map,time:Date.now(),token:n},o.logger.info("\u2B55",n.type,n.key,`operation start in store "${o.config.name}"${!Fo(o)?"":` ${o.transactionMeta.phase} "${o.transactionMeta.update.key}"`}`)},nF=(o)=>{if(o.operation.open)o.logger.info("\uD83D\uDD34",o.operation.token.type,o.operation.token.key,`operation done in store "${o.config.name}"`);o.operation={open:!1},o.on.operationClose.next(o.operation)},tF=(o,n)=>{if(!o.operation.open)return o.logger.error("\uD83D\uDC1E","unknown",n,"isDone called outside of an operation. This is probably a bug in AtomIO."),!0;return o.operation.done.has(n)},Qt=(o,n)=>{if(!o.operation.open){o.logger.error("\uD83D\uDC1E","unknown",n,"markDone called outside of an operation. This is probably a bug in AtomIO.");return}o.operation.done.add(n)};var SF=(o,n,t)=>{switch(o.type){case"mutable_atom":t.logger.info("\uD83D\uDCE2",o.type,o.key,"is now (",n.newValue,") subscribers:",o.subject.subscribers);break;default:t.logger.info("\uD83D\uDCE2",o.type,o.key,"went (",n.oldValue,"->",n.newValue,") subscribers:",o.subject.subscribers)}o.subject.next(n)};var ST=(o,n)=>{const t=m(n),S=t.selectorAtoms.getRelatedKeys(o.key);if(t.logger.info("\uD83E\uDDF9",o.type,o.key,S?`evicting ${S.size} states downstream:`:"no downstream states",S??"to evict"),S){if(t.operation.open)t.logger.info("\uD83E\uDDF9",o.type,o.key,`[ ${[...t.operation.done].join(", ")} ] already done`);for(let f of S){if(tF(t,f))continue;fF(f,t),Qt(t,f)}}};function Jy(o,n){if(MF(n.newValue))return!1;if(o.includes("\uD83D\uDD0D"))return!1;return!0}var TF=(o,n,t)=>{const{key:S}=o,f=m(t);if(!Fo(f)||f.transactionMeta.phase!=="building"){t.logger.error("\uD83D\uDC1E","atom",S,"stowUpdate called outside of a transaction. This is probably a bug.");return}if(!Jy(S,n))return;const M={type:"atom_update",key:S,...n};if(o.family)M.family=o.family;f.transactionMeta.update.updates.push(M),t.logger.info("\uD83D\uDCC1","atom",S,"stowed (",n.oldValue,"->",n.newValue,")")};var FF=(o,n,t)=>{const S=en(o,t);let f=S;if(o.type==="mutable_atom"&&Fo(t)){const{parent:M}=t;f=kS(o,M,t)}if(f=PS(n)(f),t.logger.info("\uD83D\uDCDD","atom",o.key,"set to",f),f=Rn(o.key,f,o.subject,t),kF(o.key,t))AF(o.key,t);Qt(t,o.key),ST(o,t);const T={oldValue:S,newValue:f};if(bo(t))SF(o,T,t);else if(t.parent){if(t.on.transactionApplying.state===null)TF(o,T,t);else if(o.key.startsWith("*")){const M=o.key.slice(1),F=t.atoms.get(M);let k=t.valueMap.get(M);if(F.type==="mutable_atom"&&Fo(t)){const{parent:$}=t;k=kS(F,$,t)}if(k.do(T.newValue)===null)ST(F,t)}}};var gS=(o,n,t)=>{switch(o.type){case"atom":case"mutable_atom":FF(o,n,t);break;case"selector":o.set(n);break}};function lS(o,n){if(n.family){const t=o.families.get(n.family.key);if(t)return t}}function Co(o,...n){let t,S,f,T;if(n.length===2){if(t=n[0],T=n[1],S=lS(o,t)??null,S)f=t.family?Uo(t.family.subKey):null,t=Ro(o,S,f)}else S=n[0],f=n[1],T=n[2],t=Ro(o,S,f);if("counterfeit"in t){const k=o.disposalTraces.buffer.find((A)=>A?.key===t.key);o.logger.error("\u274C",t.type,t.key,`could not be set because it was not found in the store "${o.config.name}".`,k?`This state was previously disposed:\n${k.trace}`:"No previous disposal trace was found.");return}const M=oF(o,t);if(M){const k=o.on.operationClose.subscribe(`waiting to set "${t.key}" at T-${M}`,()=>{k(),o.logger.info("\uD83D\uDFE2",t.type,t.key,`resuming deferred setState from T-${M}`),Co(o,t,T)});return}const F=u(t,o);gS(F,T,o),nF(o)}function eS(o,n,t){const{key:S,newValue:f,oldValue:T}=n,M=o==="newValue"?f:T,F={key:S,type:"atom"};if(n.family)Object.assign(F,{family:n.family});Co(t,F,M)}function fT(o,n,t){const S=l(t);try{const f=[];let T;if(n==="root")f.push(o.molecules.get('"root"')),T="all";else if(n[0][0]===$F){T="any";const $=l(n),O=o.molecules.get($);if(!O)throw new Error(`Molecule ${$} not found in store "${o.config.name}"`);f.push(O)}else if(t[0][0]===$F){T="all";for(let O of n){const w=l(O),G=o.molecules.get(w);if(!G)throw new Error(`Molecule ${w} not found in store "${o.config.name}"`);f.push(G)}}else{T="any";const O=l(n),w=o.molecules.get(O);if(!w)throw new Error(`Molecule ${O} not found in store "${o.config.name}"`);f.push(w)}const M=new Dt(f,t);M._dependsOn=T,o.molecules.set(S,M);for(let $ of f)$.below.set(M.stringKey,M);const F={type:"molecule_creation",subType:"modern",key:M.key,provenance:n},k=m(o);if(Fo(k)&&k.transactionMeta.phase==="building")k.transactionMeta.update.updates.push(F);else k.on.moleculeCreationStart.next(F)}catch(f){if(f instanceof Error)o.logger.error("\u274C","molecule",S,"allocation failed:",f.message)}return t}function AS(o,n){const t=l(n),S=o.molecules.get(t);if(!S)throw new Error(`Molecule ${t} not found in store "${o.config.name}"`);for(let A of S.joins.values())A.relations.delete(S.key),A.molecules.delete(S.stringKey);let f;if(S.above.size===1)f=S.above.values().next().value.key;else f=[...S.above.values()].map(({key:A})=>A);const T=[];for(let A of S.tokens.values()){const $=A.family;T.push([$.key,o.valueMap.get(A.key)])}for(let A of S.tokens.values())uo(o,A);for(let A of S.below.values())if(A.dependsOn==="all")AS(o,A.key);else if(A.above.delete(S.stringKey),A.above.size===0)AS(o,A.key);S.below.clear();const M={type:"molecule_disposal",subType:"modern",key:S.key,values:T,provenance:f},F=m(o);if(Fo(F)&&F.transactionMeta.phase==="building")F.transactionMeta.update.updates.push(M);else F.on.moleculeDisposal.next(M);F.molecules.delete(S.stringKey);for(let A of S.above.values())A.below.delete(S.stringKey)}var wW=Symbol("provenance"),$F="T$";function JF(o,n){const t=new s,S={type:"molecule_family",key:n.key,dependsOn:n.dependsOn??"all"},f={...S,subject:t,new:n.new};return o.moleculeFamilies.set(n.key,f),S}function zn(o,n,t){const S=xn(t,n,o.key);o.tokens.set(S.key,S);const f=Fo(t)&&t.transactionMeta.phase==="building",T=t.moleculeInProgress===o.key;if(!f&&!T)o.subject.next({type:"state_creation",token:S});return S}class Bo extends Set{mode="record";subject=new s;cacheLimit=0;cache=[];cacheIdx=-1;cacheUpdateNumber=-1;constructor(o,n=0){super(o);if(o instanceof Bo)this.parent=o,this.cacheUpdateNumber=o.cacheUpdateNumber;if(n)this.cacheLimit=n,this.cache=new Array(n),this.subscribe("auto cache",(t)=>{this.cacheIdx++,this.cacheIdx%=this.cacheLimit,this.cache[this.cacheIdx]=t})}toJSON(){return{members:[...this],cache:this.cache,cacheLimit:this.cacheLimit,cacheIdx:this.cacheIdx,cacheUpdateNumber:this.cacheUpdateNumber}}static fromJSON(o){const n=new Bo(o.members,o.cacheLimit);return n.cache=o.cache,n.cacheIdx=o.cacheIdx,n.cacheUpdateNumber=o.cacheUpdateNumber,n}add(o){const n=super.add(o);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`add:${l(o)}`);return n}clear(){const o=this.mode==="record"?[...this]:null;if(super.clear(),o)this.cacheUpdateNumber++,this.emit(`clear:${JSON.stringify(o)}`)}delete(o){const n=super.delete(o);if(this.mode==="record")this.cacheUpdateNumber++,this.emit(`del:${l(o)}`);return n}parent;child=null;transactionUpdates=null;transaction(o){this.mode="transaction",this.transactionUpdates=[],this.child=new Bo(this);const n=this.child._subscribe("transaction",(t)=>{this.transactionUpdates?.push(t)});try{if(o(this.child)){for(let S of this.transactionUpdates)this.doStep(S);this.cacheUpdateNumber++,this.emit(`tx:${this.transactionUpdates.join(";")}`)}}catch(t){throw console.error("Failed to apply transaction to SetRTX:",t),t}finally{n(),this.child=null,this.transactionUpdates=null,this.mode="record"}}_subscribe(o,n){return this.subject.subscribe(o,n)}subscribe(o,n){return this.subject.subscribe(o,(t)=>{n(`${this.cacheUpdateNumber}=${t}`)})}emit(o){this.subject.next(o)}doStep(o){const n=o.indexOf(":"),t=o.substring(0,n),S=o.substring(n+1);switch(t){case"add":this.add(JSON.parse(S));break;case"clear":this.clear();break;case"del":this.delete(JSON.parse(S));break;case"tx":for(let f of S.split(";"))this.doStep(f)}}getUpdateNumber(o){const n=o.indexOf("=");return Number(o.substring(0,n))}do(o){const n=o.indexOf("="),t=Number(o.substring(0,n)),S=t-this.cacheUpdateNumber;if(S>0){if(S===1){this.mode="playback";const T=o.substring(n+1);return this.doStep(T),this.mode="record",this.cacheUpdateNumber=t,null}return this.cacheUpdateNumber+1}if(Math.abs(S)<this.cacheLimit){const T=this.cacheIdx+S;if(this.cache[T]===o)return null;this.mode="playback";let F=!1;while(!F){this.cacheIdx%=this.cacheLimit;const A=this.cache[this.cacheIdx];if(this.cacheIdx--,!A)return"OUT_OF_RANGE";this.undo(A),F=this.cacheIdx===T-1}const k=o.substring(n+1);return this.doStep(k),this.mode="record",this.cacheUpdateNumber=t,null}return"OUT_OF_RANGE"}undoStep(o){const n=o.indexOf(":"),t=o.substring(0,n),S=o.substring(n+1);switch(t){case"add":this.delete(JSON.parse(S));break;case"del":this.add(JSON.parse(S));break;case"clear":{const f=JSON.parse(S);for(let T of f)this.add(T);break}case"tx":{const f=S.split(";");for(let T=f.length-1;T>=0;T--)this.undoStep(f[T])}}}undo(o){const n=o.indexOf("=");if(Number(o.substring(0,n))===this.cacheUpdateNumber){this.mode="playback";const S=o.substring(n+1);return this.undoStep(S),this.mode="record",this.cacheUpdateNumber--,null}return this.cacheUpdateNumber}}function zo(o){return o[0].toUpperCase()+o.slice(1)}function dS(o,n,t=ko.STORE){return TT(t).set(o.key,new FT(o,n,t)),{key:o.key,type:"join",a:o.between[0],b:o.between[1],cardinality:o.cardinality}}function TT(o){if("joins"in o&&o.joins instanceof Map)return o.joins;const n=new Map;return o.joins=n,n}function $S(o,n){const t=TT(n);let S=t.get(o.key);if(S===void 0){if(S=TT(ko.STORE).get(o.key)?.in(n),S===void 0)throw new Error(`Join "${o.key}" not found in store "${n.config.name}"`);t.set(o.key,S)}return S}function yF(o,n,t){const S=$S(o,t);let f;switch(o.cardinality){case"1:1":{const T=`${o.a}KeyOf${zo(o.b)}`,M=`${o.b}KeyOf${zo(o.a)}`;f={get[T](){const k=S.states[T];return S.retrieve(k,n)},get[M](){const k=S.states[M];return S.retrieve(k,n)}};const F=`${o.a}EntryOf${zo(o.b)}`;if(F in S.states){const k=`${o.b}EntryOf${zo(o.a)}`;Object.assign(f,{get[F](){const A=S.states[F];return S.retrieve(A,n)},get[k](){const A=S.states[k];return S.retrieve(A,n)}})}break}case"1:n":{const T=`${o.a}KeyOf${zo(o.b)}`,M=`${o.b}KeysOf${zo(o.a)}`;f={get[T](){const k=S.states[T];return S.retrieve(k,n)},get[M](){const k=S.states[M];return S.retrieve(k,n)}};const F=`${o.a}EntryOf${zo(o.b)}`;if(F in S.states){const k=`${o.b}EntriesOf${zo(o.a)}`;Object.assign(f,{get[F](){const A=S.states[F];return S.retrieve(A,n)},get[k](){const A=S.states[k];return S.retrieve(A,n)}})}break}case"n:n":{const T=`${o.a}KeysOf${zo(o.b)}`,M=`${o.b}KeysOf${zo(o.a)}`;f={get[T](){const k=S.states[T];return S.retrieve(k,n)},get[M](){const k=S.states[M];return S.retrieve(k,n)}};const F=`${o.a}EntriesOf${zo(o.b)}`;if(F in S.states){const k=`${o.b}EntriesOf${zo(o.a)}`;Object.assign(f,{get[F](){const A=S.states[F];return S.retrieve(A,n)},get[k](){const A=S.states[k];return S.retrieve(A,n)}})}}}return f}function RF(o,n){return yF(o,n,ko.STORE)}function uS(o,n,t){const S=$S(o,t),f=m(t);if(Fo(f)){const{toolkit:T}=f.transactionMeta;S.transact(T,({relations:M})=>{n(M)})}else n(S.relations)}function yy(o,n){return $S(o,n).core.findRelatedKeysState}function OF(o){return yy(o,ko.STORE)}class FT{options;defaultContent;toolkit;retrieve;molecules=new Map;relations;states;core;transact(o,n){const t=this.toolkit;this.toolkit=o,n(this),this.toolkit=t}store;alternates;[Symbol.dispose](){this.alternates.delete(this.store.config.name)}in(o){const n=o.config.name,t=this.alternates.get(n);if(t)return t;const S=new FT(this.options,this.defaultContent,o);return this.alternates.set(n,S),S.alternates=this.alternates,S}constructor(o,n,t=ko.STORE){this.store=t,this.options=o,this.defaultContent=n,this.alternates=new Map,this.alternates.set(t.config.name,this),this.store.miscResources.set(`join:${o.key}`,this),this.retrieve=(Y,K)=>{const Q=this.toolkit.seek(Y,K);if(Q)return Q;const i=this.molecules.get(l(K));if(i){const g=u(Y,t);return zn(i,g,t)}if(t.config.lifespan==="immortal")throw new tn(Y,K,t);return xn(t,Y,K)},this.toolkit={get:(...Y)=>Go(t,...Y),set:(...Y)=>{Co(t,...Y)},find:this.retrieve,seek:(...Y)=>Eo(t,...Y),json:(Y)=>ho(t,Y),dispose:(...Y)=>{uo(t,...Y)}};const S=o.between[0],f=o.between[1],T=SS(t,{key:`${o.key}/relatedKeys`,default:()=>new Bo,mutable:!0,fromJson:(Y)=>Bo.fromJSON(Y),toJson:(Y)=>Y.toJSON()},["join","relations"]);this.core={findRelatedKeysState:T};const M=({get:Y},K)=>Y(this.retrieve(T,K)),F=(Y,K,Q)=>{const{set:i}=Y,g=this.retrieve(T,K),_=this.retrieve(T,Q);i(g,(h)=>h.add(Q)),i(_,(h)=>h.add(K))},k=(Y,K,Q)=>{const{set:i}=Y,g=this.retrieve(T,K),_=this.retrieve(T,Q);let h,C;i(g,(a)=>{if(a.delete(Q),a.size===0)h=`"${K}"`;return a}),i(_,(a)=>{if(a.delete(K),a.size===0)C=`"${Q}"`;return a})},A=(Y,K,Q)=>{const{get:i,set:g}=Y,_=this.retrieve(T,K),h=i(_);for(let C of h){if(Q.includes(C))continue;const So=this.retrieve(T,C);g(So,(to)=>{return to.delete(K),to})}g(_,(C)=>{return C.transaction((a)=>{a.clear();for(let So of Q){const to=M(Y,So),Wo=to.has(K);if(this.relations.cardinality==="1:n"){const Mn=[];for(let E of to){if(E===K)continue;const x=M(Y,E);if(x.delete(So),x.size===0)Mn.push(E)}if(!Wo&&to.size>0)to.clear();for(let E of Mn){const x=[So,E].sort(),To=`"${x[0]}:${x[1]}"`;this.molecules.delete(To)}}if(!Wo)to.add(K);a.add(So)}return!0}),C})},$=(Y,K,Q)=>{const{set:i}=Y,g=this.retrieve(T,K);i(g,(_)=>{return _.transaction((h)=>{for(let C of Q)h.add(C);return!0}),_});for(let _ of Q){const h=this.retrieve(T,_);i(h,(C)=>{return C.add(K),C})}return!0},O=(Y,K,Q)=>{const i=M(Y,K);return Q?i.has(Q):i.size>0},w={getRelatedKeys:(Y)=>M(this.toolkit,Y),addRelation:(Y,K)=>{F(this.toolkit,Y,K)},deleteRelation:(Y,K)=>{k(this.toolkit,Y,K)},replaceRelationsSafely:(Y,K)=>{A(this.toolkit,Y,K)},replaceRelationsUnsafely:(Y,K)=>{$(this.toolkit,Y,K)},has:(Y,K)=>O(this.toolkit,Y,K)};let G,r,H;if(n){r=jn(t,{key:`${o.key}/content`,default:n},["join","content"]);const Y={key:o.key,type:"join",a:o.between[0],b:o.between[1],cardinality:o.cardinality};H=JF(t,{key:`${o.key}/content-molecules`,new:class _{C;constructor(h,C){this.key=C}}});const K=({get:_},h)=>_(this.retrieve(r,h)),Q=({set:_},h,C)=>{_(this.retrieve(r,h),C)},i=(_,h)=>{const C=t.molecules.get(`"${h}"`);if(C)this.toolkit.dispose(C),this.molecules.delete(`"${h}"`)};G=Object.assign(w,{getContent:(_)=>{return K(this.toolkit,_)},setContent:(_,h)=>{Q(this.toolkit,_,h)},deleteContent:(_)=>{i(this.toolkit,_)}})}else G=w;const D=new Fn(o,{externalStore:G,makeContentKey:(...Y)=>{const K=Y.sort(),Q=`${K[0]}:${K[1]}`,[i,g]=K.map((_)=>this.molecules.get(l(_)));if(t.config.lifespan==="immortal"&&i&&g){const _=m(t),h=vn(_,[i,g],H,Q);this.molecules.set(`"${Q}"`,u(h,_))}return Q}}),I=()=>hn(t,{key:`${o.key}/singleRelatedKey`,get:(Y)=>({get:K})=>{const Q=this.retrieve(T,Y),i=K(Q);for(let g of i)return g;return null}},["join","keys"]),v=()=>{return hn(t,{key:`${o.key}/multipleRelatedKeys`,get:(Y)=>({get:K})=>{const Q=MT(T,t),i=this.retrieve(Q,Y);return K(i).members}},["join","keys"])},N=()=>hn(t,{key:`${o.key}/singleRelatedEntry`,get:(Y)=>({get:K})=>{const Q=this.retrieve(T,Y),i=K(Q);for(let g of i){const _=D.makeContentKey(Y,g),h=this.retrieve(r,_),C=K(h);return[g,C]}return null}},["join","entries"]),P=()=>hn(t,{key:`${o.key}/multipleRelatedEntries`,get:(Y)=>({get:K})=>{const Q=MT(T,t),i=this.retrieve(Q,Y);return K(i).members.map((_)=>{const h=D.makeContentKey(Y,_),C=this.retrieve(r,h),a=K(C);return[_,a]})}},["join","entries"]);switch(o.cardinality){case"1:1":{const Y=I(),K=`${S}KeyOf${zo(f)}`,Q=`${f}KeyOf${zo(S)}`,i={[K]:Y,[Q]:Y};let g;if(n){const _=N(),h=`${S}EntryOf${zo(f)}`,C=`${f}EntryOf${zo(S)}`,a={[h]:_,[C]:_};g=Object.assign(i,a)}else g=i;this.relations=D,this.states=g;break}case"1:n":{const Y=I(),K=v(),Q=`${S}KeyOf${zo(f)}`,i=`${f}KeysOf${zo(S)}`,g={[Q]:Y,[i]:K};let _;if(n){const h=N(),C=P(),a=`${S}EntryOf${zo(f)}`,So=`${f}EntriesOf${zo(S)}`,to={[a]:h,[So]:C};_=Object.assign(g,to)}else _=g;this.relations=D,this.states=_;break}default:{const Y=v(),K=`${S}KeysOf${zo(f)}`,Q=`${f}KeysOf${zo(S)}`,i={[K]:Y,[Q]:Y};let g;if(n){const _=P(),h=`${S}EntriesOf${zo(f)}`,C=`${f}EntriesOf${zo(S)}`,a={[h]:_,[C]:_};g=Object.assign(i,a)}else g=i;this.relations=D,this.states=g}}}}function aS(o){return{store:o}}function Go(o,...n){let t,S,f;if(n.length===1){if(t=n[0],t.type!=="molecule"){if(S=lS(o,t)??null,S)f=t.family?Uo(t.family.subKey):null,t=Ro(o,S,f)}}else{S=n[0],f=n[1];let T;if(S.type==="molecule_family")T=Eo(o,S,f)??Ht(S,f);else T=Ro(o,S,f);t=T}if("counterfeit"in t&&"family"in t){S=t.type==="molecule"?u(t.family,o):o.families.get(t.family.key);const T=t.type==="molecule"?t.key:t.family.subKey,M=o.disposalTraces.buffer.find((F)=>F?.key===t.key);switch(o.logger.error("\u274C",t.type,t.key,`could not be retrieved because it was not found in the store "${o.config.name}".`,M?`This state was previously disposed:\n${M.trace}`:"No previous disposal trace was found."),S.type){case"atom_family":case"mutable_atom_family":return o.defaults.get(S.key);case"selector_family":case"readonly_selector_family":{if(o.defaults.has(S.key))return o.defaults.get(t.family.key);const F=u(S,o).default(T);return o.defaults.set(S.key,F),F}case"molecule_family":throw new tn(S,T,o)}}switch(t.type){case"atom":case"mutable_atom":case"selector":case"readonly_selector":return en(u(t,o),o);case"molecule":return u(t,o).instance}}class Dt{n;type="molecule";stringKey;family;_dependsOn;get dependsOn(){if(this.family)return this.family.dependsOn;return this._dependsOn}subject=new s;tokens=new Map;above=new Map;below=new Map;joins=new Map;instance;constructor(o,n,t){this.key=n;if(this.stringKey=l(n),t)this.family=t,this._dependsOn=t.dependsOn;if(o)for(let S of o)this.above.set(S.stringKey,S)}}function WF(o){return o[0].toUpperCase()+o.slice(1)}function vn(o,n,t,S,...f){const T=lM(o),M=m(o),F=l(S);M.moleculeInProgress=F;const k=Array.isArray(n)?n:[n],A=k.map((D)=>{if(D instanceof Dt)return D;const I=l(D.key),v=o.molecules.get(I);if(!v)throw new Error(`Molecule ${I} not found in store "${o.config.name}"`);return v}),$=new Dt(A,S,t);M.molecules.set(F,$);for(let D of A)D.below.set($.stringKey,$);const O={get:(...D)=>Go(m(T),...D),set:(...D)=>{Co(m(T),...D)},seek:(D,I)=>Eo(m(T),D,I),json:(D)=>ho(m(T),D),run:(D,I=zt())=>At(D,I,m(o)),make:(D,I,v,...N)=>vn(m(T),D,I,v,...N),dispose:(D)=>{uo(m(T),D)},env:()=>aS(m(T)),bond:(D,I)=>{if(D.type==="join"){const{as:v}=I,N=$S(D,T);N.molecules.set(F,$),$.joins.set(D.key,N);const P=w.subject.subscribe(`join:${D.key}-${F}`,(_)=>{if(_.type==="molecule_disposal"){if(l(_.token.key)===F)P(),N.molecules.delete(F)}});if(v===null)return;const Y=D.a===v?D.b:D.a,K=RF(D,S),Q=K[`${Y}KeysOf${WF(v)}`],i=K[`${Y}EntriesOf${WF(v)}`];let g={relatedKeys:Q};if(i)g=Object.assign(g,{relatedEntries:i});return g}return zn($,u(D,T),m(T))},claim:(D,I)=>{const{exclusive:v}=I,N=m(o).molecules.get(l(D.key));if(N)if(v){for(let P of N.above.values())P.below.delete(N.stringKey);N.above.clear(),N.above.set($.stringKey,$),$.below.set(N.stringKey,N)}else N.above.set($.stringKey,$),$.below.set(N.stringKey,N)},spawn:(D,I,...v)=>vn(m(o),[$],u(D,o),I,...v)},w=u(t,o),G=w.new;$.instance=new G(O,S,...f);const r={type:"molecule",key:S,family:t},H={type:"molecule_creation",subType:"classic",token:r,family:t,context:k,params:f};if(bo(M))w.subject.next(H);else if(Fo(M)&&M.on.transactionApplying.state===null)M.transactionMeta.update.updates.push(H);return M.moleculeInProgress=null,r}function kT(o,n,t){switch(n){case"newValue":{_F(o,t);break}case"oldValue":{uo(t,o.token);break}}}function AT(o,n,t){switch(n){case"newValue":{uo(t,o.token);break}case"oldValue":{_F(o,t),t.valueMap.set(o.token.key,o.value);break}}}function _F(o,n){const{family:t}=o.token;if(t){const S=n.families.get(t.key);if(S)Ro(n,S,Uo(t.subKey))}}function $T(o,n,t){switch(n){case"newValue":switch(o.subType){case"classic":vn(t,o.context,o.family,o.token.key,...o.params);break;case"modern":fT(t,o.provenance,o.key);break}break;case"oldValue":switch(o.subType){case"classic":uo(t,o.token);break;case"modern":AS(t,o.key);break}break}}function JT(o,n,t){switch(n){case"newValue":switch(o.subType){case"classic":uo(t,o.token);break;case"modern":AS(t,o.key);break}break;case"oldValue":switch(o.subType){case"classic":{const S=vn(t,o.context,o.family,o.token.key);for(let[f,T]of o.values){const M=`${f}(${l(S.key)})`,F=u(S,t),k=F.tokens.has(M),A=t.families.get(f);if(A&&!k)zn(F,A,t);t.valueMap.set(M,T)}}break;case"modern":{fT(t,o.provenance,o.key);for(let[S,f]of o.values){const T=t.families.get(S);if(T){Ro(t,T,o.key);const M=`${S}(${l(o.key)})`;t.valueMap.set(M,f)}}}}break}}function sS(o,n,t){const S=o==="newValue"?n.updates:[...n.updates].reverse();for(let f of S)switch(f.type){case"atom_update":case"selector_update":eS(o,f,t);break;case"state_creation":kT(f,o,t);break;case"state_disposal":AT(f,o,t);break;case"molecule_creation":$T(f,o,t);break;case"molecule_disposal":JT(f,o,t);break;case"transaction_update":sS(o,f,t);break}}function wF(o,n,t){if(!bo(t))return;const f=t.transactionMeta.actionContinuities.getRelatedKey(o);if(f!==void 0)t.transactionMeta.epoch.set(f,n)}var KF=(o,n)=>{const t=m(n),{parent:S}=t;if(S===null||!Fo(t)||t.transactionMeta?.phase!=="building"){n.logger.warn("\uD83D\uDC1E","transaction","???","applyTransaction called outside of a transaction. This is probably a bug in AtomIO.");return}t.transactionMeta.phase="applying",t.transactionMeta.update.output=o,S.child=null,S.on.transactionApplying.next(t.transactionMeta);const{updates:f}=t.transactionMeta.update;if(n.logger.info("\uD83D\uDEC4","transaction",t.transactionMeta.update.key,`Applying transaction with ${f.length} updates:`,f),sS("newValue",t.transactionMeta.update,S),bo(S))wF(t.transactionMeta.update.key,t.transactionMeta.update.epoch,S),u({key:t.transactionMeta.update.key,type:"transaction"},n)?.subject.next(t.transactionMeta.update),n.logger.info("\uD83D\uDEEC","transaction",t.transactionMeta.update.key,"Finished applying transaction.");else if(Fo(S))S.transactionMeta.update.updates.push(t.transactionMeta.update);S.on.transactionApplying.next(null)};class On extends Map{o;deleted=new Set;constructor(o){super();this.source=o}get(o){if(super.has(o))return super.get(o);if(!this.deleted.has(o)&&this.source.has(o))return this.source.get(o);return}set(o,n){return this.deleted.delete(o),super.set(o,n)}hasOwn(o){return super.has(o)}has(o){return!this.deleted.has(o)&&(super.has(o)||this.source.has(o))}delete(o){return this.deleted.add(o),super.delete(o)}}var XF=(o,n,t,S)=>{const f=m(t),T={parent:f,child:null,on:f.on,loggers:f.loggers,logger:f.logger,config:f.config,atoms:new On(f.atoms),atomsThatAreDefault:new Set(f.atomsThatAreDefault),families:new On(f.families),operation:{open:!1},readonlySelectors:new On(f.readonlySelectors),timelines:new On(f.timelines),timelineTopics:new Fn(f.timelineTopics.toJSON()),trackers:new Map,transactions:new On(f.transactions),selectorAtoms:new Fn(f.selectorAtoms.toJSON()),selectorGraph:new Fn(f.selectorGraph.toJSON(),{makeContentKey:(...A)=>A.sort().join(":")}),selectors:new On(f.selectors),valueMap:new On(f.valueMap),defaults:f.defaults,disposalTraces:t.disposalTraces.copy(),molecules:new On(f.molecules),moleculeFamilies:new On(f.moleculeFamilies),moleculeInProgress:f.moleculeInProgress,miscResources:new On(f.miscResources)},M=YF(o,t),F={phase:"building",update:{type:"transaction_update",key:o,id:S,epoch:M===void 0?Number.NaN:M+1,updates:[],params:n,output:void 0},toolkit:{get:(...A)=>Go(k,...A),set:(...A)=>{Co(k,...A)},run:(A,$=zt())=>At(A,$,k),find:(A,$)=>Ro(k,A,$),seek:(A,$)=>Eo(k,A,$),json:(A)=>ho(k,A),make:(A,$,O,...w)=>vn(k,A,$,O,...w),dispose:(...A)=>{uo(k,...A)},env:()=>aS(k)}},k=Object.assign(T,{transactionMeta:F});return f.child=k,t.logger.info("\uD83D\uDEEB","transaction",o,"Building transaction with params:",n),k};function tT(o,n){const t={key:o.key,type:"transaction",run:(T,M)=>{const F=XF(o.key,T,n,M);try{const k=m(n),{toolkit:A}=F.transactionMeta,$=o.do(A,...T);return KF($,k),$}catch(k){throw aM(S),n.logger.warn("\uD83D\uDCA5","transaction",o.key,"caught:",k),k}},install:(T)=>tT(o,T),subject:new s},S=m(n);S.transactions.set(t.key,t);const f=Po(t);return n.on.transactionCreation.next(f),f}function YF(o,n){const t=bo(n),S=t?n.transactionMeta.actionContinuities.getRelatedKey(o):void 0;return t&&S!==void 0?n.transactionMeta.epoch.get(S):void 0}class of{_buffer;_index=0;constructor(o){let n;if(typeof o==="number")n=o;else n=o.length;this._buffer=Array.from({length:n})}get buffer(){return this._buffer}get index(){return this._index}add(o){this._buffer[this._index]=o,this._index=(this._index+1)%this._buffer.length}copy(){const o=new of([...this._buffer]);return o._index=this._index,o}}class EF{parent=null;child=null;valueMap=new Map;defaults=new Map;atoms=new Map;selectors=new Map;readonlySelectors=new Map;atomsThatAreDefault=new Set;selectorAtoms=new Fn({between:["selectorKey","atomKey"],cardinality:"n:n"});selectorGraph=new Fn({between:["upstreamSelectorKey","downstreamSelectorKey"],cardinality:"n:n"},{makeContentKey:(...o)=>o.sort().join(":")});trackers=new Map;families=new Map;transactions=new Map;transactionMeta={epoch:new Map,actionContinuities:new Fn({between:["continuity","action"],cardinality:"1:n"})};timelines=new Map;timelineTopics=new Fn({between:["timelineKey","topicKey"],cardinality:"1:n"});disposalTraces=new of(100);molecules=new Map;moleculeFamilies=new Map;moleculeInProgress=null;miscResources=new Map;on={atomCreation:new s,atomDisposal:new s,selectorCreation:new s,selectorDisposal:new s,timelineCreation:new s,transactionCreation:new s,transactionApplying:new af(null),operationClose:new s,moleculeCreationStart:new s,moleculeCreationDone:new s,moleculeDisposal:new s};operation={open:!1};config={name:"IMPLICIT_STORE",lifespan:"ephemeral"};loggers=[new nT("warn",(o,n,t)=>!t.includes("\uD83D\uDD0D"))];logger={error:(...o)=>{for(let n of this.loggers)n.error(...o)},info:(...o)=>{for(let n of this.loggers)n.info(...o)},warn:(...o)=>{for(let n of this.loggers)n.warn(...o)}};constructor(o,n=null){if(this.config={...n?.config,...o},n!==null){if(this.valueMap=new Map(n?.valueMap),this.operation={...n?.operation},bo(n))this.transactionMeta={epoch:new Map(n?.transactionMeta.epoch),actionContinuities:new Fn(n?.transactionMeta.actionContinuities.toJSON())};for(let[,S]of n.families){if(S.internalRoles?.includes("mutable")||S.internalRoles?.includes("join"))continue;S.install(this)}const t=new Set;for(let[,S]of n.atoms){if(t.has(S.key))continue;if(S.install(this),S.type==="mutable_atom"){const f=ho(n,S),T=dn(S);t.add(f.key),t.add(T.key)}}for(let[,S]of n.readonlySelectors)S.install(this);for(let[,S]of n.selectors){if(t.has(S.key))continue;S.install(this)}for(let[,S]of n.transactions)S.install(this);for(let[,S]of n.timelines)S.install(this)}}}var ko={get STORE(){if(!globalThis.ATOM_IO_IMPLICIT_STORE)globalThis.ATOM_IO_IMPLICIT_STORE=new EF({name:"IMPLICIT_STORE",lifespan:"ephemeral"});return globalThis.ATOM_IO_IMPLICIT_STORE}};function u(o,n){let t,S=n;while(S!==null){switch(o.type){case"atom":case"mutable_atom":t=S.atoms.get(o.key);break;case"selector":t=S.selectors.get(o.key);break;case"readonly_selector":t=S.readonlySelectors.get(o.key);break;case"atom_family":case"mutable_atom_family":case"selector_family":case"readonly_selector_family":t=S.families.get(o.key);break;case"timeline":t=S.timelines.get(o.key);break;case"transaction":t=S.transactions.get(o.key);break;case"molecule":t=S.molecules.get(l(o.key));break;case"molecule_family":t=S.moleculeFamilies.get(o.key);break}if(t)return t;S=S.child}throw new tn(o,n)}function nf(o,n){let t;t=u(o,n);const{family:S}=o;for(let M of t.joins.values())M.relations.delete(t.key),M.molecules.delete(t.stringKey);const f=[];for(let M of t.above.values())f.push(Po(M));const T=[];for(let M of t.tokens.values()){const F=M.family;T.push([F.key,n.valueMap.get(M.key)])}if(S){const M=u(S,n),F={type:"molecule_disposal",subType:"classic",token:o,family:S,context:f,values:T};if(o.family)F.family=o.family;for(let A of t.tokens.values())uo(n,A);for(let A of t.below.values())if(A.dependsOn==="all")nf(A,n);else if(A.above.delete(t.stringKey),A.above.size===0)nf(A,n);if(t.below.clear(),Fo(n)&&n.transactionMeta.phase==="building")n.transactionMeta.update.updates.push(F);else M.subject.next(F);n.molecules.delete(t.stringKey)}for(let M of t.above.values())M.below.delete(t.stringKey)}function xn(o,n,t){const S=o.families.get(n.key);if(S===void 0)throw new tn(n,o);const f=S(t),T=m(o);if(f.family&&T.moleculeInProgress===null){if(bo(T))switch(f.type){case"atom":case"mutable_atom":o.on.atomCreation.next(f);break;case"selector":case"readonly_selector":o.on.selectorCreation.next(f);break}else if(Fo(T)&&T.on.transactionApplying.state===null)T.transactionMeta.update.updates.push({type:"state_creation",token:f})}return f}function Eo(o,n,t){const S=l(t),f=`${n.key}(${S})`,T=m(o);let M;switch(n.type){case"atom_family":case"mutable_atom_family":M=T.atoms.get(f);break;case"selector_family":M=T.selectors.get(f);break;case"readonly_selector_family":M=T.readonlySelectors.get(f);break;case"molecule_family":M=T.molecules.get(l(t))}if(M)return Po(M);return M}function Ro(o,n,t){let S=Eo(o,n,t);if(S)return S;const f=o.molecules.get(l(t));if(f)return zn(f,n,o);if(o.config.lifespan==="immortal"){const T=Ht(n,t);return o.logger.error("\u274C",T.type,T.key,`was not found in store "${o.config.name}"; returned a counterfeit token.`),T}return S=xn(o,n,t),S}function uo(o,...n){let t,S;if(n.length===1)t=n[0],S=t.key;else{const T=n[0],M=n[1];t=T.type==="molecule_family"?Eo(o,T,M)??Ht(T,M):Ro(o,T,M)}try{u(t,o)}catch(T){const M=o.disposalTraces.buffer.find((F)=>F?.key===t.key);o.logger.error("\u274C",t.type,t.key,`could not be disposed because it was not found in the store "${o.config.name}".`,M?`\n This state was most recently disposed\n${M.trace}`:"No previous disposal trace was found.");return}switch(t.type){case"atom":case"mutable_atom":yT(t,o);break;case"selector":case"readonly_selector":GF(t,o);break;case"molecule":nf(t,o);break}const{stack:f}=new Error;if(f){const T=f?.split("\n")?.slice(3)?.join("\n");o.disposalTraces.add({key:t.key,trace:T})}}var tf=(o,n)=>m(n).atoms.has(o),Ry=(o,n)=>m(n).selectors.has(o),Oy=(o,n)=>m(n).readonlySelectors.has(o),zF=(o,n)=>tf(o,n)||Ry(o,n)||Oy(o,n);var Sf=(o,n)=>{return m(n).selectorGraph.getRelationEntries({downstreamSelectorKey:o}).filter(([S,{source:f}])=>f!==o).map(([S,{source:f}])=>f).filter((S)=>zF(S,n))};var RT=(o,n,t)=>{const S=[],f=Sf(o,t);while(f.length>0){const T=f.shift();if(n.has(T))continue;if(n.add(T),!tf(T,t))f.push(...Sf(T,t));else if(!S.includes(T))S.push(T)}return S},HF=(o,n)=>{const t=o.key,S=Sf(t,n),f=new Set;return S.flatMap((T)=>tf(T,n)?T:RT(T,f,n))};var mF=(o,n,t,S)=>{const f=m(S);if(n.type==="atom"||n.type==="mutable_atom")f.selectorAtoms.set({selectorKey:o,atomKey:n.key}),S.logger.info("\uD83D\uDD0D","selector",o,`discovers root atom "${n.key}"`);else{const T=RT(n.key,t,S);S.logger.info("\uD83D\uDD0D","selector",o,`discovers root atoms: [ ${T.map((M)=>`"${M}"`).join(", ")} ]`);for(let M of T)f.selectorAtoms=f.selectorAtoms.set({selectorKey:o,atomKey:M})}t.add(n.key)};var ff=(o,n,t)=>({get:(...S)=>{const f=m(t);let T;if(S.length===2){const[k,A]=S;switch(k.type){case"molecule_family":return Go(t,k,A);default:if(t.config.lifespan==="ephemeral")T=Ro(t,k,A);else{const $=Eo(t,k,A);if($)T=$;else throw new tn(k,A,t)}}}else[T]=S;if(T.type==="molecule")return Go(t,T);const M=u(T,t),F=en(M,t);return t.logger.info("\uD83D\uDD0C","selector",o,`registers dependency ( "${T.key}" =`,F,")"),f.selectorGraph.set({upstreamSelectorKey:T.key,downstreamSelectorKey:o},{source:T.key}),mF(o,T,n,t),F},set:(...S)=>{let f,T;if(S.length===2)f=S[0],T=S[1];else{const k=S[0],A=S[1];T=S[2];const $=t.config.lifespan==="ephemeral"?Ro(t,k,A):Eo(t,k,A);if(!$)throw new tn(k,A,t);f=$}const M=m(t),F=u(f,M);gS(F,T,M)},find:(S,f)=>Ro(t,S,f),seek:(S,f)=>Eo(t,S,f),json:(S)=>ho(t,S)});var fS=(o,n,t)=>{const S=m(o),f=new s,T=new Set,{get:M,find:F,seek:k,json:A}=ff(n.key,T,S),$=()=>{const r=n.get({get:M,find:F,seek:k,json:A});return Rn(n.key,r,f,m(o)),T.clear(),r},O={...n,subject:f,install:(r)=>fS(r,n,t),get:$,type:"readonly_selector",...t&&{family:t}};S.readonlySelectors.set(n.key,O);const w=$();o.logger.info("\u2728",O.type,O.key,"=",w);const G={key:n.key,type:"readonly_selector"};if(t)G.family=t;return G};var JS=(o,n,t)=>{const S=m(o),f=new s,T=new Set,M=ff(n.key,T,S),{find:F,get:k,seek:A,json:$}=M,O={find:F,get:k,seek:A,json:$},w=(I=n.get,v=m(o))=>{const N=I(O);return Rn(n.key,N,f,v),T.clear(),N},r={...n,subject:f,install:(I)=>JS(I,n,t),get:w,set:(I)=>{const v=m(o),N=w(n.get,v),P=PS(I)(N);if(o.logger.info("\uD83D\uDCDD","selector",n.key,"set (",N,"->",P,")"),Rn(n.key,P,f,v),Qt(v,n.key),bo(v))f.next({newValue:P,oldValue:N});n.set(M,P)},type:"selector",...t&&{family:t}};S.selectors.set(n.key,r);const H=w();o.logger.info("\u2728",r.type,r.key,"=",H);const D={key:n.key,type:"selector"};if(t)D.family=t;return D};function En(o,n){if("set"in n){const f=JS(o,n,void 0);return o.on.selectorCreation.next(f),f}const S=fS(o,n,void 0);return o.on.selectorCreation.next(S),S}function GF(o,n){const t=m(n),{key:S}=o,f=u(o,t);if(!f.family)n.logger.error("\u274C","selector",S,"Standalone selectors cannot be disposed.");else{const T=t.molecules.get(f.family.subKey);if(T)T.tokens.delete(S);switch(o.type){case"selector":t.selectors.delete(S),u({key:f.family.key,type:"selector_family"},n).subject.next({type:"state_disposal",token:o});break;case"readonly_selector":t.readonlySelectors.delete(S),u({key:f.family.key,type:"readonly_selector_family"},n).subject.next({type:"state_disposal",token:o});break}if(t.valueMap.delete(S),t.selectorAtoms.delete(S),t.selectorGraph.delete(S),n.logger.info("\uD83D\uDD25",o.type,S,"deleted"),Fo(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.selectorDisposal.next(o)}}function MS(o,n,t){const S={key:n.key,type:"selector_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","selector_family",n.key,`Overwriting an existing ${Gn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const T=new s,F=Object.assign((k)=>{const A=l(k),$={key:n.key,subKey:A},O=`${n.key}(${A})`,w=m(o),G=JS(w,{key:O,get:n.get(k),set:n.set(k)},$);return T.next({type:"state_creation",token:G}),G},S,{internalRoles:t,subject:T,install:(k)=>MS(k,n),default:(k)=>{return n.get(k)({get:(...$)=>Go(o,...$),find:($,O)=>Ro(o,$,O),seek:($,O)=>Eo(o,$,O),json:($)=>ho(o,$)})}});return o.families.set(n.key,F),S}function QF(o,n,t=ko.STORE){const S=MS(t,{key:`${o.key}:JSON`,get:(T)=>({seek:M,get:F})=>{const k=M(o,T);if(k)return n.toJson(F(k));const A=l(T),$=t.molecules.get(A);if($){const w=zn($,o,t);return n.toJson(F(w))}if(t.config.lifespan==="immortal")throw new Error(`No molecule found for key "${A}"`);const O=xn(t,o,T);return n.toJson(F(O))},set:(T)=>({seek:M,set:F},k)=>{const A=M(o,T);if(A)F(A,n.fromJson(k));else{const $=l(T),O=t.molecules.get($);if(O){const w=zn(O,o,t);F(w,n.fromJson(k))}else{if(t.config.lifespan==="immortal")throw new Error(`No molecule found for key "${$}"`);F(xn(t,o,T),n.fromJson(k))}}}},["mutable","json"]);return u(o,t).subject.subscribe(`store=${t.config.name}::json-selector-family`,(T)=>{if(T.token.family)Eo(t,S,Uo(T.token.family.subKey))}),S}var Uo=(o)=>JSON.parse(o),l=(o)=>JSON.stringify(o),rK=[Array.prototype,Boolean.prototype,Number.prototype,Object.prototype,String.prototype];var DF=(o,n)=>{const t=m(n);if(t.operation.open)return t.operation.prev.get(o.key);return t.valueMap.get(o.key)};var WT=(o,n)=>{const t=m(n);return HF(o,n).map((f)=>{const T=t.atoms.get(f);if(T===void 0)throw new Error(`Atom "${f}", a dependency of selector "${o.key}", not found in store "${n.config.name}".`);return T.subject.subscribe(`${o.type}:${o.key}`,(M)=>{n.logger.info("\uD83D\uDCE2",o.type,o.key,"root",f,"went",M.oldValue,"->",M.newValue);const F=DF(o,t),k=en(o,t);n.logger.info("\u2728",o.type,o.key,"went",F,"->",k),o.subject.next({newValue:k,oldValue:F})})})};function kn(o,n,t,S){function f(O){if(S.operation.open){const w=S.on.operationClose.subscribe(`state subscription ${t}`,()=>{w(),n(O)})}else n(O)}const T=u(o,S);S.logger.info("\uD83D\uDC40",T.type,T.key,`Adding subscription "${t}"`);const M=T.type==="selector"||T.type==="readonly_selector";let F=null,k=f;if(M)F=WT(T,S),k=(O)=>{if(F)F.length=0,F.push(...WT(T,S));f(O)};const A=T.subject.subscribe(t,k);return()=>{if(S.logger.info("\uD83D\uDE48",T.type,T.key,`Removing subscription "${t}"`),A(),F)for(let O of F)O()}}var OT=(o,n,t,S)=>{const f=u(o,S);S.logger.info("\uD83D\uDC40","timeline",o.key,`Adding subscription "${t}"`);const T=f.subject.subscribe(t,n);return()=>{S.logger.info("\uD83D\uDE48","timeline",o.key,`Removing subscription "${t}" from timeline`),T()}};class un{Update;initializeState(o,n){const t=`*${o.key}`;n.atoms.delete(t),n.valueMap.delete(t);const S=o.family?{key:`*${o.family.key}`,subKey:o.family.subKey}:void 0,f=nn(n,{key:t,default:null},S);if(n.parent?.valueMap.has(t)){const T=n.parent.valueMap.get(t);n.valueMap.set(t,T)}return f}unsubscribeFromInnerValue;unsubscribeFromState;observeCore(o,n,t){const S=`tracker:${t.config.name}:${Fo(t)?t.transactionMeta.update.key:"main"}:${o.key}`,f=Go(t,o);this.unsubscribeFromInnerValue=f.subscribe(S,(T)=>{Co(t,n,T)}),this.unsubscribeFromState=kn(o,(T)=>{if(T.newValue!==T.oldValue)this.unsubscribeFromInnerValue(),this.unsubscribeFromInnerValue=T.newValue.subscribe(S,(M)=>{Co(t,n,M)})},S,t)}updateCore(o,n,t){const S=`tracker:${t.config.name}:${Fo(t)?t.transactionMeta.update.key:"main"}:${o.key}`;kn(n,({newValue:f,oldValue:T})=>{const M=t.timelineTopics.getRelatedKey(n.key);if(M){if(t.timelines.get(M)?.timeTraveling){const A=OT({key:M,type:"timeline"},($)=>{A(),Co(t,o,(O)=>{if($==="redo"&&f)O.do(f);else if($==="undo"&&T)O.undo(T);return O})},S,t);return}}const F=t.on.operationClose.subscribe(S,()=>{F();const k=Go(t,o),A=f===null?-1:k.getUpdateNumber(f),$=A-k.cacheUpdateNumber;if(f&&$===1)Co(t,o,(O)=>(O.do(f),O));else t.logger.info("\u274C","mutable_atom",o.key,`could not be updated. Expected update number ${k.cacheUpdateNumber+1}, but got ${A}`)})},S,t)}mutableState;latestUpdateState;dispose;constructor(o,n){this.mutableState=o;const t=m(n);this.latestUpdateState=this.initializeState(o,t),this.observeCore(o,this.latestUpdateState,t),this.updateCore(o,this.latestUpdateState,t),t.trackers.set(o.key,this),this.dispose=()=>{this.unsubscribeFromInnerValue(),this.unsubscribeFromState(),t.trackers.delete(o.key)}}}function yS(o,n,t){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);const S=m(o),f=S.atoms.get(n.key);if(f&&f.type==="mutable_atom")return o.logger.error("\u274C","atom",n.key,"Tried to create atom, but it already exists in the store."),Po(f);const T=new s,M={...n,type:"mutable_atom",install:(A)=>{return A.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${A.config.name}"`),yS(A,n,t)},subject:T};if(t)M.family=t;const F=n.default();S.atoms.set(M.key,M),Tf(n.key,o),Rn(n.key,F,T,S);const k=Po(M);if(n.effects){let A=0;const $=[];for(let O of n.effects){const w=O({setSelf:(G)=>{Co(o,k,G)},onSet:(G)=>kn(k,G,`effect[${A}]`,o)});if(w)$.push(w);++A}M.cleanup=()=>{for(let O of $)O()}}if(new un(k,o),!t)gM(k,n,o);return k}class _T{Update;latestUpdateAtoms;mutableAtoms;constructor(o,n){const t=jn(n,{key:`*${o.key}`,default:null},["mutable","updates"]);this.latestUpdateAtoms=u(t,n),this.mutableAtoms=o,this.mutableAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(S)=>{if(S.token.family){const f=Uo(S.token.family.subKey);Eo(n,this.latestUpdateAtoms,f),new un(S.token,n)}}),this.latestUpdateAtoms.subject.subscribe(`store=${n.config.name}::tracker-atom-family`,(S)=>{if(S.token.family){const f=Uo(S.token.family.subKey),T=Eo(n,this.mutableAtoms,f);if(T)new un(T,n)}})}}function SS(o,n,t){const S={key:n.key,type:"mutable_atom_family"},f=o.families.get(n.key);if(f)o.logger.error("\u2757","mutable_atom_family",n.key,`Overwriting an existing ${Gn(f)} "${f.key}" in store "${o.config.name}". You can safely ignore this warning if it is due to hot module replacement.`);const T=new s,F=Object.assign((k)=>{const A=l(k),$={key:n.key,subKey:A},O=`${n.key}(${A})`,w=m(o),G={key:O,default:()=>n.default(k),toJson:n.toJson,fromJson:n.fromJson,mutable:!0};if(n.effects)G.effects=n.effects(k);const r=yS(w,G,$);return T.next({type:"state_creation",token:r}),r},S,{subject:T,install:(k)=>SS(k,n),toJson:n.toJson,fromJson:n.fromJson,internalRoles:t});return o.families.set(n.key,F),QF(F,n,o),new _T(F,o),S}var MT=(o,n)=>{const t=m(n),S=`${o.key}:JSON`;return t.families.get(S)};var ho=(o,n)=>{if(n.family){const S=m(o),T={key:`${n.family.key}:JSON`,type:"selector_family"},M=u(T,S),F=JSON.parse(n.family.subKey);return Ro(o,M,F)}return{type:"selector",key:`${n.key}:JSON`}};var dn=(o)=>{const t={type:"atom",key:`*${o.key}`};if(o.family)t.family={key:`*${o.family.key}`,subKey:o.family.subKey};return t};function MF(o){return typeof o==="object"&&o!==null&&"do"in o&&"undo"in o&&"subscribe"in o}function kS(o,n,t){const S=n.valueMap.get(o.key),f=t.valueMap.get(o.key);if(S===f){if(S===void 0)return typeof o.default==="function"?o.default():o.default;n.logger.info("\uD83D\uDCC3","atom",o.key,"copying");const T=o.toJson(S),M=o.fromJson(T);return t.valueMap.set(o.key,M),new un(o,n),M}return f}function Rn(o,n,t,S){const f=S.valueMap.get(o);if(f instanceof tS)f.use(n);if(n instanceof Promise){const T=new tS(n);return S.valueMap.set(o,T),T.then((M)=>{Rn(o,M,t,S),t.next({newValue:M,oldValue:T})}).catch((M)=>{S.logger.error("\uD83D\uDCA5","state",o,"rejected:",M)}),T}return S.valueMap.set(o,n),n}var sM=(o,n)=>{let t=n.valueMap.get(o.key);if(o.type==="mutable_atom"&&Fo(n)){const{parent:S}=n;t=kS(o,S,n)}return t},fF=(o,n)=>{const t=n.valueMap.get(o);if(t instanceof tS){const S=t,f=n.selectors.get(o)??n.readonlySelectors.get(o);if(f)S.use(f.get());return}if(n.operation.open)n.operation.prev.set(o,t);n.valueMap.delete(o),n.logger.info("\uD83D\uDDD1","state",o,"evicted")};var kF=(o,n)=>{return m(n).atomsThatAreDefault.has(o)},Tf=(o,n)=>{const t=m(n);t.atomsThatAreDefault=new Set(t.atomsThatAreDefault).add(o)},AF=(o,n)=>{const t=m(n);t.atomsThatAreDefault=new Set(m(n).atomsThatAreDefault),t.atomsThatAreDefault.delete(o)};function nn(o,n,t){o.logger.info("\uD83D\uDD28","atom",n.key,`creating in store "${o.config.name}"`);const S=m(o),f=S.atoms.get(n.key);if(f&&f.type==="atom")return o.logger.error("\u274C","atom",n.key,"Tried to create atom, but it already exists in the store."),Po(f);const T=new s,M={...n,type:"atom",install:(A)=>{return A.logger.info("\uD83D\uDEE0\uFE0F","atom",n.key,`installing in store "${A.config.name}"`),nn(A,n,t)},subject:T};if(t)M.family=t;let F=n.default;if(n.default instanceof Function)F=n.default();S.atoms.set(M.key,M),Tf(n.key,o),Rn(n.key,F,T,S);const k=Po(M);if(n.effects){let A=0;const $=[];for(let O of n.effects){const w=O({setSelf:(G)=>{Co(o,k,G)},onSet:(G)=>kn(k,G,`effect[${A}]`,o)});if(w)$.push(w);++A}M.cleanup=()=>{for(let O of $)O()}}return k}function dM(o,n){if("mutable"in n){const f=yS(o,n,void 0);return o.on.atomCreation.next(f),f}const S=nn(o,n,void 0);return o.on.atomCreation.next(S),S}function yT(o,n){const t=m(n),{key:S}=o,f=u(o,t);if(!f.family)n.logger.error("\u274C","atom",S,"Standalone atoms cannot be disposed.");else{f.cleanup?.();const T=n.valueMap.get(f.key);u({key:f.family.key,type:"atom_family"},n).subject.next({type:"state_disposal",token:o,value:T});const F=t.molecules.get(f.family.subKey);if(F)F.tokens.delete(S);if(t.atoms.delete(S),t.valueMap.delete(S),t.selectorAtoms.delete(S),t.atomsThatAreDefault.delete(S),n.timelineTopics.delete(S),o.type==="mutable_atom"){const k=dn(o);yT(k,n),n.trackers.delete(S)}if(n.logger.info("\uD83D\uDD25","atom",S,"deleted"),Fo(t)&&t.transactionMeta.phase==="building")t.transactionMeta.update.updates.push({type:"state_disposal",token:o});else n.on.atomDisposal.next(o)}}var wT=(o)=>{const n=nn(o,{key:"\uD83D\uDD0D Atom Token Index (Internal)",default:()=>{const t=new Map;for(let[S,f]of o.atoms)if(!S.includes("\uD83D\uDD0D")){const T=Po(f);if(f.family){let M=t.get(f.family.key);if(!M||!("familyMembers"in M))M={key:f.family.key,familyMembers:new Map},t.set(f.family.key,M);M.familyMembers.set(f.family.subKey,T)}else t.set(S,T)}return t},effects:[({setSelf:t})=>{o.on.atomCreation.subscribe("introspection",(S)=>{if(S.key.includes("\uD83D\uDD0D"))return;t((f)=>{if(S.family){const{key:T,subKey:M}=S.family;let F=f.get(T);if(F===void 0||!("familyMembers"in F))F={key:T,familyMembers:new Map},f.set(T,F);F.familyMembers.set(M,S)}else f.set(S.key,S);return f})}),o.on.atomDisposal.subscribe("introspection",(S)=>{t((f)=>{if(S.family){const{key:T,subKey:M}=S.family,F=f.get(T);if(F&&"familyMembers"in F){if(F.familyMembers.delete(M),F.familyMembers.size===0)f.delete(T)}}else f.delete(S.key);return f})})}]},void 0);return En(o,{key:"\uD83D\uDD0D Atom Token Index",get:({get:t})=>t(n)})};var KT=(o)=>{const n=nn(o,{key:"\uD83D\uDD0D Selector Token Index (Internal)",default:()=>{const t=new Map;for(let S of[o.readonlySelectors,o.selectors])for(let[f,T]of S)if(!f.includes("\uD83D\uDD0D")){const M=Po(T);if(T.family){let F=t.get(T.family.key);if(!F||!("familyMembers"in F))F={key:T.family.key,familyMembers:new Map},t.set(T.family.key,F);F.familyMembers.set(T.family.subKey,M)}else t.set(f,M)}return t},effects:[({setSelf:t})=>{o.on.selectorCreation.subscribe("introspection",(S)=>{if(S.key.includes("\uD83D\uDD0D"))return;t((f)=>{if(S.family){const{key:T,subKey:M}=S.family;let F=f.get(T);if(F===void 0||!("familyMembers"in F))F={key:T,familyMembers:new Map},f.set(T,F);F.familyMembers.set(M,S)}else f.set(S.key,S);return f})}),o.on.selectorDisposal.subscribe("introspection",(S)=>{t((f)=>{if(S.family){const{key:T,subKey:M}=S.family,F=f.get(T);if(F&&"familyMembers"in F){if(F.familyMembers.delete(M),F.familyMembers.size===0)f.delete(T)}}else f.delete(S.key);return f})})}]},void 0);return En(o,{key:"\uD83D\uDD0D Selector Token Index",get:({get:t})=>t(n)})};function YT(o){if(!o)return!1;return Object.getPrototypeOf(o)===Object.prototype}class Mf{supported;constructor(o){this.supported=o}refine(o){for(let[n,t]of Object.entries(this.supported))try{if(t(o)===!0&&t!==Boolean)return{type:n,data:o}}catch(S){try{if(o instanceof t)return{type:n,data:o}}catch(f){}}return null}}var XT=new Mf({number:(o)=>typeof o==="number",string:(o)=>typeof o==="string",boolean:(o)=>typeof o==="boolean",null:(o)=>o===null}),ET=new Mf({object:YT,array:(o)=>Array.isArray(o)}),_y=new Mf({...XT.supported,...ET.supported}),Ut=(o)=>{if(o===void 0)return"undefined";const n=_y.refine(o);if(n)return n.type;return Object.getPrototypeOf(o).constructor.name};class UF{o;auditorCreatedAt=performance.now();statesCreatedAt=new Map;atomIndex;selectorIndex;disposed=!1;unsubscribeFromAtomCreation;unsubscribeFromAtomDisposal;unsubscribeFromSelectorCreation;unsubscribeFromSelectorDisposal;constructor(o=ko.STORE){this.store=o;this.atomIndex=wT(this.store),this.selectorIndex=KT(this.store),this.unsubscribeFromAtomCreation=this.store.on.atomCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:n})=>{this.statesCreatedAt.set(n,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromAtomDisposal=this.store.on.atomDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:n})=>{this.statesCreatedAt.delete(n)}),this.unsubscribeFromSelectorCreation=this.store.on.selectorCreation.subscribe(`auditor-${this.auditorCreatedAt}`,({key:n})=>{this.statesCreatedAt.set(n,performance.now()-this.auditorCreatedAt)}),this.unsubscribeFromSelectorDisposal=this.store.on.selectorDisposal.subscribe(`auditor-${this.auditorCreatedAt}`,({key:n})=>{this.statesCreatedAt.delete(n)})}static DEFAULT_LIST_RESOURCES_PARAM={atomFamilies:!0,selectorFamilies:!0};listResources(o=UF.DEFAULT_LIST_RESOURCES_PARAM){if(this.disposed)throw new Error("This Auditor has been disposed");const n=sf(this.atomIndex),t=sf(this.selectorIndex),S=[...n.values()].filter((F)=>("familyMembers"in F)),f=[...t.values()].filter((F)=>("familyMembers"in F)),T=performance.now(),M=[];if(o.atomFamilies)for(let F of S){const k=F.familyMembers.values();for(let A of k){const O=this.statesCreatedAt.get(A.key)??this.auditorCreatedAt,w=T-O;M.push([A,w])}}if(o.selectorFamilies)for(let F of f){const k=F.familyMembers.values();for(let A of k){const O=this.statesCreatedAt.get(A.key)??this.auditorCreatedAt,w=T-O;M.push([A,w])}}return M}[Symbol.dispose](){this.unsubscribeFromAtomCreation(),this.unsubscribeFromAtomDisposal(),this.unsubscribeFromSelectorCreation(),this.unsubscribeFromSelectorDisposal(),this.disposed=!0}}var GT=(o,n)=>{const t=(S,f)=>{const M=((k,A)=>{const $=n(k,A);if($)return $;return null})(S,f);if(M?.jobComplete??M?.pathComplete)return M;const F=Array.isArray(f)?f.map((k,A)=>[A,k]):YT(f)?Object.entries(f):[];for(let[k,A]of F){const $=t([...S,k],A);if($?.jobComplete)return $}return{}};t([],o)};function wy(o,n){return{summary:`${o<n?"+":"-"}${Math.abs(o-n)} (${o} \u2192 ${n})`}}function Ky(o,n){return{summary:`${o.length<n.length?"+":"-"}${Math.abs(o.length-n.length)} ("${o}" \u2192 "${n}")`}}function Xy(o,n){return{summary:`${o} \u2192 ${n}`}}function VF(o,n,t){let S="";const f=[],T=[],M=[];return GT(o,(F,k)=>{let A;for(A of F){const $=n[A];if($===void 0)T.push([A,JSON.stringify(k)]);else{const O=t(k,$);if(O.summary!=="No Change")M.push([A,O])}}}),GT(n,(F,k)=>{let A;for(A of F)if(o[A]===void 0)f.push([A,JSON.stringify(k)])}),S=`\uFF5E${M.length} \uFF0B${f.length} \uFF0D${T.length}`,{summary:S,added:f,removed:T,changed:M}}function Yy(o,n,t){return VF(o,n,t)}class rF{leafRefinery;treeRefinery;leafDiffers;treeDiffers;constructor(o,n,t){this.leafRefinery=o,this.treeRefinery=n,this.leafDiffers={},this.treeDiffers={};for(let S of Object.keys(o.supported)){const f=t[S];this.leafDiffers[S]=f}for(let S of Object.keys(n.supported)){const f=t[S];this.treeDiffers[S]=f}}diff(o,n){if(o===n)return{summary:"No Change"};const t=this.leafRefinery.refine(o)??this.treeRefinery.refine(o),S=this.leafRefinery.refine(n)??this.treeRefinery.refine(n);if(t!==null&&S!==null){if(t.type===S.type){if(t.type in this.leafDiffers)return this.leafDiffers[t.type](t.data,S.data);if(t.type in this.treeDiffers)return this.treeDiffers[t.type](t.data,S.data,(F,k)=>this.diff(F,k))}}const f=Ut(o),T=Ut(n);if(f===T)return{summary:`${f} \u2192 ${T}`};return{summary:`Type change: ${f} \u2192 ${T}`}}}var iX=new rF(XT,ET,{number:wy,string:Ky,boolean:Xy,null:()=>({summary:"No Change"}),object:VF,array:Yy});class Vt{o;listeners;globalListeners;handleEvent(o,...n){for(let S of this.globalListeners)S(o,...n);const t=this.listeners.get(o);if(t)for(let S of t)S(...n)}id="no_id_retrieved";constructor(o){this.emit=o;this.listeners=new Map,this.globalListeners=new Set}on(o,n){const t=this.listeners.get(o);if(t)t.add(n);else this.listeners.set(o,new Set([n]));return this}onAny(o){return this.globalListeners.add(o),this}off(o,n){const t=this.listeners.get(o);if(t)if(n)t.delete(n);else this.listeners.delete(o);return this}offAny(o){return this.globalListeners.delete(o),this}}class zT extends Vt{o;n;t;incompleteData="";unprocessedEvents=[];incompleteLog="";unprocessedLogs=[];id="#####";handleLog(o){if(Array.isArray(o)){const[n,...t]=o;switch(n){case"i":this.logger.info(this.id,this.key,...t);break;case"w":this.logger.warn(this.id,this.key,...t);break;case"e":this.logger.error(this.id,this.key,...t);break}}}constructor(o,n,t=console){super((S,...f)=>{const T=JSON.stringify([S,...f])+"\x03",M=(F)=>{if(F.code==="EPIPE")console.error("EPIPE error during write",this.process.stdin);this.process.stdin.removeListener("error",M)};return this.process.stdin.once("error",M),this.process.stdin.write(T),this});this.process=o;this.key=n;this.logger=t;if(this.process=o,this.process.stdout.on("data",(S)=>{const f=S.toString();if(f==="\u2728")return;this.unprocessedEvents.push(...f.split("\x03"));const T=this.unprocessedEvents.shift();this.incompleteData+=T??"";try{if(this.incompleteData.startsWith("error"))console.log("\u2757",this.incompleteData);let M=Uo(this.incompleteData);this.handleEvent(...M);while(this.unprocessedEvents.length>0){const F=this.unprocessedEvents.shift();if(F){if(this.unprocessedEvents.length===0)this.incompleteData=F;M=Uo(F),this.handleEvent(...M)}}this.incompleteData=""}catch(M){console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.warn(this.incompleteData),console.warn("\u26A0\uFE0F----------------\u26A0\uFE0F"),console.error(M)}}),this.process.stderr.on("data",(S)=>{const f=S.toString();this.unprocessedLogs.push(...f.split("\x03"));const T=this.unprocessedLogs.shift();this.incompleteLog+=T??"";try{let M=Uo(this.incompleteLog);this.handleLog(M);while(this.unprocessedLogs.length>0)if(this.incompleteLog=this.unprocessedLogs.shift()??"",this.incompleteLog)M=Uo(this.incompleteLog),this.handleLog(M)}catch(M){console.error("\u274C\u274C\u274C"),console.error(this.incompleteLog),console.error(M),console.error("\u274C\u274C\u274C\uFE0F")}}),o.pid)this.id=o.pid.toString()}}class CF extends Vt{in;out;id="no_id_retrieved";disposalFunctions=[];constructor(o){super((...n)=>{return this.out.next(n),this});this.id=o,this.in=new s,this.out=new s,this.in.subscribe("socket",(n)=>{this.handleEvent(...n)})}dispose(){for(let o of this.disposalFunctions)o()}}class HT extends Vt{incompleteData="";unprocessedEvents=[];relays;relayServices;process;id="#####";log(...o){this.process.stderr.write(l(o.map((n)=>n instanceof Bo?`{ ${n.toJSON().members.join(" | ")} }`:n))+"\x03")}logger={info:(...o)=>{this.log("i",...o)},warn:(...o)=>{this.log("w",...o)},error:(...o)=>{this.log("e",...o)}};constructor(){super((o,...n)=>{const t=JSON.stringify([o,...n]);return this.process.stdout.write(t+"\x03"),this});if(this.process=process,this.process.stdin.resume(),this.relays=new Map,this.relayServices=[],this.process.stdin.on("data",(o)=>{const n=o.toString();this.unprocessedEvents.push(...n.split("\x03"));const t=this.unprocessedEvents.shift();this.incompleteData+=t??"";try{const S=Uo(this.incompleteData);this.logger.info("\uD83C\uDFB0","received",S),this.handleEvent(...S);while(this.unprocessedEvents.length>0){const f=this.unprocessedEvents.shift();if(f){if(this.unprocessedEvents.length===0)this.incompleteData=f;const T=Uo(f);this.handleEvent(...T)}}this.incompleteData=""}catch(S){if(S instanceof Error)this.logger.error("\u2757",S.message,S.cause,S.stack)}}),this.on("exit",()=>{this.logger.info("\uD83D\uDD25",this.id,'received "exit"'),process.exit(0)}),process.on("exit",(o)=>{this.logger.info("\uD83D\uDD25",this.id,`exited with code ${o}`)}),process.on("end",()=>{this.logger.info("\uD83D\uDD25",this.id,"ended"),process.exit(0)}),process.on("SIGTERM",()=>{this.logger.error("\uD83D\uDD25",this.id,"terminated"),process.exit(0)}),process.on("SIGINT",()=>{this.logger.error("\uD83D\uDD25",this.id,"interrupted"),process.exit(0)}),process.pid)this.id=process.pid?.toString();this.on("user-joins",(o)=>{this.logger.info("\uD83D\uDC64","user",o,"joined");const n=new CF(`user:${o}`);this.relays.set(o,n),this.logger.info("\uD83D\uDD17","attaching services:",`[${[...this.relayServices.keys()].join(", ")}]`);for(let t of this.relayServices){const S=t(n);if(S)n.disposalFunctions.push(S)}this.on(`user:${o}`,(...t)=>{n.in.next(t)}),n.out.subscribe("socket",(t)=>{this.emit(...t)})}),this.on("user-leaves",(o)=>{const n=this.relays.get(o);if(this.off(`relay:${o}`),n)n.dispose(),this.relays.delete(o)}),process.stdout.write("\u2728")}relay(o){this.logger.info("\uD83D\uDD17","running relay method"),this.relayServices.push(o)}}class LF extends Map{set(o,n){if(this.has(o))return console.warn("Tried to set a key that already exists in an InvariantMap",{key:o,value:n}),this;return super.set(o,n)}clear(){throw new Error("Cannot clear an InvariantMap")}}class mT{o;type="continuity";globals=[];actions=[];perspectives=[];constructor(o){this.key=o}static existing=new LF;static create(o,n){const t=new mT(o),{type:S,globals:f,actions:T,perspectives:M}=n(t),F={type:S,key:o,globals:f,actions:T,perspectives:M};return mT.existing.set(o,F),F}add(...o){switch(o[0].type){case"atom":case"mutable_atom":this.globals.push(...o);break;case"transaction":this.actions.push(...o);break;case"atom_family":{const[t,S]=o;this.perspectives.push({type:"realtime_perspective",resourceAtoms:t,viewAtoms:S})}break}return this}}var K8=mt({key:"usersInRoomIndex",mutable:!0,default:()=>new Bo,toJson:(o)=>o.toJSON(),fromJson:(o)=>Bo.fromJSON(o)}),QT=mt({key:"roomIndex",default:()=>new Bo,mutable:!0,toJson:(o)=>o.toJSON(),fromJson:(o)=>Bo.fromJSON(o)}),Ey={enteredAtEpoch:0},RS=dS({key:"usersInRooms",between:["room","user"],cardinality:"1:n"},Ey),X8=ZS({key:"usersInMyRoomView",get:(o)=>({find:n})=>{const t=OF(RS);return[n(t,o)]}});import{spawn as Gy}from"child_process";var DT=kt({key:"roomArguments",default:["echo",["Hello World!"]]}),IF=ZS({key:"room",get:(o)=>async({get:n,find:t})=>{const S=t(DT,o),f=n(S),[T,M]=f,F=await new Promise((k)=>{const A=Gy(T,M,{env:process.env}),$=(O)=>{if(O.toString()==="\u2728")A.stdout.off("data",$),k(A)};A.stdout.on("data",$)});return new zT(F,o)}});var I8=FS({key:"createRoom",do:({get:o,set:n,find:t},S,f,T)=>{const M=T?[f,T]:[f],F=t(DT,S);n(F,M),n(QT,($)=>$.add(S));const k=t(IF,S);return o(k)}}),j8=FS({key:"joinRoom",do:(o,n,t,S)=>{const f={enteredAtEpoch:S};return uS(RS,(T)=>{T.set({room:n,user:t},f)},o.env().store),f}}),B8=FS({key:"leaveRoom",do:(o,n,t)=>{uS(RS,(S)=>{S.delete({room:n,user:t})},o.env().store)}}),c8=FS({key:"destroyRoom",do:(o,n)=>{uS(RS,(t)=>{t.delete({room:n})},o.env().store),o.set(QT,(t)=>(t.delete(n),t))}});var h8=kt({key:"transactionRedactor",default:{occlude:(o)=>o}}),zy=kt({key:"unacknowledgedUpdates",default:()=>[]});var Hy=kt({key:"sockets",default:null}),p8=mt({key:"socketsIndex",mutable:!0,default:()=>new Bo,toJson:(o)=>o.toJSON(),fromJson:(o)=>Bo.fromJSON(o)}),Z8=mt({key:"usersIndex",mutable:!0,default:()=>new Bo,toJson:(o)=>o.toJSON(),fromJson:(o)=>Bo.fromJSON(o)}),my=dS({key:"usersOfSockets",between:["user","socket"],cardinality:"1:1"});var{file:yJ,serve:r0}=globalThis.Bun;function X(o,n){if(!o||typeof o!=="object")return!1;if(o instanceof n)return!0;if(!Object.prototype.hasOwnProperty.call(n,y))throw new Error(`Class "${n.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(o).constructor;if(t)while(t){if(y in t&&t[y]===n[y])return!0;t=Object.getPrototypeOf(t)}return!1}var y=Symbol.for("drizzle:entityKind"),Q5=Symbol.for("drizzle:hasOwnEntityKind");class Ko{constructor(o,n){this.table=o,this.config=n,this.name=n.name,this.keyAsName=n.keyAsName,this.notNull=n.notNull,this.default=n.default,this.defaultFn=n.defaultFn,this.onUpdateFn=n.onUpdateFn,this.hasDefault=n.hasDefault,this.primary=n.primaryKey,this.isUnique=n.isUnique,this.uniqueName=n.uniqueName,this.uniqueType=n.uniqueType,this.dataType=n.dataType,this.columnType=n.columnType,this.generated=n.generated,this.generatedIdentity=n.generatedIdentity}static[y]="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(o){return o}mapToDriverValue(o){return o}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class UT{static[y]="ColumnBuilder";config;constructor(o,n,t){this.config={name:o,keyAsName:o==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:n,columnType:t,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(o){return this.config.default=o,this.config.hasDefault=!0,this}$defaultFn(o){return this.config.defaultFn=o,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(o){return this.config.onUpdateFn=o,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(o){if(this.config.name!=="")return;this.config.name=o}}var Hn=Symbol.for("drizzle:Name");class VT{static[y]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(o,n){if(this.reference=()=>{const{name:t,columns:S,foreignColumns:f}=o();return{name:t,columns:S,foreignTable:f[0].table,foreignColumns:f}},n)this._onUpdate=n.onUpdate,this._onDelete=n.onDelete}onUpdate(o){return this._onUpdate=o===void 0?"no action":o,this}onDelete(o){return this._onDelete=o===void 0?"no action":o,this}build(o){return new jF(o,this)}}class jF{constructor(o,n){this.table=o,this.reference=n.reference,this.onUpdate=n._onUpdate,this.onDelete=n._onDelete}static[y]="PgForeignKey";reference;onUpdate;onDelete;getName(){const{name:o,columns:n,foreignColumns:t}=this.reference(),S=n.map((M)=>M.name),f=t.map((M)=>M.name),T=[this.table[Hn],...S,t[0].table[Hn],...f];return o??`${T.join("_")}_fk`}}function Ff(o,...n){return o(...n)}function BF(o,n){return`${o[Hn]}_${n.join("_")}_unique`}function cF(o,n,t){for(let S=n;S<o.length;S++){const f=o[S];if(f==="\\"){S++;continue}if(f==='"')return[o.slice(n,S).replace(/\\/g,""),S+1];if(t)continue;if(f===","||f==="}")return[o.slice(n,S).replace(/\\/g,""),S]}return[o.slice(n).replace(/\\/g,""),o.length]}function bF(o,n=0){const t=[];let S=n,f=!1;while(S<o.length){const T=o[S];if(T===","){if(f||S===n)t.push("");f=!0,S++;continue}if(f=!1,T==="\\"){S+=2;continue}if(T==='"'){const[k,A]=cF(o,S+1,!0);t.push(k),S=A;continue}if(T==="}")return[t,S+1];if(T==="{"){const[k,A]=bF(o,S+1);t.push(k),S=A;continue}const[M,F]=cF(o,S,!1);t.push(M),S=F}return[t,S]}function NF(o){const[n]=bF(o,1);return n}function rT(o){return`{${o.map((n)=>{if(Array.isArray(n))return rT(n);if(typeof n==="string")return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;return`${n}`}).join(",")}}`}class c extends UT{foreignKeyConfigs=[];static[y]="PgColumnBuilder";array(o){return new xF(this.config.name,this,o)}references(o,n={}){return this.foreignKeyConfigs.push({ref:o,actions:n}),this}unique(o,n){return this.config.isUnique=!0,this.config.uniqueName=o,this.config.uniqueType=n?.nulls,this}generatedAlwaysAs(o){return this.config.generated={as:o,type:"always",mode:"stored"},this}buildForeignKeys(o,n){return this.foreignKeyConfigs.map(({ref:t,actions:S})=>{return Ff((f,T)=>{const M=new VT(()=>{const F=f();return{columns:[o],foreignColumns:[F]}});if(T.onUpdate)M.onUpdate(T.onUpdate);if(T.onDelete)M.onDelete(T.onDelete);return M.build(n)},t,S)})}buildExtraConfigColumn(o){return new hF(o,this.config)}}class U extends Ko{constructor(o,n){if(!n.uniqueName)n.uniqueName=BF(o,[n.name]);super(o,n);this.table=o}static[y]="PgColumn"}class hF extends U{static[y]="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(o){return this.indexConfig.opClass=o,this}}class OS{static[y]="IndexedColumn";constructor(o,n,t,S){this.name=o,this.keyAsName=n,this.type=t,this.indexConfig=S}name;keyAsName;type;indexConfig}class xF extends c{static[y]="PgArrayBuilder";constructor(o,n,t){super(o,"array","PgArray");this.config.baseBuilder=n,this.config.size=t}build(o){const n=this.config.baseBuilder.build(o);return new CT(o,this.config,n)}}class CT extends U{constructor(o,n,t,S){super(o,n);this.baseColumn=t,this.range=S,this.size=n.size}size;static[y]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(o){if(typeof o==="string")o=NF(o);return o.map((n)=>this.baseColumn.mapFromDriverValue(n))}mapToDriverValue(o,n=!1){const t=o.map((S)=>S===null?null:X(this.baseColumn,CT)?this.baseColumn.mapToDriverValue(S,!0):this.baseColumn.mapToDriverValue(S));if(n)return t;return rT(t)}}function iF(o){return!!o&&typeof o==="function"&&LT in o&&o[LT]===!0}function kf(o,n){return Qy(o,n,void 0)}function Qy(o,n,t){const S=Object.assign((f)=>new vF(f??"",S),{enumName:o,enumValues:n,schema:t,[LT]:!0});return S}var LT=Symbol.for("drizzle:isPgEnum");class vF extends c{static[y]="PgEnumColumnBuilder";constructor(o,n){super(o,"string","PgEnumColumn");this.config.enum=n}build(o){return new qF(o,this.config)}}class qF extends U{static[y]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(o,n){super(o,n);this.enum=n.enum}getSQLType(){return this.enum.enumName}}class xo{static[y]="Subquery";constructor(o,n,t,S=!1){this._={brand:"Subquery",sql:o,selectedFields:n,alias:t,isWith:S}}}class WS extends xo{static[y]="WithSubquery"}var pF="0.35.1";var IT,jT,Oo={startActiveSpan(o,n){if(!IT)return n();if(!jT)jT=IT.trace.getTracer("drizzle-orm",pF);return Ff((t,S)=>S.startActiveSpan(o,(f)=>{try{return n(f)}catch(T){throw f.setStatus({code:t.SpanStatusCode.ERROR,message:T instanceof Error?T.message:"Unknown error"}),T}finally{f.end()}}),IT,jT)}};var mo=Symbol.for("drizzle:ViewBaseConfig");function Wn(o){return o[Hn]}function $t(o){return`${o[Af]??"public"}.${o[Hn]}`}var Af=Symbol.for("drizzle:Schema"),ZF=Symbol.for("drizzle:Columns"),PF=Symbol.for("drizzle:ExtraConfigColumns"),BT=Symbol.for("drizzle:OriginalName"),cT=Symbol.for("drizzle:BaseName"),gF=Symbol.for("drizzle:IsAlias"),lF=Symbol.for("drizzle:ExtraConfigBuilder"),Dy=Symbol.for("drizzle:IsDrizzleTable");class j{static[y]="Table";static Symbol={Name:Hn,Schema:Af,OriginalName:BT,Columns:ZF,ExtraConfigColumns:PF,BaseName:cT,IsAlias:gF,ExtraConfigBuilder:lF};[Hn];[BT];[Af];[ZF];[PF];[cT];[gF]=!1;[Dy]=!0;[lF]=void 0;constructor(o,n,t){this[Hn]=this[BT]=o,this[Af]=n,this[cT]=t}}function bT(o){return o!==null&&o!==void 0&&typeof o.getSQL==="function"}function Uy(o){const n={sql:"",params:[]};for(let t of o)if(n.sql+=t.sql,n.params.push(...t.params),t.typings?.length){if(!n.typings)n.typings=[];n.typings.push(...t.typings)}return n}function eF(o){return typeof o==="object"&&o!==null&&"mapToDriverValue"in o&&typeof o.mapToDriverValue==="function"}function R(o,...n){const t=[];if(n.length>0||o.length>0&&o[0]!=="")t.push(new co(o[0]));for(let[S,f]of n.entries())t.push(f,new co(o[S+1]));return new b(t)}function NT(o,n){return o.map((t)=>{if(X(t,an)){if(!(t.name in n))throw new Error(`No value for placeholder "${t.name}" was provided`);return n[t.name]}if(X(t,An)&&X(t.value,an)){if(!(t.value.name in n))throw new Error(`No value for placeholder "${t.value.name}" was provided`);return t.encoder.mapToDriverValue(n[t.value.name])}return t})}class co{static[y]="StringChunk";value;constructor(o){this.value=Array.isArray(o)?o:[o]}getSQL(){return new b([this])}}class b{constructor(o){this.queryChunks=o}static[y]="SQL";decoder=dF;shouldInlineParams=!1;append(o){return this.queryChunks.push(...o.queryChunks),this}toQuery(o){return Oo.startActiveSpan("drizzle.buildSQL",(n)=>{const t=this.buildQueryFromSourceParams(this.queryChunks,o);return n?.setAttributes({"drizzle.query.text":t.sql,"drizzle.query.params":JSON.stringify(t.params)}),t})}buildQueryFromSourceParams(o,n){const t=Object.assign({},n,{inlineParams:n.inlineParams||this.shouldInlineParams,paramStartIndex:n.paramStartIndex||{value:0}}),{casing:S,escapeName:f,escapeParam:T,prepareTyping:M,inlineParams:F,paramStartIndex:k}=t;return Uy(o.map((A)=>{if(X(A,co))return{sql:A.value.join(""),params:[]};if(X(A,$f))return{sql:f(A.value),params:[]};if(A===void 0)return{sql:"",params:[]};if(Array.isArray(A)){const $=[new co("(")];for(let[O,w]of A.entries())if($.push(w),O<A.length-1)$.push(new co(", "));return $.push(new co(")")),this.buildQueryFromSourceParams($,t)}if(X(A,b))return this.buildQueryFromSourceParams(A.queryChunks,{...t,inlineParams:F||A.shouldInlineParams});if(X(A,j)){const $=A[j.Symbol.Schema],O=A[j.Symbol.Name];return{sql:$===void 0?f(O):f($)+"."+f(O),params:[]}}if(X(A,Ko)){const $=S.getColumnCasing(A);if(n.invokeSource==="indexes")return{sql:f($),params:[]};return{sql:f(A.table[j.Symbol.Name])+"."+f($),params:[]}}if(X(A,Sn)){const $=A[mo].schema,O=A[mo].name;return{sql:$===void 0?f(O):f($)+"."+f(O),params:[]}}if(X(A,An)){if(X(A.value,an))return{sql:T(k.value++,A),params:[A],typings:["none"]};const $=A.value===null?null:A.encoder.mapToDriverValue(A.value);if(X($,b))return this.buildQueryFromSourceParams([$],t);if(F)return{sql:this.mapInlineParam($,t),params:[]};let O=["none"];if(M)O=[M(A.encoder)];return{sql:T(k.value++,$),params:[$],typings:O}}if(X(A,an))return{sql:T(k.value++,A),params:[A],typings:["none"]};if(X(A,b.Aliased)&&A.fieldAlias!==void 0)return{sql:f(A.fieldAlias),params:[]};if(X(A,xo)){if(A._.isWith)return{sql:f(A._.alias),params:[]};return this.buildQueryFromSourceParams([new co("("),A._.sql,new co(") "),new $f(A._.alias)],t)}if(iF(A)){if(A.schema)return{sql:f(A.schema)+"."+f(A.enumName),params:[]};return{sql:f(A.enumName),params:[]}}if(bT(A)){if(A.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([A.getSQL()],t);return this.buildQueryFromSourceParams([new co("("),A.getSQL(),new co(")")],t)}if(F)return{sql:this.mapInlineParam(A,t),params:[]};return{sql:T(k.value++,A),params:[A],typings:["none"]}}))}mapInlineParam(o,{escapeString:n}){if(o===null)return"null";if(typeof o==="number"||typeof o==="boolean")return o.toString();if(typeof o==="string")return n(o);if(typeof o==="object"){const t=o.toString();if(t==="[object Object]")return n(JSON.stringify(o));return n(t)}throw new Error("Unexpected param value: "+o)}getSQL(){return this}as(o){if(o===void 0)return this;return new b.Aliased(this,o)}mapWith(o){return this.decoder=typeof o==="function"?{mapFromDriverValue:o}:o,this}inlineParams(){return this.shouldInlineParams=!0,this}if(o){return o?this:void 0}}class $f{constructor(o){this.value=o}static[y]="Name";brand;getSQL(){return new b([this])}}var dF={mapFromDriverValue:(o)=>o},uF={mapToDriverValue:(o)=>o},OY={...dF,...uF};class An{constructor(o,n=uF){this.value=o,this.encoder=n}static[y]="Param";brand;getSQL(){return new b([this])}}((o)=>{function n(){return new b([])}o.empty=n;function t(k){return new b(k)}o.fromList=t;function S(k){return new b([new co(k)])}o.raw=S;function f(k,A){const $=[];for(let[O,w]of k.entries()){if(O>0&&A!==void 0)$.push(A);$.push(w)}return new b($)}o.join=f;function T(k){return new $f(k)}o.identifier=T;function M(k){return new an(k)}o.placeholder=M;function F(k,A){return new An(k,A)}o.param=F})(R||(R={}));((o)=>{class n{constructor(t,S){this.sql=t,this.fieldAlias=S}static[y]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new n(this.sql,this.fieldAlias)}}o.Aliased=n})(b||(b={}));class an{constructor(o){this.name=o}static[y]="Placeholder";getSQL(){return new b([this])}}class Sn{static[y]="View";[mo];constructor({name:o,schema:n,selectedFields:t,query:S}){this[mo]={name:o,originalName:o,schema:n,selectedFields:t,query:S,isExisting:!S,isAlias:!1}}getSQL(){return new b([this])}}Ko.prototype.getSQL=function(){return new b([this])};j.prototype.getSQL=function(){return new b([this])};xo.prototype.getSQL=function(){return new b([this])};function Jf(o,n){return new Proxy(o,new _S(n,!1))}function Bn(o,n){return new Proxy(o,new rt(new Proxy(o.table,new _S(n,!1))))}function hT(o,n){return new b.Aliased(wS(o.sql,n),o.fieldAlias)}function wS(o,n){return R.join(o.queryChunks.map((t)=>{if(X(t,Ko))return Bn(t,n);if(X(t,b))return wS(t,n);if(X(t,b.Aliased))return hT(t,n);return t}))}class rt{constructor(o){this.table=o}static[y]="ColumnAliasProxyHandler";get(o,n){if(n==="table")return this.table;return o[n]}}class _S{constructor(o,n){this.alias=o,this.replaceOriginalName=n}static[y]="TableAliasProxyHandler";get(o,n){if(n===j.Symbol.IsAlias)return!0;if(n===j.Symbol.Name)return this.alias;if(this.replaceOriginalName&&n===j.Symbol.OriginalName)return this.alias;if(n===mo)return{...o[mo],name:this.alias,isAlias:!0};if(n===j.Symbol.Columns){const S=o[j.Symbol.Columns];if(!S)return S;const f={};return Object.keys(S).map((T)=>{f[T]=new Proxy(S[T],new rt(new Proxy(o,this)))}),f}const t=o[n];if(X(t,Ko))return new Proxy(t,new rt(new Proxy(o,this)));return t}}class yf extends Error{static[y]="DrizzleError";constructor({message:o,cause:n}){super(o);this.name="DrizzleError",this.cause=n}}class xT extends yf{static[y]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}function fn(o,n){if(eF(n)&&!bT(o)&&!X(o,An)&&!X(o,an)&&!X(o,Ko)&&!X(o,j)&&!X(o,Sn))return new An(o,n);return o}function KS(...o){const n=o.filter((t)=>t!==void 0);if(n.length===0)return;if(n.length===1)return new b(n);return new b([new co("("),R.join(n,new co(" and ")),new co(")")])}function sF(...o){const n=o.filter((t)=>t!==void 0);if(n.length===0)return;if(n.length===1)return new b(n);return new b([new co("("),R.join(n,new co(" or ")),new co(")")])}function ok(o){return R`not ${o}`}function Tk(o,n){if(Array.isArray(n)){if(n.length===0)return R`false`;return R`${o} in ${n.map((t)=>fn(t,o))}`}return R`${o} in ${fn(n,o)}`}function Mk(o,n){if(Array.isArray(n)){if(n.length===0)return R`true`;return R`${o} not in ${n.map((t)=>fn(t,o))}`}return R`${o} not in ${fn(n,o)}`}function Fk(o){return R`${o} is null`}function kk(o){return R`${o} is not null`}function Ak(o){return R`exists ${o}`}function $k(o){return R`not exists ${o}`}function Jk(o,n,t){return R`${o} between ${fn(n,o)} and ${fn(t,o)}`}function yk(o,n,t){return R`${o} not between ${fn(n,o)} and ${fn(t,o)}`}function Rk(o,n){return R`${o} like ${n}`}function Ok(o,n){return R`${o} not like ${n}`}function Wk(o,n){return R`${o} ilike ${n}`}function _k(o,n){return R`${o} not ilike ${n}`}var Ct=(o,n)=>{return R`${o} = ${fn(n,o)}`},aF=(o,n)=>{return R`${o} <> ${fn(n,o)}`},nk=(o,n)=>{return R`${o} > ${fn(n,o)}`},tk=(o,n)=>{return R`${o} >= ${fn(n,o)}`},Sk=(o,n)=>{return R`${o} < ${fn(n,o)}`},fk=(o,n)=>{return R`${o} <= ${fn(n,o)}`};function wk(o){return R`${o} asc`}function Kk(o){return R`${o} desc`}class Xk{static[y]="ConsoleLogWriter";write(o){console.log(o)}}class iT{static[y]="DefaultLogger";writer;constructor(o){this.writer=o?.writer??new Xk}logQuery(o,n){const t=n.map((f)=>{try{return JSON.stringify(f)}catch{return String(f)}}),S=t.length?` -- params: [${t.join(", ")}]`:"";this.writer.write(`Query: ${o}${S}`)}}class vT{static[y]="NoopLogger";logQuery(){}}class ao{static[y]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(o){return this.then(void 0,o)}finally(o){return this.then((n)=>{return o?.(),n},(n)=>{throw o?.(),n})}then(o,n){return this.execute().then(o,n)}}function Yk(o,n,t){const S={},f=o.reduce((T,{path:M,field:F},k)=>{let A;if(X(F,Ko))A=F;else if(X(F,b))A=F.decoder;else A=F.sql.decoder;let $=T;for(let[O,w]of M.entries())if(O<M.length-1){if(!(w in $))$[w]={};$=$[w]}else{const G=n[k],r=$[w]=G===null?null:A.mapFromDriverValue(G);if(t&&X(F,Ko)&&M.length===2){const H=M[0];if(!(H in S))S[H]=r===null?Wn(F.table):!1;else if(typeof S[H]==="string"&&S[H]!==Wn(F.table))S[H]=!1}}return T},{});if(t&&Object.keys(S).length>0){for(let[T,M]of Object.entries(S))if(typeof M==="string"&&!t[M])f[T]=null}return f}function _n(o,n){return Object.entries(o).reduce((t,[S,f])=>{if(typeof S!=="string")return t;const T=n?[...n,S]:[S];if(X(f,Ko)||X(f,b)||X(f,b.Aliased))t.push({path:T,field:f});else if(X(f,j))t.push(..._n(f[j.Symbol.Columns],T));else t.push(..._n(f,T));return t},[])}function qT(o,n){const t=Object.keys(o),S=Object.keys(n);if(t.length!==S.length)return!1;for(let[f,T]of t.entries())if(T!==S[f])return!1;return!0}function Rf(o,n){const t=Object.entries(n).filter(([,S])=>S!==void 0).map(([S,f])=>{if(X(f,b))return[S,f];else return[S,new An(f,o[j.Symbol.Columns][S])]});if(t.length===0)throw new Error("No values to set");return Object.fromEntries(t)}function Ek(o,n){for(let t of n)for(let S of Object.getOwnPropertyNames(t.prototype)){if(S==="constructor")continue;Object.defineProperty(o.prototype,S,Object.getOwnPropertyDescriptor(t.prototype,S)||Object.create(null))}}function Gk(o){return o[j.Symbol.Columns]}function pT(o){return X(o,xo)?o._.alias:X(o,Sn)?o[mo].name:X(o,b)?void 0:o[j.Symbol.IsAlias]?o[j.Symbol.Name]:o[j.Symbol.BaseName]}function Mo(o,n){return{name:typeof o==="string"&&o.length>0?o:"",config:typeof o==="object"?o:n}}class sn extends c{static[y]="PgIntColumnBaseBuilder";generatedAlwaysAsIdentity(o){if(o){const{name:n,...t}=o;this.config.generatedIdentity={type:"always",sequenceName:n,sequenceOptions:t}}else this.config.generatedIdentity={type:"always"};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(o){if(o){const{name:n,...t}=o;this.config.generatedIdentity={type:"byDefault",sequenceName:n,sequenceOptions:t}}else this.config.generatedIdentity={type:"byDefault"};return this.config.hasDefault=!0,this.config.notNull=!0,this}}function Dk(o,n){const{name:t,config:S}=Mo(o,n);if(S.mode==="number")return new zk(t);return new mk(t)}class zk extends sn{static[y]="PgBigInt53Builder";constructor(o){super(o,"number","PgBigInt53")}build(o){return new Hk(o,this.config)}}class Hk extends U{static[y]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class mk extends sn{static[y]="PgBigInt64Builder";constructor(o){super(o,"bigint","PgBigInt64")}build(o){return new Qk(o,this.config)}}class Qk extends U{static[y]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(o){return BigInt(o)}}function Lk(o,n){const{name:t,config:S}=Mo(o,n);if(S.mode==="number")return new Uk(t);return new rk(t)}class Uk extends c{static[y]="PgBigSerial53Builder";constructor(o){super(o,"number","PgBigSerial53");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new Vk(o,this.config)}}class Vk extends U{static[y]="PgBigSerial53";getSQLType(){return"bigserial"}mapFromDriverValue(o){if(typeof o==="number")return o;return Number(o)}}class rk extends c{static[y]="PgBigSerial64Builder";constructor(o){super(o,"bigint","PgBigSerial64");this.config.hasDefault=!0}build(o){return new Ck(o,this.config)}}class Ck extends U{static[y]="PgBigSerial64";getSQLType(){return"bigserial"}mapFromDriverValue(o){return BigInt(o)}}function XS(o){return new Ik(o??"")}class Ik extends c{static[y]="PgBooleanBuilder";constructor(o){super(o,"boolean","PgBoolean")}build(o){return new jk(o,this.config)}}class jk extends U{static[y]="PgBoolean";getSQLType(){return"boolean"}}function bk(o,n={}){const{name:t,config:S}=Mo(o,n);return new Bk(t,S)}class Bk extends c{static[y]="PgCharBuilder";constructor(o,n){super(o,"string","PgChar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new ck(o,this.config)}}class ck extends U{static[y]="PgChar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"char":`char(${this.length})`}}function xk(o){return new Nk(o??"")}class Nk extends c{static[y]="PgCidrBuilder";constructor(o){super(o,"string","PgCidr")}build(o){return new hk(o,this.config)}}class hk extends U{static[y]="PgCidr";getSQLType(){return"cidr"}}function qk(o){return(n,t)=>{const{name:S,config:f}=Mo(n,t);return new ik(S,f,o)}}class ik extends c{static[y]="PgCustomColumnBuilder";constructor(o,n,t){super(o,"custom","PgCustomColumn");this.config.fieldConfig=n,this.config.customTypeParams=t}build(o){return new vk(o,this.config)}}class vk extends U{static[y]="PgCustomColumn";sqlName;mapTo;mapFrom;constructor(o,n){super(o,n);this.sqlName=n.customTypeParams.dataType(n.fieldConfig),this.mapTo=n.customTypeParams.toDriver,this.mapFrom=n.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(o){return typeof this.mapFrom==="function"?this.mapFrom(o):o}mapToDriverValue(o){return typeof this.mapTo==="function"?this.mapTo(o):o}}class qn extends c{static[y]="PgDateColumnBaseBuilder";defaultNow(){return this.default(R`now()`)}}function Pk(o,n){const{name:t,config:S}=Mo(o,n);if(S?.mode==="date")return new pk(t);return new Zk(t)}class pk extends qn{static[y]="PgDateBuilder";constructor(o){super(o,"date","PgDate")}build(o){return new Of(o,this.config)}}class Of extends U{static[y]="PgDate";getSQLType(){return"date"}mapFromDriverValue(o){return new Date(o)}mapToDriverValue(o){return o.toISOString()}}class Zk extends qn{static[y]="PgDateStringBuilder";constructor(o){super(o,"string","PgDateString")}build(o){return new Wf(o,this.config)}}class Wf extends U{static[y]="PgDateString";getSQLType(){return"date"}}function ek(o){return new gk(o??"")}class gk extends c{static[y]="PgDoublePrecisionBuilder";constructor(o){super(o,"number","PgDoublePrecision")}build(o){return new lk(o,this.config)}}class lk extends U{static[y]="PgDoublePrecision";getSQLType(){return"double precision"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseFloat(o);return o}}function ak(o){return new dk(o??"")}class dk extends c{static[y]="PgInetBuilder";constructor(o){super(o,"string","PgInet")}build(o){return new uk(o,this.config)}}class uk extends U{static[y]="PgInet";getSQLType(){return"inet"}}function _f(o){return new sk(o??"")}class sk extends sn{static[y]="PgIntegerBuilder";constructor(o){super(o,"number","PgInteger")}build(o){return new oA(o,this.config)}}class oA extends U{static[y]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(o){if(typeof o==="string")return Number.parseInt(o);return o}}function SA(o,n={}){const{name:t,config:S}=Mo(o,n);return new nA(t,S)}class nA extends c{static[y]="PgIntervalBuilder";constructor(o,n){super(o,"string","PgInterval");this.config.intervalConfig=n}build(o){return new tA(o,this.config)}}class tA extends U{static[y]="PgInterval";fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){const o=this.fields?` ${this.fields}`:"",n=this.precision?`(${this.precision})`:"";return`interval${o}${n}`}}function TA(o){return new fA(o??"")}class fA extends c{static[y]="PgJsonBuilder";constructor(o){super(o,"json","PgJson")}build(o){return new wf(o,this.config)}}class wf extends U{static[y]="PgJson";constructor(o,n){super(o,n)}getSQLType(){return"json"}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){if(typeof o==="string")try{return JSON.parse(o)}catch{return o}return o}}function FA(o){return new MA(o??"")}class MA extends c{static[y]="PgJsonbBuilder";constructor(o){super(o,"json","PgJsonb")}build(o){return new Kf(o,this.config)}}class Kf extends U{static[y]="PgJsonb";constructor(o,n){super(o,n)}getSQLType(){return"jsonb"}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){if(typeof o==="string")try{return JSON.parse(o)}catch{return o}return o}}function yA(o,n){const{name:t,config:S}=Mo(o,n);if(!S?.mode||S.mode==="tuple")return new kA(t);return new $A(t)}class kA extends c{static[y]="PgLineBuilder";constructor(o){super(o,"array","PgLine")}build(o){return new AA(o,this.config)}}class AA extends U{static[y]="PgLine";getSQLType(){return"line"}mapFromDriverValue(o){const[n,t,S]=o.slice(1,-1).split(",");return[Number.parseFloat(n),Number.parseFloat(t),Number.parseFloat(S)]}mapToDriverValue(o){return`{${o[0]},${o[1]},${o[2]}}`}}class $A extends c{static[y]="PgLineABCBuilder";constructor(o){super(o,"json","PgLineABC")}build(o){return new JA(o,this.config)}}class JA extends U{static[y]="PgLineABC";getSQLType(){return"line"}mapFromDriverValue(o){const[n,t,S]=o.slice(1,-1).split(",");return{a:Number.parseFloat(n),b:Number.parseFloat(t),c:Number.parseFloat(S)}}mapToDriverValue(o){return`{${o.a},${o.b},${o.c}}`}}function WA(o){return new RA(o??"")}class RA extends c{static[y]="PgMacaddrBuilder";constructor(o){super(o,"string","PgMacaddr")}build(o){return new OA(o,this.config)}}class OA extends U{static[y]="PgMacaddr";getSQLType(){return"macaddr"}}function KA(o){return new _A(o??"")}class _A extends c{static[y]="PgMacaddr8Builder";constructor(o){super(o,"string","PgMacaddr8")}build(o){return new wA(o,this.config)}}class wA extends U{static[y]="PgMacaddr8";getSQLType(){return"macaddr8"}}function YA(o,n){const{name:t,config:S}=Mo(o,n);return new XA(t,S?.precision,S?.scale)}class XA extends c{static[y]="PgNumericBuilder";constructor(o,n,t){super(o,"string","PgNumeric");this.config.precision=n,this.config.scale=t}build(o){return new Xf(o,this.config)}}class Xf extends U{static[y]="PgNumeric";precision;scale;constructor(o,n){super(o,n);this.precision=n.precision,this.scale=n.scale}getSQLType(){if(this.precision!==void 0&&this.scale!==void 0)return`numeric(${this.precision}, ${this.scale})`;else if(this.precision===void 0)return"numeric";else return`numeric(${this.precision})`}}function mA(o,n){const{name:t,config:S}=Mo(o,n);if(!S?.mode||S.mode==="tuple")return new EA(t);return new zA(t)}class EA extends c{static[y]="PgPointTupleBuilder";constructor(o){super(o,"array","PgPointTuple")}build(o){return new GA(o,this.config)}}class GA extends U{static[y]="PgPointTuple";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){const[n,t]=o.slice(1,-1).split(",");return[Number.parseFloat(n),Number.parseFloat(t)]}return[o.x,o.y]}mapToDriverValue(o){return`(${o[0]},${o[1]})`}}class zA extends c{static[y]="PgPointObjectBuilder";constructor(o){super(o,"json","PgPointObject")}build(o){return new HA(o,this.config)}}class HA extends U{static[y]="PgPointObject";getSQLType(){return"point"}mapFromDriverValue(o){if(typeof o==="string"){const[n,t]=o.slice(1,-1).split(",");return{x:Number.parseFloat(n),y:Number.parseFloat(t)}}return o}mapToDriverValue(o){return`(${o.x},${o.y})`}}function Vy(o){const n=[];for(let t=0;t<o.length;t+=2)n.push(Number.parseInt(o.slice(t,t+2),16));return new Uint8Array(n)}function QA(o,n){const t=new ArrayBuffer(8),S=new DataView(t);for(let f=0;f<8;f++)S.setUint8(f,o[n+f]);return S.getFloat64(0,!0)}function ZT(o){const n=Vy(o);let t=0;const S=n[t];t+=1;const f=new DataView(n.buffer),T=f.getUint32(t,S===1);t+=4;let M;if(T&536870912)M=f.getUint32(t,S===1),t+=4;if((T&65535)===1){const F=QA(n,t);t+=8;const k=QA(n,t);return t+=8,[F,k]}throw new Error("Unsupported geometry type")}function CA(o,n){const{name:t,config:S}=Mo(o,n);if(!S?.mode||S.mode==="tuple")return new DA(t);return new VA(t)}class DA extends c{static[y]="PgGeometryBuilder";constructor(o){super(o,"array","PgGeometry")}build(o){return new UA(o,this.config)}}class UA extends U{static[y]="PgGeometry";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){return ZT(o)}mapToDriverValue(o){return`point(${o[0]} ${o[1]})`}}class VA extends c{static[y]="PgGeometryObjectBuilder";constructor(o){super(o,"json","PgGeometryObject")}build(o){return new rA(o,this.config)}}class rA extends U{static[y]="PgGeometryObject";getSQLType(){return"geometry(point)"}mapFromDriverValue(o){const n=ZT(o);return{x:n[0],y:n[1]}}mapToDriverValue(o){return`point(${o.x} ${o.y})`}}function jA(o){return new LA(o??"")}class LA extends c{static[y]="PgRealBuilder";constructor(o,n){super(o,"number","PgReal");this.config.length=n}build(o){return new IA(o,this.config)}}class IA extends U{static[y]="PgReal";constructor(o,n){super(o,n)}getSQLType(){return"real"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number.parseFloat(o);return o}}function bA(o){return new BA(o??"")}class BA extends c{static[y]="PgSerialBuilder";constructor(o){super(o,"number","PgSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new cA(o,this.config)}}class cA extends U{static[y]="PgSerial";getSQLType(){return"serial"}}function xA(o){return new NA(o??"")}class NA extends sn{static[y]="PgSmallIntBuilder";constructor(o){super(o,"number","PgSmallInt")}build(o){return new hA(o,this.config)}}class hA extends U{static[y]="PgSmallInt";getSQLType(){return"smallint"}mapFromDriverValue=(o)=>{if(typeof o==="string")return Number(o);return o}}function qA(o){return new iA(o??"")}class iA extends c{static[y]="PgSmallSerialBuilder";constructor(o){super(o,"number","PgSmallSerial");this.config.hasDefault=!0,this.config.notNull=!0}build(o){return new vA(o,this.config)}}class vA extends U{static[y]="PgSmallSerial";getSQLType(){return"smallserial"}}function PA(o,n={}){const{name:t,config:S}=Mo(o,n);return new pA(t,S)}class pA extends c{static[y]="PgTextBuilder";constructor(o,n){super(o,"string","PgText");this.config.enumValues=n.enum}build(o){return new ZA(o,this.config)}}class ZA extends U{static[y]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function lA(o,n={}){const{name:t,config:S}=Mo(o,n);return new gA(t,S.withTimezone??!1,S.precision)}class gA extends qn{constructor(o,n,t){super(o,"string","PgTime");this.withTimezone=n,this.precision=t,this.config.withTimezone=n,this.config.precision=t}static[y]="PgTimeBuilder";build(o){return new Yf(o,this.config)}}class Yf extends U{static[y]="PgTime";withTimezone;precision;constructor(o,n){super(o,n);this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`time${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function mn(o,n={}){const{name:t,config:S}=Mo(o,n);if(S?.mode==="string")return new dA(t,S.withTimezone??!1,S.precision);return new eA(t,S?.withTimezone??!1,S?.precision)}class eA extends qn{static[y]="PgTimestampBuilder";constructor(o,n,t){super(o,"date","PgTimestamp");this.config.withTimezone=n,this.config.precision=t}build(o){return new Ef(o,this.config)}}class Ef extends U{static[y]="PgTimestamp";withTimezone;precision;constructor(o,n){super(o,n);this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`timestamp${this.precision===void 0?"":` (${this.precision})`}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=(o)=>{return new Date(this.withTimezone?o:o+"+0000")};mapToDriverValue=(o)=>{return o.toISOString()}}class dA extends qn{static[y]="PgTimestampStringBuilder";constructor(o,n,t){super(o,"string","PgTimestampString");this.config.withTimezone=n,this.config.precision=t}build(o){return new Gf(o,this.config)}}class Gf extends U{static[y]="PgTimestampString";withTimezone;precision;constructor(o,n){super(o,n);this.withTimezone=n.withTimezone,this.precision=n.precision}getSQLType(){return`timestamp${this.precision===void 0?"":`(${this.precision})`}${this.withTimezone?" with time zone":""}`}}function $n(o){return new uA(o??"")}class uA extends c{static[y]="PgUUIDBuilder";constructor(o){super(o,"string","PgUUID")}defaultRandom(){return this.default(R`gen_random_uuid()`)}build(o){return new zf(o,this.config)}}class zf extends U{static[y]="PgUUID";getSQLType(){return"uuid"}}function io(o,n={}){const{name:t,config:S}=Mo(o,n);return new aA(t,S)}class aA extends c{static[y]="PgVarcharBuilder";constructor(o,n){super(o,"string","PgVarchar");this.config.length=n.length,this.config.enumValues=n.enum}build(o){return new sA(o,this.config)}}class sA extends U{static[y]="PgVarchar";length=this.config.length;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?"varchar":`varchar(${this.length})`}}function t$(o,n){const{name:t,config:S}=Mo(o,n);return new o$(t,S)}class o$ extends c{static[y]="PgBinaryVectorBuilder";constructor(o,n){super(o,"string","PgBinaryVector");this.config.dimensions=n.dimensions}build(o){return new n$(o,this.config)}}class n$ extends U{static[y]="PgBinaryVector";dimensions=this.config.dimensions;getSQLType(){return`bit(${this.dimensions})`}}function T$(o,n){const{name:t,config:S}=Mo(o,n);return new S$(t,S)}class S$ extends c{static[y]="PgHalfVectorBuilder";constructor(o,n){super(o,"array","PgHalfVector");this.config.dimensions=n.dimensions}build(o){return new f$(o,this.config)}}class f$ extends U{static[y]="PgHalfVector";dimensions=this.config.dimensions;getSQLType(){return`halfvec(${this.dimensions})`}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){return o.slice(1,-1).split(",").map((n)=>Number.parseFloat(n))}}function k$(o,n){const{name:t,config:S}=Mo(o,n);return new M$(t,S)}class M$ extends c{static[y]="PgSparseVectorBuilder";constructor(o,n){super(o,"string","PgSparseVector");this.config.dimensions=n.dimensions}build(o){return new F$(o,this.config)}}class F$ extends U{static[y]="PgSparseVector";dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}}function J$(o,n){const{name:t,config:S}=Mo(o,n);return new A$(t,S)}class A$ extends c{static[y]="PgVectorBuilder";constructor(o,n){super(o,"array","PgVector");this.config.dimensions=n.dimensions}build(o){return new $$(o,this.config)}}class $$ extends U{static[y]="PgVector";dimensions=this.config.dimensions;getSQLType(){return`vector(${this.dimensions})`}mapToDriverValue(o){return JSON.stringify(o)}mapFromDriverValue(o){return o.slice(1,-1).split(",").map((n)=>Number.parseFloat(n))}}function y$(){return{bigint:Dk,bigserial:Lk,boolean:XS,char:bk,cidr:xk,customType:qk,date:Pk,doublePrecision:ek,inet:ak,integer:_f,interval:SA,json:TA,jsonb:FA,line:yA,macaddr:WA,macaddr8:KA,numeric:YA,point:mA,geometry:CA,real:jA,serial:bA,smallint:xA,smallserial:qA,text:PA,time:lA,timestamp:mn,uuid:$n,varchar:io,bit:t$,halfvec:T$,sparsevec:k$,vector:J$}}function ry(o,n,t,S,f=o){const T=new Qn(o,S,f),M=typeof n==="function"?n(y$()):n,F=Object.fromEntries(Object.entries(M).map(([$,O])=>{const w=O;w.setName($);const G=w.build(T);return T[PT].push(...w.buildForeignKeys(G,T)),[$,G]})),k=Object.fromEntries(Object.entries(M).map(([$,O])=>{const w=O;w.setName($);const G=w.buildExtraConfigColumn(T);return[$,G]})),A=Object.assign(T,F);if(A[j.Symbol.Columns]=F,A[j.Symbol.ExtraConfigColumns]=k,t)A[Qn.Symbol.ExtraConfigBuilder]=t;return A}var PT=Symbol.for("drizzle:PgInlineForeignKeys");class Qn extends j{static[y]="PgTable";static Symbol=Object.assign({},j.Symbol,{InlineForeignKeys:PT});[PT]=[];[j.Symbol.ExtraConfigBuilder]=void 0}var ot=(o,n,t)=>{return ry(o,n,t,void 0)};function R$(...o){if(o[0].columns)return new YS(o[0].columns,o[0].name);return new YS(o)}class YS{static[y]="PgPrimaryKeyBuilder";columns;name;constructor(o,n){this.columns=o,this.name=n}build(o){return new O$(o,this.columns,this.name)}}class O${constructor(o,n,t){this.table=o,this.columns=n,this.name=t}static[y]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[Qn.Symbol.Name]}_${this.columns.map((o)=>o.name).join("_")}_pk`}}function _$(){return{and:KS,between:Jk,eq:Ct,exists:Ak,gt:nk,gte:tk,ilike:Wk,inArray:Tk,isNull:Fk,isNotNull:kk,like:Rk,lt:Sk,lte:fk,ne:aF,not:ok,notBetween:yk,notExists:$k,notLike:Ok,notIlike:_k,notInArray:Mk,or:sF,sql:R}}function w$(){return{sql:R,asc:wk,desc:Kk}}function K$(o,n){if(Object.keys(o).length===1&&"default"in o&&!X(o.default,j))o=o.default;const t={},S={},f={};for(let[T,M]of Object.entries(o))if(X(M,j)){const F=$t(M),k=S[F];t[F]=T,f[T]={tsName:T,dbName:M[j.Symbol.Name],schema:M[j.Symbol.Schema],columns:M[j.Symbol.Columns],relations:k?.relations??{},primaryKey:k?.primaryKey??[]};for(let $ of Object.values(M[j.Symbol.Columns]))if($.primary)f[T].primaryKey.push($);const A=M[j.Symbol.ExtraConfigBuilder]?.(M[j.Symbol.ExtraConfigColumns]);if(A){for(let $ of Object.values(A))if(X($,YS))f[T].primaryKey.push(...$.columns)}}else if(X(M,W$)){const F=$t(M.table),k=t[F],A=M.config(n(M.table));let $;for(let[O,w]of Object.entries(A))if(k){const G=f[k];if(G.relations[O]=w,$)G.primaryKey.push(...$)}else{if(!(F in S))S[F]={relations:{},primaryKey:$};S[F].relations[O]=w}}return{tables:f,tableNamesMap:t}}function Cy(o){return function n(t,S){return new nt(o,t,S,S?.fields.reduce((f,T)=>f&&T.notNull,!0)??!1)}}function Ly(o){return function n(t,S){return new ES(o,t,S)}}function X$(o,n,t){if(X(t,nt)&&t.config)return{fields:t.config.fields,references:t.config.references};const S=n[$t(t.referencedTable)];if(!S)throw new Error(`Table "${t.referencedTable[j.Symbol.Name]}" not found in schema`);const f=o[S];if(!f)throw new Error(`Table "${S}" not found in schema`);const T=t.sourceTable,M=n[$t(T)];if(!M)throw new Error(`Table "${T[j.Symbol.Name]}" not found in schema`);const F=[];for(let k of Object.values(f.relations))if(t.relationName&&t!==k&&k.relationName===t.relationName||!t.relationName&&k.referencedTable===t.sourceTable)F.push(k);if(F.length>1)throw t.relationName?new Error(`There are multiple relations with name "${t.relationName}" in table "${S}"`):new Error(`There are multiple relations between "${S}" and "${t.sourceTable[j.Symbol.Name]}". Please specify relation name`);if(F[0]&&X(F[0],nt)&&F[0].config)return{fields:F[0].config.references,references:F[0].config.fields};throw new Error(`There is not enough information to infer relation "${M}.${t.fieldName}"`)}function Y$(o){return{one:Cy(o),many:Ly(o)}}function Hf(o,n,t,S,f=(T)=>T){const T={};for(let[M,F]of S.entries())if(F.isJson){const k=n.relations[F.tsKey],A=t[M],$=typeof A==="string"?JSON.parse(A):A;T[F.tsKey]=X(k,nt)?$&&Hf(o,o[F.relationTableTsKey],$,F.selection,f):$.map((O)=>Hf(o,o[F.relationTableTsKey],O,F.selection,f))}else{const k=f(t[M]),A=F.field;let $;if(X(A,Ko))$=A;else if(X(A,b))$=A.decoder;else $=A.sql.decoder;T[F.tsKey]=k===null?null:$.mapFromDriverValue(k)}return T}class gT{constructor(o,n,t){this.sourceTable=o,this.referencedTable=n,this.relationName=t,this.referencedTableName=n[j.Symbol.Name]}static[y]="Relation";referencedTableName;fieldName}class W${constructor(o,n){this.table=o,this.config=n}static[y]="Relations"}class nt extends gT{constructor(o,n,t,S){super(o,n,t?.relationName);this.config=t,this.isNullable=S}static[y]="One";withFieldName(o){const n=new nt(this.sourceTable,this.referencedTable,this.config,this.isNullable);return n.fieldName=o,n}}class ES extends gT{constructor(o,n,t){super(o,n,t?.relationName);this.config=t}static[y]="Many";withFieldName(o){const n=new ES(this.sourceTable,this.referencedTable,this.config);return n.fieldName=o,n}}import Q0 from"path";import tR from"os";import SR from"fs";function Iy(o){if(mf.has(o))return mf.get(o);const n=Error.stackTraceLimit;return Error.stackTraceLimit=4,mf.set(o,new Error),Error.stackTraceLimit=n,mf.get(o)}var mf=new Map,lT=new Map,eT=Symbol("OriginError"),Lt={};class wn extends Promise{constructor(o,n,t,S,f={}){let T,M;super((F,k)=>{T=F,M=k});this.tagged=Array.isArray(o.raw),this.strings=o,this.args=n,this.handler=t,this.canceller=S,this.options=f,this.state=null,this.statement=null,this.resolve=(F)=>(this.active=!1,T(F)),this.reject=(F)=>(this.active=!1,M(F)),this.active=!1,this.cancelled=null,this.executed=!1,this.signature="",this[eT]=this.handler.debug?new Error:this.tagged&&Iy(this.strings)}get origin(){return(this.handler.debug?this[eT].stack:this.tagged&&lT.has(this.strings)?lT.get(this.strings):lT.set(this.strings,this[eT].stack).get(this.strings))||""}static get[Symbol.species](){return Promise}cancel(){return this.canceller&&(this.canceller(this),this.canceller=null)}simple(){return this.options.simple=!0,this.options.prepare=!1,this}async readable(){return this.simple(),this.streaming=!0,this}async writable(){return this.simple(),this.streaming=!0,this}cursor(o=1,n){if(this.options.simple=!1,typeof o==="function")n=o,o=1;if(this.cursorRows=o,typeof n==="function")return this.cursorFn=n,this;let t;return{[Symbol.asyncIterator]:()=>({next:()=>{if(this.executed&&!this.active)return{done:!0};t&&t();const S=new Promise((f,T)=>{this.cursorFn=(M)=>{return f({value:M,done:!1}),new Promise((F)=>t=F)},this.resolve=()=>(this.active=!1,f({done:!0})),this.reject=(M)=>(this.active=!1,T(M))});return this.execute(),S},return(){return t&&t(Lt),{done:!0}}})}}describe(){return this.options.simple=!1,this.onlyDescribe=this.options.prepare=!0,this}stream(){throw new Error(".stream has been renamed to .forEach")}forEach(o){return this.forEachFn=o,this.handle(),this}raw(){return this.isRaw=!0,this}values(){return this.isRaw="values",this}async handle(){!this.executed&&(this.executed=!0)&&await 1&&this.handler(this)}execute(){return this.handle(),this}then(){return this.handle(),super.then.apply(this,arguments)}catch(){return this.handle(),super.catch.apply(this,arguments)}finally(){return this.handle(),super.finally.apply(this,arguments)}}function E$(o,n,t){const{host:S,port:f}=t||n,T=Object.assign(new Error("write "+o+" "+(n.path||S+":"+f)),{code:o,errno:o,address:n.path||S},n.path?{}:{port:f});return Error.captureStackTrace(T,E$),T}function G$(o){const n=new It(o);return Error.captureStackTrace(n,G$),n}function z$(o,n){const t=Object.assign(new Error(o+": "+n),{code:o});return Error.captureStackTrace(t,z$),t}function H$(o){const n=Object.assign(new Error(o+" (B) is not supported"),{code:"MESSAGE_NOT_SUPPORTED",name:o});return Error.captureStackTrace(n,H$),n}class It extends Error{constructor(o){super(o.message);this.name=this.constructor.name,Object.assign(this,o)}}var Lo={connection:E$,postgres:G$,generic:z$,notSupported:H$};function rf(o,n,t,S){let f=o instanceof cn?o.value:o;if(f===void 0){if(o instanceof cn?o.value=S.transform.undefined:f=o=S.transform.undefined,f===void 0)throw Lo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return"$"+t.push(o instanceof cn?(n.push(o.value),o.array?o.array[o.type||Df(o.value)]||o.type||U$(o.value):o.type):(n.push(o),Df(o)))}function sT(o,n,t,S,f,T){for(let M=1;M<o.strings.length;M++)n+=oM(n,t,S,f,T)+o.strings[M],t=o.args[M];return n}function oM(o,n,t,S,f){return n instanceof Vf?n.build(o,t,S,f):n instanceof wn?aT(n,t,S,f):n instanceof mS?n.value:n&&n[0]instanceof wn?n.reduce((T,M)=>T+" "+aT(M,t,S,f),""):rf(n,t,S,f)}function aT(o,n,t,S){return o.fragment=!0,sT(o,o.strings[0],o.args[0],n,t,S)}function D$(o,n,t,S,f){return o.map((T)=>"("+S.map((M)=>oM("values",T[M],n,t,f)).join(",")+")").join(",")}function m$(o,n,t,S,f){const T=Array.isArray(o[0]),M=n.length?n.flat():Object.keys(T?o[0]:o);return D$(T?o:[o],t,S,M,f)}function Qf(o,n,t,S,f){if(typeof o==="string"&&(o=[o].concat(n)),Array.isArray(o))return nM(o,f);let T;return(n.length?n.flat():Object.keys(o)).map((F)=>{return T=o[F],(T instanceof wn?aT(T,t,S,f):T instanceof mS?T.value:rf(T,t,S,f))+" as "+Cf(f.transform.column.to?f.transform.column.to(F):F)}).join(",")}function dT(){throw Lo.generic("NOT_TAGGED_CALL","Query not called as a tagged template literal")}function U$(o){if(Array.isArray(o))return U$(o[0]);return typeof o==="string"?1009:0}function r$(o){return Object.keys(o).reduce((n,t)=>{if(o[t].from&&[].concat(o[t].from).forEach((S)=>n.parsers[S]=o[t].parse),o[t].serialize)n.serializers[o[t].to]=o[t].serialize,o[t].from&&[].concat(o[t].from).forEach((S)=>n.serializers[S]=o[t].serialize);return n},{parsers:{},serializers:{}})}function nM(o,{transform:{column:n}}){return o.map((t)=>Cf(n.to?n.to(t):t)).join(",")}function xy(o){return o.replace(Ny,"\\\\").replace(hy,'\\"')}function I$(o,n,t,S){const f=[],T=S===1020?";":",";for(;o.i<n.length;o.i++){if(o.char=n[o.i],o.quoted)if(o.char==="\\")o.str+=n[++o.i];else if(o.char==='"')f.push(t?t(o.str):o.str),o.str="",o.quoted=n[o.i+1]==='"',o.last=o.i+2;else o.str+=o.char;else if(o.char==='"')o.quoted=!0;else if(o.char==="{")o.last=++o.i,f.push(I$(o,n,t,S));else if(o.char==="}"){o.quoted=!1,o.last<o.i&&f.push(t?t(n.slice(o.last,o.i)):n.slice(o.last,o.i)),o.last=o.i+1;break}else if(o.char===T&&o.p!=="}"&&o.p!=='"')f.push(t?t(n.slice(o.last,o.i)):n.slice(o.last,o.i)),o.last=o.i+1;o.p=o.char}return o.last<o.i&&f.push(t?t(n.slice(o.last,o.i+1)):n.slice(o.last,o.i+1)),f}function tM(o){return function n(t,S){return typeof t==="object"&&t!==null&&(S.type===114||S.type===3802)?Array.isArray(t)?t.map((f)=>n(f,S)):Object.entries(t).reduce((f,[T,M])=>Object.assign(f,{[o(T)]:n(M,S)}),{}):t}}var jy={string:{to:25,from:null,serialize:(o)=>""+o},number:{to:0,from:[21,23,26,700,701],serialize:(o)=>""+o,parse:(o)=>+o},json:{to:114,from:[114,3802],serialize:(o)=>JSON.stringify(o),parse:(o)=>JSON.parse(o)},boolean:{to:16,from:16,serialize:(o)=>o===!0?"t":"f",parse:(o)=>o==="t"},date:{to:1184,from:[1082,1114,1184],serialize:(o)=>(o instanceof Date?o:new Date(o)).toISOString(),parse:(o)=>new Date(o)},bytea:{to:17,from:17,serialize:(o)=>"\\x"+Buffer.from(o).toString("hex"),parse:(o)=>Buffer.from(o.slice(2),"hex")}};class Uf{then(){dT()}catch(){dT()}finally(){dT()}}class mS extends Uf{constructor(o){super();this.value=Cf(o)}}class cn extends Uf{constructor(o,n,t){super();this.value=o,this.type=n,this.array=t}}class Vf extends Uf{constructor(o,n){super();this.first=o,this.rest=n}build(o,n,t,S){const f=By.map(([T,M])=>({fn:M,i:o.search(T)})).sort((T,M)=>T.i-M.i).pop();return f.i===-1?nM(this.first,S):f.fn(this.first,this.rest,n,t,S)}}var Q$=r$(jy),By=Object.entries({values:m$,in:(...o)=>{const n=m$(...o);return n==="()"?"(null)":n},select:Qf,as:Qf,returning:Qf,"\\(":Qf,update(o,n,t,S,f){return(n.length?n.flat():Object.keys(o)).map((T)=>Cf(f.transform.column.to?f.transform.column.to(T):T)+"="+oM("values",o[T],t,S,f))},insert(o,n,t,S,f){const T=n.length?n.flat():Object.keys(Array.isArray(o)?o[0]:o);return"("+nM(T,f)+")values"+D$(Array.isArray(o)?o:[o],t,S,T,f)}}).map(([o,n])=>[new RegExp("((?:^|[\\s(])"+o+"(?:$|[\\s(]))(?![\\s\\S]*\\1)","i"),n]),cy=Q$.serializers,by=Q$.parsers;var V$=function(o){const n=r$(o||{});return{serializers:Object.assign({},cy,n.serializers),parsers:Object.assign({},by,n.parsers)}},Cf=function o(n){return'"'+n.replace(/"/g,'""').replace(/\./g,'"."')+'"'},Df=function o(n){return n instanceof cn?n.type:n instanceof Date?1184:n instanceof Uint8Array?17:n===!0||n===!1?16:typeof n==="bigint"?20:Array.isArray(n)?o(n[0]):0},Ny=/\\/g,hy=/"/g,C$=function o(n,t,S,f){if(Array.isArray(n)===!1)return n;if(!n.length)return"{}";const T=n[0],M=f===1020?";":",";if(Array.isArray(T)&&!T.type)return"{"+n.map((F)=>o(F,t,S,f)).join(M)+"}";return"{"+n.map((F)=>{if(F===void 0){if(F=S.transform.undefined,F===void 0)throw Lo.generic("UNDEFINED_VALUE","Undefined values are not allowed")}return F===null?"null":'"'+xy(t?t(F.type?F.value:F):""+F)+'"'}).join(M)+"}"},uT={i:0,char:null,str:"",quoted:!1,last:0},L$=function o(n,t,S){return uT.i=uT.last=0,I$(uT,n,t,S)},Jt=(o)=>{let n=o[0];for(let t=1;t<o.length;t++)n+=o[t]==="_"?o[++t].toUpperCase():o[t];return n},yt=(o)=>{let n=o[0].toUpperCase();for(let t=1;t<o.length;t++)n+=o[t]==="_"?o[++t].toUpperCase():o[t];return n},Rt=(o)=>o.replace(/_/g,"-"),GS=(o)=>o.replace(/([A-Z])/g,"_$1").toLowerCase(),zS=(o)=>(o.slice(0,1)+o.slice(1).replace(/([A-Z])/g,"_$1")).toLowerCase(),HS=(o)=>o.replace(/-/g,"_");Jt.column={from:Jt};Jt.value={from:tM(Jt)};GS.column={to:GS};var SM={...Jt};SM.column.to=GS;yt.column={from:yt};yt.value={from:tM(yt)};zS.column={to:zS};var fM={...yt};fM.column.to=zS;Rt.column={from:Rt};Rt.value={from:tM(Rt)};HS.column={to:HS};var TM={...Rt};TM.column.to=HS;import j$ from"net";import py from"tls";import QS from"crypto";import MM from"stream";import{performance as B$}from"perf_hooks";class Ot extends Array{constructor(){super();Object.defineProperties(this,{count:{value:null,writable:!0},state:{value:null,writable:!0},command:{value:null,writable:!0},columns:{value:null,writable:!0},statement:{value:null,writable:!0}})}static get[Symbol.species](){return Array}}function iy(o=[]){let n=o.slice(),t=0;return{get length(){return n.length-t},remove:(S)=>{const f=n.indexOf(S);return f===-1?null:(n.splice(f,1),S)},push:(S)=>(n.push(S),S),shift:()=>{const S=n[t++];if(t===n.length)t=0,n=[];else n[t-1]=void 0;return S}}}var Jn=iy;function Lf(o){if(go.length-yo.i<o){const n=go,t=n.length;go=Buffer.allocUnsafe(t+(t>>1)+o),n.copy(go)}}function qy(){return yo.i=0,yo}var go=Buffer.allocUnsafe(256),vy="BCcDdEFfHPpQSX".split("").reduce((o,n)=>{const t=n.charCodeAt(0);return o[n]=()=>{return go[0]=t,yo.i=5,yo},o},{}),yo=Object.assign(qy,vy,{N:String.fromCharCode(0),i:0,inc(o){return yo.i+=o,yo},str(o){const n=Buffer.byteLength(o);return Lf(n),yo.i+=go.write(o,yo.i,n,"utf8"),yo},i16(o){return Lf(2),go.writeUInt16BE(o,yo.i),yo.i+=2,yo},i32(o,n){if(n||n===0)return go.writeUInt32BE(o,n),yo;return Lf(4),go.writeUInt32BE(o,yo.i),yo.i+=4,yo},z(o){return Lf(o),go.fill(0,yo.i,yo.i+o),yo.i+=o,yo},raw(o){return go=Buffer.concat([go.subarray(0,yo.i),o]),yo.i=go.length,yo},end(o=1){go.writeUInt32BE(yo.i-o,o);const n=go.subarray(0,yo.i);return yo.i=0,go=Buffer.allocUnsafe(256),n}}),p=yo;function N$(o,n={},{onopen:t=jt,onend:S=jt,onclose:f=jt}={}){const{ssl:T,max:M,user:F,host:k,port:A,database:$,parsers:O,transform:w,onnotice:G,onnotify:r,onparameter:H,max_pipeline:D,keep_alive:I,backoff:v,target_session_attrs:N}=o,P=Jn(),Y=Zy++,K={pid:null,secret:null},Q=kM(df,o.idle_timeout),i=kM(df,o.max_lifetime),g=kM(XJ,o.connect_timeout);let _=null,h,C=new Ot,a=Buffer.alloc(0),So=o.fetch_types,to={},Wo={},Mn=Math.random().toString(36).slice(2),E=1,x=0,To=0,Jo=0,Io=0,fo=0,_o=0,ro=0,Ho=null,Xo=null,vo=!1,wo=null,Xn=null,qo=null,gn=null,jo=null,Yo=null,Yn=null,Ln=null,V=null,st=null;const po={queue:n.closed,idleTimer:Q,connect(J){qo=J||!0,iM()},terminate:nS,execute:oS,cancel:WJ,end:df,count:0,id:Y};return n.closed&&n.closed.push(po),po;async function OJ(){let J;try{J=o.socket?await Promise.resolve(o.socket(o)):new j$.Socket}catch(W){Gt(W);return}return J.on("error",Gt),J.on("close",vM),J.on("drain",hM),J}async function WJ({pid:J,secret:W},Z,$o){try{h=p().i32(16).i32(80877102).i32(J).i32(W).end(16),await xM(),_.once("error",$o),_.once("close",Z)}catch(Do){$o(Do)}}function oS(J){if(vo)return pS(J,Lo.connection("CONNECTION_DESTROYED",o));if(J.cancelled)return;try{return J.state=K,V?P.push(J):(V=J,V.active=!0),KJ(J),No(_J(J))&&!J.describeFirst&&!J.cursorFn&&P.length<D&&(!J.options.onexecute||J.options.onexecute(po))}catch(W){return P.length===0&&No(tt),In(W),!0}}function _J(J){if(J.parameters.length>=65534)throw Lo.generic("MAX_PARAMETERS_EXCEEDED","Max number of parameters (65534) exceeded");return J.options.simple?p().Q().str(J.statement.string+p.N).end():J.describeFirst?Buffer.concat([cM(J),c$]):J.prepare?J.prepared?qS(J):Buffer.concat([cM(J),qS(J)]):wJ(J)}function cM(J){return Buffer.concat([pM(J.statement.string,J.parameters,J.statement.types,J.statement.name),Sy("S",J.statement.name)])}function qS(J){return Buffer.concat([ty(J.parameters,J.statement.types,J.statement.name,J.cursorName),J.cursorFn?ZM("",J.cursorRows):gy])}function wJ(J){return Buffer.concat([pM(J.statement.string,J.parameters,J.statement.types),ly,qS(J)])}function KJ(J){const W=[],Z=[],$o=sT(J,J.strings[0],J.args[0],W,Z,o);!J.tagged&&J.args.forEach((Do)=>rf(Do,W,Z,o)),J.prepare=o.prepare&&("prepare"in J.options?J.options.prepare:!0),J.string=$o,J.signature=J.prepare&&Z+$o,J.onlyDescribe&&delete Wo[J.signature],J.parameters=J.parameters||W,J.prepared=J.prepare&&J.signature in Wo,J.describeFirst=J.onlyDescribe||W.length&&!J.prepared,J.statement=J.prepared?Wo[J.signature]:{string:$o,types:Z,name:J.prepare?Mn+E++:""},typeof o.debug==="function"&&o.debug(Y,$o,W,Z)}function No(J,W){if(Yo=Yo?Buffer.concat([Yo,J]):Buffer.from(J),W||Yo.length>=1024)return bM(W);return Xo===null&&(Xo=setImmediate(bM)),!0}function bM(J){const W=_.write(Yo,J);return Xo!==null&&clearImmediate(Xo),Yo=Xo=null,W}function XJ(){In(Lo.connection("CONNECT_TIMEOUT",o,_)),_.destroy()}async function NM(){if(No(Py),!await new Promise((W)=>_.once("data",(Z)=>W(Z[0]===83)))&&T==="prefer")return Et();_.removeAllListeners(),_=py.connect({socket:_,servername:j$.isIP(_.host)?void 0:_.host,...T==="require"||T==="allow"||T==="prefer"?{rejectUnauthorized:!1}:T==="verify-full"?{}:typeof T==="object"?T:{}}),_.on("secureConnect",Et),_.on("error",Gt),_.on("close",vM),_.on("drain",hM)}function hM(){!V&&t(po)}function ef(J){if(wo){if(wo.push(J),To-=J.length,To>=0)return}a=wo?Buffer.concat(wo,fo-To):a.length===0?J:Buffer.concat([a,J],a.length+J.length);while(a.length>4){if(fo=a.readUInt32BE(1),fo>=a.length){To=fo-a.length,wo=[a];break}try{YJ(a.subarray(0,fo+1))}catch(W){V&&(V.cursorFn||V.describeFirst)&&No(tt),In(W)}a=a.subarray(fo+1),To=0,wo=null}}async function xM(){if(vo=!1,to={},_||(_=await OJ()),!_)return;if(g.start(),o.socket)return T?NM():Et();if(_.on("connect",T?NM:Et),o.path)return _.connect(o.path);_.ssl=T,_.connect(A[Jo],k[Jo]),_.host=k[Jo],_.port=A[Jo],Jo=(Jo+1)%A.length}function iM(){setTimeout(xM,x?x+_o-B$.now():0)}function Et(){try{Wo={},So=o.fetch_types,Mn=Math.random().toString(36).slice(2),E=1,i.start(),_.on("data",ef),I&&_.setKeepAlive&&_.setKeepAlive(!0,1000*I);const J=Ty();No(J)}catch(J){Gt(J)}}function Gt(J){if(po.queue===n.connecting&&o.host[Io+1])return;In(J);while(P.length)pS(P.shift(),J)}function In(J){jo&&(jo.destroy(J),jo=null),V&&pS(V,J),qo&&(pS(qo,J),qo=null)}function pS(J,W){Object.defineProperties(W,{stack:{value:W.stack+J.origin.replace(/.*\n/,"\n"),enumerable:o.debug},query:{value:J.string,enumerable:o.debug},parameters:{value:J.parameters,enumerable:o.debug},args:{value:J.args,enumerable:o.debug},types:{value:J.statement&&J.statement.types,enumerable:o.debug}}),J.reject(W)}function df(){return gn||(!po.reserved&&S(po),!po.reserved&&!qo&&!V&&P.length===0?(nS(),new Promise((J)=>_&&_.readyState!=="closed"?_.once("close",J):J())):gn=new Promise((J)=>Yn=J))}function nS(){if(vo=!0,jo||V||qo||P.length)Gt(Lo.connection("CONNECTION_DESTROYED",o));if(clearImmediate(Xo),_)_.removeListener("data",ef),_.removeListener("connect",Et),_.readyState==="open"&&_.end(p().X().end());Yn&&(Yn(),gn=Yn=null)}async function vM(J){if(a=Buffer.alloc(0),To=0,wo=null,clearImmediate(Xo),_.removeListener("data",ef),_.removeListener("connect",Et),Q.cancel(),i.cancel(),g.cancel(),_.removeAllListeners(),_=null,qo)return iM();!J&&(V||P.length)&&Gt(Lo.connection("CONNECTION_CLOSED",o,_)),x=B$.now(),J&&o.shared.retries++,_o=(typeof v==="function"?v(o.shared.retries):v)*1000,f(po,Lo.connection("CONNECTION_CLOSED",o,_))}function YJ(J,W=J[0]){(W===68?EJ:W===100?lJ:W===65?vJ:W===83?GJ:W===90?zJ:W===67?HJ:W===50?qM:W===49?mJ:W===116?QJ:W===84?DJ:W===82?UJ:W===110?jJ:W===75?BJ:W===69?xJ:W===115?qJ:W===51?pJ:W===71?ZJ:W===78?dJ:W===72?PJ:W===99?eJ:W===73?uJ:W===86?aJ:W===118?sJ:W===87?gJ:oy)(J)}function EJ(J){let W=7,Z,$o,Do;const Zo=V.isRaw?new Array(V.statement.columns.length):{};for(let eo=0;eo<V.statement.columns.length;eo++)$o=V.statement.columns[eo],Z=J.readInt32BE(W),W+=4,Do=Z===-1?null:V.isRaw===!0?J.subarray(W,W+=Z):$o.parser===void 0?J.toString("utf8",W,W+=Z):$o.parser.array===!0?$o.parser(J.toString("utf8",W+1,W+=Z)):$o.parser(J.toString("utf8",W,W+=Z)),V.isRaw?Zo[eo]=V.isRaw===!0?Do:w.value.from?w.value.from(Do,$o):Do:Zo[$o.name]=w.value.from?w.value.from(Do,$o):Do;V.forEachFn?V.forEachFn(w.row.from?w.row.from(Zo):Zo,C):C[ro++]=w.row.from?w.row.from(Zo):Zo}function GJ(J){const[W,Z]=J.toString("utf8",5,J.length-1).split(p.N);if(to[W]=Z,o.parameters[W]!==Z)o.parameters[W]=Z,H&&H(W,Z)}function zJ(J){if(V&&V.options.simple&&V.resolve(Xn||C),V=Xn=null,C=new Ot,g.cancel(),qo){if(N){if(!to.in_hot_standby||!to.default_transaction_read_only)return hJ();else if(NJ(N,to))return nS()}if(So)return qo===!0&&(qo=null),cJ();qo!==!0&&oS(qo),o.shared.retries=Io=0,qo=null;return}while(P.length&&(V=P.shift())&&(V.active=!0,V.cancelled))N$(o).cancel(V.state,V.cancelled.resolve,V.cancelled.reject);if(V)return;po.reserved?!po.reserved.release&&J[5]===73?gn?nS():(po.reserved=null,t(po)):po.reserved():gn?nS():t(po)}function HJ(J){ro=0;for(let W=J.length-1;W>0;W--){if(J[W]===32&&J[W+1]<58&&C.count===null)C.count=+J.toString("utf8",W+1,J.length-1);if(J[W-1]>=65){C.command=J.toString("utf8",5,W),C.state=K;break}}if(st&&(st(),st=null),C.command==="BEGIN"&&M!==1&&!po.reserved)return In(Lo.generic("UNSAFE_TRANSACTION","Only use sql.begin, sql.reserved or max: 1"));if(V.options.simple)return qM();if(V.cursorFn)C.count&&V.cursorFn(C),No(tt);V.resolve(C)}function mJ(){V.parsing=!1}function qM(){!C.statement&&(C.statement=V.statement),C.columns=V.statement.columns}function QJ(J){const W=J.readUInt16BE(5);for(let Z=0;Z<W;++Z)!V.statement.types[Z]&&(V.statement.types[Z]=J.readUInt32BE(7+Z*4));V.prepare&&(Wo[V.signature]=V.statement),V.describeFirst&&!V.onlyDescribe&&(No(qS(V)),V.describeFirst=!1)}function DJ(J){if(C.command)Xn=Xn||[C],Xn.push(C=new Ot),C.count=null,V.statement.columns=null;const W=J.readUInt16BE(5);let Z=7,$o;V.statement.columns=Array(W);for(let Do=0;Do<W;++Do){$o=Z;while(J[Z++]!==0);const Zo=J.readUInt32BE(Z),eo=J.readUInt16BE(Z+4),ln=J.readUInt32BE(Z+6);V.statement.columns[Do]={name:w.column.from?w.column.from(J.toString("utf8",$o,Z-1)):J.toString("utf8",$o,Z-1),parser:O[ln],table:Zo,number:eo,type:ln},Z+=18}if(C.statement=V.statement,V.onlyDescribe)return V.resolve(V.statement),No(tt)}async function UJ(J,W=J.readUInt32BE(5)){(W===3?VJ:W===5?rJ:W===10?CJ:W===11?LJ:W===12?IJ:W!==0?ny:jt)(J,W)}async function VJ(){const J=await uf();No(p().p().str(J).z(1).end())}async function rJ(J){const W="md5"+await b$(Buffer.concat([Buffer.from(await b$(await uf()+F)),J.subarray(9)]));No(p().p().str(W).z(1).end())}async function CJ(){Ln=(await QS.randomBytes(18)).toString("base64"),p().p().str("SCRAM-SHA-256"+p.N);const J=p.i;No(p.inc(4).str("n,,n=*,r="+Ln).i32(p.i-J-4,J).end())}async function LJ(J){const W=J.toString("utf8",9).split(",").reduce((eo,ln)=>(eo[ln[0]]=ln.slice(2),eo),{}),Z=await QS.pbkdf2Sync(await uf(),Buffer.from(W.s,"base64"),parseInt(W.i),32,"sha256"),$o=await If(Z,"Client Key"),Do="n=*,r="+Ln+",r="+W.r+",s="+W.s+",i="+W.i+",c=biws,r="+W.r;Ho=(await If(await If(Z,"Server Key"),Do)).toString("base64");const Zo="c=biws,r="+W.r+",p="+ay($o,Buffer.from(await If(await uy($o),Do))).toString("base64");No(p().p().str(Zo).end())}function IJ(J){if(J.toString("utf8",9).split(p.N,1)[0].slice(2)===Ho)return;In(Lo.generic("SASL_SIGNATURE_MISMATCH","The server did not return the correct signature")),_.destroy()}function uf(){return Promise.resolve(typeof o.pass==="function"?o.pass():o.pass)}function jJ(){if(C.statement=V.statement,C.statement.columns=[],V.onlyDescribe)return V.resolve(V.statement),No(tt)}function BJ(J){K.pid=J.readUInt32BE(5),K.secret=J.readUInt32BE(9)}async function cJ(){So=!1,(await new wn([`
4
+ select b.oid, b.typarray
5
+ from pg_catalog.pg_type a
6
+ left join pg_catalog.pg_type b on b.oid = a.typelem
7
+ where a.typcategory = 'A'
8
+ group by b.oid, b.typarray
9
+ order by b.oid
10
+ `],[],oS)).forEach(({oid:W,typarray:Z})=>bJ(W,Z))}function bJ(J,W){if(!!o.parsers[W]&&!!o.serializers[W])return;const Z=o.parsers[J];o.shared.typeArrayMap[J]=W,o.parsers[W]=($o)=>L$($o,Z,W),o.parsers[W].array=!0,o.serializers[W]=($o)=>C$($o,o.serializers[J],o,W)}function NJ(J,W){return J==="read-write"&&W.default_transaction_read_only==="on"||J==="read-only"&&W.default_transaction_read_only==="off"||J==="primary"&&W.in_hot_standby==="on"||J==="standby"&&W.in_hot_standby==="off"||J==="prefer-standby"&&W.in_hot_standby==="off"&&o.host[Io]}function hJ(){const J=new wn([`
11
+ show transaction_read_only;
12
+ select pg_catalog.pg_is_in_recovery()
13
+ `],[],oS,null,{simple:!0});J.resolve=([[W],[Z]])=>{to.default_transaction_read_only=W.transaction_read_only,to.in_hot_standby=Z.pg_is_in_recovery?"on":"off"},J.execute()}function xJ(J){V&&(V.cursorFn||V.describeFirst)&&No(tt);const W=Lo.postgres(FM(J));V&&V.retried?In(V.retried):V&&V.prepared&&ey.has(W.routine)?iJ(V,W):In(W)}function iJ(J,W){delete Wo[J.signature],J.retried=W,oS(J)}function vJ(J){if(!r)return;let W=9;while(J[W++]!==0);r(J.toString("utf8",9,W-1),J.toString("utf8",W,J.length-1))}async function qJ(){try{const J=await Promise.resolve(V.cursorFn(C));ro=0,J===Lt?No(fy(V.portal)):(C=new Ot,No(ZM("",V.cursorRows)))}catch(J){No(tt),V.reject(J)}}function pJ(){C.count&&V.cursorFn(C),V.resolve(C)}function ZJ(){jo=new MM.Writable({autoDestroy:!0,write(J,W,Z){_.write(p().d().raw(J).end(),Z)},destroy(J,W){W(J),_.write(p().f().str(J+p.N).end()),jo=null},final(J){_.write(p().c().end()),st=J}}),V.resolve(jo)}function PJ(){jo=new MM.Readable({read(){_.resume()}}),V.resolve(jo)}function gJ(){jo=new MM.Duplex({autoDestroy:!0,read(){_.resume()},write(J,W,Z){_.write(p().d().raw(J).end(),Z)},destroy(J,W){W(J),_.write(p().f().str(J+p.N).end()),jo=null},final(J){_.write(p().c().end()),st=J}}),V.resolve(jo)}function lJ(J){jo&&(jo.push(J.subarray(5))||_.pause())}function eJ(){jo&&jo.push(null),jo=null}function dJ(J){G?G(FM(J)):console.log(FM(J))}function uJ(){}function aJ(){In(Lo.notSupported("FunctionCallResponse"))}function sJ(){In(Lo.notSupported("NegotiateProtocolVersion"))}function oy(J){console.error("Postgres.js : Unknown Message:",J[0])}function ny(J,W){console.error("Postgres.js : Unknown Auth:",W)}function ty(J,W,Z="",$o=""){let Do,Zo;return p().B().str($o+p.N).str(Z+p.N).i16(0).i16(J.length),J.forEach((eo,ln)=>{if(eo===null)return p.i32(4294967295);Zo=W[ln],J[ln]=eo=Zo in o.serializers?o.serializers[Zo](eo):""+eo,Do=p.i,p.inc(4).str(eo).i32(p.i-Do-4,Do)}),p.i16(0),p.end()}function pM(J,W,Z,$o=""){return p().P().str($o+p.N).str(J+p.N).i16(W.length),W.forEach((Do,Zo)=>p.i32(Z[Zo]||0)),p.end()}function Sy(J,W=""){return p().D().str(J).str(W+p.N).end()}function ZM(J="",W=0){return Buffer.concat([p().E().str(J+p.N).i32(W).end(),c$])}function fy(J=""){return Buffer.concat([p().C().str("P").str(J+p.N).end(),p().S().end()])}function Ty(){return h||p().inc(4).i16(3).z(2).str(Object.entries(Object.assign({user:F,database:$,client_encoding:"UTF8"},o.connection)).filter(([,J])=>J).map(([J,W])=>J+p.N+W).join(p.N)).z(2).end(0)}}function FM(o){const n={};let t=5;for(let S=5;S<o.length-1;S++)if(o[S]===0)n[dy[o[t]]]=o.toString("utf8",t+1,S),t=S+1;return n}function b$(o){return QS.createHash("md5").update(o).digest("hex")}function If(o,n){return QS.createHmac("sha256",o).update(n).digest()}function uy(o){return QS.createHash("sha256").update(o).digest()}function ay(o,n){const t=Math.max(o.length,n.length),S=Buffer.allocUnsafe(t);for(let f=0;f<t;f++)S[f]=o[f]^n[f];return S}function kM(o,n){if(n=typeof n==="function"?n():n,!n)return{cancel:jt,start:jt};let t;return{cancel(){t&&(clearTimeout(t),t=null)},start(){t&&clearTimeout(t),t=setTimeout(S,n*1000,arguments)}};function S(f){o.apply(null,f),t=null}}var AM=N$,Zy=1,tt=p().S().end(),c$=p().H().end(),Py=p().i32(8).i32(80877103).end(8),gy=Buffer.concat([p().E().str(p.N).i32(0).end(),tt]),ly=p().D().str("S").str(p.N).end(),jt=()=>{},ey=new Set(["FetchPreparedStatement","RevalidateCachedQuery","transformAssignedExpr"]),dy={83:"severity_local",86:"severity",67:"code",77:"message",68:"detail",72:"hint",80:"position",112:"internal_position",113:"internal_query",87:"where",115:"schema_name",116:"table_name",99:"column_name",100:"data type_name",110:"constraint_name",70:"file",76:"line",82:"routine"};function sy(o){return new Date(Date.UTC(2000,0,1)+Number(o/BigInt(1000)))}function oR(o,n,t,S,f){const T=(M,[F,k])=>(M[F.charCodeAt(0)]=k,M);Object.entries({R:(M)=>{let F=1;const k=n[M.readUInt32BE(F)]={schema:M.toString("utf8",F+=4,F=M.indexOf(0,F))||"pg_catalog",table:M.toString("utf8",F+1,F=M.indexOf(0,F+1)),columns:Array(M.readUInt16BE(F+=2)),keys:[]};F+=2;let A=0,$;while(F<M.length)$=k.columns[A++]={key:M[F++],name:f.column.from?f.column.from(M.toString("utf8",F,F=M.indexOf(0,F))):M.toString("utf8",F,F=M.indexOf(0,F)),type:M.readUInt32BE(F+=1),parser:t[M.readUInt32BE(F)],atttypmod:M.readUInt32BE(F+=4)},$.key&&k.keys.push($),F+=4},Y:()=>{},O:()=>{},B:(M)=>{n.date=sy(M.readBigInt64BE(9)),n.lsn=M.subarray(1,9)},I:(M)=>{let F=1;const k=n[M.readUInt32BE(F)],{row:A}=jf(M,k.columns,F+=7,f);S(A,{command:"insert",relation:k})},D:(M)=>{let F=1;const k=n[M.readUInt32BE(F)];F+=4;const A=M[F]===75;S(A||M[F]===79?jf(M,k.columns,F+=3,f).row:null,{command:"delete",relation:k,key:A})},U:(M)=>{let F=1;const k=n[M.readUInt32BE(F)];F+=4;const A=M[F]===75,$=A||M[F]===79?jf(M,k.columns,F+=3,f):null;$&&(F=$.i);const{row:O}=jf(M,k.columns,F+3,f);S(O,{command:"update",relation:k,key:A,old:$&&$.row})},T:()=>{},C:()=>{}}).reduce(T,{})[o[0]](o)}function jf(o,n,t,S){let f,T,M;const F=S.raw?new Array(n.length):{};for(let k=0;k<n.length;k++)f=o[t++],T=n[k],M=f===110?null:f===117?void 0:T.parser===void 0?o.toString("utf8",t+4,t+=4+o.readUInt32BE(t)):T.parser.array===!0?T.parser(o.toString("utf8",t+5,t+=4+o.readUInt32BE(t))):T.parser(o.toString("utf8",t+4,t+=4+o.readUInt32BE(t))),S.raw?F[k]=S.raw===!0?M:S.value.from?S.value.from(M,T):M:F[T.name]=S.value.from?S.value.from(M,T):M;return{i:t,row:S.row.from?S.row.from(F):F}}function nR(o){const n=o.match(/^(\*|insert|update|delete)?:?([^.]+?\.?[^=]+)?=?(.+)?/i)||[];if(!n)throw new Error("Malformed subscribe pattern: "+o);const[,t,S,f]=n;return(t||"*")+(S?":"+(S.indexOf(".")===-1?"public."+S:S):"")+(f?"="+f:"")}var h$=()=>{};function $M(o,n){const t=new Map,S="postgresjs_"+Math.random().toString(36).slice(2),f={};let T,M,F=!1;const k=O.sql=o({...n,transform:{column:{},value:{},row:{}},max:1,fetch_types:!1,idle_timeout:null,max_lifetime:null,connection:{...n.connection,replication:"database"},onclose:async function(){if(F)return;M=null,f.pid=f.secret=void 0,w(await G(k,S,n.publications)),t.forEach((H)=>H.forEach(({onsubscribe:D})=>D()))},no_subscribe:!0}),A=k.end,$=k.close;return k.end=async()=>{return F=!0,M&&await new Promise((H)=>(M.once("close",H),M.end())),A()},k.close=async()=>{return M&&await new Promise((H)=>(M.once("close",H),M.end())),$()},O;async function O(H,D,I=h$,v=h$){if(H=nR(H),!T)T=G(k,S,n.publications);const N={fn:D,onsubscribe:I},P=t.has(H)?t.get(H).add(N):t.set(H,new Set([N])).get(H),Y=()=>{P.delete(N),P.size===0&&t.delete(H)};return T.then((K)=>{return w(K),I(),M&&M.on("error",v),{unsubscribe:Y,state:f,sql:k}})}function w(H){M=H.stream,f.pid=H.state.pid,f.secret=H.state.secret}async function G(H,D,I){if(!I)throw new Error("Missing publication names");const v=await H.unsafe(`CREATE_REPLICATION_SLOT ${D} TEMPORARY LOGICAL pgoutput NOEXPORT_SNAPSHOT`),[N]=v,P=await H.unsafe(`START_REPLICATION SLOT ${D} LOGICAL ${N.consistent_point} (proto_version '1', publication_names '${I}')`).writable(),Y={lsn:Buffer.concat(N.consistent_point.split("/").map((_)=>Buffer.from(("00000000"+_).slice(-8),"hex")))};return P.on("data",Q),P.on("error",K),P.on("close",H.close),{stream:P,state:v.state};function K(_){console.error("Unexpected error during logical streaming - reconnecting",_)}function Q(_){if(_[0]===119)oR(_.subarray(25),Y,H.options.parsers,i,n.transform);else if(_[0]===107&&_[17])Y.lsn=_.subarray(1,9),g()}function i(_,h){const C=h.relation.schema+"."+h.relation.table;r("*",_,h),r("*:"+C,_,h),h.relation.keys.length&&r("*:"+C+"="+h.relation.keys.map((a)=>_[a.name]),_,h),r(h.command,_,h),r(h.command+":"+C,_,h),h.relation.keys.length&&r(h.command+":"+C+"="+h.relation.keys.map((a)=>_[a.name]),_,h)}function g(){const _=Buffer.alloc(34);_[0]="r".charCodeAt(0),_.fill(Y.lsn,1),_.writeBigInt64BE(BigInt(Date.now()-Date.UTC(2000,0,1))*BigInt(1000),25),P.write(_)}}function r(H,D,I){t.has(H)&&t.get(H).forEach(({fn:v})=>v(D,I,H))}}import x$ from"stream";function JM(o,n,t=393216){return new Promise(async(S,f)=>{await o.begin(async(T)=>{let M;!n&&([{oid:n}]=await T`select lo_creat(-1) as oid`);const[{fd:F}]=await T`select lo_open(${n}, ${t}) as fd`,k={writable:$,readable:A,close:()=>T`select lo_close(${F})`.then(M),tell:()=>T`select lo_tell64(${F})`,read:(O)=>T`select loread(${F}, ${O}) as data`,write:(O)=>T`select lowrite(${F}, ${O})`,truncate:(O)=>T`select lo_truncate64(${F}, ${O})`,seek:(O,w=0)=>T`select lo_lseek64(${F}, ${O}, ${w})`,size:()=>T`
14
+ select
15
+ lo_lseek64(${F}, location, 0) as position,
16
+ seek.size
17
+ from (
18
+ select
19
+ lo_lseek64($1, 0, 2) as size,
20
+ tell.location
21
+ from (select lo_tell64($1) as location) tell
22
+ ) seek
23
+ `};return S(k),new Promise(async(O)=>M=O);async function A({highWaterMark:O=16384,start:w=0,end:G=1/0}={}){let r=G-w;return w&&await k.seek(w),new x$.Readable({highWaterMark:O,async read(H){const D=H>r?H-r:H;r-=H;const[{data:I}]=await k.read(D);if(this.push(I),I.length<H)this.push(null)}})}async function $({highWaterMark:O=16384,start:w=0}={}){return w&&await k.seek(w),new x$.Writable({highWaterMark:O,write(G,r,H){k.write(G).then(()=>H(),H)}})}}).catch(f)})}function Bf(o,n){const t=fR(o,n),S=t.no_subscribe||$M(Bf,{...t});let f=!1;const T=Jn(),M=Jn(),F=Jn(),k=Jn(),A=Jn(),$=Jn(),O=Jn(),w=Jn(),G={connecting:M,reserved:F,closed:k,ended:A,open:$,busy:O,full:w},r=[...Array(t.max)].map(()=>AM(t,G,{onopen:Wo,onend:to,onclose:Mn})),H=D(i);return Object.assign(H,{get parameters(){return t.parameters},largeObject:JM.bind(null,H),subscribe:S,CLOSE:Lt,END:Lt,PostgresError:It,options:t,reserve:N,listen:I,begin:P,close:C,end:h}),H;function D(E){return E.debug=t.debug,Object.entries(t.types).reduce((fo,[_o,ro])=>{return fo[_o]=(Ho)=>new cn(Ho,ro.to),fo},x),Object.assign(To,{types:x,typed:x,unsafe:Jo,notify:v,array:Q,json:K,file:Io}),To;function x(fo,_o){return new cn(fo,_o)}function To(fo,..._o){return fo&&Array.isArray(fo.raw)?new wn(fo,_o,E,_):typeof fo==="string"&&!_o.length?new mS(t.transform.column.to?t.transform.column.to(fo):fo):new Vf(fo,_o)}function Jo(fo,_o=[],ro={}){return arguments.length===2&&!Array.isArray(_o)&&(ro=_o,_o=[]),new wn([fo],_o,E,_,{prepare:!1,...ro,simple:"simple"in ro?ro.simple:_o.length===0})}function Io(fo,_o=[],ro={}){return arguments.length===2&&!Array.isArray(_o)&&(ro=_o,_o=[]),new wn([],_o,(Xo)=>{SR.readFile(fo,"utf8",(vo,wo)=>{if(vo)return Xo.reject(vo);Xo.strings=[wo],E(Xo)})},_,{...ro,simple:"simple"in ro?ro.simple:_o.length===0})}}async function I(E,x,To){const Jo={fn:x,onlisten:To},Io=I.sql||(I.sql=Bf({...t,max:1,idle_timeout:null,max_lifetime:null,fetch_types:!1,onclose(){Object.entries(I.channels).forEach(([Xo,{listeners:vo}])=>{delete I.channels[Xo],Promise.all(vo.map((wo)=>I(Xo,wo.fn,wo.onlisten).catch(()=>{})))})},onnotify(Xo,vo){Xo in I.channels&&I.channels[Xo].listeners.forEach((wo)=>wo.fn(vo))}})),fo=I.channels||(I.channels={});if(E in fo){fo[E].listeners.push(Jo);const Xo=await fo[E].result;return Jo.onlisten&&Jo.onlisten(),{state:Xo.state,unlisten:Ho}}fo[E]={result:Io`listen ${Io.unsafe('"'+E.replace(/"/g,'""')+'"')}`,listeners:[Jo]};const ro=await fo[E].result;return Jo.onlisten&&Jo.onlisten(),{state:ro.state,unlisten:Ho};async function Ho(){if(E in fo===!1)return;if(fo[E].listeners=fo[E].listeners.filter((Xo)=>Xo!==Jo),fo[E].listeners.length)return;return delete fo[E],Io`unlisten ${Io.unsafe('"'+E.replace(/"/g,'""')+'"')}`}}async function v(E,x){return await H`select pg_notify(${E}, ${""+x})`}async function N(){const E=Jn(),x=$.length?$.shift():await new Promise((Io)=>{T.push({reserve:Io}),k.length&&So(k.shift())});Y(x,F),x.reserved=()=>E.length?x.execute(E.shift()):Y(x,F),x.reserved.release=!0;const To=D(Jo);return To.release=()=>{x.reserved=null,Wo(x)},To;function Jo(Io){x.queue===w?E.push(Io):x.execute(Io)||Y(x,w)}}async function P(E,x){!x&&(x=E,E="");const To=Jn();let Jo=0,Io,fo=null;try{return await H.unsafe("begin "+E.replace(/[^a-z ]/ig,""),[],{onexecute:ro}).execute(),await Promise.race([_o(Io,x),new Promise((Ho,Xo)=>Io.onclose=Xo)])}catch(Ho){throw Ho}async function _o(Ho,Xo,vo){const wo=D(jo);wo.savepoint=gn,wo.prepare=(Yo)=>fo=Yo.replace(/[^a-z0-9$-_. ]/gi);let Xn,qo;vo&&await wo`savepoint ${wo(vo)}`;try{if(qo=await new Promise((Yo,Yn)=>{const Ln=Xo(wo);Promise.resolve(Array.isArray(Ln)?Promise.all(Ln):Ln).then(Yo,Yn)}),Xn)throw Xn}catch(Yo){throw await(vo?wo`rollback to ${wo(vo)}`:wo`rollback`),Yo instanceof It&&Yo.code==="25P02"&&Xn||Yo}if(!vo)fo?await wo`prepare transaction '${wo.unsafe(fo)}'`:await wo`commit`;return qo;function gn(Yo,Yn){if(Yo&&Array.isArray(Yo.raw))return gn((Ln)=>Ln.apply(Ln,arguments));return arguments.length===1&&(Yn=Yo,Yo=null),_o(Ho,Yn,"s"+Jo+++(Yo?"_"+Yo:""))}function jo(Yo){Yo.catch((Yn)=>Xn||(Xn=Yn)),Ho.queue===w?To.push(Yo):Ho.execute(Yo)||Y(Ho,w)}}function ro(Ho){Io=Ho,Y(Ho,F),Ho.reserved=()=>To.length?Ho.execute(To.shift()):Y(Ho,F)}}function Y(E,x){return E.queue.remove(E),x.push(E),E.queue=x,x===$?E.idleTimer.start():E.idleTimer.cancel(),E}function K(E){return new cn(E,3802)}function Q(E,x){if(!Array.isArray(E))return Q(Array.from(arguments));return new cn(E,x||(E.length?Df(E)||25:0),t.shared.typeArrayMap)}function i(E){if(f)return E.reject(Lo.connection("CONNECTION_ENDED",t,t));if($.length)return g($.shift(),E);if(k.length)return So(k.shift(),E);O.length?g(O.shift(),E):T.push(E)}function g(E,x){return E.execute(x)?Y(E,O):Y(E,w)}function _(E){return new Promise((x,To)=>{E.state?E.active?AM(t).cancel(E.state,x,To):E.cancelled={resolve:x,reject:To}:(T.remove(E),E.cancelled=!0,E.reject(Lo.generic("57014","canceling statement due to user request")),x())})}async function h({timeout:E=null}={}){if(f)return f;await 1;let x;return f=Promise.race([new Promise((To)=>E!==null&&(x=setTimeout(a,E*1000,To))),Promise.all(r.map((To)=>To.end()).concat(I.sql?I.sql.end({timeout:0}):[],S.sql?S.sql.end({timeout:0}):[]))]).then(()=>clearTimeout(x))}async function C(){await Promise.all(r.map((E)=>E.end()))}async function a(E){await Promise.all(r.map((x)=>x.terminate()));while(T.length)T.shift().reject(Lo.connection("CONNECTION_DESTROYED",t));E()}function So(E,x){return Y(E,M),E.connect(x),E}function to(E){Y(E,A)}function Wo(E){if(T.length===0)return Y(E,$);let x=Math.ceil(T.length/(M.length+1)),To=!0;while(To&&T.length&&x-- >0){const Jo=T.shift();if(Jo.reserve)return Jo.reserve(E);To=E.execute(Jo)}To?Y(E,O):Y(E,w)}function Mn(E,x){Y(E,k),E.reserved=null,E.onclose&&(E.onclose(x),E.onclose=null),t.onclose&&t.onclose(E.id),T.length&&So(E,T.shift())}}function fR(o,n){if(o&&o.shared)return o;const t=process.env,S=(!o||typeof o==="string"?n:o)||{},{url:f,multihost:T}=AR(o),M=[...f.searchParams].reduce((w,[G,r])=>(w[G]=r,w),{}),F=S.hostname||S.host||T||f.hostname||t.PGHOST||"localhost",k=S.port||f.port||t.PGPORT||5432,A=S.user||S.username||f.username||t.PGUSERNAME||t.PGUSER||$R();S.no_prepare&&(S.prepare=!1),M.sslmode&&(M.ssl=M.sslmode,delete M.sslmode),"timeout"in S&&(console.log("The timeout option is deprecated, use idle_timeout instead"),S.idle_timeout=S.timeout),M.sslrootcert==="system"&&(M.ssl="verify-full");const $=["idle_timeout","connect_timeout","max_lifetime","max_pipeline","backoff","keep_alive"],O={max:10,ssl:!1,idle_timeout:null,connect_timeout:30,max_lifetime:FR,max_pipeline:100,backoff:MR,keep_alive:60,prepare:!0,debug:!1,fetch_types:!0,publications:"alltables",target_session_attrs:null};return{host:Array.isArray(F)?F:F.split(",").map((w)=>w.split(":")[0]),port:Array.isArray(k)?k:F.split(",").map((w)=>parseInt(w.split(":")[1]||k)),path:S.path||F.indexOf("/")>-1&&F+"/.s.PGSQL."+k,database:S.database||S.db||(f.pathname||"").slice(1)||t.PGDATABASE||A,user:A,pass:S.pass||S.password||f.password||t.PGPASSWORD||"",...Object.entries(O).reduce((w,[G,r])=>{const H=G in S?S[G]:(G in M)?M[G]==="disable"||M[G]==="false"?!1:M[G]:t["PG"+G.toUpperCase()]||r;return w[G]=typeof H==="string"&&$.includes(G)?+H:H,w},{}),connection:{application_name:"postgres.js",...S.connection,...Object.entries(M).reduce((w,[G,r])=>((G in O)||(w[G]=r),w),{})},types:S.types||{},target_session_attrs:TR(S,f,t),onnotice:S.onnotice,onnotify:S.onnotify,onclose:S.onclose,onparameter:S.onparameter,socket:S.socket,transform:kR(S.transform||{undefined:void 0}),parameters:{},shared:{retries:0,typeArrayMap:{}},...V$(S.types)}}function TR(o,n,t){const S=o.target_session_attrs||n.searchParams.get("target_session_attrs")||t.PGTARGETSESSIONATTRS;if(!S||["read-write","read-only","primary","standby","prefer-standby"].includes(S))return S;throw new Error("target_session_attrs "+S+" is not supported")}function MR(o){return(0.5+Math.random()/2)*Math.min(3**o/100,20)}function FR(){return 60*(30+Math.random()*30)}function kR(o){return{undefined:o.undefined,column:{from:typeof o.column==="function"?o.column:o.column&&o.column.from,to:o.column&&o.column.to},value:{from:typeof o.value==="function"?o.value:o.value&&o.value.from,to:o.value&&o.value.to},row:{from:typeof o.row==="function"?o.row:o.row&&o.row.from,to:o.row&&o.row.to}}}function AR(o){if(!o||typeof o!=="string")return{url:{searchParams:new Map}};let n=o;n=n.slice(n.indexOf("://")+3).split(/[?/]/)[0],n=decodeURIComponent(n.slice(n.indexOf("@")+1));const t=new URL(o.replace(n,n.split(",")[0]));return{url:{username:decodeURIComponent(t.username),password:decodeURIComponent(t.password),host:t.host,hostname:t.hostname,port:t.port,pathname:t.pathname,searchParams:t.searchParams},multihost:n.indexOf(",")>-1&&n}}function $R(){try{return tR.userInfo().username}catch(o){return process.env.USERNAME||process.env.USER||process.env.LOGNAME}}Object.assign(Bf,{PostgresError:It,toPascal:yt,pascal:fM,toCamel:Jt,camel:SM,toKebab:Rt,kebab:TM,fromPascal:zS,fromCamel:GS,fromKebab:HS,BigInt:{to:20,from:[20],parse:(o)=>BigInt(o),serialize:(o)=>o.toString()}});var Bt=Bf;class cf extends ao{constructor(o,n,t,S){super();this.session=n,this.dialect=t,this.config={table:o,withList:S}}static[y]="PgDelete";config;where(o){return this.config.where=o,this}returning(o=this.config.table[j.Symbol.Columns]){return this.config.returning=_n(o),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)})}prepare(o){return this._prepare(o)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})};$dynamic(){return this}}class bf{constructor(o,n,t,S){this.table=o,this.session=n,this.dialect=t,this.withList=S}static[y]="PgInsertBuilder";values(o){if(o=Array.isArray(o)?o:[o],o.length===0)throw new Error("values() must be called with at least one value");const n=o.map((t)=>{const S={},f=this.table[j.Symbol.Columns];for(let T of Object.keys(t)){const M=t[T];S[T]=X(M,b)?M:new An(M,f[T])}return S});return new i$(this.table,n,this.session,this.dialect,this.withList)}}class i$ extends ao{constructor(o,n,t,S,f){super();this.session=t,this.dialect=S,this.config={table:o,values:n,withList:f}}static[y]="PgInsert";config;returning(o=this.config.table[j.Symbol.Columns]){return this.config.returning=_n(o),this}onConflictDoNothing(o={}){if(o.target===void 0)this.config.onConflict=R`do nothing`;else{let n="";n=Array.isArray(o.target)?o.target.map((S)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(S))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target));const t=o.where?R` where ${o.where}`:void 0;this.config.onConflict=R`(${R.raw(n)})${t} do nothing`}return this}onConflictDoUpdate(o){if(o.where&&(o.targetWhere||o.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');const n=o.where?R` where ${o.where}`:void 0,t=o.targetWhere?R` where ${o.targetWhere}`:void 0,S=o.setWhere?R` where ${o.setWhere}`:void 0,f=this.dialect.buildUpdateSet(this.config.table,Rf(this.config.table,o.set));let T="";return T=Array.isArray(o.target)?o.target.map((M)=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(M))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(o.target)),this.config.onConflict=R`(${R.raw(T)})${t} do update set ${f}${n}${S}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)})}prepare(o){return this._prepare(o)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})};$dynamic(){return this}}function JR(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((t)=>t.toLowerCase()).join("_")}function yR(o){return(o.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((t,S,f)=>{const T=f===0?S.toLowerCase():`${S[0].toUpperCase()}${S.slice(1)}`;return t+T},"")}function RR(o){return o}class yM{static[y]="CasingCache";cache={};cachedTables={};convert;constructor(o){this.convert=o==="snake_case"?JR:o==="camelCase"?yR:RR}getColumnCasing(o){if(!o.keyAsName)return o.name;const n=o.table[j.Symbol.Schema]??"public",t=o.table[j.Symbol.OriginalName],S=`${n}.${t}.${o.name}`;if(!this.cache[S])this.cacheTable(o.table);return this.cache[S]}cacheTable(o){const n=o[j.Symbol.Schema]??"public",t=o[j.Symbol.OriginalName],S=`${n}.${t}`;if(!this.cachedTables[S]){for(let f of Object.values(o[j.Symbol.Columns])){const T=`${S}.${f.name}`;this.cache[T]=this.convert(f.name)}this.cachedTables[S]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class DS extends Sn{static[y]="PgViewBase"}class Wt{static[y]="PgDialect";casing;constructor(o){this.casing=new yM(o?.casing)}async migrate(o,n,t){const S=typeof t==="string"?"__drizzle_migrations":t.migrationsTable??"__drizzle_migrations",f=typeof t==="string"?"drizzle":t.migrationsSchema??"drizzle",T=R`
24
+ CREATE TABLE IF NOT EXISTS ${R.identifier(f)}.${R.identifier(S)} (
25
+ id SERIAL PRIMARY KEY,
26
+ hash text NOT NULL,
27
+ created_at bigint
28
+ )
29
+ `;await n.execute(R`CREATE SCHEMA IF NOT EXISTS ${R.identifier(f)}`),await n.execute(T);const F=(await n.all(R`select id, hash, created_at from ${R.identifier(f)}.${R.identifier(S)} order by created_at desc limit 1`))[0];await n.transaction(async(k)=>{for await(let A of o)if(!F||Number(F.created_at)<A.folderMillis){for(let $ of A.sql)await k.execute(R.raw($));await k.execute(R`insert into ${R.identifier(f)}.${R.identifier(S)} ("hash", "created_at") values(${A.hash}, ${A.folderMillis})`)}})}escapeName(o){return`"${o}"`}escapeParam(o){return`\$${o+1}`}escapeString(o){return`'${o.replace(/'/g,"''")}'`}buildWithCTE(o){if(!o?.length)return;const n=[R`with `];for(let[t,S]of o.entries())if(n.push(R`${R.identifier(S._.alias)} as (${S._.sql})`),t<o.length-1)n.push(R`, `);return n.push(R` `),R.join(n)}buildDeleteQuery({table:o,where:n,returning:t,withList:S}){const f=this.buildWithCTE(S),T=t?R` returning ${this.buildSelection(t,{isSingleTable:!0})}`:void 0,M=n?R` where ${n}`:void 0;return R`${f}delete from ${o}${M}${T}`}buildUpdateSet(o,n){const t=o[j.Symbol.Columns],S=Object.keys(t).filter((T)=>n[T]!==void 0||t[T]?.onUpdateFn!==void 0),f=S.length;return R.join(S.flatMap((T,M)=>{const F=t[T],k=n[T]??R.param(F.onUpdateFn(),F),A=R`${R.identifier(this.casing.getColumnCasing(F))} = ${k}`;if(M<f-1)return[A,R.raw(", ")];return[A]}))}buildUpdateQuery({table:o,set:n,where:t,returning:S,withList:f}){const T=this.buildWithCTE(f),M=this.buildUpdateSet(o,n),F=S?R` returning ${this.buildSelection(S,{isSingleTable:!0})}`:void 0,k=t?R` where ${t}`:void 0;return R`${T}update ${o} set ${M}${k}${F}`}buildSelection(o,{isSingleTable:n=!1}={}){const t=o.length,S=o.flatMap(({field:f},T)=>{const M=[];if(X(f,b.Aliased)&&f.isSelectionField)M.push(R.identifier(f.fieldAlias));else if(X(f,b.Aliased)||X(f,b)){const F=X(f,b.Aliased)?f.sql:f;if(n)M.push(new b(F.queryChunks.map((k)=>{if(X(k,U))return R.identifier(this.casing.getColumnCasing(k));return k})));else M.push(F);if(X(f,b.Aliased))M.push(R` as ${R.identifier(f.fieldAlias)}`)}else if(X(f,Ko))if(n)M.push(R.identifier(this.casing.getColumnCasing(f)));else M.push(f);if(T<t-1)M.push(R`, `);return M});return R.join(S)}buildSelectQuery({withList:o,fields:n,fieldsFlat:t,where:S,having:f,table:T,joins:M,orderBy:F,groupBy:k,limit:A,offset:$,lockingClause:O,distinct:w,setOperators:G}){const r=t??_n(n);for(let So of r)if(X(So.field,Ko)&&Wn(So.field.table)!==(X(T,xo)?T._.alias:X(T,DS)?T[mo].name:X(T,b)?void 0:Wn(T))&&!((to)=>M?.some(({alias:Wo})=>Wo===(to[j.Symbol.IsAlias]?Wn(to):to[j.Symbol.BaseName])))(So.field.table)){const to=Wn(So.field.table);throw new Error(`Your "${So.path.join("->")}" field references a column "${to}"."${So.field.name}", but the table "${to}" is not part of the query! Did you forget to join it?`)}const H=!M||M.length===0,D=this.buildWithCTE(o);let I;if(w)I=w===!0?R` distinct`:R` distinct on (${R.join(w.on,R`, `)})`;const v=this.buildSelection(r,{isSingleTable:H}),N=(()=>{if(X(T,j)&&T[j.Symbol.OriginalName]!==T[j.Symbol.Name]){let So=R`${R.identifier(T[j.Symbol.OriginalName])}`;if(T[j.Symbol.Schema])So=R`${R.identifier(T[j.Symbol.Schema])}.${So}`;return R`${So} ${R.identifier(T[j.Symbol.Name])}`}return T})(),P=[];if(M)for(let[So,to]of M.entries()){if(So===0)P.push(R` `);const Wo=to.table,Mn=to.lateral?R` lateral`:void 0;if(X(Wo,Qn)){const E=Wo[Qn.Symbol.Name],x=Wo[Qn.Symbol.Schema],To=Wo[Qn.Symbol.OriginalName],Jo=E===To?void 0:to.alias;P.push(R`${R.raw(to.joinType)} join${Mn} ${x?R`${R.identifier(x)}.`:void 0}${R.identifier(To)}${Jo&&R` ${R.identifier(Jo)}`} on ${to.on}`)}else if(X(Wo,Sn)){const E=Wo[mo].name,x=Wo[mo].schema,To=Wo[mo].originalName,Jo=E===To?void 0:to.alias;P.push(R`${R.raw(to.joinType)} join${Mn} ${x?R`${R.identifier(x)}.`:void 0}${R.identifier(To)}${Jo&&R` ${R.identifier(Jo)}`} on ${to.on}`)}else P.push(R`${R.raw(to.joinType)} join${Mn} ${Wo} on ${to.on}`);if(So<M.length-1)P.push(R` `)}const Y=R.join(P),K=S?R` where ${S}`:void 0,Q=f?R` having ${f}`:void 0;let i;if(F&&F.length>0)i=R` order by ${R.join(F,R`, `)}`;let g;if(k&&k.length>0)g=R` group by ${R.join(k,R`, `)}`;const _=typeof A==="object"||typeof A==="number"&&A>=0?R` limit ${A}`:void 0,h=$?R` offset ${$}`:void 0,C=R.empty();if(O){const So=R` for ${R.raw(O.strength)}`;if(O.config.of)So.append(R` of ${R.join(Array.isArray(O.config.of)?O.config.of:[O.config.of],R`, `)}`);if(O.config.noWait)So.append(R` no wait`);else if(O.config.skipLocked)So.append(R` skip locked`);C.append(So)}const a=R`${D}select${I} ${v} from ${N}${Y}${K}${g}${Q}${i}${_}${h}${C}`;if(G.length>0)return this.buildSetOperations(a,G);return a}buildSetOperations(o,n){const[t,...S]=n;if(!t)throw new Error("Cannot pass undefined values to any set operator");if(S.length===0)return this.buildSetOperationQuery({leftSelect:o,setOperator:t});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:o,setOperator:t}),S)}buildSetOperationQuery({leftSelect:o,setOperator:{type:n,isAll:t,rightSelect:S,limit:f,orderBy:T,offset:M}}){const F=R`(${o.getSQL()}) `,k=R`(${S.getSQL()})`;let A;if(T&&T.length>0){const G=[];for(let r of T)if(X(r,U))G.push(R.identifier(r.name));else if(X(r,b)){for(let H=0;H<r.queryChunks.length;H++){const D=r.queryChunks[H];if(X(D,U))r.queryChunks[H]=R.identifier(D.name)}G.push(R`${r}`)}else G.push(R`${r}`);A=R` order by ${R.join(G,R`, `)} `}const $=typeof f==="object"||typeof f==="number"&&f>=0?R` limit ${f}`:void 0,O=R.raw(`${n} ${t?"all ":""}`),w=M?R` offset ${M}`:void 0;return R`${F}${O}${k}${A}${$}${w}`}buildInsertQuery({table:o,values:n,onConflict:t,returning:S,withList:f}){const T=[],M=o[j.Symbol.Columns],F=Object.entries(M).filter(([G,r])=>!r.shouldDisableInsert()),k=F.map(([,G])=>R.identifier(this.casing.getColumnCasing(G)));for(let[G,r]of n.entries()){const H=[];for(let[D,I]of F){const v=r[D];if(v===void 0||X(v,An)&&v.value===void 0)if(I.defaultFn!==void 0){const N=I.defaultFn(),P=X(N,b)?N:R.param(N,I);H.push(P)}else if(!I.default&&I.onUpdateFn!==void 0){const N=I.onUpdateFn(),P=X(N,b)?N:R.param(N,I);H.push(P)}else H.push(R`default`);else H.push(v)}if(T.push(H),G<n.length-1)T.push(R`, `)}const A=this.buildWithCTE(f),$=R.join(T),O=S?R` returning ${this.buildSelection(S,{isSingleTable:!0})}`:void 0,w=t?R` on conflict ${t}`:void 0;return R`${A}insert into ${o} ${k} values ${$}${w}${O}`}buildRefreshMaterializedViewQuery({view:o,concurrently:n,withNoData:t}){const S=n?R` concurrently`:void 0,f=t?R` with no data`:void 0;return R`refresh materialized view${S} ${o}${f}`}prepareTyping(o){if(X(o,Kf)||X(o,wf))return"json";else if(X(o,Xf))return"decimal";else if(X(o,Yf))return"time";else if(X(o,Ef)||X(o,Gf))return"timestamp";else if(X(o,Of)||X(o,Wf))return"date";else if(X(o,zf))return"uuid";else return"none"}sqlToQuery(o,n){return o.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:n})}buildRelationalQueryWithoutPK({fullSchema:o,schema:n,tableNamesMap:t,table:S,tableConfig:f,queryConfig:T,tableAlias:M,nestedQueryRelation:F,joinOn:k}){let A=[],$,O,w=[],G;const r=[];if(T===!0)A=Object.entries(f.columns).map(([I,v])=>({dbKey:v.name,tsKey:I,field:Bn(v,M),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{const D=Object.fromEntries(Object.entries(f.columns).map(([K,Q])=>[K,Bn(Q,M)]));if(T.where){const K=typeof T.where==="function"?T.where(D,_$()):T.where;G=K&&wS(K,M)}const I=[];let v=[];if(T.columns){let K=!1;for(let[Q,i]of Object.entries(T.columns)){if(i===void 0)continue;if(Q in f.columns){if(!K&&i===!0)K=!0;v.push(Q)}}if(v.length>0)v=K?v.filter((Q)=>T.columns?.[Q]===!0):Object.keys(f.columns).filter((Q)=>!v.includes(Q))}else v=Object.keys(f.columns);for(let K of v){const Q=f.columns[K];I.push({tsKey:K,value:Q})}let N=[];if(T.with)N=Object.entries(T.with).filter((K)=>!!K[1]).map(([K,Q])=>({tsKey:K,queryConfig:Q,relation:f.relations[K]}));let P;if(T.extras){P=typeof T.extras==="function"?T.extras(D,{sql:R}):T.extras;for(let[K,Q]of Object.entries(P))I.push({tsKey:K,value:hT(Q,M)})}for(let{tsKey:K,value:Q}of I)A.push({dbKey:X(Q,b.Aliased)?Q.fieldAlias:f.columns[K].name,tsKey:K,field:X(Q,Ko)?Bn(Q,M):Q,relationTableTsKey:void 0,isJson:!1,selection:[]});let Y=typeof T.orderBy==="function"?T.orderBy(D,w$()):T.orderBy??[];if(!Array.isArray(Y))Y=[Y];w=Y.map((K)=>{if(X(K,Ko))return Bn(K,M);return wS(K,M)}),$=T.limit,O=T.offset;for(let{tsKey:K,queryConfig:Q,relation:i}of N){const g=X$(n,t,i),_=$t(i.referencedTable),h=t[_],C=`${M}_${K}`,a=KS(...g.fields.map((Wo,Mn)=>Ct(Bn(g.references[Mn],C),Bn(Wo,M)))),So=this.buildRelationalQueryWithoutPK({fullSchema:o,schema:n,tableNamesMap:t,table:o[h],tableConfig:n[h],queryConfig:X(i,nt)?Q===!0?{limit:1}:{...Q,limit:1}:Q,tableAlias:C,joinOn:a,nestedQueryRelation:i}),to=R`${R.identifier(C)}.${R.identifier("data")}`.as(K);r.push({on:R`true`,table:new xo(So.sql,{},C),alias:C,joinType:"left",lateral:!0}),A.push({dbKey:K,tsKey:K,field:to,relationTableTsKey:h,isJson:!0,selection:So.selection})}}if(A.length===0)throw new yf({message:`No fields selected for table "${f.tsName}" ("${M}")`});let H;if(G=KS(k,G),F){let D=R`json_build_array(${R.join(A.map(({field:N,tsKey:P,isJson:Y})=>Y?R`${R.identifier(`${M}_${P}`)}.${R.identifier("data")}`:X(N,b.Aliased)?N.sql:N),R`, `)})`;if(X(F,ES))D=R`coalesce(json_agg(${D}${w.length>0?R` order by ${R.join(w,R`, `)}`:void 0}), '[]'::json)`;const I=[{dbKey:"data",tsKey:"data",field:D.as("data"),isJson:!0,relationTableTsKey:f.tsName,selection:A}];if($!==void 0||O!==void 0||w.length>0)H=this.buildSelectQuery({table:Jf(S,M),fields:{},fieldsFlat:[{path:[],field:R.raw("*")}],where:G,limit:$,offset:O,orderBy:w,setOperators:[]}),G=void 0,$=void 0,O=void 0,w=[];else H=Jf(S,M);H=this.buildSelectQuery({table:X(H,Qn)?H:new xo(H,{},M),fields:{},fieldsFlat:I.map(({field:N})=>({path:[],field:X(N,Ko)?Bn(N,M):N})),joins:r,where:G,limit:$,offset:O,orderBy:w,setOperators:[]})}else H=this.buildSelectQuery({table:Jf(S,M),fields:{},fieldsFlat:A.map(({field:D})=>({path:[],field:X(D,Ko)?Bn(D,M):D})),joins:r,where:G,limit:$,offset:O,orderBy:w,setOperators:[]});return{tableTsKey:f.tsName,sql:H,selection:A}}}class Tn{static[y]="SelectionProxyHandler";config;constructor(o){this.config={...o}}get(o,n){if(n==="_")return{...o._,selectedFields:new Proxy(o._.selectedFields,this)};if(n===mo)return{...o[mo],selectedFields:new Proxy(o[mo].selectedFields,this)};if(typeof n==="symbol")return o[n];const S=(X(o,xo)?o._.selectedFields:X(o,Sn)?o[mo].selectedFields:o)[n];if(X(S,b.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!S.isSelectionField)return S.sql;const f=S.clone();return f.isSelectionField=!0,f}if(X(S,b)){if(this.config.sqlBehavior==="sql")return S;throw new Error(`You tried to reference "${n}" 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.`)}if(X(S,Ko)){if(this.config.alias)return new Proxy(S,new rt(new Proxy(S.table,new _S(this.config.alias,this.config.replaceOriginalName??!1))));return S}if(typeof S!=="object"||S===null)return S;return new Proxy(S,new Tn(this.config))}}class RM{static[y]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}function ct(o,n){return(t,S,...f)=>{const T=[S,...f].map((M)=>({type:o,isAll:n,rightSelect:M}));for(let M of T)if(!qT(t.getSelectedFields(),M.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(T)}}class so{static[y]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(o){if(this.fields=o.fields,this.session=o.session,this.dialect=o.dialect,o.withList)this.withList=o.withList;this.distinct=o.distinct}from(o){const n=!!this.fields;let t;if(this.fields)t=this.fields;else if(X(o,xo))t=Object.fromEntries(Object.keys(o._.selectedFields).map((S)=>[S,o[S]]));else if(X(o,DS))t=o[mo].selectedFields;else if(X(o,b))t={};else t=Gk(o);return new OM({table:o,fields:t,isPartialSelect:n,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class v$ extends RM{static[y]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;constructor({table:o,fields:n,isPartialSelect:t,session:S,dialect:f,withList:T,distinct:M}){super();this.config={withList:T,table:o,fields:{...n},distinct:M,setOperators:[]},this.isPartialSelect=t,this.session=S,this.dialect=f,this._={selectedFields:n},this.tableName=pT(o),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{}}createJoin(o){return(n,t)=>{const S=this.tableName,f=pT(n);if(typeof f==="string"&&this.config.joins?.some((T)=>T.alias===f))throw new Error(`Alias "${f}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof S==="string")this.config.fields={[S]:this.config.fields};if(typeof f==="string"&&!X(n,b)){const T=X(n,xo)?n._.selectedFields:X(n,Sn)?n[mo].selectedFields:n[j.Symbol.Columns];this.config.fields[f]=T}}if(typeof t==="function")t=t(new Proxy(this.config.fields,new Tn({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:t,table:n,joinType:o,alias:f}),typeof f==="string")switch(o){case"left":{this.joinsNotNullableMap[f]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([T])=>[T,!1])),this.joinsNotNullableMap[f]=!0;break}case"inner":{this.joinsNotNullableMap[f]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([T])=>[T,!1])),this.joinsNotNullableMap[f]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");createSetOperator(o,n){return(t)=>{const S=typeof t==="function"?t(OR()):t;if(!qT(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:o,isAll:n,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(o){return this.config.setOperators.push(...o),this}where(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new Tn({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=o,this}having(o){if(typeof o==="function")o=o(new Proxy(this.config.fields,new Tn({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=o,this}groupBy(...o){if(typeof o[0]==="function"){const n=o[0](new Proxy(this.config.fields,new Tn({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(n)?n:[n]}else this.config.groupBy=o;return this}orderBy(...o){if(typeof o[0]==="function"){const n=o[0](new Proxy(this.config.fields,new Tn({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),t=Array.isArray(n)?n:[n];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=t;else this.config.orderBy=t}else{const n=o;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=n;else this.config.orderBy=n}return this}limit(o){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=o;else this.config.limit=o;return this}offset(o){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=o;else this.config.offset=o;return this}for(o,n={}){return this.config.lockingClause={strength:o,config:n},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}as(o){return new Proxy(new xo(this.getSQL(),this.config.fields,o),new Tn({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new Tn({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class OM extends v${static[y]="PgSelect";_prepare(o){const{session:n,config:t,dialect:S,joinsNotNullableMap:f}=this;if(!n)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");return Oo.startActiveSpan("drizzle.prepareQuery",()=>{const T=_n(t.fields),M=n.prepareQuery(S.sqlToQuery(this.getSQL()),T,o,!0);return M.joinsNotNullableMap=f,M})}prepare(o){return this._prepare(o)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})}}Ek(OM,[ao]);var OR=()=>({union:WR,unionAll:_R,intersect:wR,intersectAll:KR,except:XR,exceptAll:YR}),WR=ct("union",!1),_R=ct("union",!0),wR=ct("intersect",!1),KR=ct("intersect",!0),XR=ct("except",!1),YR=ct("except",!0);class WM{static[y]="PgQueryBuilder";dialect;dialectConfig;constructor(o){this.dialect=X(o,Wt)?o:void 0,this.dialectConfig=X(o,Wt)?void 0:o}$with(o){const n=this;return{as(t){if(typeof t==="function")t=t(n);return new Proxy(new WS(t.getSQL(),t.getSelectedFields(),o,!0),new Tn({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}with(...o){const n=this;function t(T){return new so({fields:T??void 0,session:void 0,dialect:n.getDialect(),withList:o})}function S(T){return new so({fields:T??void 0,session:void 0,dialect:n.getDialect(),distinct:!0})}function f(T,M){return new so({fields:M??void 0,session:void 0,dialect:n.getDialect(),distinct:{on:T}})}return{select:t,selectDistinct:S,selectDistinctOn:f}}select(o){return new so({fields:o??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(o){return new so({fields:o??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(o,n){return new so({fields:n??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:o}})}getDialect(){if(!this.dialect)this.dialect=new Wt(this.dialectConfig);return this.dialect}}class _M extends ao{constructor(o,n,t){super();this.session=n,this.dialect=t,this.config={view:o}}static[y]="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(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,o,!0)})}prepare(o){return this._prepare(o)}execute=(o)=>{return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute(o)})}}class Nf{constructor(o,n,t,S){this.table=o,this.session=n,this.dialect=t,this.withList=S}static[y]="PgUpdateBuilder";set(o){return new q$(this.table,Rf(this.table,o),this.session,this.dialect,this.withList)}}class q$ extends ao{constructor(o,n,t,S,f){super();this.session=t,this.dialect=S,this.config={set:n,table:o,withList:f}}static[y]="PgUpdate";config;where(o){return this.config.where=o,this}returning(o=this.config.table[j.Symbol.Columns]){return this.config.returning=_n(o),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){const{typings:o,...n}=this.dialect.sqlToQuery(this.getSQL());return n}_prepare(o){return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,o,!0)}prepare(o){return this._prepare(o)}execute=(o)=>{return this._prepare().execute(o)};$dynamic(){return this}}class US extends b{constructor(o){super(US.buildEmbeddedCount(o.source,o.filters).queryChunks);this.params=o,this.mapWith(Number),this.session=o.session,this.sql=US.buildCount(o.source,o.filters)}sql;static[y]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(o,n){return R`(select count(*) from ${o}${R.raw(" where ").if(n)}${n})`}static buildCount(o,n){return R`select count(*) as count from ${o}${R.raw(" where ").if(n)}${n};`}then(o,n){return Promise.resolve(this.session.count(this.sql)).then(o,n)}catch(o){return this.then(void 0,o)}finally(o){return this.then((n)=>{return o?.(),n},(n)=>{throw o?.(),n})}}class KM{constructor(o,n,t,S,f,T,M){this.fullSchema=o,this.schema=n,this.tableNamesMap=t,this.table=S,this.tableConfig=f,this.dialect=T,this.session=M}static[y]="PgRelationalQueryBuilder";findMany(o){return new wM(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?o:{},"many")}findFirst(o){return new wM(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,o?{...o,limit:1}:{limit:1},"first")}}class wM extends ao{constructor(o,n,t,S,f,T,M,F,k){super();this.fullSchema=o,this.schema=n,this.tableNamesMap=t,this.table=S,this.tableConfig=f,this.dialect=T,this.session=M,this.config=F,this.mode=k}static[y]="PgRelationalQuery";_prepare(o){return Oo.startActiveSpan("drizzle.prepareQuery",()=>{const{query:n,builtQuery:t}=this._toSQL();return this.session.prepareQuery(t,void 0,o,!0,(S,f)=>{const T=S.map((M)=>Hf(this.schema,this.tableConfig,M,n.selection,f));if(this.mode==="first")return T[0];return T})})}prepare(o){return this._prepare(o)}_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(){const o=this._getQuery(),n=this.dialect.sqlToQuery(o.sql);return{query:o,builtQuery:n}}toSQL(){return this._toSQL().builtQuery}execute(){return Oo.startActiveSpan("drizzle.operation",()=>{return this._prepare().execute()})}}class XM extends ao{constructor(o,n,t,S){super();this.execute=o,this.sql=n,this.query=t,this.mapBatchResult=S}static[y]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(o,n){return n?this.mapBatchResult(o):o}_prepare(){return this}isResponseInArrayMode(){return!1}}class VS{constructor(o,n,t){if(this.dialect=o,this.session=n,this._=t?{schema:t.schema,fullSchema:t.fullSchema,tableNamesMap:t.tableNamesMap,session:n}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:n},this.query={},this._.schema)for(let[S,f]of Object.entries(this._.schema))this.query[S]=new KM(t.fullSchema,this._.schema,this._.tableNamesMap,t.fullSchema[S],f,o,n)}static[y]="PgDatabase";query;$with(o){const n=this;return{as(t){if(typeof t==="function")t=t(new WM(n.dialect));return new Proxy(new WS(t.getSQL(),t.getSelectedFields(),o,!0),new Tn({alias:o,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}}$count(o,n){return new US({source:o,filters:n,session:this.session})}with(...o){const n=this;function t(k){return new so({fields:k??void 0,session:n.session,dialect:n.dialect,withList:o})}function S(k){return new so({fields:k??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:!0})}function f(k,A){return new so({fields:A??void 0,session:n.session,dialect:n.dialect,withList:o,distinct:{on:k}})}function T(k){return new Nf(k,n.session,n.dialect,o)}function M(k){return new bf(k,n.session,n.dialect,o)}function F(k){return new cf(k,n.session,n.dialect,o)}return{select:t,selectDistinct:S,selectDistinctOn:f,update:T,insert:M,delete:F}}select(o){return new so({fields:o??void 0,session:this.session,dialect:this.dialect})}selectDistinct(o){return new so({fields:o??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(o,n){return new so({fields:n??void 0,session:this.session,dialect:this.dialect,distinct:{on:o}})}update(o){return new Nf(o,this.session,this.dialect)}insert(o){return new bf(o,this.session,this.dialect)}delete(o){return new cf(o,this.session,this.dialect)}refreshMaterializedView(o){return new _M(o,this.session,this.dialect)}execute(o){const n=typeof o==="string"?R.raw(o):o.getSQL(),t=this.dialect.sqlToQuery(n),S=this.session.prepareQuery(t,void 0,void 0,!1);return new XM(()=>S.execute(),n,t,(f)=>S.mapResult(f,!0))}transaction(o,n){return this.session.transaction(o,n)}}function YM(o){return new p$(!0,o)}class p${constructor(o,n){this.unique=o,this.name=n}static[y]="PgIndexBuilderOn";on(...o){return new hf(o.map((n)=>{if(X(n,b))return n;n=n;const t=new OS(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=JSON.parse(JSON.stringify(n.defaultConfig)),t}),this.unique,!1,this.name)}onOnly(...o){return new hf(o.map((n)=>{if(X(n,b))return n;n=n;const t=new OS(n.name,!!n.keyAsName,n.columnType,n.indexConfig);return n.indexConfig=n.defaultConfig,t}),this.unique,!0,this.name)}using(o,...n){return new hf(n.map((t)=>{if(X(t,b))return t;t=t;const S=new OS(t.name,!!t.keyAsName,t.columnType,t.indexConfig);return t.indexConfig=JSON.parse(JSON.stringify(t.defaultConfig)),S}),this.unique,!0,this.name,o)}}class hf{static[y]="PgIndexBuilder";config;constructor(o,n,t,S,f="btree"){this.config={name:S,columns:o,unique:n,only:t,method:f}}concurrently(){return this.config.concurrently=!0,this}with(o){return this.config.with=o,this}where(o){return this.config.where=o,this}build(o){return new Z$(this.config,o)}}class Z${static[y]="PgIndex";config;constructor(o,n){this.config={...o,table:n}}}class EM{constructor(o){this.query=o}getQuery(){return this.query}mapResult(o,n){return o}static[y]="PgPreparedQuery";joinsNotNullableMap}class GM{constructor(o){this.dialect=o}static[y]="PgSession";execute(o){return Oo.startActiveSpan("drizzle.operation",()=>{return Oo.startActiveSpan("drizzle.prepareQuery",()=>{return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1)}).execute()})}all(o){return this.prepareQuery(this.dialect.sqlToQuery(o),void 0,void 0,!1).all()}async count(o){const n=await this.execute(o);return Number(n[0].count)}}class zM extends VS{constructor(o,n,t,S=0){super(o,n,t);this.schema=t,this.nestedIndex=S}static[y]="PgTransaction";rollback(){throw new xT}getTransactionConfigSQL(o){const n=[];if(o.isolationLevel)n.push(`isolation level ${o.isolationLevel}`);if(o.accessMode)n.push(o.accessMode);if(typeof o.deferrable==="boolean")n.push(o.deferrable?"deferrable":"not deferrable");return R.raw(n.join(" "))}setTransaction(o){return this.session.execute(R`set transaction ${this.getTransactionConfigSQL(o)}`)}}class P$ extends EM{constructor(o,n,t,S,f,T,M){super({sql:n,params:t});this.client=o,this.queryString=n,this.params=t,this.logger=S,this.fields=f,this._isResponseInArrayMode=T,this.customResultMapper=M}static[y]="PostgresJsPreparedQuery";async execute(o={}){return Oo.startActiveSpan("drizzle.execute",async(n)=>{const t=NT(this.params,o);n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(t)}),this.logger.logQuery(this.queryString,t);const{fields:S,queryString:f,client:T,joinsNotNullableMap:M,customResultMapper:F}=this;if(!S&&!F)return Oo.startActiveSpan("drizzle.driver.execute",()=>{return T.unsafe(f,t)});const k=await Oo.startActiveSpan("drizzle.driver.execute",()=>{return n?.setAttributes({"drizzle.query.text":f,"drizzle.query.params":JSON.stringify(t)}),T.unsafe(f,t).values()});return Oo.startActiveSpan("drizzle.mapResponse",()=>{return F?F(k):k.map((A)=>Yk(S,A,M))})})}all(o={}){return Oo.startActiveSpan("drizzle.execute",async(n)=>{const t=NT(this.params,o);return n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(t)}),this.logger.logQuery(this.queryString,t),Oo.startActiveSpan("drizzle.driver.execute",()=>{return n?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(t)}),this.client.unsafe(this.queryString,t)})})}isResponseInArrayMode(){return this._isResponseInArrayMode}}class rS extends GM{constructor(o,n,t,S={}){super(n);this.client=o,this.schema=t,this.options=S,this.logger=S.logger??new vT}static[y]="PostgresJsSession";logger;prepareQuery(o,n,t,S,f){return new P$(this.client,o.sql,o.params,this.logger,n,S,f)}query(o,n){return this.logger.logQuery(o,n),this.client.unsafe(o,n).values()}queryObjects(o,n){return this.client.unsafe(o,n)}transaction(o,n){return this.client.begin(async(t)=>{const S=new rS(t,this.dialect,this.schema,this.options),f=new HM(this.dialect,S,this.schema);if(n)await f.setTransaction(n);return o(f)})}}class HM extends zM{constructor(o,n,t,S=0){super(o,n,t,S);this.session=n}static[y]="PostgresJsTransaction";transaction(o){return this.session.client.savepoint((n)=>{const t=new rS(n,this.dialect,this.schema,this.session.options),S=new HM(this.dialect,t,this.schema);return o(S)})}}function bt(o,n={}){const t=(k)=>k;for(let k of["1184","1082","1083","1114"])o.options.parsers[k]=t,o.options.serializers[k]=t;o.options.serializers["114"]=t,o.options.serializers["3802"]=t;const S=new Wt({casing:n.casing});let f;if(n.logger===!0)f=new iT;else if(n.logger!==!1)f=n.logger;let T;if(n.schema){const k=K$(n.schema,Y$);T={fullSchema:n.schema,schema:k.tables,tableNamesMap:k.tableNamesMap}}const M=new rS(o,S,T,{logger:f}),F=new g$(S,M,T);return F.$client=o,F}function xf(...o){if(typeof o[0]==="function")return bt(o[0],o[1]);if(typeof o[0]==="object"){const{connection:t,client:S,...f}=o[0];if(S)return bt(S,f);if(typeof t==="object"&&t.url!==void 0){const{url:M,...F}=t,k=Bt(M,F);return bt(k,f)}const T=Bt(t);return bt(T,f)}const n=Bt(o[0]);return bt(n,o[1])}class g$ extends VS{static[y]="PostgresJsDatabase"}((o)=>{function n(t){return bt({},t)}o.mock=n})(xf||(xf={}));function GR(o){d$=o}function vf(){return d$}function L(o,n){const t=vf(),S=qf({issueData:n,data:o.data,path:o.path,errorMaps:[o.common.contextualErrorMap,o.schemaErrorMap,t,t===it?void 0:it].filter((f)=>!!f)});o.common.issues.push(S)}function pf(o,n,t,S){if(t==="a"&&!S)throw new TypeError("Private accessor was defined without a getter");if(typeof n==="function"?o!==n||!S:!n.has(o))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?S:t==="a"?S.call(o):S?S.value:n.get(o)}function u$(o,n,t,S,f){if(S==="m")throw new TypeError("Private method is not writable");if(S==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof n==="function"?o!==n||!f:!n.has(o))throw new TypeError("Cannot write private member to an object whose class did not declare it");return S==="a"?f.call(o,t):f?f.value=t:n.set(o,t),t}function oo(o){if(!o)return{};const{errorMap:n,invalid_type_error:t,required_error:S,description:f}=o;if(n&&(t||S))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(n)return{errorMap:n,description:f};return{errorMap:(M,F)=>{var k,A;const{message:$}=o;if(M.code==="invalid_enum_value")return{message:$!==null&&$!==void 0?$:F.defaultError};if(typeof F.data==="undefined")return{message:(k=$!==null&&$!==void 0?$:S)!==null&&k!==void 0?k:F.defaultError};if(M.code!=="invalid_type")return{message:F.defaultError};return{message:(A=$!==null&&$!==void 0?$:t)!==null&&A!==void 0?A:F.defaultError}},description:f}}function s$(o){let n="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";if(o.precision)n=`${n}\\.\\d{${o.precision}}`;else if(o.precision==null)n=`${n}(\\.\\d+)?`;return n}function cR(o){return new RegExp(`^${s$(o)}\$`)}function oJ(o){let n=`${a$}T${s$(o)}`;const t=[];if(t.push(o.local?"Z?":"Z"),o.offset)t.push("([+-]\\d{2}:?\\d{2})");return n=`${n}(${t.join("|")})`,new RegExp(`^${n}\$`)}function bR(o,n){if((n==="v4"||!n)&&LR.test(o))return!0;if((n==="v6"||!n)&&IR.test(o))return!0;return!1}function NR(o,n){const t=(o.toString().split(".")[1]||"").length,S=(n.toString().split(".")[1]||"").length,f=t>S?t:S,T=parseInt(o.toFixed(f).replace(".","")),M=parseInt(n.toFixed(f).replace(".",""));return T%M/Math.pow(10,f)}function Nt(o){if(o instanceof Qo){const n={};for(let t in o.shape){const S=o.shape[t];n[t]=Vn.create(Nt(S))}return new Qo({...o._def,shape:()=>n})}else if(o instanceof Un)return new Un({...o._def,type:Nt(o.element)});else if(o instanceof Vn)return Vn.create(Nt(o.unwrap()));else if(o instanceof Zn)return Zn.create(Nt(o.unwrap()));else if(o instanceof Nn)return Nn.create(o.items.map((n)=>Nt(n)));else return o}function VM(o,n){const t=St(o),S=St(n);if(o===n)return{valid:!0,data:o};else if(t===B.object&&S===B.object){const f=Ao.objectKeys(n),T=Ao.objectKeys(o).filter((F)=>f.indexOf(F)!==-1),M={...o,...n};for(let F of T){const k=VM(o[F],n[F]);if(!k.valid)return{valid:!1};M[F]=k.data}return{valid:!0,data:M}}else if(t===B.array&&S===B.array){if(o.length!==n.length)return{valid:!1};const f=[];for(let T=0;T<o.length;T++){const M=o[T],F=n[T],k=VM(M,F);if(!k.valid)return{valid:!1};f.push(k.data)}return{valid:!0,data:f}}else if(t===B.date&&S===B.date&&+o===+n)return{valid:!0,data:o};else return{valid:!1}}function nJ(o,n){return new Ft({values:o,typeName:e.ZodEnum,...oo(n)})}function tJ(o,n={},t){if(o)return wt.create().superRefine((S,f)=>{var T,M;if(!o(S)){const F=typeof n==="function"?n(S):typeof n==="string"?{message:n}:n,k=(M=(T=F.fatal)!==null&&T!==void 0?T:t)!==null&&M!==void 0?M:!0,A=typeof F==="string"?{message:F}:F;f.addIssue({code:"custom",...A,fatal:k})}});return wt.create()}var Ao;(function(o){o.assertEqual=(f)=>f;function n(f){}o.assertIs=n;function t(f){throw new Error}o.assertNever=t,o.arrayToEnum=(f)=>{const T={};for(let M of f)T[M]=M;return T},o.getValidEnumValues=(f)=>{const T=o.objectKeys(f).filter((F)=>typeof f[f[F]]!=="number"),M={};for(let F of T)M[F]=f[F];return o.objectValues(M)},o.objectValues=(f)=>{return o.objectKeys(f).map(function(T){return f[T]})},o.objectKeys=typeof Object.keys==="function"?(f)=>Object.keys(f):(f)=>{const T=[];for(let M in f)if(Object.prototype.hasOwnProperty.call(f,M))T.push(M);return T},o.find=(f,T)=>{for(let M of f)if(T(M))return M;return},o.isInteger=typeof Number.isInteger==="function"?(f)=>Number.isInteger(f):(f)=>typeof f==="number"&&isFinite(f)&&Math.floor(f)===f;function S(f,T=" | "){return f.map((M)=>typeof M==="string"?`'${M}'`:M).join(T)}o.joinValues=S,o.jsonStringifyReplacer=(f,T)=>{if(typeof T==="bigint")return T.toString();return T}})(Ao||(Ao={}));var QM;(function(o){o.mergeShapes=(n,t)=>{return{...n,...t}}})(QM||(QM={}));var B=Ao.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),St=(o)=>{switch(typeof o){case"undefined":return B.undefined;case"string":return B.string;case"number":return isNaN(o)?B.nan:B.number;case"boolean":return B.boolean;case"function":return B.function;case"bigint":return B.bigint;case"symbol":return B.symbol;case"object":if(Array.isArray(o))return B.array;if(o===null)return B.null;if(o.then&&typeof o.then==="function"&&o.catch&&typeof o.catch==="function")return B.promise;if(typeof Map!=="undefined"&&o instanceof Map)return B.map;if(typeof Set!=="undefined"&&o instanceof Set)return B.set;if(typeof Date!=="undefined"&&o instanceof Date)return B.date;return B.object;default:return B.unknown}},z=Ao.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ER=(o)=>{return JSON.stringify(o,null,2).replace(/"([^"]+)":/g,"$1:")};class yn extends Error{constructor(o){super();this.issues=[],this.addIssue=(t)=>{this.issues=[...this.issues,t]},this.addIssues=(t=[])=>{this.issues=[...this.issues,...t]};const n=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,n);else this.__proto__=n;this.name="ZodError",this.issues=o}get errors(){return this.issues}format(o){const n=o||function(f){return f.message},t={_errors:[]},S=(f)=>{for(let T of f.issues)if(T.code==="invalid_union")T.unionErrors.map(S);else if(T.code==="invalid_return_type")S(T.returnTypeError);else if(T.code==="invalid_arguments")S(T.argumentsError);else if(T.path.length===0)t._errors.push(n(T));else{let M=t,F=0;while(F<T.path.length){const k=T.path[F];if(F!==T.path.length-1)M[k]=M[k]||{_errors:[]};else M[k]=M[k]||{_errors:[]},M[k]._errors.push(n(T));M=M[k],F++}}};return S(this),t}static assert(o){if(!(o instanceof yn))throw new Error(`Not a ZodError: ${o}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ao.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(o=(n)=>n.message){const n={},t=[];for(let S of this.issues)if(S.path.length>0)n[S.path[0]]=n[S.path[0]]||[],n[S.path[0]].push(o(S));else t.push(o(S));return{formErrors:t,fieldErrors:n}}get formErrors(){return this.flatten()}}yn.create=(o)=>{return new yn(o)};var it=(o,n)=>{let t;switch(o.code){case z.invalid_type:if(o.received===B.undefined)t="Required";else t=`Expected ${o.expected}, received ${o.received}`;break;case z.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(o.expected,Ao.jsonStringifyReplacer)}`;break;case z.unrecognized_keys:t=`Unrecognized key(s) in object: ${Ao.joinValues(o.keys,", ")}`;break;case z.invalid_union:t="Invalid input";break;case z.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Ao.joinValues(o.options)}`;break;case z.invalid_enum_value:t=`Invalid enum value. Expected ${Ao.joinValues(o.options)}, received '${o.received}'`;break;case z.invalid_arguments:t="Invalid function arguments";break;case z.invalid_return_type:t="Invalid function return type";break;case z.invalid_date:t="Invalid date";break;case z.invalid_string:if(typeof o.validation==="object")if("includes"in o.validation){if(t=`Invalid input: must include "${o.validation.includes}"`,typeof o.validation.position==="number")t=`${t} at one or more positions greater than or equal to ${o.validation.position}`}else if("startsWith"in o.validation)t=`Invalid input: must start with "${o.validation.startsWith}"`;else if("endsWith"in o.validation)t=`Invalid input: must end with "${o.validation.endsWith}"`;else Ao.assertNever(o.validation);else if(o.validation!=="regex")t=`Invalid ${o.validation}`;else t="Invalid";break;case z.too_small:if(o.type==="array")t=`Array must contain ${o.exact?"exactly":o.inclusive?"at least":"more than"} ${o.minimum} element(s)`;else if(o.type==="string")t=`String must contain ${o.exact?"exactly":o.inclusive?"at least":"over"} ${o.minimum} character(s)`;else if(o.type==="number")t=`Number must be ${o.exact?"exactly equal to ":o.inclusive?"greater than or equal to ":"greater than "}${o.minimum}`;else if(o.type==="date")t=`Date must be ${o.exact?"exactly equal to ":o.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(o.minimum))}`;else t="Invalid input";break;case z.too_big:if(o.type==="array")t=`Array must contain ${o.exact?"exactly":o.inclusive?"at most":"less than"} ${o.maximum} element(s)`;else if(o.type==="string")t=`String must contain ${o.exact?"exactly":o.inclusive?"at most":"under"} ${o.maximum} character(s)`;else if(o.type==="number")t=`Number must be ${o.exact?"exactly":o.inclusive?"less than or equal to":"less than"} ${o.maximum}`;else if(o.type==="bigint")t=`BigInt must be ${o.exact?"exactly":o.inclusive?"less than or equal to":"less than"} ${o.maximum}`;else if(o.type==="date")t=`Date must be ${o.exact?"exactly":o.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(o.maximum))}`;else t="Invalid input";break;case z.custom:t="Invalid input";break;case z.invalid_intersection_types:t="Intersection results could not be merged";break;case z.not_multiple_of:t=`Number must be a multiple of ${o.multipleOf}`;break;case z.not_finite:t="Number must be finite";break;default:t=n.defaultError,Ao.assertNever(o)}return{message:t}},d$=it,qf=(o)=>{const{data:n,path:t,errorMaps:S,issueData:f}=o,T=[...t,...f.path||[]],M={...f,path:T};if(f.message!==void 0)return{...f,path:T,message:f.message};let F="";const k=S.filter((A)=>!!A).slice().reverse();for(let A of k)F=A(M,{data:n,defaultError:F}).message;return{...f,path:T,message:F}},zR=[];class lo{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(o,n){const t=[];for(let S of n){if(S.status==="aborted")return d;if(S.status==="dirty")o.dirty();t.push(S.value)}return{status:o.value,value:t}}static async mergeObjectAsync(o,n){const t=[];for(let S of n){const f=await S.key,T=await S.value;t.push({key:f,value:T})}return lo.mergeObjectSync(o,t)}static mergeObjectSync(o,n){const t={};for(let S of n){const{key:f,value:T}=S;if(f.status==="aborted")return d;if(T.status==="aborted")return d;if(f.status==="dirty")o.dirty();if(T.status==="dirty")o.dirty();if(f.value!=="__proto__"&&(typeof T.value!=="undefined"||S.alwaysSet))t[f.value]=T.value}return{status:o.value,value:t}}}var d=Object.freeze({status:"aborted"}),ht=(o)=>({status:"dirty",value:o}),on=(o)=>({status:"valid",value:o}),DM=(o)=>o.status==="aborted",UM=(o)=>o.status==="dirty",IS=(o)=>o.status==="valid",jS=(o)=>typeof Promise!=="undefined"&&o instanceof Promise;var q;(function(o){o.errToObj=(n)=>typeof n==="string"?{message:n}:n||{},o.toString=(n)=>typeof n==="string"?n:n===null||n===void 0?void 0:n.message})(q||(q={}));var CS,LS;class rn{constructor(o,n,t,S){this._cachedPath=[],this.parent=o,this.data=n,this._path=t,this._key=S}get path(){if(!this._cachedPath.length)if(this._key instanceof Array)this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var l$=(o,n)=>{if(IS(n))return{success:!0,data:n.value};else{if(!o.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new yn(o.common.issues);return this._error=t,this._error}}}};class no{constructor(o){this.spa=this.safeParseAsync,this._def=o,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(o){return St(o.data)}_getOrReturnCtx(o,n){return n||{common:o.parent.common,data:o.data,parsedType:St(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}_processInputParams(o){return{status:new lo,ctx:{common:o.parent.common,data:o.data,parsedType:St(o.data),schemaErrorMap:this._def.errorMap,path:o.path,parent:o.parent}}}_parseSync(o){const n=this._parse(o);if(jS(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(o){const n=this._parse(o);return Promise.resolve(n)}parse(o,n){const t=this.safeParse(o,n);if(t.success)return t.data;throw t.error}safeParse(o,n){var t;const S={common:{issues:[],async:(t=n===null||n===void 0?void 0:n.async)!==null&&t!==void 0?t:!1,contextualErrorMap:n===null||n===void 0?void 0:n.errorMap},path:(n===null||n===void 0?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:St(o)},f=this._parseSync({data:o,path:S.path,parent:S});return l$(S,f)}async parseAsync(o,n){const t=await this.safeParseAsync(o,n);if(t.success)return t.data;throw t.error}async safeParseAsync(o,n){const t={common:{issues:[],contextualErrorMap:n===null||n===void 0?void 0:n.errorMap,async:!0},path:(n===null||n===void 0?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:o,parsedType:St(o)},S=this._parse({data:o,path:t.path,parent:t}),f=await(jS(S)?S:Promise.resolve(S));return l$(t,f)}refine(o,n){const t=(S)=>{if(typeof n==="string"||typeof n==="undefined")return{message:n};else if(typeof n==="function")return n(S);else return n};return this._refinement((S,f)=>{const T=o(S),M=()=>f.addIssue({code:z.custom,...t(S)});if(typeof Promise!=="undefined"&&T instanceof Promise)return T.then((F)=>{if(!F)return M(),!1;else return!0});if(!T)return M(),!1;else return!0})}refinement(o,n){return this._refinement((t,S)=>{if(!o(t))return S.addIssue(typeof n==="function"?n(t,S):n),!1;else return!0})}_refinement(o){return new Kn({schema:this,typeName:e.ZodEffects,effect:{type:"refinement",refinement:o}})}superRefine(o){return this._refinement(o)}optional(){return Vn.create(this,this._def)}nullable(){return Zn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Un.create(this,this._def)}promise(){return Xt.create(this,this._def)}or(o){return Zt.create([this,o],this._def)}and(o){return Pt.create(this,o,this._def)}transform(o){return new Kn({...oo(this._def),schema:this,typeName:e.ZodEffects,effect:{type:"transform",transform:o}})}default(o){const n=typeof o==="function"?o:()=>o;return new dt({...oo(this._def),innerType:this,defaultValue:n,typeName:e.ZodDefault})}brand(){return new Pf({typeName:e.ZodBranded,type:this,...oo(this._def)})}catch(o){const n=typeof o==="function"?o:()=>o;return new ut({...oo(this._def),innerType:this,catchValue:n,typeName:e.ZodCatch})}describe(o){return new this.constructor({...this._def,description:o})}pipe(o){return xS.create(this,o)}readonly(){return at.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var HR=/^c[^\s-]{8,}$/i,mR=/^[0-9a-z]+$/,QR=/^[0-9A-HJKMNP-TV-Z]{26}$/,DR=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,UR=/^[a-z0-9_-]{21}$/i,VR=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,rR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,CR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",mM,LR=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,IR=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,jR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,a$="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",BR=new RegExp(`^${a$}\$`);class Dn extends no{_parse(o){if(this._def.coerce)o.data=String(o.data);if(this._getType(o)!==B.string){const f=this._getOrReturnCtx(o);return L(f,{code:z.invalid_type,expected:B.string,received:f.parsedType}),d}const t=new lo;let S=void 0;for(let f of this._def.checks)if(f.kind==="min"){if(o.data.length<f.value)S=this._getOrReturnCtx(o,S),L(S,{code:z.too_small,minimum:f.value,type:"string",inclusive:!0,exact:!1,message:f.message}),t.dirty()}else if(f.kind==="max"){if(o.data.length>f.value)S=this._getOrReturnCtx(o,S),L(S,{code:z.too_big,maximum:f.value,type:"string",inclusive:!0,exact:!1,message:f.message}),t.dirty()}else if(f.kind==="length"){const T=o.data.length>f.value,M=o.data.length<f.value;if(T||M){if(S=this._getOrReturnCtx(o,S),T)L(S,{code:z.too_big,maximum:f.value,type:"string",inclusive:!0,exact:!0,message:f.message});else if(M)L(S,{code:z.too_small,minimum:f.value,type:"string",inclusive:!0,exact:!0,message:f.message});t.dirty()}}else if(f.kind==="email"){if(!rR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"email",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="emoji"){if(!mM)mM=new RegExp(CR,"u");if(!mM.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"emoji",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="uuid"){if(!DR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"uuid",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="nanoid"){if(!UR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"nanoid",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="cuid"){if(!HR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"cuid",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="cuid2"){if(!mR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"cuid2",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="ulid"){if(!QR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"ulid",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="url")try{new URL(o.data)}catch(T){S=this._getOrReturnCtx(o,S),L(S,{validation:"url",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="regex"){if(f.regex.lastIndex=0,!f.regex.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"regex",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="trim")o.data=o.data.trim();else if(f.kind==="includes"){if(!o.data.includes(f.value,f.position))S=this._getOrReturnCtx(o,S),L(S,{code:z.invalid_string,validation:{includes:f.value,position:f.position},message:f.message}),t.dirty()}else if(f.kind==="toLowerCase")o.data=o.data.toLowerCase();else if(f.kind==="toUpperCase")o.data=o.data.toUpperCase();else if(f.kind==="startsWith"){if(!o.data.startsWith(f.value))S=this._getOrReturnCtx(o,S),L(S,{code:z.invalid_string,validation:{startsWith:f.value},message:f.message}),t.dirty()}else if(f.kind==="endsWith"){if(!o.data.endsWith(f.value))S=this._getOrReturnCtx(o,S),L(S,{code:z.invalid_string,validation:{endsWith:f.value},message:f.message}),t.dirty()}else if(f.kind==="datetime"){if(!oJ(f).test(o.data))S=this._getOrReturnCtx(o,S),L(S,{code:z.invalid_string,validation:"datetime",message:f.message}),t.dirty()}else if(f.kind==="date"){if(!BR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{code:z.invalid_string,validation:"date",message:f.message}),t.dirty()}else if(f.kind==="time"){if(!cR(f).test(o.data))S=this._getOrReturnCtx(o,S),L(S,{code:z.invalid_string,validation:"time",message:f.message}),t.dirty()}else if(f.kind==="duration"){if(!VR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"duration",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="ip"){if(!bR(o.data,f.version))S=this._getOrReturnCtx(o,S),L(S,{validation:"ip",code:z.invalid_string,message:f.message}),t.dirty()}else if(f.kind==="base64"){if(!jR.test(o.data))S=this._getOrReturnCtx(o,S),L(S,{validation:"base64",code:z.invalid_string,message:f.message}),t.dirty()}else Ao.assertNever(f);return{status:t.value,value:o.data}}_regex(o,n,t){return this.refinement((S)=>o.test(S),{validation:n,code:z.invalid_string,...q.errToObj(t)})}_addCheck(o){return new Dn({...this._def,checks:[...this._def.checks,o]})}email(o){return this._addCheck({kind:"email",...q.errToObj(o)})}url(o){return this._addCheck({kind:"url",...q.errToObj(o)})}emoji(o){return this._addCheck({kind:"emoji",...q.errToObj(o)})}uuid(o){return this._addCheck({kind:"uuid",...q.errToObj(o)})}nanoid(o){return this._addCheck({kind:"nanoid",...q.errToObj(o)})}cuid(o){return this._addCheck({kind:"cuid",...q.errToObj(o)})}cuid2(o){return this._addCheck({kind:"cuid2",...q.errToObj(o)})}ulid(o){return this._addCheck({kind:"ulid",...q.errToObj(o)})}base64(o){return this._addCheck({kind:"base64",...q.errToObj(o)})}ip(o){return this._addCheck({kind:"ip",...q.errToObj(o)})}datetime(o){var n,t;if(typeof o==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:o});return this._addCheck({kind:"datetime",precision:typeof(o===null||o===void 0?void 0:o.precision)==="undefined"?null:o===null||o===void 0?void 0:o.precision,offset:(n=o===null||o===void 0?void 0:o.offset)!==null&&n!==void 0?n:!1,local:(t=o===null||o===void 0?void 0:o.local)!==null&&t!==void 0?t:!1,...q.errToObj(o===null||o===void 0?void 0:o.message)})}date(o){return this._addCheck({kind:"date",message:o})}time(o){if(typeof o==="string")return this._addCheck({kind:"time",precision:null,message:o});return this._addCheck({kind:"time",precision:typeof(o===null||o===void 0?void 0:o.precision)==="undefined"?null:o===null||o===void 0?void 0:o.precision,...q.errToObj(o===null||o===void 0?void 0:o.message)})}duration(o){return this._addCheck({kind:"duration",...q.errToObj(o)})}regex(o,n){return this._addCheck({kind:"regex",regex:o,...q.errToObj(n)})}includes(o,n){return this._addCheck({kind:"includes",value:o,position:n===null||n===void 0?void 0:n.position,...q.errToObj(n===null||n===void 0?void 0:n.message)})}startsWith(o,n){return this._addCheck({kind:"startsWith",value:o,...q.errToObj(n)})}endsWith(o,n){return this._addCheck({kind:"endsWith",value:o,...q.errToObj(n)})}min(o,n){return this._addCheck({kind:"min",value:o,...q.errToObj(n)})}max(o,n){return this._addCheck({kind:"max",value:o,...q.errToObj(n)})}length(o,n){return this._addCheck({kind:"length",value:o,...q.errToObj(n)})}nonempty(o){return this.min(1,q.errToObj(o))}trim(){return new Dn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Dn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Dn({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((o)=>o.kind==="datetime")}get isDate(){return!!this._def.checks.find((o)=>o.kind==="date")}get isTime(){return!!this._def.checks.find((o)=>o.kind==="time")}get isDuration(){return!!this._def.checks.find((o)=>o.kind==="duration")}get isEmail(){return!!this._def.checks.find((o)=>o.kind==="email")}get isURL(){return!!this._def.checks.find((o)=>o.kind==="url")}get isEmoji(){return!!this._def.checks.find((o)=>o.kind==="emoji")}get isUUID(){return!!this._def.checks.find((o)=>o.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((o)=>o.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((o)=>o.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((o)=>o.kind==="cuid2")}get isULID(){return!!this._def.checks.find((o)=>o.kind==="ulid")}get isIP(){return!!this._def.checks.find((o)=>o.kind==="ip")}get isBase64(){return!!this._def.checks.find((o)=>o.kind==="base64")}get minLength(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o}get maxLength(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o}}Dn.create=(o)=>{var n;return new Dn({checks:[],typeName:e.ZodString,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...oo(o)})};class Tt extends no{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(o){if(this._def.coerce)o.data=Number(o.data);if(this._getType(o)!==B.number){const f=this._getOrReturnCtx(o);return L(f,{code:z.invalid_type,expected:B.number,received:f.parsedType}),d}let t=void 0;const S=new lo;for(let f of this._def.checks)if(f.kind==="int"){if(!Ao.isInteger(o.data))t=this._getOrReturnCtx(o,t),L(t,{code:z.invalid_type,expected:"integer",received:"float",message:f.message}),S.dirty()}else if(f.kind==="min"){if(f.inclusive?o.data<f.value:o.data<=f.value)t=this._getOrReturnCtx(o,t),L(t,{code:z.too_small,minimum:f.value,type:"number",inclusive:f.inclusive,exact:!1,message:f.message}),S.dirty()}else if(f.kind==="max"){if(f.inclusive?o.data>f.value:o.data>=f.value)t=this._getOrReturnCtx(o,t),L(t,{code:z.too_big,maximum:f.value,type:"number",inclusive:f.inclusive,exact:!1,message:f.message}),S.dirty()}else if(f.kind==="multipleOf"){if(NR(o.data,f.value)!==0)t=this._getOrReturnCtx(o,t),L(t,{code:z.not_multiple_of,multipleOf:f.value,message:f.message}),S.dirty()}else if(f.kind==="finite"){if(!Number.isFinite(o.data))t=this._getOrReturnCtx(o,t),L(t,{code:z.not_finite,message:f.message}),S.dirty()}else Ao.assertNever(f);return{status:S.value,value:o.data}}gte(o,n){return this.setLimit("min",o,!0,q.toString(n))}gt(o,n){return this.setLimit("min",o,!1,q.toString(n))}lte(o,n){return this.setLimit("max",o,!0,q.toString(n))}lt(o,n){return this.setLimit("max",o,!1,q.toString(n))}setLimit(o,n,t,S){return new Tt({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:t,message:q.toString(S)}]})}_addCheck(o){return new Tt({...this._def,checks:[...this._def.checks,o]})}int(o){return this._addCheck({kind:"int",message:q.toString(o)})}positive(o){return this._addCheck({kind:"min",value:0,inclusive:!1,message:q.toString(o)})}negative(o){return this._addCheck({kind:"max",value:0,inclusive:!1,message:q.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:0,inclusive:!0,message:q.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:0,inclusive:!0,message:q.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:q.toString(n)})}finite(o){return this._addCheck({kind:"finite",message:q.toString(o)})}safe(o){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:q.toString(o)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:q.toString(o)})}get minValue(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o}get maxValue(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o}get isInt(){return!!this._def.checks.find((o)=>o.kind==="int"||o.kind==="multipleOf"&&Ao.isInteger(o.value))}get isFinite(){let o=null,n=null;for(let t of this._def.checks)if(t.kind==="finite"||t.kind==="int"||t.kind==="multipleOf")return!0;else if(t.kind==="min"){if(n===null||t.value>n)n=t.value}else if(t.kind==="max"){if(o===null||t.value<o)o=t.value}return Number.isFinite(n)&&Number.isFinite(o)}}Tt.create=(o)=>{return new Tt({checks:[],typeName:e.ZodNumber,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...oo(o)})};class Mt extends no{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(o){if(this._def.coerce)o.data=BigInt(o.data);if(this._getType(o)!==B.bigint){const f=this._getOrReturnCtx(o);return L(f,{code:z.invalid_type,expected:B.bigint,received:f.parsedType}),d}let t=void 0;const S=new lo;for(let f of this._def.checks)if(f.kind==="min"){if(f.inclusive?o.data<f.value:o.data<=f.value)t=this._getOrReturnCtx(o,t),L(t,{code:z.too_small,type:"bigint",minimum:f.value,inclusive:f.inclusive,message:f.message}),S.dirty()}else if(f.kind==="max"){if(f.inclusive?o.data>f.value:o.data>=f.value)t=this._getOrReturnCtx(o,t),L(t,{code:z.too_big,type:"bigint",maximum:f.value,inclusive:f.inclusive,message:f.message}),S.dirty()}else if(f.kind==="multipleOf"){if(o.data%f.value!==BigInt(0))t=this._getOrReturnCtx(o,t),L(t,{code:z.not_multiple_of,multipleOf:f.value,message:f.message}),S.dirty()}else Ao.assertNever(f);return{status:S.value,value:o.data}}gte(o,n){return this.setLimit("min",o,!0,q.toString(n))}gt(o,n){return this.setLimit("min",o,!1,q.toString(n))}lte(o,n){return this.setLimit("max",o,!0,q.toString(n))}lt(o,n){return this.setLimit("max",o,!1,q.toString(n))}setLimit(o,n,t,S){return new Mt({...this._def,checks:[...this._def.checks,{kind:o,value:n,inclusive:t,message:q.toString(S)}]})}_addCheck(o){return new Mt({...this._def,checks:[...this._def.checks,o]})}positive(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:q.toString(o)})}negative(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:q.toString(o)})}nonpositive(o){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:q.toString(o)})}nonnegative(o){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:q.toString(o)})}multipleOf(o,n){return this._addCheck({kind:"multipleOf",value:o,message:q.toString(n)})}get minValue(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o}get maxValue(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o}}Mt.create=(o)=>{var n;return new Mt({checks:[],typeName:e.ZodBigInt,coerce:(n=o===null||o===void 0?void 0:o.coerce)!==null&&n!==void 0?n:!1,...oo(o)})};class vt extends no{_parse(o){if(this._def.coerce)o.data=Boolean(o.data);if(this._getType(o)!==B.boolean){const t=this._getOrReturnCtx(o);return L(t,{code:z.invalid_type,expected:B.boolean,received:t.parsedType}),d}return on(o.data)}}vt.create=(o)=>{return new vt({typeName:e.ZodBoolean,coerce:(o===null||o===void 0?void 0:o.coerce)||!1,...oo(o)})};class _t extends no{_parse(o){if(this._def.coerce)o.data=new Date(o.data);if(this._getType(o)!==B.date){const f=this._getOrReturnCtx(o);return L(f,{code:z.invalid_type,expected:B.date,received:f.parsedType}),d}if(isNaN(o.data.getTime())){const f=this._getOrReturnCtx(o);return L(f,{code:z.invalid_date}),d}const t=new lo;let S=void 0;for(let f of this._def.checks)if(f.kind==="min"){if(o.data.getTime()<f.value)S=this._getOrReturnCtx(o,S),L(S,{code:z.too_small,message:f.message,inclusive:!0,exact:!1,minimum:f.value,type:"date"}),t.dirty()}else if(f.kind==="max"){if(o.data.getTime()>f.value)S=this._getOrReturnCtx(o,S),L(S,{code:z.too_big,message:f.message,inclusive:!0,exact:!1,maximum:f.value,type:"date"}),t.dirty()}else Ao.assertNever(f);return{status:t.value,value:new Date(o.data.getTime())}}_addCheck(o){return new _t({...this._def,checks:[...this._def.checks,o]})}min(o,n){return this._addCheck({kind:"min",value:o.getTime(),message:q.toString(n)})}max(o,n){return this._addCheck({kind:"max",value:o.getTime(),message:q.toString(n)})}get minDate(){let o=null;for(let n of this._def.checks)if(n.kind==="min"){if(o===null||n.value>o)o=n.value}return o!=null?new Date(o):null}get maxDate(){let o=null;for(let n of this._def.checks)if(n.kind==="max"){if(o===null||n.value<o)o=n.value}return o!=null?new Date(o):null}}_t.create=(o)=>{return new _t({checks:[],coerce:(o===null||o===void 0?void 0:o.coerce)||!1,typeName:e.ZodDate,...oo(o)})};class BS extends no{_parse(o){if(this._getType(o)!==B.symbol){const t=this._getOrReturnCtx(o);return L(t,{code:z.invalid_type,expected:B.symbol,received:t.parsedType}),d}return on(o.data)}}BS.create=(o)=>{return new BS({typeName:e.ZodSymbol,...oo(o)})};class qt extends no{_parse(o){if(this._getType(o)!==B.undefined){const t=this._getOrReturnCtx(o);return L(t,{code:z.invalid_type,expected:B.undefined,received:t.parsedType}),d}return on(o.data)}}qt.create=(o)=>{return new qt({typeName:e.ZodUndefined,...oo(o)})};class pt extends no{_parse(o){if(this._getType(o)!==B.null){const t=this._getOrReturnCtx(o);return L(t,{code:z.invalid_type,expected:B.null,received:t.parsedType}),d}return on(o.data)}}pt.create=(o)=>{return new pt({typeName:e.ZodNull,...oo(o)})};class wt extends no{constructor(){super(...arguments);this._any=!0}_parse(o){return on(o.data)}}wt.create=(o)=>{return new wt({typeName:e.ZodAny,...oo(o)})};class ft extends no{constructor(){super(...arguments);this._unknown=!0}_parse(o){return on(o.data)}}ft.create=(o)=>{return new ft({typeName:e.ZodUnknown,...oo(o)})};class bn extends no{_parse(o){const n=this._getOrReturnCtx(o);return L(n,{code:z.invalid_type,expected:B.never,received:n.parsedType}),d}}bn.create=(o)=>{return new bn({typeName:e.ZodNever,...oo(o)})};class cS extends no{_parse(o){if(this._getType(o)!==B.undefined){const t=this._getOrReturnCtx(o);return L(t,{code:z.invalid_type,expected:B.void,received:t.parsedType}),d}return on(o.data)}}cS.create=(o)=>{return new cS({typeName:e.ZodVoid,...oo(o)})};class Un extends no{_parse(o){const{ctx:n,status:t}=this._processInputParams(o),S=this._def;if(n.parsedType!==B.array)return L(n,{code:z.invalid_type,expected:B.array,received:n.parsedType}),d;if(S.exactLength!==null){const T=n.data.length>S.exactLength.value,M=n.data.length<S.exactLength.value;if(T||M)L(n,{code:T?z.too_big:z.too_small,minimum:M?S.exactLength.value:void 0,maximum:T?S.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:S.exactLength.message}),t.dirty()}if(S.minLength!==null){if(n.data.length<S.minLength.value)L(n,{code:z.too_small,minimum:S.minLength.value,type:"array",inclusive:!0,exact:!1,message:S.minLength.message}),t.dirty()}if(S.maxLength!==null){if(n.data.length>S.maxLength.value)L(n,{code:z.too_big,maximum:S.maxLength.value,type:"array",inclusive:!0,exact:!1,message:S.maxLength.message}),t.dirty()}if(n.common.async)return Promise.all([...n.data].map((T,M)=>{return S.type._parseAsync(new rn(n,T,n.path,M))})).then((T)=>{return lo.mergeArray(t,T)});const f=[...n.data].map((T,M)=>{return S.type._parseSync(new rn(n,T,n.path,M))});return lo.mergeArray(t,f)}get element(){return this._def.type}min(o,n){return new Un({...this._def,minLength:{value:o,message:q.toString(n)}})}max(o,n){return new Un({...this._def,maxLength:{value:o,message:q.toString(n)}})}length(o,n){return new Un({...this._def,exactLength:{value:o,message:q.toString(n)}})}nonempty(o){return this.min(1,o)}}Un.create=(o,n)=>{return new Un({type:o,minLength:null,maxLength:null,exactLength:null,typeName:e.ZodArray,...oo(n)})};class Qo extends no{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const o=this._def.shape(),n=Ao.objectKeys(o);return this._cached={shape:o,keys:n}}_parse(o){if(this._getType(o)!==B.object){const k=this._getOrReturnCtx(o);return L(k,{code:z.invalid_type,expected:B.object,received:k.parsedType}),d}const{status:t,ctx:S}=this._processInputParams(o),{shape:f,keys:T}=this._getCached(),M=[];if(!(this._def.catchall instanceof bn&&this._def.unknownKeys==="strip")){for(let k in S.data)if(!T.includes(k))M.push(k)}const F=[];for(let k of T){const A=f[k],$=S.data[k];F.push({key:{status:"valid",value:k},value:A._parse(new rn(S,$,S.path,k)),alwaysSet:k in S.data})}if(this._def.catchall instanceof bn){const k=this._def.unknownKeys;if(k==="passthrough")for(let A of M)F.push({key:{status:"valid",value:A},value:{status:"valid",value:S.data[A]}});else if(k==="strict"){if(M.length>0)L(S,{code:z.unrecognized_keys,keys:M}),t.dirty()}else if(k==="strip");else throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const k=this._def.catchall;for(let A of M){const $=S.data[A];F.push({key:{status:"valid",value:A},value:k._parse(new rn(S,$,S.path,A)),alwaysSet:A in S.data})}}if(S.common.async)return Promise.resolve().then(async()=>{const k=[];for(let A of F){const $=await A.key,O=await A.value;k.push({key:$,value:O,alwaysSet:A.alwaysSet})}return k}).then((k)=>{return lo.mergeObjectSync(t,k)});else return lo.mergeObjectSync(t,F)}get shape(){return this._def.shape()}strict(o){return q.errToObj,new Qo({...this._def,unknownKeys:"strict",...o!==void 0?{errorMap:(n,t)=>{var S,f,T,M;const F=(T=(f=(S=this._def).errorMap)===null||f===void 0?void 0:f.call(S,n,t).message)!==null&&T!==void 0?T:t.defaultError;if(n.code==="unrecognized_keys")return{message:(M=q.errToObj(o).message)!==null&&M!==void 0?M:F};return{message:F}}}:{}})}strip(){return new Qo({...this._def,unknownKeys:"strip"})}passthrough(){return new Qo({...this._def,unknownKeys:"passthrough"})}extend(o){return new Qo({...this._def,shape:()=>({...this._def.shape(),...o})})}merge(o){return new Qo({unknownKeys:o._def.unknownKeys,catchall:o._def.catchall,shape:()=>({...this._def.shape(),...o._def.shape()}),typeName:e.ZodObject})}setKey(o,n){return this.augment({[o]:n})}catchall(o){return new Qo({...this._def,catchall:o})}pick(o){const n={};return Ao.objectKeys(o).forEach((t)=>{if(o[t]&&this.shape[t])n[t]=this.shape[t]}),new Qo({...this._def,shape:()=>n})}omit(o){const n={};return Ao.objectKeys(this.shape).forEach((t)=>{if(!o[t])n[t]=this.shape[t]}),new Qo({...this._def,shape:()=>n})}deepPartial(){return Nt(this)}partial(o){const n={};return Ao.objectKeys(this.shape).forEach((t)=>{const S=this.shape[t];if(o&&!o[t])n[t]=S;else n[t]=S.optional()}),new Qo({...this._def,shape:()=>n})}required(o){const n={};return Ao.objectKeys(this.shape).forEach((t)=>{if(o&&!o[t])n[t]=this.shape[t];else{let f=this.shape[t];while(f instanceof Vn)f=f._def.innerType;n[t]=f}}),new Qo({...this._def,shape:()=>n})}keyof(){return nJ(Ao.objectKeys(this.shape))}}Qo.create=(o,n)=>{return new Qo({shape:()=>o,unknownKeys:"strip",catchall:bn.create(),typeName:e.ZodObject,...oo(n)})};Qo.strictCreate=(o,n)=>{return new Qo({shape:()=>o,unknownKeys:"strict",catchall:bn.create(),typeName:e.ZodObject,...oo(n)})};Qo.lazycreate=(o,n)=>{return new Qo({shape:o,unknownKeys:"strip",catchall:bn.create(),typeName:e.ZodObject,...oo(n)})};class Zt extends no{_parse(o){const{ctx:n}=this._processInputParams(o),t=this._def.options;function S(f){for(let M of f)if(M.result.status==="valid")return M.result;for(let M of f)if(M.result.status==="dirty")return n.common.issues.push(...M.ctx.common.issues),M.result;const T=f.map((M)=>new yn(M.ctx.common.issues));return L(n,{code:z.invalid_union,unionErrors:T}),d}if(n.common.async)return Promise.all(t.map(async(f)=>{const T={...n,common:{...n.common,issues:[]},parent:null};return{result:await f._parseAsync({data:n.data,path:n.path,parent:T}),ctx:T}})).then(S);else{let f=void 0;const T=[];for(let F of t){const k={...n,common:{...n.common,issues:[]},parent:null},A=F._parseSync({data:n.data,path:n.path,parent:k});if(A.status==="valid")return A;else if(A.status==="dirty"&&!f)f={result:A,ctx:k};if(k.common.issues.length)T.push(k.common.issues)}if(f)return n.common.issues.push(...f.ctx.common.issues),f.result;const M=T.map((F)=>new yn(F));return L(n,{code:z.invalid_union,unionErrors:M}),d}}get options(){return this._def.options}}Zt.create=(o,n)=>{return new Zt({options:o,typeName:e.ZodUnion,...oo(n)})};var pn=(o)=>{if(o instanceof gt)return pn(o.schema);else if(o instanceof Kn)return pn(o.innerType());else if(o instanceof lt)return[o.value];else if(o instanceof Ft)return o.options;else if(o instanceof et)return Ao.objectValues(o.enum);else if(o instanceof dt)return pn(o._def.innerType);else if(o instanceof qt)return[void 0];else if(o instanceof pt)return[null];else if(o instanceof Vn)return[void 0,...pn(o.unwrap())];else if(o instanceof Zn)return[null,...pn(o.unwrap())];else if(o instanceof Pf)return pn(o.unwrap());else if(o instanceof at)return pn(o.unwrap());else if(o instanceof ut)return pn(o._def.innerType);else return[]};class Zf extends no{_parse(o){const{ctx:n}=this._processInputParams(o);if(n.parsedType!==B.object)return L(n,{code:z.invalid_type,expected:B.object,received:n.parsedType}),d;const t=this.discriminator,S=n.data[t],f=this.optionsMap.get(S);if(!f)return L(n,{code:z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[t]}),d;if(n.common.async)return f._parseAsync({data:n.data,path:n.path,parent:n});else return f._parseSync({data:n.data,path:n.path,parent:n})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(o,n,t){const S=new Map;for(let f of n){const T=pn(f.shape[o]);if(!T.length)throw new Error(`A discriminator value for key \`${o}\` could not be extracted from all schema options`);for(let M of T){if(S.has(M))throw new Error(`Discriminator property ${String(o)} has duplicate value ${String(M)}`);S.set(M,f)}}return new Zf({typeName:e.ZodDiscriminatedUnion,discriminator:o,options:n,optionsMap:S,...oo(t)})}}class Pt extends no{_parse(o){const{status:n,ctx:t}=this._processInputParams(o),S=(f,T)=>{if(DM(f)||DM(T))return d;const M=VM(f.value,T.value);if(!M.valid)return L(t,{code:z.invalid_intersection_types}),d;if(UM(f)||UM(T))n.dirty();return{status:n.value,value:M.data}};if(t.common.async)return Promise.all([this._def.left._parseAsync({data:t.data,path:t.path,parent:t}),this._def.right._parseAsync({data:t.data,path:t.path,parent:t})]).then(([f,T])=>S(f,T));else return S(this._def.left._parseSync({data:t.data,path:t.path,parent:t}),this._def.right._parseSync({data:t.data,path:t.path,parent:t}))}}Pt.create=(o,n,t)=>{return new Pt({left:o,right:n,typeName:e.ZodIntersection,...oo(t)})};class Nn extends no{_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==B.array)return L(t,{code:z.invalid_type,expected:B.array,received:t.parsedType}),d;if(t.data.length<this._def.items.length)return L(t,{code:z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),d;if(!this._def.rest&&t.data.length>this._def.items.length)L(t,{code:z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty();const f=[...t.data].map((T,M)=>{const F=this._def.items[M]||this._def.rest;if(!F)return null;return F._parse(new rn(t,T,t.path,M))}).filter((T)=>!!T);if(t.common.async)return Promise.all(f).then((T)=>{return lo.mergeArray(n,T)});else return lo.mergeArray(n,f)}get items(){return this._def.items}rest(o){return new Nn({...this._def,rest:o})}}Nn.create=(o,n)=>{if(!Array.isArray(o))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Nn({items:o,typeName:e.ZodTuple,rest:null,...oo(n)})};class bS extends no{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==B.object)return L(t,{code:z.invalid_type,expected:B.object,received:t.parsedType}),d;const S=[],f=this._def.keyType,T=this._def.valueType;for(let M in t.data)S.push({key:f._parse(new rn(t,M,t.path,M)),value:T._parse(new rn(t,t.data[M],t.path,M)),alwaysSet:M in t.data});if(t.common.async)return lo.mergeObjectAsync(n,S);else return lo.mergeObjectSync(n,S)}get element(){return this._def.valueType}static create(o,n,t){if(n instanceof no)return new bS({keyType:o,valueType:n,typeName:e.ZodRecord,...oo(t)});return new bS({keyType:Dn.create(),valueType:o,typeName:e.ZodRecord,...oo(n)})}}class NS extends no{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==B.map)return L(t,{code:z.invalid_type,expected:B.map,received:t.parsedType}),d;const S=this._def.keyType,f=this._def.valueType,T=[...t.data.entries()].map(([M,F],k)=>{return{key:S._parse(new rn(t,M,t.path,[k,"key"])),value:f._parse(new rn(t,F,t.path,[k,"value"]))}});if(t.common.async){const M=new Map;return Promise.resolve().then(async()=>{for(let F of T){const k=await F.key,A=await F.value;if(k.status==="aborted"||A.status==="aborted")return d;if(k.status==="dirty"||A.status==="dirty")n.dirty();M.set(k.value,A.value)}return{status:n.value,value:M}})}else{const M=new Map;for(let F of T){const{key:k,value:A}=F;if(k.status==="aborted"||A.status==="aborted")return d;if(k.status==="dirty"||A.status==="dirty")n.dirty();M.set(k.value,A.value)}return{status:n.value,value:M}}}}NS.create=(o,n,t)=>{return new NS({valueType:n,keyType:o,typeName:e.ZodMap,...oo(t)})};class Kt extends no{_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.parsedType!==B.set)return L(t,{code:z.invalid_type,expected:B.set,received:t.parsedType}),d;const S=this._def;if(S.minSize!==null){if(t.data.size<S.minSize.value)L(t,{code:z.too_small,minimum:S.minSize.value,type:"set",inclusive:!0,exact:!1,message:S.minSize.message}),n.dirty()}if(S.maxSize!==null){if(t.data.size>S.maxSize.value)L(t,{code:z.too_big,maximum:S.maxSize.value,type:"set",inclusive:!0,exact:!1,message:S.maxSize.message}),n.dirty()}const f=this._def.valueType;function T(F){const k=new Set;for(let A of F){if(A.status==="aborted")return d;if(A.status==="dirty")n.dirty();k.add(A.value)}return{status:n.value,value:k}}const M=[...t.data.values()].map((F,k)=>f._parse(new rn(t,F,t.path,k)));if(t.common.async)return Promise.all(M).then((F)=>T(F));else return T(M)}min(o,n){return new Kt({...this._def,minSize:{value:o,message:q.toString(n)}})}max(o,n){return new Kt({...this._def,maxSize:{value:o,message:q.toString(n)}})}size(o,n){return this.min(o,n).max(o,n)}nonempty(o){return this.min(1,o)}}Kt.create=(o,n)=>{return new Kt({valueType:o,minSize:null,maxSize:null,typeName:e.ZodSet,...oo(n)})};class xt extends no{constructor(){super(...arguments);this.validate=this.implement}_parse(o){const{ctx:n}=this._processInputParams(o);if(n.parsedType!==B.function)return L(n,{code:z.invalid_type,expected:B.function,received:n.parsedType}),d;function t(M,F){return qf({data:M,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,vf(),it].filter((k)=>!!k),issueData:{code:z.invalid_arguments,argumentsError:F}})}function S(M,F){return qf({data:M,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,vf(),it].filter((k)=>!!k),issueData:{code:z.invalid_return_type,returnTypeError:F}})}const f={errorMap:n.common.contextualErrorMap},T=n.data;if(this._def.returns instanceof Xt){const M=this;return on(async function(...F){const k=new yn([]),A=await M._def.args.parseAsync(F,f).catch((w)=>{throw k.addIssue(t(F,w)),k}),$=await Reflect.apply(T,this,A);return await M._def.returns._def.type.parseAsync($,f).catch((w)=>{throw k.addIssue(S($,w)),k})})}else{const M=this;return on(function(...F){const k=M._def.args.safeParse(F,f);if(!k.success)throw new yn([t(F,k.error)]);const A=Reflect.apply(T,this,k.data),$=M._def.returns.safeParse(A,f);if(!$.success)throw new yn([S(A,$.error)]);return $.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...o){return new xt({...this._def,args:Nn.create(o).rest(ft.create())})}returns(o){return new xt({...this._def,returns:o})}implement(o){return this.parse(o)}strictImplement(o){return this.parse(o)}static create(o,n,t){return new xt({args:o?o:Nn.create([]).rest(ft.create()),returns:n||ft.create(),typeName:e.ZodFunction,...oo(t)})}}class gt extends no{get schema(){return this._def.getter()}_parse(o){const{ctx:n}=this._processInputParams(o);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}gt.create=(o,n)=>{return new gt({getter:o,typeName:e.ZodLazy,...oo(n)})};class lt extends no{_parse(o){if(o.data!==this._def.value){const n=this._getOrReturnCtx(o);return L(n,{received:n.data,code:z.invalid_literal,expected:this._def.value}),d}return{status:"valid",value:o.data}}get value(){return this._def.value}}lt.create=(o,n)=>{return new lt({value:o,typeName:e.ZodLiteral,...oo(n)})};class Ft extends no{constructor(){super(...arguments);CS.set(this,void 0)}_parse(o){if(typeof o.data!=="string"){const n=this._getOrReturnCtx(o),t=this._def.values;return L(n,{expected:Ao.joinValues(t),received:n.parsedType,code:z.invalid_type}),d}if(!pf(this,CS,"f"))u$(this,CS,new Set(this._def.values),"f");if(!pf(this,CS,"f").has(o.data)){const n=this._getOrReturnCtx(o),t=this._def.values;return L(n,{received:n.data,code:z.invalid_enum_value,options:t}),d}return on(o.data)}get options(){return this._def.values}get enum(){const o={};for(let n of this._def.values)o[n]=n;return o}get Values(){const o={};for(let n of this._def.values)o[n]=n;return o}get Enum(){const o={};for(let n of this._def.values)o[n]=n;return o}extract(o,n=this._def){return Ft.create(o,{...this._def,...n})}exclude(o,n=this._def){return Ft.create(this.options.filter((t)=>!o.includes(t)),{...this._def,...n})}}CS=new WeakMap;Ft.create=nJ;class et extends no{constructor(){super(...arguments);LS.set(this,void 0)}_parse(o){const n=Ao.getValidEnumValues(this._def.values),t=this._getOrReturnCtx(o);if(t.parsedType!==B.string&&t.parsedType!==B.number){const S=Ao.objectValues(n);return L(t,{expected:Ao.joinValues(S),received:t.parsedType,code:z.invalid_type}),d}if(!pf(this,LS,"f"))u$(this,LS,new Set(Ao.getValidEnumValues(this._def.values)),"f");if(!pf(this,LS,"f").has(o.data)){const S=Ao.objectValues(n);return L(t,{received:t.data,code:z.invalid_enum_value,options:S}),d}return on(o.data)}get enum(){return this._def.values}}LS=new WeakMap;et.create=(o,n)=>{return new et({values:o,typeName:e.ZodNativeEnum,...oo(n)})};class Xt extends no{unwrap(){return this._def.type}_parse(o){const{ctx:n}=this._processInputParams(o);if(n.parsedType!==B.promise&&n.common.async===!1)return L(n,{code:z.invalid_type,expected:B.promise,received:n.parsedType}),d;const t=n.parsedType===B.promise?n.data:Promise.resolve(n.data);return on(t.then((S)=>{return this._def.type.parseAsync(S,{path:n.path,errorMap:n.common.contextualErrorMap})}))}}Xt.create=(o,n)=>{return new Xt({type:o,typeName:e.ZodPromise,...oo(n)})};class Kn extends no{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===e.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(o){const{status:n,ctx:t}=this._processInputParams(o),S=this._def.effect||null,f={addIssue:(T)=>{if(L(t,T),T.fatal)n.abort();else n.dirty()},get path(){return t.path}};if(f.addIssue=f.addIssue.bind(f),S.type==="preprocess"){const T=S.transform(t.data,f);if(t.common.async)return Promise.resolve(T).then(async(M)=>{if(n.value==="aborted")return d;const F=await this._def.schema._parseAsync({data:M,path:t.path,parent:t});if(F.status==="aborted")return d;if(F.status==="dirty")return ht(F.value);if(n.value==="dirty")return ht(F.value);return F});else{if(n.value==="aborted")return d;const M=this._def.schema._parseSync({data:T,path:t.path,parent:t});if(M.status==="aborted")return d;if(M.status==="dirty")return ht(M.value);if(n.value==="dirty")return ht(M.value);return M}}if(S.type==="refinement"){const T=(M)=>{const F=S.refinement(M,f);if(t.common.async)return Promise.resolve(F);if(F instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return M};if(t.common.async===!1){const M=this._def.schema._parseSync({data:t.data,path:t.path,parent:t});if(M.status==="aborted")return d;if(M.status==="dirty")n.dirty();return T(M.value),{status:n.value,value:M.value}}else return this._def.schema._parseAsync({data:t.data,path:t.path,parent:t}).then((M)=>{if(M.status==="aborted")return d;if(M.status==="dirty")n.dirty();return T(M.value).then(()=>{return{status:n.value,value:M.value}})})}if(S.type==="transform")if(t.common.async===!1){const T=this._def.schema._parseSync({data:t.data,path:t.path,parent:t});if(!IS(T))return T;const M=S.transform(T.value,f);if(M instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:M}}else return this._def.schema._parseAsync({data:t.data,path:t.path,parent:t}).then((T)=>{if(!IS(T))return T;return Promise.resolve(S.transform(T.value,f)).then((M)=>({status:n.value,value:M}))});Ao.assertNever(S)}}Kn.create=(o,n,t)=>{return new Kn({schema:o,typeName:e.ZodEffects,effect:n,...oo(t)})};Kn.createWithPreprocess=(o,n,t)=>{return new Kn({schema:n,effect:{type:"preprocess",transform:o},typeName:e.ZodEffects,...oo(t)})};class Vn extends no{_parse(o){if(this._getType(o)===B.undefined)return on(void 0);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}Vn.create=(o,n)=>{return new Vn({innerType:o,typeName:e.ZodOptional,...oo(n)})};class Zn extends no{_parse(o){if(this._getType(o)===B.null)return on(null);return this._def.innerType._parse(o)}unwrap(){return this._def.innerType}}Zn.create=(o,n)=>{return new Zn({innerType:o,typeName:e.ZodNullable,...oo(n)})};class dt extends no{_parse(o){const{ctx:n}=this._processInputParams(o);let t=n.data;if(n.parsedType===B.undefined)t=this._def.defaultValue();return this._def.innerType._parse({data:t,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}dt.create=(o,n)=>{return new dt({innerType:o,typeName:e.ZodDefault,defaultValue:typeof n.default==="function"?n.default:()=>n.default,...oo(n)})};class ut extends no{_parse(o){const{ctx:n}=this._processInputParams(o),t={...n,common:{...n.common,issues:[]}},S=this._def.innerType._parse({data:t.data,path:t.path,parent:{...t}});if(jS(S))return S.then((f)=>{return{status:"valid",value:f.status==="valid"?f.value:this._def.catchValue({get error(){return new yn(t.common.issues)},input:t.data})}});else return{status:"valid",value:S.status==="valid"?S.value:this._def.catchValue({get error(){return new yn(t.common.issues)},input:t.data})}}removeCatch(){return this._def.innerType}}ut.create=(o,n)=>{return new ut({innerType:o,typeName:e.ZodCatch,catchValue:typeof n.catch==="function"?n.catch:()=>n.catch,...oo(n)})};class hS extends no{_parse(o){if(this._getType(o)!==B.nan){const t=this._getOrReturnCtx(o);return L(t,{code:z.invalid_type,expected:B.nan,received:t.parsedType}),d}return{status:"valid",value:o.data}}}hS.create=(o)=>{return new hS({typeName:e.ZodNaN,...oo(o)})};var hR=Symbol("zod_brand");class Pf extends no{_parse(o){const{ctx:n}=this._processInputParams(o),t=n.data;return this._def.type._parse({data:t,path:n.path,parent:n})}unwrap(){return this._def.type}}class xS extends no{_parse(o){const{status:n,ctx:t}=this._processInputParams(o);if(t.common.async)return(async()=>{const f=await this._def.in._parseAsync({data:t.data,path:t.path,parent:t});if(f.status==="aborted")return d;if(f.status==="dirty")return n.dirty(),ht(f.value);else return this._def.out._parseAsync({data:f.value,path:t.path,parent:t})})();else{const S=this._def.in._parseSync({data:t.data,path:t.path,parent:t});if(S.status==="aborted")return d;if(S.status==="dirty")return n.dirty(),{status:"dirty",value:S.value};else return this._def.out._parseSync({data:S.value,path:t.path,parent:t})}}static create(o,n){return new xS({in:o,out:n,typeName:e.ZodPipeline})}}class at extends no{_parse(o){const n=this._def.innerType._parse(o),t=(S)=>{if(IS(S))S.value=Object.freeze(S.value);return S};return jS(n)?n.then((S)=>t(S)):t(n)}unwrap(){return this._def.innerType}}at.create=(o,n)=>{return new at({innerType:o,typeName:e.ZodReadonly,...oo(n)})};var xR={object:Qo.lazycreate},e;(function(o){o.ZodString="ZodString",o.ZodNumber="ZodNumber",o.ZodNaN="ZodNaN",o.ZodBigInt="ZodBigInt",o.ZodBoolean="ZodBoolean",o.ZodDate="ZodDate",o.ZodSymbol="ZodSymbol",o.ZodUndefined="ZodUndefined",o.ZodNull="ZodNull",o.ZodAny="ZodAny",o.ZodUnknown="ZodUnknown",o.ZodNever="ZodNever",o.ZodVoid="ZodVoid",o.ZodArray="ZodArray",o.ZodObject="ZodObject",o.ZodUnion="ZodUnion",o.ZodDiscriminatedUnion="ZodDiscriminatedUnion",o.ZodIntersection="ZodIntersection",o.ZodTuple="ZodTuple",o.ZodRecord="ZodRecord",o.ZodMap="ZodMap",o.ZodSet="ZodSet",o.ZodFunction="ZodFunction",o.ZodLazy="ZodLazy",o.ZodLiteral="ZodLiteral",o.ZodEnum="ZodEnum",o.ZodEffects="ZodEffects",o.ZodNativeEnum="ZodNativeEnum",o.ZodOptional="ZodOptional",o.ZodNullable="ZodNullable",o.ZodDefault="ZodDefault",o.ZodCatch="ZodCatch",o.ZodPromise="ZodPromise",o.ZodBranded="ZodBranded",o.ZodPipeline="ZodPipeline",o.ZodReadonly="ZodReadonly"})(e||(e={}));var iR=(o,n={message:`Input not instance of ${o.name}`})=>tJ((t)=>t instanceof o,n),SJ=Dn.create,fJ=Tt.create,vR=hS.create,qR=Mt.create,TJ=vt.create,pR=_t.create,ZR=BS.create,PR=qt.create,gR=pt.create,lR=wt.create,eR=ft.create,dR=bn.create,uR=cS.create,aR=Un.create,iS=Qo.create,sR=Qo.strictCreate,o0=Zt.create,n0=Zf.create,t0=Pt.create,S0=Nn.create,f0=bS.create,T0=NS.create,M0=Kt.create,F0=xt.create,k0=gt.create,A0=lt.create,$0=Ft.create,J0=et.create,y0=Xt.create,e$=Kn.create,R0=Vn.create,O0=Zn.create,W0=Kn.createWithPreprocess,_0=xS.create,w0=()=>SJ().optional(),K0=()=>fJ().optional(),X0=()=>TJ().optional(),Y0={string:(o)=>Dn.create({...o,coerce:!0}),number:(o)=>Tt.create({...o,coerce:!0}),boolean:(o)=>vt.create({...o,coerce:!0}),bigint:(o)=>Mt.create({...o,coerce:!0}),date:(o)=>_t.create({...o,coerce:!0})},E0=d,Vo=Object.freeze({__proto__:null,defaultErrorMap:it,setErrorMap:GR,getErrorMap:vf,makeIssue:qf,EMPTY_PATH:zR,addIssueToContext:L,ParseStatus:lo,INVALID:d,DIRTY:ht,OK:on,isAborted:DM,isDirty:UM,isValid:IS,isAsync:jS,get util(){return Ao},get objectUtil(){return QM},ZodParsedType:B,getParsedType:St,ZodType:no,datetimeRegex:oJ,ZodString:Dn,ZodNumber:Tt,ZodBigInt:Mt,ZodBoolean:vt,ZodDate:_t,ZodSymbol:BS,ZodUndefined:qt,ZodNull:pt,ZodAny:wt,ZodUnknown:ft,ZodNever:bn,ZodVoid:cS,ZodArray:Un,ZodObject:Qo,ZodUnion:Zt,ZodDiscriminatedUnion:Zf,ZodIntersection:Pt,ZodTuple:Nn,ZodRecord:bS,ZodMap:NS,ZodSet:Kt,ZodFunction:xt,ZodLazy:gt,ZodLiteral:lt,ZodEnum:Ft,ZodNativeEnum:et,ZodPromise:Xt,ZodEffects:Kn,ZodTransformer:Kn,ZodOptional:Vn,ZodNullable:Zn,ZodDefault:dt,ZodCatch:ut,ZodNaN:hS,BRAND:hR,ZodBranded:Pf,ZodPipeline:xS,ZodReadonly:at,custom:tJ,Schema:no,ZodSchema:no,late:xR,get ZodFirstPartyTypeKind(){return e},coerce:Y0,any:lR,array:aR,bigint:qR,boolean:TJ,date:pR,discriminatedUnion:n0,effect:e$,enum:$0,function:F0,instanceof:iR,intersection:t0,lazy:k0,literal:A0,map:T0,nan:vR,nativeEnum:J0,never:dR,null:gR,nullable:O0,number:fJ,object:iS,oboolean:X0,onumber:K0,optional:R0,ostring:w0,pipeline:_0,preprocess:W0,promise:y0,record:f0,set:M0,strictObject:sR,string:SJ,symbol:ZR,transformer:e$,tuple:S0,undefined:PR,union:o0,unknown:eR,void:uR,NEVER:E0,ZodIssueCode:z,quotelessJson:ER,ZodError:yn});function MJ(o){const n=o.runtimeEnvStrict??o.runtimeEnv??process.env;if(o.emptyStringAsUndefined??!1){for(let[K,Q]of Object.entries(n))if(Q==="")delete n[K]}if(!!o.skipValidation)return n;const f=typeof o.client==="object"?o.client:{},T=typeof o.server==="object"?o.server:{},M=typeof o.shared==="object"?o.shared:{},F=iS(f),k=iS(T),A=iS(M),$=o.isServer??(typeof window==="undefined"||("Deno"in window)),O=F.merge(A),w=k.merge(A).merge(F),G=$?w.safeParse(n):O.safeParse(n),r=o.onValidationError??((K)=>{throw console.error("\u274C Invalid environment variables:",K.flatten().fieldErrors),new Error("Invalid environment variables")}),H=o.onInvalidAccess??((K)=>{throw new Error("\u274C Attempted to access a server-side environment variable on the client")});if(G.success===!1)return r(G.error);const D=(K)=>{if(!o.clientPrefix)return!0;return!K.startsWith(o.clientPrefix)&&!(K in A.shape)},I=(K)=>{return $||!D(K)},v=(K)=>{return K==="__esModule"||K==="$$typeof"},N=(o.extends??[]).reduce((K,Q)=>{return Object.assign(K,Q)},{}),P=Object.assign(G.data,N);return new Proxy(P,{get(K,Q){if(typeof Q!=="string")return;if(v(Q))return;if(!I(Q))return H(Q);return Reflect.get(K,Q)}})}var Pn=MJ({isServer:typeof window==="undefined",server:{POSTGRES_USER:Vo.string(),POSTGRES_PASSWORD:Vo.string(),POSTGRES_DATABASE:Vo.string(),POSTGRES_HOST:Vo.string(),POSTGRES_PORT:Vo.string().transform((o)=>Number.parseInt(o,10)),BACKEND_PORT:Vo.string().transform((o)=>Number.parseInt(o,10)),RUN_WORKERS_FROM_SOURCE:Vo.union([Vo.literal("true"),Vo.literal("false")]).optional().transform((o)=>o==="true"),FRONTEND_PORT:Vo.string().transform((o)=>Number.parseInt(o,10)),FRONTEND_ORIGINS:Vo.string().transform((o)=>Uo(o)).pipe(Vo.array(Vo.string())),OPENAI_API_KEY:Vo.string().optional()},clientPrefix:"VITE_",client:{VITE_BACKEND_ORIGIN:Vo.string()},runtimeEnv:import.meta.env,emptyStringAsUndefined:!0});var CM={};Fy(CM,{users:()=>Yt,userChanges:()=>z0,untrackedUserColumnNames:()=>G0,twoFactorMethod:()=>$J,trackedUserColumnName:()=>AJ,trackableUserColumnNames:()=>kJ,role:()=>FJ,players:()=>rM,passwordResetAttempts:()=>m0,loginHistory:()=>H0,games:()=>gf,banishedIps:()=>vS});var FJ=kf("role",["admin","user"]),Yt=ot("users",{id:$n().primaryKey().defaultRandom(),username:io({length:16}).notNull(),email:io({length:254}).notNull(),hash:io({length:64}).notNull(),salt:io({length:36}).notNull(),createdAt:mn({withTimezone:!0}).notNull().defaultNow(),createdIp:io({length:45}).notNull(),isActive:XS().notNull().default(!1),verifiedAt:mn({withTimezone:!0}),userRole:FJ().default("user")},(o)=>({usersUsernameUnique:YM().on(o.username),usersEmailUnique:YM().on(o.email)})),G0=["id","createdAt","createdIp","isActive","salt","verifiedAt"],kJ=["username","email","hash","userRole"],AJ=kf("trackedUserColumnName",kJ),z0=ot("userChanges",{id:$n().primaryKey().defaultRandom(),userId:$n().notNull().references(()=>Yt.id),changedAt:mn({withTimezone:!0}).notNull().defaultNow(),changedIp:io({length:45}).notNull(),changedColumn:AJ().notNull(),oldValue:io({length:255}),newValue:io({length:255})}),gf=ot("games",{id:$n("id").primaryKey().defaultRandom()}),rM=ot("players",{userId:$n().notNull().references(()=>Yt.id),gameId:$n().notNull().references(()=>gf.id),score:_f().notNull()},(o)=>({pk:R$({columns:[o.userId,o.gameId]})})),H0=ot("loginHistory",{id:$n().primaryKey().defaultRandom(),userId:$n().references(()=>Yt.id),loginTime:mn({withTimezone:!0}).notNull().defaultNow(),ipAddress:io({length:45}).notNull(),userAgent:io({length:1024}),successful:XS().notNull().default(!1)}),$J=kf("twoFactorMethod",["email","phone"]),m0=ot("passwordResetAttempts",{id:$n().primaryKey().defaultRandom(),userId:$n().notNull().references(()=>Yt.id),requestedIp:io({length:45}).notNull(),requestedAt:mn({withTimezone:!0}).notNull().defaultNow(),succeededIp:io({length:45}),succeededAt:mn({withTimezone:!0}),verificationMethod:$J().notNull()}),vS=ot("banishedIps",{ip:io({length:45}).primaryKey(),reason:io({length:2048}).notNull(),banishedAt:mn({withTimezone:!0}).notNull().defaultNow(),banishedUntil:mn({withTimezone:!0})});var __dirname="/home/runner/work/wayforge/wayforge/apps/tempest.games/src/database";class LM{options;sql;drizzle;observers=new Map;async setupTriggersAndNotifications(){await this.sql.file(Q0.resolve(__dirname,"notify_update.sql"));const o=[Wn(Yt),Wn(gf),Wn(rM)];await this.sql`SELECT create_notify_triggers(${this.sql.array(o)})`,await this.sql.listen("table_update",(n)=>{const t=n.split(","),S=t[0],f=t[1],T=`${S}("${f}")`;if(this.observers.has(T))this.observers.get(T).next(T)})}constructor(o={host:Pn.POSTGRES_HOST,port:Pn.POSTGRES_PORT,user:Pn.POSTGRES_USER,password:Pn.POSTGRES_PASSWORD,database:Pn.POSTGRES_DATABASE}){this.options=o,this.sql=Bt(o),this.drizzle=xf(this.sql,{schema:CM})}observe(o,n){if(!this.observers.has(o))this.observers.set(o,new s);this.observers.get(o).subscribe("SINGLETON",n)}}var lf={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"},IM=PM(lf).map(([o])=>Vo.literal(Number(o))),D0=Vo.union([IM[0],IM[1],...IM]),JJ=Vo.tuple([D0,Vo.string()]);function BM(){Cn.logger.info("\uD83D\uDEEC frontend server exiting"),process.exit(0)}var Cn=new HT;Cn.logger.info(" ready");var jM=RJ(import.meta.dir,"..","app"),C0=new LM;r0({port:Pn.FRONTEND_PORT??3333,async fetch(o,n){try{const t=new Date,S=new URL(o.url),f=n.requestIP(o)?.address??"??";Cn.logger.info(t,f,o.method,S.pathname);const[T]=await C0.drizzle.select({banishedUntil:vS.banishedUntil}).from(vS).where(Ct(vS.ip,f)).limit(1),M=T?.banishedUntil===null,F=T?.banishedUntil&&T.banishedUntil>t;if(M||F)throw Cn.logger.info(`\uD83D\uDE45 request from banned ip ${f}`),[403,f];if(S.pathname==="/")return new Response(Bun.file(RJ(jM,"index.html")));if(S.pathname==="/index.html")return Response.redirect("/");const k=U0(jM,S.pathname),A=V0(k);if(!A.startsWith(jM))throw[403,"Access Denied"];if(!await yJ(A).exists())return Response.redirect("/");return new Response(yJ(A))}catch(t){const S=JJ.safeParse(t);if(S.success){const[f,T]=S.data,F=`${lf[f]}. ${T}`;return Cn.logger.info(`\u274C ${f}: ${F}`),new Response(F,{status:f})}if(t instanceof Error)Cn.logger.error(t.message);else{const f=Ut(t);Cn.logger.error("frontend server threw",f)}return new Response(lf[500],{status:500})}}});process.on("SIGINT",()=>{Cn.logger.info("\u2757 received SIGINT; exiting gracefully"),BM()});process.on("SIGTERM",()=>{Cn.logger.info("\u2757 received SIGTERM; exiting gracefully"),BM()});process.on("exit",()=>{Cn.logger.info("\u2757 received exit; exiting gracefully"),BM()});Cn.logger.info(`\uD83D\uDEEB frontend server running at http://localhost:${Pn.FRONTEND_PORT??3333}/`);