@rizom/ops 0.2.0-alpha.756 → 0.2.0-alpha.757

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.
@@ -400,8 +400,8 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
400
400
  `)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
401
401
  `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let r="end"in t.value?t.value.end:void 0;if((Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment")r?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){iy(o,t.start),o.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,o=r&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",n=[];if(o&&t.sep&&!t.value){let i=[];for(let s=0;s<t.sep.length;++s){let a=t.sep[s];switch(a.type){case"newline":i.push(s);break;case"space":break;case"comment":if(a.indent>e.indent)i.length=0;break;default:i.length=0}}if(i.length>=2)n=t.sep.splice(i[1])}switch(this.type){case"anchor":case"tag":if(o||t.value)n.push(this.sourceToken),e.items.push({start:n}),this.onKeyLine=!0;else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"explicit-key-ind":if(!t.sep&&!t.explicitKey)t.start.push(this.sourceToken),t.explicitKey=!0;else if(o||t.value)n.push(this.sourceToken),e.items.push({start:n,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(!t.sep)if(Ui(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let i=Yc(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Ui(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]});else if(D6(t.key)&&!Ui(t.sep,"newline")){let i=Yc(t.start),s=t.key,a=t.sep;a.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:s,sep:a}]})}else if(n.length>0)t.sep=t.sep.concat(n,this.sourceToken);else t.sep.push(this.sourceToken);else if(!t.sep)Object.assign(t,{key:null,sep:[this.sourceToken]});else if(t.value||o)e.items.push({start:n,key:null,sep:[this.sourceToken]});else if(Ui(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else t.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);if(o||t.value)e.items.push({start:n,key:i,sep:[]}),this.onKeyLine=!0;else if(t.sep)this.stack.push(i);else Object.assign(t,{key:i,sep:[]}),this.onKeyLine=!0;return}default:{let i=this.startBlockValue(e);if(i){if(i.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Ui(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(r)e.items.push({start:n});this.stack.push(i);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let r="end"in t.value?t.value.end:void 0;if((Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment")r?.push(this.sourceToken);else e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){iy(o,t.start),o.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;if(t.value||Ui(t.start,"seq-item-ind"))e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!t||t.sep)e.items.push({start:[this.sourceToken]});else t.start.push(this.sourceToken);return;case"map-value-ind":if(!t||t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!t||t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);if(!t||t.value)e.items.push({start:[],key:o,sep:[]});else if(t.sep)this.stack.push(o);else Object.assign(t,{key:o,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);if(r)this.stack.push(r);else yield*this.pop(),yield*this.step()}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let o=oy(r),n=Yc(o);N6(e);let i=e.end.splice(1,e.end.length);i.push(this.sourceToken);let s={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=s}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
402
402
  `)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
403
- `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=oy(e),r=Yc(t);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=oy(e),r=Yc(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){if(this.type!=="comment")return!1;if(this.indent<=t)return!1;return e.every((r)=>r.type==="newline"||r.type==="space")}*documentEnd(e){if(this.type!=="doc-mode"){if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}mle.Parser=L6});var M6=ge(function(_le){var B6=aR(),gle=tp(),ap=rp(),yle=yA(),ble=qe(),Sle=yR(),j6=bR();function Z6(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Sle.LineCounter||null,prettyErrors:t}}function vle(e,t={}){let{lineCounter:r,prettyErrors:o}=Z6(t),n=new j6.Parser(r?.addNewLine),i=new B6.Composer(t),s=Array.from(i.compose(n.parse(e)));if(o&&r)for(let a of s)a.errors.forEach(ap.prettifyError(e,r)),a.warnings.forEach(ap.prettifyError(e,r));if(s.length>0)return s;return Object.assign([],{empty:!0},i.streamInfo())}function U6(e,t={}){let{lineCounter:r,prettyErrors:o}=Z6(t),n=new j6.Parser(r?.addNewLine),i=new B6.Composer(t),s=null;for(let a of i.compose(n.parse(e),!0,e.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new ap.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(o&&r)s.errors.forEach(ap.prettifyError(e,r)),s.warnings.forEach(ap.prettifyError(e,r));return s}function wle(e,t,r){let o=void 0;if(typeof t==="function")o=t;else if(r===void 0&&t&&typeof t==="object")r=t;let n=U6(e,r);if(!n)return null;if(n.warnings.forEach((i)=>yle.warn(n.options.logLevel,i)),n.errors.length>0)if(n.options.logLevel!=="silent")throw n.errors[0];else n.errors=[];return n.toJS(Object.assign({reviver:o},r))}function xle(e,t,r){let o=null;if(typeof t==="function"||Array.isArray(t))o=t;else if(r===void 0&&t)r=t;if(typeof r==="string")r=r.length;if(typeof r==="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}if(ble.isDocument(e)&&!o)return e.toString(r);return new gle.Document(e,o,r).toString(r)}_le.parse=wle;_le.parseAllDocuments=vle;_le.parseDocument=U6;_le.stringify=xle});var Rle,Tle,$le,SR,Ole,Mi,Cle,Ple,zle,Nle,VCe,Dle,Lle,Ble,sy,q6,jle,Zle,Ule,Mle,qle,Fle,Jle,Kle,Hle,Vle,vn,Oo,Wle,Co,vR,Gle,Qle,Yle,Xle,eue,tue,rue,nue,oue,tn,iue,sue,aue;var Xc=v(()=>{Rle=aR(),Tle=tp(),$le=JA(),SR=rp(),Ole=Ud(),Mi=qe(),Cle=Li(),Ple=It(),zle=ji(),Nle=Zi(),VCe=ry(),Dle=gR(),Lle=yR(),Ble=bR(),sy=M6(),q6=jd();jle=Rle.Composer,Zle=Tle.Document,Ule=$le.Schema,Mle=SR.YAMLError,qle=SR.YAMLParseError,Fle=SR.YAMLWarning,Jle=Ole.Alias,Kle=Mi.isAlias,Hle=Mi.isCollection,Vle=Mi.isDocument,vn=Mi.isMap,Oo=Mi.isNode,Wle=Mi.isPair,Co=Mi.isScalar,vR=Mi.isSeq,Gle=Cle.Pair,Qle=Ple.Scalar,Yle=zle.YAMLMap,Xle=Nle.YAMLSeq,eue=Dle.Lexer,tue=Lle.LineCounter,rue=Ble.Parser,nue=sy.parse,oue=sy.parseAllDocuments,tn=sy.parseDocument,iue=sy.stringify,sue=q6.visit,aue=q6.visitAsync});var H6={};Lt(H6,{migratePilotDeploySecrets:()=>J6,migratePilotEnvSchema:()=>K6,migratePilotRepoProviderKeys:()=>hue,migrateProviderKeyFieldsYaml:()=>_R,openaiSelectorFor:()=>ER,renameProviderKeyFields:()=>qi});import{readdir as cue,readFile as wR,writeFile as F6}from"fs/promises";import{join as Po}from"path";function _R(e){let t=tn(e,{keepSourceTokens:!0});return qi(t)?t.toString({lineWidth:0}):e}function qi(e){if(!vn(e.contents))return!1;return e.contents.items.filter((r)=>{if(!Co(r.key)||typeof r.key.value!=="string")return!1;let o=lue[r.key.value];if(!o)return!1;if(r.key.value==="aiApiKey"&&Co(r.value)&&r.value.value===cy)r.value.value=ly;return r.key.value=o,!0}).length>0}function ER(e){return e===cy?ly:e}function J6(e){return e.replace(new RegExp(`^(\\s+- )${cy}$`,"m"),`$1${ly}`)}function K6(e){return e.replace(new RegExp(`^${cy}=`,"m"),`${ly}=`)}async function ay(e){try{return(await cue(e)).filter((r)=>r.endsWith(".yaml")).sort()}catch{return[]}}async function xR(e){try{return await wR(e,"utf8")}catch{return}}async function fue(e){let t=await ay(Po(e,"cohorts")),r=await Promise.all(t.map(async(i)=>{let s=yr(await wR(Po(e,"cohorts",i),"utf8"),due);return s.ok&&s.data.aiApiKeyOverride?s.data.members:[]})),o=(await ay(Po(e,"users"))).filter((i)=>!i.endsWith(".secrets.yaml")),n=await Promise.all(o.map(async(i)=>{let s=yr(await wR(Po(e,"users",i),"utf8"),uue);return s.ok&&s.data.aiApiKeyOverride?[i.replace(/\.yaml$/,"")]:[]}));return[...new Set([...r.flat(),...n.flat()])]}async function mue(e,t,r,o){let n=Po(e,"users",`${t}.secrets.yaml.age`),i=await xR(n);if(i===void 0)return!1;if(!r)throw Error(`users/${t}.secrets.yaml.age may hold the legacy AI key; set AGE_SECRET_KEY or AGE_SECRET_KEY_FILE to migrate it`);let s=new Ou;s.addIdentity(r);let a=await s.decrypt(yi.decode(i),"text"),l=_R(a);if(l===a)return!1;let u=new $u;return u.addRecipient(o),await F6(n,yi.encode(await u.encrypt(l))),!0}async function hue(e,t){let r=["pilot.yaml",...(await ay(Po(e,"cohorts"))).map((l)=>`cohorts/${l}`),...(await ay(Po(e,"users"))).filter((l)=>!l.endsWith(".secrets.yaml")).map((l)=>`users/${l}`)],o=await fue(e),n=await Promise.all([...r.map((l)=>({file:l,migrate:_R})),{file:".env.schema",migrate:K6},{file:"deploy/kamal/deploy.yml",migrate:J6}].map(async({file:l,migrate:u})=>{let d=Po(e,l),p=await xR(d);if(p===void 0)return[];let m=u(p);if(m===p)return[];return await F6(d,m),[l]})),i=yr(await xR(Po(e,"pilot.yaml"))??"",pue),s=oA(e,t,Lr(e)),a=o.length===0?[]:await Promise.all(o.map(async(l)=>{if(!i.ok)throw Error("pilot.yaml needs agePublicKey to re-encrypt secrets");return await mue(e,l,s,i.data.agePublicKey)?[`users/${l}.secrets.yaml.age`]:[]}));return[...n.flat(),...a.flat()]}var cy="AI_API_KEY",ly="OPENAI_API_KEY",lue,uue,due,pue;var uy=v(()=>{gi();vi();Vn();pe();Xc();sA();lue={aiApiKey:"openaiApiKey",aiApiKeyOverride:"openaiApiKeyOverride"};uue=c.looseObject({aiApiKeyOverride:c.string().optional()}),due=c.looseObject({members:c.array(c.string()).default([]),aiApiKeyOverride:c.string().optional()}),pue=c.looseObject({agePublicKey:c.string()})});function Q6(e){if(e==="core")return{bundles:["core","media","web","chat"]};if(e==="default")return{bundles:["core","media","automation","web","chat","site","publishing","federation"],add:["obsidian-vault"],remove:[...bue]};return{bundles:["core","media","automation","web","chat","site","publishing","federation"],add:["obsidian-vault"]}}function Sue(e){let t=gue.parse(e);return Qs.parse({brainVersion:t.brainVersion,bundleContract:Gs,...Q6(t.preset),githubOrg:t.githubOrg,contentRepoPrefix:t.contentRepoPrefix,domainSuffix:t.domainSuffix,openaiApiKey:ER(t.aiApiKey),gitSyncToken:t.gitSyncToken,contentRepoAdminToken:t.contentRepoAdminToken,agePublicKey:t.agePublicKey})}function vue(e){let t=yue.parse(e),r=t.presetOverride?Q6(t.presetOverride):void 0;return hn.parse({members:[...t.members],...t.brainVersionOverride?{brainVersionOverride:t.brainVersionOverride}:{},...r?{bundlesOverride:r.bundles,...r.add?{addOverride:r.add}:{},...r.remove?{removeOverride:r.remove}:{}}:{},...t.aiApiKeyOverride?{openaiApiKeyOverride:t.aiApiKeyOverride}:{},...t.gitSyncTokenOverride?{gitSyncTokenOverride:t.gitSyncTokenOverride}:{}})}function Y6(e){let t=tn(e,{keepSourceTokens:!0});if(t.errors.length>0)throw Error(`Invalid desired-state YAML: ${t.errors[0]?.message}`);if(!vn(t.contents))throw Error("Desired-state YAML must contain a mapping");return t}function IR(e,t){if(!vn(e.contents))return;return e.contents.items.find((r)=>Co(r.key)&&r.key.value===t)}function V6(e,t){if(!Oo(e)||!Oo(t))return;if(e.commentBefore!==void 0)t.commentBefore=e.commentBefore;if(e.comment!==void 0)t.comment=e.comment;if(e.spaceBefore!==void 0)t.spaceBefore=e.spaceBefore}function W6(e,t){if(!e||!Oo(t))return;let r=[Oo(e.key)?e.key.commentBefore:void 0,Oo(e.key)?e.key.comment:void 0,Oo(e.value)?e.value.commentBefore:void 0,Oo(e.value)?e.value.comment:void 0].filter((o)=>o!==void 0);if(r.length===0)return;t.commentBefore=[t.commentBefore,...r].filter((o)=>o!==void 0).join(`
404
- `)}function X6(e,t,r,o){if(!vn(e.contents))throw Error("Desired-state YAML must contain a mapping");let n=e.contents.items.findIndex((s)=>Co(s.key)&&s.key.value===t),i=e.createPair(r,[...o]);if(n>=0){let s=e.contents.items[n];V6(s?.key,i.key),V6(s?.value,i.value),e.contents.items.splice(n,1,i)}else e.contents.add(i);return i}function eM(e){let t=Y6(e),r=Sue(t.toJS()),o=IR(t,"schemaVersion"),n=IR(t,"model");W6(o,IR(t,"brainVersion")?.key),t.delete("schemaVersion"),t.set("bundleContract",Gs);let i=X6(t,"preset","bundles",r.bundles);if(W6(n,i.key),t.delete("model"),r.add)t.set("add",r.add);else t.delete("add");if(r.remove)t.set("remove",r.remove);else t.delete("remove");return qi(t),Qs.parse(t.toJS()),t.toString({lineWidth:0})}function tM(e){let t=Y6(e),r=vue(t.toJS());if(r.bundlesOverride)X6(t,"presetOverride","bundlesOverride",r.bundlesOverride);else t.delete("presetOverride"),t.delete("bundlesOverride");if(r.addOverride)t.set("addOverride",r.addOverride);else t.delete("addOverride");if(r.removeOverride)t.set("removeOverride",r.removeOverride);else t.delete("removeOverride");return qi(t),hn.parse(t.toJS()),t.toString({lineWidth:0})}var G6,cp,gue,yue,bue;var rM=v(()=>{uy();Vn();pe();Xc();Ao();G6=c.enum(["core","default","pro"]),cp=c.string().min(1),gue=c.strictObject({schemaVersion:c.literal(1),brainVersion:Ct,model:c.literal("rover"),githubOrg:c.string().min(1),contentRepoPrefix:c.string().min(1),domainSuffix:c.string().min(1),preset:G6,aiApiKey:cp,gitSyncToken:cp,contentRepoAdminToken:cp,agePublicKey:c.string().startsWith("age1").min(1)}),yue=c.strictObject({members:c.array(br).min(1),brainVersionOverride:Ct.optional(),presetOverride:G6.optional(),aiApiKeyOverride:cp.optional(),gitSyncTokenOverride:cp.optional()}).superRefine((e,t)=>{if(new Set(e.members).size!==e.members.length)t.addIssue({code:c.ZodIssueCode.custom,path:["members"],message:"cohort members must be unique"})}),bue=["series","portfolio","content-pipeline","social-media","newsletter","stock-photo"]});function oM(e,t){let r=tn(e,{keepSourceTokens:!0});if(r.errors.length>0||!vn(r.contents))throw Error(`Invalid ${t} YAML`);return r}function Iue(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function iM(e,t,r){if(!Iue(t,r.sourceBundles))throw Error(`${e} source bundles changed after review: expected [${r.sourceBundles.join(", ")}], received [${t.join(", ")}]`)}function sM(e){let t=yr(e,Eue);if(!t.ok)throw Error(`Invalid capability bundle review: ${t.error}`);return t.data}function aM(e,t){let r=oM(e,"pilot desired-state"),o=xue.parse(r.toJS());return iM("pilot.yaml",o.bundles,t),r.set("bundleContract",Gs),r.set("bundles",t.targetBundles),qi(r),Qs.parse(r.toJS()),r.toString({lineWidth:0})}function cM(e,t,r){let o=oM(e,`cohort ${t}`),n=_ue.parse(o.toJS());if(n.bundlesOverride===void 0){if(r!==void 0)throw Error(`Capability bundle review names inheriting cohort ${t}`)}else{if(r===void 0)throw Error(`Cohort ${t} has an explicit legacy bundle selection but no reviewed mapping`);iM(`cohort ${t}`,n.bundlesOverride,r),o.set("bundlesOverride",r.targetBundles)}return qi(o),hn.parse(o.toJS()),o.toString({lineWidth:0})}var wue,kR,dy,xue,_ue,nM,Eue;var lM=v(()=>{uy();Vn();pe();Xc();Ao();wue=c.enum(["core","site","publishing","team"]),kR=c.array(wue).min(1),dy=c.array(c.string().min(1)),xue=c.strictObject({brainVersion:Ct,bundles:kR,add:dy.optional(),remove:dy.optional(),githubOrg:c.string().min(1),contentRepoPrefix:c.string().min(1),domainSuffix:c.string().min(1),aiApiKey:c.string().min(1),gitSyncToken:c.string().min(1),contentRepoAdminToken:c.string().min(1),agePublicKey:c.string().startsWith("age1").min(1)}),_ue=c.strictObject({members:c.array(br).min(1),brainVersionOverride:Ct.optional(),bundlesOverride:kR.optional(),addOverride:dy.optional(),removeOverride:dy.optional(),aiApiKeyOverride:c.string().min(1).optional(),gitSyncTokenOverride:c.string().min(1).optional()}),nM=c.strictObject({sourceBundles:kR,targetBundles:c.array(jk).min(1)}),Eue=c.strictObject({bundleContract:c.literal(Gs),pilot:nM,cohorts:c.record(br,nM)})});var mM={};Lt(mM,{loadCapabilityBundleReview:()=>zue,loadReviewedSitePins:()=>Pue,parseReviewedSitePins:()=>fM,stageLegacyCrossover:()=>Due});import{access as kue,cp as Aue,mkdir as uM,readFile as tl,readdir as pM,writeFile as el}from"fs/promises";import{basename as Rue,join as Yn,relative as py,resolve as dM}from"path";import{fileURLToPath as Tue}from"url";function fM(e){let t=yr(e,$ue);if(!t.ok)throw Error(`Invalid reviewed site pins: ${t.error}`);return t.data.sites}async function Pue(e){return fM(await tl(e,"utf8"))}async function zue(e){return sM(await tl(e,"utf8"))}async function Nue(e,t){let r=Yn(e,"users"),o=(await pM(r,{withFileTypes:!0})).filter((s)=>s.isFile()&&/\.ya?ml$/.test(s.name)).map((s)=>s.name).sort(),n=new Set(Object.keys(t??{})),i=[];for(let s of o){let a=Yn(r,s),l=await tl(a,"utf8"),u=tn(l,{keepSourceTokens:!0});if(u.errors.length>0||!vn(u.contents))throw Error(`Invalid user desired-state YAML: ${s}`);let d=Oue.parse(u.toJS());if(!d.siteOverride)continue;let p=t?.[d.handle];if(!p)throw Error(`User ${d.handle} has a siteOverride but no reviewed site pin`);if(n.delete(d.handle),p.package!==d.siteOverride.package||p.theme!==d.siteOverride.theme)throw Error(`Reviewed site pin identity does not match user ${d.handle}`);if(d.siteOverride.version!==void 0&&d.siteOverride.version!==p.version)throw Error(`Reviewed site version does not match the existing pin for user ${d.handle}`);if(d.siteOverride.themeVersion!==void 0&&d.siteOverride.themeVersion!==p.themeVersion)throw Error(`Reviewed theme version does not match the existing pin for user ${d.handle}`);if(u.setIn(["siteOverride","version"],p.version),p.themeVersion!==void 0)u.setIn(["siteOverride","themeVersion"],p.themeVersion);else u.deleteIn(["siteOverride","themeVersion"]);ag.parse(u.toJS());let m=u.toString({lineWidth:0});if(m!==l)await el(a,m),i.push(py(e,a))}if(n.size>0)throw Error(`Reviewed site pins do not match site users: ${[...n].sort().join(", ")}`);return i}async function Due(e,t,r={}){let o=dM(e),n=dM(t);if(o===n||n.startsWith(`${o}/`))throw Error("Crossover output must be outside the source repository");await Aue(o,n,{recursive:!0,errorOnExist:!0,force:!1,filter:(A)=>{let O=Rue(A);return O!==".git"&&O!==".operator"&&O!==".brains-ops"&&O!==".turbo"&&O!=="dist"&&O!=="node_modules"&&O!==".env"&&O!==".env.local"&&!O.endsWith(".secrets.yaml")}});let i=[],s=Yn(n,"docs","canonical-crossover-record.md");try{await kue(s)}catch{await uM(Yn(n,"docs"),{recursive:!0}),await el(s,await tl(Cue,"utf8")),i.push("docs/canonical-crossover-record.md")}let a=Yn(n,"pilot.yaml"),l=await tl(a,"utf8"),d=tn(l).toJS();if(!Pd(d))throw Error(`${a} is not a YAML mapping`);let p=Array.isArray(d.bundles),m=r.bundleReview,h;if(p){if(!m)throw Error("Current canonical desired state requires an explicit capability bundle review manifest");h=aM(l,m.pilot)}else h=eM(l);await el(a,h),i.push("pilot.yaml");let b=Yn(n,"cohorts"),y=(await pM(b,{withFileTypes:!0})).filter((A)=>A.isFile()&&/\.ya?ml$/.test(A.name)).map((A)=>A.name).sort(),S=new Set(Object.keys(m?.cohorts??{}));for(let A of y){let O=Yn(b,A),L=await tl(O,"utf8"),z=A.replace(/\.ya?ml$/,""),K=m?.cohorts[z];if(K)S.delete(z);await el(O,p?cM(L,z,K):tM(L)),i.push(py(n,O))}if(p&&S.size>0)throw Error(`Capability bundle review names unknown cohorts: ${[...S].sort().join(", ")}`);i.push(...await Nue(n,r.sitePins));let x=await wt(n),_=dg(x.pilot.githubOrg);for(let A of x.users){let O=await _(A),L=Yn(n,"users",A.handle);if(await uM(L,{recursive:!0}),O.brainYaml){let z=Yn(L,"brain.yaml");await el(z,O.brainYaml),i.push(py(n,z))}if(O.envFile){let z=Yn(L,".env");await el(z,O.envFile),i.push(py(n,z))}}return await Pi(n,{registry:x}),i.push("views/users.md"),{outputDir:n,changedFiles:[...new Set(i)].sort()}}var $ue,Oue,Cue;var hM=v(()=>{Vn();zd();pe();Xc();eA();rM();lM();gn();Cd();Ao();$ue=c.strictObject({sites:c.record(br,Zk)}),Oue=c.object({handle:br,siteOverride:c.object({package:c.string().min(1),version:Ct.optional(),theme:c.string().min(1).optional(),themeVersion:Ct.optional()}).optional()}).passthrough(),Cue=Tue(new URL("../templates/rover-pilot/docs/canonical-crossover-record.md",import.meta.url))});var yM,Lue,Bue,jue,zo,lp,Zue,AR,Uue,Mue,gM,que,Fue,bM,$1e,SM;var fy=v(()=>{VI();yM=["primary","secondary"],Lue=c.custom((e)=>typeof e==="function","Expected a React component"),Bue=c.strictObject({show:c.boolean().optional(),label:c.string().min(1).optional(),slot:c.enum(yM).optional(),priority:c.number().optional()}),jue=c.strictObject({id:c.string().min(1),template:c.string().min(1),content:c.unknown().optional(),dataQuery:c.looseObject({entityType:c.string().optional(),template:c.string().optional(),query:c.record(c.string(),c.unknown()).optional()}).optional(),order:c.number().optional()}),zo=c.string().regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/,{message:"must be a language tag such as en or zh-TW"}),lp=c.strictObject({title:c.string().optional(),description:c.string().optional(),navigationLabel:c.string().optional()}),Zue=c.strictObject({id:c.string().min(1),path:c.string().startsWith("/"),title:c.string().optional(),pageLabel:c.string().optional(),description:c.string().optional(),sections:c.array(jue).optional(),layout:c.string().min(1).optional(),fullscreen:c.boolean().optional(),pluginId:c.string().optional(),sourceEntityType:c.string().optional(),external:c.boolean().optional(),navigation:Bue.optional(),translations:c.record(zo,lp).optional()}),AR=c.strictObject({label:c.string().min(1),pluralName:c.string().min(1).optional(),layout:c.string().min(1).optional(),detailTemplate:c.string().min(1).optional(),paginate:c.boolean().optional(),pageSize:c.number().int().positive().optional(),citable:c.boolean().optional(),navigation:c.strictObject({show:c.boolean().optional(),slot:c.enum(yM).optional(),priority:c.number().optional()}).optional()}),Uue=c.strictObject({schema:c.custom((e)=>e instanceof c.ZodType,"Expected a Zod schema"),component:c.custom((e)=>typeof e==="function","Expected a React component"),title:c.string().min(1),description:c.string(),requiredPermission:c.enum(["admin","trusted","public"]).optional(),fullscreen:c.boolean().optional(),dataSource:c.string().min(1).optional()}),Mue=c.custom((e)=>typeof e==="object"&&e!==null&&Reflect.get(e,"kind")==="rizom-data-source"&&typeof Reflect.get(e,"id")==="string"&&typeof Reflect.get(e,"fetch")==="function","Expected a fetching data source declared with defineDataSource"),gM=c.strictObject({namespace:c.string().min(1),sections:c.record(c.string(),Uue)}),que=c.record(c.string(),c.json()),Fue=c.record(c.string(),c.record(c.string(),que)),bM={layouts:c.record(c.string(),Lue).refine((e)=>typeof e.default==="function",{message:'Site layouts must include a "default" component'}),routes:c.array(Zue),content:Fue.optional(),sections:c.union([gM,c.array(gM)]).optional(),themeOverride:c.string().optional(),headScripts:c.array(c.string()).optional(),entityDisplay:c.record(c.string(),AR),staticAssets:c.record(c.string(),c.string()).optional(),languages:c.array(zo).min(1).optional(),dataSources:c.array(Mue).readonly().optional()},$1e=c.strictObject(bM).partial(),SM=c.strictObject(bM).superRefine((e,t)=>{let r=e.languages??[],o=new Set;for(let[u,d]of r.entries()){let p=d.toLowerCase();if(o.has(p))t.addIssue({code:"custom",path:["languages",u],message:`Language "${d}" is declared twice`});o.add(p)}let n=r.slice(1).map((u)=>`/${u.toLowerCase()}`),i=new Set;for(let[u,d]of e.routes.entries()){if(i.has(d.id))t.addIssue({code:"custom",path:["routes",u,"id"],message:`Duplicate route id "${d.id}"`});i.add(d.id);let p=d.path.toLowerCase(),m=n.find((b)=>p===b||p.startsWith(`${b}/`));if(m)t.addIssue({code:"custom",path:["routes",u,"path"],message:`Route path "${d.path}" is under ${m}, where another language's pages are built`});let h=d.layout??"default";if(!e.layouts[h])t.addIssue({code:"custom",path:["routes",u,"layout"],message:`Unknown layout "${h}"`});for(let[b,y]of(d.sections??[]).entries()){let S=/^([^:.\s]+)\.([^:.\s]+)$/.exec(y.template);if(S)t.addIssue({code:"custom",path:["routes",u,"sections",b,"template"],message:`Section template "${y.template}" is written "${S[1]}:${S[2]}"`})}}let s=Array.isArray(e.sections)?e.sections:e.sections?[e.sections]:[],a=new Map(s.map((u)=>[u.namespace,u]));if(a.size!==s.length)t.addIssue({code:"custom",path:["sections"],message:"Section group namespaces must be unique"});let l=new Set;for(let[u,d]of(e.dataSources??[]).entries()){if(l.has(d.id))t.addIssue({code:"custom",path:["dataSources",u],message:`Data source "${d.id}" is declared twice`});l.add(d.id)}for(let u of s)for(let[d,p]of Object.entries(u.sections))if(p.dataSource&&!l.has(p.dataSource))t.addIssue({code:"custom",path:["sections",u.namespace,d,"dataSource"],message:`Section "${u.namespace}:${d}" reads data source "${p.dataSource}", which the site does not declare`});for(let[u,d]of Object.entries(e.content??{})){let p=a.get(u);if(!p){t.addIssue({code:"custom",path:["content",u],message:`Content namespace "${u}" has no section group`});continue}for(let[m,h]of Object.entries(d)){let b=p.sections[m];if(!b){t.addIssue({code:"custom",path:["content",u,m],message:`Content section "${u}:${m}" is not defined`});continue}let y=b.schema.safeParse(h);if(!y.success)t.addIssue({code:"custom",path:["content",u,m],message:`Content does not satisfy the "${u}:${m}" schema: ${c.prettifyError(y.error)}`})}}})});var vM,wM,xM,my,_M,Kue,EM,IM,Hue,kM,AM,Vue,hy;var RR=v(()=>{Ot();pe();fy();fy();vM=c.object({id:c.string(),template:c.string(),content:c.unknown().optional(),dataQuery:c.looseObject({entityType:c.string().optional(),template:c.string().optional(),query:c.looseObject({id:c.string().optional(),limit:c.number().optional(),offset:c.number().optional()}).optional()}).optional(),order:c.number().optional()}),wM=["primary","secondary"],xM=c.object({show:c.boolean().default(!1),label:c.string().optional(),slot:c.enum(wM).default("primary"),priority:c.number().min(0).max(100).default(50)}).optional(),my=c.object({id:c.string(),path:c.string(),title:c.string().default(""),pageLabel:c.string().optional(),description:c.string().default(""),sections:c.array(vM).default([]),layout:c.string().default("default"),fullscreen:c.boolean().optional(),pluginId:c.string().optional(),sourceEntityType:c.string().optional(),external:c.boolean().optional(),navigation:xM,translations:c.record(zo,lp).optional(),languages:c.array(zo).optional()}),_M=c.object({routes:c.array(my),pluginId:c.string()}),Kue=we({channel:"plugin:site-builder:route:register",request:_M,response:c.void(),delivery:"command"}),EM=c.strictObject({}),IM=c.array(my),Hue=we({channel:"site-builder:routes:list",request:EM,response:IM,delivery:"request"}),kM=c.strictObject({}),AM=c.array(my),Vue=we({channel:"plugin:site-builder:pages",request:kM,response:AM,delivery:"collect"}),hy=c.object({label:c.string(),href:c.string(),priority:c.number()})});var RM,TM,$M,Wue;var OM=v(()=>{Ot();pe();RM=c.object({pluginId:c.string(),slotName:c.string(),render:c.custom((e)=>typeof e==="function"),priority:c.number().optional()}),TM=c.strictObject({}),$M=c.array(RM),Wue=we({channel:"plugin:site-builder:slots",request:TM,response:$M,delivery:"collect"})});var CM="site:metadata:updated",gy,PM,zM,rl,NM,Gue,Que,Yue;var TR=v(()=>{Ot();pe();RR();gy=c.object({heading:c.string().describe("Main CTA heading text"),subtitle:c.string().optional().describe("A line under the CTA heading"),buttonText:c.string().describe("Call-to-action button text"),buttonLink:c.string().describe("URL or anchor for the CTA button")}),PM=c.object({title:c.string().optional(),description:c.string().optional(),copyright:c.string().optional(),cta:gy.optional()}),zM=c.object({blurb:c.string().optional().describe("Short italic subtitle under the section title")}),rl=c.object({represents:c.enum(["brain","anchor"]).default("anchor").describe("Identity represented by the site"),title:c.string().describe("The site's title"),description:c.string().describe("The site's description"),url:c.string().optional().describe("Canonical site URL"),copyright:c.string().optional().describe("Copyright notice text"),logo:c.boolean().optional().describe("Whether to display logo instead of title text in header"),themeMode:c.enum(["light","dark"]).optional().describe("Default theme mode"),analyticsScript:c.string().optional().describe("Analytics script HTML"),cta:gy.optional().describe("Call-to-action configuration"),sections:c.record(c.string(),zM).optional().describe("Optional per-section blurbs, keyed by section id (e.g. 'essays', 'presentations', 'about'). Used by homepage templates that render editorial section headers."),translations:c.record(zo,PM).optional().describe("The site's title, description, copyright and call to action in its other languages, keyed by language tag. A site is built in a language only once it has one.")}),NM=c.strictObject({}),Gue=we({channel:"site:metadata:get",request:NM,response:rl,delivery:"request"}),Que=Ci(CM,rl),Yue=rl.extend({copyright:c.string(),navigation:c.object({primary:c.array(hy),secondary:c.array(hy)}),socialLinks:c.array(Bk).optional().describe("Social media links from profile metadata"),photo:c.string().optional().describe("The anchor's photo, as ![alt](entity://image/<id>)")})});var J1e;var $R=v(()=>{pe();J1e=c.record(c.string(),c.unknown())});var up=v(()=>{$R()});var DM=v(()=>{Ot();up()});var LM=v(()=>{up();Ot()});var BM=v(()=>{up();Ot()});var aPe;var jM=v(()=>{pe();aPe=c.record(c.string(),c.unknown())});var uPe;var ZM=v(()=>{pe();Pc();uPe=c.record(c.string(),c.unknown())});var UM=v(()=>{Pc()});var MM=v(()=>{up();DM();LM();BM();jM();ZM();UM();$R()});var cde;var qM=v(()=>{pe();cde=c.object({slug:c.string(),title:c.string(),type:c.string(),entityId:c.string(),contentHash:c.string()})});var CR=v(()=>{MM();qM()});var FM=v(()=>{CR();pe()});var PR=()=>{};var lde,ude,dde;var by=v(()=>{pe();Ot();lde={url:c.string(),typeLabel:c.string(),listUrl:c.string(),listLabel:c.string()},ude={url:c.string().nullable().default(null),typeLabel:c.string().nullable().default(null),listUrl:c.string().nullable().default(null),listLabel:c.string().nullable().default(null)},dde=c.object({name:c.string(),description:c.string(),schema:c.unknown(),basePrompt:c.string().optional(),useKnowledgeContext:c.boolean().optional(),requiredPermission:c.enum(["admin","trusted","public"]),formatter:c.unknown().optional(),overlayFormatter:c.unknown().optional(),layout:c.object({component:c.unknown().optional(),fullscreen:c.boolean().optional(),formats:c.unknown().optional()}).optional(),dataSourceId:c.string().optional()})});var Sy=v(()=>{by()});var HM=v(()=>{Sy()});var zR=()=>{};var fde,mde,nl,VM,hde;var WM=v(()=>{Ot();pe();zR();fde=c.enum(["admin","trusted","public"]),mde=c.enum(["create","update","delete","extract","publish"]),nl=c.enum(["never","admin","trusted","public"]),VM=c.strictObject({create:nl.optional(),update:nl.optional(),delete:nl.optional(),extract:nl.optional(),publish:nl.optional()}),hde=c.record(c.string(),VM)});var GM=v(()=>{Sy();by()});var gde,yde,vy,bde,Sde,vde;var QM=v(()=>{pe();gde=c.enum(["site-content-preview","site-content-production"]),yde=c.enum(["web","image","pdf","epub"]),vy=c.custom((e)=>typeof e==="function"),bde=c.object({name:c.string(),schema:c.unknown(),description:c.string().optional(),pluginId:c.string(),renderers:c.object({web:c.union([vy,c.string()]).optional(),image:c.union([vy,c.string()]).optional(),pdf:c.union([vy,c.string()]).optional(),epub:c.union([vy,c.string()]).optional()})}),Sde=c.object({enableContentGeneration:c.boolean().default(!1),outputDir:c.string(),workingDir:c.string().optional(),environment:c.enum(["preview","production"]).default("preview"),siteConfig:c.object({title:c.string(),description:c.string(),url:c.string().optional()}).optional()}),vde=c.object({success:c.boolean(),routesBuilt:c.number(),errors:c.array(c.string()).optional(),warnings:c.array(c.string()).optional()})});var YM=v(()=>{by();HM();Sy();WM();zR();GM();QM()});var NR=ge(function(xde,wy){(function(){function e(g,E){Object.defineProperty(o.prototype,g,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",E[0],E[1])}})}function t(g){if(g===null||typeof g!=="object")return null;return g=De&&g[De]||g["@@iterator"],typeof g==="function"?g:null}function r(g,E){g=(g=g.constructor)&&(g.displayName||g.name)||"ReactClass";var D=g+"."+E;Qe[D]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",E,g),Qe[D]=!0)}function o(g,E,D){this.props=g,this.context=E,this.refs=Dt,this.updater=D||bt}function n(){}function i(g,E,D){this.props=g,this.context=E,this.refs=Dt,this.updater=D||bt}function s(){}function a(g){return""+g}function l(g){try{a(g);var E=!1}catch(M){E=!0}if(E){E=console;var D=E.error,J=typeof Symbol==="function"&&Symbol.toStringTag&&g[Symbol.toStringTag]||g.constructor.name||"Object";return D.call(E,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",J),a(g)}}function u(g){if(g==null)return null;if(typeof g==="function")return g.$$typeof===$n?null:g.displayName||g.name||null;if(typeof g==="string")return g;switch(g){case H:return"Fragment";case re:return"Profiler";case G:return"StrictMode";case xe:return"Suspense";case Ae:return"SuspenseList";case Ue:return"Activity"}if(typeof g==="object")switch(typeof g.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),g.$$typeof){case N:return"Portal";case me:return g.displayName||"Context";case ae:return(g._context.displayName||"Context")+".Consumer";case be:var E=g.render;return g=g.displayName,g||(g=E.displayName||E.name||"",g=g!==""?"ForwardRef("+g+")":"ForwardRef"),g;case ke:return E=g.displayName||null,E!==null?E:u(g.type)||"Memo";case _e:E=g._payload,g=g._init;try{return u(g(E))}catch(D){}}return null}function d(g){if(g===H)return"<>";if(typeof g==="object"&&g!==null&&g.$$typeof===_e)return"<...>";try{var E=u(g);return E?"<"+E+">":"<...>"}catch(D){return"<...>"}}function p(){var g=Le.A;return g===null?null:g.getOwner()}function m(){return Error("react-stack-top-frame")}function h(g){if(ao.call(g,"key")){var E=Object.getOwnPropertyDescriptor(g,"key").get;if(E&&E.isReactWarning)return!1}return g.key!==void 0}function b(g,E){function D(){ls||(ls=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",E))}D.isReactWarning=!0,Object.defineProperty(g,"key",{get:D,configurable:!0})}function y(){var g=u(this.type);return us[g]||(us[g]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),g=this.props.ref,g!==void 0?g:null}function S(g,E,D,J,M,te){var se=D.ref;return g={$$typeof:q,type:g,key:E,props:D,_owner:J},(se!==void 0?se:null)!==null?Object.defineProperty(g,"ref",{enumerable:!1,get:y}):Object.defineProperty(g,"ref",{enumerable:!1,value:null}),g._store={},Object.defineProperty(g._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(g,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(g,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:M}),Object.defineProperty(g,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:te}),Object.freeze&&(Object.freeze(g.props),Object.freeze(g)),g}function x(g,E){return E=S(g.type,E,g.props,g._owner,g._debugStack,g._debugTask),g._store&&(E._store.validated=g._store.validated),E}function _(g){A(g)?g._store&&(g._store.validated=1):typeof g==="object"&&g!==null&&g.$$typeof===_e&&(g._payload.status==="fulfilled"?A(g._payload.value)&&g._payload.value._store&&(g._payload.value._store.validated=1):g._store&&(g._store.validated=1))}function A(g){return typeof g==="object"&&g!==null&&g.$$typeof===q}function O(g){var E={"=":"=0",":":"=2"};return"$"+g.replace(/[=:]/g,function(D){return E[D]})}function L(g,E){return typeof g==="object"&&g!==null&&g.key!=null?(l(g.key),O(""+g.key)):E.toString(36)}function z(g){switch(g.status){case"fulfilled":return g.value;case"rejected":throw g.reason;default:switch(typeof g.status==="string"?g.then(s,s):(g.status="pending",g.then(function(E){g.status==="pending"&&(g.status="fulfilled",g.value=E)},function(E){g.status==="pending"&&(g.status="rejected",g.reason=E)})),g.status){case"fulfilled":return g.value;case"rejected":throw g.reason}}throw g}function K(g,E,D,J,M){var te=typeof g;if(te==="undefined"||te==="boolean")g=null;var se=!1;if(g===null)se=!0;else switch(te){case"bigint":case"string":case"number":se=!0;break;case"object":switch(g.$$typeof){case q:case N:se=!0;break;case _e:return se=g._init,K(se(g._payload),E,D,J,M)}}if(se){se=g,M=M(se);var ye=J===""?"."+L(se,0):J;return Or(M)?(D="",ye!=null&&(D=ye.replace(Ea,"$&/")+"/"),K(M,E,D,"",function(Te){return Te})):M!=null&&(A(M)&&(M.key!=null&&(se&&se.key===M.key||l(M.key)),D=x(M,D+(M.key==null||se&&se.key===M.key?"":(""+M.key).replace(Ea,"$&/")+"/")+ye),J!==""&&se!=null&&A(se)&&se.key==null&&se._store&&!se._store.validated&&(D._store.validated=2),M=D),E.push(M)),1}if(se=0,ye=J===""?".":J+":",Or(g))for(var fe=0;fe<g.length;fe++)J=g[fe],te=ye+L(J,fe),se+=K(J,E,D,te,M);else if(fe=t(g),typeof fe==="function")for(fe===g.entries&&(Go||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),Go=!0),g=fe.call(g),fe=0;!(J=g.next()).done;)J=J.value,te=ye+L(J,fe++),se+=K(J,E,D,te,M);else if(te==="object"){if(typeof g.then==="function")return K(z(g),E,D,J,M);throw E=String(g),Error("Objects are not valid as a React child (found: "+(E==="[object Object]"?"object with keys {"+Object.keys(g).join(", ")+"}":E)+"). If you meant to render a collection of children, use an array instead.")}return se}function P(g,E,D){if(g==null)return g;var J=[],M=0;return K(g,J,"","",function(te){return E.call(D,te,M++)}),J}function W(g){if(g._status===-1){var E=g._ioInfo;E!=null&&(E.start=E.end=performance.now()),E=g._result;var D=E();if(D.then(function(M){if(g._status===0||g._status===-1){g._status=1,g._result=M;var te=g._ioInfo;te!=null&&(te.end=performance.now()),D.status===void 0&&(D.status="fulfilled",D.value=M)}},function(M){if(g._status===0||g._status===-1){g._status=2,g._result=M;var te=g._ioInfo;te!=null&&(te.end=performance.now()),D.status===void 0&&(D.status="rejected",D.reason=M)}}),E=g._ioInfo,E!=null){E.value=D;var J=D.displayName;typeof J==="string"&&(E.name=J)}g._status===-1&&(g._status=0,g._result=D)}if(g._status===1)return E=g._result,E===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
403
+ `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=oy(e),r=Yc(t);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=oy(e),r=Yc(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){if(this.type!=="comment")return!1;if(this.indent<=t)return!1;return e.every((r)=>r.type==="newline"||r.type==="space")}*documentEnd(e){if(this.type!=="doc-mode"){if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(e.end)e.end.push(this.sourceToken);else e.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}mle.Parser=L6});var M6=ge(function(_le){var B6=aR(),gle=tp(),ap=rp(),yle=yA(),ble=qe(),Sle=yR(),j6=bR();function Z6(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Sle.LineCounter||null,prettyErrors:t}}function vle(e,t={}){let{lineCounter:r,prettyErrors:o}=Z6(t),n=new j6.Parser(r?.addNewLine),i=new B6.Composer(t),s=Array.from(i.compose(n.parse(e)));if(o&&r)for(let a of s)a.errors.forEach(ap.prettifyError(e,r)),a.warnings.forEach(ap.prettifyError(e,r));if(s.length>0)return s;return Object.assign([],{empty:!0},i.streamInfo())}function U6(e,t={}){let{lineCounter:r,prettyErrors:o}=Z6(t),n=new j6.Parser(r?.addNewLine),i=new B6.Composer(t),s=null;for(let a of i.compose(n.parse(e),!0,e.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new ap.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(o&&r)s.errors.forEach(ap.prettifyError(e,r)),s.warnings.forEach(ap.prettifyError(e,r));return s}function wle(e,t,r){let o=void 0;if(typeof t==="function")o=t;else if(r===void 0&&t&&typeof t==="object")r=t;let n=U6(e,r);if(!n)return null;if(n.warnings.forEach((i)=>yle.warn(n.options.logLevel,i)),n.errors.length>0)if(n.options.logLevel!=="silent")throw n.errors[0];else n.errors=[];return n.toJS(Object.assign({reviver:o},r))}function xle(e,t,r){let o=null;if(typeof t==="function"||Array.isArray(t))o=t;else if(r===void 0&&t)r=t;if(typeof r==="string")r=r.length;if(typeof r==="number"){let n=Math.round(r);r=n<1?void 0:n>8?{indent:8}:{indent:n}}if(e===void 0){let{keepUndefined:n}=r??t??{};if(!n)return}if(ble.isDocument(e)&&!o)return e.toString(r);return new gle.Document(e,o,r).toString(r)}_le.parse=wle;_le.parseAllDocuments=vle;_le.parseDocument=U6;_le.stringify=xle});var Rle,Tle,$le,SR,Ole,Mi,Cle,Ple,zle,Nle,GCe,Dle,Lle,Ble,sy,q6,jle,Zle,Ule,Mle,qle,Fle,Jle,Kle,Hle,Vle,vn,Oo,Wle,Co,vR,Gle,Qle,Yle,Xle,eue,tue,rue,nue,oue,tn,iue,sue,aue;var Xc=v(()=>{Rle=aR(),Tle=tp(),$le=JA(),SR=rp(),Ole=Ud(),Mi=qe(),Cle=Li(),Ple=It(),zle=ji(),Nle=Zi(),GCe=ry(),Dle=gR(),Lle=yR(),Ble=bR(),sy=M6(),q6=jd();jle=Rle.Composer,Zle=Tle.Document,Ule=$le.Schema,Mle=SR.YAMLError,qle=SR.YAMLParseError,Fle=SR.YAMLWarning,Jle=Ole.Alias,Kle=Mi.isAlias,Hle=Mi.isCollection,Vle=Mi.isDocument,vn=Mi.isMap,Oo=Mi.isNode,Wle=Mi.isPair,Co=Mi.isScalar,vR=Mi.isSeq,Gle=Cle.Pair,Qle=Ple.Scalar,Yle=zle.YAMLMap,Xle=Nle.YAMLSeq,eue=Dle.Lexer,tue=Lle.LineCounter,rue=Ble.Parser,nue=sy.parse,oue=sy.parseAllDocuments,tn=sy.parseDocument,iue=sy.stringify,sue=q6.visit,aue=q6.visitAsync});var H6={};Lt(H6,{migratePilotDeploySecrets:()=>J6,migratePilotEnvSchema:()=>K6,migratePilotRepoProviderKeys:()=>hue,migrateProviderKeyFieldsYaml:()=>_R,openaiSelectorFor:()=>ER,renameProviderKeyFields:()=>qi});import{readdir as cue,readFile as wR,writeFile as F6}from"fs/promises";import{join as Po}from"path";function _R(e){let t=tn(e,{keepSourceTokens:!0});return qi(t)?t.toString({lineWidth:0}):e}function qi(e){if(!vn(e.contents))return!1;return e.contents.items.filter((r)=>{if(!Co(r.key)||typeof r.key.value!=="string")return!1;let o=lue[r.key.value];if(!o)return!1;if(r.key.value==="aiApiKey"&&Co(r.value)&&r.value.value===cy)r.value.value=ly;return r.key.value=o,!0}).length>0}function ER(e){return e===cy?ly:e}function J6(e){return e.replace(new RegExp(`^(\\s+- )${cy}$`,"m"),`$1${ly}`)}function K6(e){return e.replace(new RegExp(`^${cy}=`,"m"),`${ly}=`)}async function ay(e){try{return(await cue(e)).filter((r)=>r.endsWith(".yaml")).sort()}catch{return[]}}async function xR(e){try{return await wR(e,"utf8")}catch{return}}async function fue(e){let t=await ay(Po(e,"cohorts")),r=await Promise.all(t.map(async(i)=>{let s=yr(await wR(Po(e,"cohorts",i),"utf8"),due);return s.ok&&s.data.aiApiKeyOverride?s.data.members:[]})),o=(await ay(Po(e,"users"))).filter((i)=>!i.endsWith(".secrets.yaml")),n=await Promise.all(o.map(async(i)=>{let s=yr(await wR(Po(e,"users",i),"utf8"),uue);return s.ok&&s.data.aiApiKeyOverride?[i.replace(/\.yaml$/,"")]:[]}));return[...new Set([...r.flat(),...n.flat()])]}async function mue(e,t,r,o){let n=Po(e,"users",`${t}.secrets.yaml.age`),i=await xR(n);if(i===void 0)return!1;if(!r)throw Error(`users/${t}.secrets.yaml.age may hold the legacy AI key; set AGE_SECRET_KEY or AGE_SECRET_KEY_FILE to migrate it`);let s=new Ou;s.addIdentity(r);let a=await s.decrypt(yi.decode(i),"text"),l=_R(a);if(l===a)return!1;let u=new $u;return u.addRecipient(o),await F6(n,yi.encode(await u.encrypt(l))),!0}async function hue(e,t){let r=["pilot.yaml",...(await ay(Po(e,"cohorts"))).map((l)=>`cohorts/${l}`),...(await ay(Po(e,"users"))).filter((l)=>!l.endsWith(".secrets.yaml")).map((l)=>`users/${l}`)],o=await fue(e),n=await Promise.all([...r.map((l)=>({file:l,migrate:_R})),{file:".env.schema",migrate:K6},{file:"deploy/kamal/deploy.yml",migrate:J6}].map(async({file:l,migrate:u})=>{let d=Po(e,l),p=await xR(d);if(p===void 0)return[];let m=u(p);if(m===p)return[];return await F6(d,m),[l]})),i=yr(await xR(Po(e,"pilot.yaml"))??"",pue),s=oA(e,t,Lr(e)),a=o.length===0?[]:await Promise.all(o.map(async(l)=>{if(!i.ok)throw Error("pilot.yaml needs agePublicKey to re-encrypt secrets");return await mue(e,l,s,i.data.agePublicKey)?[`users/${l}.secrets.yaml.age`]:[]}));return[...n.flat(),...a.flat()]}var cy="AI_API_KEY",ly="OPENAI_API_KEY",lue,uue,due,pue;var uy=v(()=>{gi();vi();Vn();pe();Xc();sA();lue={aiApiKey:"openaiApiKey",aiApiKeyOverride:"openaiApiKeyOverride"};uue=c.looseObject({aiApiKeyOverride:c.string().optional()}),due=c.looseObject({members:c.array(c.string()).default([]),aiApiKeyOverride:c.string().optional()}),pue=c.looseObject({agePublicKey:c.string()})});function Q6(e){if(e==="core")return{bundles:["core","media","web","chat"]};if(e==="default")return{bundles:["core","media","automation","web","chat","site","publishing","federation"],add:["obsidian-vault"],remove:[...bue]};return{bundles:["core","media","automation","web","chat","site","publishing","federation"],add:["obsidian-vault"]}}function Sue(e){let t=gue.parse(e);return Qs.parse({brainVersion:t.brainVersion,bundleContract:Gs,...Q6(t.preset),githubOrg:t.githubOrg,contentRepoPrefix:t.contentRepoPrefix,domainSuffix:t.domainSuffix,openaiApiKey:ER(t.aiApiKey),gitSyncToken:t.gitSyncToken,contentRepoAdminToken:t.contentRepoAdminToken,agePublicKey:t.agePublicKey})}function vue(e){let t=yue.parse(e),r=t.presetOverride?Q6(t.presetOverride):void 0;return hn.parse({members:[...t.members],...t.brainVersionOverride?{brainVersionOverride:t.brainVersionOverride}:{},...r?{bundlesOverride:r.bundles,...r.add?{addOverride:r.add}:{},...r.remove?{removeOverride:r.remove}:{}}:{},...t.aiApiKeyOverride?{openaiApiKeyOverride:t.aiApiKeyOverride}:{},...t.gitSyncTokenOverride?{gitSyncTokenOverride:t.gitSyncTokenOverride}:{}})}function Y6(e){let t=tn(e,{keepSourceTokens:!0});if(t.errors.length>0)throw Error(`Invalid desired-state YAML: ${t.errors[0]?.message}`);if(!vn(t.contents))throw Error("Desired-state YAML must contain a mapping");return t}function IR(e,t){if(!vn(e.contents))return;return e.contents.items.find((r)=>Co(r.key)&&r.key.value===t)}function V6(e,t){if(!Oo(e)||!Oo(t))return;if(e.commentBefore!==void 0)t.commentBefore=e.commentBefore;if(e.comment!==void 0)t.comment=e.comment;if(e.spaceBefore!==void 0)t.spaceBefore=e.spaceBefore}function W6(e,t){if(!e||!Oo(t))return;let r=[Oo(e.key)?e.key.commentBefore:void 0,Oo(e.key)?e.key.comment:void 0,Oo(e.value)?e.value.commentBefore:void 0,Oo(e.value)?e.value.comment:void 0].filter((o)=>o!==void 0);if(r.length===0)return;t.commentBefore=[t.commentBefore,...r].filter((o)=>o!==void 0).join(`
404
+ `)}function X6(e,t,r,o){if(!vn(e.contents))throw Error("Desired-state YAML must contain a mapping");let n=e.contents.items.findIndex((s)=>Co(s.key)&&s.key.value===t),i=e.createPair(r,[...o]);if(n>=0){let s=e.contents.items[n];V6(s?.key,i.key),V6(s?.value,i.value),e.contents.items.splice(n,1,i)}else e.contents.add(i);return i}function eM(e){let t=Y6(e),r=Sue(t.toJS()),o=IR(t,"schemaVersion"),n=IR(t,"model");W6(o,IR(t,"brainVersion")?.key),t.delete("schemaVersion"),t.set("bundleContract",Gs);let i=X6(t,"preset","bundles",r.bundles);if(W6(n,i.key),t.delete("model"),r.add)t.set("add",r.add);else t.delete("add");if(r.remove)t.set("remove",r.remove);else t.delete("remove");return qi(t),Qs.parse(t.toJS()),t.toString({lineWidth:0})}function tM(e){let t=Y6(e),r=vue(t.toJS());if(r.bundlesOverride)X6(t,"presetOverride","bundlesOverride",r.bundlesOverride);else t.delete("presetOverride"),t.delete("bundlesOverride");if(r.addOverride)t.set("addOverride",r.addOverride);else t.delete("addOverride");if(r.removeOverride)t.set("removeOverride",r.removeOverride);else t.delete("removeOverride");return qi(t),hn.parse(t.toJS()),t.toString({lineWidth:0})}var G6,cp,gue,yue,bue;var rM=v(()=>{uy();Vn();pe();Xc();Ao();G6=c.enum(["core","default","pro"]),cp=c.string().min(1),gue=c.strictObject({schemaVersion:c.literal(1),brainVersion:Ct,model:c.literal("rover"),githubOrg:c.string().min(1),contentRepoPrefix:c.string().min(1),domainSuffix:c.string().min(1),preset:G6,aiApiKey:cp,gitSyncToken:cp,contentRepoAdminToken:cp,agePublicKey:c.string().startsWith("age1").min(1)}),yue=c.strictObject({members:c.array(br).min(1),brainVersionOverride:Ct.optional(),presetOverride:G6.optional(),aiApiKeyOverride:cp.optional(),gitSyncTokenOverride:cp.optional()}).superRefine((e,t)=>{if(new Set(e.members).size!==e.members.length)t.addIssue({code:c.ZodIssueCode.custom,path:["members"],message:"cohort members must be unique"})}),bue=["series","portfolio","content-pipeline","social-media","newsletter","stock-photo"]});function oM(e,t){let r=tn(e,{keepSourceTokens:!0});if(r.errors.length>0||!vn(r.contents))throw Error(`Invalid ${t} YAML`);return r}function Iue(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function iM(e,t,r){if(!Iue(t,r.sourceBundles))throw Error(`${e} source bundles changed after review: expected [${r.sourceBundles.join(", ")}], received [${t.join(", ")}]`)}function sM(e){let t=yr(e,Eue);if(!t.ok)throw Error(`Invalid capability bundle review: ${t.error}`);return t.data}function aM(e,t){let r=oM(e,"pilot desired-state"),o=xue.parse(r.toJS());return iM("pilot.yaml",o.bundles,t),r.set("bundleContract",Gs),r.set("bundles",t.targetBundles),qi(r),Qs.parse(r.toJS()),r.toString({lineWidth:0})}function cM(e,t,r){let o=oM(e,`cohort ${t}`),n=_ue.parse(o.toJS());if(n.bundlesOverride===void 0){if(r!==void 0)throw Error(`Capability bundle review names inheriting cohort ${t}`)}else{if(r===void 0)throw Error(`Cohort ${t} has an explicit legacy bundle selection but no reviewed mapping`);iM(`cohort ${t}`,n.bundlesOverride,r),o.set("bundlesOverride",r.targetBundles)}return qi(o),hn.parse(o.toJS()),o.toString({lineWidth:0})}var wue,kR,dy,xue,_ue,nM,Eue;var lM=v(()=>{uy();Vn();pe();Xc();Ao();wue=c.enum(["core","site","publishing","team"]),kR=c.array(wue).min(1),dy=c.array(c.string().min(1)),xue=c.strictObject({brainVersion:Ct,bundles:kR,add:dy.optional(),remove:dy.optional(),githubOrg:c.string().min(1),contentRepoPrefix:c.string().min(1),domainSuffix:c.string().min(1),aiApiKey:c.string().min(1),gitSyncToken:c.string().min(1),contentRepoAdminToken:c.string().min(1),agePublicKey:c.string().startsWith("age1").min(1)}),_ue=c.strictObject({members:c.array(br).min(1),brainVersionOverride:Ct.optional(),bundlesOverride:kR.optional(),addOverride:dy.optional(),removeOverride:dy.optional(),aiApiKeyOverride:c.string().min(1).optional(),gitSyncTokenOverride:c.string().min(1).optional()}),nM=c.strictObject({sourceBundles:kR,targetBundles:c.array(jk).min(1)}),Eue=c.strictObject({bundleContract:c.literal(Gs),pilot:nM,cohorts:c.record(br,nM)})});var mM={};Lt(mM,{loadCapabilityBundleReview:()=>zue,loadReviewedSitePins:()=>Pue,parseReviewedSitePins:()=>fM,stageLegacyCrossover:()=>Due});import{access as kue,cp as Aue,mkdir as uM,readFile as tl,readdir as pM,writeFile as el}from"fs/promises";import{basename as Rue,join as Yn,relative as py,resolve as dM}from"path";import{fileURLToPath as Tue}from"url";function fM(e){let t=yr(e,$ue);if(!t.ok)throw Error(`Invalid reviewed site pins: ${t.error}`);return t.data.sites}async function Pue(e){return fM(await tl(e,"utf8"))}async function zue(e){return sM(await tl(e,"utf8"))}async function Nue(e,t){let r=Yn(e,"users"),o=(await pM(r,{withFileTypes:!0})).filter((s)=>s.isFile()&&/\.ya?ml$/.test(s.name)).map((s)=>s.name).sort(),n=new Set(Object.keys(t??{})),i=[];for(let s of o){let a=Yn(r,s),l=await tl(a,"utf8"),u=tn(l,{keepSourceTokens:!0});if(u.errors.length>0||!vn(u.contents))throw Error(`Invalid user desired-state YAML: ${s}`);let d=Oue.parse(u.toJS());if(!d.siteOverride)continue;let p=t?.[d.handle];if(!p)throw Error(`User ${d.handle} has a siteOverride but no reviewed site pin`);if(n.delete(d.handle),p.package!==d.siteOverride.package||p.theme!==d.siteOverride.theme)throw Error(`Reviewed site pin identity does not match user ${d.handle}`);if(d.siteOverride.version!==void 0&&d.siteOverride.version!==p.version)throw Error(`Reviewed site version does not match the existing pin for user ${d.handle}`);if(d.siteOverride.themeVersion!==void 0&&d.siteOverride.themeVersion!==p.themeVersion)throw Error(`Reviewed theme version does not match the existing pin for user ${d.handle}`);if(u.setIn(["siteOverride","version"],p.version),p.themeVersion!==void 0)u.setIn(["siteOverride","themeVersion"],p.themeVersion);else u.deleteIn(["siteOverride","themeVersion"]);ag.parse(u.toJS());let m=u.toString({lineWidth:0});if(m!==l)await el(a,m),i.push(py(e,a))}if(n.size>0)throw Error(`Reviewed site pins do not match site users: ${[...n].sort().join(", ")}`);return i}async function Due(e,t,r={}){let o=dM(e),n=dM(t);if(o===n||n.startsWith(`${o}/`))throw Error("Crossover output must be outside the source repository");await Aue(o,n,{recursive:!0,errorOnExist:!0,force:!1,filter:(A)=>{let O=Rue(A);return O!==".git"&&O!==".operator"&&O!==".brains-ops"&&O!==".turbo"&&O!=="dist"&&O!=="node_modules"&&O!==".env"&&O!==".env.local"&&!O.endsWith(".secrets.yaml")}});let i=[],s=Yn(n,"docs","canonical-crossover-record.md");try{await kue(s)}catch{await uM(Yn(n,"docs"),{recursive:!0}),await el(s,await tl(Cue,"utf8")),i.push("docs/canonical-crossover-record.md")}let a=Yn(n,"pilot.yaml"),l=await tl(a,"utf8"),d=tn(l).toJS();if(!Pd(d))throw Error(`${a} is not a YAML mapping`);let p=Array.isArray(d.bundles),m=r.bundleReview,h;if(p){if(!m)throw Error("Current canonical desired state requires an explicit capability bundle review manifest");h=aM(l,m.pilot)}else h=eM(l);await el(a,h),i.push("pilot.yaml");let b=Yn(n,"cohorts"),y=(await pM(b,{withFileTypes:!0})).filter((A)=>A.isFile()&&/\.ya?ml$/.test(A.name)).map((A)=>A.name).sort(),S=new Set(Object.keys(m?.cohorts??{}));for(let A of y){let O=Yn(b,A),L=await tl(O,"utf8"),z=A.replace(/\.ya?ml$/,""),K=m?.cohorts[z];if(K)S.delete(z);await el(O,p?cM(L,z,K):tM(L)),i.push(py(n,O))}if(p&&S.size>0)throw Error(`Capability bundle review names unknown cohorts: ${[...S].sort().join(", ")}`);i.push(...await Nue(n,r.sitePins));let x=await wt(n),_=dg(x.pilot.githubOrg);for(let A of x.users){let O=await _(A),L=Yn(n,"users",A.handle);if(await uM(L,{recursive:!0}),O.brainYaml){let z=Yn(L,"brain.yaml");await el(z,O.brainYaml),i.push(py(n,z))}if(O.envFile){let z=Yn(L,".env");await el(z,O.envFile),i.push(py(n,z))}}return await Pi(n,{registry:x}),i.push("views/users.md"),{outputDir:n,changedFiles:[...new Set(i)].sort()}}var $ue,Oue,Cue;var hM=v(()=>{Vn();zd();pe();Xc();eA();rM();lM();gn();Cd();Ao();$ue=c.strictObject({sites:c.record(br,Zk)}),Oue=c.object({handle:br,siteOverride:c.object({package:c.string().min(1),version:Ct.optional(),theme:c.string().min(1).optional(),themeVersion:Ct.optional()}).optional()}).passthrough(),Cue=Tue(new URL("../templates/rover-pilot/docs/canonical-crossover-record.md",import.meta.url))});var yM,Lue,Bue,jue,zo,lp,Zue,AR,Uue,Mue,gM,que,Fue,bM,C1e,SM;var fy=v(()=>{VI();yM=["primary","secondary"],Lue=c.custom((e)=>typeof e==="function","Expected a React component"),Bue=c.strictObject({show:c.boolean().optional(),label:c.string().min(1).optional(),slot:c.enum(yM).optional(),priority:c.number().optional()}),jue=c.strictObject({id:c.string().min(1),template:c.string().min(1),content:c.unknown().optional(),dataQuery:c.looseObject({entityType:c.string().optional(),template:c.string().optional(),query:c.record(c.string(),c.unknown()).optional()}).optional(),order:c.number().optional()}),zo=c.string().regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/,{message:"must be a language tag such as en or zh-TW"}),lp=c.strictObject({title:c.string().optional(),description:c.string().optional(),navigationLabel:c.string().optional()}),Zue=c.strictObject({id:c.string().min(1),path:c.string().startsWith("/"),title:c.string().optional(),pageLabel:c.string().optional(),description:c.string().optional(),sections:c.array(jue).optional(),layout:c.string().min(1).optional(),fullscreen:c.boolean().optional(),pluginId:c.string().optional(),sourceEntityType:c.string().optional(),external:c.boolean().optional(),navigation:Bue.optional(),translations:c.record(zo,lp).optional()}),AR=c.strictObject({label:c.string().min(1),pluralName:c.string().min(1).optional(),layout:c.string().min(1).optional(),detailTemplate:c.string().min(1).optional(),paginate:c.boolean().optional(),pageSize:c.number().int().positive().optional(),citable:c.boolean().optional(),navigation:c.strictObject({show:c.boolean().optional(),slot:c.enum(yM).optional(),priority:c.number().optional()}).optional()}),Uue=c.strictObject({schema:c.custom((e)=>e instanceof c.ZodType,"Expected a Zod schema"),component:c.custom((e)=>typeof e==="function","Expected a React component"),title:c.string().min(1),description:c.string(),requiredPermission:c.enum(["admin","trusted","public"]).optional(),fullscreen:c.boolean().optional(),dataSource:c.string().min(1).optional()}),Mue=c.custom((e)=>typeof e==="object"&&e!==null&&Reflect.get(e,"kind")==="rizom-data-source"&&typeof Reflect.get(e,"id")==="string"&&typeof Reflect.get(e,"fetch")==="function","Expected a fetching data source declared with defineDataSource"),gM=c.strictObject({namespace:c.string().min(1),sections:c.record(c.string(),Uue)}),que=c.record(c.string(),c.json()),Fue=c.record(c.string(),c.record(c.string(),que)),bM={layouts:c.record(c.string(),Lue).refine((e)=>typeof e.default==="function",{message:'Site layouts must include a "default" component'}),routes:c.array(Zue),content:Fue.optional(),sections:c.union([gM,c.array(gM)]).optional(),themeOverride:c.string().optional(),headScripts:c.array(c.string()).optional(),entityDisplay:c.record(c.string(),AR),staticAssets:c.record(c.string(),c.string()).optional(),languages:c.array(zo).min(1).optional(),dataSources:c.array(Mue).readonly().optional()},C1e=c.strictObject(bM).partial(),SM=c.strictObject(bM).superRefine((e,t)=>{let r=e.languages??[],o=new Set;for(let[u,d]of r.entries()){let p=d.toLowerCase();if(o.has(p))t.addIssue({code:"custom",path:["languages",u],message:`Language "${d}" is declared twice`});o.add(p)}let n=r.slice(1).map((u)=>`/${u.toLowerCase()}`),i=new Set;for(let[u,d]of e.routes.entries()){if(i.has(d.id))t.addIssue({code:"custom",path:["routes",u,"id"],message:`Duplicate route id "${d.id}"`});i.add(d.id);let p=d.path.toLowerCase(),m=n.find((b)=>p===b||p.startsWith(`${b}/`));if(m)t.addIssue({code:"custom",path:["routes",u,"path"],message:`Route path "${d.path}" is under ${m}, where another language's pages are built`});let h=d.layout??"default";if(!e.layouts[h])t.addIssue({code:"custom",path:["routes",u,"layout"],message:`Unknown layout "${h}"`});for(let[b,y]of(d.sections??[]).entries()){let S=/^([^:.\s]+)\.([^:.\s]+)$/.exec(y.template);if(S)t.addIssue({code:"custom",path:["routes",u,"sections",b,"template"],message:`Section template "${y.template}" is written "${S[1]}:${S[2]}"`})}}let s=Array.isArray(e.sections)?e.sections:e.sections?[e.sections]:[],a=new Map(s.map((u)=>[u.namespace,u]));if(a.size!==s.length)t.addIssue({code:"custom",path:["sections"],message:"Section group namespaces must be unique"});let l=new Set;for(let[u,d]of(e.dataSources??[]).entries()){if(l.has(d.id))t.addIssue({code:"custom",path:["dataSources",u],message:`Data source "${d.id}" is declared twice`});l.add(d.id)}for(let u of s)for(let[d,p]of Object.entries(u.sections))if(p.dataSource&&!l.has(p.dataSource))t.addIssue({code:"custom",path:["sections",u.namespace,d,"dataSource"],message:`Section "${u.namespace}:${d}" reads data source "${p.dataSource}", which the site does not declare`});for(let[u,d]of Object.entries(e.content??{})){let p=a.get(u);if(!p){t.addIssue({code:"custom",path:["content",u],message:`Content namespace "${u}" has no section group`});continue}for(let[m,h]of Object.entries(d)){let b=p.sections[m];if(!b){t.addIssue({code:"custom",path:["content",u,m],message:`Content section "${u}:${m}" is not defined`});continue}let y=b.schema.safeParse(h);if(!y.success)t.addIssue({code:"custom",path:["content",u,m],message:`Content does not satisfy the "${u}:${m}" schema: ${c.prettifyError(y.error)}`})}}})});var vM,wM,xM,my,_M,Kue,EM,IM,Hue,kM,AM,Vue,hy;var RR=v(()=>{Ot();pe();fy();fy();vM=c.object({id:c.string(),template:c.string(),content:c.unknown().optional(),dataQuery:c.looseObject({entityType:c.string().optional(),template:c.string().optional(),query:c.looseObject({id:c.string().optional(),limit:c.number().optional(),offset:c.number().optional()}).optional()}).optional(),order:c.number().optional()}),wM=["primary","secondary"],xM=c.object({show:c.boolean().default(!1),label:c.string().optional(),slot:c.enum(wM).default("primary"),priority:c.number().min(0).max(100).default(50)}).optional(),my=c.object({id:c.string(),path:c.string(),title:c.string().default(""),pageLabel:c.string().optional(),description:c.string().default(""),sections:c.array(vM).default([]),layout:c.string().default("default"),fullscreen:c.boolean().optional(),pluginId:c.string().optional(),sourceEntityType:c.string().optional(),external:c.boolean().optional(),navigation:xM,translations:c.record(zo,lp).optional(),languages:c.array(zo).optional()}),_M=c.object({routes:c.array(my),pluginId:c.string()}),Kue=we({channel:"plugin:site-builder:route:register",request:_M,response:c.void(),delivery:"command"}),EM=c.strictObject({}),IM=c.array(my),Hue=we({channel:"site-builder:routes:list",request:EM,response:IM,delivery:"request"}),kM=c.strictObject({}),AM=c.array(my),Vue=we({channel:"plugin:site-builder:pages",request:kM,response:AM,delivery:"collect"}),hy=c.object({label:c.string(),href:c.string(),priority:c.number()})});var RM,TM,$M,Wue;var OM=v(()=>{Ot();pe();RM=c.object({pluginId:c.string(),slotName:c.string(),render:c.custom((e)=>typeof e==="function"),priority:c.number().optional()}),TM=c.strictObject({}),$M=c.array(RM),Wue=we({channel:"plugin:site-builder:slots",request:TM,response:$M,delivery:"collect"})});var CM="site:metadata:updated",gy,PM,zM,rl,NM,Gue,Que,Yue;var TR=v(()=>{Ot();pe();RR();gy=c.object({heading:c.string().describe("Main CTA heading text"),subtitle:c.string().optional().describe("A line under the CTA heading"),buttonText:c.string().describe("Call-to-action button text"),buttonLink:c.string().describe("URL or anchor for the CTA button")}),PM=c.object({title:c.string().optional(),description:c.string().optional(),copyright:c.string().optional(),cta:gy.optional()}),zM=c.object({blurb:c.string().optional().describe("Short italic subtitle under the section title")}),rl=c.object({represents:c.enum(["brain","anchor"]).default("anchor").describe("Identity represented by the site"),title:c.string().describe("The site's title"),description:c.string().describe("The site's description"),url:c.string().optional().describe("Canonical site URL"),copyright:c.string().optional().describe("Copyright notice text"),logo:c.boolean().optional().describe("Whether to display logo instead of title text in header"),themeMode:c.enum(["light","dark"]).optional().describe("Default theme mode"),analyticsScript:c.string().optional().describe("Analytics script HTML"),cta:gy.optional().describe("Call-to-action configuration"),sections:c.record(c.string(),zM).optional().describe("Optional per-section blurbs, keyed by section id (e.g. 'essays', 'presentations', 'about'). Used by homepage templates that render editorial section headers."),translations:c.record(zo,PM).optional().describe("The site's title, description, copyright and call to action in its other languages, keyed by language tag. A site is built in a language only once it has one.")}),NM=c.strictObject({}),Gue=we({channel:"site:metadata:get",request:NM,response:rl,delivery:"request"}),Que=Ci(CM,rl),Yue=rl.extend({copyright:c.string(),navigation:c.object({primary:c.array(hy),secondary:c.array(hy)}),socialLinks:c.array(Bk).optional().describe("Social media links from profile metadata"),photo:c.string().optional().describe("The anchor's photo, as ![alt](entity://image/<id>)")})});var H1e;var $R=v(()=>{pe();H1e=c.record(c.string(),c.unknown())});var up=v(()=>{$R()});var DM=v(()=>{Ot();up()});var LM=v(()=>{up();Ot()});var BM=v(()=>{up();Ot()});var lPe;var jM=v(()=>{pe();lPe=c.record(c.string(),c.unknown())});var pPe;var ZM=v(()=>{pe();Pc();pPe=c.record(c.string(),c.unknown())});var UM=v(()=>{Pc()});var MM=v(()=>{up();DM();LM();BM();jM();ZM();UM();$R()});var cde;var qM=v(()=>{pe();cde=c.object({slug:c.string(),title:c.string(),type:c.string(),entityId:c.string(),contentHash:c.string()})});var CR=v(()=>{MM();qM()});var FM=v(()=>{CR();pe()});var PR=()=>{};var lde,ude,dde;var by=v(()=>{pe();Ot();lde={url:c.string(),typeLabel:c.string(),listUrl:c.string(),listLabel:c.string()},ude={url:c.string().nullable().default(null),typeLabel:c.string().nullable().default(null),listUrl:c.string().nullable().default(null),listLabel:c.string().nullable().default(null)},dde=c.object({name:c.string(),description:c.string(),schema:c.unknown(),basePrompt:c.string().optional(),useKnowledgeContext:c.boolean().optional(),requiredPermission:c.enum(["admin","trusted","public"]),formatter:c.unknown().optional(),overlayFormatter:c.unknown().optional(),layout:c.object({component:c.unknown().optional(),fullscreen:c.boolean().optional(),formats:c.unknown().optional()}).optional(),dataSourceId:c.string().optional()})});var Sy=v(()=>{by()});var HM=v(()=>{Sy()});var zR=()=>{};var fde,mde,nl,VM,hde;var WM=v(()=>{Ot();pe();zR();fde=c.enum(["admin","trusted","public"]),mde=c.enum(["create","update","delete","extract","publish"]),nl=c.enum(["never","admin","trusted","public"]),VM=c.strictObject({create:nl.optional(),update:nl.optional(),delete:nl.optional(),extract:nl.optional(),publish:nl.optional()}),hde=c.record(c.string(),VM)});var GM=v(()=>{Sy();by()});var gde,yde,vy,bde,Sde,vde;var QM=v(()=>{pe();gde=c.enum(["site-content-preview","site-content-production"]),yde=c.enum(["web","image","pdf","epub"]),vy=c.custom((e)=>typeof e==="function"),bde=c.object({name:c.string(),schema:c.unknown(),description:c.string().optional(),pluginId:c.string(),renderers:c.object({web:c.union([vy,c.string()]).optional(),image:c.union([vy,c.string()]).optional(),pdf:c.union([vy,c.string()]).optional(),epub:c.union([vy,c.string()]).optional()})}),Sde=c.object({enableContentGeneration:c.boolean().default(!1),outputDir:c.string(),workingDir:c.string().optional(),environment:c.enum(["preview","production"]).default("preview"),siteConfig:c.object({title:c.string(),description:c.string(),url:c.string().optional()}).optional()}),vde=c.object({success:c.boolean(),routesBuilt:c.number(),errors:c.array(c.string()).optional(),warnings:c.array(c.string()).optional()})});var YM=v(()=>{by();HM();Sy();WM();zR();GM();QM()});var NR=ge(function(xde,wy){(function(){function e(g,E){Object.defineProperty(o.prototype,g,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",E[0],E[1])}})}function t(g){if(g===null||typeof g!=="object")return null;return g=De&&g[De]||g["@@iterator"],typeof g==="function"?g:null}function r(g,E){g=(g=g.constructor)&&(g.displayName||g.name)||"ReactClass";var D=g+"."+E;Qe[D]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",E,g),Qe[D]=!0)}function o(g,E,D){this.props=g,this.context=E,this.refs=Dt,this.updater=D||bt}function n(){}function i(g,E,D){this.props=g,this.context=E,this.refs=Dt,this.updater=D||bt}function s(){}function a(g){return""+g}function l(g){try{a(g);var E=!1}catch(M){E=!0}if(E){E=console;var D=E.error,J=typeof Symbol==="function"&&Symbol.toStringTag&&g[Symbol.toStringTag]||g.constructor.name||"Object";return D.call(E,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",J),a(g)}}function u(g){if(g==null)return null;if(typeof g==="function")return g.$$typeof===$n?null:g.displayName||g.name||null;if(typeof g==="string")return g;switch(g){case H:return"Fragment";case re:return"Profiler";case G:return"StrictMode";case xe:return"Suspense";case Ae:return"SuspenseList";case Ue:return"Activity"}if(typeof g==="object")switch(typeof g.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),g.$$typeof){case N:return"Portal";case me:return g.displayName||"Context";case ae:return(g._context.displayName||"Context")+".Consumer";case be:var E=g.render;return g=g.displayName,g||(g=E.displayName||E.name||"",g=g!==""?"ForwardRef("+g+")":"ForwardRef"),g;case ke:return E=g.displayName||null,E!==null?E:u(g.type)||"Memo";case _e:E=g._payload,g=g._init;try{return u(g(E))}catch(D){}}return null}function d(g){if(g===H)return"<>";if(typeof g==="object"&&g!==null&&g.$$typeof===_e)return"<...>";try{var E=u(g);return E?"<"+E+">":"<...>"}catch(D){return"<...>"}}function p(){var g=Le.A;return g===null?null:g.getOwner()}function m(){return Error("react-stack-top-frame")}function h(g){if(ao.call(g,"key")){var E=Object.getOwnPropertyDescriptor(g,"key").get;if(E&&E.isReactWarning)return!1}return g.key!==void 0}function b(g,E){function D(){ls||(ls=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",E))}D.isReactWarning=!0,Object.defineProperty(g,"key",{get:D,configurable:!0})}function y(){var g=u(this.type);return us[g]||(us[g]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),g=this.props.ref,g!==void 0?g:null}function S(g,E,D,J,M,te){var se=D.ref;return g={$$typeof:q,type:g,key:E,props:D,_owner:J},(se!==void 0?se:null)!==null?Object.defineProperty(g,"ref",{enumerable:!1,get:y}):Object.defineProperty(g,"ref",{enumerable:!1,value:null}),g._store={},Object.defineProperty(g._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(g,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(g,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:M}),Object.defineProperty(g,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:te}),Object.freeze&&(Object.freeze(g.props),Object.freeze(g)),g}function x(g,E){return E=S(g.type,E,g.props,g._owner,g._debugStack,g._debugTask),g._store&&(E._store.validated=g._store.validated),E}function _(g){A(g)?g._store&&(g._store.validated=1):typeof g==="object"&&g!==null&&g.$$typeof===_e&&(g._payload.status==="fulfilled"?A(g._payload.value)&&g._payload.value._store&&(g._payload.value._store.validated=1):g._store&&(g._store.validated=1))}function A(g){return typeof g==="object"&&g!==null&&g.$$typeof===q}function O(g){var E={"=":"=0",":":"=2"};return"$"+g.replace(/[=:]/g,function(D){return E[D]})}function L(g,E){return typeof g==="object"&&g!==null&&g.key!=null?(l(g.key),O(""+g.key)):E.toString(36)}function z(g){switch(g.status){case"fulfilled":return g.value;case"rejected":throw g.reason;default:switch(typeof g.status==="string"?g.then(s,s):(g.status="pending",g.then(function(E){g.status==="pending"&&(g.status="fulfilled",g.value=E)},function(E){g.status==="pending"&&(g.status="rejected",g.reason=E)})),g.status){case"fulfilled":return g.value;case"rejected":throw g.reason}}throw g}function K(g,E,D,J,M){var te=typeof g;if(te==="undefined"||te==="boolean")g=null;var se=!1;if(g===null)se=!0;else switch(te){case"bigint":case"string":case"number":se=!0;break;case"object":switch(g.$$typeof){case q:case N:se=!0;break;case _e:return se=g._init,K(se(g._payload),E,D,J,M)}}if(se){se=g,M=M(se);var ye=J===""?"."+L(se,0):J;return Or(M)?(D="",ye!=null&&(D=ye.replace(Ea,"$&/")+"/"),K(M,E,D,"",function(Te){return Te})):M!=null&&(A(M)&&(M.key!=null&&(se&&se.key===M.key||l(M.key)),D=x(M,D+(M.key==null||se&&se.key===M.key?"":(""+M.key).replace(Ea,"$&/")+"/")+ye),J!==""&&se!=null&&A(se)&&se.key==null&&se._store&&!se._store.validated&&(D._store.validated=2),M=D),E.push(M)),1}if(se=0,ye=J===""?".":J+":",Or(g))for(var fe=0;fe<g.length;fe++)J=g[fe],te=ye+L(J,fe),se+=K(J,E,D,te,M);else if(fe=t(g),typeof fe==="function")for(fe===g.entries&&(Go||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),Go=!0),g=fe.call(g),fe=0;!(J=g.next()).done;)J=J.value,te=ye+L(J,fe++),se+=K(J,E,D,te,M);else if(te==="object"){if(typeof g.then==="function")return K(z(g),E,D,J,M);throw E=String(g),Error("Objects are not valid as a React child (found: "+(E==="[object Object]"?"object with keys {"+Object.keys(g).join(", ")+"}":E)+"). If you meant to render a collection of children, use an array instead.")}return se}function P(g,E,D){if(g==null)return g;var J=[],M=0;return K(g,J,"","",function(te){return E.call(D,te,M++)}),J}function W(g){if(g._status===-1){var E=g._ioInfo;E!=null&&(E.start=E.end=performance.now()),E=g._result;var D=E();if(D.then(function(M){if(g._status===0||g._status===-1){g._status=1,g._result=M;var te=g._ioInfo;te!=null&&(te.end=performance.now()),D.status===void 0&&(D.status="fulfilled",D.value=M)}},function(M){if(g._status===0||g._status===-1){g._status=2,g._result=M;var te=g._ioInfo;te!=null&&(te.end=performance.now()),D.status===void 0&&(D.status="rejected",D.reason=M)}}),E=g._ioInfo,E!=null){E.value=D;var J=D.displayName;typeof J==="string"&&(E.name=J)}g._status===-1&&(g._status=0,g._result=D)}if(g._status===1)return E=g._result,E===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
405
405
 
406
406
  Your code should look like:
407
407
  const MyComponent = lazy(() => import('./MyComponent'))
@@ -414,7 +414,7 @@ Your code should look like:
414
414
  2. You might be breaking the Rules of Hooks
415
415
  3. You might have more than one copy of React in the same app
416
416
  See https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem.`),g}function j(){Le.asyncTransitions--}function T(g){if(U===null)try{var E=("require"+Math.random()).slice(0,7);U=(wy&&wy[E]).call(wy,"timers").setImmediate}catch(D){U=function(J){f===!1&&(f=!0,typeof MessageChannel>"u"&&console.error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."));var M=new MessageChannel;M.port1.onmessage=J,M.port2.postMessage(void 0)}}return U(g)}function B(g){return 1<g.length&&typeof AggregateError==="function"?AggregateError(g):g[0]}function I(g,E){E!==ne-1&&console.error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "),ne=E}function R(g,E,D){var J=Le.actQueue;if(J!==null)if(J.length!==0)try{k(J),T(function(){return R(g,E,D)});return}catch(M){Le.thrownErrors.push(M)}else Le.actQueue=null;0<Le.thrownErrors.length?(J=B(Le.thrownErrors),Le.thrownErrors.length=0,D(J)):E(g)}function k(g){if(!X){X=!0;var E=0;try{for(;E<g.length;E++){var D=g[E];do{Le.didUsePromise=!1;var J=D(!1);if(J!==null){if(Le.didUsePromise){g[E]=D,g.splice(0,E);return}D=J}else break}while(1)}g.length=0}catch(M){g.splice(0,E+1),Le.thrownErrors.push(M)}finally{X=!1}}}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart==="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var q=Symbol.for("react.transitional.element"),N=Symbol.for("react.portal"),H=Symbol.for("react.fragment"),G=Symbol.for("react.strict_mode"),re=Symbol.for("react.profiler"),ae=Symbol.for("react.consumer"),me=Symbol.for("react.context"),be=Symbol.for("react.forward_ref"),xe=Symbol.for("react.suspense"),Ae=Symbol.for("react.suspense_list"),ke=Symbol.for("react.memo"),_e=Symbol.for("react.lazy"),Ue=Symbol.for("react.activity"),De=Symbol.iterator,Qe={},bt={isMounted:function(){return!1},enqueueForceUpdate:function(g){r(g,"forceUpdate")},enqueueReplaceState:function(g){r(g,"replaceState")},enqueueSetState:function(g){r(g,"setState")}},Rt=Object.assign,Dt={};Object.freeze(Dt),o.prototype.isReactComponent={},o.prototype.setState=function(g,E){if(typeof g!=="object"&&typeof g!=="function"&&g!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,g,E,"setState")},o.prototype.forceUpdate=function(g){this.updater.enqueueForceUpdate(this,g,"forceUpdate")};var lt={isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."]};for(V in lt)lt.hasOwnProperty(V)&&e(V,lt[V]);n.prototype=o.prototype,lt=i.prototype=new n,lt.constructor=i,Rt(lt,o.prototype),lt.isPureReactComponent=!0;var Or=Array.isArray,$n=Symbol.for("react.client.reference"),Le={H:null,A:null,T:null,S:null,actQueue:null,asyncTransitions:0,isBatchingLegacy:!1,didScheduleLegacyUpdate:!1,didUsePromise:!1,thrownErrors:[],getCurrentStack:null,recentlyCreatedOwnerStacks:0},ao=Object.prototype.hasOwnProperty,cs=console.createTask?console.createTask:function(){return null};lt={react_stack_bottom_frame:function(g){return g()}};var ls,_a,us={},On=lt.react_stack_bottom_frame.bind(lt,m)(),ql=cs(d(m)),Go=!1,Ea=/\/+/g,Ia=typeof reportError==="function"?reportError:function(g){if(typeof window==="object"&&typeof window.ErrorEvent==="function"){var E=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof g==="object"&&g!==null&&typeof g.message==="string"?String(g.message):String(g),error:g});if(!window.dispatchEvent(E))return}else if(typeof process==="object"&&typeof process.emit==="function"){process.emit("uncaughtException",g);return}console.error(g)},f=!1,U=null,ne=0,ie=!1,X=!1,w=typeof queueMicrotask==="function"?function(g){queueMicrotask(function(){return queueMicrotask(g)})}:T;lt=Object.freeze({__proto__:null,c:function(g){return ee().useMemoCache(g)}});var V={map:P,forEach:function(g,E,D){P(g,function(){E.apply(this,arguments)},D)},count:function(g){var E=0;return P(g,function(){E++}),E},toArray:function(g){return P(g,function(E){return E})||[]},only:function(g){if(!A(g))throw Error("React.Children.only expected to receive a single React element child.");return g}};xde.Activity=Ue,xde.Children=V,xde.Component=o,xde.Fragment=H,xde.Profiler=re,xde.PureComponent=i,xde.StrictMode=G,xde.Suspense=xe,xde.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Le,xde.__COMPILER_RUNTIME=lt,xde.act=function(g){var E=Le.actQueue,D=ne;ne++;var J=Le.actQueue=E!==null?E:[],M=!1;try{var te=g()}catch(fe){Le.thrownErrors.push(fe)}if(0<Le.thrownErrors.length)throw I(E,D),g=B(Le.thrownErrors),Le.thrownErrors.length=0,g;if(te!==null&&typeof te==="object"&&typeof te.then==="function"){var se=te;return w(function(){M||ie||(ie=!0,console.error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"))}),{then:function(fe,Te){M=!0,se.then(function(ze){if(I(E,D),D===0){try{k(J),T(function(){return R(ze,fe,Te)})}catch(ds){Le.thrownErrors.push(ds)}if(0<Le.thrownErrors.length){var Cn=B(Le.thrownErrors);Le.thrownErrors.length=0,Te(Cn)}}else fe(ze)},function(ze){I(E,D),0<Le.thrownErrors.length?(ze=B(Le.thrownErrors),Le.thrownErrors.length=0,Te(ze)):Te(ze)})}}}var ye=te;if(I(E,D),D===0&&(k(J),J.length!==0&&w(function(){M||ie||(ie=!0,console.error("A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)"))}),Le.actQueue=null),0<Le.thrownErrors.length)throw g=B(Le.thrownErrors),Le.thrownErrors.length=0,g;return{then:function(fe,Te){M=!0,D===0?(Le.actQueue=J,T(function(){return R(ye,fe,Te)})):fe(ye)}}},xde.cache=function(g){return function(){return g.apply(null,arguments)}},xde.cacheSignal=function(){return null},xde.captureOwnerStack=function(){var g=Le.getCurrentStack;return g===null?null:g()},xde.cloneElement=function(g,E,D){if(g===null||g===void 0)throw Error("The argument must be a React element, but you passed "+g+".");var J=Rt({},g.props),M=g.key,te=g._owner;if(E!=null){var se;e:{if(ao.call(E,"ref")&&(se=Object.getOwnPropertyDescriptor(E,"ref").get)&&se.isReactWarning){se=!1;break e}se=E.ref!==void 0}se&&(te=p()),h(E)&&(l(E.key),M=""+E.key);for(ye in E)!ao.call(E,ye)||ye==="key"||ye==="__self"||ye==="__source"||ye==="ref"&&E.ref===void 0||(J[ye]=E[ye])}var ye=arguments.length-2;if(ye===1)J.children=D;else if(1<ye){se=Array(ye);for(var fe=0;fe<ye;fe++)se[fe]=arguments[fe+2];J.children=se}J=S(g.type,M,J,te,g._debugStack,g._debugTask);for(M=2;M<arguments.length;M++)_(arguments[M]);return J},xde.createContext=function(g){return g={$$typeof:me,_currentValue:g,_currentValue2:g,_threadCount:0,Provider:null,Consumer:null},g.Provider=g,g.Consumer={$$typeof:ae,_context:g},g._currentRenderer=null,g._currentRenderer2=null,g},xde.createElement=function(g,E,D){for(var J=2;J<arguments.length;J++)_(arguments[J]);J={};var M=null;if(E!=null)for(fe in _a||!("__self"in E)||"key"in E||(_a=!0,console.warn("Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform")),h(E)&&(l(E.key),M=""+E.key),E)ao.call(E,fe)&&fe!=="key"&&fe!=="__self"&&fe!=="__source"&&(J[fe]=E[fe]);var te=arguments.length-2;if(te===1)J.children=D;else if(1<te){for(var se=Array(te),ye=0;ye<te;ye++)se[ye]=arguments[ye+2];Object.freeze&&Object.freeze(se),J.children=se}if(g&&g.defaultProps)for(fe in te=g.defaultProps,te)J[fe]===void 0&&(J[fe]=te[fe]);M&&b(J,typeof g==="function"?g.displayName||g.name||"Unknown":g);var fe=1e4>Le.recentlyCreatedOwnerStacks++;return S(g,M,J,p(),fe?Error("react-stack-top-frame"):On,fe?cs(d(g)):ql)},xde.createRef=function(){var g={current:null};return Object.seal(g),g},xde.forwardRef=function(g){g!=null&&g.$$typeof===ke?console.error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."):typeof g!=="function"?console.error("forwardRef requires a render function but was given %s.",g===null?"null":typeof g):g.length!==0&&g.length!==2&&console.error("forwardRef render functions accept exactly two parameters: props and ref. %s",g.length===1?"Did you forget to use the ref parameter?":"Any additional parameter will be undefined."),g!=null&&g.defaultProps!=null&&console.error("forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?");var E={$$typeof:be,render:g},D;return Object.defineProperty(E,"displayName",{enumerable:!1,configurable:!0,get:function(){return D},set:function(J){D=J,g.name||g.displayName||(Object.defineProperty(g,"name",{value:J}),g.displayName=J)}}),E},xde.isValidElement=A,xde.lazy=function(g){g={_status:-1,_result:g};var E={$$typeof:_e,_payload:g,_init:W},D={name:"lazy",start:-1,end:-1,value:null,owner:null,debugStack:Error("react-stack-top-frame"),debugTask:console.createTask?console.createTask("lazy()"):null};return g._ioInfo=D,E._debugInfo=[{awaited:D}],E},xde.memo=function(g,E){g==null&&console.error("memo: The first argument must be a component. Instead received: %s",g===null?"null":typeof g),E={$$typeof:ke,type:g,compare:E===void 0?null:E};var D;return Object.defineProperty(E,"displayName",{enumerable:!1,configurable:!0,get:function(){return D},set:function(J){D=J,g.name||g.displayName||(Object.defineProperty(g,"name",{value:J}),g.displayName=J)}}),E},xde.startTransition=function(g){var E=Le.T,D={};D._updatedFibers=new Set,Le.T=D;try{var J=g(),M=Le.S;M!==null&&M(D,J),typeof J==="object"&&J!==null&&typeof J.then==="function"&&(Le.asyncTransitions++,J.then(j,j),J.then(s,Ia))}catch(te){Ia(te)}finally{E===null&&D._updatedFibers&&(g=D._updatedFibers.size,D._updatedFibers.clear(),10<g&&console.warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table.")),E!==null&&D.types!==null&&(E.types!==null&&E.types!==D.types&&console.error("We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React."),E.types=D.types),Le.T=E}},xde.unstable_useCacheRefresh=function(){return ee().useCacheRefresh()},xde.use=function(g){return ee().use(g)},xde.useActionState=function(g,E,D){return ee().useActionState(g,E,D)},xde.useCallback=function(g,E){return ee().useCallback(g,E)},xde.useContext=function(g){var E=ee();return g.$$typeof===ae&&console.error("Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?"),E.useContext(g)},xde.useDebugValue=function(g,E){return ee().useDebugValue(g,E)},xde.useDeferredValue=function(g,E){return ee().useDeferredValue(g,E)},xde.useEffect=function(g,E){return g==null&&console.warn("React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?"),ee().useEffect(g,E)},xde.useEffectEvent=function(g){return ee().useEffectEvent(g)},xde.useId=function(){return ee().useId()},xde.useImperativeHandle=function(g,E,D){return ee().useImperativeHandle(g,E,D)},xde.useInsertionEffect=function(g,E){return g==null&&console.warn("React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?"),ee().useInsertionEffect(g,E)},xde.useLayoutEffect=function(g,E){return g==null&&console.warn("React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?"),ee().useLayoutEffect(g,E)},xde.useMemo=function(g,E){return ee().useMemo(g,E)},xde.useOptimistic=function(g,E){return ee().useOptimistic(g,E)},xde.useReducer=function(g,E,D){return ee().useReducer(g,E,D)},xde.useRef=function(g){return ee().useRef(g)},xde.useState=function(g){return ee().useState(g)},xde.useSyncExternalStore=function(g,E,D){return ee().useSyncExternalStore(g,E,D)},xde.useTransition=function(){return ee().useTransition()},xde.version="19.2.7",typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop==="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())})()});var XM,eq;var DR=v(()=>{XM=Jl(NR(),1),eq=XM.createContext(void 0)});var _de;var tq=v(()=>{CR();YM();DR();pe();_de=Jl(NR(),1)});var Ede,Ide;var rq=v(()=>{Ot();pe();TR();Ede=rl.omit({url:!0,analyticsScript:!0}),Ide=Ede.extend({title:c.string().optional().describe("Optional site title override"),description:c.string().optional().describe("Optional site description override")})});function LR(e,t={}){let r=nq(e),o=nq(t.sharedDomain??"rizom.ai").replace(/^\./,""),n=`.${o}`;if(r.endsWith(n)){let i=r.slice(0,-n.length);if(i.length>0&&!i.includes("."))return`${i}-preview.${o}`}return`preview.${r}`}function nq(e){return e.trim().replace(/^https?:\/\//i,"").replace(/\/$/,"").toLowerCase()}var oq=v(()=>{gg()});var Rde,Tde;var iq=v(()=>{pe();fy();PR();Rde=c.string(),Tde=c.custom((e)=>Vs(e)&&SM.safeParse(e).success)});var $de;var sq=v(()=>{gg();pe();$de=c.object({title:c.string().min(1),slug:c.string().min(1),description:c.string(),content:c.string(),author:c.string(),publishedAt:c.iso.datetime({offset:!0}),category:c.string().min(1).optional()})});var aq=v(()=>{RR();OM();TR();FM();PR();tq();rq();oq();iq();DR();sq()});function cq(e,t={}){return LR(e,t)}var lq=v(()=>{aq()});var hq={};Lt(hq,{assertPilotUsersRemoved:()=>mq,createPilotOffboardDriver:()=>dq,offboardPilotUsers:()=>Nde});import{readdir as Ode,readFile as Cde,rm as dp,writeFile as Pde}from"fs/promises";import{basename as zde,join as No}from"path";async function Nde(e,t){let r=[...new Set(t.handles.map((p)=>br.parse(p)))].sort((p,m)=>p.localeCompare(m));if(r.length===0)throw Error("At least one pilot handle is required");let o=t.dryRun??!0,n=`sunset:${r.join(",")}`;if(!o&&t.confirmation!==n)throw Error(`Exact confirmation required: ${n}`);let i=t.env??process.env,s=t.logger??console.info,a=await wt(e),l=r.map((p)=>Dde(a,p,i)),u=t.driver??dq({env:i,fetchImpl:t.fetchImpl,contentRepoTokenName:a.pilot.contentRepoAdminToken}),d=await Promise.all(l.map(async(p)=>({target:p,inspection:await u.inspect(p)})));if(Bde(d),jde(d,o,s),!o){for(let p of d)if(!p.inspection.contentRepoArchived)await u.archiveContentRepo(p.target),s(`[${p.target.handle}] archived ${p.target.contentRepo}`);for(let p of d)for(let m of p.inspection.dnsRecords)await u.deleteDnsRecord(p.target,m),s(`[${p.target.handle}] deleted DNS ${m.name}`);for(let p of d)if(p.inspection.server)await u.deleteServer(p.target,p.inspection.server),s(`[${p.target.handle}] deleted ${p.target.instanceName}`);await Lde(l,u,t.sleep??((p)=>new Promise((m)=>setTimeout(m,p)))),await Zde(e,r),await Pi(e),await mq(e,r),s(`Removed desired state for ${r.length} pilot user(s)`)}return{dryRun:o,handles:r,confirmation:n,plans:d}}function Dde(e,t,r){let o=e.users.find((d)=>d.handle===t),n=`${t}${e.pilot.domainSuffix}`,i=o?.domain??n,s=cq(i,{sharedDomain:e.pilot.domainSuffix}),a=o?.cloudflareZoneId??xy(r,"CF_ZONE_ID"),l=o?.contentRepo??`${e.pilot.contentRepoPrefix}${t}-content`,u=l.includes("/")?l:`${e.pilot.githubOrg}/${l}`;return{handle:t,instanceName:`rover-${t}`,domain:i,previewDomain:s,...i===n?{}:{wwwDomain:`www.${i}`},contentRepo:u,cloudflareZoneId:a}}async function Lde(e,t,r){for(let o of e)for(let n=1;n<=20;n+=1){let i=await t.inspect(o);if(!i.server&&i.dnsRecords.length===0&&i.contentRepoArchived)break;if(n===20)throw Error(`[${o.handle}] provider cleanup did not converge`);await r(1500)}}function Bde(e){for(let{target:t,inspection:r}of e){if(r.server&&r.server.name!==t.instanceName)throw Error(`[${t.handle}] unexpected server name: ${r.server.name}`);let o=new Set([t.domain,t.previewDomain,...t.wwwDomain?[t.wwwDomain]:[]]);for(let n of r.dnsRecords){if(!o.has(n.name))throw Error(`[${t.handle}] refusing unexpected DNS record ${n.name}`);if(n.type==="A"&&r.server?.ip&&n.content!==r.server.ip)throw Error(`[${t.handle}] ${n.name} does not point to the retiring server`)}}}function jde(e,t,r){r(`${t?"Dry run":"Apply"}: ${e.map(({target:o})=>o.handle).join(", ")}`);for(let{target:o,inspection:n}of e){let i=n.server?`delete ${o.instanceName}`:"already absent",s=n.dnsRecords.length>0?n.dnsRecords.map((l)=>`${l.type} ${l.name}`).join(", "):"already absent",a=n.contentRepoArchived?"already archived":`archive ${o.contentRepo}`;r(`[${o.handle}] server: ${i}; DNS: ${s}; repo: ${a}`)}r("Runtime backups: none")}async function Zde(e,t){let r=new Set(t),o=No(e,"cohorts");for(let n of(await Ode(o)).filter((i)=>i.endsWith(".yaml"))){let i=No(o,n),s=await Cde(i,"utf8"),a=tn(s);if(a.errors.length>0)throw Error(`${n}: ${a.errors[0]?.message??"invalid YAML"}`);let l=a.get("members",!0);if(!vR(l))throw Error(`${n}: members must be a sequence`);let u=l.items.filter((d)=>!Co(d)||typeof d.value!=="string"||!r.has(d.value));if(u.length===l.items.length)continue;if(u.length===0){await dp(i);continue}l.items=u,hn.parse(a.toJS()),await Pde(i,a.toString())}for(let n of t)await Promise.all([dp(No(e,"users",`${n}.yaml`),{force:!0}),dp(No(e,"users",`${n}.secrets.yaml`),{force:!0}),dp(No(e,"users",`${n}.secrets.yaml.age`),{force:!0}),dp(No(e,"users",n),{recursive:!0,force:!0})])}function dq(e){let t=e.fetchImpl??fetch,r=xy(e.env,"HCLOUD_TOKEN"),o=xy(e.env,"CF_API_TOKEN"),n=xy(e.env,e.contentRepoTokenName);return{async inspect(i){let[s,a,l]=await Promise.all([Ude(t,r,i.instanceName),Promise.all([i.domain,i.previewDomain,...i.wwwDomain?[i.wwwDomain]:[]].map((u)=>Mde(t,o,i.cloudflareZoneId,u))).then((u)=>u.flat()),qde(t,n,i.contentRepo)]);if(s.length>1)throw Error(`[${i.handle}] expected at most one server, found ${s.length}`);return{...s[0]?{server:s[0]}:{},dnsRecords:a,contentRepoArchived:l.archived}},async archiveContentRepo(i){await ol(t,`https://api.github.com/repos/${i.contentRepo}`,{method:"PATCH",headers:pq(n),body:JSON.stringify({archived:!0})},"GitHub repository archive")},async deleteDnsRecord(i,s){if(il(await ol(t,`https://api.cloudflare.com/client/v4/zones/${i.cloudflareZoneId}/dns_records/${s.id}`,{method:"DELETE",headers:fq(o)},"Cloudflare DNS delete")).success!==!0)throw Error(`Cloudflare DNS delete failed for ${s.name}`)},async deleteServer(i,s){await ol(t,`https://api.hetzner.cloud/v1/servers/${s.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}},"Hetzner server delete",!0)}}}async function Ude(e,t,r){let o=new URL("https://api.hetzner.cloud/v1/servers");o.searchParams.set("label_selector",`brain=${r}`);let i=il(await ol(e,o.toString(),{headers:{Authorization:`Bearer ${t}`}},"Hetzner server lookup")).servers;if(!Array.isArray(i))throw Error("Hetzner server lookup returned an invalid payload");return i.map((s)=>{let a=il(s),l=uq(a.public_net),u=uq(l?.ipv4);return{id:Fde(a.id,"Hetzner server id"),name:pp(a.name,"Hetzner server name"),...typeof u?.ip==="string"?{ip:u.ip}:{}}})}async function Mde(e,t,r,o){let n=new URL(`https://api.cloudflare.com/client/v4/zones/${r}/dns_records`);n.searchParams.set("name",o);let i=il(await ol(e,n.toString(),{headers:fq(t)},"Cloudflare DNS lookup")),s=i.result;if(i.success!==!0||!Array.isArray(s))throw Error(`Cloudflare DNS lookup failed for ${o}`);return s.map((a)=>{let l=il(a),u=pp(l.type,"Cloudflare record type");if(u!=="A"&&u!=="CNAME")throw Error(`Unsupported Cloudflare record type ${u} for ${o}`);return{id:pp(l.id,"Cloudflare record id"),name:pp(l.name,"Cloudflare record name"),type:u,content:pp(l.content,"Cloudflare record content")}})}async function qde(e,t,r){let o=il(await ol(e,`https://api.github.com/repos/${r}`,{headers:pq(t)},"GitHub repository lookup"));if(typeof o.archived!=="boolean")throw Error(`Invalid repository archive state for ${r}`);return{archived:o.archived}}async function ol(e,t,r,o,n=!1){let i=await e(t,r),s=await i.text();if(!i.ok)throw Error(`${o} failed (${i.status}): ${s}`);if(!s&&n)return{};try{return JSON.parse(s)}catch{throw Error(`${o} returned an invalid JSON response`)}}function pq(e){return{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-GitHub-Api-Version":"2022-11-28"}}function fq(e){return{Authorization:`Bearer ${e}`}}function xy(e,t){let r=e[t];if(!r)throw Error(`Missing required environment variable: ${t}`);return r}function il(e){if(!Vs(e))throw Error("Provider returned an unexpected payload");return e}function uq(e){return Vs(e)?e:void 0}function pp(e,t){if(typeof e!=="string"||e.length===0)throw Error(`Missing ${t}`);return e}function Fde(e,t){if(typeof e!=="number")throw Error(`Missing ${t}`);return e}async function mq(e,t){for(let r of t)for(let o of[No(e,"users",`${r}.yaml`),No(e,"users",`${r}.secrets.yaml.age`),No(e,"users",r)])if(await kr(o))throw Error(`Offboarded user state remains: ${zde(o)}`)}var gq=v(()=>{Xc();gn();lq();Cd();Ao();Ys()});var yq="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as bq}from"crypto";function Kde(e){if(e<0)throw RangeError("Wrong ID size");try{if(!Fi||Fi.length<e)Fi=Buffer.allocUnsafe(e*Jde),bq.getRandomValues(Fi),sl=0;else if(sl+e>Fi.length)bq.getRandomValues(Fi),sl=0}catch(t){throw Fi=void 0,t}sl+=e}function Sq(e=21){Kde(e|=0);let t="";for(let r=sl-e;r<sl;r++)t+=yq[Fi[r]&63];return t}var Jde=128,Fi,sl;var vq=()=>{};function Do(e=12){return Sq(e)}var fp=v(()=>{vq()});import{openSync as Hde,writeSync as Vde}from"fs";function Wde(e){return al?`[${al}] ${e}`:e}class Rr{static instance=null;level;context;useStderr;format;logFile;fileHandle;constructor(e={},t){if(this.level=e.level??aa.INFO,this.context=e.context??void 0,this.useStderr=e.useStderr??!1,this.format=e.format??"text",this.logFile=e.logFile,t!==void 0)this.fileHandle=t;else if(this.logFile)try{this.fileHandle=Hde(this.logFile,"a")}catch{}}static getInstance(e){if(!Rr.instance)Rr.instance=new Rr(e);else{if(e?.useStderr!==void 0)Rr.instance.useStderr=e.useStderr;if(e?.level!==void 0)Rr.instance.level=e.level}return Rr.instance}static resetInstance(){Rr.instance=null,al=void 0}static setProcessRole(e){al=e}static createFresh(e){return new Rr(e)}formatEntry(e,t,r){if(this.format==="json")return this.formatJsonEntry(e,t,r);return Wde([`[${new Date().toISOString()}]`,...this.context?[`[${this.context}]`]:[],t].join(" "))}write(e,t,r,o){if(this.format==="json")e(this.formatEntry(t,r,o));else if(o.length>0)e(this.formatEntry(t,r,[]),...o);else e(this.formatEntry(t,r,[]));if(this.fileHandle!==void 0){let n=this.formatJsonEntry(t,r,o);try{Vde(this.fileHandle,n+`
417
- `)}catch{}}}formatJsonEntry(e,t,r){let o={ts:new Date().toISOString(),level:e,...al&&{role:al},msg:t};if(this.context)o.ctx=this.context;if(r.length>0)o.data=r;return JSON.stringify(o)}debugStream(){return this.useStderr?console.error.bind(console):console.debug.bind(console)}silly(e,...t){if(this.level<=aa.SILLY)this.write(this.debugStream(),"silly",e,t)}verbose(e,...t){if(this.level<=aa.VERBOSE)this.write(this.debugStream(),"verbose",e,t)}debug(e,...t){if(this.level<=aa.DEBUG)this.write(this.debugStream(),"debug",e,t)}info(e,...t){if(this.level<=aa.INFO){let r=this.useStderr?console.error.bind(console):console.info.bind(console);this.write(r,"info",e,t)}}warn(e,...t){if(this.level<=aa.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=aa.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new Rr({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var aa,al,E2e;var BR=v(()=>{aa={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};E2e=Rr.getInstance()});var jR,Gde,cl,R2e;var mp=v(()=>{Ot();pe();jR=c.enum(["file_operations","content_operations","data_processing","batch_processing"]),Gde=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:jR,operationTarget:c.string().optional(),interfaceType:c.string().optional(),interfaceId:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:Wn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:ko.optional()}),cl=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:jR,operationTarget:c.string().optional(),interfaceType:c.string().optional(),interfaceId:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:Wn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:ko.optional(),rootJobId:c.string()}),R2e=c.enum(["none","skip","replace","coalesce"])});var Qde,Ji=15000;var hp=v(()=>{mp();pe();Qde=c.object({id:c.string(),type:c.string(),data:c.string(),status:c.enum(["pending","processing","completed","failed"]),source:c.string().nullable(),priority:c.number(),retryCount:c.number(),maxRetries:c.number(),lastError:c.string().nullable(),lastErrorPublic:c.unknown(),createdAt:c.number(),scheduledFor:c.number(),startedAt:c.number().nullable(),completedAt:c.number().nullable(),attemptId:c.string().nullable(),workerSlotId:c.string().nullable(),workerSessionId:c.string().nullable(),leaseExpiresAt:c.number().nullable(),attemptHeartbeatAt:c.number().nullable(),runtimeUpdatedAt:c.number().nullable(),metadata:cl,progress:c.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:c.unknown().nullable().optional()})});var ZR,wq,Oe,Yde,Xde,xq,_q,Eq;var Lo=v(()=>{Ot();pe();mp();ZR=c.enum(["pending","processing","completed","failed"]),wq=c.enum(["completed","failed"]),Oe={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},Yde=c.object({id:c.string(),type:c.string(),status:ZR,data:c.unknown(),result:c.unknown().optional(),lastError:c.string().optional().nullable(),attempts:c.number(),maxRetries:c.number(),priority:c.number(),createdAt:c.date(),updatedAt:c.date(),processedAt:c.date().optional().nullable(),completedAt:c.date().optional().nullable(),failedAt:c.date().optional().nullable()}),Xde=c.object({jobId:c.string(),type:c.string(),status:wq,result:c.unknown().optional(),error:c.string().optional()}),xq=c.object({success:c.literal(!1),error:c.string().optional()}),_q=c.object({id:c.string(),type:c.enum(["job","batch"]),status:ZR,message:c.string().optional(),progress:c.object({current:c.number(),total:c.number(),percentage:c.number()}).optional(),aggregationKey:c.string().optional(),batchDetails:c.object({totalOperations:c.number(),completedOperations:c.number(),failedOperations:c.number(),currentOperation:c.string().optional(),errors:c.array(c.string()).optional()}).optional(),jobDetails:c.object({jobType:c.string(),priority:c.number(),retryCount:c.number()}).optional(),metadata:cl}),Eq=Ci(zk.progress,_q)});var Ce,Wt;var wn=v(()=>{Ce=class Ce extends Error{code;extendedCode;rawCode;constructor(e,t,r,o,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=o,this.name="LibsqlError"}};Wt=class Wt extends Ce{statementIndex;constructor(e,t,r,o,n,i){super(e,r,o,n,i);this.statementIndex=t,this.name="LibsqlBatchError"}}});function Iq(e){let t=epe.exec(e);if(t===null)throw new Ce(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,o=r.scheme,n=r.authority!==void 0?tpe(r.authority):void 0,i=ca(r.path),s=r.query!==void 0?npe(r.query):void 0,a=r.fragment!==void 0?ca(r.fragment):void 0;return{scheme:o,authority:n,path:i,query:s,fragment:a}}function tpe(e){let t=rpe.exec(e);if(t===null)throw new Ce("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,o=ca(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,i=r.username!==void 0?{username:ca(r.username),password:r.password!==void 0?ca(r.password):void 0}:void 0;return{host:o,port:n,userinfo:i}}function npe(e){let t=e.split("&"),r=[];for(let o of t){if(o==="")continue;let n,i,s=o.indexOf("=");if(s<0)n=o,i="";else n=o.substring(0,s),i=o.substring(s+1);r.push({key:ca(n.replaceAll("+"," ")),value:ca(i.replaceAll("+"," "))})}return{pairs:r}}function ca(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Ce(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function gp(e,t,r){if(t===void 0)throw new Ce(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let o=`${e}:`,n=ope(t.host),i=ipe(t.port),a=`//${spe(t.userinfo)}${n}${i}`,l=r.split("/").map(encodeURIComponent).join("/");if(l!==""&&!l.startsWith("/"))l="/"+l;return new URL(`${o}${a}${l}`)}function ope(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function ipe(e){return e!==void 0?`:${e}`:""}function spe(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var epe,rpe;var _y=v(()=>{wn();epe=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();rpe=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var ul,kq,Aq,yp,Ey,ape,Gt,Rq,Oq=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),Cq=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),Pq=(e)=>{let t,r,o,n,i="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(o=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|o<<8|n,i+=yp[t>>18&63]+yp[t>>12&63]+yp[t>>6&63]+yp[t&63]}return s?i.slice(0,s-3)+"===".substring(s):i},qR,UR,Iy=(e,t=!1)=>t?Oq(UR(e)):UR(e),cpe=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?Gt(192|t>>>6)+Gt(128|t&63):Gt(224|t>>>12&15)+Gt(128|t>>>6&63)+Gt(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return Gt(240|t>>>18&7)+Gt(128|t>>>12&63)+Gt(128|t>>>6&63)+Gt(128|t&63)}},lpe,zq=(e)=>e.replace(lpe,cpe),Tq,ll=(e,t=!1)=>t?Oq(Tq(e)):Tq(e),$q=(e)=>ll(e,!0),upe,dpe=(e)=>{switch(e.length){case 4:var t=(7&e.charCodeAt(0))<<18|(63&e.charCodeAt(1))<<12|(63&e.charCodeAt(2))<<6|63&e.charCodeAt(3),r=t-65536;return Gt((r>>>10)+55296)+Gt((r&1023)+56320);case 3:return Gt((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return Gt((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},Nq=(e)=>e.replace(upe,dpe),Dq=(e)=>{if(e=e.replace(/\s+/g,""),!ape.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,o,n=[];for(let i=0;i<e.length;)if(t=Ey[e.charAt(i++)]<<18|Ey[e.charAt(i++)]<<12|(r=Ey[e.charAt(i++)])<<6|(o=Ey[e.charAt(i++)]),r===64)n.push(Gt(t>>16&255));else if(o===64)n.push(Gt(t>>16&255,t>>8&255));else n.push(Gt(t>>16&255,t>>8&255,t&255));return n.join("")},FR,Lq,Bq=(e)=>Lq(jq(e)),ppe,jq=(e)=>Cq(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),MR=(e)=>ppe(jq(e)),fpe=(e)=>{if(typeof e!=="string")return!1;let t=e.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},Zq=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),Uq=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,Zq(r));e("fromBase64",function(){return MR(this)}),e("toBase64",function(t){return ll(this,t)}),e("toBase64URI",function(){return ll(this,!0)}),e("toBase64URL",function(){return ll(this,!0)}),e("toUint8Array",function(){return Bq(this)})},Mq=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,Zq(r));e("toBase64",function(t){return Iy(this,t)}),e("toBase64URI",function(){return Iy(this,!0)}),e("toBase64URL",function(){return Iy(this,!0)})},mpe=()=>{Uq(),Mq()},dl;var ky=v(()=>{ul=typeof Buffer==="function",kq=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,Aq=typeof TextEncoder==="function"?new TextEncoder:void 0,yp=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),Ey=((e)=>{let t={};return e.forEach((r,o)=>t[r]=o),t})(yp),ape=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,Gt=String.fromCharCode.bind(String),Rq=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),qR=typeof btoa==="function"?(e)=>btoa(e):ul?(e)=>Buffer.from(e,"binary").toString("base64"):Pq,UR=ul?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let o=0,n=e.length;o<n;o+=4096)r.push(Gt.apply(null,e.subarray(o,o+4096)));return qR(r.join(""))},lpe=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Tq=ul?(e)=>Buffer.from(e,"utf8").toString("base64"):Aq?(e)=>UR(Aq.encode(e)):(e)=>qR(zq(e)),upe=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,FR=typeof atob==="function"?(e)=>atob(Cq(e)):ul?(e)=>Buffer.from(e,"base64").toString("binary"):Dq,Lq=ul?(e)=>Rq(Buffer.from(e,"base64")):(e)=>Rq(FR(e).split("").map((t)=>t.charCodeAt(0))),ppe=ul?(e)=>Buffer.from(e,"base64").toString("utf8"):kq?(e)=>kq.decode(Lq(e)):(e)=>Nq(FR(e)),dl={version:"3.8.0",VERSION:"3.8.0",atob:FR,atobPolyfill:Dq,btoa:qR,btoaPolyfill:Pq,fromBase64:MR,toBase64:ll,encode:ll,encodeURI:$q,encodeURL:$q,utob:zq,btou:Nq,decode:MR,isValid:fpe,fromUint8Array:Iy,toUint8Array:Bq,extendString:Uq,extendUint8Array:Mq,extendBuiltins:mpe}});function Ki(e){if(e==="write")return"BEGIN IMMEDIATE";else if(e==="read")return"BEGIN TRANSACTION READONLY";else if(e==="deferred")return"BEGIN DEFERRED";else throw RangeError('Unknown transaction mode, supported values are "write", "read" and "deferred"')}class pl{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,o,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=o,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(hpe),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function hpe(e){return Array.prototype.map.call(e,gpe)}function gpe(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return dl.fromUint8Array(new Uint8Array(e));else return e}var Xn="https://github.com/libsql/libsql-client-ts#supported-urls";var fl=v(()=>{ky()});function Fq(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function bp(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:o,tls:n,intMode:i,concurrency:s}=e;s=Math.max(0,s||20),i??="number";let a=[];if(r===qq)r="file::memory:";let l=Iq(r),u=l.scheme.toLowerCase(),d=u==="file"&&l.path===qq&&l.authority===void 0,p;if(d)p={cache:{values:["shared","private"],update:(y,S)=>a.push(`${y}=${S}`)}};else p={tls:{values:["0","1"],update:(y,S)=>n=S==="1"},authToken:{update:(y,S)=>o=S}};for(let{key:y,value:S}of l.query?.pairs??[]){if(!Object.hasOwn(p,y))throw new Ce(`Unsupported URL query parameter ${JSON.stringify(y)}`,"URL_PARAM_NOT_SUPPORTED");let x=p[y];if(x.values!==void 0&&!x.values.includes(S))throw new Ce(`Unknown value for the "${y}" query argument: ${JSON.stringify(S)}. Supported values are: [${x.values.map((_)=>'"'+_+'"').join(", ")}]`,"URL_INVALID");if(x.update!==void 0)x?.update(y,S)}let m=a.length===0?"":`?${a.join("&")}`,h=l.path+m,b;if(u==="libsql")if(n===!1){if(l.authority?.port===void 0)throw new Ce('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");b=t?"http":"ws"}else b=t?"https":"wss";else b=u;if(b==="http"||b==="ws")n??=!1;else n??=!0;if(b!=="http"&&b!=="ws"&&b!=="https"&&b!=="wss"&&b!=="file")throw new Ce(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(l.scheme+":")}. For more information, please read ${Xn}`,"URL_SCHEME_NOT_SUPPORTED");if(i!=="number"&&i!=="bigint"&&i!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(i)}`);if(l.fragment!==void 0)throw new Ce(`URL fragments are not supported: ${JSON.stringify("#"+l.fragment)}`,"URL_INVALID");if(d)return{scheme:"file",tls:!1,path:h,intMode:i,concurrency:s,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout,authToken:void 0,encryptionKey:void 0,remoteEncryptionKey:void 0,authority:void 0};return{scheme:b,tls:n,authority:l.authority,path:h,authToken:o,intMode:i,concurrency:s,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout}}var qq=":memory:";var Sp=v(()=>{wn();_y();fl()});var Kq=ge(function(rn){var ype=rn&&rn.__createBinding||(Object.create?function(e,t,r,o){if(o===void 0)o=r;var n=Object.getOwnPropertyDescriptor(t,r);if(!n||("get"in n?!t.__esModule:n.writable||n.configurable))n={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,o,n)}:function(e,t,r,o){if(o===void 0)o=r;e[o]=t[r]}),bpe=rn&&rn.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Jq=rn&&rn.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null){for(var r in e)if(r!=="default"&&Object.prototype.hasOwnProperty.call(e,r))ype(t,e,r)}return bpe(t,e),t};Object.defineProperty(rn,"__esModule",{value:!0});rn.load=rn.currentTarget=void 0;var Spe=Jq(Fr("path")),vpe=Jq(Fr("fs"));function wpe(){let e=null;switch(process.platform){case"android":switch(process.arch){case"arm":return"android-arm-eabi";case"arm64":return"android-arm64"}e="Android";break;case"win32":switch(process.arch){case"x64":return"win32-x64-msvc";case"arm64":return"win32-arm64-msvc";case"ia32":return"win32-ia32-msvc"}e="Windows";break;case"darwin":switch(process.arch){case"x64":return"darwin-x64";case"arm64":return"darwin-arm64"}e="macOS";break;case"linux":switch(process.arch){case"x64":case"arm64":return xpe()?`linux-${process.arch}-gnu`:`linux-${process.arch}-musl`;case"arm":return"linux-arm-gnueabihf"}e="Linux";break;case"freebsd":if(process.arch==="x64")return"freebsd-x64";e="FreeBSD";break}if(e)throw Error(`Neon: unsupported ${e} architecture: ${process.arch}`);throw Error(`Neon: unsupported system: ${process.platform}`)}rn.currentTarget=wpe;function xpe(){let e=process.report?.getReport();if(typeof e!=="object"||!e||!("header"in e))return!1;let t=e.header;return typeof t==="object"&&!!t&&"glibcVersionRuntime"in t}function _pe(e){let t=Spe.join(e,"index.node");return vpe.existsSync(t)?Fr(t):null}rn.load=_pe});var Wq=ge(function(W2e,Vq){var Hq=()=>process.platform==="linux",JR=null,Epe=()=>{if(!JR)JR=Hq()&&process.report?process.report.getReport():{};return JR};Vq.exports={isLinux:Hq,getReport:Epe}});var Yq=ge(function(G2e,Qq){var Gq=Fr("fs"),Ipe=(e)=>Gq.readFileSync(e,"utf-8"),kpe=(e)=>new Promise((t,r)=>{Gq.readFile(e,"utf-8",(o,n)=>{if(o)r(o);else t(n)})});Qq.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:Ipe,readFile:kpe}});var h4=ge(function(Q2e,m4){var e4=Fr("child_process"),{isLinux:ml,getReport:t4}=Wq(),{LDD_PATH:Ay,readFile:r4,readFileSync:n4}=Yq(),eo,to,Hi="",o4=()=>{if(!Hi)return new Promise((e)=>{e4.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{Hi=t?" ":r,e(Hi)})});return Hi},i4=()=>{if(!Hi)try{Hi=e4.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){Hi=" "}return Hi},Bo="glibc",s4=/GLIBC\s(\d+\.\d+)/,la="musl",Ape=Bo.toUpperCase(),Rpe=la.toLowerCase(),Tpe=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),a4=()=>{let e=t4();if(e.header&&e.header.glibcVersionRuntime)return Bo;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(Tpe))return la}return null},c4=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(Bo))return Bo;if(r&&r.includes(la))return la;return null},l4=(e)=>{if(e.includes(Rpe))return la;if(e.includes(Ape))return Bo;return null},$pe=async()=>{if(eo!==void 0)return eo;eo=null;try{let e=await r4(Ay);eo=l4(e)}catch(e){}return eo},Ope=()=>{if(eo!==void 0)return eo;eo=null;try{let e=n4(Ay);eo=l4(e)}catch(e){}return eo},u4=async()=>{let e=null;if(ml()){if(e=await $pe(),!e)e=a4();if(!e){let t=await o4();e=c4(t)}}return e},d4=()=>{let e=null;if(ml()){if(e=Ope(),!e)e=a4();if(!e){let t=i4();e=c4(t)}}return e},Cpe=async()=>ml()&&await u4()!==Bo,Ppe=()=>ml()&&d4()!==Bo,zpe=async()=>{if(to!==void 0)return to;to=null;try{let t=(await r4(Ay)).match(s4);if(t)to=t[1]}catch(e){}return to},Npe=()=>{if(to!==void 0)return to;to=null;try{let t=n4(Ay).match(s4);if(t)to=t[1]}catch(e){}return to},p4=()=>{let e=t4();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},Xq=(e)=>e.trim().split(/\s+/)[1],f4=(e)=>{let[t,r,o]=e.split(/[\r\n]+/);if(t&&t.includes(Bo))return Xq(t);if(r&&o&&r.includes(la))return Xq(o);return null},Dpe=async()=>{let e=null;if(ml()){if(e=await zpe(),!e)e=p4();if(!e){let t=await o4();e=f4(t)}}return e},Lpe=()=>{let e=null;if(ml()){if(e=Npe(),!e)e=p4();if(!e){let t=i4();e=f4(t)}}return e};m4.exports={GLIBC:Bo,MUSL:la,family:u4,familySync:d4,isNonGlibcLinux:Cpe,isNonGlibcLinuxSync:Ppe,version:Dpe,versionSync:Lpe}});var y4=ge(function(Y2e,g4){var Bpe={ALLOW:0,DENY:1};g4.exports=Bpe});var S4=ge(function(X2e,b4){var KR={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function ua(e,t,r){if(new.target!==ua)return new ua(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),KR.value=""+e,Object.defineProperty(this,"message",KR),Error.captureStackTrace(this,ua),this.code=t,this.rawCode=r}Object.setPrototypeOf(ua,Error);Object.setPrototypeOf(ua.prototype,Error.prototype);Object.defineProperty(ua.prototype,"name",KR);b4.exports=ua});var A4=ge(function(eDe,Ry){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:jpe,currentTarget:Zpe}=Kq(),{familySync:v4,GLIBC:Upe,MUSL:Mpe}=h4();function qpe(){if(process.env.LIBSQL_JS_DEV)return jpe(__dirname);let e=Zpe();if(v4()==Upe)switch(e){case"linux-x64-musl":e="linux-x64-gnu";break;case"linux-arm64-musl":e="linux-arm64-gnu";break}if(e==="linux-arm-gnueabihf"&&v4()==Mpe)e="linux-arm-musleabihf";return Fr(`@libsql/${e}`)}var{databaseOpen:Fpe,databaseOpenWithSync:Jpe,databaseInTransaction:Kpe,databaseInterrupt:Hpe,databaseClose:Vpe,databaseSyncSync:Wpe,databaseSyncUntilSync:Gpe,databaseExecSync:Qpe,databasePrepareSync:Ype,databaseDefaultSafeIntegers:Xpe,databaseAuthorizer:efe,databaseLoadExtension:tfe,databaseMaxWriteReplicationIndex:rfe,statementRaw:nfe,statementIsReader:ofe,statementGet:w4,statementRun:x4,statementInterrupt:ife,statementRowsSync:_4,statementColumns:sfe,statementSafeIntegers:afe,rowsNext:cfe}=qpe(),lfe=y4(),E4=S4();function hl(e){if(e.libsqlError)return new E4(e.message,e.code,e.rawCode);return e}class I4{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var o="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),o=t.syncAuth;else if(t.authToken)o=t.authToken;let i=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,l=t?.offline??!1,u=t?.remoteEncryptionKey??"";this.db=Jpe(e,t.syncUrl,o,r,i,s,a,l,u)}else{let i=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,l=t?.remoteEncryptionKey??"";this.db=Fpe(e,i,r,s,a,l)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let n=this.db;Object.defineProperties(this,{inTransaction:{get(){return Kpe(n)}}})}sync(){return Wpe.call(this.db)}syncUntil(e){return Gpe.call(this.db,e)}prepare(e){try{let t=Ype.call(this.db,e);return new k4(t)}catch(t){throw hl(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...i)=>{t.exec("BEGIN "+n);try{let s=e(...i);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},o={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(o.default.value,o),Object.defineProperties(o.deferred.value,o),Object.defineProperties(o.immediate.value,o),Object.defineProperties(o.exclusive.value,o),o.default.value}pragma(e,t){if(t==null)t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");let r=t.simple,o=this.prepare(`PRAGMA ${e}`,this,!0);return r?o.pluck().get():o.all()}backup(e,t){throw Error("not implemented")}serialize(e){throw Error("not implemented")}function(e,t,r){if(t==null)t={};if(typeof t==="function")r=t,t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof r!=="function")throw TypeError("Expected last argument to be a function");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}aggregate(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object"||t===null)throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}table(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(!e)throw TypeError("Virtual table module name cannot be an empty string");throw Error("not implemented")}authorizer(e){efe.call(this.db,e)}loadExtension(...e){tfe.call(this.db,...e)}maxWriteReplicationIndex(){return rfe.call(this.db)}exec(e){try{Qpe.call(this.db,e)}catch(t){throw hl(t)}}interrupt(){Hpe.call(this.db)}close(){Vpe.call(this.db),this.open=!1}defaultSafeIntegers(e){return Xpe.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class k4{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return nfe.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return ofe.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return x4.call(this.stmt,e[0]);else return x4.call(this.stmt,e.flat())}catch(t){throw hl(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return w4.call(this.stmt,e[0]);else return w4.call(this.stmt,e.flat())}catch(t){throw hl(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=_4.call(this.stmt,e[0]);else t=_4.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)cfe.call(t,this.nextRows),this.nextRowIndex=0;let o=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!o)return{done:!0};return this.nextRowIndex++,{value:o,done:!1}}catch(o){throw hl(o)}},[Symbol.iterator](){return this}}}all(...e){try{let t=[];for(let r of this.iterate(...e))if(this.pluckMode)t.push(r[Object.keys(r)[0]]);else t.push(r);return t}catch(t){throw hl(t)}}interrupt(){ife.call(this.stmt)}columns(){return sfe.call(this.stmt)}safeIntegers(e){return afe.call(this.stmt,e??!0),this}}Ry.exports=I4;Ry.exports.Authorization=lfe;Ry.exports.SqliteError=E4});import{Buffer as T4}from"buffer";function $4(e){if(e.scheme!=="file")throw new Ce(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${Xn}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Ce(`Invalid host in file URL: ${JSON.stringify(t.host)}. A "file:" URL with an absolute path should start with one slash ("file:/absolute/path.db") or with three slashes ("file:///absolute/path.db"). For more information, please read ${Xn}`,"URL_INVALID");if(t.port!==void 0)throw new Ce("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Ce("File URL cannot have username and password","URL_INVALID")}let r=Fq(e);if(r&&e.syncUrl)throw new Ce(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let o=e.path;if(r)o=`${e.scheme}:${e.path}`;let n={authToken:e.authToken,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncPeriod:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,timeout:e.timeout},i=new vp.default(o,n);return zt(i,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new O4(o,n,i,e.intMode)}class O4{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,o){this.#e=e,this.#t=t,this.#r=r,this.#n=o,this.closed=!1,this.protocol="file"}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#o(),zt(this.#i(),r,this.#n)}async batch(e,t="deferred"){this.#o();let r=this.#i();try{zt(r,Ki(t),this.#n);let o=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new Wt("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let i=e[n],s=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;o.push(zt(r,s,this.#n))}catch(i){if(i instanceof Wt)throw i;if(i instanceof Ce)throw new Wt(i.message,n,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return zt(r,"COMMIT",this.#n),o}finally{if(r.inTransaction)zt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#o();let t=this.#i();try{zt(t,"PRAGMA foreign_keys=off",this.#n),zt(t,Ki("deferred"),this.#n);let r=[];for(let o=0;o<e.length;o++)try{if(!t.inTransaction)throw new Wt("The transaction has been rolled back",o,"TRANSACTION_CLOSED");r.push(zt(t,e[o],this.#n))}catch(n){if(n instanceof Wt)throw n;if(n instanceof Ce)throw new Wt(n.message,o,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return zt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)zt(t,"ROLLBACK",this.#n);zt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#i();return zt(t,Ki(e),this.#n),this.#r=null,new C4(t,this.#n)}async executeMultiple(e){this.#o();let t=this.#i();try{return P4(t,e)}finally{if(t.inTransaction)zt(t,"ROLLBACK",this.#n)}}async sync(){this.#o();let e=await this.#i().sync();return{frames_synced:e.frames_synced,frame_no:e.frame_no}}async reconnect(){try{if(!this.closed&&this.#r!==null)this.#r.close()}finally{this.#r=new vp.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#o(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED")}#i(){if(this.#r===null)this.#r=new vp.default(this.#e,this.#t);return this.#r}}class C4{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#r(),zt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let o=e[r],n=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;t.push(zt(this.#e,n,this.#t))}catch(o){if(o instanceof Wt)throw o;if(o instanceof Ce)throw new Wt(o.message,r,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return t}async executeMultiple(e){return this.#r(),P4(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),zt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),zt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)zt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Ce("The transaction is closed","TRANSACTION_CLOSED")}}function zt(e,t,r){let o,n;if(typeof t==="string")o=t,n=[];else if(o=t.sql,Array.isArray(t.args))n=t.args.map((i)=>R4(i,r));else{n={};for(let i in t.args){let s=i[0]==="@"||i[0]==="$"||i[0]===":"?i.substring(1):i;n[s]=R4(t.args[i],r)}}try{let i=e.prepare(o);i.safeIntegers(!0);let s=!0;try{i.raw(!0)}catch{s=!1}if(s){let a=Array.from(i.columns().map((m)=>m.name)),l=Array.from(i.columns().map((m)=>m.type??"")),u=i.all(n).map((m)=>ufe(m,a,r)),d=0,p=void 0;return new pl(a,l,u,0,void 0)}else{let a=i.run(n),l=a.changes,u=BigInt(a.lastInsertRowid);return new pl([],[],[],l,u)}}catch(i){throw z4(i)}}function ufe(e,t,r){let o={};Object.defineProperty(o,"length",{value:e.length});for(let n=0;n<e.length;++n){let i=dfe(e[n],r);Object.defineProperty(o,n,{value:i});let s=t[n];if(!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function dfe(e,t){if(typeof e==="bigint")if(t==="number"){if(e<pfe||e>ffe)throw RangeError("Received integer which cannot be safely represented as a JavaScript number");return Number(e)}else if(t==="bigint")return e;else if(t==="string")return""+e;else throw Error("Invalid value for IntMode");else if(e instanceof T4)return e.buffer;return e}function R4(e,t){if(typeof e==="number"){if(!Number.isFinite(e))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return e}else if(typeof e==="bigint"){if(e<mfe||e>hfe)throw RangeError("bigint is too large to be represented as a 64-bit integer and passed as argument");return e}else if(typeof e==="boolean")switch(t){case"bigint":return e?1n:0n;case"string":return e?"1":"0";default:return e?1:0}else if(e instanceof ArrayBuffer)return T4.from(e);else if(e instanceof Date)return e.valueOf();else if(e===void 0)throw TypeError("undefined cannot be passed as argument to the database");else return e}function P4(e,t){try{e.exec(t)}catch(r){throw z4(r)}}function z4(e){if(e instanceof vp.default.SqliteError){let t=e.code,r=gfe(e.rawCode);return new Ce(e.message,r,t,e.rawCode,e)}return e}function gfe(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return yfe[t]??`SQLITE_UNKNOWN_${t.toString()}`}var vp,pfe,ffe=9007199254740991n,mfe,hfe=9223372036854775807n,yfe;var N4=v(()=>{wn();Sp();fl();vp=Jl(A4(),1);wn();pfe=-9007199254740991n;mfe=-9223372036854775808n;yfe={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",16:"SQLITE_EMPTY",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",22:"SQLITE_NOLFS",23:"SQLITE_AUTH",24:"SQLITE_FORMAT",25:"SQLITE_RANGE",26:"SQLITE_NOTADB",27:"SQLITE_NOTICE",28:"SQLITE_WARNING"}});var Vi;var HR=v(()=>{if(typeof WebSocket<"u")Vi=WebSocket;else if(typeof global<"u")Vi=global.WebSocket;else if(typeof window<"u")Vi=window.WebSocket;else if(typeof self<"u")Vi=self.WebSocket});class gl{constructor(){this.intMode="number"}intMode}var Ge,Pe,wp,xt,xp,yl,da,xn,or,ro;var _t=v(()=>{Ge=class Ge extends Error{constructor(e){super(e);this.name="ClientError"}};Pe=class Pe extends Ge{constructor(e){super(e);this.name="ProtoError"}};wp=class wp extends Ge{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};xt=class xt extends Ge{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};xp=class xp extends Ge{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};yl=class yl extends Ge{constructor(e){super(e);this.name="WebSocketError"}};da=class da extends Ge{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};xn=class xn extends Ge{constructor(e){super(e);this.name="ProtocolVersionError"}};or=class or extends Ge{constructor(e){super(e);this.name="InternalError"}};ro=class ro extends Ge{constructor(e){super(e);this.name="MisuseError"}}});function Tr(e){if(typeof e==="string")return e;throw bl(e,"string")}function Ur(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw bl(e,"string or null")}function jo(e){if(typeof e==="number")return e;throw bl(e,"number")}function Wi(e){if(typeof e==="boolean")return e;throw bl(e,"boolean")}function _p(e){if(Array.isArray(e))return e;throw bl(e,"array")}function kt(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw bl(e,"object")}function _n(e,t){return _p(e).map((r)=>t(kt(r)))}function bl(e,t){if(e===void 0)return new Pe(`Expected ${t}, but the property was missing`);let r=typeof e;if(e===null)r="null";else if(Array.isArray(e))r="array";return new Pe(`Expected ${t}, received ${r}`)}function pa(e,t){return t(kt(e))}var Sl=v(()=>{_t()});class D4{#e;#t;constructor(e){this.#e=e,this.#t=!1}begin(){this.#e.push("{"),this.#t=!0}end(){this.#e.push("}"),this.#t=!1}#r(e){if(this.#t)this.#e.push('"'),this.#t=!1;else this.#e.push(',"');this.#e.push(e),this.#e.push('":')}string(e,t){this.#r(e),this.#e.push(JSON.stringify(t))}stringRaw(e,t){this.#r(e),this.#e.push('"'),this.#e.push(t),this.#e.push('"')}number(e,t){this.#r(e),this.#e.push(""+t)}boolean(e,t){this.#r(e),this.#e.push(t?"true":"false")}object(e,t,r){this.#r(e),this.begin(),r(this,t),this.end()}arrayObjects(e,t,r){this.#r(e),this.#e.push("[");for(let o=0;o<t.length;++o){if(o!==0)this.#e.push(",");this.begin(),r(this,t[o]),this.end()}this.#e.push("]")}}function Ep(e,t){let r=[],o=new D4(r);return o.begin(),t(o,e),o.end(),r.join("")}var fa=0,Ip=1,kp=2,L4=5;class B4{#e;#t;#r;constructor(e){this.#e=e,this.#t=new DataView(e.buffer,e.byteOffset,e.byteLength),this.#r=0}varint(){let e=0;for(let t=0;;t+=7){let r=this.#e[this.#r++];if(e|=(r&127)<<t,!(r&128))break}return e}varintBig(){let e=0n;for(let t=0n;;t+=7n){let r=this.#e[this.#r++];if(e|=BigInt(r&127)<<t,!(r&128))break}return e}bytes(e){let t=new Uint8Array(this.#e.buffer,this.#e.byteOffset+this.#r,e);return this.#r+=e,t}double(){let e=this.#t.getFloat64(this.#r,!0);return this.#r+=8,e}skipVarint(){for(;;)if(!(this.#e[this.#r++]&128))break}skip(e){this.#r+=e}eof(){return this.#r>=this.#e.byteLength}}class j4{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new Pe(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(kp);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return Gi(this.bytes(),e)}int32(){return this.#r(fa),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r(fa),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(Ip),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===fa)this.#e.skipVarint();else if(this.#t===Ip)this.#e.skip(8);else if(this.#t===kp){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===L4)this.#e.skip(4);else throw new Pe(`Unexpected wire type ${this.#t}`);this.#t=-1}}function Gi(e,t){let r=new B4(e),o=new j4(r),n=t.default();while(!r.eof()){let i=r.varint(),s=i>>3,a=i&7;o.setup(a);let l=t[s];if(l!==void 0){let u=l(o,n);if(u!==void 0)n=u}o.maybeSkip()}return n}var VR=v(()=>{_t()});class WR{#e;#t;#r;#n;constructor(){this.#e=new ArrayBuffer(256),this.#t=new Uint8Array(this.#e),this.#r=new DataView(this.#e),this.#n=0}#o(e){if(this.#n+e<=this.#e.byteLength)return;let t=this.#e.byteLength;while(t<this.#n+e)t*=2;let r=new ArrayBuffer(t),o=new Uint8Array(r),n=new DataView(r);o.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=o,this.#r=n}#i(e){this.#o(5),e=0|e;do{let t=e&127;e>>>=7,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#a(e){this.#o(10),e=e&0xffffffffffffffffn;do{let t=Number(e&0x7fn);e>>=7n,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#s(e,t){this.#i(e<<3|t)}bytes(e,t){this.#s(e,kp),this.#i(t.byteLength),this.#o(t.byteLength),this.#t.set(t,this.#n),this.#n+=t.byteLength}string(e,t){this.bytes(e,new TextEncoder().encode(t))}message(e,t,r){let o=new WR;r(o,t),this.bytes(e,o.data())}int32(e,t){this.#s(e,fa),this.#i(t)}uint32(e,t){this.int32(e,t)}bool(e,t){this.int32(e,t?1:0)}sint64(e,t){this.#s(e,fa),this.#a(t<<1n^t>>63n)}double(e,t){this.#s(e,Ip),this.#o(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function Ap(e,t){let r=new WR;return t(r,e),r.data()}var Z4=()=>{};var GR=v(()=>{Sl();VR();Z4()});class Qi{#e;#t;constructor(){this.#e=new Set,this.#t=new Set}alloc(){for(let t of this.#t){if(this.#t.delete(t),this.#e.add(t),!this.#e.has(this.#e.size-1))this.#t.add(this.#e.size-1);return t}let e=this.#e.size;return this.#e.add(e),e}free(e){if(!this.#e.delete(e))throw new or("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var QR=v(()=>{_t()});function Ke(e,t){throw new or(t)}var nn=v(()=>{_t()});function vl(e){if(e===null)return null;else if(typeof e==="string")return e;else if(typeof e==="number"){if(!Number.isFinite(e))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return e}else if(typeof e==="bigint"){if(e<Sfe||e>vfe)throw RangeError("This bigint value is too large to be represented as a 64-bit integer and passed as argument");return e}else if(typeof e==="boolean")return e?1n:0n;else if(e instanceof ArrayBuffer)return new Uint8Array(e);else if(e instanceof Uint8Array)return e;else if(e instanceof Date)return+e.valueOf();else if(typeof e==="object")return""+e.toString();else throw TypeError("Unsupported type of value")}function YR(e,t){if(e===null)return null;else if(typeof e==="number")return e;else if(typeof e==="string")return e;else if(typeof e==="bigint")if(t==="number"){let r=Number(e);if(!Number.isSafeInteger(r))throw RangeError("Received integer which is too large to be safely represented as a JavaScript number");return r}else if(t==="bigint")return e;else if(t==="string")return""+e;else throw new ro("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new Pe("Received unrecognized type of Value");else throw Ke(e,"Impossible type of Value")}var Sfe,vfe=9223372036854775807n;var XR=v(()=>{_t();nn();Sfe=-9223372036854775808n});function ma(e){return{affectedRowCount:e.affectedRowCount,lastInsertRowid:e.lastInsertRowid,columnNames:e.cols.map((t)=>t.name),columnDecltypes:e.cols.map((t)=>t.decltype)}}function $y(e,t){let r=ma(e),o=e.rows.map((n)=>U4(r.columnNames,n,t));return{...r,rows:o}}function Oy(e,t){let r=ma(e),o;if(e.rows.length>0)o=U4(r.columnNames,e.rows[0],t);return{...r,row:o}}function Cy(e,t){let r=ma(e),o;if(e.rows.length>0&&r.columnNames.length>0)o=YR(e.rows[0][0],t);return{...r,value:o}}function U4(e,t,r){let o={};Object.defineProperty(o,"length",{value:t.length});for(let n=0;n<t.length;++n){let i=YR(t[n],r);Object.defineProperty(o,n,{value:i});let s=e[n];if(s!==void 0&&!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function Zo(e){return new wp(e.message,e)}var Rp=v(()=>{_t();XR()});class ha{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new ro("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new xt("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new Ge("SQL text was manually closed"))}_setClosed(e){if(this.#r===void 0)this.#r=e,this.#e._closeSql(this.#t)}get closed(){return this.#r!==void 0}}function Tp(e,t){if(t instanceof ha)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var wl=v(()=>{_t()});class Yi{#e;#t;constructor(){this.#e=[],this.#t=[]}get length(){return this.#e.length+this.#t.length}push(e){this.#e.push(e)}shift(){if(this.#t.length===0&&this.#e.length>0)this.#t=this.#e.reverse(),this.#e=[];return this.#t.pop()}first(){return this.#t.length!==0?this.#t[this.#t.length-1]:this.#e[0]}}class $p{sql;_args;_namedArgs;constructor(e){this.sql=e,this._args=[],this._namedArgs=new Map}bindIndexes(e){this._args.length=0;for(let t of e)this._args.push(vl(t));return this}bindIndex(e,t){if(e!==(e|0)||e<=0)throw RangeError("Index of a positional argument must be positive integer");while(this._args.length<e)this._args.push(null);return this._args[e-1]=vl(t),this}bindName(e,t){return this._namedArgs.set(e,vl(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function Py(e,t,r){let o,n=[],i=[];if(t instanceof $p){o=t.sql,n=t._args;for(let[l,u]of t._namedArgs.entries())i.push({name:l,value:u})}else if(Array.isArray(t))if(o=t[0],Array.isArray(t[1]))n=t[1].map((l)=>vl(l));else i=Object.entries(t[1]).map(([l,u])=>({name:l,value:vl(u)}));else o=t;let{sql:s,sqlId:a}=Tp(e,o);return{sql:s,sqlId:a,args:n,namedArgs:i,wantRows:r}}var zy=v(()=>{wl();XR()});class Ny{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new eT(this)}execute(){if(this.#t)throw new ro("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return xfe(this._stream,this._steps,e);else return wfe(this._stream,this._steps,e)}}function wfe(e,t,r){return e._batch(r).then((o)=>{for(let n=0;n<t.length;++n){let i=o.stepResults.get(n),s=o.stepErrors.get(n);t[n].callback(i,s)}})}async function xfe(e,t,r){let o=await e._openCursor(r);try{let n=0,i=void 0,s=[];for(;;){let a=await o.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new Pe("Server produced StepBeginEntry for unexpected step");else if(i!==void 0)throw new Pe("Server produced StepBeginEntry before terminating previous step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0);n=a.step+1,i=a,s=[]}else if(a.type==="step_end"){if(i===void 0)throw new Pe("Server produced StepEndEntry but no step is active");let l={cols:i.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[i.step].callback(l,void 0),i=void 0,s=[]}else if(a.type==="step_error"){if(i===void 0){if(a.step>=t.length)throw new Pe("Server produced StepErrorEntry for unexpected step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0)}else{if(a.step!==i.step)throw new Pe("Server produced StepErrorEntry for unexpected step");i=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(i===void 0)throw new Pe("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw Zo(a.error);else if(a.type==="none")throw new Pe("Server produced unrecognized CursorEntry");else throw Ke(a,"Impossible CursorEntry")}if(i!==void 0)throw new Pe("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{o.close()}}class eT{_batch;#e;_index;constructor(e){this._batch=e,this.#e=[],this._index=void 0}condition(e){return this.#e.push(e._proto),this}query(e){return this.#t(e,!0,$y)}queryRow(e){return this.#t(e,!0,Oy)}queryValue(e){return this.#t(e,!0,Cy)}run(e){return this.#t(e,!1,ma)}#t(e,t,r){if(this._index!==void 0)throw new ro("This BatchStep has already been added to the batch");let o=Py(this._batch._stream._sqlOwner(),e,t),n;if(this.#e.length===0)n=void 0;else if(this.#e.length===1)n=this.#e[0];else n={type:"and",conds:this.#e.slice()};let i={stmt:o,condition:n};return new Promise((s,a)=>{let l=(u,d)=>{if(u!==void 0&&d!==void 0)a(new Pe("Server returned both result and error"));else if(d!==void 0)a(Zo(d));else if(u!==void 0)s(r(u,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:i,callback:l})})}}class ut{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new ut(e._batch,{type:"ok",step:M4(e)})}static error(e){return new ut(e._batch,{type:"error",step:M4(e)})}static not(e){return new ut(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)q4(e,r);return new ut(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)q4(e,r);return new ut(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new ut(e,{type:"is_autocommit"})}}function M4(e){if(e._index===void 0)throw new ro("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function q4(e,t){if(t._batch!==e)throw new ro("Cannot mix BatchCond objects for different Batch objects")}var tT=v(()=>{_t();Rp();zy();nn()});function F4(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class xl{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,$y)}queryRow(e){return this.#e(e,!0,Oy)}queryValue(e){return this.#e(e,!0,Cy)}run(e){return this.#e(e,!1,ma)}#e(e,t,r){let o=Py(this._sqlOwner(),e,t);return this._execute(o).then((n)=>r(n,this.intMode))}batch(e=!1){return new Ny(this,e)}describe(e){let t=Tp(this._sqlOwner(),e);return this._describe(t).then(F4)}sequence(e){let t=Tp(this._sqlOwner(),e);return this._sequence(t)}intMode}var Dy=v(()=>{tT();Rp();wl();zy()});class Op{}var _fe=1000,Efe=10,rT;var J4=v(()=>{_t();rT=class rT extends Op{#e;#t;#r;#n;#o;#i;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new Yi,this.#o=new Yi,this.#i=void 0,this.#a=!1}async next(){for(;;){if(this.#i!==void 0)throw new xt("Cursor is closed",this.#i);while(!this.#a&&this.#o.length<Efe)this.#o.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#o.shift().then((t)=>{if(t===void 0)return;for(let r of t.entries)this.#n.push(r);this.#a||=t.done})}}#s(){return this.#t._sendCursorRequest(this,{type:"fetch_cursor",cursorId:this.#r,maxCount:_fe}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#i!==void 0)return;this.#i=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new Ge("Cursor was manually closed"))}get closed(){return this.#i!==void 0}}});var Cp;var nT=v(()=>{_t();Dy();J4();Cp=class Cp extends xl{#e;#t;#r;#n;#o;#i;static open(e){let t=e._streamIdAlloc.alloc(),r=new Cp(e,t),o=()=>{return},n=(s)=>r.#l(s),i={type:"open_stream",streamId:t};return e._sendRequest(i,{responseCallback:o,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new Yi,this.#n=void 0,this.#o=!1,this.#i=void 0}client(){return this.#e}_sqlOwner(){return this.#e}_execute(e){return this.#a({type:"execute",streamId:this.#t,stmt:e}).then((t)=>t.result)}_batch(e){return this.#a({type:"batch",streamId:this.#t,batch:e}).then((t)=>t.result)}_describe(e){return this.#e._ensureVersion(2,"describe()"),this.#a({type:"describe",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#e._ensureVersion(2,"sequence()"),this.#a({type:"sequence",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#a({type:"get_autocommit",streamId:this.#t}).then((e)=>e.isAutocommit)}#a(e){return new Promise((t,r)=>{this.#s({type:"request",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return this.#e._ensureVersion(3,"cursor"),new Promise((t,r)=>{this.#s({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_sendCursorRequest(e,t){if(e!==this.#n)throw new or("Cursor not associated with the stream attempted to execute a request");return new Promise((r,o)=>{if(this.#i!==void 0)o(new xt("Stream is closed",this.#i));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})})}_cursorClosed(e){if(e!==this.#n)throw new or("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#i!==void 0)e.errorCallback(new xt("Stream is closed",this.#i));else if(this.#o)e.errorCallback(new xt("Stream is closing",void 0));else this.#r.push(e),this.#c()}#c(){for(;;){let e=this.#r.first();if(e===void 0&&this.#n===void 0&&this.#o){this.#l(new Ge("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:o}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let o=this.#e._cursorIdAlloc.alloc(),n=new rT(this.#e,this,o),i={type:"open_cursor",streamId:this.#t,cursorId:o,batch:t},s=()=>{return},a=(l)=>n._setClosed(l);this.#e._sendRequest(i,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#i!==void 0)return;if(this.#i=e,this.#n!==void 0)this.#n._setClosed(e);for(;;){let n=this.#r.shift();if(n!==void 0)n.errorCallback(e);else break}let t={type:"close_stream",streamId:this.#t},r=()=>this.#e._streamIdAlloc.free(this.#t),o=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}close(){this.#l(new Ge("Stream was manually closed"))}closeGracefully(){this.#o=!0,this.#c()}get closed(){return this.#i!==void 0||this.#o}}});function Pp(e,t){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId);e.arrayObjects("args",t.args,K4),e.arrayObjects("named_args",t.namedArgs,Ife),e.boolean("want_rows",t.wantRows)}function Ife(e,t){e.string("name",t.name),e.object("value",t.value,K4)}function _l(e,t){e.arrayObjects("steps",t.steps,kfe)}function kfe(e,t){if(t.condition!==void 0)e.object("condition",t.condition,oT);e.object("stmt",t.stmt,Pp)}function oT(e,t){if(e.stringRaw("type",t.type),t.type==="ok"||t.type==="error")e.number("step",t.step);else if(t.type==="not")e.object("cond",t.cond,oT);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,oT);else if(t.type==="is_autocommit");else throw Ke(t,"Impossible type of BatchCond")}function K4(e,t){if(t===null)e.stringRaw("type","null");else if(typeof t==="bigint")e.stringRaw("type","integer"),e.stringRaw("value",""+t);else if(typeof t==="number")e.stringRaw("type","float"),e.number("value",t);else if(typeof t==="string")e.stringRaw("type","text"),e.string("value",t);else if(t instanceof Uint8Array)e.stringRaw("type","blob"),e.stringRaw("base64",dl.fromUint8Array(t));else if(t===void 0);else throw Ke(t,"Impossible type of Value")}var iT=v(()=>{ky();nn()});function H4(e,t){if(e.stringRaw("type",t.type),t.type==="hello"){if(t.jwt!==void 0)e.string("jwt",t.jwt)}else if(t.type==="request")e.number("request_id",t.requestId),e.object("request",t.request,Afe);else throw Ke(t,"Impossible type of ClientMsg")}function Afe(e,t){if(e.stringRaw("type",t.type),t.type==="open_stream")e.number("stream_id",t.streamId);else if(t.type==="close_stream")e.number("stream_id",t.streamId);else if(t.type==="execute")e.number("stream_id",t.streamId),e.object("stmt",t.stmt,Pp);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,_l);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,_l);else if(t.type==="close_cursor")e.number("cursor_id",t.cursorId);else if(t.type==="fetch_cursor")e.number("cursor_id",t.cursorId),e.number("max_count",t.maxCount);else if(t.type==="sequence"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit")e.number("stream_id",t.streamId);else throw Ke(t,"Impossible type of Request")}var V4=v(()=>{iT();nn()});function zp(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId);for(let r of t.args)e.message(3,r,G4);for(let r of t.namedArgs)e.message(4,r,Rfe);e.bool(5,t.wantRows)}function Rfe(e,t){e.string(1,t.name),e.message(2,t.value,G4)}function El(e,t){for(let r of t.steps)e.message(1,r,Tfe)}function Tfe(e,t){if(t.condition!==void 0)e.message(1,t.condition,sT);e.message(2,t.stmt,zp)}function sT(e,t){if(t.type==="ok")e.uint32(1,t.step);else if(t.type==="error")e.uint32(2,t.step);else if(t.type==="not")e.message(3,t.cond,sT);else if(t.type==="and")e.message(4,t.conds,W4);else if(t.type==="or")e.message(5,t.conds,W4);else if(t.type==="is_autocommit")e.message(6,void 0,Q4);else throw Ke(t,"Impossible type of BatchCond")}function W4(e,t){for(let r of t)e.message(1,r,sT)}function G4(e,t){if(t===null)e.message(1,void 0,Q4);else if(typeof t==="bigint")e.sint64(2,t);else if(typeof t==="number")e.double(3,t);else if(typeof t==="string")e.string(4,t);else if(t instanceof Uint8Array)e.bytes(5,t);else if(t===void 0);else throw Ke(t,"Impossible type of Value")}function Q4(e,t){}var aT=v(()=>{nn()});function Y4(e,t){if(t.type==="hello")e.message(1,t,$fe);else if(t.type==="request")e.message(2,t,Ofe);else throw Ke(t,"Impossible type of ClientMsg")}function $fe(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function Ofe(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,Cfe);else if(r.type==="close_stream")e.message(3,r,Pfe);else if(r.type==="execute")e.message(4,r,zfe);else if(r.type==="batch")e.message(5,r,Nfe);else if(r.type==="open_cursor")e.message(6,r,Dfe);else if(r.type==="close_cursor")e.message(7,r,Lfe);else if(r.type==="fetch_cursor")e.message(8,r,Bfe);else if(r.type==="sequence")e.message(9,r,jfe);else if(r.type==="describe")e.message(10,r,Zfe);else if(r.type==="store_sql")e.message(11,r,Ufe);else if(r.type==="close_sql")e.message(12,r,Mfe);else if(r.type==="get_autocommit")e.message(13,r,qfe);else throw Ke(r,"Impossible type of Request")}function Cfe(e,t){e.int32(1,t.streamId)}function Pfe(e,t){e.int32(1,t.streamId)}function zfe(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,zp)}function Nfe(e,t){e.int32(1,t.streamId),e.message(2,t.batch,El)}function Dfe(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,El)}function Lfe(e,t){e.int32(1,t.cursorId)}function Bfe(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function jfe(e,t){if(e.int32(1,t.streamId),t.sql!==void 0)e.string(2,t.sql);if(t.sqlId!==void 0)e.int32(3,t.sqlId)}function Zfe(e,t){if(e.int32(1,t.streamId),t.sql!==void 0)e.string(2,t.sql);if(t.sqlId!==void 0)e.int32(3,t.sqlId)}function Ufe(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function Mfe(e,t){e.int32(1,t.sqlId)}function qfe(e,t){e.int32(1,t.streamId)}var X4=v(()=>{aT();nn()});function Xi(e){let t=Tr(e.message),r=Ur(e.code);return{message:t,code:r}}function Np(e){let t=_n(e.cols,eF),r=_p(e.rows).map((s)=>_n(s,tF)),o=jo(e.affected_row_count),n=Ur(e.last_insert_rowid),i=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:o,lastInsertRowid:i}}function eF(e){let t=Ur(e.name),r=Ur(e.decltype);return{name:t,decltype:r}}function Ly(e){let t=new Map;_p(e.step_results).forEach((o,n)=>{if(o!==null)t.set(n,Np(kt(o)))});let r=new Map;return _p(e.step_errors).forEach((o,n)=>{if(o!==null)r.set(n,Xi(kt(o)))}),{stepResults:t,stepErrors:r}}function By(e){let t=Tr(e.type);if(t==="step_begin"){let r=jo(e.step),o=_n(e.cols,eF);return{type:"step_begin",step:r,cols:o}}else if(t==="step_end"){let r=jo(e.affected_row_count),o=Ur(e.last_insert_rowid),n=o!==void 0?BigInt(o):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=jo(e.step),o=Xi(kt(e.error));return{type:"step_error",step:r,error:o}}else if(t==="row")return{type:"row",row:_n(e.row,tF)};else if(t==="error")return{type:"error",error:Xi(kt(e.error))};else throw new Pe("Unexpected type of CursorEntry")}function jy(e){let t=_n(e.params,Ffe),r=_n(e.cols,Jfe),o=Wi(e.is_explain),n=Wi(e.is_readonly);return{params:t,cols:r,isExplain:o,isReadonly:n}}function Ffe(e){return{name:Ur(e.name)}}function Jfe(e){let t=Tr(e.name),r=Ur(e.decltype);return{name:t,decltype:r}}function tF(e){let t=Tr(e.type);if(t==="null")return null;else if(t==="integer"){let r=Tr(e.value);return BigInt(r)}else if(t==="float")return jo(e.value);else if(t==="text")return Tr(e.value);else if(t==="blob")return dl.toUint8Array(Tr(e.base64));else throw new Pe("Unexpected type of Value")}var Zy=v(()=>{ky();_t();Sl()});function rF(e){let t=Tr(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:Xi(kt(e.error))};else if(t==="response_ok"){let r=jo(e.request_id),o=Kfe(kt(e.response));return{type:"response_ok",requestId:r,response:o}}else if(t==="response_error"){let r=jo(e.request_id),o=Xi(kt(e.error));return{type:"response_error",requestId:r,error:o}}else throw new Pe("Unexpected type of ServerMsg")}function Kfe(e){let t=Tr(e.type);if(t==="open_stream")return{type:"open_stream"};else if(t==="close_stream")return{type:"close_stream"};else if(t==="execute")return{type:"execute",result:Np(kt(e.result))};else if(t==="batch")return{type:"batch",result:Ly(kt(e.result))};else if(t==="open_cursor")return{type:"open_cursor"};else if(t==="close_cursor")return{type:"close_cursor"};else if(t==="fetch_cursor"){let r=_n(e.entries,By),o=Wi(e.done);return{type:"fetch_cursor",entries:r,done:o}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:jy(kt(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Wi(e.is_autocommit)};else throw new Pe("Unexpected type of Response")}var nF=v(()=>{_t();Sl();Zy()});var on,es,oF,iF,Il,Hfe,Vfe,Uy,Wfe,Gfe,Qfe,kl,Yfe,Xfe,eme;var My=v(()=>{on={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},es={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(oF))},2(e,t){t.rows.push(e.message(iF))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},oF={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},iF={default(){return[]},1(e,t){t.push(e.message(eme))}},Il={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,o]=e.message(Hfe);t.stepResults.set(r,o)},2(e,t){let[r,o]=e.message(Vfe);t.stepErrors.set(r,o)}},Hfe={default(){return[0,es.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(es)}},Vfe={default(){return[0,on.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(on)}},Uy={default(){return{type:"none"}},1(e){return e.message(Wfe)},2(e){return e.message(Gfe)},3(e){return e.message(Qfe)},4(e){return{type:"row",row:e.message(iF)}},5(e){return{type:"error",error:e.message(on)}}},Wfe={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(oF))}},Gfe={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},Qfe={default(){return{type:"step_error",step:0,error:on.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(on)}},kl={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(Yfe))},2(e,t){t.cols.push(e.message(Xfe))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},Yfe={default(){return{name:void 0}},1(e,t){t.name=e.string()}},Xfe={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},eme={default(){return},1(e){return null},2(e){return e.sint64()},3(e){return e.double()},4(e){return e.string()},5(e){return e.bytes()}}});var sF,tme,rme,nme,ome,ime,sme,ame,cme;var aF=v(()=>{My();sF={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(tme)},3(e){return e.message(nme)},4(e){return e.message(rme)}},tme={default(){return{type:"hello_error",error:on.default()}},1(e,t){t.error=e.message(on)}},rme={default(){return{type:"response_error",requestId:0,error:on.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(on)}},nme={default(){return{type:"response_ok",requestId:0,response:{type:"none"}}},1(e,t){t.requestId=e.int32()},2(e,t){t.response={type:"open_stream"}},3(e,t){t.response={type:"close_stream"}},4(e,t){t.response=e.message(ome)},5(e,t){t.response=e.message(ime)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(sme)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(ame)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(cme)}},ome={default(){return{type:"execute",result:es.default()}},1(e,t){t.result=e.message(es)}},ime={default(){return{type:"batch",result:Il.default()}},1(e,t){t.result=e.message(Il)}},sme={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(Uy))},2(e,t){t.done=e.bool()}},ame={default(){return{type:"describe",result:kl.default()}},1(e,t){t.result=e.message(kl)}},cme={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var cF,cT,qy;var Fy=v(()=>{GR();_t();QR();Rp();wl();nn();nT();V4();X4();nF();aF();cF=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),cT=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);qy=class qy extends gl{#e;#t;#r;#n;#o;#i;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#o=!1,this.#i=void 0,this.#a=!1,this.#s=new Map,this.#c=new Qi,this._streamIdAlloc=new Qi,this._cursorIdAlloc=new Qi,this.#l=new Qi,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#p()),this.#e.addEventListener("close",(r)=>this.#g(r)),this.#e.addEventListener("error",(r)=>this.#f(r)),this.#e.addEventListener("message",(r)=>this.#y(r)),this.#d({type:"hello",jwt:t})}#d(e){if(this.#n!==void 0)throw new or("Trying to send a message on a closed client");if(this.#r)this.#m(e);else{let t=()=>this.#m(e),r=()=>{return};this.#t.push({openCallback:t,errorCallback:r})}}#p(){let e=this.#e.protocol;if(e===void 0){this.#u(new Ge("The `WebSocket.protocol` property is undefined. This most likely means that the WebSocket implementation provided by the environment is broken. If you are using Miniflare 2, please update to Miniflare 3, which fixes this problem."));return}else if(e==="")this.#i={version:1,encoding:"json"};else if(this.#i=cT.get(e),this.#i===void 0){this.#u(new Pe(`Unrecognized WebSocket subprotocol: ${JSON.stringify(e)}`));return}for(let t of this.#t)t.openCallback();this.#t.length=0,this.#r=!0}#m(e){let t=this.#i.encoding;if(t==="json"){let r=Ep(e,H4);this.#e.send(r)}else if(t==="protobuf"){let r=Ap(e,Y4);this.#e.send(r)}else throw Ke(t,"Impossible encoding")}getVersion(){return new Promise((e,t)=>{if(this.#a=!0,this.#n!==void 0)t(this.#n);else if(!this.#r){let r=()=>e(this.#i.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#i.version)})}_ensureVersion(e,t){if(this.#i===void 0||!this.#a)throw new xn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the WebSocket server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this.#i.version<e)throw new xn(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#i.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new xt("Client is closed",this.#n));return}let r=this.#c.alloc();this.#s.set(r,{...t,type:e.type}),this.#d({type:"request",requestId:r,request:e})}#f(e){let r=e.message??"WebSocket was closed due to an error";this.#u(new yl(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new yl(t))}#u(e){if(this.#n!==void 0)return;this.#n=e;for(let t of this.#t)t.errorCallback(e);this.#t.length=0;for(let[t,r]of this.#s.entries())r.errorCallback(e),this.#c.free(t);this.#s.clear(),this.#e.close()}#y(e){if(this.#n!==void 0)return;try{let t,r=this.#i.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new Pe("Received non-text message from server with JSON encoding"));return}t=pa(JSON.parse(e.data),rF)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new Pe("Received non-binary message from server with Protobuf encoding"));return}t=Gi(new Uint8Array(e.data),sF)}else throw Ke(r,"Impossible encoding");this.#b(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#b(e){if(e.type==="none")throw new Pe("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#o)throw new Pe("Received a duplicated hello response");if(this.#o=!0,e.type==="hello_error")throw Zo(e.error);return}else if(!this.#o)throw new Pe("Received a non-hello message before a hello response");if(e.type==="response_ok"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new Pe("Received unexpected type of response");r.responseCallback(e.response)}catch(o){throw r.errorCallback(o),o}}else if(e.type==="response_error"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected error response");this.#c.free(t),r.errorCallback(Zo(e.error))}else throw Ke(e,"Impossible ServerMsg type")}openStream(){return Cp.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new ha(this,t),o=()=>{return},n=(s)=>r._setClosed(s),i={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(i,{responseCallback:o,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),o={type:"close_sql",sqlId:e};this._sendRequest(o,{responseCallback:t,errorCallback:r})}close(){this.#u(new Ge("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var ga;var lF=v(()=>{if(typeof queueMicrotask<"u")ga=queueMicrotask;else{let e=Promise.resolve();ga=(t)=>{e.then(t)}}});class lT{#e;#t;#r;constructor(e){this.#e=new Uint8Array(new ArrayBuffer(e)),this.#t=0,this.#r=0}get length(){return this.#r-this.#t}data(){return this.#e.slice(this.#t,this.#r)}push(e){this.#n(e.byteLength),this.#e.set(e,this.#r),this.#r+=e.byteLength}#n(e){if(this.#r+e<=this.#e.byteLength)return;let t=this.#r-this.#t;if(t+e<=this.#e.byteLength&&2*this.#r>=this.#e.byteLength)this.#e.copyWithin(0,this.#t,this.#r);else{let r=this.#e.byteLength;do r*=2;while(t+e>r);let o=new Uint8Array(new ArrayBuffer(r));o.set(this.#e.slice(this.#t,this.#r),0),this.#e=o}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function uF(e){let t=Ur(e.baton),r=Ur(e.base_url),o=_n(e.results,lme);return{baton:t,baseUrl:r,results:o}}function lme(e){let t=Tr(e.type);if(t==="ok")return{type:"ok",response:ume(kt(e.response))};else if(t==="error")return{type:"error",error:Xi(kt(e.error))};else throw new Pe("Unexpected type of StreamResult")}function ume(e){let t=Tr(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:Np(kt(e.result))};else if(t==="batch")return{type:"batch",result:Ly(kt(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:jy(kt(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Wi(e.is_autocommit)};else throw new Pe("Unexpected type of StreamResponse")}function dF(e){let t=Ur(e.baton),r=Ur(e.base_url);return{baton:t,baseUrl:r}}var uT=v(()=>{_t();Sl();Zy()});var pF,dme,pme,fme,mme,hme,gme,fF;var dT=v(()=>{My();pF={default(){return{baton:void 0,baseUrl:void 0,results:[]}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()},3(e,t){t.results.push(e.message(dme))}},dme={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(pme)}},2(e){return{type:"error",error:e.message(on)}}},pme={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(fme)},3(e){return e.message(mme)},4(e){return{type:"sequence"}},5(e){return e.message(hme)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(gme)}},fme={default(){return{type:"execute",result:es.default()}},1(e,t){t.result=e.message(es)}},mme={default(){return{type:"batch",result:Il.default()}},1(e,t){t.result=e.message(Il)}},hme={default(){return{type:"describe",result:kl.default()}},1(e,t){t.result=e.message(kl)}},gme={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},fF={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var pT;var mF=v(()=>{Sl();VR();_t();nn();uT();dT();Zy();My();pT=class pT extends Op{#e;#t;#r;#n;#o;#i;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new lT(16384),this.#o=void 0,this.#i=!1}async open(e){if(e.body===null)throw new Pe("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(dF,fF);if(t===void 0)throw new Pe("Empty response to cursor request");return t}next(){return this.#a(By,Uy)}close(){this._setClosed(new Ge("Cursor was manually closed"))}_setClosed(e){if(this.#o!==void 0)return;if(this.#o=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#o!==void 0}async#a(e,t){for(;;){if(this.#i)return;else if(this.#o!==void 0)throw new xt("Cursor is closed",this.#o);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let i=new TextDecoder().decode(n),s=JSON.parse(i);return pa(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return Gi(n,t)}else throw Ke(this.#t,"Impossible encoding");if(this.#r===void 0)throw new or("Attempted to read from HTTP cursor before it was opened");let{value:r,done:o}=await this.#r.next();if(o&&this.#n.length===0)this.#i=!0;else if(o)throw new Pe("Unexpected end of cursor stream");else this.#n.push(r)}}#s(){let e=this.#n.data(),t=10,r=e.indexOf(10);if(r<0)return;let o=e.slice(0,r);return this.#n.shift(r+1),o}#c(){let e=this.#n.data(),t=0,r=0;for(;;){if(r>=e.byteLength)return;let n=e[r];if(t|=(n&127)<<7*r,r+=1,!(n&128))break}if(e.byteLength<r+t)return;let o=e.slice(r,r+t);return this.#n.shift(r+t),o}}});function hF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,yme)}function yme(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,Pp);else if(t.type==="batch")e.object("batch",t.batch,_l);else if(t.type==="sequence"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit");else throw Ke(t,"Impossible type of StreamRequest")}function gF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,_l)}var fT=v(()=>{iT();nn()});function yF(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,bme)}function bme(e,t){if(t.type==="close")e.message(1,t,Sme);else if(t.type==="execute")e.message(2,t,vme);else if(t.type==="batch")e.message(3,t,wme);else if(t.type==="sequence")e.message(4,t,xme);else if(t.type==="describe")e.message(5,t,_me);else if(t.type==="store_sql")e.message(6,t,Eme);else if(t.type==="close_sql")e.message(7,t,Ime);else if(t.type==="get_autocommit")e.message(8,t,kme);else throw Ke(t,"Impossible type of StreamRequest")}function Sme(e,t){}function vme(e,t){e.message(1,t.stmt,zp)}function wme(e,t){e.message(1,t.batch,El)}function xme(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function _me(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function Eme(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function Ime(e,t){e.int32(1,t.sqlId)}function kme(e,t){}function bF(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,El)}var mT=v(()=>{aT();nn()});function Ame(e,t){if(t.results.length!==e.length)throw new Pe("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let o=t.results[r],n=e[r];if(o.type==="ok"){if(o.response.type!==n.request.type)throw new Pe("Received unexpected type of response");n.responseCallback(o.response)}else if(o.type==="error")n.errorCallback(Zo(o.error));else if(o.type==="none")throw new Pe("Received unrecognized type of StreamResult");else throw Ke(o,"Received impossible type of StreamResult")}}async function Rme(e,t){if(t==="json"){let r=await e.json();return pa(r,uF)}if(t==="protobuf"){let r=await e.arrayBuffer();return Gi(new Uint8Array(r),pF)}throw await e.body?.cancel(),Ke(t,"Impossible encoding")}async function Tme(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let o=await e.json();if("message"in o)return Zo(o);return new da(r,e.status)}if(t==="text/plain"){let o=(await e.text()).trim();if(o!=="")r+=`: ${o}`;return new da(r,e.status)}return await e.body?.cancel(),new da(r,e.status)}var Jy;var hT=v(()=>{_t();GR();QR();lF();Rp();wl();Dy();nn();mF();fT();mT();fT();mT();uT();dT();Jy=class Jy extends xl{#e;#t;#r;#n;#o;#i;#a;#s;#c;#l;#d;#p;#m;constructor(e,t,r,o,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=o,this.#o=n,this.#i=void 0,this.#a=new Yi,this.#s=!1,this.#l=!1,this.#d=!1,this.#p=void 0,this.#m=new Qi}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let t=this.#m.alloc();return this.#f({type:"store_sql",sqlId:t,sql:e}).then(()=>{return},(r)=>this._setClosed(r)),new ha(this,t)}_closeSql(e){if(this.#p!==void 0)return;this.#f({type:"close_sql",sqlId:e}).then(()=>this.#m.free(e),(t)=>this._setClosed(t))}_execute(e){return this.#f({type:"execute",stmt:e}).then((t)=>t.result)}_batch(e){return this.#f({type:"batch",batch:e}).then((t)=>t.result)}_describe(e){return this.#f({type:"describe",sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#f({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#f({type:"get_autocommit"}).then((e)=>e.isAutocommit)}#f(e){return new Promise((t,r)=>{this.#g({type:"pipeline",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return new Promise((t,r)=>{this.#g({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_cursorClosed(e){if(e!==this.#c)throw new or("Cursor was closed, but it was not associated with the stream");this.#c=void 0,ga(()=>this.#u())}close(){this._setClosed(new Ge("Stream was manually closed"))}closeGracefully(){this.#l=!0,ga(()=>this.#u())}get closed(){return this.#p!==void 0||this.#l}_setClosed(e){if(this.#p!==void 0)return;if(this.#p=e,this.#c!==void 0)this.#c._setClosed(e);this.#e._streamClosed(this);for(;;){let t=this.#a.shift();if(t!==void 0)t.errorCallback(e);else break}if((this.#i!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,ga(()=>this.#u())}#g(e){if(this.#p!==void 0)throw new xt("Stream is closed",this.#p);else if(this.#l)throw new xt("Stream is closing",void 0);else this.#a.push(e),ga(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new Ge("Stream was gracefully closed"));return}let e=this.#e._endpoint;if(e===void 0){this.#e._endpointPromise.then(()=>this.#u(),(r)=>this._setClosed(r));return}let t=this.#a.shift();if(t===void 0)return;else if(t.type==="pipeline"){let r=[t];for(;;){let o=this.#a.first();if(o!==void 0&&o.type==="pipeline")r.push(o),this.#a.shift();else if(o===void 0&&this.#l&&!this.#d){r.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0;break}else break}this.#y(e,r)}else if(t.type==="cursor")this.#b(e,t);else throw Ke(t,"Impossible type of QueueEntry")}#y(e,t){this.#h(()=>this.#S(t,e),(r)=>Rme(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>Ame(t,r),(r)=>t.forEach((o)=>o.errorCallback(r)))}#b(e,t){let r=new pT(this,e.encoding);this.#c=r,this.#h(()=>this.#v(t,e),(o)=>r.open(o),(o)=>o.baton,(o)=>o.baseUrl,(o)=>t.cursorCallback(r),(o)=>t.errorCallback(o))}#h(e,t,r,o,n,i){let s;try{let a=e(),l=this.#n;s=l(a)}catch(a){s=Promise.reject(a)}this.#s=!0,s.then((a)=>{if(!a.ok)return Tme(a).then((l)=>{throw l});return t(a)}).then((a)=>{this.#i=r(a),this.#t=o(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),i(a)}).finally(()=>{this.#s=!1,this.#u()})}#S(e,t){return this.#w(new URL(t.pipelinePath,this.#t),{baton:this.#i,requests:e.map((r)=>r.request)},t.encoding,hF,yF)}#v(e,t){if(t.cursorPath===void 0)throw new xn(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#w(new URL(t.cursorPath,this.#t),{baton:this.#i,batch:e.batch},t.encoding,gF,bF)}#w(e,t,r,o,n){let i,s;if(r==="json")i=Ep(t,o),s="application/json";else if(r==="protobuf")i=Ap(t,n),s="application/x-protobuf";else throw Ke(r,"Impossible encoding");let a=new Headers;if(a.set("content-type",s),this.#r!==void 0)a.set("authorization",`Bearer ${this.#r}`);if(this.#o!==void 0)a.set("x-turso-encryption-key",this.#o);return new Request(e.toString(),{method:"POST",headers:a,body:i})}}});async function Ome(e,t){let r=e;for(let o of $me){let n=new URL(o.versionPath,t),i=new Request(n.toString(),{method:"GET"}),s=await r(i);if(await s.arrayBuffer(),s.ok)return o}return gT}var $me,gT,Ky;var yT=v(()=>{_t();hT();$me=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],gT={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};Ky=class Ky extends gl{#e;#t;#r;#n;#o;#i;_endpointPromise;_endpoint;constructor(e,t,r,o,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=o,this.#o=void 0,this.#i=new Set,n==3)this._endpointPromise=Ome(this.#r,this.#e),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i));else this._endpointPromise=Promise.resolve(gT),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=gT.version)return;else if(this._endpoint===void 0)throw new xn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the HTTP server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this._endpoint.version<e)throw new xn(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#o!==void 0)throw new xt("Client is closed",this.#o);let e=new Jy(this,this.#e,this.#t,this.#r,this.#n);return this.#i.add(e),e}_streamClosed(e){this.#i.delete(e)}close(){this.#a(new Ge("Client was manually closed"))}get closed(){return this.#o!==void 0}#a(e){if(this.#o!==void 0)return;this.#o=e;for(let t of Array.from(this.#i))t._setClosed(new xt("Client was closed",e))}}});var SF=v(()=>{_t()});function bT(e,t,r=2){if(typeof Vi>"u")throw new xp("WebSockets are not supported in this environment");var o=void 0;if(r==3)o=Array.from(cT.keys());else o=Array.from(cF.keys());let n=new Vi(e,o);return new qy(n,t)}function ST(e,t,r,o,n=2){return new Ky(e instanceof URL?e:new URL(e),t,r,o,n)}var Hy=v(()=>{HR();Fy();_t();yT();Fy();HR();tT();SF();wl();zy();Dy();yT();hT();Fy();nT();_t()});class Dp{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}execute(e){return this.batch([e]).then((t)=>t[0])}async batch(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(Uo),o;if(this.#r===void 0){this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=i.step(),a=s.run(Ki(this.#e)),l=s;o=r.map((u)=>{let d=i.step().condition(ut.ok(l));if(this.#t>=3)d.condition(ut.not(ut.isAutocommit(i)));let p=d.query(u);return p.catch(()=>{return}),l=d,p}),this.#r=i.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(u){throw this.close(),u}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=void 0;o=r.map((a)=>{let l=i.step();if(s!==void 0)l.condition(ut.ok(s));if(this.#t>=3)l.condition(ut.not(ut.isAutocommit(i)));let u=l.query(a);return u.catch(()=>{return}),s=l,u}),await i.execute()}let n=[];for(let i=0;i<o.length;i++)try{let s=await o[i];if(s===void 0)throw new Wt("Statement in a transaction was not executed, probably because the transaction has been rolled back",i,"TRANSACTION_CLOSED");n.push(Rl(s))}catch(s){if(s instanceof Wt)throw s;let a=st(s);if(a instanceof Ce)throw new Wt(a.message,i,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw st(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(Ki(this.#e)).then(()=>{return});try{await this.#r}catch(r){throw this.close(),r}}else await this.#r;await t.sequence(e)}catch(r){throw st(r)}}async rollback(){try{let e=this._getStream();if(e.closed)return;if(this.#r!==void 0);else return;let t=e.run("ROLLBACK").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Ce("Cannot commit the transaction because it is already closed","TRANSACTION_CLOSED");if(this.#r!==void 0)await this.#r;else return;let t=e.run("COMMIT").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}}async function Al(e,t,r,o,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let i=r.step(),s=i.run(Ki(e)),a=i,l=o.map((h)=>{let b=r.step().condition(ut.ok(a));if(t>=3)b.condition(ut.not(ut.isAutocommit(r)));let y=b.query(h);return a=b,y}),u=r.step().condition(ut.ok(a));if(t>=3)u.condition(ut.not(ut.isAutocommit(r)));let d=u.run("COMMIT");if(r.step().condition(ut.not(ut.ok(u))).run("ROLLBACK").catch((h)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let m=[];await s;for(let h=0;h<l.length;h++)try{let b=await l[h];if(b===void 0)throw new Wt("Statement in a batch was not executed, probably because the transaction has been rolled back",h,"TRANSACTION_CLOSED");m.push(Rl(b))}catch(b){if(b instanceof Wt)throw b;let y=st(b);if(y instanceof Ce)throw new Wt(y.message,h,y.code,y.extendedCode,y.rawCode,y.cause instanceof Error?y.cause:void 0);throw y}return await d,m}function Uo(e){let t,r;if(Array.isArray(e))[t,r]=e;else if(typeof e==="string")t=e;else t=e.sql,r=e.args;let o=new $p(t);if(r)if(Array.isArray(r))o.bindIndexes(r);else for(let[n,i]of Object.entries(r))o.bindName(n,i);return o}function Rl(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),o=e.rows,n=e.affectedRowCount,i=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new pl(t,r,o,n,i)}function st(e){if(e instanceof Ge){let t=vF(e);return new Ce(e.message,t,void 0,void 0,e)}return e}function vF(e){if(e instanceof wp&&e.code!==void 0)return e.code;else if(e instanceof Pe)return"HRANA_PROTO_ERROR";else if(e instanceof xt)return e.cause instanceof Ge?vF(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof yl)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof da)return"SERVER_ERROR";else if(e instanceof xn)return"PROTOCOL_VERSION_ERROR";else if(e instanceof or)return"INTERNAL_ERROR";else return"UNKNOWN"}var wT=v(()=>{Hy();wn();fl()});class Tl{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new wF,this.capacity=t}apply(e){if(this.capacity<=0)return;let t=new Set;for(let r of e){if(typeof r.sql!=="string")continue;let o=r.sql;if(o.length>=5000)continue;let n=this.#t.get(o);if(n===void 0){while(this.#t.size+1>this.capacity){let[i,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(i)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(o),this.#t.set(o,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class wF{#e;constructor(){this.#e=new Map}get(e){let t=this.#e.get(e);if(t!==void 0)this.#e.delete(e),this.#e.set(e,t);return t}set(e,t){this.#e.set(e,t)}peekLru(){for(let e of this.#e.entries())return e;return}delete(e){this.#e.delete(e)}get size(){return this.#e.size}}var xT=ge(function(eje,_F){function Cme(e){var t=0,r=[];function o(){if(t--,t<e)n()}function n(){var l=r.shift();if(a.queue=r.length,l)s(l.fn).then(l.resolve).catch(l.reject)}function i(l){return new Promise(function(u,d){r.push({fn:l,resolve:u,reject:d}),a.queue=r.length})}function s(l){t++;try{return Promise.resolve(l()).then(function(u){return o(),u},function(u){throw o(),u})}catch(u){return o(),Promise.reject(u)}}var a=function(l){if(t>=e)return i(l);else return s(l)};return a}function Pme(e,t){var r=!1,o=this;return Promise.all(e.map(function(){var n=arguments;return o(function(){if(!r)return t.apply(void 0,n).catch(function(i){throw r=!0,i})})}))}function xF(e){return e.queue=0,e.map=Pme,e}_F.exports=function(e){if(e)return xF(Cme(e));else return xF(function(t){return t()})}});function kF(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Ce(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${Xn}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Ce('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Ce('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=gp(e.scheme,e.authority,e.path),r;try{r=bT(t,e.authToken)}catch(o){if(o instanceof xp){let n=e.scheme==="wss"?"https":"http",i=gp(n,e.authority,e.path);throw new Ce(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(i)}). For more information, please read ${Xn}`,"WEBSOCKETS_NOT_SUPPORTED")}throw st(o)}return new AF(r,t,e.authToken,e.intMode,e.concurrency)}class AF{#e;#t;#r;#n;#o;closed;protocol;#i;#a;constructor(e,t,r,o,n){this.#e=t,this.#t=r,this.#r=o,this.#n=this.#c(e),this.#o=void 0,this.closed=!1,this.protocol="ws",this.#a=IF.default(n)}async limit(e){return this.#a(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{let o=await this.#s();try{let n=Uo(r);o.conn.sqlCache.apply([n]);let i=o.stream.query(n);o.stream.closeGracefully();let s=await i;return Rl(s)}catch(n){throw st(n)}finally{this._closeStream(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((u)=>{if(Array.isArray(u))return{sql:u[0],args:u[1]||[]};return u}).map(Uo),i=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(i>=3);return await Al(t,i,s,n)}catch(o){throw st(o)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(Uo),o=await t.conn.client.getVersion(),n=t.stream.batch(o>=3);return await Al("deferred",o,n,r,!0)}catch(r){throw st(r)}finally{this._closeStream(t)}})}async transaction(e="write"){return this.limit(async()=>{let t=await this.#s();try{let r=await t.conn.client.getVersion();return new RF(this,t,e,r)}catch(r){throw this._closeStream(t),st(r)}})}async executeMultiple(e){return this.limit(async()=>{let t=await this.#s();try{let r=t.stream.sequence(e);t.stream.closeGracefully(),await r}catch(r){throw st(r)}finally{this._closeStream(t)}})}sync(){throw new Ce("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>zme&&this.#o===void 0){let o=this.#c();this.#o=o,o.client.getVersion().then((n)=>{if(this.#n!==o){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=o,this.#o=void 0},(n)=>{this.#o=void 0})}if(this.#n.client.closed)try{if(this.#o!==void 0)this.#n=this.#o;else this.#n=this.#c()}catch(o){throw st(o)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=EF}let o=r.client.openStream();o.intMode=this.#r;let n={conn:r,stream:o};return r.streamStates.add(n),n}catch(o){throw st(o)}}#c(e){try{return e??=bT(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new Tl(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw st(t)}}async reconnect(){try{for(let r of Array.from(this.#n.streamStates))try{r.stream.close()}catch{}this.#n.client.close()}catch{}if(this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=EF;this.#n=e,this.closed=!1}_closeStream(e){e.stream.close();let t=e.conn;if(t.streamStates.delete(e),t.streamStates.size===0&&t!==this.#n)t.client.close()}close(){if(this.#n.client.close(),this.closed=!0,this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}this.closed=!0}}var IF,zme=60000,EF=100,RF;var TF=v(()=>{Hy();wn();Sp();wT();_y();fl();IF=Jl(xT(),1);wn();RF=class RF extends Dp{#e;#t;constructor(e,t,r,o){super(r,o);this.#e=e,this.#t=t}_getStream(){return this.#t.stream}_getSqlCache(){return this.#t.conn.sqlCache}close(){this.#e._closeStream(this.#t)}get closed(){return this.#t.stream.closed}}});function OF(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Ce(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${Xn}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Ce('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Ce('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=gp(e.scheme,e.authority,e.path);return new PF(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class PF{#e;protocol;#t;#r;#n;#o;#i;#a;#s;constructor(e,t,r,o,n,i){this.#t=e,this.#i=t,this.#r=r,this.#n=o,this.#o=n,this.#a=i,this.#e=ST(this.#t,this.#i,this.#n,i),this.#e.intMode=this.#r,this.protocol="http",this.#s=$F.default(this.#o)}async limit(e){return this.#s(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{try{let o=Uo(r),n,i=this.#e.openStream();try{n=i.query(o)}finally{i.closeGracefully()}let s=await n;return Rl(s)}catch(o){throw st(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let o=e.map((l)=>{if(Array.isArray(l))return{sql:l[0],args:l[1]||[]};return l}).map(Uo),n=await this.#e.getVersion(),i,s=this.#e.openStream();try{new Tl(s,CF).apply(o);let u=s.batch(!1);i=Al(t,n,u,o)}finally{s.closeGracefully()}return await i}catch(r){throw st(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(Uo),r=await this.#e.getVersion(),o,n=this.#e.openStream();try{let s=n.batch(!1);o=Al("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await o}catch(t){throw st(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new zF(this.#e.openStream(),e,t)}catch(t){throw st(t)}})}async executeMultiple(e){return this.limit(async()=>{try{let t,r=this.#e.openStream();try{t=r.sequence(e)}finally{r.closeGracefully()}await t}catch(t){throw st(t)}})}sync(){throw new Ce("sync not supported in http mode","SYNC_NOT_SUPPORTED")}close(){this.#e.close()}async reconnect(){try{if(!this.closed)this.#e.close()}finally{this.#e=ST(this.#t,this.#i,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var $F,CF=30,zF;var NF=v(()=>{Hy();wn();Sp();wT();_y();fl();$F=Jl(xT(),1);wn();zF=class zF extends Dp{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new Tl(e,CF)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function $l(e){return Nme(bp(e,!0))}function Nme(e){if(e.scheme==="wss"||e.scheme==="ws")return kF(e);else if(e.scheme==="https"||e.scheme==="http")return OF(e);else return $4(e)}var _T=v(()=>{Sp();N4();TF();NF();wn()});function oe(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,F))throw Error(`Class "${t.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 r=Object.getPrototypeOf(e).constructor;if(r)while(r){if(F in r&&r[F]===t[F])return!0;r=Object.getPrototypeOf(r)}return!1}var F;var $e=v(()=>{F=Symbol.for("drizzle:entityKind")});var He;var En=v(()=>{$e();He=class He{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[F]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var Lp;var Vy=v(()=>{$e();Lp=class Lp{static[F]="ColumnBuilder";config;constructor(e,t,r){this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:r,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){if(this.config.name!=="")return;this.config.name=e}}});var ir;var Ol=v(()=>{ir=Symbol.for("drizzle:Name")});var ET,DF;var LF=v(()=>{$e();Ol();ET=class ET{static[F]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e===void 0?"no action":e,this}onDelete(e){return this._onDelete=e===void 0?"no action":e,this}build(e){return new DF(e,this)}};DF=class DF{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function Wy(e,...t){return e(...t)}var IT=()=>{};function kT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var BF,Dme,jF;var ZF=v(()=>{$e();Ol();BF=class BF{constructor(e,t){this.name=t,this.columns=e}static[F]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new jF(e,this.columns,this.nullsNotDistinctConfig,this.name)}};Dme=class Dme{static[F]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new BF(e,this.name)}};jF=class jF{constructor(e,t,r,o){this.table=e,this.columns=t,this.name=o??kT(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[F]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function UF(e,t,r){for(let o=t;o<e.length;o++){let n=e[o];if(n==="\\"){o++;continue}if(n==='"')return[e.slice(t,o).replace(/\\/g,""),o+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,o).replace(/\\/g,""),o]}return[e.slice(t).replace(/\\/g,""),e.length]}function MF(e,t=0){let r=[],o=t,n=!1;while(o<e.length){let i=e[o];if(i===","){if(n||o===t)r.push("");n=!0,o++;continue}if(n=!1,i==="\\"){o+=2;continue}if(i==='"'){let[l,u]=UF(e,o+1,!0);r.push(l),o=u;continue}if(i==="}")return[r,o+1];if(i==="{"){let[l,u]=MF(e,o+1);r.push(l),o=u;continue}let[s,a]=UF(e,o,!1);r.push(s),o=a}return[r,o]}function qF(e){let[t]=MF(e,1);return t}function AT(e){return`{${e.map((t)=>{if(Array.isArray(t))return AT(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var FF=()=>{};var Bp,Cl,JF,Lme,KF,RT;var HF=v(()=>{Vy();En();$e();LF();IT();ZF();FF();Bp=class Bp extends Lp{foreignKeyConfigs=[];static[F]="PgColumnBuilder";array(e){return new KF(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>Wy((n,i)=>{let s=new ET(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)},r,o))}buildExtraConfigColumn(e){return new JF(e,this.config)}};Cl=class Cl extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=kT(e,[t.name]);super(e,t);this.table=e}static[F]="PgColumn"};JF=class JF extends Cl{static[F]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}};Lme=class Lme{static[F]="IndexedColumn";constructor(e,t,r,o){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=o}name;keyAsName;type;indexConfig};KF=class KF extends Bp{static[F]="PgArrayBuilder";constructor(e,t,r){super(e,"array","PgArray");this.config.baseBuilder=t,this.config.size=r}build(e){let t=this.config.baseBuilder.build(e);return new RT(e,this.config,t)}};RT=class RT extends Cl{constructor(e,t,r,o){super(e,t);this.baseColumn=r,this.range=o,this.size=t.size}size;static[F]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=qF(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((o)=>o===null?null:oe(this.baseColumn,RT)?this.baseColumn.mapToDriverValue(o,!0):this.baseColumn.mapToDriverValue(o));if(t)return r;return AT(r)}}});function GF(e){return!!e&&typeof e==="function"&&VF in e&&e[VF]===!0}var Bme,WF,VF,jme,QF;var YF=v(()=>{$e();HF();Bme=class Bme extends Bp{static[F]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new WF(e,this.config)}};WF=class WF extends Cl{static[F]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};VF=Symbol.for("drizzle:isPgEnum");jme=class jme extends Bp{static[F]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new QF(e,this.config)}};QF=class QF extends Cl{static[F]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}}});var dt,jp;var In=v(()=>{$e();dt=class dt{static[F]="Subquery";constructor(e,t,r,o=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:o,usedTables:n}}};jp=class jp extends dt{static[F]="WithSubquery"}});var XF="0.45.2";var e3=()=>{};var TT,$T,t3;var r3=v(()=>{IT();e3();t3={startActiveSpan(e,t){if(!TT)return t();if(!$T)$T=TT.trace.getTracer("drizzle-orm",XF);return Wy((r,o)=>o.startActiveSpan(e,(n)=>{try{return t(n)}catch(i){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:i instanceof Error?i.message:"Unknown error"}),i}finally{n.end()}}),TT,$T)}}});var pt;var Mo=v(()=>{pt=Symbol.for("drizzle:ViewBaseConfig")});function ts(e){return e[ir]}function ya(e){return`${e[Gy]??"public"}.${e[ir]}`}var Gy,Qy,n3,OT,CT,Zp,o3,Zme,he;var sr=v(()=>{$e();Ol();Gy=Symbol.for("drizzle:Schema"),Qy=Symbol.for("drizzle:Columns"),n3=Symbol.for("drizzle:ExtraConfigColumns"),OT=Symbol.for("drizzle:OriginalName"),CT=Symbol.for("drizzle:BaseName"),Zp=Symbol.for("drizzle:IsAlias"),o3=Symbol.for("drizzle:ExtraConfigBuilder"),Zme=Symbol.for("drizzle:IsDrizzleTable");he=class he{static[F]="Table";static Symbol={Name:ir,Schema:Gy,OriginalName:OT,Columns:Qy,ExtraConfigColumns:n3,BaseName:CT,IsAlias:Zp,ExtraConfigBuilder:o3};[ir];[OT];[Gy];[Qy];[n3];[CT];[Zp]=!1;[Zme]=!0;[o3]=void 0;constructor(e,t,r){this[ir]=this[OT]=e,this[Gy]=t,this[CT]=r}}});function PT(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function Mme(e){let t={sql:"",params:[]};for(let r of e)if(t.sql+=r.sql,t.params.push(...r.params),r.typings?.length){if(!t.typings)t.typings=[];t.typings.push(...r.typings)}return t}function i3(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function C(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Nt(e[0]));for(let[o,n]of t.entries())r.push(n,new Nt(e[o+1]));return new Ee(r)}function Up(e,t){return e.map((r)=>{if(oe(r,rs)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(oe(r,Mr)&&oe(r.value,rs)){if(!(r.value.name in t))throw Error(`No value for placeholder "${r.value.name}" was provided`);return r.encoder.mapToDriverValue(t[r.value.name])}return r})}var Ume,Nt,Ee,Yy,s3,a3,dZe,Mr,rs,qme,sn;var Qt=v(()=>{$e();YF();In();r3();Mo();En();sr();Ume=class Ume{static[F]="FakePrimitiveParam"};Nt=class Nt{static[F]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new Ee([this])}};Ee=class Ee{constructor(e){this.queryChunks=e;for(let t of e)if(oe(t,he)){let r=t[he.Symbol.Schema];this.usedTables.push(r===void 0?t[he.Symbol.Name]:r+"."+t[he.Symbol.Name])}}static[F]="SQL";decoder=s3;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return t3.startActiveSpan("drizzle.buildSQL",(t)=>{let r=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(e,t){let r=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:o,escapeName:n,escapeParam:i,prepareTyping:s,inlineParams:a,paramStartIndex:l}=r;return Mme(e.map((u)=>{if(oe(u,Nt))return{sql:u.value.join(""),params:[]};if(oe(u,Yy))return{sql:n(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){let d=[new Nt("(")];for(let[p,m]of u.entries())if(d.push(m),p<u.length-1)d.push(new Nt(", "));return d.push(new Nt(")")),this.buildQueryFromSourceParams(d,r)}if(oe(u,Ee))return this.buildQueryFromSourceParams(u.queryChunks,{...r,inlineParams:a||u.shouldInlineParams});if(oe(u,he)){let d=u[he.Symbol.Schema],p=u[he.Symbol.Name];return{sql:d===void 0||u[Zp]?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,He)){let d=o.getColumnCasing(u);if(t.invokeSource==="indexes")return{sql:n(d),params:[]};let p=u.table[he.Symbol.Schema];return{sql:u.table[Zp]||p===void 0?n(u.table[he.Symbol.Name])+"."+n(d):n(p)+"."+n(u.table[he.Symbol.Name])+"."+n(d),params:[]}}if(oe(u,sn)){let d=u[pt].schema,p=u[pt].name;return{sql:d===void 0||u[pt].isAlias?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,Mr)){if(oe(u.value,rs))return{sql:i(l.value++,u),params:[u],typings:["none"]};let d=u.value===null?null:u.encoder.mapToDriverValue(u.value);if(oe(d,Ee))return this.buildQueryFromSourceParams([d],r);if(a)return{sql:this.mapInlineParam(d,r),params:[]};let p=["none"];if(s)p=[s(u.encoder)];return{sql:i(l.value++,d),params:[d],typings:p}}if(oe(u,rs))return{sql:i(l.value++,u),params:[u],typings:["none"]};if(oe(u,Ee.Aliased)&&u.fieldAlias!==void 0)return{sql:n(u.fieldAlias),params:[]};if(oe(u,dt)){if(u._.isWith)return{sql:n(u._.alias),params:[]};return this.buildQueryFromSourceParams([new Nt("("),u._.sql,new Nt(") "),new Yy(u._.alias)],r)}if(GF(u)){if(u.schema)return{sql:n(u.schema)+"."+n(u.enumName),params:[]};return{sql:n(u.enumName),params:[]}}if(PT(u)){if(u.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([u.getSQL()],r);return this.buildQueryFromSourceParams([new Nt("("),u.getSQL(),new Nt(")")],r)}if(a)return{sql:this.mapInlineParam(u,r),params:[]};return{sql:i(l.value++,u),params:[u],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e==="number"||typeof e==="boolean")return e.toString();if(typeof e==="string")return t(e);if(typeof e==="object"){let r=e.toString();if(r==="[object Object]")return t(JSON.stringify(e));return t(r)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){if(e===void 0)return this;return new Ee.Aliased(this,e)}mapWith(e){return this.decoder=typeof e==="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}};Yy=class Yy{constructor(e){this.value=e}static[F]="Name";brand;getSQL(){return new Ee([this])}};s3={mapFromDriverValue:(e)=>e},a3={mapToDriverValue:(e)=>e},dZe={...s3,...a3};Mr=class Mr{constructor(e,t=a3){this.value=e,this.encoder=t}static[F]="Param";brand;getSQL(){return new Ee([this])}};((e)=>{function t(){return new Ee([])}e.empty=t;function r(l){return new Ee(l)}e.fromList=r;function o(l){return new Ee([new Nt(l)])}e.raw=o;function n(l,u){let d=[];for(let[p,m]of l.entries()){if(p>0&&u!==void 0)d.push(u);d.push(m)}return new Ee(d)}e.join=n;function i(l){return new Yy(l)}e.identifier=i;function s(l){return new rs(l)}e.placeholder=s;function a(l,u){return new Mr(l,u)}e.param=a})(C||(C={}));((e)=>{class t{constructor(r,o){this.sql=r,this.fieldAlias=o}static[F]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(Ee||(Ee={}));rs=class rs{constructor(e){this.name=e}static[F]="Placeholder";getSQL(){return new Ee([this])}};qme=Symbol.for("drizzle:IsDrizzleView");sn=class sn{static[F]="View";[pt];[qme]=!0;constructor({name:e,schema:t,selectedFields:r,query:o}){this[pt]={name:e,originalName:e,schema:t,selectedFields:r,query:o,isExisting:!o,isAlias:!1}}getSQL(){return new Ee([this])}};He.prototype.getSQL=function(){return new Ee([this])};he.prototype.getSQL=function(){return new Ee([this])};dt.prototype.getSQL=function(){return new Ee([this])}});function zT(e,t,r){let o={},n=e.reduce((i,{path:s,field:a},l)=>{let u;if(oe(a,He))u=a;else if(oe(a,Ee))u=a.decoder;else if(oe(a,dt))u=a._.sql.decoder;else u=a.sql.decoder;let d=i;for(let[p,m]of s.entries())if(p<s.length-1){if(!(m in d))d[m]={};d=d[m]}else{let h=t[l],b=d[m]=h===null?null:u.mapFromDriverValue(h);if(r&&oe(a,He)&&s.length===2){let y=s[0];if(!(y in o))o[y]=b===null?ts(a.table):!1;else if(typeof o[y]==="string"&&o[y]!==ts(a.table))o[y]=!1}}return i},{});if(r&&Object.keys(o).length>0){for(let[i,s]of Object.entries(o))if(typeof s==="string"&&!r[s])n[i]=null}return n}function an(e,t){return Object.entries(e).reduce((r,[o,n])=>{if(typeof o!=="string")return r;let i=t?[...t,o]:[o];if(oe(n,He)||oe(n,Ee)||oe(n,Ee.Aliased)||oe(n,dt))r.push({path:i,field:n});else if(oe(n,he))r.push(...an(n[he.Symbol.Columns],i));else r.push(...an(n,i));return r},[])}function Mp(e,t){let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(let[n,i]of r.entries())if(i!==o[n])return!1;return!0}function Xy(e,t){let r=Object.entries(t).filter(([,o])=>o!==void 0).map(([o,n])=>{if(oe(n,Ee)||oe(n,He))return[o,n];else return[o,new Mr(n,e[he.Symbol.Columns][o])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function c3(e,t){for(let r of t)for(let o of Object.getOwnPropertyNames(r.prototype)){if(o==="constructor")continue;Object.defineProperty(e.prototype,o,Object.getOwnPropertyDescriptor(r.prototype,o)||Object.create(null))}}function eb(e){return e[he.Symbol.Columns]}function qp(e){return oe(e,dt)?e._.alias:oe(e,sn)?e[pt].name:oe(e,Ee)?void 0:e[he.Symbol.IsAlias]?e[he.Symbol.Name]:e[he.Symbol.BaseName]}function no(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function l3(e){if(typeof e!=="object"||e===null)return!1;if(e.constructor.name!=="Object")return!1;if("logger"in e){let t=typeof e.logger;if(t!=="boolean"&&(t!=="object"||typeof e.logger.logQuery!=="function")&&t!=="undefined")return!1;return!0}if("schema"in e){let t=typeof e.schema;if(t!=="object"&&t!=="undefined")return!1;return!0}if("casing"in e){let t=typeof e.casing;if(t!=="string"&&t!=="undefined")return!1;return!0}if("mode"in e){if(e.mode!=="default"||e.mode!=="planetscale"||e.mode!==void 0)return!1;return!0}if("connection"in e){let t=typeof e.connection;if(t!=="string"&&t!=="object"&&t!=="undefined")return!1;return!0}if("client"in e){let t=typeof e.client;if(t!=="object"&&t!=="function"&&t!=="undefined")return!1;return!0}if(Object.keys(e).length===0)return!0;return!1}var NT;var Sr=v(()=>{En();$e();Qt();In();sr();Mo();NT=typeof TextDecoder>"u"?null:new TextDecoder});var u3,DT,LT;var tb=v(()=>{$e();u3=class u3{static[F]="ConsoleLogWriter";write(e){console.log(e)}};DT=class DT{static[F]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new u3}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),o=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${o}`)}};LT=class LT{static[F]="NoopLogger";logQuery(){}}});var d3,p3,BT;var f3=v(()=>{$e();sr();d3=Symbol.for("drizzle:PgInlineForeignKeys"),p3=Symbol.for("drizzle:EnableRLS");BT=class BT extends he{static[F]="PgTable";static Symbol=Object.assign({},he.Symbol,{InlineForeignKeys:d3,EnableRLS:p3});[d3]=[];[p3]=!1;[he.Symbol.ExtraConfigBuilder]=void 0;[he.Symbol.ExtraConfigColumns]={}}});var jT,m3;var h3=v(()=>{$e();f3();jT=class jT{static[F]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new m3(e,this.columns,this.name)}};m3=class m3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[BT.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function $r(e,t){if(i3(t)&&!PT(e)&&!oe(e,Mr)&&!oe(e,rs)&&!oe(e,He)&&!oe(e,he)&&!oe(e,sn))return new Mr(e,t);return e}function tt(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Ee(t);return new Ee([new Nt("("),C.join(t,new Nt(" and ")),new Nt(")")])}function cn(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Ee(t);return new Ee([new Nt("("),C.join(t,new Nt(" or ")),new Nt(")")])}function y3(e){return C`not ${e}`}function os(e,t){if(Array.isArray(t)){if(t.length===0)return C`false`;return C`${e} in ${t.map((r)=>$r(r,e))}`}return C`${e} in ${$r(t,e)}`}function rb(e,t){if(Array.isArray(t)){if(t.length===0)return C`true`;return C`${e} not in ${t.map((r)=>$r(r,e))}`}return C`${e} not in ${$r(t,e)}`}function qr(e){return C`${e} is null`}function v3(e){return C`${e} is not null`}function nb(e){return C`exists ${e}`}function is(e){return C`not exists ${e}`}function w3(e,t,r){return C`${e} between ${$r(t,e)} and ${$r(r,e)}`}function x3(e,t,r){return C`${e} not between ${$r(t,e)} and ${$r(r,e)}`}function _3(e,t){return C`${e} like ${t}`}function E3(e,t){return C`${e} not like ${t}`}function I3(e,t){return C`${e} ilike ${t}`}function k3(e,t){return C`${e} not ilike ${t}`}var je=(e,t)=>C`${e} = ${$r(t,e)}`,g3=(e,t)=>C`${e} <> ${$r(t,e)}`,kn=(e,t)=>C`${e} > ${$r(t,e)}`,b3=(e,t)=>C`${e} >= ${$r(t,e)}`,S3=(e,t)=>C`${e} < ${$r(t,e)}`,ns=(e,t)=>C`${e} <= ${$r(t,e)}`;var A3=v(()=>{En();$e();sr();Qt()});function qo(e){return C`${e} asc`}function ba(e){return C`${e} desc`}var R3=v(()=>{Qt()});var ZT=v(()=>{A3();R3()});function $3(){return{and:tt,between:w3,eq:je,exists:nb,gt:kn,gte:b3,ilike:I3,inArray:os,isNull:qr,isNotNull:v3,like:_3,lt:S3,lte:ns,ne:g3,not:y3,notBetween:x3,notExists:is,notLike:E3,notIlike:k3,notInArray:rb,or:cn,sql:C}}function O3(){return{sql:C,asc:qo,desc:ba}}function C3(e,t){if(Object.keys(e).length===1&&"default"in e&&!oe(e.default,he))e=e.default;let r={},o={},n={};for(let[i,s]of Object.entries(e))if(oe(s,he)){let a=ya(s),l=o[a];r[a]=i,n[i]={tsName:i,dbName:s[he.Symbol.Name],schema:s[he.Symbol.Schema],columns:s[he.Symbol.Columns],relations:l?.relations??{},primaryKey:l?.primaryKey??[]};for(let d of Object.values(s[he.Symbol.Columns]))if(d.primary)n[i].primaryKey.push(d);let u=s[he.Symbol.ExtraConfigBuilder]?.(s[he.Symbol.ExtraConfigColumns]);if(u){for(let d of Object.values(u))if(oe(d,jT))n[i].primaryKey.push(...d.columns)}}else if(oe(s,T3)){let a=ya(s.table),l=r[a],u=s.config(t(s.table)),d;for(let[p,m]of Object.entries(u))if(l){let h=n[l];if(h.relations[p]=m,d)h.primaryKey.push(...d)}else{if(!(a in o))o[a]={relations:{},primaryKey:d};o[a].relations[p]=m}}return{tables:n,tableNamesMap:r}}function Fme(e){return function(r,o){return new ss(e,r,o,o?.fields.reduce((n,i)=>n&&i.notNull,!0)??!1)}}function Jme(e){return function(r,o){return new Fp(e,r,o)}}function P3(e,t,r){if(oe(r,ss)&&r.config)return{fields:r.config.fields,references:r.config.references};let o=t[ya(r.referencedTable)];if(!o)throw Error(`Table "${r.referencedTable[he.Symbol.Name]}" not found in schema`);let n=e[o];if(!n)throw Error(`Table "${o}" not found in schema`);let i=r.sourceTable,s=t[ya(i)];if(!s)throw Error(`Table "${i[he.Symbol.Name]}" not found in schema`);let a=[];for(let l of Object.values(n.relations))if(r.relationName&&r!==l&&l.relationName===r.relationName||!r.relationName&&l.referencedTable===r.sourceTable)a.push(l);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${o}"`):Error(`There are multiple relations between "${o}" and "${r.sourceTable[he.Symbol.Name]}". Please specify relation name`);if(a[0]&&oe(a[0],ss)&&a[0].config)return{fields:a[0].config.references,references:a[0].config.fields};throw Error(`There is not enough information to infer relation "${s}.${r.fieldName}"`)}function z3(e){return{one:Fme(e),many:Jme(e)}}function ob(e,t,r,o,n=(i)=>i){let i={};for(let[s,a]of o.entries())if(a.isJson){let l=t.relations[a.tsKey],u=r[s],d=typeof u==="string"?JSON.parse(u):u;i[a.tsKey]=oe(l,ss)?d&&ob(e,e[a.relationTableTsKey],d,a.selection,n):d.map((p)=>ob(e,e[a.relationTableTsKey],p,a.selection,n))}else{let l=n(r[s]),u=a.field,d;if(oe(u,He))d=u;else if(oe(u,Ee))d=u.decoder;else d=u.sql.decoder;i[a.tsKey]=l===null?null:d.mapFromDriverValue(l)}return i}var UT,T3,ss,Fp;var Jp=v(()=>{sr();En();$e();h3();ZT();Qt();UT=class UT{constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[he.Symbol.Name]}static[F]="Relation";referencedTableName;fieldName};T3=class T3{constructor(e,t){this.table=e,this.config=t}static[F]="Relations"};ss=class ss extends UT{constructor(e,t,r,o){super(e,t,r?.relationName);this.config=r,this.isNullable=o}static[F]="One";withFieldName(e){let t=new ss(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};Fp=class Fp extends UT{constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[F]="Many";withFieldName(e){let t=new Fp(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function Kp(e,t){return new Proxy(e,new Sa(t,!1))}function oo(e,t){return new Proxy(e,new Pl(new Proxy(e.table,new Sa(t,!1))))}function MT(e,t){return new Ee.Aliased(Hp(e.sql,t),e.fieldAlias)}function Hp(e,t){return C.join(e.queryChunks.map((r)=>{if(oe(r,He))return oo(r,t);if(oe(r,Ee))return Hp(r,t);if(oe(r,Ee.Aliased))return MT(r,t);return r}))}var Pl,Sa,Kme;var Vp=v(()=>{En();$e();Qt();sr();Mo();Pl=class Pl{constructor(e){this.table=e}static[F]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};Sa=class Sa{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[F]="TableAliasProxyHandler";get(e,t){if(t===he.Symbol.IsAlias)return!0;if(t===he.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===he.Symbol.OriginalName)return this.alias;if(t===pt)return{...e[pt],name:this.alias,isAlias:!0};if(t===he.Symbol.Columns){let o=e[he.Symbol.Columns];if(!o)return o;let n={};return Object.keys(o).map((i)=>{n[i]=new Proxy(o[i],new Pl(new Proxy(e,this)))}),n}let r=e[t];if(oe(r,He))return new Proxy(r,new Pl(new Proxy(e,this)));return r}};Kme=class Kme{constructor(e){this.alias=e}static[F]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return Kp(e.sourceTable,this.alias);return e[t]}}});var at;var va=v(()=>{Vp();En();$e();Qt();In();Mo();at=class at{static[F]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===pt)return{...e[pt],selectedFields:new Proxy(e[pt].selectedFields,this)};if(typeof t==="symbol")return e[t];let o=(oe(e,dt)?e._.selectedFields:oe(e,sn)?e[pt].selectedFields:e)[t];if(oe(o,Ee.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!o.isSelectionField)return o.sql;let n=o.clone();return n.isSelectionField=!0,n}if(oe(o,Ee)){if(this.config.sqlBehavior==="sql")return o;throw Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(oe(o,He)){if(this.config.alias)return new Proxy(o,new Pl(new Proxy(o.table,new Sa(this.config.alias,this.config.replaceOriginalName??!1))));return o}if(typeof o!=="object"||o===null)return o;return new Proxy(o,new at(this.config))}}});var vr;var Fo=v(()=>{$e();vr=class vr{static[F]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}});var qT,N3;var FT=v(()=>{$e();Ol();qT=class qT{static[F]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new N3(e,this)}};N3=class N3{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function JT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var D3,Hme,L3;var KT=v(()=>{$e();Ol();D3=class D3{constructor(e,t){this.name=t,this.columns=e}static[F]="SQLiteUniqueConstraintBuilder";columns;build(e){return new L3(e,this.columns,this.name)}};Hme=class Hme{static[F]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new D3(e,this.name)}};L3=class L3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??JT(this.table,this.columns.map((o)=>o.name))}static[F]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Zt,yt;var as=v(()=>{Vy();En();$e();FT();KT();Zt=class Zt extends Lp{static[F]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:"always",mode:t?.mode??"virtual"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>((n,i)=>{let s=new qT(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)})(r,o))}};yt=class yt extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=JT(e,[t.name]);super(e,t);this.table=e}static[F]="SQLiteColumn"}});function F3(e,t){let{name:r,config:o}=no(e,t);if(o?.mode==="json")return new Z3(r);if(o?.mode==="bigint")return new B3(r);return new M3(r)}var B3,j3,Z3,U3,M3,q3;var HT=v(()=>{$e();Sr();as();B3=class B3 extends Zt{static[F]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new j3(e,this.config)}};j3=class j3 extends yt{static[F]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return BigInt(t.toString("utf8"))}return BigInt(NT.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};Z3=class Z3 extends Zt{static[F]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new U3(e,this.config)}};U3=class U3 extends yt{static[F]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return JSON.parse(t.toString("utf8"))}return JSON.parse(NT.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};M3=class M3 extends Zt{static[F]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new q3(e,this.config)}};q3=class q3 extends yt{static[F]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function H3(e){return(t,r)=>{let{name:o,config:n}=no(t,r);return new J3(o,n,e)}}var J3,K3;var VT=v(()=>{$e();Sr();as();J3=class J3 extends Zt{static[F]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new K3(e,this.config)}};K3=class K3 extends yt{static[F]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(e,t){super(e,t);this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom==="function"?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo==="function"?this.mapTo(e):e}}});function ar(e,t){let{name:r,config:o}=no(e,t);if(o?.mode==="timestamp"||o?.mode==="timestamp_ms")return new G3(r,o.mode);if(o?.mode==="boolean")return new Y3(r,o.mode);return new V3(r)}var ib,sb,V3,W3,G3,Q3,Y3,X3;var WT=v(()=>{$e();Qt();Sr();as();ib=class ib extends Zt{static[F]="SQLiteBaseIntegerBuilder";constructor(e,t,r){super(e,t,r);this.config.autoIncrement=!1}primaryKey(e){if(e?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};sb=class sb extends yt{static[F]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};V3=class V3 extends ib{static[F]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new W3(e,this.config)}};W3=class W3 extends sb{static[F]="SQLiteInteger"};G3=class G3 extends ib{static[F]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(C`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new Q3(e,this.config)}};Q3=class Q3 extends sb{static[F]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(e){if(this.config.mode==="timestamp")return new Date(e*1000);return new Date(e)}mapToDriverValue(e){let t=e.getTime();if(this.config.mode==="timestamp")return Math.floor(t/1000);return t}};Y3=class Y3 extends ib{static[F]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new X3(e,this.config)}};X3=class X3 extends sb{static[F]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function s5(e,t){let{name:r,config:o}=no(e,t),n=o?.mode;return n==="number"?new r5(r):n==="bigint"?new o5(r):new e5(r)}var e5,t5,r5,n5,o5,i5;var GT=v(()=>{$e();Sr();as();e5=class e5 extends Zt{static[F]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new t5(e,this.config)}};t5=class t5 extends yt{static[F]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};r5=class r5 extends Zt{static[F]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new n5(e,this.config)}};n5=class n5 extends yt{static[F]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};o5=class o5 extends Zt{static[F]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new i5(e,this.config)}};i5=class i5 extends yt{static[F]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function l5(e){return new a5(e??"")}var a5,c5;var QT=v(()=>{$e();as();a5=class a5 extends Zt{static[F]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new c5(e,this.config)}};c5=class c5 extends yt{static[F]="SQLiteReal";getSQLType(){return"real"}}});function ft(e,t={}){let{name:r,config:o}=no(e,t);if(o.mode==="json")return new p5(r);return new u5(r,o)}var u5,d5,p5,f5;var YT=v(()=>{$e();Sr();as();u5=class u5 extends Zt{static[F]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new d5(e,this.config)}};d5=class d5 extends yt{static[F]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};p5=class p5 extends Zt{static[F]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new f5(e,this.config)}};f5=class f5 extends yt{static[F]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function m5(){return{blob:F3,customType:H3,integer:ar,numeric:s5,real:l5,text:ft}}var h5=v(()=>{HT();VT();WT();GT();QT();YT()});function Vme(e,t,r,o,n=e){let i=new At(e,o,n),s=typeof t==="function"?t(m5()):t,a=Object.fromEntries(Object.entries(s).map(([u,d])=>{let p=d;p.setName(u);let m=p.build(i);return i[XT].push(...p.buildForeignKeys(m,i)),[u,m]})),l=Object.assign(i,a);if(l[he.Symbol.Columns]=a,l[he.Symbol.ExtraConfigColumns]=a,r)l[At.Symbol.ExtraConfigBuilder]=r;return l}var XT,At,Wp=(e,t,r)=>Vme(e,t,r);var Jo=v(()=>{$e();sr();h5();XT=Symbol.for("drizzle:SQLiteInlineForeignKeys");At=class At extends he{static[F]="SQLiteTable";static Symbol=Object.assign({},he.Symbol,{InlineForeignKeys:XT});[he.Symbol.Columns];[XT]=[];[he.Symbol.ExtraConfigBuilder]=void 0}});var Wme,g5;var y5=v(()=>{$e();Wme=class Wme{constructor(e,t){this.name=e,this.value=t}static[F]="SQLiteCheckBuilder";brand;build(e){return new g5(e,this)}};g5=class g5{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[F]="SQLiteCheck";name;value}});function Ko(e){return new b5(e,!1)}var b5,S5,v5;var w5=v(()=>{$e();b5=class b5{constructor(e,t){this.name=e,this.unique=t}static[F]="SQLiteIndexBuilderOn";on(...e){return new S5(this.name,e,this.unique)}};S5=class S5{static[F]="SQLiteIndexBuilder";config;constructor(e,t,r){this.config={name:e,columns:t,unique:r,where:void 0}}where(e){return this.config.where=e,this}build(e){return new v5(this.config,e)}};v5=class v5{static[F]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var Gme,x5;var _5=v(()=>{$e();Jo();Gme=class Gme{static[F]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new x5(e,this.columns,this.name)}};x5=class x5{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[At.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function An(e){if(oe(e,At))return[`${e[he.Symbol.BaseName]}`];if(oe(e,dt))return e._.usedTables??[];if(oe(e,Ee))return e.usedTables??[];return[]}var zl=v(()=>{$e();Qt();In();sr();Jo()});var ab;var E5=v(()=>{$e();Fo();va();Jo();sr();Sr();zl();ab=class ab extends vr{constructor(e,t,r,o){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:o}}static[F]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[he.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[At.Symbol.Columns]){return this.config.returning=an(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:An(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(e){return this._prepare().execute(e)}$dynamic(){return this}}});function Qme(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function Yme(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,o,n)=>{let i=n===0?o.toLowerCase():`${o[0].toUpperCase()}${o.slice(1)}`;return r+i},"")}function Xme(e){return e}var e$;var I5=v(()=>{$e();sr();e$=class e${static[F]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Qme:e==="camelCase"?Yme:Xme}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[he.Symbol.Schema]??"public",r=e.table[he.Symbol.OriginalName],o=`${t}.${r}.${e.name}`;if(!this.cache[o])this.cacheTable(e.table);return this.cache[o]}cacheTable(e){let t=e[he.Symbol.Schema]??"public",r=e[he.Symbol.OriginalName],o=`${t}.${r}`;if(!this.cachedTables[o]){for(let n of Object.values(e[he.Symbol.Columns])){let i=`${o}.${n.name}`;this.cache[i]=this.convert(n.name)}this.cachedTables[o]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var Nl,Ho,t$;var cb=v(()=>{$e();Nl=class Nl extends Error{static[F]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};Ho=class Ho extends Error{constructor(e,t,r){super(`Failed query: ${e}
417
+ `)}catch{}}}formatJsonEntry(e,t,r){let o={ts:new Date().toISOString(),level:e,...al&&{role:al},msg:t};if(this.context)o.ctx=this.context;if(r.length>0)o.data=r;return JSON.stringify(o)}debugStream(){return this.useStderr?console.error.bind(console):console.debug.bind(console)}silly(e,...t){if(this.level<=aa.SILLY)this.write(this.debugStream(),"silly",e,t)}verbose(e,...t){if(this.level<=aa.VERBOSE)this.write(this.debugStream(),"verbose",e,t)}debug(e,...t){if(this.level<=aa.DEBUG)this.write(this.debugStream(),"debug",e,t)}info(e,...t){if(this.level<=aa.INFO){let r=this.useStderr?console.error.bind(console):console.info.bind(console);this.write(r,"info",e,t)}}warn(e,...t){if(this.level<=aa.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=aa.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new Rr({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var aa,al,k2e;var BR=v(()=>{aa={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};k2e=Rr.getInstance()});var jR,Gde,cl,$2e;var mp=v(()=>{Ot();pe();jR=c.enum(["file_operations","content_operations","data_processing","batch_processing"]),Gde=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:jR,operationTarget:c.string().optional(),interfaceType:c.string().optional(),interfaceId:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:Wn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:ko.optional()}),cl=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:jR,operationTarget:c.string().optional(),interfaceType:c.string().optional(),interfaceId:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:Wn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:ko.optional(),rootJobId:c.string()}),$2e=c.enum(["none","skip","replace","coalesce"])});var Qde,Ji=15000;var hp=v(()=>{mp();pe();Qde=c.object({id:c.string(),type:c.string(),data:c.string(),status:c.enum(["pending","processing","completed","failed"]),source:c.string().nullable(),priority:c.number(),retryCount:c.number(),maxRetries:c.number(),lastError:c.string().nullable(),lastErrorPublic:c.unknown(),createdAt:c.number(),scheduledFor:c.number(),startedAt:c.number().nullable(),completedAt:c.number().nullable(),attemptId:c.string().nullable(),workerSlotId:c.string().nullable(),workerSessionId:c.string().nullable(),leaseExpiresAt:c.number().nullable(),attemptHeartbeatAt:c.number().nullable(),runtimeUpdatedAt:c.number().nullable(),metadata:cl,progress:c.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:c.unknown().nullable().optional()})});var ZR,wq,Oe,Yde,Xde,xq,_q,Eq;var Lo=v(()=>{Ot();pe();mp();ZR=c.enum(["pending","processing","completed","failed"]),wq=c.enum(["completed","failed"]),Oe={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},Yde=c.object({id:c.string(),type:c.string(),status:ZR,data:c.unknown(),result:c.unknown().optional(),lastError:c.string().optional().nullable(),attempts:c.number(),maxRetries:c.number(),priority:c.number(),createdAt:c.date(),updatedAt:c.date(),processedAt:c.date().optional().nullable(),completedAt:c.date().optional().nullable(),failedAt:c.date().optional().nullable()}),Xde=c.object({jobId:c.string(),type:c.string(),status:wq,result:c.unknown().optional(),error:c.string().optional()}),xq=c.object({success:c.literal(!1),error:c.string().optional()}),_q=c.object({id:c.string(),type:c.enum(["job","batch"]),status:ZR,message:c.string().optional(),progress:c.object({current:c.number(),total:c.number(),percentage:c.number()}).optional(),aggregationKey:c.string().optional(),batchDetails:c.object({totalOperations:c.number(),completedOperations:c.number(),failedOperations:c.number(),currentOperation:c.string().optional(),errors:c.array(c.string()).optional()}).optional(),jobDetails:c.object({jobType:c.string(),priority:c.number(),retryCount:c.number()}).optional(),metadata:cl}),Eq=Ci(zk.progress,_q)});var Ce,Wt;var wn=v(()=>{Ce=class Ce extends Error{code;extendedCode;rawCode;constructor(e,t,r,o,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=o,this.name="LibsqlError"}};Wt=class Wt extends Ce{statementIndex;constructor(e,t,r,o,n,i){super(e,r,o,n,i);this.statementIndex=t,this.name="LibsqlBatchError"}}});function Iq(e){let t=epe.exec(e);if(t===null)throw new Ce(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,o=r.scheme,n=r.authority!==void 0?tpe(r.authority):void 0,i=ca(r.path),s=r.query!==void 0?npe(r.query):void 0,a=r.fragment!==void 0?ca(r.fragment):void 0;return{scheme:o,authority:n,path:i,query:s,fragment:a}}function tpe(e){let t=rpe.exec(e);if(t===null)throw new Ce("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,o=ca(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,i=r.username!==void 0?{username:ca(r.username),password:r.password!==void 0?ca(r.password):void 0}:void 0;return{host:o,port:n,userinfo:i}}function npe(e){let t=e.split("&"),r=[];for(let o of t){if(o==="")continue;let n,i,s=o.indexOf("=");if(s<0)n=o,i="";else n=o.substring(0,s),i=o.substring(s+1);r.push({key:ca(n.replaceAll("+"," ")),value:ca(i.replaceAll("+"," "))})}return{pairs:r}}function ca(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Ce(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function gp(e,t,r){if(t===void 0)throw new Ce(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let o=`${e}:`,n=ope(t.host),i=ipe(t.port),a=`//${spe(t.userinfo)}${n}${i}`,l=r.split("/").map(encodeURIComponent).join("/");if(l!==""&&!l.startsWith("/"))l="/"+l;return new URL(`${o}${a}${l}`)}function ope(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function ipe(e){return e!==void 0?`:${e}`:""}function spe(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var epe,rpe;var _y=v(()=>{wn();epe=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();rpe=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var ul,kq,Aq,yp,Ey,ape,Gt,Rq,Oq=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),Cq=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),Pq=(e)=>{let t,r,o,n,i="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(o=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|o<<8|n,i+=yp[t>>18&63]+yp[t>>12&63]+yp[t>>6&63]+yp[t&63]}return s?i.slice(0,s-3)+"===".substring(s):i},qR,UR,Iy=(e,t=!1)=>t?Oq(UR(e)):UR(e),cpe=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?Gt(192|t>>>6)+Gt(128|t&63):Gt(224|t>>>12&15)+Gt(128|t>>>6&63)+Gt(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return Gt(240|t>>>18&7)+Gt(128|t>>>12&63)+Gt(128|t>>>6&63)+Gt(128|t&63)}},lpe,zq=(e)=>e.replace(lpe,cpe),Tq,ll=(e,t=!1)=>t?Oq(Tq(e)):Tq(e),$q=(e)=>ll(e,!0),upe,dpe=(e)=>{switch(e.length){case 4:var t=(7&e.charCodeAt(0))<<18|(63&e.charCodeAt(1))<<12|(63&e.charCodeAt(2))<<6|63&e.charCodeAt(3),r=t-65536;return Gt((r>>>10)+55296)+Gt((r&1023)+56320);case 3:return Gt((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return Gt((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},Nq=(e)=>e.replace(upe,dpe),Dq=(e)=>{if(e=e.replace(/\s+/g,""),!ape.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,o,n=[];for(let i=0;i<e.length;)if(t=Ey[e.charAt(i++)]<<18|Ey[e.charAt(i++)]<<12|(r=Ey[e.charAt(i++)])<<6|(o=Ey[e.charAt(i++)]),r===64)n.push(Gt(t>>16&255));else if(o===64)n.push(Gt(t>>16&255,t>>8&255));else n.push(Gt(t>>16&255,t>>8&255,t&255));return n.join("")},FR,Lq,Bq=(e)=>Lq(jq(e)),ppe,jq=(e)=>Cq(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),MR=(e)=>ppe(jq(e)),fpe=(e)=>{if(typeof e!=="string")return!1;let t=e.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},Zq=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),Uq=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,Zq(r));e("fromBase64",function(){return MR(this)}),e("toBase64",function(t){return ll(this,t)}),e("toBase64URI",function(){return ll(this,!0)}),e("toBase64URL",function(){return ll(this,!0)}),e("toUint8Array",function(){return Bq(this)})},Mq=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,Zq(r));e("toBase64",function(t){return Iy(this,t)}),e("toBase64URI",function(){return Iy(this,!0)}),e("toBase64URL",function(){return Iy(this,!0)})},mpe=()=>{Uq(),Mq()},dl;var ky=v(()=>{ul=typeof Buffer==="function",kq=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,Aq=typeof TextEncoder==="function"?new TextEncoder:void 0,yp=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),Ey=((e)=>{let t={};return e.forEach((r,o)=>t[r]=o),t})(yp),ape=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,Gt=String.fromCharCode.bind(String),Rq=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),qR=typeof btoa==="function"?(e)=>btoa(e):ul?(e)=>Buffer.from(e,"binary").toString("base64"):Pq,UR=ul?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let o=0,n=e.length;o<n;o+=4096)r.push(Gt.apply(null,e.subarray(o,o+4096)));return qR(r.join(""))},lpe=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Tq=ul?(e)=>Buffer.from(e,"utf8").toString("base64"):Aq?(e)=>UR(Aq.encode(e)):(e)=>qR(zq(e)),upe=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,FR=typeof atob==="function"?(e)=>atob(Cq(e)):ul?(e)=>Buffer.from(e,"base64").toString("binary"):Dq,Lq=ul?(e)=>Rq(Buffer.from(e,"base64")):(e)=>Rq(FR(e).split("").map((t)=>t.charCodeAt(0))),ppe=ul?(e)=>Buffer.from(e,"base64").toString("utf8"):kq?(e)=>kq.decode(Lq(e)):(e)=>Nq(FR(e)),dl={version:"3.8.0",VERSION:"3.8.0",atob:FR,atobPolyfill:Dq,btoa:qR,btoaPolyfill:Pq,fromBase64:MR,toBase64:ll,encode:ll,encodeURI:$q,encodeURL:$q,utob:zq,btou:Nq,decode:MR,isValid:fpe,fromUint8Array:Iy,toUint8Array:Bq,extendString:Uq,extendUint8Array:Mq,extendBuiltins:mpe}});function Ki(e){if(e==="write")return"BEGIN IMMEDIATE";else if(e==="read")return"BEGIN TRANSACTION READONLY";else if(e==="deferred")return"BEGIN DEFERRED";else throw RangeError('Unknown transaction mode, supported values are "write", "read" and "deferred"')}class pl{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,o,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=o,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(hpe),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function hpe(e){return Array.prototype.map.call(e,gpe)}function gpe(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return dl.fromUint8Array(new Uint8Array(e));else return e}var Xn="https://github.com/libsql/libsql-client-ts#supported-urls";var fl=v(()=>{ky()});function Fq(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function bp(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:o,tls:n,intMode:i,concurrency:s}=e;s=Math.max(0,s||20),i??="number";let a=[];if(r===qq)r="file::memory:";let l=Iq(r),u=l.scheme.toLowerCase(),d=u==="file"&&l.path===qq&&l.authority===void 0,p;if(d)p={cache:{values:["shared","private"],update:(y,S)=>a.push(`${y}=${S}`)}};else p={tls:{values:["0","1"],update:(y,S)=>n=S==="1"},authToken:{update:(y,S)=>o=S}};for(let{key:y,value:S}of l.query?.pairs??[]){if(!Object.hasOwn(p,y))throw new Ce(`Unsupported URL query parameter ${JSON.stringify(y)}`,"URL_PARAM_NOT_SUPPORTED");let x=p[y];if(x.values!==void 0&&!x.values.includes(S))throw new Ce(`Unknown value for the "${y}" query argument: ${JSON.stringify(S)}. Supported values are: [${x.values.map((_)=>'"'+_+'"').join(", ")}]`,"URL_INVALID");if(x.update!==void 0)x?.update(y,S)}let m=a.length===0?"":`?${a.join("&")}`,h=l.path+m,b;if(u==="libsql")if(n===!1){if(l.authority?.port===void 0)throw new Ce('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");b=t?"http":"ws"}else b=t?"https":"wss";else b=u;if(b==="http"||b==="ws")n??=!1;else n??=!0;if(b!=="http"&&b!=="ws"&&b!=="https"&&b!=="wss"&&b!=="file")throw new Ce(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(l.scheme+":")}. For more information, please read ${Xn}`,"URL_SCHEME_NOT_SUPPORTED");if(i!=="number"&&i!=="bigint"&&i!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(i)}`);if(l.fragment!==void 0)throw new Ce(`URL fragments are not supported: ${JSON.stringify("#"+l.fragment)}`,"URL_INVALID");if(d)return{scheme:"file",tls:!1,path:h,intMode:i,concurrency:s,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout,authToken:void 0,encryptionKey:void 0,remoteEncryptionKey:void 0,authority:void 0};return{scheme:b,tls:n,authority:l.authority,path:h,authToken:o,intMode:i,concurrency:s,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout}}var qq=":memory:";var Sp=v(()=>{wn();_y();fl()});var Kq=ge(function(rn){var ype=rn&&rn.__createBinding||(Object.create?function(e,t,r,o){if(o===void 0)o=r;var n=Object.getOwnPropertyDescriptor(t,r);if(!n||("get"in n?!t.__esModule:n.writable||n.configurable))n={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,o,n)}:function(e,t,r,o){if(o===void 0)o=r;e[o]=t[r]}),bpe=rn&&rn.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),Jq=rn&&rn.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null){for(var r in e)if(r!=="default"&&Object.prototype.hasOwnProperty.call(e,r))ype(t,e,r)}return bpe(t,e),t};Object.defineProperty(rn,"__esModule",{value:!0});rn.load=rn.currentTarget=void 0;var Spe=Jq(Fr("path")),vpe=Jq(Fr("fs"));function wpe(){let e=null;switch(process.platform){case"android":switch(process.arch){case"arm":return"android-arm-eabi";case"arm64":return"android-arm64"}e="Android";break;case"win32":switch(process.arch){case"x64":return"win32-x64-msvc";case"arm64":return"win32-arm64-msvc";case"ia32":return"win32-ia32-msvc"}e="Windows";break;case"darwin":switch(process.arch){case"x64":return"darwin-x64";case"arm64":return"darwin-arm64"}e="macOS";break;case"linux":switch(process.arch){case"x64":case"arm64":return xpe()?`linux-${process.arch}-gnu`:`linux-${process.arch}-musl`;case"arm":return"linux-arm-gnueabihf"}e="Linux";break;case"freebsd":if(process.arch==="x64")return"freebsd-x64";e="FreeBSD";break}if(e)throw Error(`Neon: unsupported ${e} architecture: ${process.arch}`);throw Error(`Neon: unsupported system: ${process.platform}`)}rn.currentTarget=wpe;function xpe(){let e=process.report?.getReport();if(typeof e!=="object"||!e||!("header"in e))return!1;let t=e.header;return typeof t==="object"&&!!t&&"glibcVersionRuntime"in t}function _pe(e){let t=Spe.join(e,"index.node");return vpe.existsSync(t)?Fr(t):null}rn.load=_pe});var Wq=ge(function(Q2e,Vq){var Hq=()=>process.platform==="linux",JR=null,Epe=()=>{if(!JR)JR=Hq()&&process.report?process.report.getReport():{};return JR};Vq.exports={isLinux:Hq,getReport:Epe}});var Yq=ge(function(Y2e,Qq){var Gq=Fr("fs"),Ipe=(e)=>Gq.readFileSync(e,"utf-8"),kpe=(e)=>new Promise((t,r)=>{Gq.readFile(e,"utf-8",(o,n)=>{if(o)r(o);else t(n)})});Qq.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:Ipe,readFile:kpe}});var h4=ge(function(X2e,m4){var e4=Fr("child_process"),{isLinux:ml,getReport:t4}=Wq(),{LDD_PATH:Ay,readFile:r4,readFileSync:n4}=Yq(),eo,to,Hi="",o4=()=>{if(!Hi)return new Promise((e)=>{e4.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{Hi=t?" ":r,e(Hi)})});return Hi},i4=()=>{if(!Hi)try{Hi=e4.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){Hi=" "}return Hi},Bo="glibc",s4=/GLIBC\s(\d+\.\d+)/,la="musl",Ape=Bo.toUpperCase(),Rpe=la.toLowerCase(),Tpe=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),a4=()=>{let e=t4();if(e.header&&e.header.glibcVersionRuntime)return Bo;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(Tpe))return la}return null},c4=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(Bo))return Bo;if(r&&r.includes(la))return la;return null},l4=(e)=>{if(e.includes(Rpe))return la;if(e.includes(Ape))return Bo;return null},$pe=async()=>{if(eo!==void 0)return eo;eo=null;try{let e=await r4(Ay);eo=l4(e)}catch(e){}return eo},Ope=()=>{if(eo!==void 0)return eo;eo=null;try{let e=n4(Ay);eo=l4(e)}catch(e){}return eo},u4=async()=>{let e=null;if(ml()){if(e=await $pe(),!e)e=a4();if(!e){let t=await o4();e=c4(t)}}return e},d4=()=>{let e=null;if(ml()){if(e=Ope(),!e)e=a4();if(!e){let t=i4();e=c4(t)}}return e},Cpe=async()=>ml()&&await u4()!==Bo,Ppe=()=>ml()&&d4()!==Bo,zpe=async()=>{if(to!==void 0)return to;to=null;try{let t=(await r4(Ay)).match(s4);if(t)to=t[1]}catch(e){}return to},Npe=()=>{if(to!==void 0)return to;to=null;try{let t=n4(Ay).match(s4);if(t)to=t[1]}catch(e){}return to},p4=()=>{let e=t4();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},Xq=(e)=>e.trim().split(/\s+/)[1],f4=(e)=>{let[t,r,o]=e.split(/[\r\n]+/);if(t&&t.includes(Bo))return Xq(t);if(r&&o&&r.includes(la))return Xq(o);return null},Dpe=async()=>{let e=null;if(ml()){if(e=await zpe(),!e)e=p4();if(!e){let t=await o4();e=f4(t)}}return e},Lpe=()=>{let e=null;if(ml()){if(e=Npe(),!e)e=p4();if(!e){let t=i4();e=f4(t)}}return e};m4.exports={GLIBC:Bo,MUSL:la,family:u4,familySync:d4,isNonGlibcLinux:Cpe,isNonGlibcLinuxSync:Ppe,version:Dpe,versionSync:Lpe}});var y4=ge(function(eDe,g4){var Bpe={ALLOW:0,DENY:1};g4.exports=Bpe});var S4=ge(function(tDe,b4){var KR={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function ua(e,t,r){if(new.target!==ua)return new ua(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),KR.value=""+e,Object.defineProperty(this,"message",KR),Error.captureStackTrace(this,ua),this.code=t,this.rawCode=r}Object.setPrototypeOf(ua,Error);Object.setPrototypeOf(ua.prototype,Error.prototype);Object.defineProperty(ua.prototype,"name",KR);b4.exports=ua});var A4=ge(function(rDe,Ry){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:jpe,currentTarget:Zpe}=Kq(),{familySync:v4,GLIBC:Upe,MUSL:Mpe}=h4();function qpe(){if(process.env.LIBSQL_JS_DEV)return jpe(__dirname);let e=Zpe();if(v4()==Upe)switch(e){case"linux-x64-musl":e="linux-x64-gnu";break;case"linux-arm64-musl":e="linux-arm64-gnu";break}if(e==="linux-arm-gnueabihf"&&v4()==Mpe)e="linux-arm-musleabihf";return Fr(`@libsql/${e}`)}var{databaseOpen:Fpe,databaseOpenWithSync:Jpe,databaseInTransaction:Kpe,databaseInterrupt:Hpe,databaseClose:Vpe,databaseSyncSync:Wpe,databaseSyncUntilSync:Gpe,databaseExecSync:Qpe,databasePrepareSync:Ype,databaseDefaultSafeIntegers:Xpe,databaseAuthorizer:efe,databaseLoadExtension:tfe,databaseMaxWriteReplicationIndex:rfe,statementRaw:nfe,statementIsReader:ofe,statementGet:w4,statementRun:x4,statementInterrupt:ife,statementRowsSync:_4,statementColumns:sfe,statementSafeIntegers:afe,rowsNext:cfe}=qpe(),lfe=y4(),E4=S4();function hl(e){if(e.libsqlError)return new E4(e.message,e.code,e.rawCode);return e}class I4{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var o="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),o=t.syncAuth;else if(t.authToken)o=t.authToken;let i=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,l=t?.offline??!1,u=t?.remoteEncryptionKey??"";this.db=Jpe(e,t.syncUrl,o,r,i,s,a,l,u)}else{let i=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,l=t?.remoteEncryptionKey??"";this.db=Fpe(e,i,r,s,a,l)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let n=this.db;Object.defineProperties(this,{inTransaction:{get(){return Kpe(n)}}})}sync(){return Wpe.call(this.db)}syncUntil(e){return Gpe.call(this.db,e)}prepare(e){try{let t=Ype.call(this.db,e);return new k4(t)}catch(t){throw hl(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...i)=>{t.exec("BEGIN "+n);try{let s=e(...i);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},o={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(o.default.value,o),Object.defineProperties(o.deferred.value,o),Object.defineProperties(o.immediate.value,o),Object.defineProperties(o.exclusive.value,o),o.default.value}pragma(e,t){if(t==null)t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");let r=t.simple,o=this.prepare(`PRAGMA ${e}`,this,!0);return r?o.pluck().get():o.all()}backup(e,t){throw Error("not implemented")}serialize(e){throw Error("not implemented")}function(e,t,r){if(t==null)t={};if(typeof t==="function")r=t,t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof r!=="function")throw TypeError("Expected last argument to be a function");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}aggregate(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object"||t===null)throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}table(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(!e)throw TypeError("Virtual table module name cannot be an empty string");throw Error("not implemented")}authorizer(e){efe.call(this.db,e)}loadExtension(...e){tfe.call(this.db,...e)}maxWriteReplicationIndex(){return rfe.call(this.db)}exec(e){try{Qpe.call(this.db,e)}catch(t){throw hl(t)}}interrupt(){Hpe.call(this.db)}close(){Vpe.call(this.db),this.open=!1}defaultSafeIntegers(e){return Xpe.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class k4{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return nfe.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return ofe.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return x4.call(this.stmt,e[0]);else return x4.call(this.stmt,e.flat())}catch(t){throw hl(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return w4.call(this.stmt,e[0]);else return w4.call(this.stmt,e.flat())}catch(t){throw hl(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=_4.call(this.stmt,e[0]);else t=_4.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)cfe.call(t,this.nextRows),this.nextRowIndex=0;let o=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!o)return{done:!0};return this.nextRowIndex++,{value:o,done:!1}}catch(o){throw hl(o)}},[Symbol.iterator](){return this}}}all(...e){try{let t=[];for(let r of this.iterate(...e))if(this.pluckMode)t.push(r[Object.keys(r)[0]]);else t.push(r);return t}catch(t){throw hl(t)}}interrupt(){ife.call(this.stmt)}columns(){return sfe.call(this.stmt)}safeIntegers(e){return afe.call(this.stmt,e??!0),this}}Ry.exports=I4;Ry.exports.Authorization=lfe;Ry.exports.SqliteError=E4});import{Buffer as T4}from"buffer";function $4(e){if(e.scheme!=="file")throw new Ce(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${Xn}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Ce(`Invalid host in file URL: ${JSON.stringify(t.host)}. A "file:" URL with an absolute path should start with one slash ("file:/absolute/path.db") or with three slashes ("file:///absolute/path.db"). For more information, please read ${Xn}`,"URL_INVALID");if(t.port!==void 0)throw new Ce("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Ce("File URL cannot have username and password","URL_INVALID")}let r=Fq(e);if(r&&e.syncUrl)throw new Ce(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let o=e.path;if(r)o=`${e.scheme}:${e.path}`;let n={authToken:e.authToken,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncPeriod:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,timeout:e.timeout},i=new vp.default(o,n);return zt(i,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new O4(o,n,i,e.intMode)}class O4{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,o){this.#e=e,this.#t=t,this.#r=r,this.#n=o,this.closed=!1,this.protocol="file"}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#o(),zt(this.#i(),r,this.#n)}async batch(e,t="deferred"){this.#o();let r=this.#i();try{zt(r,Ki(t),this.#n);let o=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new Wt("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let i=e[n],s=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;o.push(zt(r,s,this.#n))}catch(i){if(i instanceof Wt)throw i;if(i instanceof Ce)throw new Wt(i.message,n,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return zt(r,"COMMIT",this.#n),o}finally{if(r.inTransaction)zt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#o();let t=this.#i();try{zt(t,"PRAGMA foreign_keys=off",this.#n),zt(t,Ki("deferred"),this.#n);let r=[];for(let o=0;o<e.length;o++)try{if(!t.inTransaction)throw new Wt("The transaction has been rolled back",o,"TRANSACTION_CLOSED");r.push(zt(t,e[o],this.#n))}catch(n){if(n instanceof Wt)throw n;if(n instanceof Ce)throw new Wt(n.message,o,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return zt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)zt(t,"ROLLBACK",this.#n);zt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#i();return zt(t,Ki(e),this.#n),this.#r=null,new C4(t,this.#n)}async executeMultiple(e){this.#o();let t=this.#i();try{return P4(t,e)}finally{if(t.inTransaction)zt(t,"ROLLBACK",this.#n)}}async sync(){this.#o();let e=await this.#i().sync();return{frames_synced:e.frames_synced,frame_no:e.frame_no}}async reconnect(){try{if(!this.closed&&this.#r!==null)this.#r.close()}finally{this.#r=new vp.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#o(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED")}#i(){if(this.#r===null)this.#r=new vp.default(this.#e,this.#t);return this.#r}}class C4{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#r(),zt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let o=e[r],n=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;t.push(zt(this.#e,n,this.#t))}catch(o){if(o instanceof Wt)throw o;if(o instanceof Ce)throw new Wt(o.message,r,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return t}async executeMultiple(e){return this.#r(),P4(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),zt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),zt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)zt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Ce("The transaction is closed","TRANSACTION_CLOSED")}}function zt(e,t,r){let o,n;if(typeof t==="string")o=t,n=[];else if(o=t.sql,Array.isArray(t.args))n=t.args.map((i)=>R4(i,r));else{n={};for(let i in t.args){let s=i[0]==="@"||i[0]==="$"||i[0]===":"?i.substring(1):i;n[s]=R4(t.args[i],r)}}try{let i=e.prepare(o);i.safeIntegers(!0);let s=!0;try{i.raw(!0)}catch{s=!1}if(s){let a=Array.from(i.columns().map((m)=>m.name)),l=Array.from(i.columns().map((m)=>m.type??"")),u=i.all(n).map((m)=>ufe(m,a,r)),d=0,p=void 0;return new pl(a,l,u,0,void 0)}else{let a=i.run(n),l=a.changes,u=BigInt(a.lastInsertRowid);return new pl([],[],[],l,u)}}catch(i){throw z4(i)}}function ufe(e,t,r){let o={};Object.defineProperty(o,"length",{value:e.length});for(let n=0;n<e.length;++n){let i=dfe(e[n],r);Object.defineProperty(o,n,{value:i});let s=t[n];if(!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function dfe(e,t){if(typeof e==="bigint")if(t==="number"){if(e<pfe||e>ffe)throw RangeError("Received integer which cannot be safely represented as a JavaScript number");return Number(e)}else if(t==="bigint")return e;else if(t==="string")return""+e;else throw Error("Invalid value for IntMode");else if(e instanceof T4)return e.buffer;return e}function R4(e,t){if(typeof e==="number"){if(!Number.isFinite(e))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return e}else if(typeof e==="bigint"){if(e<mfe||e>hfe)throw RangeError("bigint is too large to be represented as a 64-bit integer and passed as argument");return e}else if(typeof e==="boolean")switch(t){case"bigint":return e?1n:0n;case"string":return e?"1":"0";default:return e?1:0}else if(e instanceof ArrayBuffer)return T4.from(e);else if(e instanceof Date)return e.valueOf();else if(e===void 0)throw TypeError("undefined cannot be passed as argument to the database");else return e}function P4(e,t){try{e.exec(t)}catch(r){throw z4(r)}}function z4(e){if(e instanceof vp.default.SqliteError){let t=e.code,r=gfe(e.rawCode);return new Ce(e.message,r,t,e.rawCode,e)}return e}function gfe(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return yfe[t]??`SQLITE_UNKNOWN_${t.toString()}`}var vp,pfe,ffe=9007199254740991n,mfe,hfe=9223372036854775807n,yfe;var N4=v(()=>{wn();Sp();fl();vp=Jl(A4(),1);wn();pfe=-9007199254740991n;mfe=-9223372036854775808n;yfe={1:"SQLITE_ERROR",2:"SQLITE_INTERNAL",3:"SQLITE_PERM",4:"SQLITE_ABORT",5:"SQLITE_BUSY",6:"SQLITE_LOCKED",7:"SQLITE_NOMEM",8:"SQLITE_READONLY",9:"SQLITE_INTERRUPT",10:"SQLITE_IOERR",11:"SQLITE_CORRUPT",12:"SQLITE_NOTFOUND",13:"SQLITE_FULL",14:"SQLITE_CANTOPEN",15:"SQLITE_PROTOCOL",16:"SQLITE_EMPTY",17:"SQLITE_SCHEMA",18:"SQLITE_TOOBIG",19:"SQLITE_CONSTRAINT",20:"SQLITE_MISMATCH",21:"SQLITE_MISUSE",22:"SQLITE_NOLFS",23:"SQLITE_AUTH",24:"SQLITE_FORMAT",25:"SQLITE_RANGE",26:"SQLITE_NOTADB",27:"SQLITE_NOTICE",28:"SQLITE_WARNING"}});var Vi;var HR=v(()=>{if(typeof WebSocket<"u")Vi=WebSocket;else if(typeof global<"u")Vi=global.WebSocket;else if(typeof window<"u")Vi=window.WebSocket;else if(typeof self<"u")Vi=self.WebSocket});class gl{constructor(){this.intMode="number"}intMode}var Ge,Pe,wp,xt,xp,yl,da,xn,or,ro;var _t=v(()=>{Ge=class Ge extends Error{constructor(e){super(e);this.name="ClientError"}};Pe=class Pe extends Ge{constructor(e){super(e);this.name="ProtoError"}};wp=class wp extends Ge{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};xt=class xt extends Ge{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};xp=class xp extends Ge{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};yl=class yl extends Ge{constructor(e){super(e);this.name="WebSocketError"}};da=class da extends Ge{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};xn=class xn extends Ge{constructor(e){super(e);this.name="ProtocolVersionError"}};or=class or extends Ge{constructor(e){super(e);this.name="InternalError"}};ro=class ro extends Ge{constructor(e){super(e);this.name="MisuseError"}}});function Tr(e){if(typeof e==="string")return e;throw bl(e,"string")}function Ur(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw bl(e,"string or null")}function jo(e){if(typeof e==="number")return e;throw bl(e,"number")}function Wi(e){if(typeof e==="boolean")return e;throw bl(e,"boolean")}function _p(e){if(Array.isArray(e))return e;throw bl(e,"array")}function kt(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw bl(e,"object")}function _n(e,t){return _p(e).map((r)=>t(kt(r)))}function bl(e,t){if(e===void 0)return new Pe(`Expected ${t}, but the property was missing`);let r=typeof e;if(e===null)r="null";else if(Array.isArray(e))r="array";return new Pe(`Expected ${t}, received ${r}`)}function pa(e,t){return t(kt(e))}var Sl=v(()=>{_t()});class D4{#e;#t;constructor(e){this.#e=e,this.#t=!1}begin(){this.#e.push("{"),this.#t=!0}end(){this.#e.push("}"),this.#t=!1}#r(e){if(this.#t)this.#e.push('"'),this.#t=!1;else this.#e.push(',"');this.#e.push(e),this.#e.push('":')}string(e,t){this.#r(e),this.#e.push(JSON.stringify(t))}stringRaw(e,t){this.#r(e),this.#e.push('"'),this.#e.push(t),this.#e.push('"')}number(e,t){this.#r(e),this.#e.push(""+t)}boolean(e,t){this.#r(e),this.#e.push(t?"true":"false")}object(e,t,r){this.#r(e),this.begin(),r(this,t),this.end()}arrayObjects(e,t,r){this.#r(e),this.#e.push("[");for(let o=0;o<t.length;++o){if(o!==0)this.#e.push(",");this.begin(),r(this,t[o]),this.end()}this.#e.push("]")}}function Ep(e,t){let r=[],o=new D4(r);return o.begin(),t(o,e),o.end(),r.join("")}var fa=0,Ip=1,kp=2,L4=5;class B4{#e;#t;#r;constructor(e){this.#e=e,this.#t=new DataView(e.buffer,e.byteOffset,e.byteLength),this.#r=0}varint(){let e=0;for(let t=0;;t+=7){let r=this.#e[this.#r++];if(e|=(r&127)<<t,!(r&128))break}return e}varintBig(){let e=0n;for(let t=0n;;t+=7n){let r=this.#e[this.#r++];if(e|=BigInt(r&127)<<t,!(r&128))break}return e}bytes(e){let t=new Uint8Array(this.#e.buffer,this.#e.byteOffset+this.#r,e);return this.#r+=e,t}double(){let e=this.#t.getFloat64(this.#r,!0);return this.#r+=8,e}skipVarint(){for(;;)if(!(this.#e[this.#r++]&128))break}skip(e){this.#r+=e}eof(){return this.#r>=this.#e.byteLength}}class j4{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new Pe(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(kp);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return Gi(this.bytes(),e)}int32(){return this.#r(fa),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r(fa),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(Ip),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===fa)this.#e.skipVarint();else if(this.#t===Ip)this.#e.skip(8);else if(this.#t===kp){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===L4)this.#e.skip(4);else throw new Pe(`Unexpected wire type ${this.#t}`);this.#t=-1}}function Gi(e,t){let r=new B4(e),o=new j4(r),n=t.default();while(!r.eof()){let i=r.varint(),s=i>>3,a=i&7;o.setup(a);let l=t[s];if(l!==void 0){let u=l(o,n);if(u!==void 0)n=u}o.maybeSkip()}return n}var VR=v(()=>{_t()});class WR{#e;#t;#r;#n;constructor(){this.#e=new ArrayBuffer(256),this.#t=new Uint8Array(this.#e),this.#r=new DataView(this.#e),this.#n=0}#o(e){if(this.#n+e<=this.#e.byteLength)return;let t=this.#e.byteLength;while(t<this.#n+e)t*=2;let r=new ArrayBuffer(t),o=new Uint8Array(r),n=new DataView(r);o.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=o,this.#r=n}#i(e){this.#o(5),e=0|e;do{let t=e&127;e>>>=7,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#a(e){this.#o(10),e=e&0xffffffffffffffffn;do{let t=Number(e&0x7fn);e>>=7n,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#s(e,t){this.#i(e<<3|t)}bytes(e,t){this.#s(e,kp),this.#i(t.byteLength),this.#o(t.byteLength),this.#t.set(t,this.#n),this.#n+=t.byteLength}string(e,t){this.bytes(e,new TextEncoder().encode(t))}message(e,t,r){let o=new WR;r(o,t),this.bytes(e,o.data())}int32(e,t){this.#s(e,fa),this.#i(t)}uint32(e,t){this.int32(e,t)}bool(e,t){this.int32(e,t?1:0)}sint64(e,t){this.#s(e,fa),this.#a(t<<1n^t>>63n)}double(e,t){this.#s(e,Ip),this.#o(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function Ap(e,t){let r=new WR;return t(r,e),r.data()}var Z4=()=>{};var GR=v(()=>{Sl();VR();Z4()});class Qi{#e;#t;constructor(){this.#e=new Set,this.#t=new Set}alloc(){for(let t of this.#t){if(this.#t.delete(t),this.#e.add(t),!this.#e.has(this.#e.size-1))this.#t.add(this.#e.size-1);return t}let e=this.#e.size;return this.#e.add(e),e}free(e){if(!this.#e.delete(e))throw new or("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var QR=v(()=>{_t()});function Ke(e,t){throw new or(t)}var nn=v(()=>{_t()});function vl(e){if(e===null)return null;else if(typeof e==="string")return e;else if(typeof e==="number"){if(!Number.isFinite(e))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return e}else if(typeof e==="bigint"){if(e<Sfe||e>vfe)throw RangeError("This bigint value is too large to be represented as a 64-bit integer and passed as argument");return e}else if(typeof e==="boolean")return e?1n:0n;else if(e instanceof ArrayBuffer)return new Uint8Array(e);else if(e instanceof Uint8Array)return e;else if(e instanceof Date)return+e.valueOf();else if(typeof e==="object")return""+e.toString();else throw TypeError("Unsupported type of value")}function YR(e,t){if(e===null)return null;else if(typeof e==="number")return e;else if(typeof e==="string")return e;else if(typeof e==="bigint")if(t==="number"){let r=Number(e);if(!Number.isSafeInteger(r))throw RangeError("Received integer which is too large to be safely represented as a JavaScript number");return r}else if(t==="bigint")return e;else if(t==="string")return""+e;else throw new ro("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new Pe("Received unrecognized type of Value");else throw Ke(e,"Impossible type of Value")}var Sfe,vfe=9223372036854775807n;var XR=v(()=>{_t();nn();Sfe=-9223372036854775808n});function ma(e){return{affectedRowCount:e.affectedRowCount,lastInsertRowid:e.lastInsertRowid,columnNames:e.cols.map((t)=>t.name),columnDecltypes:e.cols.map((t)=>t.decltype)}}function $y(e,t){let r=ma(e),o=e.rows.map((n)=>U4(r.columnNames,n,t));return{...r,rows:o}}function Oy(e,t){let r=ma(e),o;if(e.rows.length>0)o=U4(r.columnNames,e.rows[0],t);return{...r,row:o}}function Cy(e,t){let r=ma(e),o;if(e.rows.length>0&&r.columnNames.length>0)o=YR(e.rows[0][0],t);return{...r,value:o}}function U4(e,t,r){let o={};Object.defineProperty(o,"length",{value:t.length});for(let n=0;n<t.length;++n){let i=YR(t[n],r);Object.defineProperty(o,n,{value:i});let s=e[n];if(s!==void 0&&!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function Zo(e){return new wp(e.message,e)}var Rp=v(()=>{_t();XR()});class ha{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new ro("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new xt("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new Ge("SQL text was manually closed"))}_setClosed(e){if(this.#r===void 0)this.#r=e,this.#e._closeSql(this.#t)}get closed(){return this.#r!==void 0}}function Tp(e,t){if(t instanceof ha)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var wl=v(()=>{_t()});class Yi{#e;#t;constructor(){this.#e=[],this.#t=[]}get length(){return this.#e.length+this.#t.length}push(e){this.#e.push(e)}shift(){if(this.#t.length===0&&this.#e.length>0)this.#t=this.#e.reverse(),this.#e=[];return this.#t.pop()}first(){return this.#t.length!==0?this.#t[this.#t.length-1]:this.#e[0]}}class $p{sql;_args;_namedArgs;constructor(e){this.sql=e,this._args=[],this._namedArgs=new Map}bindIndexes(e){this._args.length=0;for(let t of e)this._args.push(vl(t));return this}bindIndex(e,t){if(e!==(e|0)||e<=0)throw RangeError("Index of a positional argument must be positive integer");while(this._args.length<e)this._args.push(null);return this._args[e-1]=vl(t),this}bindName(e,t){return this._namedArgs.set(e,vl(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function Py(e,t,r){let o,n=[],i=[];if(t instanceof $p){o=t.sql,n=t._args;for(let[l,u]of t._namedArgs.entries())i.push({name:l,value:u})}else if(Array.isArray(t))if(o=t[0],Array.isArray(t[1]))n=t[1].map((l)=>vl(l));else i=Object.entries(t[1]).map(([l,u])=>({name:l,value:vl(u)}));else o=t;let{sql:s,sqlId:a}=Tp(e,o);return{sql:s,sqlId:a,args:n,namedArgs:i,wantRows:r}}var zy=v(()=>{wl();XR()});class Ny{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new eT(this)}execute(){if(this.#t)throw new ro("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return xfe(this._stream,this._steps,e);else return wfe(this._stream,this._steps,e)}}function wfe(e,t,r){return e._batch(r).then((o)=>{for(let n=0;n<t.length;++n){let i=o.stepResults.get(n),s=o.stepErrors.get(n);t[n].callback(i,s)}})}async function xfe(e,t,r){let o=await e._openCursor(r);try{let n=0,i=void 0,s=[];for(;;){let a=await o.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new Pe("Server produced StepBeginEntry for unexpected step");else if(i!==void 0)throw new Pe("Server produced StepBeginEntry before terminating previous step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0);n=a.step+1,i=a,s=[]}else if(a.type==="step_end"){if(i===void 0)throw new Pe("Server produced StepEndEntry but no step is active");let l={cols:i.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[i.step].callback(l,void 0),i=void 0,s=[]}else if(a.type==="step_error"){if(i===void 0){if(a.step>=t.length)throw new Pe("Server produced StepErrorEntry for unexpected step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0)}else{if(a.step!==i.step)throw new Pe("Server produced StepErrorEntry for unexpected step");i=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(i===void 0)throw new Pe("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw Zo(a.error);else if(a.type==="none")throw new Pe("Server produced unrecognized CursorEntry");else throw Ke(a,"Impossible CursorEntry")}if(i!==void 0)throw new Pe("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{o.close()}}class eT{_batch;#e;_index;constructor(e){this._batch=e,this.#e=[],this._index=void 0}condition(e){return this.#e.push(e._proto),this}query(e){return this.#t(e,!0,$y)}queryRow(e){return this.#t(e,!0,Oy)}queryValue(e){return this.#t(e,!0,Cy)}run(e){return this.#t(e,!1,ma)}#t(e,t,r){if(this._index!==void 0)throw new ro("This BatchStep has already been added to the batch");let o=Py(this._batch._stream._sqlOwner(),e,t),n;if(this.#e.length===0)n=void 0;else if(this.#e.length===1)n=this.#e[0];else n={type:"and",conds:this.#e.slice()};let i={stmt:o,condition:n};return new Promise((s,a)=>{let l=(u,d)=>{if(u!==void 0&&d!==void 0)a(new Pe("Server returned both result and error"));else if(d!==void 0)a(Zo(d));else if(u!==void 0)s(r(u,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:i,callback:l})})}}class ut{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new ut(e._batch,{type:"ok",step:M4(e)})}static error(e){return new ut(e._batch,{type:"error",step:M4(e)})}static not(e){return new ut(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)q4(e,r);return new ut(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)q4(e,r);return new ut(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new ut(e,{type:"is_autocommit"})}}function M4(e){if(e._index===void 0)throw new ro("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function q4(e,t){if(t._batch!==e)throw new ro("Cannot mix BatchCond objects for different Batch objects")}var tT=v(()=>{_t();Rp();zy();nn()});function F4(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class xl{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,$y)}queryRow(e){return this.#e(e,!0,Oy)}queryValue(e){return this.#e(e,!0,Cy)}run(e){return this.#e(e,!1,ma)}#e(e,t,r){let o=Py(this._sqlOwner(),e,t);return this._execute(o).then((n)=>r(n,this.intMode))}batch(e=!1){return new Ny(this,e)}describe(e){let t=Tp(this._sqlOwner(),e);return this._describe(t).then(F4)}sequence(e){let t=Tp(this._sqlOwner(),e);return this._sequence(t)}intMode}var Dy=v(()=>{tT();Rp();wl();zy()});class Op{}var _fe=1000,Efe=10,rT;var J4=v(()=>{_t();rT=class rT extends Op{#e;#t;#r;#n;#o;#i;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new Yi,this.#o=new Yi,this.#i=void 0,this.#a=!1}async next(){for(;;){if(this.#i!==void 0)throw new xt("Cursor is closed",this.#i);while(!this.#a&&this.#o.length<Efe)this.#o.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#o.shift().then((t)=>{if(t===void 0)return;for(let r of t.entries)this.#n.push(r);this.#a||=t.done})}}#s(){return this.#t._sendCursorRequest(this,{type:"fetch_cursor",cursorId:this.#r,maxCount:_fe}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#i!==void 0)return;this.#i=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new Ge("Cursor was manually closed"))}get closed(){return this.#i!==void 0}}});var Cp;var nT=v(()=>{_t();Dy();J4();Cp=class Cp extends xl{#e;#t;#r;#n;#o;#i;static open(e){let t=e._streamIdAlloc.alloc(),r=new Cp(e,t),o=()=>{return},n=(s)=>r.#l(s),i={type:"open_stream",streamId:t};return e._sendRequest(i,{responseCallback:o,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new Yi,this.#n=void 0,this.#o=!1,this.#i=void 0}client(){return this.#e}_sqlOwner(){return this.#e}_execute(e){return this.#a({type:"execute",streamId:this.#t,stmt:e}).then((t)=>t.result)}_batch(e){return this.#a({type:"batch",streamId:this.#t,batch:e}).then((t)=>t.result)}_describe(e){return this.#e._ensureVersion(2,"describe()"),this.#a({type:"describe",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#e._ensureVersion(2,"sequence()"),this.#a({type:"sequence",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#a({type:"get_autocommit",streamId:this.#t}).then((e)=>e.isAutocommit)}#a(e){return new Promise((t,r)=>{this.#s({type:"request",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return this.#e._ensureVersion(3,"cursor"),new Promise((t,r)=>{this.#s({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_sendCursorRequest(e,t){if(e!==this.#n)throw new or("Cursor not associated with the stream attempted to execute a request");return new Promise((r,o)=>{if(this.#i!==void 0)o(new xt("Stream is closed",this.#i));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})})}_cursorClosed(e){if(e!==this.#n)throw new or("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#i!==void 0)e.errorCallback(new xt("Stream is closed",this.#i));else if(this.#o)e.errorCallback(new xt("Stream is closing",void 0));else this.#r.push(e),this.#c()}#c(){for(;;){let e=this.#r.first();if(e===void 0&&this.#n===void 0&&this.#o){this.#l(new Ge("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:o}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let o=this.#e._cursorIdAlloc.alloc(),n=new rT(this.#e,this,o),i={type:"open_cursor",streamId:this.#t,cursorId:o,batch:t},s=()=>{return},a=(l)=>n._setClosed(l);this.#e._sendRequest(i,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#i!==void 0)return;if(this.#i=e,this.#n!==void 0)this.#n._setClosed(e);for(;;){let n=this.#r.shift();if(n!==void 0)n.errorCallback(e);else break}let t={type:"close_stream",streamId:this.#t},r=()=>this.#e._streamIdAlloc.free(this.#t),o=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}close(){this.#l(new Ge("Stream was manually closed"))}closeGracefully(){this.#o=!0,this.#c()}get closed(){return this.#i!==void 0||this.#o}}});function Pp(e,t){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId);e.arrayObjects("args",t.args,K4),e.arrayObjects("named_args",t.namedArgs,Ife),e.boolean("want_rows",t.wantRows)}function Ife(e,t){e.string("name",t.name),e.object("value",t.value,K4)}function _l(e,t){e.arrayObjects("steps",t.steps,kfe)}function kfe(e,t){if(t.condition!==void 0)e.object("condition",t.condition,oT);e.object("stmt",t.stmt,Pp)}function oT(e,t){if(e.stringRaw("type",t.type),t.type==="ok"||t.type==="error")e.number("step",t.step);else if(t.type==="not")e.object("cond",t.cond,oT);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,oT);else if(t.type==="is_autocommit");else throw Ke(t,"Impossible type of BatchCond")}function K4(e,t){if(t===null)e.stringRaw("type","null");else if(typeof t==="bigint")e.stringRaw("type","integer"),e.stringRaw("value",""+t);else if(typeof t==="number")e.stringRaw("type","float"),e.number("value",t);else if(typeof t==="string")e.stringRaw("type","text"),e.string("value",t);else if(t instanceof Uint8Array)e.stringRaw("type","blob"),e.stringRaw("base64",dl.fromUint8Array(t));else if(t===void 0);else throw Ke(t,"Impossible type of Value")}var iT=v(()=>{ky();nn()});function H4(e,t){if(e.stringRaw("type",t.type),t.type==="hello"){if(t.jwt!==void 0)e.string("jwt",t.jwt)}else if(t.type==="request")e.number("request_id",t.requestId),e.object("request",t.request,Afe);else throw Ke(t,"Impossible type of ClientMsg")}function Afe(e,t){if(e.stringRaw("type",t.type),t.type==="open_stream")e.number("stream_id",t.streamId);else if(t.type==="close_stream")e.number("stream_id",t.streamId);else if(t.type==="execute")e.number("stream_id",t.streamId),e.object("stmt",t.stmt,Pp);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,_l);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,_l);else if(t.type==="close_cursor")e.number("cursor_id",t.cursorId);else if(t.type==="fetch_cursor")e.number("cursor_id",t.cursorId),e.number("max_count",t.maxCount);else if(t.type==="sequence"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(e.number("stream_id",t.streamId),t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit")e.number("stream_id",t.streamId);else throw Ke(t,"Impossible type of Request")}var V4=v(()=>{iT();nn()});function zp(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId);for(let r of t.args)e.message(3,r,G4);for(let r of t.namedArgs)e.message(4,r,Rfe);e.bool(5,t.wantRows)}function Rfe(e,t){e.string(1,t.name),e.message(2,t.value,G4)}function El(e,t){for(let r of t.steps)e.message(1,r,Tfe)}function Tfe(e,t){if(t.condition!==void 0)e.message(1,t.condition,sT);e.message(2,t.stmt,zp)}function sT(e,t){if(t.type==="ok")e.uint32(1,t.step);else if(t.type==="error")e.uint32(2,t.step);else if(t.type==="not")e.message(3,t.cond,sT);else if(t.type==="and")e.message(4,t.conds,W4);else if(t.type==="or")e.message(5,t.conds,W4);else if(t.type==="is_autocommit")e.message(6,void 0,Q4);else throw Ke(t,"Impossible type of BatchCond")}function W4(e,t){for(let r of t)e.message(1,r,sT)}function G4(e,t){if(t===null)e.message(1,void 0,Q4);else if(typeof t==="bigint")e.sint64(2,t);else if(typeof t==="number")e.double(3,t);else if(typeof t==="string")e.string(4,t);else if(t instanceof Uint8Array)e.bytes(5,t);else if(t===void 0);else throw Ke(t,"Impossible type of Value")}function Q4(e,t){}var aT=v(()=>{nn()});function Y4(e,t){if(t.type==="hello")e.message(1,t,$fe);else if(t.type==="request")e.message(2,t,Ofe);else throw Ke(t,"Impossible type of ClientMsg")}function $fe(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function Ofe(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,Cfe);else if(r.type==="close_stream")e.message(3,r,Pfe);else if(r.type==="execute")e.message(4,r,zfe);else if(r.type==="batch")e.message(5,r,Nfe);else if(r.type==="open_cursor")e.message(6,r,Dfe);else if(r.type==="close_cursor")e.message(7,r,Lfe);else if(r.type==="fetch_cursor")e.message(8,r,Bfe);else if(r.type==="sequence")e.message(9,r,jfe);else if(r.type==="describe")e.message(10,r,Zfe);else if(r.type==="store_sql")e.message(11,r,Ufe);else if(r.type==="close_sql")e.message(12,r,Mfe);else if(r.type==="get_autocommit")e.message(13,r,qfe);else throw Ke(r,"Impossible type of Request")}function Cfe(e,t){e.int32(1,t.streamId)}function Pfe(e,t){e.int32(1,t.streamId)}function zfe(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,zp)}function Nfe(e,t){e.int32(1,t.streamId),e.message(2,t.batch,El)}function Dfe(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,El)}function Lfe(e,t){e.int32(1,t.cursorId)}function Bfe(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function jfe(e,t){if(e.int32(1,t.streamId),t.sql!==void 0)e.string(2,t.sql);if(t.sqlId!==void 0)e.int32(3,t.sqlId)}function Zfe(e,t){if(e.int32(1,t.streamId),t.sql!==void 0)e.string(2,t.sql);if(t.sqlId!==void 0)e.int32(3,t.sqlId)}function Ufe(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function Mfe(e,t){e.int32(1,t.sqlId)}function qfe(e,t){e.int32(1,t.streamId)}var X4=v(()=>{aT();nn()});function Xi(e){let t=Tr(e.message),r=Ur(e.code);return{message:t,code:r}}function Np(e){let t=_n(e.cols,eF),r=_p(e.rows).map((s)=>_n(s,tF)),o=jo(e.affected_row_count),n=Ur(e.last_insert_rowid),i=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:o,lastInsertRowid:i}}function eF(e){let t=Ur(e.name),r=Ur(e.decltype);return{name:t,decltype:r}}function Ly(e){let t=new Map;_p(e.step_results).forEach((o,n)=>{if(o!==null)t.set(n,Np(kt(o)))});let r=new Map;return _p(e.step_errors).forEach((o,n)=>{if(o!==null)r.set(n,Xi(kt(o)))}),{stepResults:t,stepErrors:r}}function By(e){let t=Tr(e.type);if(t==="step_begin"){let r=jo(e.step),o=_n(e.cols,eF);return{type:"step_begin",step:r,cols:o}}else if(t==="step_end"){let r=jo(e.affected_row_count),o=Ur(e.last_insert_rowid),n=o!==void 0?BigInt(o):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=jo(e.step),o=Xi(kt(e.error));return{type:"step_error",step:r,error:o}}else if(t==="row")return{type:"row",row:_n(e.row,tF)};else if(t==="error")return{type:"error",error:Xi(kt(e.error))};else throw new Pe("Unexpected type of CursorEntry")}function jy(e){let t=_n(e.params,Ffe),r=_n(e.cols,Jfe),o=Wi(e.is_explain),n=Wi(e.is_readonly);return{params:t,cols:r,isExplain:o,isReadonly:n}}function Ffe(e){return{name:Ur(e.name)}}function Jfe(e){let t=Tr(e.name),r=Ur(e.decltype);return{name:t,decltype:r}}function tF(e){let t=Tr(e.type);if(t==="null")return null;else if(t==="integer"){let r=Tr(e.value);return BigInt(r)}else if(t==="float")return jo(e.value);else if(t==="text")return Tr(e.value);else if(t==="blob")return dl.toUint8Array(Tr(e.base64));else throw new Pe("Unexpected type of Value")}var Zy=v(()=>{ky();_t();Sl()});function rF(e){let t=Tr(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:Xi(kt(e.error))};else if(t==="response_ok"){let r=jo(e.request_id),o=Kfe(kt(e.response));return{type:"response_ok",requestId:r,response:o}}else if(t==="response_error"){let r=jo(e.request_id),o=Xi(kt(e.error));return{type:"response_error",requestId:r,error:o}}else throw new Pe("Unexpected type of ServerMsg")}function Kfe(e){let t=Tr(e.type);if(t==="open_stream")return{type:"open_stream"};else if(t==="close_stream")return{type:"close_stream"};else if(t==="execute")return{type:"execute",result:Np(kt(e.result))};else if(t==="batch")return{type:"batch",result:Ly(kt(e.result))};else if(t==="open_cursor")return{type:"open_cursor"};else if(t==="close_cursor")return{type:"close_cursor"};else if(t==="fetch_cursor"){let r=_n(e.entries,By),o=Wi(e.done);return{type:"fetch_cursor",entries:r,done:o}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:jy(kt(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Wi(e.is_autocommit)};else throw new Pe("Unexpected type of Response")}var nF=v(()=>{_t();Sl();Zy()});var on,es,oF,iF,Il,Hfe,Vfe,Uy,Wfe,Gfe,Qfe,kl,Yfe,Xfe,eme;var My=v(()=>{on={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},es={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(oF))},2(e,t){t.rows.push(e.message(iF))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},oF={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},iF={default(){return[]},1(e,t){t.push(e.message(eme))}},Il={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,o]=e.message(Hfe);t.stepResults.set(r,o)},2(e,t){let[r,o]=e.message(Vfe);t.stepErrors.set(r,o)}},Hfe={default(){return[0,es.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(es)}},Vfe={default(){return[0,on.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(on)}},Uy={default(){return{type:"none"}},1(e){return e.message(Wfe)},2(e){return e.message(Gfe)},3(e){return e.message(Qfe)},4(e){return{type:"row",row:e.message(iF)}},5(e){return{type:"error",error:e.message(on)}}},Wfe={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(oF))}},Gfe={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},Qfe={default(){return{type:"step_error",step:0,error:on.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(on)}},kl={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(Yfe))},2(e,t){t.cols.push(e.message(Xfe))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},Yfe={default(){return{name:void 0}},1(e,t){t.name=e.string()}},Xfe={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},eme={default(){return},1(e){return null},2(e){return e.sint64()},3(e){return e.double()},4(e){return e.string()},5(e){return e.bytes()}}});var sF,tme,rme,nme,ome,ime,sme,ame,cme;var aF=v(()=>{My();sF={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(tme)},3(e){return e.message(nme)},4(e){return e.message(rme)}},tme={default(){return{type:"hello_error",error:on.default()}},1(e,t){t.error=e.message(on)}},rme={default(){return{type:"response_error",requestId:0,error:on.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(on)}},nme={default(){return{type:"response_ok",requestId:0,response:{type:"none"}}},1(e,t){t.requestId=e.int32()},2(e,t){t.response={type:"open_stream"}},3(e,t){t.response={type:"close_stream"}},4(e,t){t.response=e.message(ome)},5(e,t){t.response=e.message(ime)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(sme)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(ame)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(cme)}},ome={default(){return{type:"execute",result:es.default()}},1(e,t){t.result=e.message(es)}},ime={default(){return{type:"batch",result:Il.default()}},1(e,t){t.result=e.message(Il)}},sme={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(Uy))},2(e,t){t.done=e.bool()}},ame={default(){return{type:"describe",result:kl.default()}},1(e,t){t.result=e.message(kl)}},cme={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var cF,cT,qy;var Fy=v(()=>{GR();_t();QR();Rp();wl();nn();nT();V4();X4();nF();aF();cF=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),cT=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);qy=class qy extends gl{#e;#t;#r;#n;#o;#i;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#o=!1,this.#i=void 0,this.#a=!1,this.#s=new Map,this.#c=new Qi,this._streamIdAlloc=new Qi,this._cursorIdAlloc=new Qi,this.#l=new Qi,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#p()),this.#e.addEventListener("close",(r)=>this.#g(r)),this.#e.addEventListener("error",(r)=>this.#f(r)),this.#e.addEventListener("message",(r)=>this.#y(r)),this.#d({type:"hello",jwt:t})}#d(e){if(this.#n!==void 0)throw new or("Trying to send a message on a closed client");if(this.#r)this.#m(e);else{let t=()=>this.#m(e),r=()=>{return};this.#t.push({openCallback:t,errorCallback:r})}}#p(){let e=this.#e.protocol;if(e===void 0){this.#u(new Ge("The `WebSocket.protocol` property is undefined. This most likely means that the WebSocket implementation provided by the environment is broken. If you are using Miniflare 2, please update to Miniflare 3, which fixes this problem."));return}else if(e==="")this.#i={version:1,encoding:"json"};else if(this.#i=cT.get(e),this.#i===void 0){this.#u(new Pe(`Unrecognized WebSocket subprotocol: ${JSON.stringify(e)}`));return}for(let t of this.#t)t.openCallback();this.#t.length=0,this.#r=!0}#m(e){let t=this.#i.encoding;if(t==="json"){let r=Ep(e,H4);this.#e.send(r)}else if(t==="protobuf"){let r=Ap(e,Y4);this.#e.send(r)}else throw Ke(t,"Impossible encoding")}getVersion(){return new Promise((e,t)=>{if(this.#a=!0,this.#n!==void 0)t(this.#n);else if(!this.#r){let r=()=>e(this.#i.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#i.version)})}_ensureVersion(e,t){if(this.#i===void 0||!this.#a)throw new xn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the WebSocket server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this.#i.version<e)throw new xn(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#i.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new xt("Client is closed",this.#n));return}let r=this.#c.alloc();this.#s.set(r,{...t,type:e.type}),this.#d({type:"request",requestId:r,request:e})}#f(e){let r=e.message??"WebSocket was closed due to an error";this.#u(new yl(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new yl(t))}#u(e){if(this.#n!==void 0)return;this.#n=e;for(let t of this.#t)t.errorCallback(e);this.#t.length=0;for(let[t,r]of this.#s.entries())r.errorCallback(e),this.#c.free(t);this.#s.clear(),this.#e.close()}#y(e){if(this.#n!==void 0)return;try{let t,r=this.#i.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new Pe("Received non-text message from server with JSON encoding"));return}t=pa(JSON.parse(e.data),rF)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new Pe("Received non-binary message from server with Protobuf encoding"));return}t=Gi(new Uint8Array(e.data),sF)}else throw Ke(r,"Impossible encoding");this.#b(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#b(e){if(e.type==="none")throw new Pe("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#o)throw new Pe("Received a duplicated hello response");if(this.#o=!0,e.type==="hello_error")throw Zo(e.error);return}else if(!this.#o)throw new Pe("Received a non-hello message before a hello response");if(e.type==="response_ok"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new Pe("Received unexpected type of response");r.responseCallback(e.response)}catch(o){throw r.errorCallback(o),o}}else if(e.type==="response_error"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected error response");this.#c.free(t),r.errorCallback(Zo(e.error))}else throw Ke(e,"Impossible ServerMsg type")}openStream(){return Cp.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new ha(this,t),o=()=>{return},n=(s)=>r._setClosed(s),i={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(i,{responseCallback:o,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),o={type:"close_sql",sqlId:e};this._sendRequest(o,{responseCallback:t,errorCallback:r})}close(){this.#u(new Ge("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var ga;var lF=v(()=>{if(typeof queueMicrotask<"u")ga=queueMicrotask;else{let e=Promise.resolve();ga=(t)=>{e.then(t)}}});class lT{#e;#t;#r;constructor(e){this.#e=new Uint8Array(new ArrayBuffer(e)),this.#t=0,this.#r=0}get length(){return this.#r-this.#t}data(){return this.#e.slice(this.#t,this.#r)}push(e){this.#n(e.byteLength),this.#e.set(e,this.#r),this.#r+=e.byteLength}#n(e){if(this.#r+e<=this.#e.byteLength)return;let t=this.#r-this.#t;if(t+e<=this.#e.byteLength&&2*this.#r>=this.#e.byteLength)this.#e.copyWithin(0,this.#t,this.#r);else{let r=this.#e.byteLength;do r*=2;while(t+e>r);let o=new Uint8Array(new ArrayBuffer(r));o.set(this.#e.slice(this.#t,this.#r),0),this.#e=o}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function uF(e){let t=Ur(e.baton),r=Ur(e.base_url),o=_n(e.results,lme);return{baton:t,baseUrl:r,results:o}}function lme(e){let t=Tr(e.type);if(t==="ok")return{type:"ok",response:ume(kt(e.response))};else if(t==="error")return{type:"error",error:Xi(kt(e.error))};else throw new Pe("Unexpected type of StreamResult")}function ume(e){let t=Tr(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:Np(kt(e.result))};else if(t==="batch")return{type:"batch",result:Ly(kt(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:jy(kt(e.result))};else if(t==="store_sql")return{type:"store_sql"};else if(t==="close_sql")return{type:"close_sql"};else if(t==="get_autocommit")return{type:"get_autocommit",isAutocommit:Wi(e.is_autocommit)};else throw new Pe("Unexpected type of StreamResponse")}function dF(e){let t=Ur(e.baton),r=Ur(e.base_url);return{baton:t,baseUrl:r}}var uT=v(()=>{_t();Sl();Zy()});var pF,dme,pme,fme,mme,hme,gme,fF;var dT=v(()=>{My();pF={default(){return{baton:void 0,baseUrl:void 0,results:[]}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()},3(e,t){t.results.push(e.message(dme))}},dme={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(pme)}},2(e){return{type:"error",error:e.message(on)}}},pme={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(fme)},3(e){return e.message(mme)},4(e){return{type:"sequence"}},5(e){return e.message(hme)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(gme)}},fme={default(){return{type:"execute",result:es.default()}},1(e,t){t.result=e.message(es)}},mme={default(){return{type:"batch",result:Il.default()}},1(e,t){t.result=e.message(Il)}},hme={default(){return{type:"describe",result:kl.default()}},1(e,t){t.result=e.message(kl)}},gme={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},fF={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var pT;var mF=v(()=>{Sl();VR();_t();nn();uT();dT();Zy();My();pT=class pT extends Op{#e;#t;#r;#n;#o;#i;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new lT(16384),this.#o=void 0,this.#i=!1}async open(e){if(e.body===null)throw new Pe("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(dF,fF);if(t===void 0)throw new Pe("Empty response to cursor request");return t}next(){return this.#a(By,Uy)}close(){this._setClosed(new Ge("Cursor was manually closed"))}_setClosed(e){if(this.#o!==void 0)return;if(this.#o=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#o!==void 0}async#a(e,t){for(;;){if(this.#i)return;else if(this.#o!==void 0)throw new xt("Cursor is closed",this.#o);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let i=new TextDecoder().decode(n),s=JSON.parse(i);return pa(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return Gi(n,t)}else throw Ke(this.#t,"Impossible encoding");if(this.#r===void 0)throw new or("Attempted to read from HTTP cursor before it was opened");let{value:r,done:o}=await this.#r.next();if(o&&this.#n.length===0)this.#i=!0;else if(o)throw new Pe("Unexpected end of cursor stream");else this.#n.push(r)}}#s(){let e=this.#n.data(),t=10,r=e.indexOf(10);if(r<0)return;let o=e.slice(0,r);return this.#n.shift(r+1),o}#c(){let e=this.#n.data(),t=0,r=0;for(;;){if(r>=e.byteLength)return;let n=e[r];if(t|=(n&127)<<7*r,r+=1,!(n&128))break}if(e.byteLength<r+t)return;let o=e.slice(r,r+t);return this.#n.shift(r+t),o}}});function hF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,yme)}function yme(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,Pp);else if(t.type==="batch")e.object("batch",t.batch,_l);else if(t.type==="sequence"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="describe"){if(t.sql!==void 0)e.string("sql",t.sql);if(t.sqlId!==void 0)e.number("sql_id",t.sqlId)}else if(t.type==="store_sql")e.number("sql_id",t.sqlId),e.string("sql",t.sql);else if(t.type==="close_sql")e.number("sql_id",t.sqlId);else if(t.type==="get_autocommit");else throw Ke(t,"Impossible type of StreamRequest")}function gF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,_l)}var fT=v(()=>{iT();nn()});function yF(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,bme)}function bme(e,t){if(t.type==="close")e.message(1,t,Sme);else if(t.type==="execute")e.message(2,t,vme);else if(t.type==="batch")e.message(3,t,wme);else if(t.type==="sequence")e.message(4,t,xme);else if(t.type==="describe")e.message(5,t,_me);else if(t.type==="store_sql")e.message(6,t,Eme);else if(t.type==="close_sql")e.message(7,t,Ime);else if(t.type==="get_autocommit")e.message(8,t,kme);else throw Ke(t,"Impossible type of StreamRequest")}function Sme(e,t){}function vme(e,t){e.message(1,t.stmt,zp)}function wme(e,t){e.message(1,t.batch,El)}function xme(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function _me(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function Eme(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function Ime(e,t){e.int32(1,t.sqlId)}function kme(e,t){}function bF(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,El)}var mT=v(()=>{aT();nn()});function Ame(e,t){if(t.results.length!==e.length)throw new Pe("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let o=t.results[r],n=e[r];if(o.type==="ok"){if(o.response.type!==n.request.type)throw new Pe("Received unexpected type of response");n.responseCallback(o.response)}else if(o.type==="error")n.errorCallback(Zo(o.error));else if(o.type==="none")throw new Pe("Received unrecognized type of StreamResult");else throw Ke(o,"Received impossible type of StreamResult")}}async function Rme(e,t){if(t==="json"){let r=await e.json();return pa(r,uF)}if(t==="protobuf"){let r=await e.arrayBuffer();return Gi(new Uint8Array(r),pF)}throw await e.body?.cancel(),Ke(t,"Impossible encoding")}async function Tme(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let o=await e.json();if("message"in o)return Zo(o);return new da(r,e.status)}if(t==="text/plain"){let o=(await e.text()).trim();if(o!=="")r+=`: ${o}`;return new da(r,e.status)}return await e.body?.cancel(),new da(r,e.status)}var Jy;var hT=v(()=>{_t();GR();QR();lF();Rp();wl();Dy();nn();mF();fT();mT();fT();mT();uT();dT();Jy=class Jy extends xl{#e;#t;#r;#n;#o;#i;#a;#s;#c;#l;#d;#p;#m;constructor(e,t,r,o,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=o,this.#o=n,this.#i=void 0,this.#a=new Yi,this.#s=!1,this.#l=!1,this.#d=!1,this.#p=void 0,this.#m=new Qi}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let t=this.#m.alloc();return this.#f({type:"store_sql",sqlId:t,sql:e}).then(()=>{return},(r)=>this._setClosed(r)),new ha(this,t)}_closeSql(e){if(this.#p!==void 0)return;this.#f({type:"close_sql",sqlId:e}).then(()=>this.#m.free(e),(t)=>this._setClosed(t))}_execute(e){return this.#f({type:"execute",stmt:e}).then((t)=>t.result)}_batch(e){return this.#f({type:"batch",batch:e}).then((t)=>t.result)}_describe(e){return this.#f({type:"describe",sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#f({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#f({type:"get_autocommit"}).then((e)=>e.isAutocommit)}#f(e){return new Promise((t,r)=>{this.#g({type:"pipeline",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return new Promise((t,r)=>{this.#g({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_cursorClosed(e){if(e!==this.#c)throw new or("Cursor was closed, but it was not associated with the stream");this.#c=void 0,ga(()=>this.#u())}close(){this._setClosed(new Ge("Stream was manually closed"))}closeGracefully(){this.#l=!0,ga(()=>this.#u())}get closed(){return this.#p!==void 0||this.#l}_setClosed(e){if(this.#p!==void 0)return;if(this.#p=e,this.#c!==void 0)this.#c._setClosed(e);this.#e._streamClosed(this);for(;;){let t=this.#a.shift();if(t!==void 0)t.errorCallback(e);else break}if((this.#i!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,ga(()=>this.#u())}#g(e){if(this.#p!==void 0)throw new xt("Stream is closed",this.#p);else if(this.#l)throw new xt("Stream is closing",void 0);else this.#a.push(e),ga(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new Ge("Stream was gracefully closed"));return}let e=this.#e._endpoint;if(e===void 0){this.#e._endpointPromise.then(()=>this.#u(),(r)=>this._setClosed(r));return}let t=this.#a.shift();if(t===void 0)return;else if(t.type==="pipeline"){let r=[t];for(;;){let o=this.#a.first();if(o!==void 0&&o.type==="pipeline")r.push(o),this.#a.shift();else if(o===void 0&&this.#l&&!this.#d){r.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0;break}else break}this.#y(e,r)}else if(t.type==="cursor")this.#b(e,t);else throw Ke(t,"Impossible type of QueueEntry")}#y(e,t){this.#h(()=>this.#S(t,e),(r)=>Rme(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>Ame(t,r),(r)=>t.forEach((o)=>o.errorCallback(r)))}#b(e,t){let r=new pT(this,e.encoding);this.#c=r,this.#h(()=>this.#v(t,e),(o)=>r.open(o),(o)=>o.baton,(o)=>o.baseUrl,(o)=>t.cursorCallback(r),(o)=>t.errorCallback(o))}#h(e,t,r,o,n,i){let s;try{let a=e(),l=this.#n;s=l(a)}catch(a){s=Promise.reject(a)}this.#s=!0,s.then((a)=>{if(!a.ok)return Tme(a).then((l)=>{throw l});return t(a)}).then((a)=>{this.#i=r(a),this.#t=o(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),i(a)}).finally(()=>{this.#s=!1,this.#u()})}#S(e,t){return this.#w(new URL(t.pipelinePath,this.#t),{baton:this.#i,requests:e.map((r)=>r.request)},t.encoding,hF,yF)}#v(e,t){if(t.cursorPath===void 0)throw new xn(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#w(new URL(t.cursorPath,this.#t),{baton:this.#i,batch:e.batch},t.encoding,gF,bF)}#w(e,t,r,o,n){let i,s;if(r==="json")i=Ep(t,o),s="application/json";else if(r==="protobuf")i=Ap(t,n),s="application/x-protobuf";else throw Ke(r,"Impossible encoding");let a=new Headers;if(a.set("content-type",s),this.#r!==void 0)a.set("authorization",`Bearer ${this.#r}`);if(this.#o!==void 0)a.set("x-turso-encryption-key",this.#o);return new Request(e.toString(),{method:"POST",headers:a,body:i})}}});async function Ome(e,t){let r=e;for(let o of $me){let n=new URL(o.versionPath,t),i=new Request(n.toString(),{method:"GET"}),s=await r(i);if(await s.arrayBuffer(),s.ok)return o}return gT}var $me,gT,Ky;var yT=v(()=>{_t();hT();$me=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],gT={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};Ky=class Ky extends gl{#e;#t;#r;#n;#o;#i;_endpointPromise;_endpoint;constructor(e,t,r,o,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=o,this.#o=void 0,this.#i=new Set,n==3)this._endpointPromise=Ome(this.#r,this.#e),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i));else this._endpointPromise=Promise.resolve(gT),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=gT.version)return;else if(this._endpoint===void 0)throw new xn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the HTTP server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this._endpoint.version<e)throw new xn(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#o!==void 0)throw new xt("Client is closed",this.#o);let e=new Jy(this,this.#e,this.#t,this.#r,this.#n);return this.#i.add(e),e}_streamClosed(e){this.#i.delete(e)}close(){this.#a(new Ge("Client was manually closed"))}get closed(){return this.#o!==void 0}#a(e){if(this.#o!==void 0)return;this.#o=e;for(let t of Array.from(this.#i))t._setClosed(new xt("Client was closed",e))}}});var SF=v(()=>{_t()});function bT(e,t,r=2){if(typeof Vi>"u")throw new xp("WebSockets are not supported in this environment");var o=void 0;if(r==3)o=Array.from(cT.keys());else o=Array.from(cF.keys());let n=new Vi(e,o);return new qy(n,t)}function ST(e,t,r,o,n=2){return new Ky(e instanceof URL?e:new URL(e),t,r,o,n)}var Hy=v(()=>{HR();Fy();_t();yT();Fy();HR();tT();SF();wl();zy();Dy();yT();hT();Fy();nT();_t()});class Dp{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}execute(e){return this.batch([e]).then((t)=>t[0])}async batch(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(Uo),o;if(this.#r===void 0){this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=i.step(),a=s.run(Ki(this.#e)),l=s;o=r.map((u)=>{let d=i.step().condition(ut.ok(l));if(this.#t>=3)d.condition(ut.not(ut.isAutocommit(i)));let p=d.query(u);return p.catch(()=>{return}),l=d,p}),this.#r=i.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(u){throw this.close(),u}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=void 0;o=r.map((a)=>{let l=i.step();if(s!==void 0)l.condition(ut.ok(s));if(this.#t>=3)l.condition(ut.not(ut.isAutocommit(i)));let u=l.query(a);return u.catch(()=>{return}),s=l,u}),await i.execute()}let n=[];for(let i=0;i<o.length;i++)try{let s=await o[i];if(s===void 0)throw new Wt("Statement in a transaction was not executed, probably because the transaction has been rolled back",i,"TRANSACTION_CLOSED");n.push(Rl(s))}catch(s){if(s instanceof Wt)throw s;let a=st(s);if(a instanceof Ce)throw new Wt(a.message,i,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw st(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(Ki(this.#e)).then(()=>{return});try{await this.#r}catch(r){throw this.close(),r}}else await this.#r;await t.sequence(e)}catch(r){throw st(r)}}async rollback(){try{let e=this._getStream();if(e.closed)return;if(this.#r!==void 0);else return;let t=e.run("ROLLBACK").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Ce("Cannot commit the transaction because it is already closed","TRANSACTION_CLOSED");if(this.#r!==void 0)await this.#r;else return;let t=e.run("COMMIT").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}}async function Al(e,t,r,o,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let i=r.step(),s=i.run(Ki(e)),a=i,l=o.map((h)=>{let b=r.step().condition(ut.ok(a));if(t>=3)b.condition(ut.not(ut.isAutocommit(r)));let y=b.query(h);return a=b,y}),u=r.step().condition(ut.ok(a));if(t>=3)u.condition(ut.not(ut.isAutocommit(r)));let d=u.run("COMMIT");if(r.step().condition(ut.not(ut.ok(u))).run("ROLLBACK").catch((h)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let m=[];await s;for(let h=0;h<l.length;h++)try{let b=await l[h];if(b===void 0)throw new Wt("Statement in a batch was not executed, probably because the transaction has been rolled back",h,"TRANSACTION_CLOSED");m.push(Rl(b))}catch(b){if(b instanceof Wt)throw b;let y=st(b);if(y instanceof Ce)throw new Wt(y.message,h,y.code,y.extendedCode,y.rawCode,y.cause instanceof Error?y.cause:void 0);throw y}return await d,m}function Uo(e){let t,r;if(Array.isArray(e))[t,r]=e;else if(typeof e==="string")t=e;else t=e.sql,r=e.args;let o=new $p(t);if(r)if(Array.isArray(r))o.bindIndexes(r);else for(let[n,i]of Object.entries(r))o.bindName(n,i);return o}function Rl(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),o=e.rows,n=e.affectedRowCount,i=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new pl(t,r,o,n,i)}function st(e){if(e instanceof Ge){let t=vF(e);return new Ce(e.message,t,void 0,void 0,e)}return e}function vF(e){if(e instanceof wp&&e.code!==void 0)return e.code;else if(e instanceof Pe)return"HRANA_PROTO_ERROR";else if(e instanceof xt)return e.cause instanceof Ge?vF(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof yl)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof da)return"SERVER_ERROR";else if(e instanceof xn)return"PROTOCOL_VERSION_ERROR";else if(e instanceof or)return"INTERNAL_ERROR";else return"UNKNOWN"}var wT=v(()=>{Hy();wn();fl()});class Tl{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new wF,this.capacity=t}apply(e){if(this.capacity<=0)return;let t=new Set;for(let r of e){if(typeof r.sql!=="string")continue;let o=r.sql;if(o.length>=5000)continue;let n=this.#t.get(o);if(n===void 0){while(this.#t.size+1>this.capacity){let[i,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(i)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(o),this.#t.set(o,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class wF{#e;constructor(){this.#e=new Map}get(e){let t=this.#e.get(e);if(t!==void 0)this.#e.delete(e),this.#e.set(e,t);return t}set(e,t){this.#e.set(e,t)}peekLru(){for(let e of this.#e.entries())return e;return}delete(e){this.#e.delete(e)}get size(){return this.#e.size}}var xT=ge(function(rje,_F){function Cme(e){var t=0,r=[];function o(){if(t--,t<e)n()}function n(){var l=r.shift();if(a.queue=r.length,l)s(l.fn).then(l.resolve).catch(l.reject)}function i(l){return new Promise(function(u,d){r.push({fn:l,resolve:u,reject:d}),a.queue=r.length})}function s(l){t++;try{return Promise.resolve(l()).then(function(u){return o(),u},function(u){throw o(),u})}catch(u){return o(),Promise.reject(u)}}var a=function(l){if(t>=e)return i(l);else return s(l)};return a}function Pme(e,t){var r=!1,o=this;return Promise.all(e.map(function(){var n=arguments;return o(function(){if(!r)return t.apply(void 0,n).catch(function(i){throw r=!0,i})})}))}function xF(e){return e.queue=0,e.map=Pme,e}_F.exports=function(e){if(e)return xF(Cme(e));else return xF(function(t){return t()})}});function kF(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Ce(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${Xn}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Ce('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Ce('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=gp(e.scheme,e.authority,e.path),r;try{r=bT(t,e.authToken)}catch(o){if(o instanceof xp){let n=e.scheme==="wss"?"https":"http",i=gp(n,e.authority,e.path);throw new Ce(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(i)}). For more information, please read ${Xn}`,"WEBSOCKETS_NOT_SUPPORTED")}throw st(o)}return new AF(r,t,e.authToken,e.intMode,e.concurrency)}class AF{#e;#t;#r;#n;#o;closed;protocol;#i;#a;constructor(e,t,r,o,n){this.#e=t,this.#t=r,this.#r=o,this.#n=this.#c(e),this.#o=void 0,this.closed=!1,this.protocol="ws",this.#a=IF.default(n)}async limit(e){return this.#a(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{let o=await this.#s();try{let n=Uo(r);o.conn.sqlCache.apply([n]);let i=o.stream.query(n);o.stream.closeGracefully();let s=await i;return Rl(s)}catch(n){throw st(n)}finally{this._closeStream(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((u)=>{if(Array.isArray(u))return{sql:u[0],args:u[1]||[]};return u}).map(Uo),i=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(i>=3);return await Al(t,i,s,n)}catch(o){throw st(o)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(Uo),o=await t.conn.client.getVersion(),n=t.stream.batch(o>=3);return await Al("deferred",o,n,r,!0)}catch(r){throw st(r)}finally{this._closeStream(t)}})}async transaction(e="write"){return this.limit(async()=>{let t=await this.#s();try{let r=await t.conn.client.getVersion();return new RF(this,t,e,r)}catch(r){throw this._closeStream(t),st(r)}})}async executeMultiple(e){return this.limit(async()=>{let t=await this.#s();try{let r=t.stream.sequence(e);t.stream.closeGracefully(),await r}catch(r){throw st(r)}finally{this._closeStream(t)}})}sync(){throw new Ce("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>zme&&this.#o===void 0){let o=this.#c();this.#o=o,o.client.getVersion().then((n)=>{if(this.#n!==o){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=o,this.#o=void 0},(n)=>{this.#o=void 0})}if(this.#n.client.closed)try{if(this.#o!==void 0)this.#n=this.#o;else this.#n=this.#c()}catch(o){throw st(o)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=EF}let o=r.client.openStream();o.intMode=this.#r;let n={conn:r,stream:o};return r.streamStates.add(n),n}catch(o){throw st(o)}}#c(e){try{return e??=bT(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new Tl(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw st(t)}}async reconnect(){try{for(let r of Array.from(this.#n.streamStates))try{r.stream.close()}catch{}this.#n.client.close()}catch{}if(this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=EF;this.#n=e,this.closed=!1}_closeStream(e){e.stream.close();let t=e.conn;if(t.streamStates.delete(e),t.streamStates.size===0&&t!==this.#n)t.client.close()}close(){if(this.#n.client.close(),this.closed=!0,this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}this.closed=!0}}var IF,zme=60000,EF=100,RF;var TF=v(()=>{Hy();wn();Sp();wT();_y();fl();IF=Jl(xT(),1);wn();RF=class RF extends Dp{#e;#t;constructor(e,t,r,o){super(r,o);this.#e=e,this.#t=t}_getStream(){return this.#t.stream}_getSqlCache(){return this.#t.conn.sqlCache}close(){this.#e._closeStream(this.#t)}get closed(){return this.#t.stream.closed}}});function OF(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Ce(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${Xn}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Ce('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Ce('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=gp(e.scheme,e.authority,e.path);return new PF(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class PF{#e;protocol;#t;#r;#n;#o;#i;#a;#s;constructor(e,t,r,o,n,i){this.#t=e,this.#i=t,this.#r=r,this.#n=o,this.#o=n,this.#a=i,this.#e=ST(this.#t,this.#i,this.#n,i),this.#e.intMode=this.#r,this.protocol="http",this.#s=$F.default(this.#o)}async limit(e){return this.#s(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{try{let o=Uo(r),n,i=this.#e.openStream();try{n=i.query(o)}finally{i.closeGracefully()}let s=await n;return Rl(s)}catch(o){throw st(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let o=e.map((l)=>{if(Array.isArray(l))return{sql:l[0],args:l[1]||[]};return l}).map(Uo),n=await this.#e.getVersion(),i,s=this.#e.openStream();try{new Tl(s,CF).apply(o);let u=s.batch(!1);i=Al(t,n,u,o)}finally{s.closeGracefully()}return await i}catch(r){throw st(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(Uo),r=await this.#e.getVersion(),o,n=this.#e.openStream();try{let s=n.batch(!1);o=Al("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await o}catch(t){throw st(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new zF(this.#e.openStream(),e,t)}catch(t){throw st(t)}})}async executeMultiple(e){return this.limit(async()=>{try{let t,r=this.#e.openStream();try{t=r.sequence(e)}finally{r.closeGracefully()}await t}catch(t){throw st(t)}})}sync(){throw new Ce("sync not supported in http mode","SYNC_NOT_SUPPORTED")}close(){this.#e.close()}async reconnect(){try{if(!this.closed)this.#e.close()}finally{this.#e=ST(this.#t,this.#i,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var $F,CF=30,zF;var NF=v(()=>{Hy();wn();Sp();wT();_y();fl();$F=Jl(xT(),1);wn();zF=class zF extends Dp{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new Tl(e,CF)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function $l(e){return Nme(bp(e,!0))}function Nme(e){if(e.scheme==="wss"||e.scheme==="ws")return kF(e);else if(e.scheme==="https"||e.scheme==="http")return OF(e);else return $4(e)}var _T=v(()=>{Sp();N4();TF();NF();wn()});function oe(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,F))throw Error(`Class "${t.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 r=Object.getPrototypeOf(e).constructor;if(r)while(r){if(F in r&&r[F]===t[F])return!0;r=Object.getPrototypeOf(r)}return!1}var F;var $e=v(()=>{F=Symbol.for("drizzle:entityKind")});var He;var En=v(()=>{$e();He=class He{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[F]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var Lp;var Vy=v(()=>{$e();Lp=class Lp{static[F]="ColumnBuilder";config;constructor(e,t,r){this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:r,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){if(this.config.name!=="")return;this.config.name=e}}});var ir;var Ol=v(()=>{ir=Symbol.for("drizzle:Name")});var ET,DF;var LF=v(()=>{$e();Ol();ET=class ET{static[F]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e===void 0?"no action":e,this}onDelete(e){return this._onDelete=e===void 0?"no action":e,this}build(e){return new DF(e,this)}};DF=class DF{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function Wy(e,...t){return e(...t)}var IT=()=>{};function kT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var BF,Dme,jF;var ZF=v(()=>{$e();Ol();BF=class BF{constructor(e,t){this.name=t,this.columns=e}static[F]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new jF(e,this.columns,this.nullsNotDistinctConfig,this.name)}};Dme=class Dme{static[F]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new BF(e,this.name)}};jF=class jF{constructor(e,t,r,o){this.table=e,this.columns=t,this.name=o??kT(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[F]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function UF(e,t,r){for(let o=t;o<e.length;o++){let n=e[o];if(n==="\\"){o++;continue}if(n==='"')return[e.slice(t,o).replace(/\\/g,""),o+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,o).replace(/\\/g,""),o]}return[e.slice(t).replace(/\\/g,""),e.length]}function MF(e,t=0){let r=[],o=t,n=!1;while(o<e.length){let i=e[o];if(i===","){if(n||o===t)r.push("");n=!0,o++;continue}if(n=!1,i==="\\"){o+=2;continue}if(i==='"'){let[l,u]=UF(e,o+1,!0);r.push(l),o=u;continue}if(i==="}")return[r,o+1];if(i==="{"){let[l,u]=MF(e,o+1);r.push(l),o=u;continue}let[s,a]=UF(e,o,!1);r.push(s),o=a}return[r,o]}function qF(e){let[t]=MF(e,1);return t}function AT(e){return`{${e.map((t)=>{if(Array.isArray(t))return AT(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var FF=()=>{};var Bp,Cl,JF,Lme,KF,RT;var HF=v(()=>{Vy();En();$e();LF();IT();ZF();FF();Bp=class Bp extends Lp{foreignKeyConfigs=[];static[F]="PgColumnBuilder";array(e){return new KF(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>Wy((n,i)=>{let s=new ET(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)},r,o))}buildExtraConfigColumn(e){return new JF(e,this.config)}};Cl=class Cl extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=kT(e,[t.name]);super(e,t);this.table=e}static[F]="PgColumn"};JF=class JF extends Cl{static[F]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}};Lme=class Lme{static[F]="IndexedColumn";constructor(e,t,r,o){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=o}name;keyAsName;type;indexConfig};KF=class KF extends Bp{static[F]="PgArrayBuilder";constructor(e,t,r){super(e,"array","PgArray");this.config.baseBuilder=t,this.config.size=r}build(e){let t=this.config.baseBuilder.build(e);return new RT(e,this.config,t)}};RT=class RT extends Cl{constructor(e,t,r,o){super(e,t);this.baseColumn=r,this.range=o,this.size=t.size}size;static[F]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=qF(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((o)=>o===null?null:oe(this.baseColumn,RT)?this.baseColumn.mapToDriverValue(o,!0):this.baseColumn.mapToDriverValue(o));if(t)return r;return AT(r)}}});function GF(e){return!!e&&typeof e==="function"&&VF in e&&e[VF]===!0}var Bme,WF,VF,jme,QF;var YF=v(()=>{$e();HF();Bme=class Bme extends Bp{static[F]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new WF(e,this.config)}};WF=class WF extends Cl{static[F]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};VF=Symbol.for("drizzle:isPgEnum");jme=class jme extends Bp{static[F]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new QF(e,this.config)}};QF=class QF extends Cl{static[F]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}}});var dt,jp;var In=v(()=>{$e();dt=class dt{static[F]="Subquery";constructor(e,t,r,o=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:o,usedTables:n}}};jp=class jp extends dt{static[F]="WithSubquery"}});var XF="0.45.2";var e3=()=>{};var TT,$T,t3;var r3=v(()=>{IT();e3();t3={startActiveSpan(e,t){if(!TT)return t();if(!$T)$T=TT.trace.getTracer("drizzle-orm",XF);return Wy((r,o)=>o.startActiveSpan(e,(n)=>{try{return t(n)}catch(i){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:i instanceof Error?i.message:"Unknown error"}),i}finally{n.end()}}),TT,$T)}}});var pt;var Mo=v(()=>{pt=Symbol.for("drizzle:ViewBaseConfig")});function ts(e){return e[ir]}function ya(e){return`${e[Gy]??"public"}.${e[ir]}`}var Gy,Qy,n3,OT,CT,Zp,o3,Zme,he;var sr=v(()=>{$e();Ol();Gy=Symbol.for("drizzle:Schema"),Qy=Symbol.for("drizzle:Columns"),n3=Symbol.for("drizzle:ExtraConfigColumns"),OT=Symbol.for("drizzle:OriginalName"),CT=Symbol.for("drizzle:BaseName"),Zp=Symbol.for("drizzle:IsAlias"),o3=Symbol.for("drizzle:ExtraConfigBuilder"),Zme=Symbol.for("drizzle:IsDrizzleTable");he=class he{static[F]="Table";static Symbol={Name:ir,Schema:Gy,OriginalName:OT,Columns:Qy,ExtraConfigColumns:n3,BaseName:CT,IsAlias:Zp,ExtraConfigBuilder:o3};[ir];[OT];[Gy];[Qy];[n3];[CT];[Zp]=!1;[Zme]=!0;[o3]=void 0;constructor(e,t,r){this[ir]=this[OT]=e,this[Gy]=t,this[CT]=r}}});function PT(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function Mme(e){let t={sql:"",params:[]};for(let r of e)if(t.sql+=r.sql,t.params.push(...r.params),r.typings?.length){if(!t.typings)t.typings=[];t.typings.push(...r.typings)}return t}function i3(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function C(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Nt(e[0]));for(let[o,n]of t.entries())r.push(n,new Nt(e[o+1]));return new Ee(r)}function Up(e,t){return e.map((r)=>{if(oe(r,rs)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(oe(r,Mr)&&oe(r.value,rs)){if(!(r.value.name in t))throw Error(`No value for placeholder "${r.value.name}" was provided`);return r.encoder.mapToDriverValue(t[r.value.name])}return r})}var Ume,Nt,Ee,Yy,s3,a3,fZe,Mr,rs,qme,sn;var Qt=v(()=>{$e();YF();In();r3();Mo();En();sr();Ume=class Ume{static[F]="FakePrimitiveParam"};Nt=class Nt{static[F]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new Ee([this])}};Ee=class Ee{constructor(e){this.queryChunks=e;for(let t of e)if(oe(t,he)){let r=t[he.Symbol.Schema];this.usedTables.push(r===void 0?t[he.Symbol.Name]:r+"."+t[he.Symbol.Name])}}static[F]="SQL";decoder=s3;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return t3.startActiveSpan("drizzle.buildSQL",(t)=>{let r=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(e,t){let r=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:o,escapeName:n,escapeParam:i,prepareTyping:s,inlineParams:a,paramStartIndex:l}=r;return Mme(e.map((u)=>{if(oe(u,Nt))return{sql:u.value.join(""),params:[]};if(oe(u,Yy))return{sql:n(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){let d=[new Nt("(")];for(let[p,m]of u.entries())if(d.push(m),p<u.length-1)d.push(new Nt(", "));return d.push(new Nt(")")),this.buildQueryFromSourceParams(d,r)}if(oe(u,Ee))return this.buildQueryFromSourceParams(u.queryChunks,{...r,inlineParams:a||u.shouldInlineParams});if(oe(u,he)){let d=u[he.Symbol.Schema],p=u[he.Symbol.Name];return{sql:d===void 0||u[Zp]?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,He)){let d=o.getColumnCasing(u);if(t.invokeSource==="indexes")return{sql:n(d),params:[]};let p=u.table[he.Symbol.Schema];return{sql:u.table[Zp]||p===void 0?n(u.table[he.Symbol.Name])+"."+n(d):n(p)+"."+n(u.table[he.Symbol.Name])+"."+n(d),params:[]}}if(oe(u,sn)){let d=u[pt].schema,p=u[pt].name;return{sql:d===void 0||u[pt].isAlias?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,Mr)){if(oe(u.value,rs))return{sql:i(l.value++,u),params:[u],typings:["none"]};let d=u.value===null?null:u.encoder.mapToDriverValue(u.value);if(oe(d,Ee))return this.buildQueryFromSourceParams([d],r);if(a)return{sql:this.mapInlineParam(d,r),params:[]};let p=["none"];if(s)p=[s(u.encoder)];return{sql:i(l.value++,d),params:[d],typings:p}}if(oe(u,rs))return{sql:i(l.value++,u),params:[u],typings:["none"]};if(oe(u,Ee.Aliased)&&u.fieldAlias!==void 0)return{sql:n(u.fieldAlias),params:[]};if(oe(u,dt)){if(u._.isWith)return{sql:n(u._.alias),params:[]};return this.buildQueryFromSourceParams([new Nt("("),u._.sql,new Nt(") "),new Yy(u._.alias)],r)}if(GF(u)){if(u.schema)return{sql:n(u.schema)+"."+n(u.enumName),params:[]};return{sql:n(u.enumName),params:[]}}if(PT(u)){if(u.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([u.getSQL()],r);return this.buildQueryFromSourceParams([new Nt("("),u.getSQL(),new Nt(")")],r)}if(a)return{sql:this.mapInlineParam(u,r),params:[]};return{sql:i(l.value++,u),params:[u],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e==="number"||typeof e==="boolean")return e.toString();if(typeof e==="string")return t(e);if(typeof e==="object"){let r=e.toString();if(r==="[object Object]")return t(JSON.stringify(e));return t(r)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){if(e===void 0)return this;return new Ee.Aliased(this,e)}mapWith(e){return this.decoder=typeof e==="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}};Yy=class Yy{constructor(e){this.value=e}static[F]="Name";brand;getSQL(){return new Ee([this])}};s3={mapFromDriverValue:(e)=>e},a3={mapToDriverValue:(e)=>e},fZe={...s3,...a3};Mr=class Mr{constructor(e,t=a3){this.value=e,this.encoder=t}static[F]="Param";brand;getSQL(){return new Ee([this])}};((e)=>{function t(){return new Ee([])}e.empty=t;function r(l){return new Ee(l)}e.fromList=r;function o(l){return new Ee([new Nt(l)])}e.raw=o;function n(l,u){let d=[];for(let[p,m]of l.entries()){if(p>0&&u!==void 0)d.push(u);d.push(m)}return new Ee(d)}e.join=n;function i(l){return new Yy(l)}e.identifier=i;function s(l){return new rs(l)}e.placeholder=s;function a(l,u){return new Mr(l,u)}e.param=a})(C||(C={}));((e)=>{class t{constructor(r,o){this.sql=r,this.fieldAlias=o}static[F]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(Ee||(Ee={}));rs=class rs{constructor(e){this.name=e}static[F]="Placeholder";getSQL(){return new Ee([this])}};qme=Symbol.for("drizzle:IsDrizzleView");sn=class sn{static[F]="View";[pt];[qme]=!0;constructor({name:e,schema:t,selectedFields:r,query:o}){this[pt]={name:e,originalName:e,schema:t,selectedFields:r,query:o,isExisting:!o,isAlias:!1}}getSQL(){return new Ee([this])}};He.prototype.getSQL=function(){return new Ee([this])};he.prototype.getSQL=function(){return new Ee([this])};dt.prototype.getSQL=function(){return new Ee([this])}});function zT(e,t,r){let o={},n=e.reduce((i,{path:s,field:a},l)=>{let u;if(oe(a,He))u=a;else if(oe(a,Ee))u=a.decoder;else if(oe(a,dt))u=a._.sql.decoder;else u=a.sql.decoder;let d=i;for(let[p,m]of s.entries())if(p<s.length-1){if(!(m in d))d[m]={};d=d[m]}else{let h=t[l],b=d[m]=h===null?null:u.mapFromDriverValue(h);if(r&&oe(a,He)&&s.length===2){let y=s[0];if(!(y in o))o[y]=b===null?ts(a.table):!1;else if(typeof o[y]==="string"&&o[y]!==ts(a.table))o[y]=!1}}return i},{});if(r&&Object.keys(o).length>0){for(let[i,s]of Object.entries(o))if(typeof s==="string"&&!r[s])n[i]=null}return n}function an(e,t){return Object.entries(e).reduce((r,[o,n])=>{if(typeof o!=="string")return r;let i=t?[...t,o]:[o];if(oe(n,He)||oe(n,Ee)||oe(n,Ee.Aliased)||oe(n,dt))r.push({path:i,field:n});else if(oe(n,he))r.push(...an(n[he.Symbol.Columns],i));else r.push(...an(n,i));return r},[])}function Mp(e,t){let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(let[n,i]of r.entries())if(i!==o[n])return!1;return!0}function Xy(e,t){let r=Object.entries(t).filter(([,o])=>o!==void 0).map(([o,n])=>{if(oe(n,Ee)||oe(n,He))return[o,n];else return[o,new Mr(n,e[he.Symbol.Columns][o])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function c3(e,t){for(let r of t)for(let o of Object.getOwnPropertyNames(r.prototype)){if(o==="constructor")continue;Object.defineProperty(e.prototype,o,Object.getOwnPropertyDescriptor(r.prototype,o)||Object.create(null))}}function eb(e){return e[he.Symbol.Columns]}function qp(e){return oe(e,dt)?e._.alias:oe(e,sn)?e[pt].name:oe(e,Ee)?void 0:e[he.Symbol.IsAlias]?e[he.Symbol.Name]:e[he.Symbol.BaseName]}function no(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function l3(e){if(typeof e!=="object"||e===null)return!1;if(e.constructor.name!=="Object")return!1;if("logger"in e){let t=typeof e.logger;if(t!=="boolean"&&(t!=="object"||typeof e.logger.logQuery!=="function")&&t!=="undefined")return!1;return!0}if("schema"in e){let t=typeof e.schema;if(t!=="object"&&t!=="undefined")return!1;return!0}if("casing"in e){let t=typeof e.casing;if(t!=="string"&&t!=="undefined")return!1;return!0}if("mode"in e){if(e.mode!=="default"||e.mode!=="planetscale"||e.mode!==void 0)return!1;return!0}if("connection"in e){let t=typeof e.connection;if(t!=="string"&&t!=="object"&&t!=="undefined")return!1;return!0}if("client"in e){let t=typeof e.client;if(t!=="object"&&t!=="function"&&t!=="undefined")return!1;return!0}if(Object.keys(e).length===0)return!0;return!1}var NT;var Sr=v(()=>{En();$e();Qt();In();sr();Mo();NT=typeof TextDecoder>"u"?null:new TextDecoder});var u3,DT,LT;var tb=v(()=>{$e();u3=class u3{static[F]="ConsoleLogWriter";write(e){console.log(e)}};DT=class DT{static[F]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new u3}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),o=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${o}`)}};LT=class LT{static[F]="NoopLogger";logQuery(){}}});var d3,p3,BT;var f3=v(()=>{$e();sr();d3=Symbol.for("drizzle:PgInlineForeignKeys"),p3=Symbol.for("drizzle:EnableRLS");BT=class BT extends he{static[F]="PgTable";static Symbol=Object.assign({},he.Symbol,{InlineForeignKeys:d3,EnableRLS:p3});[d3]=[];[p3]=!1;[he.Symbol.ExtraConfigBuilder]=void 0;[he.Symbol.ExtraConfigColumns]={}}});var jT,m3;var h3=v(()=>{$e();f3();jT=class jT{static[F]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new m3(e,this.columns,this.name)}};m3=class m3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[BT.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function $r(e,t){if(i3(t)&&!PT(e)&&!oe(e,Mr)&&!oe(e,rs)&&!oe(e,He)&&!oe(e,he)&&!oe(e,sn))return new Mr(e,t);return e}function tt(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Ee(t);return new Ee([new Nt("("),C.join(t,new Nt(" and ")),new Nt(")")])}function cn(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new Ee(t);return new Ee([new Nt("("),C.join(t,new Nt(" or ")),new Nt(")")])}function y3(e){return C`not ${e}`}function os(e,t){if(Array.isArray(t)){if(t.length===0)return C`false`;return C`${e} in ${t.map((r)=>$r(r,e))}`}return C`${e} in ${$r(t,e)}`}function rb(e,t){if(Array.isArray(t)){if(t.length===0)return C`true`;return C`${e} not in ${t.map((r)=>$r(r,e))}`}return C`${e} not in ${$r(t,e)}`}function qr(e){return C`${e} is null`}function v3(e){return C`${e} is not null`}function nb(e){return C`exists ${e}`}function is(e){return C`not exists ${e}`}function w3(e,t,r){return C`${e} between ${$r(t,e)} and ${$r(r,e)}`}function x3(e,t,r){return C`${e} not between ${$r(t,e)} and ${$r(r,e)}`}function _3(e,t){return C`${e} like ${t}`}function E3(e,t){return C`${e} not like ${t}`}function I3(e,t){return C`${e} ilike ${t}`}function k3(e,t){return C`${e} not ilike ${t}`}var je=(e,t)=>C`${e} = ${$r(t,e)}`,g3=(e,t)=>C`${e} <> ${$r(t,e)}`,kn=(e,t)=>C`${e} > ${$r(t,e)}`,b3=(e,t)=>C`${e} >= ${$r(t,e)}`,S3=(e,t)=>C`${e} < ${$r(t,e)}`,ns=(e,t)=>C`${e} <= ${$r(t,e)}`;var A3=v(()=>{En();$e();sr();Qt()});function qo(e){return C`${e} asc`}function ba(e){return C`${e} desc`}var R3=v(()=>{Qt()});var ZT=v(()=>{A3();R3()});function $3(){return{and:tt,between:w3,eq:je,exists:nb,gt:kn,gte:b3,ilike:I3,inArray:os,isNull:qr,isNotNull:v3,like:_3,lt:S3,lte:ns,ne:g3,not:y3,notBetween:x3,notExists:is,notLike:E3,notIlike:k3,notInArray:rb,or:cn,sql:C}}function O3(){return{sql:C,asc:qo,desc:ba}}function C3(e,t){if(Object.keys(e).length===1&&"default"in e&&!oe(e.default,he))e=e.default;let r={},o={},n={};for(let[i,s]of Object.entries(e))if(oe(s,he)){let a=ya(s),l=o[a];r[a]=i,n[i]={tsName:i,dbName:s[he.Symbol.Name],schema:s[he.Symbol.Schema],columns:s[he.Symbol.Columns],relations:l?.relations??{},primaryKey:l?.primaryKey??[]};for(let d of Object.values(s[he.Symbol.Columns]))if(d.primary)n[i].primaryKey.push(d);let u=s[he.Symbol.ExtraConfigBuilder]?.(s[he.Symbol.ExtraConfigColumns]);if(u){for(let d of Object.values(u))if(oe(d,jT))n[i].primaryKey.push(...d.columns)}}else if(oe(s,T3)){let a=ya(s.table),l=r[a],u=s.config(t(s.table)),d;for(let[p,m]of Object.entries(u))if(l){let h=n[l];if(h.relations[p]=m,d)h.primaryKey.push(...d)}else{if(!(a in o))o[a]={relations:{},primaryKey:d};o[a].relations[p]=m}}return{tables:n,tableNamesMap:r}}function Fme(e){return function(r,o){return new ss(e,r,o,o?.fields.reduce((n,i)=>n&&i.notNull,!0)??!1)}}function Jme(e){return function(r,o){return new Fp(e,r,o)}}function P3(e,t,r){if(oe(r,ss)&&r.config)return{fields:r.config.fields,references:r.config.references};let o=t[ya(r.referencedTable)];if(!o)throw Error(`Table "${r.referencedTable[he.Symbol.Name]}" not found in schema`);let n=e[o];if(!n)throw Error(`Table "${o}" not found in schema`);let i=r.sourceTable,s=t[ya(i)];if(!s)throw Error(`Table "${i[he.Symbol.Name]}" not found in schema`);let a=[];for(let l of Object.values(n.relations))if(r.relationName&&r!==l&&l.relationName===r.relationName||!r.relationName&&l.referencedTable===r.sourceTable)a.push(l);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${o}"`):Error(`There are multiple relations between "${o}" and "${r.sourceTable[he.Symbol.Name]}". Please specify relation name`);if(a[0]&&oe(a[0],ss)&&a[0].config)return{fields:a[0].config.references,references:a[0].config.fields};throw Error(`There is not enough information to infer relation "${s}.${r.fieldName}"`)}function z3(e){return{one:Fme(e),many:Jme(e)}}function ob(e,t,r,o,n=(i)=>i){let i={};for(let[s,a]of o.entries())if(a.isJson){let l=t.relations[a.tsKey],u=r[s],d=typeof u==="string"?JSON.parse(u):u;i[a.tsKey]=oe(l,ss)?d&&ob(e,e[a.relationTableTsKey],d,a.selection,n):d.map((p)=>ob(e,e[a.relationTableTsKey],p,a.selection,n))}else{let l=n(r[s]),u=a.field,d;if(oe(u,He))d=u;else if(oe(u,Ee))d=u.decoder;else d=u.sql.decoder;i[a.tsKey]=l===null?null:d.mapFromDriverValue(l)}return i}var UT,T3,ss,Fp;var Jp=v(()=>{sr();En();$e();h3();ZT();Qt();UT=class UT{constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[he.Symbol.Name]}static[F]="Relation";referencedTableName;fieldName};T3=class T3{constructor(e,t){this.table=e,this.config=t}static[F]="Relations"};ss=class ss extends UT{constructor(e,t,r,o){super(e,t,r?.relationName);this.config=r,this.isNullable=o}static[F]="One";withFieldName(e){let t=new ss(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};Fp=class Fp extends UT{constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[F]="Many";withFieldName(e){let t=new Fp(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function Kp(e,t){return new Proxy(e,new Sa(t,!1))}function oo(e,t){return new Proxy(e,new Pl(new Proxy(e.table,new Sa(t,!1))))}function MT(e,t){return new Ee.Aliased(Hp(e.sql,t),e.fieldAlias)}function Hp(e,t){return C.join(e.queryChunks.map((r)=>{if(oe(r,He))return oo(r,t);if(oe(r,Ee))return Hp(r,t);if(oe(r,Ee.Aliased))return MT(r,t);return r}))}var Pl,Sa,Kme;var Vp=v(()=>{En();$e();Qt();sr();Mo();Pl=class Pl{constructor(e){this.table=e}static[F]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};Sa=class Sa{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[F]="TableAliasProxyHandler";get(e,t){if(t===he.Symbol.IsAlias)return!0;if(t===he.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===he.Symbol.OriginalName)return this.alias;if(t===pt)return{...e[pt],name:this.alias,isAlias:!0};if(t===he.Symbol.Columns){let o=e[he.Symbol.Columns];if(!o)return o;let n={};return Object.keys(o).map((i)=>{n[i]=new Proxy(o[i],new Pl(new Proxy(e,this)))}),n}let r=e[t];if(oe(r,He))return new Proxy(r,new Pl(new Proxy(e,this)));return r}};Kme=class Kme{constructor(e){this.alias=e}static[F]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return Kp(e.sourceTable,this.alias);return e[t]}}});var at;var va=v(()=>{Vp();En();$e();Qt();In();Mo();at=class at{static[F]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===pt)return{...e[pt],selectedFields:new Proxy(e[pt].selectedFields,this)};if(typeof t==="symbol")return e[t];let o=(oe(e,dt)?e._.selectedFields:oe(e,sn)?e[pt].selectedFields:e)[t];if(oe(o,Ee.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!o.isSelectionField)return o.sql;let n=o.clone();return n.isSelectionField=!0,n}if(oe(o,Ee)){if(this.config.sqlBehavior==="sql")return o;throw Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(oe(o,He)){if(this.config.alias)return new Proxy(o,new Pl(new Proxy(o.table,new Sa(this.config.alias,this.config.replaceOriginalName??!1))));return o}if(typeof o!=="object"||o===null)return o;return new Proxy(o,new at(this.config))}}});var vr;var Fo=v(()=>{$e();vr=class vr{static[F]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}});var qT,N3;var FT=v(()=>{$e();Ol();qT=class qT{static[F]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new N3(e,this)}};N3=class N3{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function JT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var D3,Hme,L3;var KT=v(()=>{$e();Ol();D3=class D3{constructor(e,t){this.name=t,this.columns=e}static[F]="SQLiteUniqueConstraintBuilder";columns;build(e){return new L3(e,this.columns,this.name)}};Hme=class Hme{static[F]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new D3(e,this.name)}};L3=class L3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??JT(this.table,this.columns.map((o)=>o.name))}static[F]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Zt,yt;var as=v(()=>{Vy();En();$e();FT();KT();Zt=class Zt extends Lp{static[F]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:"always",mode:t?.mode??"virtual"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>((n,i)=>{let s=new qT(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)})(r,o))}};yt=class yt extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=JT(e,[t.name]);super(e,t);this.table=e}static[F]="SQLiteColumn"}});function F3(e,t){let{name:r,config:o}=no(e,t);if(o?.mode==="json")return new Z3(r);if(o?.mode==="bigint")return new B3(r);return new M3(r)}var B3,j3,Z3,U3,M3,q3;var HT=v(()=>{$e();Sr();as();B3=class B3 extends Zt{static[F]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new j3(e,this.config)}};j3=class j3 extends yt{static[F]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return BigInt(t.toString("utf8"))}return BigInt(NT.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};Z3=class Z3 extends Zt{static[F]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new U3(e,this.config)}};U3=class U3 extends yt{static[F]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return JSON.parse(t.toString("utf8"))}return JSON.parse(NT.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};M3=class M3 extends Zt{static[F]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new q3(e,this.config)}};q3=class q3 extends yt{static[F]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function H3(e){return(t,r)=>{let{name:o,config:n}=no(t,r);return new J3(o,n,e)}}var J3,K3;var VT=v(()=>{$e();Sr();as();J3=class J3 extends Zt{static[F]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new K3(e,this.config)}};K3=class K3 extends yt{static[F]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(e,t){super(e,t);this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom==="function"?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo==="function"?this.mapTo(e):e}}});function ar(e,t){let{name:r,config:o}=no(e,t);if(o?.mode==="timestamp"||o?.mode==="timestamp_ms")return new G3(r,o.mode);if(o?.mode==="boolean")return new Y3(r,o.mode);return new V3(r)}var ib,sb,V3,W3,G3,Q3,Y3,X3;var WT=v(()=>{$e();Qt();Sr();as();ib=class ib extends Zt{static[F]="SQLiteBaseIntegerBuilder";constructor(e,t,r){super(e,t,r);this.config.autoIncrement=!1}primaryKey(e){if(e?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};sb=class sb extends yt{static[F]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};V3=class V3 extends ib{static[F]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new W3(e,this.config)}};W3=class W3 extends sb{static[F]="SQLiteInteger"};G3=class G3 extends ib{static[F]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(C`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new Q3(e,this.config)}};Q3=class Q3 extends sb{static[F]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(e){if(this.config.mode==="timestamp")return new Date(e*1000);return new Date(e)}mapToDriverValue(e){let t=e.getTime();if(this.config.mode==="timestamp")return Math.floor(t/1000);return t}};Y3=class Y3 extends ib{static[F]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new X3(e,this.config)}};X3=class X3 extends sb{static[F]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function s5(e,t){let{name:r,config:o}=no(e,t),n=o?.mode;return n==="number"?new r5(r):n==="bigint"?new o5(r):new e5(r)}var e5,t5,r5,n5,o5,i5;var GT=v(()=>{$e();Sr();as();e5=class e5 extends Zt{static[F]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new t5(e,this.config)}};t5=class t5 extends yt{static[F]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};r5=class r5 extends Zt{static[F]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new n5(e,this.config)}};n5=class n5 extends yt{static[F]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};o5=class o5 extends Zt{static[F]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new i5(e,this.config)}};i5=class i5 extends yt{static[F]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function l5(e){return new a5(e??"")}var a5,c5;var QT=v(()=>{$e();as();a5=class a5 extends Zt{static[F]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new c5(e,this.config)}};c5=class c5 extends yt{static[F]="SQLiteReal";getSQLType(){return"real"}}});function ft(e,t={}){let{name:r,config:o}=no(e,t);if(o.mode==="json")return new p5(r);return new u5(r,o)}var u5,d5,p5,f5;var YT=v(()=>{$e();Sr();as();u5=class u5 extends Zt{static[F]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new d5(e,this.config)}};d5=class d5 extends yt{static[F]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};p5=class p5 extends Zt{static[F]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new f5(e,this.config)}};f5=class f5 extends yt{static[F]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function m5(){return{blob:F3,customType:H3,integer:ar,numeric:s5,real:l5,text:ft}}var h5=v(()=>{HT();VT();WT();GT();QT();YT()});function Vme(e,t,r,o,n=e){let i=new At(e,o,n),s=typeof t==="function"?t(m5()):t,a=Object.fromEntries(Object.entries(s).map(([u,d])=>{let p=d;p.setName(u);let m=p.build(i);return i[XT].push(...p.buildForeignKeys(m,i)),[u,m]})),l=Object.assign(i,a);if(l[he.Symbol.Columns]=a,l[he.Symbol.ExtraConfigColumns]=a,r)l[At.Symbol.ExtraConfigBuilder]=r;return l}var XT,At,Wp=(e,t,r)=>Vme(e,t,r);var Jo=v(()=>{$e();sr();h5();XT=Symbol.for("drizzle:SQLiteInlineForeignKeys");At=class At extends he{static[F]="SQLiteTable";static Symbol=Object.assign({},he.Symbol,{InlineForeignKeys:XT});[he.Symbol.Columns];[XT]=[];[he.Symbol.ExtraConfigBuilder]=void 0}});var Wme,g5;var y5=v(()=>{$e();Wme=class Wme{constructor(e,t){this.name=e,this.value=t}static[F]="SQLiteCheckBuilder";brand;build(e){return new g5(e,this)}};g5=class g5{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[F]="SQLiteCheck";name;value}});function Ko(e){return new b5(e,!1)}var b5,S5,v5;var w5=v(()=>{$e();b5=class b5{constructor(e,t){this.name=e,this.unique=t}static[F]="SQLiteIndexBuilderOn";on(...e){return new S5(this.name,e,this.unique)}};S5=class S5{static[F]="SQLiteIndexBuilder";config;constructor(e,t,r){this.config={name:e,columns:t,unique:r,where:void 0}}where(e){return this.config.where=e,this}build(e){return new v5(this.config,e)}};v5=class v5{static[F]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var Gme,x5;var _5=v(()=>{$e();Jo();Gme=class Gme{static[F]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new x5(e,this.columns,this.name)}};x5=class x5{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[At.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function An(e){if(oe(e,At))return[`${e[he.Symbol.BaseName]}`];if(oe(e,dt))return e._.usedTables??[];if(oe(e,Ee))return e.usedTables??[];return[]}var zl=v(()=>{$e();Qt();In();sr();Jo()});var ab;var E5=v(()=>{$e();Fo();va();Jo();sr();Sr();zl();ab=class ab extends vr{constructor(e,t,r,o){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:o}}static[F]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[he.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[At.Symbol.Columns]){return this.config.returning=an(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:An(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(e){return this._prepare().execute(e)}$dynamic(){return this}}});function Qme(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function Yme(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,o,n)=>{let i=n===0?o.toLowerCase():`${o[0].toUpperCase()}${o.slice(1)}`;return r+i},"")}function Xme(e){return e}var e$;var I5=v(()=>{$e();sr();e$=class e${static[F]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Qme:e==="camelCase"?Yme:Xme}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[he.Symbol.Schema]??"public",r=e.table[he.Symbol.OriginalName],o=`${t}.${r}.${e.name}`;if(!this.cache[o])this.cacheTable(e.table);return this.cache[o]}cacheTable(e){let t=e[he.Symbol.Schema]??"public",r=e[he.Symbol.OriginalName],o=`${t}.${r}`;if(!this.cachedTables[o]){for(let n of Object.values(e[he.Symbol.Columns])){let i=`${o}.${n.name}`;this.cache[i]=this.convert(n.name)}this.cachedTables[o]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var Nl,Ho,t$;var cb=v(()=>{$e();Nl=class Nl extends Error{static[F]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};Ho=class Ho extends Error{constructor(e,t,r){super(`Failed query: ${e}
418
418
  params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrace(this,Ho),r)this.cause=r}};t$=class t$ extends Nl{static[F]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var k5=()=>{};var A5=()=>{};var R5=v(()=>{k5();A5()});var r$=v(()=>{ZT();R5();Qt()});var n$=v(()=>{HT();as();VT();WT();GT();QT();YT()});var Vo;var Gp=v(()=>{$e();Qt();Vo=class Vo extends sn{static[F]="SQLiteViewBase"}});var Dl,o$,i$;var lb=v(()=>{Vp();I5();En();$e();cb();Jp();r$();Qt();n$();Jo();In();sr();Sr();Mo();Gp();Dl=class Dl{static[F]="SQLiteDialect";casing;constructor(e){this.casing=new e$(e?.casing)}escapeName(e){return`"${e.replace(/"/g,'""')}"`}escapeParam(e){return"?"}escapeString(e){return`'${e.replace(/'/g,"''")}'`}buildWithCTE(e){if(!e?.length)return;let t=[C`with `];for(let[r,o]of e.entries())if(t.push(C`${C.identifier(o._.alias)} as (${o._.sql})`),r<e.length-1)t.push(C`, `);return t.push(C` `),C.join(t)}buildDeleteQuery({table:e,where:t,returning:r,withList:o,limit:n,orderBy:i}){let s=this.buildWithCTE(o),a=r?C` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,l=t?C` where ${t}`:void 0,u=this.buildOrderBy(i),d=this.buildLimit(n);return C`${s}delete from ${e}${l}${a}${u}${d}`}buildUpdateSet(e,t){let r=e[he.Symbol.Columns],o=Object.keys(r).filter((i)=>t[i]!==void 0||r[i]?.onUpdateFn!==void 0),n=o.length;return C.join(o.flatMap((i,s)=>{let a=r[i],l=a.onUpdateFn?.(),u=t[i]??(oe(l,Ee)?l:C.param(l,a)),d=C`${C.identifier(this.casing.getColumnCasing(a))} = ${u}`;if(s<n-1)return[d,C.raw(", ")];return[d]}))}buildUpdateQuery({table:e,set:t,where:r,returning:o,withList:n,joins:i,from:s,limit:a,orderBy:l}){let u=this.buildWithCTE(n),d=this.buildUpdateSet(e,t),p=s&&C.join([C.raw(" from "),this.buildFromTable(s)]),m=this.buildJoins(i),h=o?C` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,b=r?C` where ${r}`:void 0,y=this.buildOrderBy(l),S=this.buildLimit(a);return C`${u}update ${e} set ${d}${p}${m}${b}${h}${y}${S}`}buildSelection(e,{isSingleTable:t=!1}={}){let r=e.length,o=e.flatMap(({field:n},i)=>{let s=[];if(oe(n,Ee.Aliased)&&n.isSelectionField)s.push(C.identifier(n.fieldAlias));else if(oe(n,Ee.Aliased)||oe(n,Ee)){let a=oe(n,Ee.Aliased)?n.sql:n;if(t)s.push(new Ee(a.queryChunks.map((l)=>{if(oe(l,He))return C.identifier(this.casing.getColumnCasing(l));return l})));else s.push(a);if(oe(n,Ee.Aliased))s.push(C` as ${C.identifier(n.fieldAlias)}`)}else if(oe(n,He)){let a=n.table[he.Symbol.Name];if(n.columnType==="SQLiteNumericBigInt")if(t)s.push(C`cast(${C.identifier(this.casing.getColumnCasing(n))} as text)`);else s.push(C`cast(${C.identifier(a)}.${C.identifier(this.casing.getColumnCasing(n))} as text)`);else if(t)s.push(C.identifier(this.casing.getColumnCasing(n)));else s.push(C`${C.identifier(a)}.${C.identifier(this.casing.getColumnCasing(n))}`)}else if(oe(n,dt)){let a=Object.entries(n._.selectedFields);if(a.length===1){let l=a[0][1],u=oe(l,Ee)?l.decoder:oe(l,He)?{mapFromDriverValue:(d)=>l.mapFromDriverValue(d)}:l.sql.decoder;if(u)n._.sql.decoder=u}s.push(n)}if(i<r-1)s.push(C`, `);return s});return C.join(o)}buildJoins(e){if(!e||e.length===0)return;let t=[];if(e)for(let[r,o]of e.entries()){if(r===0)t.push(C` `);let n=o.table,i=o.on?C` on ${o.on}`:void 0;if(oe(n,At)){let s=n[At.Symbol.Name],a=n[At.Symbol.Schema],l=n[At.Symbol.OriginalName],u=s===l?void 0:o.alias;t.push(C`${C.raw(o.joinType)} join ${a?C`${C.identifier(a)}.`:void 0}${C.identifier(l)}${u&&C` ${C.identifier(u)}`}${i}`)}else t.push(C`${C.raw(o.joinType)} join ${n}${i}`);if(r<e.length-1)t.push(C` `)}return C.join(t)}buildLimit(e){return typeof e==="object"||typeof e==="number"&&e>=0?C` limit ${e}`:void 0}buildOrderBy(e){let t=[];if(e){for(let[r,o]of e.entries())if(t.push(o),r<e.length-1)t.push(C`, `)}return t.length>0?C` order by ${C.join(t)}`:void 0}buildFromTable(e){if(oe(e,he)&&e[he.Symbol.IsAlias])return C`${C`${C.identifier(e[he.Symbol.Schema]??"")}.`.if(e[he.Symbol.Schema])}${C.identifier(e[he.Symbol.OriginalName])} ${C.identifier(e[he.Symbol.Name])}`;return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:r,where:o,having:n,table:i,joins:s,orderBy:a,groupBy:l,limit:u,offset:d,distinct:p,setOperators:m}){let h=r??an(t);for(let T of h)if(oe(T.field,He)&&ts(T.field.table)!==(oe(i,dt)?i._.alias:oe(i,Vo)?i[pt].name:oe(i,Ee)?void 0:ts(i))&&!((B)=>s?.some(({alias:I})=>I===(B[he.Symbol.IsAlias]?ts(B):B[he.Symbol.BaseName])))(T.field.table)){let B=ts(T.field.table);throw Error(`Your "${T.path.join("->")}" field references a column "${B}"."${T.field.name}", but the table "${B}" is not part of the query! Did you forget to join it?`)}let b=!s||s.length===0,y=this.buildWithCTE(e),S=p?C` distinct`:void 0,x=this.buildSelection(h,{isSingleTable:b}),_=this.buildFromTable(i),A=this.buildJoins(s),O=o?C` where ${o}`:void 0,L=n?C` having ${n}`:void 0,z=[];if(l){for(let[T,B]of l.entries())if(z.push(B),T<l.length-1)z.push(C`, `)}let K=z.length>0?C` group by ${C.join(z)}`:void 0,P=this.buildOrderBy(a),W=this.buildLimit(u),ee=d?C` offset ${d}`:void 0,j=C`${y}select${S} ${x} from ${_}${A}${O}${K}${L}${P}${W}${ee}`;if(m.length>0)return this.buildSetOperations(j,m);return j}buildSetOperations(e,t){let[r,...o]=t;if(!r)throw Error("Cannot pass undefined values to any set operator");if(o.length===0)return this.buildSetOperationQuery({leftSelect:e,setOperator:r});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:r}),o)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:r,rightSelect:o,limit:n,orderBy:i,offset:s}}){let a=C`${e.getSQL()} `,l=C`${o.getSQL()}`,u;if(i&&i.length>0){let h=[];for(let b of i)if(oe(b,yt))h.push(C.identifier(b.name));else if(oe(b,Ee)){for(let y=0;y<b.queryChunks.length;y++){let S=b.queryChunks[y];if(oe(S,yt))b.queryChunks[y]=C.identifier(this.casing.getColumnCasing(S))}h.push(C`${b}`)}else h.push(C`${b}`);u=C` order by ${C.join(h,C`, `)}`}let d=typeof n==="object"||typeof n==="number"&&n>=0?C` limit ${n}`:void 0,p=C.raw(`${t} ${r?"all ":""}`),m=s?C` offset ${s}`:void 0;return C`${a}${p}${l}${u}${d}${m}`}buildInsertQuery({table:e,values:t,onConflict:r,returning:o,withList:n,select:i}){let s=[],a=e[he.Symbol.Columns],l=Object.entries(a).filter(([b,y])=>!y.shouldDisableInsert()),u=l.map(([,b])=>C.identifier(this.casing.getColumnCasing(b)));if(i){let b=t;if(oe(b,Ee))s.push(b);else s.push(b.getSQL())}else{let b=t;s.push(C.raw("values "));for(let[y,S]of b.entries()){let x=[];for(let[_,A]of l){let O=S[_];if(O===void 0||oe(O,Mr)&&O.value===void 0){let L;if(A.default!==null&&A.default!==void 0)L=oe(A.default,Ee)?A.default:C.param(A.default,A);else if(A.defaultFn!==void 0){let z=A.defaultFn();L=oe(z,Ee)?z:C.param(z,A)}else if(!A.default&&A.onUpdateFn!==void 0){let z=A.onUpdateFn();L=oe(z,Ee)?z:C.param(z,A)}else L=C`null`;x.push(L)}else x.push(O)}if(s.push(x),y<b.length-1)s.push(C`, `)}}let d=this.buildWithCTE(n),p=C.join(s),m=o?C` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,h=r?.length?C.join(r):void 0;return C`${d}insert into ${e} ${u} ${p}${h}${m}`}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:t})}buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:o,tableConfig:n,queryConfig:i,tableAlias:s,nestedQueryRelation:a,joinOn:l}){let u=[],d,p,m=[],h,b=[];if(i===!0)u=Object.entries(n.columns).map(([x,_])=>({dbKey:_.name,tsKey:x,field:oo(_,s),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let S=Object.fromEntries(Object.entries(n.columns).map(([z,K])=>[z,oo(K,s)]));if(i.where){let z=typeof i.where==="function"?i.where(S,$3()):i.where;h=z&&Hp(z,s)}let x=[],_=[];if(i.columns){let z=!1;for(let[K,P]of Object.entries(i.columns)){if(P===void 0)continue;if(K in n.columns){if(!z&&P===!0)z=!0;_.push(K)}}if(_.length>0)_=z?_.filter((K)=>i.columns?.[K]===!0):Object.keys(n.columns).filter((K)=>!_.includes(K))}else _=Object.keys(n.columns);for(let z of _){let K=n.columns[z];x.push({tsKey:z,value:K})}let A=[];if(i.with)A=Object.entries(i.with).filter((z)=>!!z[1]).map(([z,K])=>({tsKey:z,queryConfig:K,relation:n.relations[z]}));let O;if(i.extras){O=typeof i.extras==="function"?i.extras(S,{sql:C}):i.extras;for(let[z,K]of Object.entries(O))x.push({tsKey:z,value:MT(K,s)})}for(let{tsKey:z,value:K}of x)u.push({dbKey:oe(K,Ee.Aliased)?K.fieldAlias:n.columns[z].name,tsKey:z,field:oe(K,He)?oo(K,s):K,relationTableTsKey:void 0,isJson:!1,selection:[]});let L=typeof i.orderBy==="function"?i.orderBy(S,O3()):i.orderBy??[];if(!Array.isArray(L))L=[L];m=L.map((z)=>{if(oe(z,He))return oo(z,s);return Hp(z,s)}),d=i.limit,p=i.offset;for(let{tsKey:z,queryConfig:K,relation:P}of A){let W=P3(t,r,P),ee=ya(P.referencedTable),j=r[ee],T=`${s}_${z}`,B=tt(...W.fields.map((k,q)=>je(oo(W.references[q],T),oo(k,s)))),I=this.buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:e[j],tableConfig:t[j],queryConfig:oe(P,ss)?K===!0?{limit:1}:{...K,limit:1}:K,tableAlias:T,joinOn:B,nestedQueryRelation:P}),R=C`(${I.sql})`.as(z);u.push({dbKey:z,tsKey:z,field:R,relationTableTsKey:j,isJson:!0,selection:I.selection})}}if(u.length===0)throw new Nl({message:`No fields selected for table "${n.tsName}" ("${s}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let y;if(h=tt(l,h),a){let S=C`json_array(${C.join(u.map(({field:A})=>oe(A,yt)?C.identifier(this.casing.getColumnCasing(A)):oe(A,Ee.Aliased)?A.sql:A),C`, `)})`;if(oe(a,Fp))S=C`coalesce(json_group_array(${S}), json_array())`;let x=[{dbKey:"data",tsKey:"data",field:S.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:u}];if(d!==void 0||p!==void 0||m.length>0)y=this.buildSelectQuery({table:Kp(o,s),fields:{},fieldsFlat:[{path:[],field:C.raw("*")}],where:h,limit:d,offset:p,orderBy:m,setOperators:[]}),h=void 0,d=void 0,p=void 0,m=void 0;else y=Kp(o,s);y=this.buildSelectQuery({table:oe(y,At)?y:new dt(y,{},s),fields:{},fieldsFlat:x.map(({field:A})=>({path:[],field:oe(A,He)?oo(A,s):A})),joins:b,where:h,limit:d,offset:p,orderBy:m,setOperators:[]})}else y=this.buildSelectQuery({table:Kp(o,s),fields:{},fieldsFlat:u.map(({field:S})=>({path:[],field:oe(S,He)?oo(S,s):S})),joins:b,where:h,limit:d,offset:p,orderBy:m,setOperators:[]});return{tableTsKey:n.tsName,sql:y,selection:u}}};o$=class o$ extends Dl{static[F]="SQLiteSyncDialect";migrate(e,t,r){let o=r===void 0?"__drizzle_migrations":typeof r==="string"?"__drizzle_migrations":r.migrationsTable??"__drizzle_migrations",n=C`
419
419
  CREATE TABLE IF NOT EXISTS ${C.identifier(o)} (
420
420
  id SERIAL PRIMARY KEY,
@@ -427,7 +427,7 @@ params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrac
427
427
  hash text NOT NULL,
428
428
  created_at numeric
429
429
  )
430
- `;await t.run(n);let s=(await t.values(C`SELECT id, hash, created_at FROM ${C.identifier(o)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(a)=>{for(let l of e)if(!s||Number(s[2])<l.folderMillis){for(let u of l.sql)await a.run(C.raw(u));await a.run(C`INSERT INTO ${C.identifier(o)} ("hash", "created_at") VALUES(${l.hash}, ${l.folderMillis})`)}})}}});var s$;var T5=v(()=>{$e();s$=class s${static[F]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function ub(e,t){return(r,o,...n)=>{let i=[o,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of i)if(!Mp(r.getSelectedFields(),s.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return r.addSetOperators(i)}}var Rn,$5,a$,ehe=()=>({union:the,unionAll:rhe,intersect:nhe,except:ohe}),the,rhe,nhe,ohe;var c$=v(()=>{$e();T5();Fo();va();Qt();In();sr();Sr();Mo();zl();Gp();Rn=class Rn{static[F]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,r;if(this.fields)r=this.fields;else if(oe(e,dt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((o)=>[o,e[o]]));else if(oe(e,Vo))r=e[pt].selectedFields;else if(oe(e,Ee))r={};else r=eb(e);return new a$({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};$5=class $5 extends s${static[F]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:o,dialect:n,withList:i,distinct:s}){super();this.config={withList:i,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=r,this.session=o,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=qp(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of An(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let o=this.tableName,n=qp(t);for(let i of An(t))this.usedTables.add(i);if(typeof n==="string"&&this.config.joins?.some((i)=>i.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof o==="string")this.config.fields={[o]:this.config.fields};if(typeof n==="string"&&!oe(t,Ee)){let i=oe(t,dt)?t._.selectedFields:oe(t,sn)?t[pt].selectedFields:t[he.Symbol.Columns];this.config.fields[n]=i}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:r,table:t,joinType:e,alias:n}),typeof n==="string")switch(e){case"left":{this.joinsNotNullableMap[n]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[n]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[n]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,t){return(r)=>{let o=typeof r==="function"?r(ehe()):r;if(!Mp(this.getSelectedFields(),o.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:t,rightSelect:o}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=e,this}groupBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=r;else this.config.orderBy=r}else{let t=e;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=t;else this.config.orderBy=t}return this}limit(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=e;else this.config.limit=e;return this}offset(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=e;else this.config.offset=e;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...An(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...An(r.table));return new Proxy(new dt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new at({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};a$=class a$ extends $5{static[F]="SQLiteSelect";_prepare(e=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let t=an(this.config.fields),r=this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),t,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return r.joinsNotNullableMap=this.joinsNotNullableMap,r}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.all()}};c3(a$,[vr]);the=ub("union",!1),rhe=ub("union",!0),nhe=ub("intersect",!1),ohe=ub("except",!1)});var wa;var db=v(()=>{$e();va();lb();In();c$();wa=class wa{static[F]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=oe(e,Dl)?e:void 0,this.dialectConfig=oe(e,Dl)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new jp(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new Rn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function o(n){return new Rn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:o}}select(e){return new Rn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Rn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new o$(this.dialectConfig);return this.dialect}}});var pb,l$;var O5=v(()=>{$e();Fo();Qt();Jo();sr();Sr();zl();db();pb=class pb{constructor(e,t,r,o){this.table=e,this.session=t,this.dialect=r,this.withList=o}static[F]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error("values() must be called with at least one value");let t=e.map((r)=>{let o={},n=this.table[he.Symbol.Columns];for(let i of Object.keys(r)){let s=r[i];o[i]=oe(s,Ee)?s:new Mr(s,n[i])}return o});return new l$(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new wa):e;if(!oe(t,Ee)&&!Mp(this.table[Qy],t._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new l$(this.table,t,this.session,this.dialect,this.withList,!0)}};l$=class l$ extends vr{constructor(e,t,r,o,n,i){super();this.session=r,this.dialect=o,this.config={table:e,values:t,withList:n,select:i}}static[F]="SQLiteInsert";config;returning(e=this.config.table[At.Symbol.Columns]){return this.config.returning=an(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(C` on conflict do nothing`);else{let t=Array.isArray(e.target)?C`${e.target}`:C`${[e.target]}`,r=e.where?C` where ${e.where}`:C``;this.config.onConflict.push(C` on conflict ${t} do nothing${r}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let t=e.where?C` where ${e.where}`:void 0,r=e.targetWhere?C` where ${e.targetWhere}`:void 0,o=e.setWhere?C` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?C`${e.target}`:C`${[e.target]}`,i=this.dialect.buildUpdateSet(this.config.table,Xy(this.config.table,e.set));return this.config.onConflict.push(C` on conflict ${n}${r} do update set ${i}${t}${o}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:An(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var fb,C5;var P5=v(()=>{$e();Fo();va();Jo();In();sr();Sr();Mo();zl();Gp();fb=class fb{constructor(e,t,r,o){this.table=e,this.session=t,this.dialect=r,this.withList=o}static[F]="SQLiteUpdateBuilder";set(e){return new C5(this.table,Xy(this.table,e),this.session,this.dialect,this.withList)}};C5=class C5 extends vr{constructor(e,t,r,o,n){super();this.session=r,this.dialect=o,this.config={set:t,table:e,withList:n,joins:[]}}static[F]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let o=qp(t);if(typeof o==="string"&&this.config.joins.some((n)=>n.alias===o))throw Error(`Alias "${o}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?oe(t,At)?t[he.Symbol.Columns]:oe(t,dt)?t._.selectedFields:oe(t,Vo)?t[pt].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[he.Symbol.Columns],new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:o}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[he.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.config.table[At.Symbol.Columns]){return this.config.returning=an(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:An(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var u$=v(()=>{E5();O5();db();c$();P5()});var Qp;var z5=v(()=>{$e();Qt();Qp=class Qp extends Ee{constructor(e){super(Qp.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=Qp.buildCount(e.source,e.filters)}sql;static[F]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return C`(select count(*) from ${e}${C.raw(" where ").if(t)}${t})`}static buildCount(e,t){return C`select count(*) from ${e}${C.raw(" where ").if(t)}${t}`}then(e,t){return Promise.resolve(this.session.count(this.sql)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}}});var p$,mb,d$;var N5=v(()=>{$e();Fo();Jp();p$=class p${constructor(e,t,r,o,n,i,s,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=o,this.table=n,this.tableConfig=i,this.dialect=s,this.session=a}static[F]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new d$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new mb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new d$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new mb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};mb=class mb extends vr{constructor(e,t,r,o,n,i,s,a,l){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=o,this.tableConfig=n,this.dialect=i,this.session=s,this.config=a,this.mode=l}static[F]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:t,builtQuery:r}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](r,void 0,this.mode==="first"?"get":"all",!0,(o,n)=>{let i=o.map((s)=>ob(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return i[0];return i})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};d$=class d$ extends mb{static[F]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var Ll;var D5=v(()=>{$e();Fo();Ll=class Ll extends vr{constructor(e,t,r,o,n){super();this.execute=e,this.getSQL=t,this.dialect=o,this.mapBatchResult=n,this.config={action:r}}static[F]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}}});var Yp;var hb=v(()=>{$e();va();Qt();u$();In();z5();N5();D5();Yp=class Yp{constructor(e,t,r,o){this.resultKind=e,this.dialect=t,this.session=r,this._=o?{schema:o.schema,fullSchema:o.fullSchema,tableNamesMap:o.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let n=this.query;if(this._.schema)for(let[i,s]of Object.entries(this._.schema))n[i]=new p$(e,o.fullSchema,this._.schema,this._.tableNamesMap,o.fullSchema[i],s,t,r);this.$cache={invalidate:async(i)=>{}}}static[F]="BaseSQLiteDatabase";query;$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(new wa(r.dialect));return new Proxy(new jp(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new Qp({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Rn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function o(a){return new Rn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new fb(a,t.session,t.dialect,e)}function i(a){return new pb(a,t.session,t.dialect,e)}function s(a){return new ab(a,t.session,t.dialect,e)}return{select:r,selectDistinct:o,update:n,insert:i,delete:s}}select(e){return new Rn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Rn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new fb(e,this.session,this.dialect)}$cache;insert(e){return new pb(e,this.session,this.dialect)}delete(e){return new ab(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new Ll(async()=>this.session.run(t),()=>t,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(t)}all(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new Ll(async()=>this.session.all(t),()=>t,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(t)}get(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new Ll(async()=>this.session.get(t),()=>t,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(t)}values(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new Ll(async()=>this.session.values(t),()=>t,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values(t)}transaction(e,t){return this.session.transaction(e,t)}}});async function f$(e,t){let r=`${e}-${JSON.stringify(t)}`,n=new TextEncoder().encode(r),i=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(i)].map((l)=>l.toString(16).padStart(2,"0")).join("")}var L5,Xp;var m$=v(()=>{$e();L5=class L5{static[F]="Cache"};Xp=class Xp extends L5{strategy(){return"all"}static[F]="NoopCache";async get(e){return}async put(e,t,r,o){}async onMutate(e){}}});var B5=v(()=>{m$()});function gb(e,t){return new Proxy(e,new Sa(t,!1))}var j5=v(()=>{Vp()});var Z5,h$,g$,y$;var b$=v(()=>{m$();$e();cb();Fo();hb();Z5=class Z5 extends vr{constructor(e){super();this.resultCb=e}static[F]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};h$=class h${constructor(e,t,r,o,n,i){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=o,this.queryMetadata=n,this.cacheConfig=i,o&&o.strategy()==="all"&&i===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[F]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||oe(this.cache,Xp)||this.queryMetadata===void 0)try{return await r()}catch(o){throw new Ho(e,t,o)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(o){throw new Ho(e,t,o)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[o]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return o}catch(o){throw new Ho(e,t,o)}if(!this.cacheConfig)try{return await r()}catch(o){throw new Ho(e,t,o)}if(this.queryMetadata.type==="select"){let o=await this.cache.get(this.cacheConfig.tag??await f$(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(o===void 0){let n;try{n=await r()}catch(i){throw new Ho(e,t,i)}return await this.cache.put(this.cacheConfig.tag??await f$(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return o}try{return await r()}catch(o){throw new Ho(e,t,o)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw Error("Not implemented")}mapGetResult(e,t){throw Error("Not implemented")}execute(e){if(this.mode==="async")return this[this.executeMethod](e);return new Z5(()=>this[this.executeMethod](e))}mapResult(e,t){switch(this.executeMethod){case"run":return this.mapRunResult(e,t);case"all":return this.mapAllResult(e,t);case"get":return this.mapGetResult(e,t)}}};g$=class g${constructor(e){this.dialect=e}static[F]="SQLiteSession";prepareOneTimeQuery(e,t,r,o,n,i,s){return this.prepareQuery(e,t,r,o,n,i,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(r){throw new Nl({cause:r,message:`Failed to run the query '${t.sql}'`})}}extractRawRunValueFromBatchResult(e){return e}all(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(e){throw Error("Not implemented")}get(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(e){throw Error("Not implemented")}values(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).values()}async count(e){return(await this.values(e))[0][0]}extractRawValuesValueFromBatchResult(e){throw Error("Not implemented")}};y$=class y$ extends Yp{constructor(e,t,r,o,n=0){super(e,t,r,o);this.schema=o,this.nestedIndex=n}static[F]="SQLiteTransaction";rollback(){throw new t$}}});var S$,ihe,she,yb;var U5=v(()=>{$e();va();Sr();db();Jo();Gp();S$=class S${constructor(e){this.name=e}static[F]="SQLiteViewBuilderCore";config={}};ihe=class ihe extends S${static[F]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new wa);let t=new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new yb({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};she=class she extends S${static[F]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=eb(Wp(e,t))}existing(){return new Proxy(new yb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new yb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};yb=class yb extends Vo{static[F]="SQLiteView";constructor({config:e}){super(e)}}});var bb=v(()=>{j5();y5();n$();hb();lb();FT();w5();_5();u$();b$();Jo();KT();zl();U5()});function M5(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function Sb(e){if(typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer){if(typeof Buffer<"u"){if(!(e instanceof Buffer))return Buffer.from(e);return e}if(typeof TextDecoder<"u")return new TextDecoder().decode(e);throw Error("TextDecoder is not available. Please provide either Buffer or TextDecoder polyfill.")}return e}var vb,v$,q5;var w$=v(()=>{B5();$e();tb();Qt();bb();b$();Sr();vb=class vb extends g${constructor(e,t,r,o,n){super(t);this.client=e,this.schema=r,this.options=o,this.tx=n,this.logger=o.logger??new LT,this.cache=o.cache??new Xp}static[F]="LibSQLSession";logger;cache;prepareQuery(e,t,r,o,n,i,s){return new q5(this.client,e,this.logger,this.cache,i,s,t,this.tx,r,o,n)}async batch(e){let t=[],r=[];for(let n of e){let i=n._prepare(),s=i.getQuery();t.push(i),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,i)=>t[i].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let i=n._prepare(),s=i.getQuery();t.push(i),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,i)=>t[i].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),o=new vb(this.client,this.dialect,this.schema,this.options,r),n=new v$("async",this.dialect,o,this.schema);try{let i=await e(n);return await r.commit(),i}catch(i){throw await r.rollback(),i}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}};v$=class v$ extends y${static[F]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new v$("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(C.raw(`savepoint ${t}`));try{let o=await e(r);return await this.session.run(C.raw(`release savepoint ${t}`)),o}catch(o){throw await this.session.run(C.raw(`rollback to savepoint ${t}`)),o}}};q5=class q5 extends h${constructor(e,t,r,o,n,i,s,a,l,u,d){super("async",l,t,o,n,i);this.client=e,this.logger=r,this.fields=s,this.tx=a,this._isResponseInArrayMode=u,this.customResultMapper=d,this.customResultMapper=d,this.fields=s}static[F]="LibSQLPreparedQuery";async run(e){let t=Up(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return this.tx?this.tx.execute(r):this.client.execute(r)})}async all(e){let{fields:t,logger:r,query:o,tx:n,client:i,customResultMapper:s}=this;if(!t&&!s){let l=Up(o.params,e??{});return r.logQuery(o.sql,l),await this.queryWithCache(o.sql,l,async()=>{let u={sql:o.sql,args:l};return(n?n.execute(u):i.execute(u)).then(({rows:d})=>this.mapAllResult(d))})}let a=await this.values(e);return this.mapAllResult(a)}mapAllResult(e,t){if(t)e=e.rows;if(!this.fields&&!this.customResultMapper)return e.map((r)=>M5(r));if(this.customResultMapper)return this.customResultMapper(e,Sb);return e.map((r)=>zT(this.fields,Array.prototype.slice.call(r).map((o)=>Sb(o)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:o,tx:n,client:i,customResultMapper:s}=this;if(!t&&!s){let l=Up(o.params,e??{});return r.logQuery(o.sql,l),await this.queryWithCache(o.sql,l,async()=>{let u={sql:o.sql,args:l};return(n?n.execute(u):i.execute(u)).then(({rows:d})=>this.mapGetResult(d))})}let a=await this.values(e);return this.mapGetResult(a)}mapGetResult(e,t){if(t)e=e.rows;let r=e[0];if(!this.fields&&!this.customResultMapper)return M5(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,Sb);return zT(this.fields,Array.prototype.slice.call(r).map((o)=>Sb(o)),this.joinsNotNullableMap)}async values(e){let t=Up(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return(this.tx?this.tx.execute(r):this.client.execute(r)).then(({rows:o})=>o)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}});function Bl(e,t={}){let r=new i$({casing:t.casing}),o;if(t.logger===!0)o=new DT;else if(t.logger!==!1)o=t.logger;let n;if(t.schema){let a=C3(t.schema,z3);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let i=new vb(e,r,n,{logger:o,cache:t.cache},void 0),s=new F5("async",r,i,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var F5;var J5=v(()=>{$e();tb();Jp();hb();lb();w$();F5=class F5 extends Yp{static[F]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function wb(...e){if(typeof e[0]==="string"){let t=$l({url:e[0]});return Bl(t,e[1])}if(l3(e[0])){let{connection:t,client:r,...o}=e[0];if(r)return Bl(r,o);let n=typeof t==="string"?$l({url:t}):$l(t);return Bl(n,o)}return Bl(e[0],e[1])}var K5=v(()=>{_T();Sr();J5();((e)=>{function t(r){return Bl({},r)}e.mock=t})(wb||(wb={}))});var H5=v(()=>{K5();w$()});function ahe(){return new Promise((e)=>setTimeout(e,0))}function lhe(){if(x$)return;x$=!0,setTimeout(()=>{x$=!1,_$=performance.now()},0)}async function ef(e=che){if(lhe(),performance.now()-_$<e)return;await ahe(),_$=performance.now()}var che=50,_$,x$=!1;var V5=v(()=>{_$=performance.now()});function W5(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function fhe(e){return e instanceof Ce&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function xb(e,t){let r=Date.now()+(t.budgetMs??uhe),o=async(n)=>{if(t.isClosed())throw new Ce("The client is closed","CLIENT_CLOSED");try{return await e()}catch(i){if(t.isClosed()||!fhe(i))throw i;await t.afterRefusal?.();let s=Math.min(dhe*2**(n-1),phe),a=s/2+Math.random()*(s/2);if(t.isClosed()||Date.now()+a>=r)throw i;if(await new Promise((l)=>setTimeout(l,a)),t.isClosed()||Date.now()>=r)throw i;return o(n+1)}};return o(1)}function E$(e,t={}){let r=$l({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let o=r.transaction.bind(r),n=()=>r.closed,i=t.contentionRetryBudgetMs,s=r.execute.bind(r),a=r.batch.bind(r),l=r.migrate.bind(r),u={isClosed:n,budgetMs:i,afterRefusal:async()=>{await Promise.resolve(r.reconnect())}};async function d(p,m){return await ef(),xb(()=>typeof p==="string"?s(p,m):s(p),u)}r.execute=d,r.batch=async(p,m)=>(await ef(),xb(()=>a(p,m),u)),r.migrate=async(p)=>(await ef(),xb(()=>l(p),u)),r.transaction=async(p)=>(await ef(),xb(()=>o(p),u))}return r}function _b(e){let{url:t,schema:r}=e,o=W5(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},i=o?E$({url:t,authToken:o},n):E$({url:t},n);return{db:wb(i,{schema:r}),client:i,url:t}}async function Eb(e,t){if(!t.startsWith("file:"))return;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await e.execute(r)}var uhe=5000,dhe=5,phe=40;var I$=v(()=>{_T();H5();V5()});var G5=v(()=>{BR();I$()});var k$=v(()=>{I$();G5()});var A$=v(()=>{Vp();Vy();En();$e();cb();tb();Fo();Jp();r$();In();sr();Sr();Mo()});var Y,Me;var R$=v(()=>{bb();A$();fp();Y=Wp("job_queue",{id:ft("id").primaryKey().$defaultFn(()=>Do()),type:ft("type").notNull(),data:ft("data").notNull(),result:ft("result",{mode:"json"}),progress:ft("progress",{mode:"json"}).$type(),source:ft("source"),metadata:ft("metadata",{mode:"json"}).$type().notNull(),status:ft("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:ar("priority").notNull().default(0),retryCount:ar("retryCount").notNull().default(0),maxRetries:ar("maxRetries").notNull().default(3),lastError:ft("lastError"),lastErrorPublic:ft("lastErrorPublic",{mode:"json"}),createdAt:ar("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:ar("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:ar("startedAt"),completedAt:ar("completedAt"),attemptId:ft("attemptId"),workerSlotId:ft("workerSlotId"),workerSessionId:ft("workerSessionId"),leaseExpiresAt:ar("leaseExpiresAt"),attemptHeartbeatAt:ar("attemptHeartbeatAt"),runtimeUpdatedAt:ar("runtimeUpdatedAt"),brainVersion:ft("brainVersion"),brainVersionSortKey:ft("brainVersionSortKey")},(e)=>({queueReadyIdx:Ko("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:Ko("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:Ko("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:Ko("idx_job_queue_source").on(e.source),rootJobIdx:Ko("idx_job_queue_root_job").on(C`json_extract(${e.metadata}, '$.rootJobId')`,e.createdAt,e.id),deduplicationIdx:Ko("idx_job_queue_deduplication").on(e.type,C`json_extract(${e.metadata}, '$.deduplicationKey')`,e.status)})),Me=Wp("job_worker_sessions",{slotId:ft("slotId").primaryKey(),sessionId:ft("sessionId").notNull().unique(),startedAt:ar("startedAt").notNull(),heartbeatAt:ar("heartbeatAt").notNull(),expiresAt:ar("expiresAt").notNull().default(0),brainVersion:ft("brainVersion"),brainVersionSortKey:ft("brainVersionSortKey"),stableSlotId:ft("stableSlotId")},(e)=>({heartbeatIdx:Ko("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:Ko("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function Q5(e){return _b({url:e.url,schema:{jobQueue:Y,jobWorkerSessions:Me},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var Y5=v(()=>{k$();R$()});class T${declarations=new Map;handlers=new Map;validators=new Map;logger;mode;finalizedRegistrations;constructor(e,t){this.logger=e.child("HandlerRegistry"),this.mode=t}registerHandler(e,t,r){if(this.finalizedRegistrations)throw Error("Job handler registrations are finalized");if(this.declarations.has(e))throw Error(`Job handler is already registered for type: ${e}`);if(this.declarations.set(e,{handler:t,pluginId:r}),this.validators.set(e,t),this.mode!=="validation-only")this.handlers.set(e,t);this.logger.debug("Registered job execution declaration",{type:e,pluginId:r,mode:this.mode})}unregisterHandler(e){this.declarations.delete(e),this.handlers.delete(e),this.validators.delete(e),this.logger.debug("Unregistered job handler",{type:e})}unregisterPluginHandlers(e){let t=[...this.declarations.entries()].filter(([,r])=>r.pluginId===e).map(([r])=>r);for(let r of t)this.declarations.delete(r),this.handlers.delete(r),this.validators.delete(r);if(t.length>0)this.logger.debug("Unregistered plugin handlers",{pluginId:e,count:t.length,types:t})}finalizeRegistrations(){return this.finalizedRegistrations??=Object.freeze([...this.declarations.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>Object.freeze({type:e,pluginId:t.pluginId}))),this.finalizedRegistrations}getExecutionRegistrations(){return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getExclusiveTypes(){return[...this.handlers].filter(([,e])=>e.exclusive===!0).map(([e])=>e)}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}class $${tails=new Map;async run(e,t){let r=this.tails.get(e),o=()=>{},n=new Promise((i)=>{o=i});this.tails.set(e,n),await r;try{return await t()}finally{if(o(),this.tails.get(e)===n)this.tails.delete(e)}}}class O${findDuplicate(e,t,r){if(!t||t==="none")return null;let o=this.filterByDeduplicationKey(e,r).sort((i,s)=>s.createdAt-i.createdAt||s.id.localeCompare(i.id)),n=o.find((i)=>i.status===Oe.PENDING)??null;if(t==="skip"||t==="replace")return n;return n??o[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((r)=>{let o=mhe.safeParse(r.metadata);return o.success&&o.data.deduplicationKey===t})}}var mhe;var X5=v(()=>{pe();Lo();mhe=c.looseObject({deduplicationKey:c.string().optional()})});function r8(e){return`${String(e.length).padStart(2,"0")}${e}`}function ghe(e){return hhe.test(e)?`0${r8(e)}`:`1${e}`}function tf(e){let t=e8.exec(e);if(!t)throw Error(`Invalid brain version "${e}"`);let[,r="",o="",n="",i]=t,s=[r,o,n].map(r8).join("");return i===void 0?`${s}~`:`${s}-${i.split(".").map(ghe).join("!")}`}var e8,hhe,t8;var C$=v(()=>{pe();e8=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/u,hhe=/^\d+$/u,t8=c.string().regex(e8,"Brain version must be a semver version")});function n8(e){return JSON.stringify(new Oi(e).toJSON())}class P${db;transactionClient;databaseUrl;logger;deduplicator=new O$;writeRetryBudgetMs;constructor(e,t,r,o,n){this.db=e,this.transactionClient=t,this.databaseUrl=r,this.logger=o.child("JobQueueRepository"),this.writeRetryBudgetMs=n?.writeRetryBudgetMs??yhe}async insert(e){await this.write("insert",async()=>this.db.insert(Y).values(e))}async enqueueAtomic(e){return whe.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,r){let o=await this.runEnqueueTransaction(e,t,r);if(o.retry)return this.attemptEnqueue(e,t,r+1);return o.decision}async runEnqueueTransaction(e,t,r){let o=await this.acquireWriteTransaction(e,t),n={prepared:!1},i=!1;try{let s=await this.decideEnqueue(o,e,()=>{n.prepared=!0});return i=!0,await o.commit(),{retry:!1,decision:s}}catch(s){let a=i&&this.isSerializationConflict(s)&&!o.closed,l=!0;if(!o.closed)try{await o.rollback()}catch(u){l=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:u})}if(n.prepared)e.onInsertRollback?.();if(!a||!l)throw s;return await this.waitForConflictRetry("commit",e,t,r,s),{retry:!0}}finally{o.close()}}async decideEnqueue(e,t,r){let{jobData:o,strategy:n,deduplicationKey:i,beforeInsert:s}=t,a=n??"none",l=async()=>{await s?.(),r()},u=async()=>{await l(),await this.insertJob(e,o)};if(a==="none")return await u(),{kind:"inserted",jobId:o.id};let d=await this.getActiveDeduplicationCandidates(e,o.type,i),p=this.deduplicator.findDuplicate(d,a,i);if(!p)return await u(),{kind:"inserted",jobId:o.id};if(a==="skip")return await this.raiseBrainVersion(e,p.id,o),{kind:"skipped",jobId:p.id};if(a==="coalesce"){if(await this.raiseBrainVersion(e,p.id,o),(await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),p.id,p.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${p.id}`);return{kind:"coalesced",jobId:p.id}}await l();let m=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `lastErrorPublic` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[Oe.FAILED,"Replaced by newer job",n8("cancelled"),m,m,p.id,Oe.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${p.id}`);return await this.insertJob(e,o),{kind:"replaced",jobId:o.id,replacedJobId:p.id}}async getActiveDeduplicationCandidates(e,t,r){return(await e.execute(r?{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ?\n AND json_extract(`metadata`, '$.deduplicationKey') = ?\n AND `status` IN (?, ?)",args:[t,r,Oe.PENDING,Oe.PROCESSING]}:{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Oe.PENDING,Oe.PROCESSING]})).rows.map((n)=>this.parseDeduplicationCandidate(n))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:o,metadata:n}=e;if(typeof t!=="string"||r!==Oe.PENDING&&r!==Oe.PROCESSING||typeof o!=="number"&&typeof o!=="bigint"||typeof n!=="string")throw Error("Invalid active job row returned during atomic enqueue");let i=JSON.parse(n);return{id:t,status:r,createdAt:Number(o),metadata:i}}async raiseBrainVersion(e,t,r){if(!r.brainVersion)return;let o=tf(r.brainVersion);await e.execute({sql:"UPDATE `job_queue`\n SET `brainVersion` = ?, `brainVersionSortKey` = ?\n WHERE `id` = ?\n AND (`brainVersionSortKey` IS NULL OR `brainVersionSortKey` < ?)",args:[r.brainVersion,o,t,o]})}async insertJob(e,t){if((await e.execute({sql:"INSERT INTO `job_queue` (\n `id`, `type`, `data`, `result`, `source`, `metadata`,\n `status`, `priority`, `retryCount`, `maxRetries`,\n `lastError`, `createdAt`, `scheduledFor`, `startedAt`,\n `completedAt`, `brainVersion`, `brainVersionSortKey`\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",args:[t.id,t.type,t.data,this.serializeJson(t.result),t.source,JSON.stringify(t.metadata),t.status,t.priority,t.retryCount,t.maxRetries,t.lastError,t.createdAt,t.scheduledFor,t.startedAt,t.completedAt,t.brainVersion??null,t.brainVersion?tf(t.brainVersion):null]})).rowsAffected!==1)throw Error(`Atomic enqueue did not insert job ${t.id}`)}serializeJson(e){if(e===void 0||e===null)return null;return JSON.stringify(e)}acquireWriteTransaction(e,t){return this.retryOnConflict("acquire",e,()=>this.transactionClient.transaction("write"),(r)=>this.isSerializationConflict(r),t)}async waitForConflictRetry(e,t,r,o,n){let i=Math.min(bhe*2**(o-1),She),s=i/2+Math.random()*(i/2);if(Date.now()+s>=r)throw this.transactionConflictError(e,t,o,n);await new Promise((a)=>setTimeout(a,s))}async retryOnConflict(e,t,r,o,n=Date.now()+this.writeRetryBudgetMs,i=1){try{return await r()}catch(s){if(!o(s))throw s;return await this.waitForConflictRetry(e,t,n,i,s),this.retryOnConflict(e,t,r,o,n,i+1)}}transactionConflictError(e,t,r,o){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${r} attempts`,{cause:o});let n=t.strategy??"none",i=t.deduplicationKey?"present":"absent";return Error(`Failed to ${e} atomic enqueue transaction for type "${t.jobData.type}" within ${this.writeRetryBudgetMs}ms after ${r} attempts (strategy: ${n}, key: ${i})`,{cause:o})}write(e,t){return this.retryOnConflict("write",e,t,(r)=>{let o=new Set;for(let n=r;n!==void 0&&!o.has(n);){if(o.add(n),typeof n==="object"&&n!==null&&"code"in n&&/^SQLITE_(?:BUSY|LOCKED)(?:_|$)/u.test(String(n.code)))return!0;n=n instanceof Error?n.cause:void 0}return!1})}isSerializationConflict(e){for(let t=e;t!==void 0;){let r=typeof t==="object"&&t!==null&&"code"in t?String(t.code):"",o=Ve(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(r)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(o))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,r=Date.now(),o=Ji,n,i){let s=r+o,a={brainVersion:n??null,brainVersionSortKey:n?tf(n):null,stableSlotId:i??null};await this.write("start worker session",async()=>{await this.db.insert(Me).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:s,...a}).onConflictDoUpdate({target:Me.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:s,...a}}),await this.pruneDeadWorkerSessions(r,o)})}async heartbeatWorkerSession(e,t,r=Date.now(),o=Ji){return(await this.write("heartbeat worker session",async()=>{let i=await this.db.update(Me).set({heartbeatAt:r,expiresAt:r+o}).where(tt(je(Me.slotId,e),je(Me.sessionId,t))).returning({slotId:Me.slotId});return await this.pruneDeadWorkerSessions(r,o),i})).length===1}async pruneDeadWorkerSessions(e,t){let r=this.db.select({id:Y.id}).from(Y).where(tt(je(Y.workerSlotId,Me.slotId),je(Y.workerSessionId,Me.sessionId),je(Y.status,Oe.PROCESSING),kn(Y.leaseExpiresAt,e)));await this.db.delete(Me).where(tt(ns(Me.expiresAt,e-t),is(r)))}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(Me).where(tt(je(Me.slotId,e),je(Me.sessionId,t))).returning({slotId:Me.slotId}))).length===1}async complete(e,t,r){let o=Date.now(),i=(await this.write("complete",async()=>this.db.update(Y).set({status:Oe.COMPLETED,result:t,lastError:null,lastErrorPublic:null,completedAt:o,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o)}).where(this.attemptWriteGuard(e,r)).returning({id:Y.id}))).length===1;if(i)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return i}async update(e,t,r){let n=(await this.write("update",async()=>this.db.update(Y).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:Y.id}))).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,o=Date.now()){return(await this.write("record progress",async()=>this.db.update(Y).set({attemptHeartbeatAt:o,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async renewAttemptLease(e,t,r,o){return(await this.write("renew attempt lease",async()=>this.db.update(Y).set({attemptHeartbeatAt:r,leaseExpiresAt:r+o}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async release(e,t,r=Date.now()){return(await this.write("release",async()=>this.db.update(Y).set({status:Oe.PENDING,scheduledFor:r,startedAt:null,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async fail(e,t,r,o=Date.now()){let i=(await this.db.select({retryCount:Y.retryCount,maxRetries:Y.maxRetries,type:Y.type,scheduledFor:Y.scheduledFor,startedAt:Y.startedAt,runtimeUpdatedAt:Y.runtimeUpdatedAt}).from(Y).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!i)return!1;let s=i.retryCount<i.maxRetries,a=s?i.retryCount+1:i.retryCount,l=Math.min(1000*2**i.retryCount,60000),u=s?o+l:i.scheduledFor;if((await this.write("fail",async()=>this.db.update(Y).set({status:s?Oe.PENDING:Oe.FAILED,retryCount:a,lastError:t.message,lastErrorPublic:tg(t).toJSON(),scheduledFor:u,completedAt:s?null:o,runtimeUpdatedAt:s?i.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o),startedAt:s?null:i.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(tt(this.attemptWriteGuard(e,r),je(Y.retryCount,i.retryCount))).returning({id:Y.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:l,scheduledFor:new Date(u).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:i.type,retryCount:i.retryCount,error:t.message});return!0}async retireUnownedActiveJob(e){let t=e.reason.trim();if(t.length===0)throw Error("Retired job reason must not be empty");let o=(await this.write("retire unowned job",async()=>this.db.update(Y).set({status:Oe.FAILED,lastError:t,lastErrorPublic:new Oi("no_handler").toJSON(),completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(tt(je(Y.id,e.jobId),je(Y.type,e.expectedType),cn(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)),qr(Y.attemptId),qr(Y.workerSlotId),qr(Y.workerSessionId),qr(Y.leaseExpiresAt),qr(Y.attemptHeartbeatAt),qr(Y.progress),qr(Y.result))).returning()))[0]??null;if(o)this.logger.warn("Retired unowned legacy job",{jobId:o.id,type:o.type,reason:t});return o}async getStatus(e){return(await this.db.select().from(Y).where(je(Y.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(Y).where(C`json_extract(${Y.metadata}, '$.rootJobId') = ${e}`).orderBy(qo(Y.createdAt),qo(Y.id))}async getStatusByEntityId(e){return(await this.db.select().from(Y).where(C`json_extract(${Y.data}, '$.id') = ${e}`).orderBy(ba(Y.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:Y.status,count:C`count(*)`}).from(Y).groupBy(Y.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let o=Number(r.count);t[r.status]=o,t.total+=o}return t}async getDiagnostics(e=Date.now()){let[t,r,o]=await Promise.all([this.db.select({type:Y.type,status:Y.status,count:C`count(*)`}).from(Y).groupBy(Y.type,Y.status),this.db.select({oldestPendingAt:C`min(case when ${Y.status} = ${Oe.PENDING} then ${Y.createdAt} end)`,duePending:C`coalesce(sum(case when ${Y.status} = ${Oe.PENDING} and ${Y.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:C`min(case when ${Y.status} = ${Oe.PENDING} and ${Y.scheduledFor} <= ${e} then ${Y.scheduledFor} end)`,latestClaimAt:C`max(${Y.startedAt})`,oldestProcessingAt:C`min(case when ${Y.status} = ${Oe.PROCESSING} then ${Y.startedAt} end)`,staleLeaseCount:C`coalesce(sum(case when ${Y.status} = ${Oe.PROCESSING} and ${Y.leaseExpiresAt} is not null and ${Y.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(Y),this.db.select({total:C`count(*)`,active:C`coalesce(sum(case when ${Me.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:C`coalesce(sum(case when ${Me.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:C`max(${Me.heartbeatAt})`}).from(Me)]),n={pending:0,processing:0,completed:0,failed:0},i=t.map((u)=>{let d=Number(u.count);return n[u.status]+=d,{type:u.type,status:u.status,count:d}}),s=r[0],a=o[0],l=(u)=>u===null||u===void 0?null:Math.max(0,e-Number(u));return{totals:n,byType:i,oldestPendingAgeMs:l(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:l(s?.oldestDuePendingAt),latestClaimAgeMs:l(s?.latestClaimAt),oldestProcessingAgeMs:l(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(a?.total??0),active:Number(a?.active??0),stale:Number(a?.stale??0),latestHeartbeatAgeMs:l(a?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){let r=vhe.parse(t);if(r===0)return[];return(await this.db.select().from(Y).where(C`(${Y.runtimeUpdatedAt}, ${Y.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(qo(Y.runtimeUpdatedAt),qo(Y.id)).limit(r)).map((n)=>({job:n,cursor:{updatedAt:n.runtimeUpdatedAt??0,jobId:n.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.write("cleanup",async()=>this.db.delete(Y).where(tt(cn(je(Y.status,Oe.COMPLETED),je(Y.status,Oe.FAILED)),ns(Y.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=cn(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)),r=e&&e.length>0?tt(t,os(Y.type,e)):t;return this.db.select().from(Y).where(r).orderBy(ba(Y.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?os(Y.type,e):void 0;return this.db.select().from(Y).where(r).orderBy(ba(Y.createdAt)).limit(t)}async getFailedJobs(e){let t=je(Y.status,Oe.FAILED),r=e&&e.length>0?tt(t,os(Y.type,e)):t;return this.db.select().from(Y).where(r).orderBy(ba(Y.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:o,workerSessionId:n,leaseDurationMs:i,executableTypes:s,exclusiveTypes:a=[],brainVersion:l}=e,u=l?this.brainVersionGate(l,t):{admissible:void 0,noNewerWorker:void 0},d=this.db.select({slotId:Me.slotId}).from(Me).where(tt(je(Me.slotId,o),je(Me.sessionId,n),kn(Me.expiresAt,t))),p=this.noNewerLiveInstance(o,n,t),m=this.db.select({slotId:Me.slotId}).from(Me).where(tt(je(Me.slotId,Y.workerSlotId),je(Me.sessionId,Y.workerSessionId))),h=tt(je(Y.status,Oe.PROCESSING),cn(qr(Y.attemptId),is(m),ns(Y.leaseExpiresAt,t))),b=gb(Y,"running"),y=this.db.select({id:b.id}).from(b).where(tt(je(b.type,Y.type),je(b.status,Oe.PROCESSING),kn(b.leaseExpiresAt,t),C`${b.id} <> ${Y.id}`)),S=a.length===0?void 0:cn(rb(Y.type,[...a]),is(y)),x=C`${Y.status} = ${Oe.PROCESSING} AND ${Y.retryCount} + 1 > ${Y.maxRetries}`,_=this.db.select({id:Y.id}).from(Y).where(tt(os(Y.type,s),S,u.admissible,cn(tt(je(Y.status,Oe.PENDING),ns(Y.scheduledFor,t)),h))).orderBy(qo(Y.priority),qo(Y.createdAt)).limit(1),O=(await this.write("claim",async()=>this.db.update(Y).set({status:C`CASE WHEN ${x} THEN ${Oe.FAILED} ELSE ${Oe.PROCESSING} END`,retryCount:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN ${Y.retryCount} + 1 ELSE ${Y.retryCount} END`,lastError:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN 'Attempt lease expired' ELSE ${Y.lastError} END`,lastErrorPublic:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN ${n8("deadline_exceeded")} ELSE ${Y.lastErrorPublic} END`,startedAt:C`CASE WHEN ${x} THEN ${Y.startedAt} ELSE ${t} END`,completedAt:C`CASE WHEN ${x} THEN ${t} ELSE NULL END`,attemptId:C`CASE WHEN ${x} THEN ${Y.attemptId} ELSE ${r} END`,workerSlotId:C`CASE WHEN ${x} THEN ${Y.workerSlotId} ELSE ${o} END`,workerSessionId:C`CASE WHEN ${x} THEN ${Y.workerSessionId} ELSE ${n} END`,leaseExpiresAt:C`CASE WHEN ${x} THEN ${Y.leaseExpiresAt} ELSE ${t+i} END`,attemptHeartbeatAt:C`CASE WHEN ${x} THEN ${Y.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:C`CASE WHEN ${x} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${Y.runtimeUpdatedAt} END`}).where(tt(os(Y.id,_),nb(d),p,u.noNewerWorker)).returning()))[0];if(!O)return null;if(O.status===Oe.FAILED)return O;return this.logger.debug("Job claimed",{jobId:O.id,attemptId:O.attemptId,workerSlotId:o,workerSessionId:n}),O}noNewerLiveInstance(e,t,r){let o=gb(Me,"claimer"),n=gb(Me,"peer"),i=this.db.select({slotId:n.slotId}).from(n).innerJoin(o,tt(je(o.slotId,e),je(o.sessionId,t))).where(tt(je(n.stableSlotId,o.stableSlotId),kn(n.expiresAt,r),cn(kn(n.startedAt,o.startedAt),tt(je(n.startedAt,o.startedAt),kn(n.slotId,o.slotId)))));return is(i)}brainVersionGate(e,t){let r=tf(e),o=this.db.select({slotId:Me.slotId}).from(Me).where(tt(kn(Me.expiresAt,t),kn(Me.brainVersionSortKey,r)));return{admissible:cn(qr(Y.brainVersionSortKey),ns(Y.brainVersionSortKey,r)),noNewerWorker:is(o)}}nextRuntimeUpdatedAt(e){return C`max(${e}, coalesce((select max(${Y.runtimeUpdatedAt}) from ${Y}), 0) + 1)`}attemptWriteGuard(e,t){return t?tt(je(Y.id,e),je(Y.status,Oe.PROCESSING),je(Y.attemptId,t)):tt(je(Y.id,e),qr(Y.attemptId),cn(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)))}}var yhe=2000,bhe=5,She=40,vhe,whe;var o8=v(()=>{A$();bb();R$();Ot();pe();Lo();hp();X5();C$();vhe=c.number().int().min(0).max(1000),whe=new $$});import{AsyncLocalStorage as xhe}from"async_hooks";class jl{storage=new xhe;static createFresh(){return new jl}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let o=ko.parse(e),n=_he(o);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function _he(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var Ib=v(()=>{Ot()});class rf{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${Do()}`;directWorkerSessionId=Do();directLeaseDurationMs;directSessionStart=null;brainVersion;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new rf(e,t??Rr.getInstance(),r)}constructor(e,t,r){this.brainVersion=e.brainVersion===void 0?void 0:t8.parse(e.brainVersion);let{db:o,client:n,url:i}=Q5(e);this.client=n,this.databaseUrl=i,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??jl.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new T$(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new P$(o,n,i,this.logger),this.directLeaseDurationMs=e.claimTimeoutMs??300000}initialize(){if(this.closeRequested)return Promise.resolve();return this.walInitialization??=this.initializeWALMode(),this.walInitialization}async initializeWALMode(){try{await Eb(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable WAL mode (non-fatal)",e)}finally{this.walInitializationSettled=!0,this.closeClientWhenReady()}}closeClientWhenReady(){if(!this.closeRequested||this.inFlightEnqueues>0||this.walInitialization!==null&&!this.walInitializationSettled)return;this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}registerHandler(e,t,r){this.handlerRegistry.registerHandler(e,t,r)}unregisterHandler(e){this.handlerRegistry.unregisterHandler(e)}unregisterPluginHandlers(e){this.handlerRegistry.unregisterPluginHandlers(e)}getRegisteredTypes(){return this.handlerRegistry.getRegisteredTypes()}getHandler(e){return this.handlerRegistry.getHandler(e)}getValidator(e){return this.handlerRegistry.getValidator(e)}finalizeHandlerRegistrations(){return this.handlerRegistry.finalizeRegistrations()}getExecutionRegistrations(){return this.handlerRegistry.getExecutionRegistrations()}async enqueue(e){if(this.closeRequested)throw Error("Cannot enqueue a job after the queue service is closed");this.inFlightEnqueues++;try{return await this.enqueueValidated(e)}finally{this.inFlightEnqueues--,this.closeClientWhenReady()}}async enqueueValidated(e){let{type:t,data:r,options:o}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let i=n.validateAndParse(r);if(i===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=Do(),l=o?.rootJobId??(o?.detached?a:this.operationContext.current()?.provenance.rootJobId)??a,u=this.createJobProvenance(a,l,o),d=o?.metadata??{operationType:"data_processing"},{provenance:p,...m}=d,h={id:a,type:t,data:JSON.stringify(i),status:Oe.PENDING,priority:o?.priority??0,maxRetries:o?.maxRetries??3,retryCount:0,source:o?.source??null,metadata:{...m,...o?.deduplicationKey&&{deduplicationKey:o.deduplicationKey},rootJobId:l,provenance:u},createdAt:s,scheduledFor:o?.delayMs?s+o.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null,brainVersion:this.brainVersion},b,y=()=>{b?.rollback(),b=void 0};try{let S=await this.repository.enqueueAtomic({jobData:h,strategy:o?.deduplication,deduplicationKey:o?.deduplicationKey,beforeInsert:async()=>{b=await this.projectionAdmission?.reserveJobAdmission(u)},onInsertRollback:y});if(b?.commit(),b=void 0,S.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:S.jobId});else if(S.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:S.jobId});else{if(S.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:S.replacedJobId});this.logger.debug("Job enqueued",{id:S.jobId,type:t,priority:h.priority,rootJobId:h.metadata.rootJobId})}return S.jobId}catch(S){throw y(),this.logger.error("Failed to enqueue job",{type:t,error:Ve(S)}),S}}createJobProvenance(e,t,r){let o=this.operationContext.current(),n=r?.metadata.provenance??o?.provenance,i=n?.rootJobId===t?n:void 0,s=o?.provenance.rootJobId===t?o.operationId:void 0,a=r?.projection,l=a?[...i?.projectionLineage??[],a.id]:[...i?.projectionLineage??[]],u=a?.id??i?.projectionId;return ko.parse({rootJobId:t,causationId:s??i?.causationId??e,...u?{projectionId:u}:{},projectionLineage:l,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:i?.sourceEntity?{sourceEntity:i.sourceEntity}:{},derivationDepth:l.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let{onTerminalReclaim:r,...o}=e??await this.getDirectClaimOptions(),n=Date.now(),i=await this.repository.claimNextReady({...o,workerSlotId:this.sessionSlotId(o.workerSlotId,o.workerSessionId),brainVersion:this.brainVersion,now:n,attemptId:Do(),executableTypes:t,exclusiveTypes:this.handlerRegistry.getExclusiveTypes()});if(!i)return null;if(i.status===Oe.FAILED)return this.logger.warn("Expired attempt failed terminally on reclaim",{id:i.id,type:i.type,retryCount:i.retryCount}),await r?.(i),null;return this.logger.debug("Job dequeued",{id:i.id,type:i.type,priority:i.priority,retryCount:i.retryCount,attemptId:i.attemptId,workerSlotId:i.workerSlotId,workerSessionId:i.workerSessionId}),i}async startWorkerSession(e,t,r=Ji){await this.repository.startWorkerSession(this.sessionSlotId(e,t),t,Date.now(),r,this.brainVersion,this.versionedSlotId(e))}heartbeatWorkerSession(e,t,r=Ji){return this.repository.heartbeatWorkerSession(this.sessionSlotId(e,t),t,Date.now(),r)}endWorkerSession(e,t){return this.repository.endWorkerSession(this.sessionSlotId(e,t),t)}versionedSlotId(e){return this.brainVersion?`${e}@${this.brainVersion}`:e}sessionSlotId(e,t){return`${this.versionedSlotId(e)}#${t}`}renewAttemptLease(e,t,r){return this.repository.renewAttemptLease(e,t,Date.now(),r)}recordAttemptProgress(e,t,r){return this.repository.recordAttemptProgress(e,t,r)}complete(e,t,r){return this.repository.complete(e,t,r)}update(e,t,r){return this.repository.update(e,t,r)}fail(e,t,r){return this.repository.fail(e,t,r)}release(e,t){return this.repository.release(e,t)}retireUnownedActiveJob(e){return this.repository.retireUnownedActiveJob(e)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.sessionSlotId(this.directWorkerSlotId,this.directWorkerSessionId),this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs,this.brainVersion),await this.directSessionStart,{workerSlotId:this.directWorkerSlotId,workerSessionId:this.directWorkerSessionId,leaseDurationMs:this.directLeaseDurationMs}}async getStatus(e){return this.repository.getStatus(e)}async getJobsByRootJobId(e){return this.repository.getJobsByRootJobId(e)}async getStatusByEntityId(e){return this.repository.getStatusByEntityId(e)}async getStats(){return this.repository.getStats()}getDiagnostics(e){return this.repository.getDiagnostics(e)}async waitForIdle(e={}){let t=e.quietMs??250,r=e.pollIntervalMs??25,o=Date.now()+(e.timeoutMs??30000),n=async(i)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),l=s.pending===0&&s.processing===0?i??Date.now():null;if(l!==null&&Date.now()-l>=t)return;if(Date.now()>=o)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(r),n(l)};return n(null)}getRuntimeUpdates(e,t=1000){return this.repository.getRuntimeUpdates(e,t)}async cleanup(e){let t=await this.repository.cleanup(e);if(t>0)this.logger.info("Cleaned up old jobs",{deletedCount:t,olderThanMs:e});return t}async getActiveJobs(e){return this.repository.getActiveJobs(e)}async getRecentJobs(e,t){return this.repository.getRecentJobs(e,t)}async getFailedJobs(e){return this.repository.getFailedJobs(e)}}var i8=v(()=>{fp();BR();hp();Lo();k$();Y5();o8();Ot();Ib();C$()});var z$=()=>{};var s8=v(()=>{fp();Lo();hp();Lo();z$();Ib()});var a8=v(()=>{Lo();z$()});var kb,c8;var N$=v(()=>{pe();kb=c.object({success:c.boolean(),data:c.unknown().optional(),error:c.string().optional(),code:c.string().optional()}),c8=c.object({id:c.string().min(1),timestamp:c.string(),type:c.string().min(1),source:c.string().min(1),target:c.string().optional(),metadata:c.record(c.string(),c.unknown()).optional()})});var d3e;var l8=v(()=>{pe();N$();d3e=c.union([c.object({noop:c.literal(!0)}),kb])});var Ab=v(()=>{l8()});var u8=v(()=>{Ab()});var d8=v(()=>{Ab()});var p8=v(()=>{d8()});var T3e;var D$=v(()=>{pe();T3e=c.looseObject({issues:c.array(c.looseObject({message:c.string()})).optional()})});var f8=v(()=>{u8();Ab();p8();D$();Ot();Ib()});var Phe;var m8=v(()=>{pe();N$();Phe=c.object({id:c.string().min(1),requestId:c.string().min(1),success:c.boolean(),data:c.unknown().optional(),error:c.object({message:c.string(),code:c.string().optional()}).optional(),timestamp:c.string().datetime()})});var H3e;var h8=v(()=>{Ot();H3e=new Oi("invalid_response").toJSON()});var g8=v(()=>{f8();m8();D$();h8()});var p5e;var y8=v(()=>{pe();g8();mp();Lo();p5e=c.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},c.record(c.string(),c.unknown()))});var h5e;var b8=v(()=>{pe();h5e=c.record(c.string(),c.unknown())});var S8=v(()=>{Ot();fp()});var v8=v(()=>{i8();s8();a8();y8();b8();hp();Lo();mp();S8()});var L$={};Lt(L$,{LEGACY_PROJECTION_JOB_TYPES:()=>x8,LEGACY_PROJECTION_RETIREMENT_REASON:()=>E8,legacyProjectionJobTypeSchema:()=>_8,retireLegacyProjectionJob:()=>Bhe});import{existsSync as Nhe}from"fs";import{resolve as Dhe}from"path";function w8(e){return{id:e.id,type:e.type,status:e.status,retryCount:e.retryCount,maxRetries:e.maxRetries,createdAt:e.createdAt,startedAt:e.startedAt,completedAt:e.completedAt}}function Lhe(e,t){if(e.type!==t)throw Error(`Job ${e.id} has type ${e.type}; expected ${t}`);if(e.status!=="pending"&&e.status!=="processing")throw Error(`Job ${e.id} is already terminal (${e.status})`);if(e.attemptId!==null||e.workerSlotId!==null||e.workerSessionId!==null||e.leaseExpiresAt!==null||e.attemptHeartbeatAt!==null)throw Error(`Job ${e.id} still has attempt ownership`);if(e.progress!==null||e.result!=null)throw Error(`Job ${e.id} contains partial progress or a result`)}async function Bhe(e){let t=Dhe(e.databasePath);if(!Nhe(t))throw Error(`Job database does not exist: ${t}`);let r=_8.parse(e.jobType),o=rf.createFresh({url:`file:${t}`});try{let n=await o.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(Lhe(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:w8(n),retired:!1}}let i=`retire:${n.id}`;if(e.confirmation!==i)throw Error(`Refusing to retire ${n.id}; expected --confirm ${i}`);let s=await o.retireUnownedActiveJob({jobId:n.id,expectedType:r,reason:E8,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:w8(s),retired:!0}}finally{o.close()}}var x8,_8,E8="Retired legacy projection job superseded by scheduler-owned projections";var B$=v(()=>{v8();pe();x8=["conversation-memory:project","skill:project","swot:derive","topic:project"],_8=c.enum(x8)});function Ut(e,t,r,o,n){return k8.parse({id:e,operation:t,count:r,targetProbeCount:o,settleMs:n})}function $8(e){return $b.parse(structuredClone(qhe[e]))}function Ob(e){let t=`stress:${e.handle}`;if(e.confirmation!==t)throw Error(`Directory-sync stress requires --confirm ${t}`);let r=/(^|[-_.])smoke($|[-_.])/i;if(!r.test(e.handle)||!r.test(e.domain)||!r.test(e.contentRepo))throw Error("Directory-sync stress is smoke-only; handle, domain, and content repository must all identify smoke")}async function Z$(e,t={}){let r=t.fetchImpl??fetch,o=t.now??(()=>new Date),n=t.timeoutMs??20000,i=o(),s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let l=await r(e,{method:"GET",signal:s.signal});return await l.arrayBuffer(),j$.parse({timestamp:i.toISOString(),endpoint:new URL(e).pathname,status:l.status,durationMs:Math.max(0,o().getTime()-i.getTime()),ok:l.ok})}catch(l){return j$.parse({timestamp:i.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,o().getTime()-i.getTime()),ok:!1,error:Jhe(l)})}finally{clearTimeout(a)}}async function O8(e,t){let r=$b.parse(e),o=[],n,i=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(l){n=`monitor: ${Rb(l)}`}if(!n)for(let l of r.phases)try{let u=A8.parse(await t.executePhase(l,i));if(o.push(u),!u.success){n=`${l.id}: ${u.error??"phase failed"}`;break}}catch(u){let d=Rb(u);o.push({id:l.id,operation:l.operation,count:l.count,success:!1,error:d}),n=`${l.id}: ${d}`;break}}finally{try{if(s=R8.parse(await t.cleanup(i)),!s.success&&!n)n=s.error??"cleanup failed"}catch(l){let u=Rb(l);s={success:!1,probesRemaining:0,error:u},n??=`cleanup: ${u}`}try{a=T8.parse(await t.stopMonitoring())}catch(l){let u=Rb(l);a={health:[],runtime:[]},n??=`monitor: ${u}`}}return n??=Fhe(a,r.maximumExternalAiCalls??0),Mhe.parse({profile:r.profile,success:n===void 0&&o.length===r.phases.length&&s.success,baseline:i,phases:o,cleanup:s,metrics:a,...n?{failure:n}:{}})}function Fhe(e,t=0){let r=e.health.find((i)=>!i.ok);if(r)return`health: ${r.endpoint} unavailable`;let o=e.externalAiCalls??0;if(o>t)return t===0?`external AI: observed ${o} call(s)`:`external AI: observed ${o} call(s), cap ${t}`;if(e.container?.oomKilled)return"container: OOM killed";let n=e.container?.restartCount??0;if(n>0)return`container: restarted ${n} time(s)`;if(e.container&&e.container.status!=="running")return`container: ${e.container.status}`;return}function Jhe(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function Rb(e){return Ve(e)}var Tb,I8,k8,$b,jhe,j$,Zhe,A8,R8,Uhe,T8,Mhe,qhe;var U$=v(()=>{pe();Tb=c.enum(["regression","load","stress"]),I8=c.enum(["add","update","rename","delete"]),k8=c.object({id:c.string().min(1),operation:I8,count:c.number().int().positive().max(700),targetProbeCount:c.number().int().min(0).max(700),settleMs:c.number().int().nonnegative().max(300000)}),$b=c.object({profile:Tb,maximumProbeCount:c.number().int().positive().max(700),maximumExternalAiCalls:c.number().int().nonnegative().max(1e4).optional(),phases:c.array(k8).min(1)}),jhe=c.object({entities:c.number().int().nonnegative(),notes:c.number().int().nonnegative(),version:c.string().min(1)}),j$=c.object({timestamp:c.iso.datetime(),endpoint:c.string().startsWith("/"),status:c.number().int().nonnegative(),durationMs:c.number().nonnegative(),ok:c.boolean(),error:c.string().optional()}),Zhe=c.object({timestamp:c.iso.datetime(),cpuPercent:c.number().nonnegative(),memoryPercent:c.number().nonnegative(),pids:c.number().int().nonnegative()}),A8=c.object({id:c.string().min(1),operation:I8,count:c.number().int().positive(),success:c.boolean(),commitLatencyMs:c.number().nonnegative().optional(),persistenceLatencyMs:c.number().nonnegative().optional(),error:c.string().optional()}),R8=c.object({success:c.boolean(),probesRemaining:c.number().int().nonnegative(),finalEntities:c.number().int().nonnegative().optional(),finalNotes:c.number().int().nonnegative().optional(),contentTreeRestored:c.boolean().optional(),error:c.string().optional()}),Uhe=c.object({status:c.string(),restartCount:c.number().int().nonnegative(),oomKilled:c.boolean()}),T8=c.object({health:c.array(j$),runtime:c.array(Zhe),externalAiCalls:c.number().int().nonnegative().optional(),container:Uhe.optional()}),Mhe=c.object({profile:Tb,success:c.boolean(),baseline:jhe,phases:c.array(A8),cleanup:R8,metrics:T8,failure:c.string().optional()}),qhe={regression:{profile:"regression",maximumProbeCount:20,phases:[Ut("add20","add",20,20,0),Ut("update20","update",20,20,30000),Ut("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[Ut("add50","add",50,50,0),Ut("add150","add",100,150,0),Ut("add350","add",200,350,0),Ut("update350a","update",350,350,45000),Ut("rename100","rename",100,350,45000),Ut("update350b","update",350,350,45000),Ut("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[Ut("add50","add",50,50,0),Ut("add150","add",100,150,0),Ut("add350","add",200,350,0),Ut("add700","add",350,700,0),Ut("update700a","update",700,700,45000),Ut("rename200","rename",200,700,45000),Ut("update700b","update",700,700,45000),Ut("delete700","delete",700,0,150000)]}}});import{spawn as Khe}from"child_process";async function C8(e,t,r,o){let n=await e(t,r,o);if(n.exitCode!==0)throw io(t,r,n);return n}function io(e,t,r){let o=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${o?`: ${o}`:""}`)}var Wo=async(e,t,r={})=>new Promise((o,n)=>{let i=Khe(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",(l)=>{s+=l}),i.stderr.on("data",(l)=>{a+=l}),i.on("error",n),i.on("close",(l)=>{o({exitCode:l??1,stdout:s,stderr:a})}),i.stdin.end(r.stdin)});var nf=()=>{};class Zl{#e;#t;dir;constructor(e,t,r){this.#e=e,this.dir=t,this.#t=r}static async clone(e,t,r,o){let n=new Zl(e,r,o);return await C8(e,"git",["-c","credential.helper=","-c",`credential.helper=${P8}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",P8]),await n.run(["reset","--hard","origin/main"]),n}async run(e,t=!0){let r=await this.#e("git",e,{cwd:this.dir,env:this.environment()});if(t&&r.exitCode!==0)throw io("git",e,r);return r}async output(e){return(await this.run(e)).stdout.trim()}async sync(e=!1){if(await this.run(["fetch","origin","main"]),e)await this.run(["reset","--hard","origin/main"]);else await this.run(["pull","--rebase","origin","main"])}async commitAll(e){await this.run(["add","-A"]),await this.run(["-c","user.name=brains-ops","-c","user.email=ops@rizom.ai","commit","-m",e])}async pushMainWithRebase(){for(let e=1;e<=5;e+=1){if((await this.run(["push","origin","main"],!1)).exitCode===0)return;await this.run(["pull","--rebase","origin","main"])}throw Error("Unable to push content main after five rebase attempts")}async pruneStressBackupBranches(){let t=(await this.run(["ls-remote","--heads","origin","refs/heads/ops/directory-sync-stress-backup-*"])).stdout.split(/\r?\n/).map((r)=>r.match(/\trefs\/heads\/(ops\/directory-sync-stress-backup-[^\s]+)$/)?.[1]).filter((r)=>r!==void 0).sort();for(let r of t)await this.run(["push","origin","--delete",r]);return t}environment(){return{GH_TOKEN:this.#t,GITHUB_TOKEN:this.#t}}}var P8='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var z8=v(()=>{nf()});function of(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class M${#e;#t=[];#r=[];#n=new Set(["/health/ready"]);#o=!0;#i;#a;#s="";#c=0;#l;constructor(e){this.#e=e}get startedAt(){return this.#s}get error(){return this.#a}get healthSamples(){return this.#t}get runtimeSamples(){return this.#r}gateHealthSamples(){return this.#t.slice(this.#c,this.#l??this.#t.length)}markGateEnd(){this.#l=this.#t.length}async discoverEndpoints(){for(let e of["/health/live","/health/operate"])if((await Z$(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:5000})).status!==404)this.#n.add(e)}start(){this.#o=!1,this.#a=void 0,this.#c=this.#t.length,this.#l=void 0,this.#s=this.#e.now().toISOString(),this.#i=Promise.all([this.#m(),this.#f()]).then(()=>{return}).catch((e)=>{this.#a=e,this.#o=!0})}async stop(){this.#o=!0,await this.#i}async waitForHealthSnapshot(e){return this.waitForEntityBaseline(void 0,void 0,e)}async waitForEntityBaseline(e,t,r){let o=this.#e.now().getTime();while(this.#e.now().getTime()-o<r){let n=await this.fetchHealthPayload();if(this.#p(n,e,t))return n;await this.#e.sleep(5000)}return}async waitForStableEntityBaseline(e,t,r){let o=this.#e.now().getTime(),n=0;while(this.#e.now().getTime()-o<r){let i=await this.fetchHealthPayload();if(this.#p(i,e,t)){if(n+=1,n===2)return i}else n=0;await this.#e.sleep(5000)}return}async fetchHealthPayload(){let e=await this.#d();if(e===void 0)return;let t=await this.#e.readEntityCounts();if(!t)return;return{version:e,entities:t.reduce((r,o)=>r+o.count,0),entityCounts:t}}async#d(){let e=this.#e.now(),t=new AbortController,r=setTimeout(()=>t.abort(),20000);try{let o=await this.#e.fetchImpl(`https://${this.#e.domain}/health/operate`,{signal:t.signal}),n=await o.text();if(this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:o.status,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:o.ok}),!o.ok)return;return Hhe.parse(JSON.parse(n)).app.version}catch(o){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:o instanceof Error?`${o.name}: ${o.message}`:String(o)});return}finally{clearTimeout(r)}}#p(e,t,r){return e!==void 0&&(t===void 0||of(e)===t)&&(r===void 0||e.entities===r)}async#m(){while(!this.#o){for(let e of this.#n)this.#t.push(await Z$(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:20000}));await this.#e.sleep(4000)}}async#f(){while(!this.#o){let e=await this.#e.sampleRuntime();if(e)this.#r.push(e);await this.#e.sleep(1000)}}}var N8,Hhe;var D8=v(()=>{pe();U$();N8=c.array(c.object({entityType:c.string(),count:c.number().int().nonnegative()})),Hhe=c.object({status:c.literal("ready"),operationalStatus:c.literal("operational"),app:c.object({version:c.string()})})});var Cb={};Lt(Cb,{applyDirectorySyncStressPhase:()=>Z8,cleanupDirectorySyncStress:()=>oge,listProbeFiles:()=>xa,parseStressRuntimeSample:()=>U8,removeProbeFiles:()=>W$,runDeployedDirectorySyncStress:()=>rge,runStressCommand:()=>Wo,verifyDirectorySyncStressAccess:()=>nge});import{chmod as Vhe,mkdir as F$,mkdtemp as J$,readFile as Whe,readdir as Ghe,rename as Qhe,rm as af,writeFile as Tn}from"fs/promises";import{tmpdir as K$}from"os";import{join as ct,resolve as H$}from"path";async function rge(e){let t=e.now??(()=>new Date),r=t().toISOString(),o=G$(r),n=H$(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",o));await F$(n,{recursive:!0});let{pilot:i,user:s}=await V$(e.rootDir,e.handle);Ob({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=Tb.parse(e.profile),l=e.plan?$b.parse(e.plan):$8(a);if(l.profile!==a)throw Error(`Directory-sync stress plan profile ${l.profile} does not match requested profile ${a}`);if((l.maximumExternalAiCalls??0)===0)j8(s);let u=Yhe.parse(e.env??process.env),d=new B8({runId:o,artifactsDir:n,user:s,githubOrg:i.githubOrg,serverLabel:`${i.contentRepoPrefix}${s.handle}`,environment:u,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??Wo,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),p;try{p=await O8(l,d)}finally{await d.dispose()}let m={runId:o,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${i.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:p};return await age(m),m}async function nge(e){let r=(e.now??(()=>new Date))().toISOString(),o=G$(r),n=H$(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",`access-check-${o}`));await F$(n,{recursive:!0});let{pilot:i,user:s}=await V$(e.rootDir,e.handle);Ob({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),j8(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let l=await J$(ct(K$(),"brains-ops-directory-sync-access-check-"));try{let u=await Zl.clone(e.commandRunner??Wo,`${i.githubOrg}/${s.contentRepo}`,ct(l,"content"),a),d=await u.output(["rev-parse","HEAD"]);await u.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${o}`]);let p={success:!0,artifactsDir:n,checkedAt:r,remoteHead:d,target:{handle:s.handle,domain:s.domain,contentRepo:`${i.githubOrg}/${s.contentRepo}`}};return await Tn(ct(n,"access-check.json"),`${JSON.stringify(p,null,2)}
430
+ `;await t.run(n);let s=(await t.values(C`SELECT id, hash, created_at FROM ${C.identifier(o)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(a)=>{for(let l of e)if(!s||Number(s[2])<l.folderMillis){for(let u of l.sql)await a.run(C.raw(u));await a.run(C`INSERT INTO ${C.identifier(o)} ("hash", "created_at") VALUES(${l.hash}, ${l.folderMillis})`)}})}}});var s$;var T5=v(()=>{$e();s$=class s${static[F]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function ub(e,t){return(r,o,...n)=>{let i=[o,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of i)if(!Mp(r.getSelectedFields(),s.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return r.addSetOperators(i)}}var Rn,$5,a$,ehe=()=>({union:the,unionAll:rhe,intersect:nhe,except:ohe}),the,rhe,nhe,ohe;var c$=v(()=>{$e();T5();Fo();va();Qt();In();sr();Sr();Mo();zl();Gp();Rn=class Rn{static[F]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct}from(e){let t=!!this.fields,r;if(this.fields)r=this.fields;else if(oe(e,dt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((o)=>[o,e[o]]));else if(oe(e,Vo))r=e[pt].selectedFields;else if(oe(e,Ee))r={};else r=eb(e);return new a$({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};$5=class $5 extends s${static[F]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:o,dialect:n,withList:i,distinct:s}){super();this.config={withList:i,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=r,this.session=o,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=qp(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of An(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let o=this.tableName,n=qp(t);for(let i of An(t))this.usedTables.add(i);if(typeof n==="string"&&this.config.joins?.some((i)=>i.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof o==="string")this.config.fields={[o]:this.config.fields};if(typeof n==="string"&&!oe(t,Ee)){let i=oe(t,dt)?t._.selectedFields:oe(t,sn)?t[pt].selectedFields:t[he.Symbol.Columns];this.config.fields[n]=i}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:r,table:t,joinType:e,alias:n}),typeof n==="string")switch(e){case"left":{this.joinsNotNullableMap[n]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[n]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[n]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([i])=>[i,!1])),this.joinsNotNullableMap[n]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,t){return(r)=>{let o=typeof r==="function"?r(ehe()):r;if(!Mp(this.getSelectedFields(),o.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:t,rightSelect:o}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=e,this}groupBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.fields,new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=r;else this.config.orderBy=r}else{let t=e;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=t;else this.config.orderBy=t}return this}limit(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=e;else this.config.limit=e;return this}offset(e){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=e;else this.config.offset=e;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...An(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...An(r.table));return new Proxy(new dt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new at({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};a$=class a$ extends $5{static[F]="SQLiteSelect";_prepare(e=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let t=an(this.config.fields),r=this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),t,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return r.joinsNotNullableMap=this.joinsNotNullableMap,r}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.all()}};c3(a$,[vr]);the=ub("union",!1),rhe=ub("union",!0),nhe=ub("intersect",!1),ohe=ub("except",!1)});var wa;var db=v(()=>{$e();va();lb();In();c$();wa=class wa{static[F]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=oe(e,Dl)?e:void 0,this.dialectConfig=oe(e,Dl)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new jp(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new Rn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function o(n){return new Rn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:o}}select(e){return new Rn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Rn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new o$(this.dialectConfig);return this.dialect}}});var pb,l$;var O5=v(()=>{$e();Fo();Qt();Jo();sr();Sr();zl();db();pb=class pb{constructor(e,t,r,o){this.table=e,this.session=t,this.dialect=r,this.withList=o}static[F]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error("values() must be called with at least one value");let t=e.map((r)=>{let o={},n=this.table[he.Symbol.Columns];for(let i of Object.keys(r)){let s=r[i];o[i]=oe(s,Ee)?s:new Mr(s,n[i])}return o});return new l$(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new wa):e;if(!oe(t,Ee)&&!Mp(this.table[Qy],t._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new l$(this.table,t,this.session,this.dialect,this.withList,!0)}};l$=class l$ extends vr{constructor(e,t,r,o,n,i){super();this.session=r,this.dialect=o,this.config={table:e,values:t,withList:n,select:i}}static[F]="SQLiteInsert";config;returning(e=this.config.table[At.Symbol.Columns]){return this.config.returning=an(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(C` on conflict do nothing`);else{let t=Array.isArray(e.target)?C`${e.target}`:C`${[e.target]}`,r=e.where?C` where ${e.where}`:C``;this.config.onConflict.push(C` on conflict ${t} do nothing${r}`)}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let t=e.where?C` where ${e.where}`:void 0,r=e.targetWhere?C` where ${e.targetWhere}`:void 0,o=e.setWhere?C` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?C`${e.target}`:C`${[e.target]}`,i=this.dialect.buildUpdateSet(this.config.table,Xy(this.config.table,e.set));return this.config.onConflict.push(C` on conflict ${n}${r} do update set ${i}${t}${o}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:An(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var fb,C5;var P5=v(()=>{$e();Fo();va();Jo();In();sr();Sr();Mo();zl();Gp();fb=class fb{constructor(e,t,r,o){this.table=e,this.session=t,this.dialect=r,this.withList=o}static[F]="SQLiteUpdateBuilder";set(e){return new C5(this.table,Xy(this.table,e),this.session,this.dialect,this.withList)}};C5=class C5 extends vr{constructor(e,t,r,o,n){super();this.session=r,this.dialect=o,this.config={set:t,table:e,withList:n,joins:[]}}static[F]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let o=qp(t);if(typeof o==="string"&&this.config.joins.some((n)=>n.alias===o))throw Error(`Alias "${o}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?oe(t,At)?t[he.Symbol.Columns]:oe(t,dt)?t._.selectedFields:oe(t,Vo)?t[pt].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[he.Symbol.Columns],new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new at({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:o}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[he.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.config.table[At.Symbol.Columns]){return this.config.returning=an(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=!0){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:An(this.config.table)})}prepare(){return this._prepare(!1)}run=(e)=>this._prepare().run(e);all=(e)=>this._prepare().all(e);get=(e)=>this._prepare().get(e);values=(e)=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}});var u$=v(()=>{E5();O5();db();c$();P5()});var Qp;var z5=v(()=>{$e();Qt();Qp=class Qp extends Ee{constructor(e){super(Qp.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=Qp.buildCount(e.source,e.filters)}sql;static[F]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return C`(select count(*) from ${e}${C.raw(" where ").if(t)}${t})`}static buildCount(e,t){return C`select count(*) from ${e}${C.raw(" where ").if(t)}${t}`}then(e,t){return Promise.resolve(this.session.count(this.sql)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}}});var p$,mb,d$;var N5=v(()=>{$e();Fo();Jp();p$=class p${constructor(e,t,r,o,n,i,s,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=o,this.table=n,this.tableConfig=i,this.dialect=s,this.session=a}static[F]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new d$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new mb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new d$(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new mb(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};mb=class mb extends vr{constructor(e,t,r,o,n,i,s,a,l){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=o,this.tableConfig=n,this.dialect=i,this.session=s,this.config=a,this.mode=l}static[F]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=!1){let{query:t,builtQuery:r}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](r,void 0,this.mode==="first"?"get":"all",!0,(o,n)=>{let i=o.map((s)=>ob(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return i[0];return i})}prepare(){return this._prepare(!1)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),t=this.dialect.sqlToQuery(e.sql);return{query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}};d$=class d$ extends mb{static[F]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var Ll;var D5=v(()=>{$e();Fo();Ll=class Ll extends vr{constructor(e,t,r,o,n){super();this.execute=e,this.getSQL=t,this.dialect=o,this.mapBatchResult=n,this.config={action:r}}static[F]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}}});var Yp;var hb=v(()=>{$e();va();Qt();u$();In();z5();N5();D5();Yp=class Yp{constructor(e,t,r,o){this.resultKind=e,this.dialect=t,this.session=r,this._=o?{schema:o.schema,fullSchema:o.fullSchema,tableNamesMap:o.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let n=this.query;if(this._.schema)for(let[i,s]of Object.entries(this._.schema))n[i]=new p$(e,o.fullSchema,this._.schema,this._.tableNamesMap,o.fullSchema[i],s,t,r);this.$cache={invalidate:async(i)=>{}}}static[F]="BaseSQLiteDatabase";query;$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(new wa(r.dialect));return new Proxy(new jp(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new at({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new Qp({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Rn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function o(a){return new Rn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new fb(a,t.session,t.dialect,e)}function i(a){return new pb(a,t.session,t.dialect,e)}function s(a){return new ab(a,t.session,t.dialect,e)}return{select:r,selectDistinct:o,update:n,insert:i,delete:s}}select(e){return new Rn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Rn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new fb(e,this.session,this.dialect)}$cache;insert(e){return new pb(e,this.session,this.dialect)}delete(e){return new ab(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new Ll(async()=>this.session.run(t),()=>t,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run(t)}all(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new Ll(async()=>this.session.all(t),()=>t,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all(t)}get(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new Ll(async()=>this.session.get(t),()=>t,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get(t)}values(e){let t=typeof e==="string"?C.raw(e):e.getSQL();if(this.resultKind==="async")return new Ll(async()=>this.session.values(t),()=>t,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values(t)}transaction(e,t){return this.session.transaction(e,t)}}});async function f$(e,t){let r=`${e}-${JSON.stringify(t)}`,n=new TextEncoder().encode(r),i=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(i)].map((l)=>l.toString(16).padStart(2,"0")).join("")}var L5,Xp;var m$=v(()=>{$e();L5=class L5{static[F]="Cache"};Xp=class Xp extends L5{strategy(){return"all"}static[F]="NoopCache";async get(e){return}async put(e,t,r,o){}async onMutate(e){}}});var B5=v(()=>{m$()});function gb(e,t){return new Proxy(e,new Sa(t,!1))}var j5=v(()=>{Vp()});var Z5,h$,g$,y$;var b$=v(()=>{m$();$e();cb();Fo();hb();Z5=class Z5 extends vr{constructor(e){super();this.resultCb=e}static[F]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};h$=class h${constructor(e,t,r,o,n,i){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=o,this.queryMetadata=n,this.cacheConfig=i,o&&o.strategy()==="all"&&i===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[F]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||oe(this.cache,Xp)||this.queryMetadata===void 0)try{return await r()}catch(o){throw new Ho(e,t,o)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(o){throw new Ho(e,t,o)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[o]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return o}catch(o){throw new Ho(e,t,o)}if(!this.cacheConfig)try{return await r()}catch(o){throw new Ho(e,t,o)}if(this.queryMetadata.type==="select"){let o=await this.cache.get(this.cacheConfig.tag??await f$(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(o===void 0){let n;try{n=await r()}catch(i){throw new Ho(e,t,i)}return await this.cache.put(this.cacheConfig.tag??await f$(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return o}try{return await r()}catch(o){throw new Ho(e,t,o)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw Error("Not implemented")}mapGetResult(e,t){throw Error("Not implemented")}execute(e){if(this.mode==="async")return this[this.executeMethod](e);return new Z5(()=>this[this.executeMethod](e))}mapResult(e,t){switch(this.executeMethod){case"run":return this.mapRunResult(e,t);case"all":return this.mapAllResult(e,t);case"get":return this.mapGetResult(e,t)}}};g$=class g${constructor(e){this.dialect=e}static[F]="SQLiteSession";prepareOneTimeQuery(e,t,r,o,n,i,s){return this.prepareQuery(e,t,r,o,n,i,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(r){throw new Nl({cause:r,message:`Failed to run the query '${t.sql}'`})}}extractRawRunValueFromBatchResult(e){return e}all(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(e){throw Error("Not implemented")}get(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(e){throw Error("Not implemented")}values(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",!1).values()}async count(e){return(await this.values(e))[0][0]}extractRawValuesValueFromBatchResult(e){throw Error("Not implemented")}};y$=class y$ extends Yp{constructor(e,t,r,o,n=0){super(e,t,r,o);this.schema=o,this.nestedIndex=n}static[F]="SQLiteTransaction";rollback(){throw new t$}}});var S$,ihe,she,yb;var U5=v(()=>{$e();va();Sr();db();Jo();Gp();S$=class S${constructor(e){this.name=e}static[F]="SQLiteViewBuilderCore";config={}};ihe=class ihe extends S${static[F]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new wa);let t=new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new yb({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};she=class she extends S${static[F]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=eb(Wp(e,t))}existing(){return new Proxy(new yb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new yb({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new at({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};yb=class yb extends Vo{static[F]="SQLiteView";constructor({config:e}){super(e)}}});var bb=v(()=>{j5();y5();n$();hb();lb();FT();w5();_5();u$();b$();Jo();KT();zl();U5()});function M5(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function Sb(e){if(typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer){if(typeof Buffer<"u"){if(!(e instanceof Buffer))return Buffer.from(e);return e}if(typeof TextDecoder<"u")return new TextDecoder().decode(e);throw Error("TextDecoder is not available. Please provide either Buffer or TextDecoder polyfill.")}return e}var vb,v$,q5;var w$=v(()=>{B5();$e();tb();Qt();bb();b$();Sr();vb=class vb extends g${constructor(e,t,r,o,n){super(t);this.client=e,this.schema=r,this.options=o,this.tx=n,this.logger=o.logger??new LT,this.cache=o.cache??new Xp}static[F]="LibSQLSession";logger;cache;prepareQuery(e,t,r,o,n,i,s){return new q5(this.client,e,this.logger,this.cache,i,s,t,this.tx,r,o,n)}async batch(e){let t=[],r=[];for(let n of e){let i=n._prepare(),s=i.getQuery();t.push(i),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,i)=>t[i].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let i=n._prepare(),s=i.getQuery();t.push(i),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,i)=>t[i].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),o=new vb(this.client,this.dialect,this.schema,this.options,r),n=new v$("async",this.dialect,o,this.schema);try{let i=await e(n);return await r.commit(),i}catch(i){throw await r.rollback(),i}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}};v$=class v$ extends y${static[F]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new v$("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(C.raw(`savepoint ${t}`));try{let o=await e(r);return await this.session.run(C.raw(`release savepoint ${t}`)),o}catch(o){throw await this.session.run(C.raw(`rollback to savepoint ${t}`)),o}}};q5=class q5 extends h${constructor(e,t,r,o,n,i,s,a,l,u,d){super("async",l,t,o,n,i);this.client=e,this.logger=r,this.fields=s,this.tx=a,this._isResponseInArrayMode=u,this.customResultMapper=d,this.customResultMapper=d,this.fields=s}static[F]="LibSQLPreparedQuery";async run(e){let t=Up(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return this.tx?this.tx.execute(r):this.client.execute(r)})}async all(e){let{fields:t,logger:r,query:o,tx:n,client:i,customResultMapper:s}=this;if(!t&&!s){let l=Up(o.params,e??{});return r.logQuery(o.sql,l),await this.queryWithCache(o.sql,l,async()=>{let u={sql:o.sql,args:l};return(n?n.execute(u):i.execute(u)).then(({rows:d})=>this.mapAllResult(d))})}let a=await this.values(e);return this.mapAllResult(a)}mapAllResult(e,t){if(t)e=e.rows;if(!this.fields&&!this.customResultMapper)return e.map((r)=>M5(r));if(this.customResultMapper)return this.customResultMapper(e,Sb);return e.map((r)=>zT(this.fields,Array.prototype.slice.call(r).map((o)=>Sb(o)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:o,tx:n,client:i,customResultMapper:s}=this;if(!t&&!s){let l=Up(o.params,e??{});return r.logQuery(o.sql,l),await this.queryWithCache(o.sql,l,async()=>{let u={sql:o.sql,args:l};return(n?n.execute(u):i.execute(u)).then(({rows:d})=>this.mapGetResult(d))})}let a=await this.values(e);return this.mapGetResult(a)}mapGetResult(e,t){if(t)e=e.rows;let r=e[0];if(!this.fields&&!this.customResultMapper)return M5(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,Sb);return zT(this.fields,Array.prototype.slice.call(r).map((o)=>Sb(o)),this.joinsNotNullableMap)}async values(e){let t=Up(this.query.params,e??{});return this.logger.logQuery(this.query.sql,t),await this.queryWithCache(this.query.sql,t,async()=>{let r={sql:this.query.sql,args:t};return(this.tx?this.tx.execute(r):this.client.execute(r)).then(({rows:o})=>o)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}});function Bl(e,t={}){let r=new i$({casing:t.casing}),o;if(t.logger===!0)o=new DT;else if(t.logger!==!1)o=t.logger;let n;if(t.schema){let a=C3(t.schema,z3);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let i=new vb(e,r,n,{logger:o,cache:t.cache},void 0),s=new F5("async",r,i,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var F5;var J5=v(()=>{$e();tb();Jp();hb();lb();w$();F5=class F5 extends Yp{static[F]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function wb(...e){if(typeof e[0]==="string"){let t=$l({url:e[0]});return Bl(t,e[1])}if(l3(e[0])){let{connection:t,client:r,...o}=e[0];if(r)return Bl(r,o);let n=typeof t==="string"?$l({url:t}):$l(t);return Bl(n,o)}return Bl(e[0],e[1])}var K5=v(()=>{_T();Sr();J5();((e)=>{function t(r){return Bl({},r)}e.mock=t})(wb||(wb={}))});var H5=v(()=>{K5();w$()});function ahe(){return new Promise((e)=>setTimeout(e,0))}function lhe(){if(x$)return;x$=!0,setTimeout(()=>{x$=!1,_$=performance.now()},0)}async function ef(e=che){if(lhe(),performance.now()-_$<e)return;await ahe(),_$=performance.now()}var che=50,_$,x$=!1;var V5=v(()=>{_$=performance.now()});function W5(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function fhe(e){return e instanceof Ce&&/^SQLITE_(?:BUSY|LOCKED)$/u.test(e.code)}async function xb(e,t){let r=Date.now()+(t.budgetMs??uhe),o=async(n)=>{if(t.isClosed())throw new Ce("The client is closed","CLIENT_CLOSED");try{return await e()}catch(i){if(t.isClosed()||!fhe(i))throw i;await t.afterRefusal?.();let s=Math.min(dhe*2**(n-1),phe),a=s/2+Math.random()*(s/2);if(t.isClosed()||Date.now()+a>=r)throw i;if(await new Promise((l)=>setTimeout(l,a)),t.isClosed()||Date.now()>=r)throw i;return o(n+1)}};return o(1)}function E$(e,t={}){let r=$l({...e,...e.url.startsWith("file:")?{timeout:0}:{}});if(e.url.startsWith("file:")&&e.syncUrl===void 0){let o=r.transaction.bind(r),n=()=>r.closed,i=t.contentionRetryBudgetMs,s=r.execute.bind(r),a=r.batch.bind(r),l=r.migrate.bind(r),u={isClosed:n,budgetMs:i,afterRefusal:async()=>{await Promise.resolve(r.reconnect())}};async function d(p,m){return await ef(),xb(()=>typeof p==="string"?s(p,m):s(p),u)}r.execute=d,r.batch=async(p,m)=>(await ef(),xb(()=>a(p,m),u)),r.migrate=async(p)=>(await ef(),xb(()=>l(p),u)),r.transaction=async(p)=>(await ef(),xb(()=>o(p),u))}return r}function _b(e){let{url:t,schema:r}=e,o=W5(e),n={contentionRetryBudgetMs:e.contentionRetryBudgetMs},i=o?E$({url:t,authToken:o},n):E$({url:t},n);return{db:wb(i,{schema:r}),client:i,url:t}}async function Eb(e,t){if(!t.startsWith("file:"))return;for(let r of["PRAGMA busy_timeout = 0","PRAGMA journal_mode = WAL"])await e.execute(r)}var uhe=5000,dhe=5,phe=40;var I$=v(()=>{_T();H5();V5()});var G5=v(()=>{BR();I$()});var k$=v(()=>{I$();G5()});var A$=v(()=>{Vp();Vy();En();$e();cb();tb();Fo();Jp();r$();In();sr();Sr();Mo()});var Y,Me;var R$=v(()=>{bb();A$();fp();Y=Wp("job_queue",{id:ft("id").primaryKey().$defaultFn(()=>Do()),type:ft("type").notNull(),data:ft("data").notNull(),result:ft("result",{mode:"json"}),progress:ft("progress",{mode:"json"}).$type(),source:ft("source"),metadata:ft("metadata",{mode:"json"}).$type().notNull(),status:ft("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:ar("priority").notNull().default(0),retryCount:ar("retryCount").notNull().default(0),maxRetries:ar("maxRetries").notNull().default(3),lastError:ft("lastError"),lastErrorPublic:ft("lastErrorPublic",{mode:"json"}),createdAt:ar("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:ar("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:ar("startedAt"),completedAt:ar("completedAt"),attemptId:ft("attemptId"),workerSlotId:ft("workerSlotId"),workerSessionId:ft("workerSessionId"),leaseExpiresAt:ar("leaseExpiresAt"),attemptHeartbeatAt:ar("attemptHeartbeatAt"),runtimeUpdatedAt:ar("runtimeUpdatedAt"),brainVersion:ft("brainVersion"),brainVersionSortKey:ft("brainVersionSortKey")},(e)=>({queueReadyIdx:Ko("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:Ko("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:Ko("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:Ko("idx_job_queue_source").on(e.source),rootJobIdx:Ko("idx_job_queue_root_job").on(C`json_extract(${e.metadata}, '$.rootJobId')`,e.createdAt,e.id),deduplicationIdx:Ko("idx_job_queue_deduplication").on(e.type,C`json_extract(${e.metadata}, '$.deduplicationKey')`,e.status)})),Me=Wp("job_worker_sessions",{slotId:ft("slotId").primaryKey(),sessionId:ft("sessionId").notNull().unique(),startedAt:ar("startedAt").notNull(),heartbeatAt:ar("heartbeatAt").notNull(),expiresAt:ar("expiresAt").notNull().default(0),brainVersion:ft("brainVersion"),brainVersionSortKey:ft("brainVersionSortKey"),stableSlotId:ft("stableSlotId")},(e)=>({heartbeatIdx:Ko("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:Ko("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function Q5(e){return _b({url:e.url,schema:{jobQueue:Y,jobWorkerSessions:Me},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}var Y5=v(()=>{k$();R$()});class T${declarations=new Map;handlers=new Map;validators=new Map;logger;mode;finalizedRegistrations;constructor(e,t){this.logger=e.child("HandlerRegistry"),this.mode=t}registerHandler(e,t,r){if(this.finalizedRegistrations)throw Error("Job handler registrations are finalized");if(this.declarations.has(e))throw Error(`Job handler is already registered for type: ${e}`);if(this.declarations.set(e,{handler:t,pluginId:r}),this.validators.set(e,t),this.mode!=="validation-only")this.handlers.set(e,t);this.logger.debug("Registered job execution declaration",{type:e,pluginId:r,mode:this.mode})}unregisterHandler(e){this.declarations.delete(e),this.handlers.delete(e),this.validators.delete(e),this.logger.debug("Unregistered job handler",{type:e})}unregisterPluginHandlers(e){let t=[...this.declarations.entries()].filter(([,r])=>r.pluginId===e).map(([r])=>r);for(let r of t)this.declarations.delete(r),this.handlers.delete(r),this.validators.delete(r);if(t.length>0)this.logger.debug("Unregistered plugin handlers",{pluginId:e,count:t.length,types:t})}finalizeRegistrations(){return this.finalizedRegistrations??=Object.freeze([...this.declarations.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>Object.freeze({type:e,pluginId:t.pluginId}))),this.finalizedRegistrations}getExecutionRegistrations(){return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getExclusiveTypes(){return[...this.handlers].filter(([,e])=>e.exclusive===!0).map(([e])=>e)}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}class $${tails=new Map;async run(e,t){let r=this.tails.get(e),o=()=>{},n=new Promise((i)=>{o=i});this.tails.set(e,n),await r;try{return await t()}finally{if(o(),this.tails.get(e)===n)this.tails.delete(e)}}}class O${findDuplicate(e,t,r){if(!t||t==="none")return null;let o=this.filterByDeduplicationKey(e,r).sort((i,s)=>s.createdAt-i.createdAt||s.id.localeCompare(i.id)),n=o.find((i)=>i.status===Oe.PENDING)??null;if(t==="skip"||t==="replace")return n;return n??o[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((r)=>{let o=mhe.safeParse(r.metadata);return o.success&&o.data.deduplicationKey===t})}}var mhe;var X5=v(()=>{pe();Lo();mhe=c.looseObject({deduplicationKey:c.string().optional()})});function r8(e){return`${String(e.length).padStart(2,"0")}${e}`}function ghe(e){return hhe.test(e)?`0${r8(e)}`:`1${e}`}function tf(e){let t=e8.exec(e);if(!t)throw Error(`Invalid brain version "${e}"`);let[,r="",o="",n="",i]=t,s=[r,o,n].map(r8).join("");return i===void 0?`${s}~`:`${s}-${i.split(".").map(ghe).join("!")}`}var e8,hhe,t8;var C$=v(()=>{pe();e8=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/u,hhe=/^\d+$/u,t8=c.string().regex(e8,"Brain version must be a semver version")});function n8(e){return JSON.stringify(new Oi(e).toJSON())}class P${db;transactionClient;databaseUrl;logger;deduplicator=new O$;writeRetryBudgetMs;constructor(e,t,r,o,n){this.db=e,this.transactionClient=t,this.databaseUrl=r,this.logger=o.child("JobQueueRepository"),this.writeRetryBudgetMs=n?.writeRetryBudgetMs??yhe}async insert(e){await this.write("insert",async()=>this.db.insert(Y).values(e))}async enqueueAtomic(e){return whe.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,r){let o=await this.runEnqueueTransaction(e,t,r);if(o.retry)return this.attemptEnqueue(e,t,r+1);return o.decision}async runEnqueueTransaction(e,t,r){let o=await this.acquireWriteTransaction(e,t),n={prepared:!1},i=!1;try{let s=await this.decideEnqueue(o,e,()=>{n.prepared=!0});return i=!0,await o.commit(),{retry:!1,decision:s}}catch(s){let a=i&&this.isSerializationConflict(s)&&!o.closed,l=!0;if(!o.closed)try{await o.rollback()}catch(u){l=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:u})}if(n.prepared)e.onInsertRollback?.();if(!a||!l)throw s;return await this.waitForConflictRetry("commit",e,t,r,s),{retry:!0}}finally{o.close()}}async decideEnqueue(e,t,r){let{jobData:o,strategy:n,deduplicationKey:i,beforeInsert:s}=t,a=n??"none",l=async()=>{await s?.(),r()},u=async()=>{await l(),await this.insertJob(e,o)};if(a==="none")return await u(),{kind:"inserted",jobId:o.id};let d=await this.getActiveDeduplicationCandidates(e,o.type,i),p=this.deduplicator.findDuplicate(d,a,i);if(!p)return await u(),{kind:"inserted",jobId:o.id};if(a==="skip")return await this.raiseBrainVersion(e,p.id,o),{kind:"skipped",jobId:p.id};if(a==="coalesce"){if(await this.raiseBrainVersion(e,p.id,o),(await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),p.id,p.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${p.id}`);return{kind:"coalesced",jobId:p.id}}await l();let m=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `lastErrorPublic` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[Oe.FAILED,"Replaced by newer job",n8("cancelled"),m,m,p.id,Oe.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${p.id}`);return await this.insertJob(e,o),{kind:"replaced",jobId:o.id,replacedJobId:p.id}}async getActiveDeduplicationCandidates(e,t,r){return(await e.execute(r?{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ?\n AND json_extract(`metadata`, '$.deduplicationKey') = ?\n AND `status` IN (?, ?)",args:[t,r,Oe.PENDING,Oe.PROCESSING]}:{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Oe.PENDING,Oe.PROCESSING]})).rows.map((n)=>this.parseDeduplicationCandidate(n))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:o,metadata:n}=e;if(typeof t!=="string"||r!==Oe.PENDING&&r!==Oe.PROCESSING||typeof o!=="number"&&typeof o!=="bigint"||typeof n!=="string")throw Error("Invalid active job row returned during atomic enqueue");let i=JSON.parse(n);return{id:t,status:r,createdAt:Number(o),metadata:i}}async raiseBrainVersion(e,t,r){if(!r.brainVersion)return;let o=tf(r.brainVersion);await e.execute({sql:"UPDATE `job_queue`\n SET `brainVersion` = ?, `brainVersionSortKey` = ?\n WHERE `id` = ?\n AND (`brainVersionSortKey` IS NULL OR `brainVersionSortKey` < ?)",args:[r.brainVersion,o,t,o]})}async insertJob(e,t){if((await e.execute({sql:"INSERT INTO `job_queue` (\n `id`, `type`, `data`, `result`, `source`, `metadata`,\n `status`, `priority`, `retryCount`, `maxRetries`,\n `lastError`, `createdAt`, `scheduledFor`, `startedAt`,\n `completedAt`, `brainVersion`, `brainVersionSortKey`\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",args:[t.id,t.type,t.data,this.serializeJson(t.result),t.source,JSON.stringify(t.metadata),t.status,t.priority,t.retryCount,t.maxRetries,t.lastError,t.createdAt,t.scheduledFor,t.startedAt,t.completedAt,t.brainVersion??null,t.brainVersion?tf(t.brainVersion):null]})).rowsAffected!==1)throw Error(`Atomic enqueue did not insert job ${t.id}`)}serializeJson(e){if(e===void 0||e===null)return null;return JSON.stringify(e)}acquireWriteTransaction(e,t){return this.retryOnConflict("acquire",e,()=>this.transactionClient.transaction("write"),(r)=>this.isSerializationConflict(r),t)}async waitForConflictRetry(e,t,r,o,n){let i=Math.min(bhe*2**(o-1),She),s=i/2+Math.random()*(i/2);if(Date.now()+s>=r)throw this.transactionConflictError(e,t,o,n);await new Promise((a)=>setTimeout(a,s))}async retryOnConflict(e,t,r,o,n=Date.now()+this.writeRetryBudgetMs,i=1){try{return await r()}catch(s){if(!o(s))throw s;return await this.waitForConflictRetry(e,t,n,i,s),this.retryOnConflict(e,t,r,o,n,i+1)}}transactionConflictError(e,t,r,o){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${r} attempts`,{cause:o});let n=t.strategy??"none",i=t.deduplicationKey?"present":"absent";return Error(`Failed to ${e} atomic enqueue transaction for type "${t.jobData.type}" within ${this.writeRetryBudgetMs}ms after ${r} attempts (strategy: ${n}, key: ${i})`,{cause:o})}write(e,t){return this.retryOnConflict("write",e,t,(r)=>{let o=new Set;for(let n=r;n!==void 0&&!o.has(n);){if(o.add(n),typeof n==="object"&&n!==null&&"code"in n&&/^SQLITE_(?:BUSY|LOCKED)(?:_|$)/u.test(String(n.code)))return!0;n=n instanceof Error?n.cause:void 0}return!1})}isSerializationConflict(e){for(let t=e;t!==void 0;){let r=typeof t==="object"&&t!==null&&"code"in t?String(t.code):"",o=Ve(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(r)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(o))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,r=Date.now(),o=Ji,n,i){let s=r+o,a={brainVersion:n??null,brainVersionSortKey:n?tf(n):null,stableSlotId:i??null};await this.write("start worker session",async()=>{await this.db.insert(Me).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:s,...a}).onConflictDoUpdate({target:Me.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:s,...a}}),await this.pruneDeadWorkerSessions(r,o)})}async heartbeatWorkerSession(e,t,r=Date.now(),o=Ji){return(await this.write("heartbeat worker session",async()=>{let i=await this.db.update(Me).set({heartbeatAt:r,expiresAt:r+o}).where(tt(je(Me.slotId,e),je(Me.sessionId,t))).returning({slotId:Me.slotId});return await this.pruneDeadWorkerSessions(r,o),i})).length===1}async pruneDeadWorkerSessions(e,t){let r=this.db.select({id:Y.id}).from(Y).where(tt(je(Y.workerSlotId,Me.slotId),je(Y.workerSessionId,Me.sessionId),je(Y.status,Oe.PROCESSING),kn(Y.leaseExpiresAt,e)));await this.db.delete(Me).where(tt(ns(Me.expiresAt,e-t),is(r)))}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(Me).where(tt(je(Me.slotId,e),je(Me.sessionId,t))).returning({slotId:Me.slotId}))).length===1}async complete(e,t,r){let o=Date.now(),i=(await this.write("complete",async()=>this.db.update(Y).set({status:Oe.COMPLETED,result:t,lastError:null,lastErrorPublic:null,completedAt:o,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o)}).where(this.attemptWriteGuard(e,r)).returning({id:Y.id}))).length===1;if(i)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return i}async update(e,t,r){let n=(await this.write("update",async()=>this.db.update(Y).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:Y.id}))).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,o=Date.now()){return(await this.write("record progress",async()=>this.db.update(Y).set({attemptHeartbeatAt:o,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async renewAttemptLease(e,t,r,o){return(await this.write("renew attempt lease",async()=>this.db.update(Y).set({attemptHeartbeatAt:r,leaseExpiresAt:r+o}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async release(e,t,r=Date.now()){return(await this.write("release",async()=>this.db.update(Y).set({status:Oe.PENDING,scheduledFor:r,startedAt:null,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(this.attemptWriteGuard(e,t)).returning({id:Y.id}))).length===1}async fail(e,t,r,o=Date.now()){let i=(await this.db.select({retryCount:Y.retryCount,maxRetries:Y.maxRetries,type:Y.type,scheduledFor:Y.scheduledFor,startedAt:Y.startedAt,runtimeUpdatedAt:Y.runtimeUpdatedAt}).from(Y).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!i)return!1;let s=i.retryCount<i.maxRetries,a=s?i.retryCount+1:i.retryCount,l=Math.min(1000*2**i.retryCount,60000),u=s?o+l:i.scheduledFor;if((await this.write("fail",async()=>this.db.update(Y).set({status:s?Oe.PENDING:Oe.FAILED,retryCount:a,lastError:t.message,lastErrorPublic:tg(t).toJSON(),scheduledFor:u,completedAt:s?null:o,runtimeUpdatedAt:s?i.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(o),startedAt:s?null:i.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(tt(this.attemptWriteGuard(e,r),je(Y.retryCount,i.retryCount))).returning({id:Y.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:l,scheduledFor:new Date(u).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:i.type,retryCount:i.retryCount,error:t.message});return!0}async retireUnownedActiveJob(e){let t=e.reason.trim();if(t.length===0)throw Error("Retired job reason must not be empty");let o=(await this.write("retire unowned job",async()=>this.db.update(Y).set({status:Oe.FAILED,lastError:t,lastErrorPublic:new Oi("no_handler").toJSON(),completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(tt(je(Y.id,e.jobId),je(Y.type,e.expectedType),cn(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)),qr(Y.attemptId),qr(Y.workerSlotId),qr(Y.workerSessionId),qr(Y.leaseExpiresAt),qr(Y.attemptHeartbeatAt),qr(Y.progress),qr(Y.result))).returning()))[0]??null;if(o)this.logger.warn("Retired unowned legacy job",{jobId:o.id,type:o.type,reason:t});return o}async getStatus(e){return(await this.db.select().from(Y).where(je(Y.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(Y).where(C`json_extract(${Y.metadata}, '$.rootJobId') = ${e}`).orderBy(qo(Y.createdAt),qo(Y.id))}async getStatusByEntityId(e){return(await this.db.select().from(Y).where(C`json_extract(${Y.data}, '$.id') = ${e}`).orderBy(ba(Y.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:Y.status,count:C`count(*)`}).from(Y).groupBy(Y.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let o=Number(r.count);t[r.status]=o,t.total+=o}return t}async getDiagnostics(e=Date.now()){let[t,r,o]=await Promise.all([this.db.select({type:Y.type,status:Y.status,count:C`count(*)`}).from(Y).groupBy(Y.type,Y.status),this.db.select({oldestPendingAt:C`min(case when ${Y.status} = ${Oe.PENDING} then ${Y.createdAt} end)`,duePending:C`coalesce(sum(case when ${Y.status} = ${Oe.PENDING} and ${Y.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:C`min(case when ${Y.status} = ${Oe.PENDING} and ${Y.scheduledFor} <= ${e} then ${Y.scheduledFor} end)`,latestClaimAt:C`max(${Y.startedAt})`,oldestProcessingAt:C`min(case when ${Y.status} = ${Oe.PROCESSING} then ${Y.startedAt} end)`,staleLeaseCount:C`coalesce(sum(case when ${Y.status} = ${Oe.PROCESSING} and ${Y.leaseExpiresAt} is not null and ${Y.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(Y),this.db.select({total:C`count(*)`,active:C`coalesce(sum(case when ${Me.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:C`coalesce(sum(case when ${Me.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:C`max(${Me.heartbeatAt})`}).from(Me)]),n={pending:0,processing:0,completed:0,failed:0},i=t.map((u)=>{let d=Number(u.count);return n[u.status]+=d,{type:u.type,status:u.status,count:d}}),s=r[0],a=o[0],l=(u)=>u===null||u===void 0?null:Math.max(0,e-Number(u));return{totals:n,byType:i,oldestPendingAgeMs:l(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:l(s?.oldestDuePendingAt),latestClaimAgeMs:l(s?.latestClaimAt),oldestProcessingAgeMs:l(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(a?.total??0),active:Number(a?.active??0),stale:Number(a?.stale??0),latestHeartbeatAgeMs:l(a?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){let r=vhe.parse(t);if(r===0)return[];return(await this.db.select().from(Y).where(C`(${Y.runtimeUpdatedAt}, ${Y.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(qo(Y.runtimeUpdatedAt),qo(Y.id)).limit(r)).map((n)=>({job:n,cursor:{updatedAt:n.runtimeUpdatedAt??0,jobId:n.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.write("cleanup",async()=>this.db.delete(Y).where(tt(cn(je(Y.status,Oe.COMPLETED),je(Y.status,Oe.FAILED)),ns(Y.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=cn(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)),r=e&&e.length>0?tt(t,os(Y.type,e)):t;return this.db.select().from(Y).where(r).orderBy(ba(Y.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?os(Y.type,e):void 0;return this.db.select().from(Y).where(r).orderBy(ba(Y.createdAt)).limit(t)}async getFailedJobs(e){let t=je(Y.status,Oe.FAILED),r=e&&e.length>0?tt(t,os(Y.type,e)):t;return this.db.select().from(Y).where(r).orderBy(ba(Y.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:o,workerSessionId:n,leaseDurationMs:i,executableTypes:s,exclusiveTypes:a=[],brainVersion:l}=e,u=l?this.brainVersionGate(l,t):{admissible:void 0,noNewerWorker:void 0},d=this.db.select({slotId:Me.slotId}).from(Me).where(tt(je(Me.slotId,o),je(Me.sessionId,n),kn(Me.expiresAt,t))),p=this.noNewerLiveInstance(o,n,t),m=this.db.select({slotId:Me.slotId}).from(Me).where(tt(je(Me.slotId,Y.workerSlotId),je(Me.sessionId,Y.workerSessionId))),h=tt(je(Y.status,Oe.PROCESSING),cn(qr(Y.attemptId),is(m),ns(Y.leaseExpiresAt,t))),b=gb(Y,"running"),y=this.db.select({id:b.id}).from(b).where(tt(je(b.type,Y.type),je(b.status,Oe.PROCESSING),kn(b.leaseExpiresAt,t),C`${b.id} <> ${Y.id}`)),S=a.length===0?void 0:cn(rb(Y.type,[...a]),is(y)),x=C`${Y.status} = ${Oe.PROCESSING} AND ${Y.retryCount} + 1 > ${Y.maxRetries}`,_=this.db.select({id:Y.id}).from(Y).where(tt(os(Y.type,s),S,u.admissible,cn(tt(je(Y.status,Oe.PENDING),ns(Y.scheduledFor,t)),h))).orderBy(qo(Y.priority),qo(Y.createdAt)).limit(1),O=(await this.write("claim",async()=>this.db.update(Y).set({status:C`CASE WHEN ${x} THEN ${Oe.FAILED} ELSE ${Oe.PROCESSING} END`,retryCount:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN ${Y.retryCount} + 1 ELSE ${Y.retryCount} END`,lastError:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN 'Attempt lease expired' ELSE ${Y.lastError} END`,lastErrorPublic:C`CASE WHEN ${Y.status} = ${Oe.PROCESSING} THEN ${n8("deadline_exceeded")} ELSE ${Y.lastErrorPublic} END`,startedAt:C`CASE WHEN ${x} THEN ${Y.startedAt} ELSE ${t} END`,completedAt:C`CASE WHEN ${x} THEN ${t} ELSE NULL END`,attemptId:C`CASE WHEN ${x} THEN ${Y.attemptId} ELSE ${r} END`,workerSlotId:C`CASE WHEN ${x} THEN ${Y.workerSlotId} ELSE ${o} END`,workerSessionId:C`CASE WHEN ${x} THEN ${Y.workerSessionId} ELSE ${n} END`,leaseExpiresAt:C`CASE WHEN ${x} THEN ${Y.leaseExpiresAt} ELSE ${t+i} END`,attemptHeartbeatAt:C`CASE WHEN ${x} THEN ${Y.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:C`CASE WHEN ${x} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${Y.runtimeUpdatedAt} END`}).where(tt(os(Y.id,_),nb(d),p,u.noNewerWorker)).returning()))[0];if(!O)return null;if(O.status===Oe.FAILED)return O;return this.logger.debug("Job claimed",{jobId:O.id,attemptId:O.attemptId,workerSlotId:o,workerSessionId:n}),O}noNewerLiveInstance(e,t,r){let o=gb(Me,"claimer"),n=gb(Me,"peer"),i=this.db.select({slotId:n.slotId}).from(n).innerJoin(o,tt(je(o.slotId,e),je(o.sessionId,t))).where(tt(je(n.stableSlotId,o.stableSlotId),kn(n.expiresAt,r),cn(kn(n.startedAt,o.startedAt),tt(je(n.startedAt,o.startedAt),kn(n.slotId,o.slotId)))));return is(i)}brainVersionGate(e,t){let r=tf(e),o=this.db.select({slotId:Me.slotId}).from(Me).where(tt(kn(Me.expiresAt,t),kn(Me.brainVersionSortKey,r)));return{admissible:cn(qr(Y.brainVersionSortKey),ns(Y.brainVersionSortKey,r)),noNewerWorker:is(o)}}nextRuntimeUpdatedAt(e){return C`max(${e}, coalesce((select max(${Y.runtimeUpdatedAt}) from ${Y}), 0) + 1)`}attemptWriteGuard(e,t){return t?tt(je(Y.id,e),je(Y.status,Oe.PROCESSING),je(Y.attemptId,t)):tt(je(Y.id,e),qr(Y.attemptId),cn(je(Y.status,Oe.PENDING),je(Y.status,Oe.PROCESSING)))}}var yhe=2000,bhe=5,She=40,vhe,whe;var o8=v(()=>{A$();bb();R$();Ot();pe();Lo();hp();X5();C$();vhe=c.number().int().min(0).max(1000),whe=new $$});import{AsyncLocalStorage as xhe}from"async_hooks";class jl{storage=new xhe;static createFresh(){return new jl}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let o=ko.parse(e),n=_he(o);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function _he(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var Ib=v(()=>{Ot()});class rf{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${Do()}`;directWorkerSessionId=Do();directLeaseDurationMs;directSessionStart=null;brainVersion;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new rf(e,t??Rr.getInstance(),r)}constructor(e,t,r){this.brainVersion=e.brainVersion===void 0?void 0:t8.parse(e.brainVersion);let{db:o,client:n,url:i}=Q5(e);this.client=n,this.databaseUrl=i,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??jl.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new T$(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new P$(o,n,i,this.logger),this.directLeaseDurationMs=e.claimTimeoutMs??300000}initialize(){if(this.closeRequested)return Promise.resolve();return this.walInitialization??=this.initializeWALMode(),this.walInitialization}async initializeWALMode(){try{await Eb(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable WAL mode (non-fatal)",e)}finally{this.walInitializationSettled=!0,this.closeClientWhenReady()}}closeClientWhenReady(){if(!this.closeRequested||this.inFlightEnqueues>0||this.walInitialization!==null&&!this.walInitializationSettled)return;this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}registerHandler(e,t,r){this.handlerRegistry.registerHandler(e,t,r)}unregisterHandler(e){this.handlerRegistry.unregisterHandler(e)}unregisterPluginHandlers(e){this.handlerRegistry.unregisterPluginHandlers(e)}getRegisteredTypes(){return this.handlerRegistry.getRegisteredTypes()}getHandler(e){return this.handlerRegistry.getHandler(e)}getValidator(e){return this.handlerRegistry.getValidator(e)}finalizeHandlerRegistrations(){return this.handlerRegistry.finalizeRegistrations()}getExecutionRegistrations(){return this.handlerRegistry.getExecutionRegistrations()}async enqueue(e){if(this.closeRequested)throw Error("Cannot enqueue a job after the queue service is closed");this.inFlightEnqueues++;try{return await this.enqueueValidated(e)}finally{this.inFlightEnqueues--,this.closeClientWhenReady()}}async enqueueValidated(e){let{type:t,data:r,options:o}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let i=n.validateAndParse(r);if(i===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=Do(),l=o?.rootJobId??(o?.detached?a:this.operationContext.current()?.provenance.rootJobId)??a,u=this.createJobProvenance(a,l,o),d=o?.metadata??{operationType:"data_processing"},{provenance:p,...m}=d,h={id:a,type:t,data:JSON.stringify(i),status:Oe.PENDING,priority:o?.priority??0,maxRetries:o?.maxRetries??3,retryCount:0,source:o?.source??null,metadata:{...m,...o?.deduplicationKey&&{deduplicationKey:o.deduplicationKey},rootJobId:l,provenance:u},createdAt:s,scheduledFor:o?.delayMs?s+o.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null,brainVersion:this.brainVersion},b,y=()=>{b?.rollback(),b=void 0};try{let S=await this.repository.enqueueAtomic({jobData:h,strategy:o?.deduplication,deduplicationKey:o?.deduplicationKey,beforeInsert:async()=>{b=await this.projectionAdmission?.reserveJobAdmission(u)},onInsertRollback:y});if(b?.commit(),b=void 0,S.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:S.jobId});else if(S.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:S.jobId});else{if(S.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:S.replacedJobId});this.logger.debug("Job enqueued",{id:S.jobId,type:t,priority:h.priority,rootJobId:h.metadata.rootJobId})}return S.jobId}catch(S){throw y(),this.logger.error("Failed to enqueue job",{type:t,error:Ve(S)}),S}}createJobProvenance(e,t,r){let o=this.operationContext.current(),n=r?.metadata.provenance??o?.provenance,i=n?.rootJobId===t?n:void 0,s=o?.provenance.rootJobId===t?o.operationId:void 0,a=r?.projection,l=a?[...i?.projectionLineage??[],a.id]:[...i?.projectionLineage??[]],u=a?.id??i?.projectionId;return ko.parse({rootJobId:t,causationId:s??i?.causationId??e,...u?{projectionId:u}:{},projectionLineage:l,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:i?.sourceEntity?{sourceEntity:i.sourceEntity}:{},derivationDepth:l.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let{onTerminalReclaim:r,...o}=e??await this.getDirectClaimOptions(),n=Date.now(),i=await this.repository.claimNextReady({...o,workerSlotId:this.sessionSlotId(o.workerSlotId,o.workerSessionId),brainVersion:this.brainVersion,now:n,attemptId:Do(),executableTypes:t,exclusiveTypes:this.handlerRegistry.getExclusiveTypes()});if(!i)return null;if(i.status===Oe.FAILED)return this.logger.warn("Expired attempt failed terminally on reclaim",{id:i.id,type:i.type,retryCount:i.retryCount}),await r?.(i),null;return this.logger.debug("Job dequeued",{id:i.id,type:i.type,priority:i.priority,retryCount:i.retryCount,attemptId:i.attemptId,workerSlotId:i.workerSlotId,workerSessionId:i.workerSessionId}),i}async startWorkerSession(e,t,r=Ji){await this.repository.startWorkerSession(this.sessionSlotId(e,t),t,Date.now(),r,this.brainVersion,this.versionedSlotId(e))}heartbeatWorkerSession(e,t,r=Ji){return this.repository.heartbeatWorkerSession(this.sessionSlotId(e,t),t,Date.now(),r)}endWorkerSession(e,t){return this.repository.endWorkerSession(this.sessionSlotId(e,t),t)}versionedSlotId(e){return this.brainVersion?`${e}@${this.brainVersion}`:e}sessionSlotId(e,t){return`${this.versionedSlotId(e)}#${t}`}renewAttemptLease(e,t,r){return this.repository.renewAttemptLease(e,t,Date.now(),r)}recordAttemptProgress(e,t,r){return this.repository.recordAttemptProgress(e,t,r)}complete(e,t,r){return this.repository.complete(e,t,r)}update(e,t,r){return this.repository.update(e,t,r)}fail(e,t,r){return this.repository.fail(e,t,r)}release(e,t){return this.repository.release(e,t)}retireUnownedActiveJob(e){return this.repository.retireUnownedActiveJob(e)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.sessionSlotId(this.directWorkerSlotId,this.directWorkerSessionId),this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs,this.brainVersion),await this.directSessionStart,{workerSlotId:this.directWorkerSlotId,workerSessionId:this.directWorkerSessionId,leaseDurationMs:this.directLeaseDurationMs}}async getStatus(e){return this.repository.getStatus(e)}async getJobsByRootJobId(e){return this.repository.getJobsByRootJobId(e)}async getStatusByEntityId(e){return this.repository.getStatusByEntityId(e)}async getStats(){return this.repository.getStats()}getDiagnostics(e){return this.repository.getDiagnostics(e)}async waitForIdle(e={}){let t=e.quietMs??250,r=e.pollIntervalMs??25,o=Date.now()+(e.timeoutMs??30000),n=async(i)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),l=s.pending===0&&s.processing===0?i??Date.now():null;if(l!==null&&Date.now()-l>=t)return;if(Date.now()>=o)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(r),n(l)};return n(null)}getRuntimeUpdates(e,t=1000){return this.repository.getRuntimeUpdates(e,t)}async cleanup(e){let t=await this.repository.cleanup(e);if(t>0)this.logger.info("Cleaned up old jobs",{deletedCount:t,olderThanMs:e});return t}async getActiveJobs(e){return this.repository.getActiveJobs(e)}async getRecentJobs(e,t){return this.repository.getRecentJobs(e,t)}async getFailedJobs(e){return this.repository.getFailedJobs(e)}}var i8=v(()=>{fp();BR();hp();Lo();k$();Y5();o8();Ot();Ib();C$()});var z$=()=>{};var s8=v(()=>{fp();Lo();hp();Lo();z$();Ib()});var a8=v(()=>{Lo();z$()});var kb,c8;var N$=v(()=>{pe();kb=c.object({success:c.boolean(),data:c.unknown().optional(),error:c.string().optional(),code:c.string().optional()}),c8=c.object({id:c.string().min(1),timestamp:c.string(),type:c.string().min(1),source:c.string().min(1),target:c.string().optional(),metadata:c.record(c.string(),c.unknown()).optional()})});var f3e;var l8=v(()=>{pe();N$();f3e=c.union([c.object({noop:c.literal(!0)}),kb])});var Ab=v(()=>{l8()});var u8=v(()=>{Ab()});var d8=v(()=>{Ab()});var p8=v(()=>{d8()});var O3e;var D$=v(()=>{pe();O3e=c.looseObject({issues:c.array(c.looseObject({message:c.string()})).optional()})});var f8=v(()=>{u8();Ab();p8();D$();Ot();Ib()});var Phe;var m8=v(()=>{pe();N$();Phe=c.object({id:c.string().min(1),requestId:c.string().min(1),success:c.boolean(),data:c.unknown().optional(),error:c.object({message:c.string(),code:c.string().optional()}).optional(),timestamp:c.string().datetime()})});var W3e;var h8=v(()=>{Ot();W3e=new Oi("invalid_response").toJSON()});var g8=v(()=>{f8();m8();D$();h8()});var m5e;var y8=v(()=>{pe();g8();mp();Lo();m5e=c.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},c.record(c.string(),c.unknown()))});var y5e;var b8=v(()=>{pe();y5e=c.record(c.string(),c.unknown())});var S8=v(()=>{Ot();fp()});var v8=v(()=>{i8();s8();a8();y8();b8();hp();Lo();mp();S8()});var L$={};Lt(L$,{LEGACY_PROJECTION_JOB_TYPES:()=>x8,LEGACY_PROJECTION_RETIREMENT_REASON:()=>E8,legacyProjectionJobTypeSchema:()=>_8,retireLegacyProjectionJob:()=>Bhe});import{existsSync as Nhe}from"fs";import{resolve as Dhe}from"path";function w8(e){return{id:e.id,type:e.type,status:e.status,retryCount:e.retryCount,maxRetries:e.maxRetries,createdAt:e.createdAt,startedAt:e.startedAt,completedAt:e.completedAt}}function Lhe(e,t){if(e.type!==t)throw Error(`Job ${e.id} has type ${e.type}; expected ${t}`);if(e.status!=="pending"&&e.status!=="processing")throw Error(`Job ${e.id} is already terminal (${e.status})`);if(e.attemptId!==null||e.workerSlotId!==null||e.workerSessionId!==null||e.leaseExpiresAt!==null||e.attemptHeartbeatAt!==null)throw Error(`Job ${e.id} still has attempt ownership`);if(e.progress!==null||e.result!=null)throw Error(`Job ${e.id} contains partial progress or a result`)}async function Bhe(e){let t=Dhe(e.databasePath);if(!Nhe(t))throw Error(`Job database does not exist: ${t}`);let r=_8.parse(e.jobType),o=rf.createFresh({url:`file:${t}`});try{let n=await o.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(Lhe(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:w8(n),retired:!1}}let i=`retire:${n.id}`;if(e.confirmation!==i)throw Error(`Refusing to retire ${n.id}; expected --confirm ${i}`);let s=await o.retireUnownedActiveJob({jobId:n.id,expectedType:r,reason:E8,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:w8(s),retired:!0}}finally{o.close()}}var x8,_8,E8="Retired legacy projection job superseded by scheduler-owned projections";var B$=v(()=>{v8();pe();x8=["conversation-memory:project","skill:project","swot:derive","topic:project"],_8=c.enum(x8)});function Ut(e,t,r,o,n){return k8.parse({id:e,operation:t,count:r,targetProbeCount:o,settleMs:n})}function $8(e){return $b.parse(structuredClone(qhe[e]))}function Ob(e){let t=`stress:${e.handle}`;if(e.confirmation!==t)throw Error(`Directory-sync stress requires --confirm ${t}`);let r=/(^|[-_.])smoke($|[-_.])/i;if(!r.test(e.handle)||!r.test(e.domain)||!r.test(e.contentRepo))throw Error("Directory-sync stress is smoke-only; handle, domain, and content repository must all identify smoke")}async function Z$(e,t={}){let r=t.fetchImpl??fetch,o=t.now??(()=>new Date),n=t.timeoutMs??20000,i=o(),s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let l=await r(e,{method:"GET",signal:s.signal});return await l.arrayBuffer(),j$.parse({timestamp:i.toISOString(),endpoint:new URL(e).pathname,status:l.status,durationMs:Math.max(0,o().getTime()-i.getTime()),ok:l.ok})}catch(l){return j$.parse({timestamp:i.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,o().getTime()-i.getTime()),ok:!1,error:Jhe(l)})}finally{clearTimeout(a)}}async function O8(e,t){let r=$b.parse(e),o=[],n,i=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(l){n=`monitor: ${Rb(l)}`}if(!n)for(let l of r.phases)try{let u=A8.parse(await t.executePhase(l,i));if(o.push(u),!u.success){n=`${l.id}: ${u.error??"phase failed"}`;break}}catch(u){let d=Rb(u);o.push({id:l.id,operation:l.operation,count:l.count,success:!1,error:d}),n=`${l.id}: ${d}`;break}}finally{try{if(s=R8.parse(await t.cleanup(i)),!s.success&&!n)n=s.error??"cleanup failed"}catch(l){let u=Rb(l);s={success:!1,probesRemaining:0,error:u},n??=`cleanup: ${u}`}try{a=T8.parse(await t.stopMonitoring())}catch(l){let u=Rb(l);a={health:[],runtime:[]},n??=`monitor: ${u}`}}return n??=Fhe(a,r.maximumExternalAiCalls??0),Mhe.parse({profile:r.profile,success:n===void 0&&o.length===r.phases.length&&s.success,baseline:i,phases:o,cleanup:s,metrics:a,...n?{failure:n}:{}})}function Fhe(e,t=0){let r=e.health.find((i)=>!i.ok);if(r)return`health: ${r.endpoint} unavailable`;let o=e.externalAiCalls??0;if(o>t)return t===0?`external AI: observed ${o} call(s)`:`external AI: observed ${o} call(s), cap ${t}`;if(e.container?.oomKilled)return"container: OOM killed";let n=e.container?.restartCount??0;if(n>0)return`container: restarted ${n} time(s)`;if(e.container&&e.container.status!=="running")return`container: ${e.container.status}`;return}function Jhe(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function Rb(e){return Ve(e)}var Tb,I8,k8,$b,jhe,j$,Zhe,A8,R8,Uhe,T8,Mhe,qhe;var U$=v(()=>{pe();Tb=c.enum(["regression","load","stress"]),I8=c.enum(["add","update","rename","delete"]),k8=c.object({id:c.string().min(1),operation:I8,count:c.number().int().positive().max(700),targetProbeCount:c.number().int().min(0).max(700),settleMs:c.number().int().nonnegative().max(300000)}),$b=c.object({profile:Tb,maximumProbeCount:c.number().int().positive().max(700),maximumExternalAiCalls:c.number().int().nonnegative().max(1e4).optional(),phases:c.array(k8).min(1)}),jhe=c.object({entities:c.number().int().nonnegative(),notes:c.number().int().nonnegative(),version:c.string().min(1)}),j$=c.object({timestamp:c.iso.datetime(),endpoint:c.string().startsWith("/"),status:c.number().int().nonnegative(),durationMs:c.number().nonnegative(),ok:c.boolean(),error:c.string().optional()}),Zhe=c.object({timestamp:c.iso.datetime(),cpuPercent:c.number().nonnegative(),memoryPercent:c.number().nonnegative(),pids:c.number().int().nonnegative()}),A8=c.object({id:c.string().min(1),operation:I8,count:c.number().int().positive(),success:c.boolean(),commitLatencyMs:c.number().nonnegative().optional(),persistenceLatencyMs:c.number().nonnegative().optional(),error:c.string().optional()}),R8=c.object({success:c.boolean(),probesRemaining:c.number().int().nonnegative(),finalEntities:c.number().int().nonnegative().optional(),finalNotes:c.number().int().nonnegative().optional(),contentTreeRestored:c.boolean().optional(),error:c.string().optional()}),Uhe=c.object({status:c.string(),restartCount:c.number().int().nonnegative(),oomKilled:c.boolean()}),T8=c.object({health:c.array(j$),runtime:c.array(Zhe),externalAiCalls:c.number().int().nonnegative().optional(),container:Uhe.optional()}),Mhe=c.object({profile:Tb,success:c.boolean(),baseline:jhe,phases:c.array(A8),cleanup:R8,metrics:T8,failure:c.string().optional()}),qhe={regression:{profile:"regression",maximumProbeCount:20,phases:[Ut("add20","add",20,20,0),Ut("update20","update",20,20,30000),Ut("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[Ut("add50","add",50,50,0),Ut("add150","add",100,150,0),Ut("add350","add",200,350,0),Ut("update350a","update",350,350,45000),Ut("rename100","rename",100,350,45000),Ut("update350b","update",350,350,45000),Ut("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[Ut("add50","add",50,50,0),Ut("add150","add",100,150,0),Ut("add350","add",200,350,0),Ut("add700","add",350,700,0),Ut("update700a","update",700,700,45000),Ut("rename200","rename",200,700,45000),Ut("update700b","update",700,700,45000),Ut("delete700","delete",700,0,150000)]}}});import{spawn as Khe}from"child_process";async function C8(e,t,r,o){let n=await e(t,r,o);if(n.exitCode!==0)throw io(t,r,n);return n}function io(e,t,r){let o=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${o?`: ${o}`:""}`)}var Wo=async(e,t,r={})=>new Promise((o,n)=>{let i=Khe(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";i.stdout.setEncoding("utf8"),i.stderr.setEncoding("utf8"),i.stdout.on("data",(l)=>{s+=l}),i.stderr.on("data",(l)=>{a+=l}),i.on("error",n),i.on("close",(l)=>{o({exitCode:l??1,stdout:s,stderr:a})}),i.stdin.end(r.stdin)});var nf=()=>{};class Zl{#e;#t;dir;constructor(e,t,r){this.#e=e,this.dir=t,this.#t=r}static async clone(e,t,r,o){let n=new Zl(e,r,o);return await C8(e,"git",["-c","credential.helper=","-c",`credential.helper=${P8}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",P8]),await n.run(["reset","--hard","origin/main"]),n}async run(e,t=!0){let r=await this.#e("git",e,{cwd:this.dir,env:this.environment()});if(t&&r.exitCode!==0)throw io("git",e,r);return r}async output(e){return(await this.run(e)).stdout.trim()}async sync(e=!1){if(await this.run(["fetch","origin","main"]),e)await this.run(["reset","--hard","origin/main"]);else await this.run(["pull","--rebase","origin","main"])}async commitAll(e){await this.run(["add","-A"]),await this.run(["-c","user.name=brains-ops","-c","user.email=ops@rizom.ai","commit","-m",e])}async pushMainWithRebase(){for(let e=1;e<=5;e+=1){if((await this.run(["push","origin","main"],!1)).exitCode===0)return;await this.run(["pull","--rebase","origin","main"])}throw Error("Unable to push content main after five rebase attempts")}async pruneStressBackupBranches(){let t=(await this.run(["ls-remote","--heads","origin","refs/heads/ops/directory-sync-stress-backup-*"])).stdout.split(/\r?\n/).map((r)=>r.match(/\trefs\/heads\/(ops\/directory-sync-stress-backup-[^\s]+)$/)?.[1]).filter((r)=>r!==void 0).sort();for(let r of t)await this.run(["push","origin","--delete",r]);return t}environment(){return{GH_TOKEN:this.#t,GITHUB_TOKEN:this.#t}}}var P8='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var z8=v(()=>{nf()});function of(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class M${#e;#t=[];#r=[];#n=new Set(["/health/ready"]);#o=!0;#i;#a;#s="";#c=0;#l;constructor(e){this.#e=e}get startedAt(){return this.#s}get error(){return this.#a}get healthSamples(){return this.#t}get runtimeSamples(){return this.#r}gateHealthSamples(){return this.#t.slice(this.#c,this.#l??this.#t.length)}markGateEnd(){this.#l=this.#t.length}async discoverEndpoints(){for(let e of["/health/live","/health/operate"])if((await Z$(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:5000})).status!==404)this.#n.add(e)}start(){this.#o=!1,this.#a=void 0,this.#c=this.#t.length,this.#l=void 0,this.#s=this.#e.now().toISOString(),this.#i=Promise.all([this.#m(),this.#f()]).then(()=>{return}).catch((e)=>{this.#a=e,this.#o=!0})}async stop(){this.#o=!0,await this.#i}async waitForHealthSnapshot(e){return this.waitForEntityBaseline(void 0,void 0,e)}async waitForEntityBaseline(e,t,r){let o=this.#e.now().getTime();while(this.#e.now().getTime()-o<r){let n=await this.fetchHealthPayload();if(this.#p(n,e,t))return n;await this.#e.sleep(5000)}return}async waitForStableEntityBaseline(e,t,r){let o=this.#e.now().getTime(),n=0;while(this.#e.now().getTime()-o<r){let i=await this.fetchHealthPayload();if(this.#p(i,e,t)){if(n+=1,n===2)return i}else n=0;await this.#e.sleep(5000)}return}async fetchHealthPayload(){let e=await this.#d();if(e===void 0)return;let t=await this.#e.readEntityCounts();if(!t)return;return{version:e,entities:t.reduce((r,o)=>r+o.count,0),entityCounts:t}}async#d(){let e=this.#e.now(),t=new AbortController,r=setTimeout(()=>t.abort(),20000);try{let o=await this.#e.fetchImpl(`https://${this.#e.domain}/health/operate`,{signal:t.signal}),n=await o.text();if(this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:o.status,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:o.ok}),!o.ok)return;return Hhe.parse(JSON.parse(n)).app.version}catch(o){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:o instanceof Error?`${o.name}: ${o.message}`:String(o)});return}finally{clearTimeout(r)}}#p(e,t,r){return e!==void 0&&(t===void 0||of(e)===t)&&(r===void 0||e.entities===r)}async#m(){while(!this.#o){for(let e of this.#n)this.#t.push(await Z$(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:20000}));await this.#e.sleep(4000)}}async#f(){while(!this.#o){let e=await this.#e.sampleRuntime();if(e)this.#r.push(e);await this.#e.sleep(1000)}}}var N8,Hhe;var D8=v(()=>{pe();U$();N8=c.array(c.object({entityType:c.string(),count:c.number().int().nonnegative()})),Hhe=c.object({status:c.literal("ready"),operationalStatus:c.literal("operational"),app:c.object({version:c.string()})})});var Cb={};Lt(Cb,{applyDirectorySyncStressPhase:()=>Z8,cleanupDirectorySyncStress:()=>oge,listProbeFiles:()=>xa,parseStressRuntimeSample:()=>U8,removeProbeFiles:()=>W$,runDeployedDirectorySyncStress:()=>rge,runStressCommand:()=>Wo,verifyDirectorySyncStressAccess:()=>nge});import{chmod as Vhe,mkdir as F$,mkdtemp as J$,readFile as Whe,readdir as Ghe,rename as Qhe,rm as af,writeFile as Tn}from"fs/promises";import{tmpdir as K$}from"os";import{join as ct,resolve as H$}from"path";async function rge(e){let t=e.now??(()=>new Date),r=t().toISOString(),o=G$(r),n=H$(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",o));await F$(n,{recursive:!0});let{pilot:i,user:s}=await V$(e.rootDir,e.handle);Ob({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=Tb.parse(e.profile),l=e.plan?$b.parse(e.plan):$8(a);if(l.profile!==a)throw Error(`Directory-sync stress plan profile ${l.profile} does not match requested profile ${a}`);if((l.maximumExternalAiCalls??0)===0)j8(s);let u=Yhe.parse(e.env??process.env),d=new B8({runId:o,artifactsDir:n,user:s,githubOrg:i.githubOrg,serverLabel:`${i.contentRepoPrefix}${s.handle}`,environment:u,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??Wo,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),p;try{p=await O8(l,d)}finally{await d.dispose()}let m={runId:o,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${i.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:p};return await age(m),m}async function nge(e){let r=(e.now??(()=>new Date))().toISOString(),o=G$(r),n=H$(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",`access-check-${o}`));await F$(n,{recursive:!0});let{pilot:i,user:s}=await V$(e.rootDir,e.handle);Ob({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),j8(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let l=await J$(ct(K$(),"brains-ops-directory-sync-access-check-"));try{let u=await Zl.clone(e.commandRunner??Wo,`${i.githubOrg}/${s.contentRepo}`,ct(l,"content"),a),d=await u.output(["rev-parse","HEAD"]);await u.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${o}`]);let p={success:!0,artifactsDir:n,checkedAt:r,remoteHead:d,target:{handle:s.handle,domain:s.domain,contentRepo:`${i.githubOrg}/${s.contentRepo}`}};return await Tn(ct(n,"access-check.json"),`${JSON.stringify(p,null,2)}
431
431
  `),p}finally{await af(l,{recursive:!0,force:!0})}}async function oge(e){let t=e.now??(()=>new Date),r=H$(e.artifactsDir??ct(e.rootDir,".brains-ops","stress",`cleanup-${G$(t().toISOString())}`));await F$(r,{recursive:!0});let{pilot:o,user:n}=await V$(e.rootDir,e.handle);Ob({handle:n.handle,domain:n.domain,contentRepo:n.contentRepo,confirmation:e.confirmation});let i=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!i)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let s=e.commandRunner??Wo,a=e.logger??console.info,l=await J$(ct(K$(),"brains-ops-directory-sync-cleanup-")),u=ct(l,"content");try{let d=await Zl.clone(s,`${o.githubOrg}/${n.contentRepo}`,u,i),p=await W$(d.dir),m;if(p>0)await d.commitAll("test(directory-sync): clean residual stress probes"),await d.pushMainWithRebase(),m=await d.output(["rev-parse","HEAD"]),a(`Removed ${p} directory-sync stress probes`);let h=(await xa(d.dir)).length,b=h===0?await d.pruneStressBackupBranches():[],y={success:h===0,artifactsDir:r,probesRemoved:p,probesRemaining:h,backupBranchesDeleted:b,...m?{cleanupCommit:m}:{}};return await Tn(ct(r,"cleanup.json"),`${JSON.stringify(y,null,2)}
432
432
  `),y}finally{await af(l,{recursive:!0,force:!0})}}class B8{#e;#t;#r;#n;#o;#i;#a;#s;#c;#l;#d;constructor(e){this.#e=e,this.#t=new M$({domain:e.user.domain,fetchImpl:e.fetchImpl,now:e.now,sleep:e.sleep,sampleRuntime:()=>this.#b(),readEntityCounts:()=>this.#y()})}async prepare(e){this.#r=await J$(ct(K$(),"brains-ops-directory-sync-stress-"));let t=ct(this.#r,"content");this.#o=ct(this.#r,"id_ed25519"),this.#i=ct(this.#r,"known_hosts"),this.#a=await this.#m(),await Tn(this.#o,sge(this.#e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await Vhe(this.#o,384);let r=await this.#S("ssh-keyscan",["-T","10","-t","ed25519",this.#a]);if(r.exitCode!==0||!r.stdout.trim())throw Error("Unable to resolve smoke SSH host key");await Tn(this.#i,r.stdout,{mode:384});let o=await this.#h(["docker","ps","--filter","label=service=rover","--filter","label=role=web","--format","{{.Names}}"]);if(this.#s=o.stdout.trim().split(/\r?\n/)[0],!this.#s||!/^[A-Za-z0-9_.-]+$/.test(this.#s))throw Error("Unable to resolve a running smoke container");let n=await Zl.clone(this.#e.commandRunner,`${this.#e.githubOrg}/${this.#e.user.contentRepo}`,t,this.#e.environment.CONTENT_REPO_ADMIN_TOKEN);if(this.#n=n,(await xa(n.dir)).length>0)throw Error("Directory-sync stress probes already exist");let i=await n.output(["rev-parse","HEAD"]);this.#l=await n.output(["rev-parse","HEAD^{tree}"]),this.#d=await this.#p();let s=await this.#t.waitForHealthSnapshot(60000);if(!s)throw Error("Smoke health was unavailable before stress testing");return this.#c=`ops/directory-sync-stress-backup-${this.#e.runId}`,await n.run(["push","origin",`HEAD:refs/heads/${this.#c}`]),await this.#t.discoverEndpoints(),await Tn(ct(this.#e.artifactsDir,"state.json"),`${JSON.stringify({runId:this.#e.runId,profile:e.profile,originalHead:i,originalTree:this.#l,backupBranch:this.#c,baseline:{entities:s.entities,notes:of(s),version:s.version}},null,2)}
433
433
  `),this.#e.logger(`Prepared ${e.profile} directory-sync stress run for ${this.#e.user.handle}`),{entities:s.entities,notes:of(s),version:s.version}}async startMonitoring(){this.#v(),this.#t.start()}async executePhase(e,t){this.#v();let r=this.#n;if(!r)throw Error("Directory-sync stress checkout is not prepared");await r.sync();let o=this.#t.healthSamples.length,n=this.#e.now().getTime(),i=await this.#g();if(i?.pending!==0||i.processing!==0)return Ul(e,"health did not provide a drained queue before the phase");await Z8(r.dir,e),await r.commitAll(`test(directory-sync): stress ${e.id}`),await r.pushMainWithRebase();let s=this.#e.now().getTime(),a=await r.output(["rev-parse","HEAD"]),l=await this.#f(a,900000);if(l===void 0)return Ul(e,"runtime did not pull the phase commit");let u;if(e.operation==="rename"){let h=t.notes+e.targetProbeCount;if(e.settleMs>0)await this.#e.sleep(e.settleMs);let b=await this.#t.waitForStableEntityBaseline(h,void 0,1200000);if(u=this.#e.now().getTime()-s,!b)return Ul(e,`health did not stabilize at ${h} notes`,l,u)}else if(e.operation==="add"||e.operation==="delete"){let h=t.notes+e.targetProbeCount,b=this.#e.now().getTime(),y=await this.#t.waitForEntityBaseline(h,void 0,1200000);if(u=this.#e.now().getTime()-b,!y)return Ul(e,`health did not reach ${h} notes`,l,u)}if(e.operation!=="rename"&&e.settleMs>0)await this.#e.sleep(e.settleMs);let d=e.operation==="delete"?0:Math.ceil(e.count/50);if(!await this.#u(i.completedImports+d,1200000))return Ul(e,`health did not observe ${d} completed import job(s) with a drained queue`,l,u);let m=this.#t.healthSamples.slice(o).find((h)=>!h.ok);if(m)return Ul(e,`${m.endpoint} unavailable (${m.status===0?m.error??"unknown":m.status})`,l,u);return this.#e.logger(`Completed ${e.id} in ${this.#e.now().getTime()-n}ms`),{id:e.id,operation:e.operation,count:e.count,success:!0,commitLatencyMs:l,...u===void 0?{}:{persistenceLatencyMs:u}}}async cleanup(e){let t=this.#n;if(!t)return{success:!1,probesRemaining:0,error:"stress checkout was not prepared"};try{if(await t.sync(!0),await W$(t.dir)>0)await t.commitAll("test(directory-sync): remove stress probes"),await t.pushMainWithRebase();let o=(await xa(t.dir)).length;this.#t.markGateEnd();let n=await this.#t.waitForEntityBaseline(e.notes,e.entities,1200000);await t.sync(!0);let s=await t.output(["rev-parse","HEAD^{tree}"])===this.#l,a=o===0&&n!==void 0&&s;if(a&&this.#c){if((await t.run(["push","origin","--delete",this.#c],!1)).exitCode!==0)this.#e.logger(`Warning: unable to delete backup branch ${this.#c}`)}return{success:a,probesRemaining:o,...n?{finalEntities:n.entities,finalNotes:of(n)}:{},contentTreeRestored:s,...!a?{error:!n?"entity baseline was not restored before cleanup timeout":!s?"content tree differs from the pre-stress baseline":"stress probes remain after cleanup"}:{}}}catch(r){return{success:!1,probesRemaining:(await xa(t.dir)).length,error:Ve(r)}}}async stopMonitoring(){await this.#t.stop(),await Tn(ct(this.#e.artifactsDir,"health-samples.json"),`${JSON.stringify(this.#t.healthSamples,null,2)}
@@ -441,7 +441,7 @@ Update marker: ${t.id}.
441
441
  `}function G$(e){return e.replace(/[-:.TZ]/g,"").slice(0,14)}async function age(e){await Tn(ct(e.artifactsDir,"report.json"),`${JSON.stringify(e,null,2)}
442
442
  `),await Tn(ct(e.artifactsDir,"report.md"),cge(e))}function cge(e){let t=e.report.metrics.runtime,r=e.report.metrics.health,o=t.map((a)=>a.cpuPercent).sort((a,l)=>a-l),n=t.map((a)=>a.memoryPercent),i=r.filter((a)=>!a.ok),s=["# Directory-sync stress report","",`- Run: \`${e.runId}\``,`- Target: \`${e.target.handle}\` (${e.target.domain})`,`- Profile: \`${e.report.profile}\``,`- Version: \`${e.report.baseline.version}\``,`- Result: **${e.report.success?"PASS":"FAIL"}**`,`- Started: ${e.startedAt}`,`- Completed: ${e.completedAt}`,"","## Phases","","| Phase | Operation | Count | Result | Pull latency | Persistence latency |","| --- | --- | ---: | --- | ---: | ---: |",...e.report.phases.map((a)=>`| ${a.id} | ${a.operation} | ${a.count} | ${a.success?"pass":`fail: ${a.error??"unknown"}`} | ${L8(a.commitLatencyMs)} | ${L8(a.persistenceLatencyMs)} |`),"","## Runtime","",`- Samples: ${t.length}`,`- CPU p50/p95/p99/max: ${sf(q$(o,0.5))} / ${sf(q$(o,0.95))} / ${sf(q$(o,0.99))} / ${sf(o.at(-1))}`,`- Memory max: ${sf(n.length?Math.max(...n):void 0)}`,`- PIDs max: ${t.length?Math.max(...t.map((a)=>a.pids)):"n/a"}`,`- Container status/restarts/OOM: ${e.report.metrics.container?`${e.report.metrics.container.status} / ${e.report.metrics.container.restartCount} / ${e.report.metrics.container.oomKilled}`:"unknown"}`,`- External AI calls: ${e.report.metrics.externalAiCalls??0}`,`- Health samples: ${r.length}`,`- Health failures: ${i.length}`,"","## Cleanup","",`- Result: ${e.report.cleanup.success?"pass":"fail"}`,`- Remaining probes: ${e.report.cleanup.probesRemaining}`,`- Final entities: ${e.report.cleanup.finalEntities??"unknown"}`,`- Final notes: ${e.report.cleanup.finalNotes??"unknown"}`,`- Content tree restored: ${e.report.cleanup.contentTreeRestored??"unknown"}`,""];if(e.report.failure)s.push("## Failure","",e.report.failure,"");return`${s.join(`
443
443
  `)}
444
- `}function q$(e,t){if(e.length===0)return;let r=Math.max(0,Math.ceil(e.length*t)-1);return e[r]}function sf(e){return e===void 0?"n/a":`${e.toFixed(2)}%`}function L8(e){return e===void 0?"n/a":`${(e/1000).toFixed(1)}s`}var Yhe,Xhe,ege,tge;var Pb=v(()=>{pe();U$();gn();nf();z8();D8();nf();Yhe=c.object({HCLOUD_TOKEN:c.string().min(1),KAMAL_SSH_PRIVATE_KEY:c.string().min(1),CONTENT_REPO_ADMIN_TOKEN:c.string().min(1)}),Xhe=c.object({servers:c.array(c.object({id:c.number().int(),status:c.string(),public_net:c.object({ipv4:c.object({ip:c.string().min(1)})})}))}),ege=c.object({status:c.literal("ready"),operationalStatus:c.literal("operational"),resources:c.object({queue:c.object({totals:c.object({pending:c.number().int().nonnegative(),processing:c.number().int().nonnegative()}),byType:c.array(c.object({type:c.string(),status:c.string(),count:c.number().int().nonnegative()}))})})}),tge=['import { Database } from "bun:sqlite";','const path = (process.env.XDG_DATA_HOME || "./data") + "/brain.db";',"const db = new Database(path, { readonly: true });",'const rows = db.query(`SELECT "entityType" AS "entityType", COUNT(*) AS "count" FROM entities GROUP BY "entityType"`).all();',"process.stdout.write(JSON.stringify(rows));"].join(" ")});var M8=v(()=>{vi()});var lge="/usr/local/sbin/brains-health-watchdog",uge="ai.rizom.brain.watchdog",dge="true",Q$,q8,p8e;var F8=v(async()=>{M8();Q$=`${uge}=${dge}`,q8=`#!/usr/bin/env bash
444
+ `}function q$(e,t){if(e.length===0)return;let r=Math.max(0,Math.ceil(e.length*t)-1);return e[r]}function sf(e){return e===void 0?"n/a":`${e.toFixed(2)}%`}function L8(e){return e===void 0?"n/a":`${(e/1000).toFixed(1)}s`}var Yhe,Xhe,ege,tge;var Pb=v(()=>{pe();U$();gn();nf();z8();D8();nf();Yhe=c.object({HCLOUD_TOKEN:c.string().min(1),KAMAL_SSH_PRIVATE_KEY:c.string().min(1),CONTENT_REPO_ADMIN_TOKEN:c.string().min(1)}),Xhe=c.object({servers:c.array(c.object({id:c.number().int(),status:c.string(),public_net:c.object({ipv4:c.object({ip:c.string().min(1)})})}))}),ege=c.object({status:c.literal("ready"),operationalStatus:c.literal("operational"),resources:c.object({queue:c.object({totals:c.object({pending:c.number().int().nonnegative(),processing:c.number().int().nonnegative()}),byType:c.array(c.object({type:c.string(),status:c.string(),count:c.number().int().nonnegative()}))})})}),tge=['import { Database } from "bun:sqlite";','const path = (process.env.XDG_DATA_HOME || "./data") + "/brain.db";',"const db = new Database(path, { readonly: true });",'const rows = db.query(`SELECT "entityType" AS "entityType", COUNT(*) AS "count" FROM entities GROUP BY "entityType"`).all();',"process.stdout.write(JSON.stringify(rows));"].join(" ")});var M8=v(()=>{vi()});var lge="/usr/local/sbin/brains-health-watchdog",uge="ai.rizom.brain.watchdog",dge="true",Q$,q8,m8e;var F8=v(async()=>{M8();Q$=`${uge}=${dge}`,q8=`#!/usr/bin/env bash
445
445
  set -euo pipefail
446
446
  umask 077
447
447
 
@@ -500,7 +500,7 @@ while read -r container_id; do
500
500
  logger -t brains-health-watchdog "restarting unhealthy container=$container_name service=$service_name incident=$incident_path"
501
501
  docker restart "$container_id"
502
502
  done < <(docker ps --filter health=unhealthy --filter label=${Q$} --format '{{.ID}}')
503
- `,p8e=`[Unit]
503
+ `,m8e=`[Unit]
504
504
  Description=Restart persistently unhealthy Brain containers
505
505
  After=docker.service
506
506
  Requires=docker.service
@@ -741,7 +741,7 @@ printf 'REMOTE_ARTIFACT_DIR=%s\\n' "$remote_dir"
741
741
  `).replace(/\\n/g,`
742
742
  `).trimEnd()}
743
743
  `}var W8,gge;var rO=v(async()=>{pe();J8();gn();nf();Ys();await F8();W8=c.object({HCLOUD_TOKEN:c.string().min(1),KAMAL_SSH_PRIVATE_KEY:c.string().min(1)}),gge=c.object({servers:c.array(c.object({status:c.string(),public_net:c.object({ipv4:c.object({ip:c.string().min(1)})})}))})});import{parseArgs as LJ}from"util";function nt(e){return e}class lf extends Error{constructor(e){super(e);this.name="CliUsageError"}}function BJ(e,t){let r={...t};for(let o of e)for(let[n,i]of Object.entries(o.flags??{})){let s=r[n];if(s===void 0){r[n]=i;continue}if(s.type!==i.type||s.short!==i.short||s.default!==i.default)throw Error(`Conflicting definitions for flag --${n}: commands must agree on type, short, and default`)}return r}function jJ(e){let t={};for(let[r,o]of Object.entries(e))t[r]={type:o.type,...o.short!==void 0?{short:o.short}:{},...o.default!==void 0?{default:o.default}:{}};return t}function ZJ(e){if(!(e instanceof Error)||!("code"in e))return!1;return e.code==="ERR_PARSE_ARGS_UNKNOWN_OPTION"||e.code==="ERR_PARSE_ARGS_INVALID_OPTION_VALUE"}function iO(e,t){let r=BJ(t.commands,t.globalFlags??{}),o,n;try{({values:o,positionals:n}=LJ({args:e,options:jJ(r),allowPositionals:!0,strict:t.strict??!0}))}catch(s){if(ZJ(s))throw new lf(s.message.split(". ")[0]??s.message);throw s}if("help"in r&&o.help===!0)return{command:"help",args:[],flags:{help:!0}};if("version"in r&&o.version===!0)return{command:"version",args:[],flags:{version:!0}};let i={};for(let[s,a]of Object.entries(r)){let l=o[s];if(typeof l==="string"&&a.type==="string")i[s]=l;else if(typeof l==="boolean"&&a.type==="boolean")i[s]=l}return{command:n[0]??"help",args:n.slice(1),flags:i}}function sO(e){let t=e.reduce((r,o)=>Math.max(r,o.label.length),0);return e.map((r)=>` ${r.label.padEnd(t)} ${r.description}`)}function UJ(e){return sO(e.map((t)=>({label:t.usage?`${t.name} ${t.usage}`:t.name,description:t.description})))}function MJ(e,t){let r=t.type==="string"?` ${t.placeholder??"<value>"}`:"",o=t.short!==void 0?`, -${t.short}`:"";return`--${e}${r}${o}`}function aO(e){return sO(Object.entries(e).map(([t,r])=>({label:MJ(t,r),description:r.description})))}function cO(e,t){return`Usage: ${e} ${t.name}${t.usage?` ${t.usage}`:""}`}function qJ(e){return JSON.stringify(Object.entries(e).map(([t,r])=>[t,r.type,r.short??"",r.description,r.placeholder??"",r.default??""]).sort((t,r)=>String(t[0]).localeCompare(String(r[0]))))}function FJ(e){let t=[],r=new Map;for(let n of e){let i=n.flags??{};if(Object.keys(i).length===0)continue;let s=qJ(i),a=r.get(s);if(a){a.names.push(n.name);continue}let l={names:[n.name],flags:i};r.set(s,l),t.push(l)}let o=[];for(let n of t)o.push("",`${n.names.join(" / ")} options:`),o.push(...aO(n.flags));return o}function lO(e){let t=[e.intro,"",`Usage: ${e.cliName} ${e.usage??"<command> [args]"}`,"","Commands:",...UJ(e.commands)];if(e.globalFlags&&Object.keys(e.globalFlags).length>0)t.push("","Options:",...aO(e.globalFlags));return t.push(...FJ(e.commands)),t.join(`
744
- `)}function uO(e){let t=new Map;for(let r of e){if(t.has(r.name))throw Error(`Duplicate command name: ${r.name}`);t.set(r.name,r)}return t}function ot(e,t){let r=e[t];return typeof r==="string"?r:void 0}function ps(e,t){let r=e[t];return typeof r==="boolean"?r:void 0}var uf={name:"@rizom/ops",version:"0.2.0-alpha.756",description:"Operator CLI for managing private brain fleet registry repos",keywords:["brains","ops","cli","deploy","fleet","operator"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{"brains-ops":"./dist/brains-ops.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@libsql/client":"^0.17.4","age-encryption":"^0.3.0",yaml:"^2.9.0"},devDependencies:{"@brains/contracts":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/job-queue":"workspace:*","@brains/profile":"workspace:*","@brains/site-composition":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js",bun:"./dist/deploy.js"}},files:["dist","templates"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brains-ops#readme",main:"./dist/index.js",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brains-ops"},scripts:{build:"bun scripts/build.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun test --timeout 20000","test:smoke":"bun run build && RUN_SMOKE_TESTS=1 bun test --timeout 60000",typecheck:"tsc --noEmit"},type:"module",types:"./dist/index.d.ts"};Ov();vi();import{writeFile as iX}from"fs/promises";import{join as Ij}from"path";import{createSign as CW,generateKeyPairSync as PW}from"crypto";import{mkdir as zW,writeFile as uD}from"fs/promises";import{join as dD}from"path";async function MV(e){let t=await e.text();if(!t.trim())return;try{return JSON.parse(t)}catch{return t}}async function Qa(e,t,r){let o=await MV(e),n=t.safeParse(o);if(!e.ok||!n.success){let i=r.formatError??qV;throw Error(`${r.label}${i(e,o)}`)}return n.data}function qV(e,t){let r=t===void 0?"":`: ${typeof t==="string"?t:JSON.stringify(t)}`;return` (${e.status} ${e.statusText}${r})`}pe();var NW="2.5.4.3",DW="1.2.840.113549.1.1.11",mD="https://api.cloudflare.com/client/v4",LW="origin-rsa",BW=5475,hD=15000;function gD(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}var pD=c.looseObject({message:c.string().optional()}),jW=c.looseObject({errors:c.array(pD).optional(),messages:c.array(pD).optional()}),ZW=c.looseObject({certificate:c.string().min(1),expires_on:c.string().optional()}),UW=c.looseObject({success:c.literal(!0),result:ZW}),MW=c.looseObject({success:c.literal(!0)});function qW(){let{privateKey:e,publicKey:t}=PW("rsa",{modulusLength:2048,privateKeyEncoding:{type:"pkcs8",format:"pem"},publicKeyEncoding:{type:"spki",format:"der"}});return{privateKeyPem:e,publicKeyDer:Buffer.from(t)}}function FW(e,t){let r=wd(QW(wd(fD(NW),VW(e)))),o=wd(HW(0),r,Buffer.from(t.publicKeyDer),YW(0,Buffer.alloc(0))),n=CW("sha256").update(o).sign(t.privateKeyPem),i=wd(o,wd(fD(DW),GW()),WW(n));return{csrPem:KW("CERTIFICATE REQUEST",i),certificationRequestInfoDer:o,signature:n}}async function JW(e,t,r,o){let n=await e(`${mD}/certificates`,{method:"POST",headers:gD(t),body:JSON.stringify({hostnames:[o,`*.${o}`],requested_validity:BW,request_type:LW,csr:r}),signal:AbortSignal.timeout(hD)}),i=await Qa(n,UW,{label:"Cloudflare Origin CA request failed",formatError:bD}),a={certificatePem:`${i.result.certificate.trim()}
744
+ `)}function uO(e){let t=new Map;for(let r of e){if(t.has(r.name))throw Error(`Duplicate command name: ${r.name}`);t.set(r.name,r)}return t}function ot(e,t){let r=e[t];return typeof r==="string"?r:void 0}function ps(e,t){let r=e[t];return typeof r==="boolean"?r:void 0}var uf={name:"@rizom/ops",version:"0.2.0-alpha.757",description:"Operator CLI for managing private brain fleet registry repos",keywords:["brains","ops","cli","deploy","fleet","operator"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{"brains-ops":"./dist/brains-ops.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@libsql/client":"^0.17.4","age-encryption":"^0.3.0",yaml:"^2.9.0"},devDependencies:{"@brains/contracts":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/job-queue":"workspace:*","@brains/profile":"workspace:*","@brains/site-composition":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js",bun:"./dist/deploy.js"}},files:["dist","templates"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brains-ops#readme",main:"./dist/index.js",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brains-ops"},scripts:{build:"bun scripts/build.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun test --timeout 20000","test:smoke":"bun run build && RUN_SMOKE_TESTS=1 bun test --timeout 60000",typecheck:"tsc --noEmit"},type:"module",types:"./dist/index.d.ts"};Ov();vi();import{writeFile as iX}from"fs/promises";import{join as Ij}from"path";import{createSign as CW,generateKeyPairSync as PW}from"crypto";import{mkdir as zW,writeFile as uD}from"fs/promises";import{join as dD}from"path";async function MV(e){let t=await e.text();if(!t.trim())return;try{return JSON.parse(t)}catch{return t}}async function Qa(e,t,r){let o=await MV(e),n=t.safeParse(o);if(!e.ok||!n.success){let i=r.formatError??qV;throw Error(`${r.label}${i(e,o)}`)}return n.data}function qV(e,t){let r=t===void 0?"":`: ${typeof t==="string"?t:JSON.stringify(t)}`;return` (${e.status} ${e.statusText}${r})`}pe();var NW="2.5.4.3",DW="1.2.840.113549.1.1.11",mD="https://api.cloudflare.com/client/v4",LW="origin-rsa",BW=5475,hD=15000;function gD(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}var pD=c.looseObject({message:c.string().optional()}),jW=c.looseObject({errors:c.array(pD).optional(),messages:c.array(pD).optional()}),ZW=c.looseObject({certificate:c.string().min(1),expires_on:c.string().optional()}),UW=c.looseObject({success:c.literal(!0),result:ZW}),MW=c.looseObject({success:c.literal(!0)});function qW(){let{privateKey:e,publicKey:t}=PW("rsa",{modulusLength:2048,privateKeyEncoding:{type:"pkcs8",format:"pem"},publicKeyEncoding:{type:"spki",format:"der"}});return{privateKeyPem:e,publicKeyDer:Buffer.from(t)}}function FW(e,t){let r=wd(QW(wd(fD(NW),VW(e)))),o=wd(HW(0),r,Buffer.from(t.publicKeyDer),YW(0,Buffer.alloc(0))),n=CW("sha256").update(o).sign(t.privateKeyPem),i=wd(o,wd(fD(DW),GW()),WW(n));return{csrPem:KW("CERTIFICATE REQUEST",i),certificationRequestInfoDer:o,signature:n}}async function JW(e,t,r,o){let n=await e(`${mD}/certificates`,{method:"POST",headers:gD(t),body:JSON.stringify({hostnames:[o,`*.${o}`],requested_validity:BW,request_type:LW,csr:r}),signal:AbortSignal.timeout(hD)}),i=await Qa(n,UW,{label:"Cloudflare Origin CA request failed",formatError:bD}),a={certificatePem:`${i.result.certificate.trim()}
745
745
  `};if(i.result.expires_on)a.expiresOn=i.result.expires_on;return a}async function yD(e,t,r){let o=await e(`${mD}/zones/${r}/settings/ssl`,{method:"PATCH",headers:gD(t),body:JSON.stringify({value:"strict"}),signal:AbortSignal.timeout(hD)});await Qa(o,MW,{label:"Cloudflare zone SSL update failed",formatError:bD})}function KW(e,t){let o=t.toString("base64").match(/.{1,64}/g)??[];return[`-----BEGIN ${e}-----`,...o,`-----END ${e}-----`,""].join(`
746
746
  `)}function HW(e){if(e!==0)throw Error("Only zero-valued INTEGER encoding is currently supported");return Buffer.from([2,1,0])}function fD(e){let t=e.split(".").map((s)=>Number(s));if(t.length<2||t.some((s)=>Number.isNaN(s)))throw Error(`Invalid OID: ${e}`);let r=t[0],o=t[1];if(r===void 0||o===void 0)throw Error(`Invalid OID: ${e}`);let i=[r*40+o];for(let s of t.slice(2)){let a=eG(s);i.push(...a)}return Tc(6,Buffer.from(i))}function VW(e){return Tc(12,Buffer.from(e,"utf8"))}function WW(e){return Tc(3,Buffer.concat([Buffer.from([0]),e]))}function GW(){return Buffer.from([5,0])}function wd(...e){return Tc(48,Buffer.concat(e))}function QW(...e){return Tc(49,Buffer.concat(e))}function YW(e,t){return Tc(160+e,t)}function Tc(e,t){return Buffer.concat([Buffer.from([e]),XW(t.length),t])}function XW(e){if(e<128)return Buffer.from([e]);let t=[],r=e;while(r>0)t.unshift(r&255),r>>=8;return Buffer.from([128|t.length,...t])}function eG(e){if(!Number.isInteger(e)||e<0)throw Error(`Invalid OID component: ${e}`);if(e===0)return[0];let t=[],r=e;while(r>0)t.unshift(r&127),r>>=7;for(let o=0;o<t.length-1;o+=1)t[o]=(t[o]??0)|128;return t}function bD(e,t){let r=tG(t),o=r.length>0?`: ${r.join("; ")}`:"";return` (${e.status} ${e.statusText}${o})`}function tG(e){let t=jW.safeParse(e);if(!t.success)return[];return[...t.data.errors??[],...t.data.messages??[]].map((r)=>r.message).filter((r)=>typeof r==="string"&&r.length>0)}async function SD(e,t,r){let o=qW(),{csrPem:n}=FW(r,o),i=await JW(e,t,n,r);return{certificatePem:i.certificatePem,privateKeyPem:o.privateKeyPem,...i.expiresOn!==void 0&&{expiresOn:i.expiresOn}}}async function vD(e,t){let r=dD(e,"origin.pem"),o=dD(e,"origin.key");return await zW(e,{recursive:!0}),await Promise.all([uD(r,t.certificatePem,"utf-8"),uD(o,t.privateKeyPem,{encoding:"utf-8",mode:384})]),{certificatePath:r,privateKeyPath:o}}gn();Cu();Mn();async function Aj(e,t={}){try{return await sX(e,t),{success:!0}}catch(r){return{success:!1,message:Ve(r,"Certificate bootstrap failed")}}}async function sX(e,t={}){let r=await wt(e),o=cX(r,t.handle),n=o.domain,i=t.env??process.env,s=Lr(e),a=t.cfApiToken??jt("CF_API_TOKEN",i,s),l=t.cfZoneId??o.cloudflareZoneId??jt("CF_ZONE_ID",i,s);if(!a)throw Error("Missing CF_API_TOKEN");if(!l)throw Error("Missing CF_ZONE_ID");let u=t.fetchImpl??fetch,d=t.logger??console.log,p=await SD(u,a,n),m=Ij(e,".brains-ops","certs",o.id),{certificatePath:h,privateKeyPath:b}=await vD(m,p),y=Ij(m,"secrets.yaml");await iX(y,aX(p.certificatePem,p.privateKeyPem),"utf-8"),await yD(u,a,l);let S=Wa(t.pushTo);if(S)await bi([["CERTIFICATE_PEM",p.certificatePem],["PRIVATE_KEY_PEM",p.privateKeyPem]],{logger:d,runCommand:t.runCommand??tr});if(d(`Issued ${o.id} Origin CA cert for ${n} and *.${n}`),d(`Wrote ${h}`),d(`Wrote ${b}`),d(`Wrote ${y}`),p.expiresOn)d(`Expires on ${p.expiresOn}`);if(d("Cloudflare zone SSL mode set to Full (strict)"),S)d(`Pushed CERTIFICATE_PEM and PRIVATE_KEY_PEM to ${S}`);return{domain:n,certificatePath:h,privateKeyPath:b,certificatePem:p.certificatePem,secretsSnippetPath:y}}function aX(e,t){return[`certificatePem: ${kj(e)}`,`privateKeyPem: ${kj(t)}`,""].join(`
747
747
  `)}function kj(e){return`"${e.replace(/"/g,"\\\"").replace(/\n/g,"\\n")}"`}function cX(e,t){if(!t)return{id:"shared",domain:lX(e.pilot.domainSuffix)};let r=e.users.find((o)=>o.handle===t);if(!r)throw Error(`Unknown user handle: ${t}`);return{id:t,domain:r.domain,...r.cloudflareZoneId?{cloudflareZoneId:r.cloudflareZoneId}:{}}}function lX(e){let t=e.trim().replace(/^\./,"").replace(/\.$/,"");if(!t||t.includes("*"))throw Error(`Invalid pilot domainSuffix: ${e}`);return t}import{chmod as qk,mkdir as cg,readFile as $j,writeFile as Tj}from"fs/promises";import{dirname as mX,join as jc}from"path";import{fileURLToPath as hX}from"url";vi();Cd();Ys();var gX=["pilot.yaml","package.json",".env.schema",".gitignore","cohorts/cohort-1.yaml","users/alice.yaml",".github/actions/varlock-env/action.yml",".github/workflows/build.yml",".github/workflows/deploy.yml",".github/workflows/directory-sync-stress.yml",".github/workflows/health-watchdog-smoke.yml",".github/workflows/offboard.yml",".github/workflows/reconcile.yml",".github/workflows/upgrade.yml","deploy/Dockerfile","deploy/kamal/deploy.yml","deploy/scripts/helpers.ts","deploy/scripts/create-predeploy-backup.ts","deploy/scripts/install-health-watchdog.ts","deploy/scripts/provision-server.ts","deploy/scripts/pull-local-models.ts","deploy/scripts/update-dns.ts","deploy/scripts/write-ssh-key.ts","deploy/scripts/decrypt-user-secrets.ts","deploy/scripts/validate-secrets.ts","deploy/scripts/write-kamal-secrets.ts","deploy/scripts/resolve-user-config.ts","deploy/scripts/resolve-missing-images.ts","deploy/scripts/verify-runtime-image.ts","deploy/scripts/resolve-deploy-handles.ts","deploy/scripts/sync-content-repo.ts",".kamal/hooks/pre-deploy","docs/onboarding-checklist.md","docs/canonical-crossover-record.md","docs/operator-playbook.md","docs/user-onboarding.md","README.md"],Fk=new Set([".kamal/hooks/pre-deploy"]),yX=new Set(["cohorts/cohort-1.yaml","users/alice.yaml","docs/canonical-crossover-record.md"]),bX=hX(new URL("../templates/rover-pilot/",import.meta.url));function Ro(e){return(t)=>t.includes(e)}function SX(e){return YP.find((t)=>e===`deploy/scripts/${t}`)}function Jk(e){return e.replace(/\n {2}secret:\n(?: {4}- .*\n)+\nvolumes:\n/,`