@rizom/ops 0.2.0-alpha.398 → 0.2.0-alpha.399
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/brains-ops.js +1 -1
- package/dist/index.js +4 -4
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -437,8 +437,8 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
437
437
|
`)+1;while(t!==0)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
438
438
|
`,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=Iy(e),r=bl(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=Iy(e),r=bl(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()}}}Phe.Parser=fM});var yM=te(function(Fhe){var pM=RA(),Nhe=nf(),uf=of(),Dhe=FI(),Lhe=Ge(),Bhe=FA(),mM=MA();function hM(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Bhe.LineCounter||null,prettyErrors:t}}function jhe(e,t={}){let{lineCounter:r,prettyErrors:i}=hM(t),n=new mM.Parser(r?.addNewLine),o=new pM.Composer(t),s=Array.from(o.compose(n.parse(e)));if(i&&r)for(let a of s)a.errors.forEach(uf.prettifyError(e,r)),a.warnings.forEach(uf.prettifyError(e,r));if(s.length>0)return s;return Object.assign([],{empty:!0},o.streamInfo())}function gM(e,t={}){let{lineCounter:r,prettyErrors:i}=hM(t),n=new mM.Parser(r?.addNewLine),o=new pM.Composer(t),s=null;for(let a of o.compose(n.parse(e),!0,e.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new uf.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(i&&r)s.errors.forEach(uf.prettifyError(e,r)),s.warnings.forEach(uf.prettifyError(e,r));return s}function qhe(e,t,r){let i=void 0;if(typeof t==="function")i=t;else if(r===void 0&&t&&typeof t==="object")r=t;let n=gM(e,r);if(!n)return null;if(n.warnings.forEach((o)=>Dhe.warn(n.options.logLevel,o)),n.errors.length>0)if(n.options.logLevel!=="silent")throw n.errors[0];else n.errors=[];return n.toJS(Object.assign({reviver:i},r))}function Uhe(e,t,r){let i=null;if(typeof t==="function"||Array.isArray(t))i=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(Lhe.isDocument(e)&&!i)return e.toString(r);return new Nhe.Document(e,i,r).toString(r)}Fhe.parse=qhe;Fhe.parseAllDocuments=jhe;Fhe.parseDocument=gM;Fhe.stringify=Uhe});var Khe,Vhe,Whe,ZA,Ghe,Vo,Qhe,Yhe,Xhe,ege,dUe,tge,rge,nge,$y,bM,ige,oge,sge,age,cge,lge,uge,dge,fge,pge,Li,Bi,mge,xl,HA,hge,gge,yge,bge,xge,Sge,wge,vge,_ge,ci,kge,Ege,Ige;var df=x(()=>{Khe=RA(),Vhe=nf(),Whe=gA(),ZA=of(),Ghe=Md(),Vo=Ge(),Qhe=Mo(),Yhe=jt(),Xhe=Ho(),ege=Jo(),dUe=ky(),tge=UA(),rge=FA(),nge=MA(),$y=yM(),bM=Ud();ige=Khe.Composer,oge=Vhe.Document,sge=Whe.Schema,age=ZA.YAMLError,cge=ZA.YAMLParseError,lge=ZA.YAMLWarning,uge=Ghe.Alias,dge=Vo.isAlias,fge=Vo.isCollection,pge=Vo.isDocument,Li=Vo.isMap,Bi=Vo.isNode,mge=Vo.isPair,xl=Vo.isScalar,HA=Vo.isSeq,hge=Qhe.Pair,gge=Yhe.Scalar,yge=Xhe.YAMLMap,bge=ege.YAMLSeq,xge=tge.Lexer,Sge=rge.LineCounter,wge=nge.Parser,vge=$y.parse,_ge=$y.parseAllDocuments,ci=$y.parseDocument,kge=$y.stringify,Ege=bM.visit,Ige=bM.visitAsync});var kM={};tr(kM,{assertPilotUsersRemoved:()=>KA,createPilotOffboardDriver:()=>JA,offboardPilotUsers:()=>SM});import{access as Age,readdir as $ge,readFile as Cge,rm as ff,writeFile as Tge}from"fs/promises";import{basename as Oge,join as ji}from"path";async function SM(e,t){let r=[...new Set(t.handles.map((d)=>Pr.parse(d)))].sort((d,p)=>d.localeCompare(p));if(r.length===0)throw Error("At least one pilot handle is required");let i=t.dryRun??!0,n=`sunset:${r.join(",")}`;if(!i&&t.confirmation!==n)throw Error(`Exact confirmation required: ${n}`);let o=t.env??process.env,s=t.logger??console.info,a=await Tt(e),c=r.map((d)=>Rge(a,d,o)),l=t.driver??JA({env:o,fetchImpl:t.fetchImpl,contentRepoTokenName:a.pilot.contentRepoAdminToken}),u=await Promise.all(c.map(async(d)=>({target:d,inspection:await l.inspect(d)})));if(zge(u),Nge(u,i,s),!i){for(let d of u)if(!d.inspection.contentRepoArchived)await l.archiveContentRepo(d.target),s(`[${d.target.handle}] archived ${d.target.contentRepo}`);for(let d of u)for(let p of d.inspection.dnsRecords)await l.deleteDnsRecord(d.target,p),s(`[${d.target.handle}] deleted DNS ${p.name}`);for(let d of u)if(d.inspection.server)await l.deleteServer(d.target,d.inspection.server),s(`[${d.target.handle}] deleted ${d.target.instanceName}`);await Pge(c,l,t.sleep??((d)=>new Promise((p)=>setTimeout(p,d)))),await Dge(e,r),await Oi(e),await KA(e,r),s(`Removed desired state for ${r.length} pilot user(s)`)}return{dryRun:i,handles:r,confirmation:n,plans:u}}function Rge(e,t,r){let i=e.users.find((u)=>u.handle===t),n=`${t}${e.pilot.domainSuffix}`,o=i?.domain??n,s=II(o,{sharedDomain:e.pilot.domainSuffix}),a=i?.cloudflareZoneId??Cy(r,"CF_ZONE_ID"),c=i?.contentRepo??`${e.pilot.contentRepoPrefix}${t}-content`,l=c.includes("/")?c:`${e.pilot.githubOrg}/${c}`;return{handle:t,instanceName:`rover-${t}`,domain:o,previewDomain:s,...o===n?{}:{wwwDomain:`www.${o}`},contentRepo:l,cloudflareZoneId:a}}async function Pge(e,t,r){for(let i of e)for(let n=1;n<=20;n+=1){let o=await t.inspect(i);if(!o.server&&o.dnsRecords.length===0&&o.contentRepoArchived)break;if(n===20)throw Error(`[${i.handle}] provider cleanup did not converge`);await r(1500)}}function zge(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 i=new Set([t.domain,t.previewDomain,...t.wwwDomain?[t.wwwDomain]:[]]);for(let n of r.dnsRecords){if(!i.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 Nge(e,t,r){r(`${t?"Dry run":"Apply"}: ${e.map(({target:i})=>i.handle).join(", ")}`);for(let{target:i,inspection:n}of e){let o=n.server?`delete ${i.instanceName}`:"already absent",s=n.dnsRecords.length>0?n.dnsRecords.map((c)=>`${c.type} ${c.name}`).join(", "):"already absent",a=n.contentRepoArchived?"already archived":`archive ${i.contentRepo}`;r(`[${i.handle}] server: ${o}; DNS: ${s}; repo: ${a}`)}r("Runtime backups: none")}async function Dge(e,t){let r=new Set(t),i=ji(e,"cohorts");for(let n of(await $ge(i)).filter((o)=>o.endsWith(".yaml"))){let o=ji(i,n),s=await Cge(o,"utf8"),a=ci(s);if(a.errors.length>0)throw Error(`${n}: ${a.errors[0]?.message??"invalid YAML"}`);let c=a.get("members",!0);if(!HA(c))throw Error(`${n}: members must be a sequence`);let l=c.items.filter((u)=>!xl(u)||typeof u.value!=="string"||!r.has(u.value));if(l.length===c.items.length)continue;if(l.length===0){await ff(o);continue}c.items=l,yn.parse(a.toJS()),await Tge(o,a.toString())}for(let n of t)await Promise.all([ff(ji(e,"users",`${n}.yaml`),{force:!0}),ff(ji(e,"users",`${n}.secrets.yaml`),{force:!0}),ff(ji(e,"users",`${n}.secrets.yaml.age`),{force:!0}),ff(ji(e,"users",n),{recursive:!0,force:!0})])}function JA(e){let t=e.fetchImpl??fetch,r=Cy(e.env,"HCLOUD_TOKEN"),i=Cy(e.env,"CF_API_TOKEN"),n=Cy(e.env,e.contentRepoTokenName);return{async inspect(o){let[s,a,c]=await Promise.all([Lge(t,r,o.instanceName),Promise.all([o.domain,o.previewDomain,...o.wwwDomain?[o.wwwDomain]:[]].map((l)=>Bge(t,i,o.cloudflareZoneId,l))).then((l)=>l.flat()),jge(t,n,o.contentRepo)]);if(s.length>1)throw Error(`[${o.handle}] expected at most one server, found ${s.length}`);return{...s[0]?{server:s[0]}:{},dnsRecords:a,contentRepoArchived:c.archived}},async archiveContentRepo(o){await Sl(t,`https://api.github.com/repos/${o.contentRepo}`,{method:"PATCH",headers:wM(n),body:JSON.stringify({archived:!0})},"GitHub repository archive")},async deleteDnsRecord(o,s){if(wl(await Sl(t,`https://api.cloudflare.com/client/v4/zones/${o.cloudflareZoneId}/dns_records/${s.id}`,{method:"DELETE",headers:vM(i)},"Cloudflare DNS delete")).success!==!0)throw Error(`Cloudflare DNS delete failed for ${s.name}`)},async deleteServer(o,s){await Sl(t,`https://api.hetzner.cloud/v1/servers/${s.id}`,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}},"Hetzner server delete",!0)}}}async function Lge(e,t,r){let i=new URL("https://api.hetzner.cloud/v1/servers");i.searchParams.set("label_selector",`brain=${r}`);let o=wl(await Sl(e,i.toString(),{headers:{Authorization:`Bearer ${t}`}},"Hetzner server lookup")).servers;if(!Array.isArray(o))throw Error("Hetzner server lookup returned an invalid payload");return o.map((s)=>{let a=wl(s),c=xM(a.public_net),l=xM(c?.ipv4);return{id:qge(a.id,"Hetzner server id"),name:pf(a.name,"Hetzner server name"),...typeof l?.ip==="string"?{ip:l.ip}:{}}})}async function Bge(e,t,r,i){let n=new URL(`https://api.cloudflare.com/client/v4/zones/${r}/dns_records`);n.searchParams.set("name",i);let o=wl(await Sl(e,n.toString(),{headers:vM(t)},"Cloudflare DNS lookup")),s=o.result;if(o.success!==!0||!Array.isArray(s))throw Error(`Cloudflare DNS lookup failed for ${i}`);return s.map((a)=>{let c=wl(a),l=pf(c.type,"Cloudflare record type");if(l!=="A"&&l!=="CNAME")throw Error(`Unsupported Cloudflare record type ${l} for ${i}`);return{id:pf(c.id,"Cloudflare record id"),name:pf(c.name,"Cloudflare record name"),type:l,content:pf(c.content,"Cloudflare record content")}})}async function jge(e,t,r){let i=wl(await Sl(e,`https://api.github.com/repos/${r}`,{headers:wM(t)},"GitHub repository lookup"));if(typeof i.archived!=="boolean")throw Error(`Invalid repository archive state for ${r}`);return{archived:i.archived}}async function Sl(e,t,r,i,n=!1){let o=await e(t,r),s=await o.text();if(!o.ok)throw Error(`${i} failed (${o.status}): ${s}`);if(!s&&n)return{};try{return JSON.parse(s)}catch{throw Error(`${i} returned an invalid JSON response`)}}function wM(e){return{Accept:"application/vnd.github+json",Authorization:`Bearer ${e}`,"Content-Type":"application/json","X-GitHub-Api-Version":"2022-11-28"}}function vM(e){return{Authorization:`Bearer ${e}`}}function Cy(e,t){let r=e[t];if(!r)throw Error(`Missing required environment variable: ${t}`);return r}function _M(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function wl(e){if(!_M(e))throw Error("Provider returned an unexpected payload");return e}function xM(e){return _M(e)?e:void 0}function pf(e,t){if(typeof e!=="string"||e.length===0)throw Error(`Missing ${t}`);return e}function qge(e,t){if(typeof e!=="number")throw Error(`Missing ${t}`);return e}async function Uge(e){try{return await Age(e),!0}catch{return!1}}async function KA(e,t){for(let r of t)for(let i of[ji(e,"users",`${r}.yaml`),ji(e,"users",`${r}.secrets.yaml.age`),ji(e,"users",r)])if(await Uge(i))throw Error(`Offboarded user state remains: ${Oge(i)}`)}var VA=x(()=>{df();Ln();AI();Bc();$o()});var S8={};tr(S8,{upgradePilotRepo:()=>QSe});import{readFile as KSe}from"fs/promises";import{join as VSe}from"path";async function x8(e){let t=VSe(e,"package.json"),i=WSe.parse(JSON.parse(await KSe(t,"utf8"))).devDependencies?.["@rizom/ops"];if(!i)throw Error(`${t} does not pin @rizom/ops as a devDependency`);return i}async function GSe(e,t){let i=await Bun.spawn(e,{cwd:t,stdout:"inherit",stderr:"inherit"}).exited;if(i!==0)throw Error(`${e.join(" ")} failed with exit ${i}`)}async function QSe(e,t={}){let r=t.exec??GSe,i=await x8(e),n=t.version??"latest";await r(["bun","add","--dev","--exact",`@rizom/ops@${n}`],e);let o=await x8(e);return await r(["bun","x","brains-ops","init","."],e),{from:i,to:o}}var WSe;var w8=x(()=>{Ne();WSe=f.object({devDependencies:f.record(f.string(),f.string()).optional()})});function v8(e){if(e===null||typeof e!=="object"||Array.isArray(e))return!1;let t=YSe(e);return t===Object.prototype||t===null}var YSe;var _8=x(()=>{YSe=Object.getPrototypeOf});function A8(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:[...twe]};return{bundles:["core","media","automation","web","chat","site","publishing","federation"],add:["obsidian-vault"]}}function rwe(e){let t=XSe.parse(e);return Ao.parse({brainVersion:t.brainVersion,bundleContract:Io,...A8(t.preset),githubOrg:t.githubOrg,contentRepoPrefix:t.contentRepoPrefix,domainSuffix:t.domainSuffix,aiApiKey:t.aiApiKey,gitSyncToken:t.gitSyncToken,contentRepoAdminToken:t.contentRepoAdminToken,agePublicKey:t.agePublicKey})}function nwe(e){let t=ewe.parse(e),r=t.presetOverride?A8(t.presetOverride):void 0;return yn.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?{aiApiKeyOverride:t.aiApiKeyOverride}:{},...t.gitSyncTokenOverride?{gitSyncTokenOverride:t.gitSyncTokenOverride}:{}})}function $8(e){let t=ci(e,{keepSourceTokens:!0});if(t.errors.length>0)throw Error(`Invalid desired-state YAML: ${t.errors[0]?.message}`);if(!Li(t.contents))throw Error("Desired-state YAML must contain a mapping");return t}function GC(e,t){if(!Li(e.contents))return;return e.contents.items.find((r)=>xl(r.key)&&r.key.value===t)}function k8(e,t){if(!Bi(e)||!Bi(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 E8(e,t){if(!e||!Bi(t))return;let r=[Bi(e.key)?e.key.commentBefore:void 0,Bi(e.key)?e.key.comment:void 0,Bi(e.value)?e.value.commentBefore:void 0,Bi(e.value)?e.value.comment:void 0].filter((i)=>i!==void 0);if(r.length===0)return;t.commentBefore=[t.commentBefore,...r].filter((i)=>i!==void 0).join(`
|
|
439
439
|
`)}function C8(e,t,r,i){if(!Li(e.contents))throw Error("Desired-state YAML must contain a mapping");let n=e.contents.items.findIndex((s)=>xl(s.key)&&s.key.value===t),o=e.createPair(r,[...i]);if(n>=0){let s=e.contents.items[n];k8(s?.key,o.key),k8(s?.value,o.value),e.contents.items.splice(n,1,o)}else e.contents.add(o);return o}function T8(e){let t=$8(e),r=rwe(t.toJS()),i=GC(t,"schemaVersion"),n=GC(t,"model");E8(i,GC(t,"brainVersion")?.key),t.delete("schemaVersion"),t.set("bundleContract",Io);let o=C8(t,"preset","bundles",r.bundles);if(E8(n,o.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 Ao.parse(t.toJS()),t.toString({lineWidth:0})}function O8(e){let t=$8(e),r=nwe(t.toJS());if(r.bundlesOverride)C8(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 yn.parse(t.toJS()),t.toString({lineWidth:0})}var I8,Xf,XSe,ewe,twe;var R8=x(()=>{Ai();Ne();df();$o();I8=f.enum(["core","default","pro"]),Xf=f.string().min(1),XSe=f.strictObject({schemaVersion:f.literal(1),brainVersion:nn,model:f.literal("rover"),githubOrg:f.string().min(1),contentRepoPrefix:f.string().min(1),domainSuffix:f.string().min(1),preset:I8,aiApiKey:Xf,gitSyncToken:Xf,contentRepoAdminToken:Xf,agePublicKey:f.string().startsWith("age1").min(1)}),ewe=f.strictObject({members:f.array(Pr).min(1),brainVersionOverride:nn.optional(),presetOverride:I8.optional(),aiApiKeyOverride:Xf.optional(),gitSyncTokenOverride:Xf.optional()}).superRefine((e,t)=>{if(new Set(e.members).size!==e.members.length)t.addIssue({code:f.ZodIssueCode.custom,path:["members"],message:"cohort members must be unique"})}),twe=["series","portfolio","content-pipeline","social-media","newsletter","stock-photo"]});function z8(e,t){let r=ci(e,{keepSourceTokens:!0});if(r.errors.length>0||!Li(r.contents))throw Error(`Invalid ${t} YAML`);return r}function cwe(e,t){return e.length===t.length&&e.every((r,i)=>r===t[i])}function N8(e,t,r){if(!cwe(t,r.sourceBundles))throw Error(`${e} source bundles changed after review: expected [${r.sourceBundles.join(", ")}], received [${t.join(", ")}]`)}function D8(e){let t=Nn(e,awe);if(!t.ok)throw Error(`Invalid capability bundle review: ${t.error}`);return t.data}function L8(e,t){let r=z8(e,"pilot desired-state"),i=owe.parse(r.toJS());return N8("pilot.yaml",i.bundles,t),r.set("bundleContract",Io),r.set("bundles",t.targetBundles),Ao.parse(r.toJS()),r.toString({lineWidth:0})}function B8(e,t,r){let i=z8(e,`cohort ${t}`),n=swe.parse(i.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`);N8(`cohort ${t}`,n.bundlesOverride,r),i.set("bundlesOverride",r.targetBundles)}return yn.parse(i.toJS()),i.toString({lineWidth:0})}var iwe,QC,Tb,owe,swe,P8,awe;var j8=x(()=>{Ai();Ne();df();$o();iwe=f.enum(["core","site","publishing","team"]),QC=f.array(iwe).min(1),Tb=f.array(f.string().min(1)),owe=f.strictObject({brainVersion:nn,bundles:QC,add:Tb.optional(),remove:Tb.optional(),githubOrg:f.string().min(1),contentRepoPrefix:f.string().min(1),domainSuffix:f.string().min(1),aiApiKey:f.string().min(1),gitSyncToken:f.string().min(1),contentRepoAdminToken:f.string().min(1),agePublicKey:f.string().startsWith("age1").min(1)}),swe=f.strictObject({members:f.array(Pr).min(1),brainVersionOverride:nn.optional(),bundlesOverride:QC.optional(),addOverride:Tb.optional(),removeOverride:Tb.optional(),aiApiKeyOverride:f.string().min(1).optional(),gitSyncTokenOverride:f.string().min(1).optional()}),P8=f.strictObject({sourceBundles:QC,targetBundles:f.array(jh).min(1)}),awe=f.strictObject({bundleContract:f.literal(Io),pilot:P8,cohorts:f.record(Pr,P8)})});var Z8={};tr(Z8,{loadCapabilityBundleReview:()=>ywe,loadReviewedSitePins:()=>gwe,parseReviewedSitePins:()=>M8,stageLegacyCrossover:()=>xwe});import{access as lwe,cp as uwe,mkdir as q8,readFile as Vl,readdir as F8,writeFile as Kl}from"fs/promises";import{basename as dwe,join as bi,relative as Ob,resolve as U8}from"path";import{fileURLToPath as fwe}from"url";function M8(e){let t=Nn(e,pwe);if(!t.ok)throw Error(`Invalid reviewed site pins: ${t.error}`);return t.data.sites}async function gwe(e){return M8(await Vl(e,"utf8"))}async function ywe(e){return D8(await Vl(e,"utf8"))}async function bwe(e,t){let r=bi(e,"users"),i=(await F8(r,{withFileTypes:!0})).filter((s)=>s.isFile()&&/\.ya?ml$/.test(s.name)).map((s)=>s.name).sort(),n=new Set(Object.keys(t??{})),o=[];for(let s of i){let a=bi(r,s),c=await Vl(a,"utf8"),l=ci(c,{keepSourceTokens:!0});if(l.errors.length>0||!Li(l.contents))throw Error(`Invalid user desired-state YAML: ${s}`);let u=mwe.parse(l.toJS());if(!u.siteOverride)continue;let d=t?.[u.handle];if(!d)throw Error(`User ${u.handle} has a siteOverride but no reviewed site pin`);if(n.delete(u.handle),d.package!==u.siteOverride.package||d.theme!==u.siteOverride.theme)throw Error(`Reviewed site pin identity does not match user ${u.handle}`);if(u.siteOverride.version!==void 0&&u.siteOverride.version!==d.version)throw Error(`Reviewed site version does not match the existing pin for user ${u.handle}`);if(u.siteOverride.themeVersion!==void 0&&u.siteOverride.themeVersion!==d.themeVersion)throw Error(`Reviewed theme version does not match the existing pin for user ${u.handle}`);if(l.setIn(["siteOverride","version"],d.version),d.themeVersion!==void 0)l.setIn(["siteOverride","themeVersion"],d.themeVersion);else l.deleteIn(["siteOverride","themeVersion"]);qh.parse(l.toJS());let p=l.toString({lineWidth:0});if(p!==c)await Kl(a,p),o.push(Ob(e,a))}if(n.size>0)throw Error(`Reviewed site pins do not match site users: ${[...n].sort().join(", ")}`);return o}async function xwe(e,t,r={}){let i=U8(e),n=U8(t);if(i===n||n.startsWith(`${i}/`))throw Error("Crossover output must be outside the source repository");await uwe(i,n,{recursive:!0,errorOnExist:!0,force:!1,filter:(C)=>{let z=dwe(C);return z!==".git"&&z!==".operator"&&z!==".brains-ops"&&z!==".turbo"&&z!=="dist"&&z!=="node_modules"&&z!==".env"&&z!==".env.local"&&!z.endsWith(".secrets.yaml")}});let o=[],s=bi(n,"docs","canonical-crossover-record.md");try{await lwe(s)}catch{await q8(bi(n,"docs"),{recursive:!0}),await Kl(s,await Vl(hwe,"utf8")),o.push("docs/canonical-crossover-record.md")}let a=bi(n,"pilot.yaml"),c=await Vl(a,"utf8"),u=ci(c).toJS();if(!v8(u))throw Error(`${a} is not a YAML mapping`);let d=Array.isArray(u.bundles),p=r.bundleReview,m;if(d){if(!p)throw Error("Current canonical desired state requires an explicit capability bundle review manifest");m=L8(c,p.pilot)}else m=T8(c);await Kl(a,m),o.push("pilot.yaml");let y=bi(n,"cohorts"),g=(await F8(y,{withFileTypes:!0})).filter((C)=>C.isFile()&&/\.ya?ml$/.test(C.name)).map((C)=>C.name).sort(),b=new Set(Object.keys(p?.cohorts??{}));for(let C of g){let z=bi(y,C),j=await Vl(z,"utf8"),E=C.replace(/\.ya?ml$/,""),Z=p?.cohorts[E];if(Z)b.delete(E);await Kl(z,d?B8(j,E,Z):O8(j)),o.push(Ob(n,z))}if(d&&b.size>0)throw Error(`Capability bundle review names unknown cohorts: ${[...b].sort().join(", ")}`);o.push(...await bwe(n,r.sitePins));let v=await Tt(n),A=Bg(v.pilot.githubOrg);for(let C of v.users){let z=await A(C),j=bi(n,"users",C.handle);if(await q8(j,{recursive:!0}),z.brainYaml){let E=bi(j,"brain.yaml");await Kl(E,z.brainYaml),o.push(Ob(n,E))}if(z.envFile){let E=bi(j,".env");await Kl(E,z.envFile),o.push(Ob(n,E))}}return await Oi(n,{registry:v}),o.push("views/users.md"),{outputDir:n,changedFiles:[...new Set(o)].sort()}}var pwe,mwe,hwe;var H8=x(()=>{Ai();_8();Ne();df();TI();R8();j8();Ln();Bc();$o();pwe=f.strictObject({sites:f.record(Pr,$E)}),mwe=f.object({handle:Pr,siteOverride:f.object({package:f.string().min(1),version:nn.optional(),theme:f.string().min(1).optional(),themeVersion:nn.optional()}).optional()}).passthrough(),hwe=fwe(new URL("../templates/rover-pilot/docs/canonical-crossover-record.md",import.meta.url))});var J8="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as K8}from"crypto";function wwe(e){if(e<0)throw RangeError("Wrong ID size");try{if(!ps||ps.length<e)ps=Buffer.allocUnsafe(e*Swe),K8.getRandomValues(ps),Wl=0;else if(Wl+e>ps.length)K8.getRandomValues(ps),Wl=0}catch(t){throw ps=void 0,t}Wl+=e}function V8(e=21){wwe(e|=0);let t="";for(let r=Wl-e;r<Wl;r++)t+=J8[ps[r]&63];return t}var Swe=128,ps,Wl;var W8=()=>{};function to(e=12){return V8(e)}var ep=x(()=>{W8()});import{openSync as vwe,writeSync as _we}from"fs";class fn{static instance=null;level;context;useStderr;format;logFile;fileHandle;constructor(e={},t){if(this.level=e.level??Da.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=vwe(this.logFile,"a")}catch{}}static getInstance(e){if(!fn.instance)fn.instance=new fn(e);else if(e?.useStderr!==void 0)fn.instance.useStderr=e.useStderr;return fn.instance}static resetInstance(){fn.instance=null}static createFresh(e){return new fn(e)}formatEntry(e,t,r){let i=new Date().toISOString();if(this.format==="json"){let n={ts:i,level:e,msg:t};if(this.context)n.ctx=this.context;if(r.length>0)n.data=r;return JSON.stringify(n)}return this.context?`[${i}] [${this.context}] ${t}`:`[${i}] ${t}`}write(e,t,r,i){if(this.format==="json")e(this.formatEntry(t,r,i));else if(i.length>0)e(this.formatEntry(t,r,[]),...i);else e(this.formatEntry(t,r,[]));if(this.fileHandle!==void 0){let n=this.formatJsonEntry(t,r,i);try{_we(this.fileHandle,n+`
|
|
440
|
-
`)}catch{}}}formatJsonEntry(e,t,r){let i={ts:new Date().toISOString(),level:e,msg:t};if(this.context)i.ctx=this.context;if(r.length>0)i.data=r;return JSON.stringify(i)}silly(e,...t){if(this.level<=Da.SILLY)this.write(console.debug.bind(console),"silly",e,t)}verbose(e,...t){if(this.level<=Da.VERBOSE)this.write(console.debug.bind(console),"verbose",e,t)}debug(e,...t){if(this.level<=Da.DEBUG)this.write(console.debug.bind(console),"debug",e,t)}info(e,...t){if(this.level<=Da.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<=Da.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=Da.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new fn({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var Da,g5e;var YC=x(()=>{Da={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};g5e=fn.getInstance()});var XC,kwe,Gl,S5e;var tp=x(()=>{jo();Ne();XC=f.enum(["file_operations","content_operations","data_processing","batch_processing"]),kwe=f.looseObject({pluginId:f.string().optional(),progressToken:f.union([f.string(),f.number()]).optional(),operationType:XC,operationTarget:f.string().optional(),interfaceType:f.string().optional(),conversationId:f.string().optional(),channelId:f.string().optional(),requestedByActor:ol.optional(),requestedByUserId:f.string().optional(),requestedByInterface:f.string().optional(),silent:f.boolean().optional(),provenance:Bo.optional()}),Gl=f.looseObject({pluginId:f.string().optional(),progressToken:f.union([f.string(),f.number()]).optional(),operationType:XC,operationTarget:f.string().optional(),interfaceType:f.string().optional(),conversationId:f.string().optional(),channelId:f.string().optional(),requestedByActor:ol.optional(),requestedByUserId:f.string().optional(),requestedByInterface:f.string().optional(),silent:f.boolean().optional(),provenance:Bo.optional(),rootJobId:f.string()}),S5e=f.enum(["none","skip","replace","coalesce"])});var Ewe,ms=15000;var rp=x(()=>{tp();Ne();Ewe=f.object({id:f.string(),type:f.string(),data:f.string(),status:f.enum(["pending","processing","completed","failed"]),source:f.string().nullable(),priority:f.number(),retryCount:f.number(),maxRetries:f.number(),lastError:f.string().nullable(),createdAt:f.number(),scheduledFor:f.number(),startedAt:f.number().nullable(),completedAt:f.number().nullable(),attemptId:f.string().nullable(),workerSlotId:f.string().nullable(),workerSessionId:f.string().nullable(),leaseExpiresAt:f.number().nullable(),attemptHeartbeatAt:f.number().nullable(),runtimeUpdatedAt:f.number().nullable(),metadata:Gl,progress:f.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:f.unknown().nullable().optional()})});var eT,G8,je,Iwe,Awe,Q8,$we;var hs=x(()=>{Ne();tp();eT=f.enum(["pending","processing","completed","failed"]),G8=f.enum(["completed","failed"]),je={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},Iwe=f.object({id:f.string(),type:f.string(),status:eT,data:f.unknown(),result:f.unknown().optional(),lastError:f.string().optional().nullable(),attempts:f.number(),maxRetries:f.number(),priority:f.number(),createdAt:f.date(),updatedAt:f.date(),processedAt:f.date().optional().nullable(),completedAt:f.date().optional().nullable(),failedAt:f.date().optional().nullable()}),Awe=f.object({jobId:f.string(),type:f.string(),status:G8,result:f.unknown().optional(),error:f.string().optional()}),Q8=f.object({success:f.literal(!1),error:f.string().optional()}),$we=f.object({id:f.string(),type:f.enum(["job","batch"]),status:eT,message:f.string().optional(),progress:f.object({current:f.number(),total:f.number(),percentage:f.number()}).optional(),aggregationKey:f.string().optional(),batchDetails:f.object({totalOperations:f.number(),completedOperations:f.number(),failedOperations:f.number(),currentOperation:f.string().optional(),errors:f.array(f.string()).optional()}).optional(),jobDetails:f.object({jobType:f.string(),priority:f.number(),retryCount:f.number()}).optional(),metadata:Gl})});var Me,fr;var Jn=x(()=>{Me=class Me extends Error{code;extendedCode;rawCode;constructor(e,t,r,i,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=i,this.name="LibsqlError"}};fr=class fr extends Me{statementIndex;constructor(e,t,r,i,n,o){super(e,r,i,n,o);this.statementIndex=t,this.name="LibsqlBatchError"}}});function Y8(e){let t=Cwe.exec(e);if(t===null)throw new Me(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,i=r.scheme,n=r.authority!==void 0?Twe(r.authority):void 0,o=La(r.path),s=r.query!==void 0?Rwe(r.query):void 0,a=r.fragment!==void 0?La(r.fragment):void 0;return{scheme:i,authority:n,path:o,query:s,fragment:a}}function Twe(e){let t=Owe.exec(e);if(t===null)throw new Me("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,i=La(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,o=r.username!==void 0?{username:La(r.username),password:r.password!==void 0?La(r.password):void 0}:void 0;return{host:i,port:n,userinfo:o}}function Rwe(e){let t=e.split("&"),r=[];for(let i of t){if(i==="")continue;let n,o,s=i.indexOf("=");if(s<0)n=i,o="";else n=i.substring(0,s),o=i.substring(s+1);r.push({key:La(n.replaceAll("+"," ")),value:La(o.replaceAll("+"," "))})}return{pairs:r}}function La(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Me(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function np(e,t,r){if(t===void 0)throw new Me(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let i=`${e}:`,n=Pwe(t.host),o=zwe(t.port),a=`//${Nwe(t.userinfo)}${n}${o}`,c=r.split("/").map(encodeURIComponent).join("/");if(c!==""&&!c.startsWith("/"))c="/"+c;return new URL(`${i}${a}${c}`)}function Pwe(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function zwe(e){return e!==void 0?`:${e}`:""}function Nwe(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var Cwe,Owe;var Rb=x(()=>{Jn();Cwe=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();Owe=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var Yl,X8,eH,ip,Pb,Dwe,pr,tH,iH=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),oH=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),sH=(e)=>{let t,r,i,n,o="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(i=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|i<<8|n,o+=ip[t>>18&63]+ip[t>>12&63]+ip[t>>6&63]+ip[t&63]}return s?o.slice(0,s-3)+"===".substring(s):o},nT,tT,zb=(e,t=!1)=>t?iH(tT(e)):tT(e),Lwe=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?pr(192|t>>>6)+pr(128|t&63):pr(224|t>>>12&15)+pr(128|t>>>6&63)+pr(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return pr(240|t>>>18&7)+pr(128|t>>>12&63)+pr(128|t>>>6&63)+pr(128|t&63)}},Bwe,aH=(e)=>e.replace(Bwe,Lwe),rH,Ql=(e,t=!1)=>t?iH(rH(e)):rH(e),nH=(e)=>Ql(e,!0),jwe,qwe=(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 pr((r>>>10)+55296)+pr((r&1023)+56320);case 3:return pr((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return pr((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},cH=(e)=>e.replace(jwe,qwe),lH=(e)=>{if(e=e.replace(/\s+/g,""),!Dwe.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,i,n=[];for(let o=0;o<e.length;)if(t=Pb[e.charAt(o++)]<<18|Pb[e.charAt(o++)]<<12|(r=Pb[e.charAt(o++)])<<6|(i=Pb[e.charAt(o++)]),r===64)n.push(pr(t>>16&255));else if(i===64)n.push(pr(t>>16&255,t>>8&255));else n.push(pr(t>>16&255,t>>8&255,t&255));return n.join("")},iT,uH,dH=(e)=>uH(fH(e)),Uwe,fH=(e)=>oH(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),rT=(e)=>Uwe(fH(e)),Fwe=(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)},pH=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),mH=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,pH(r));e("fromBase64",function(){return rT(this)}),e("toBase64",function(t){return Ql(this,t)}),e("toBase64URI",function(){return Ql(this,!0)}),e("toBase64URL",function(){return Ql(this,!0)}),e("toUint8Array",function(){return dH(this)})},hH=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,pH(r));e("toBase64",function(t){return zb(this,t)}),e("toBase64URI",function(){return zb(this,!0)}),e("toBase64URL",function(){return zb(this,!0)})},Mwe=()=>{mH(),hH()},Xl;var Nb=x(()=>{Yl=typeof Buffer==="function",X8=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,eH=typeof TextEncoder==="function"?new TextEncoder:void 0,ip=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),Pb=((e)=>{let t={};return e.forEach((r,i)=>t[r]=i),t})(ip),Dwe=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,pr=String.fromCharCode.bind(String),tH=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),nT=typeof btoa==="function"?(e)=>btoa(e):Yl?(e)=>Buffer.from(e,"binary").toString("base64"):sH,tT=Yl?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let i=0,n=e.length;i<n;i+=4096)r.push(pr.apply(null,e.subarray(i,i+4096)));return nT(r.join(""))},Bwe=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,rH=Yl?(e)=>Buffer.from(e,"utf8").toString("base64"):eH?(e)=>tT(eH.encode(e)):(e)=>nT(aH(e)),jwe=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,iT=typeof atob==="function"?(e)=>atob(oH(e)):Yl?(e)=>Buffer.from(e,"base64").toString("binary"):lH,uH=Yl?(e)=>tH(Buffer.from(e,"base64")):(e)=>tH(iT(e).split("").map((t)=>t.charCodeAt(0))),Uwe=Yl?(e)=>Buffer.from(e,"base64").toString("utf8"):X8?(e)=>X8.decode(uH(e)):(e)=>cH(iT(e)),Xl={version:"3.8.0",VERSION:"3.8.0",atob:iT,atobPolyfill:lH,btoa:nT,btoaPolyfill:sH,fromBase64:rT,toBase64:Ql,encode:Ql,encodeURI:nH,encodeURL:nH,utob:aH,btou:cH,decode:rT,isValid:Fwe,fromUint8Array:zb,toUint8Array:dH,extendString:mH,extendUint8Array:hH,extendBuiltins:Mwe}});function gs(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 eu{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,i,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=i,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(Zwe),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function Zwe(e){return Array.prototype.map.call(e,Hwe)}function Hwe(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return Xl.fromUint8Array(new Uint8Array(e));else return e}var xi="https://github.com/libsql/libsql-client-ts#supported-urls";var tu=x(()=>{Nb()});function yH(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function op(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:i,tls:n,intMode:o,concurrency:s}=e;s=Math.max(0,s||20),o??="number";let a=[];if(r===gH)r="file::memory:";let c=Y8(r),l=c.scheme.toLowerCase(),u=l==="file"&&c.path===gH&&c.authority===void 0,d;if(u)d={cache:{values:["shared","private"],update:(g,b)=>a.push(`${g}=${b}`)}};else d={tls:{values:["0","1"],update:(g,b)=>n=b==="1"},authToken:{update:(g,b)=>i=b}};for(let{key:g,value:b}of c.query?.pairs??[]){if(!Object.hasOwn(d,g))throw new Me(`Unsupported URL query parameter ${JSON.stringify(g)}`,"URL_PARAM_NOT_SUPPORTED");let v=d[g];if(v.values!==void 0&&!v.values.includes(b))throw new Me(`Unknown value for the "${g}" query argument: ${JSON.stringify(b)}. Supported values are: [${v.values.map((A)=>'"'+A+'"').join(", ")}]`,"URL_INVALID");if(v.update!==void 0)v?.update(g,b)}let p=a.length===0?"":`?${a.join("&")}`,m=c.path+p,y;if(l==="libsql")if(n===!1){if(c.authority?.port===void 0)throw new Me('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");y=t?"http":"ws"}else y=t?"https":"wss";else y=l;if(y==="http"||y==="ws")n??=!1;else n??=!0;if(y!=="http"&&y!=="ws"&&y!=="https"&&y!=="wss"&&y!=="file")throw new Me(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(c.scheme+":")}. For more information, please read ${xi}`,"URL_SCHEME_NOT_SUPPORTED");if(o!=="number"&&o!=="bigint"&&o!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(o)}`);if(c.fragment!==void 0)throw new Me(`URL fragments are not supported: ${JSON.stringify("#"+c.fragment)}`,"URL_INVALID");if(u)return{scheme:"file",tls:!1,path:m,intMode:o,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:y,tls:n,authority:c.authority,path:m,authToken:i,intMode:o,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 gH=":memory:";var sp=x(()=>{Jn();Rb();tu()});var xH=te(function(An){var Jwe=An&&An.__createBinding||(Object.create?function(e,t,r,i){if(i===void 0)i=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,i,n)}:function(e,t,r,i){if(i===void 0)i=r;e[i]=t[r]}),Kwe=An&&An.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),bH=An&&An.__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))Jwe(t,e,r)}return Kwe(t,e),t};Object.defineProperty(An,"__esModule",{value:!0});An.load=An.currentTarget=void 0;var Vwe=bH(Ct("path")),Wwe=bH(Ct("fs"));function Gwe(){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 Qwe()?`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}`)}An.currentTarget=Gwe;function Qwe(){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 Ywe(e){let t=Vwe.join(e,"index.node");return Wwe.existsSync(t)?Ct(t):null}An.load=Ywe});var vH=te(function(q5e,wH){var SH=()=>process.platform==="linux",oT=null,Xwe=()=>{if(!oT)oT=SH()&&process.report?process.report.getReport():{};return oT};wH.exports={isLinux:SH,getReport:Xwe}});var EH=te(function(U5e,kH){var _H=Ct("fs"),e0e=(e)=>_H.readFileSync(e,"utf-8"),t0e=(e)=>new Promise((t,r)=>{_H.readFile(e,"utf-8",(i,n)=>{if(i)r(i);else t(n)})});kH.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:e0e,readFile:t0e}});var FH=te(function(F5e,UH){var AH=Ct("child_process"),{isLinux:ru,getReport:$H}=vH(),{LDD_PATH:Db,readFile:CH,readFileSync:TH}=EH(),Si,wi,ys="",OH=()=>{if(!ys)return new Promise((e)=>{AH.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{ys=t?" ":r,e(ys)})});return ys},RH=()=>{if(!ys)try{ys=AH.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){ys=" "}return ys},ro="glibc",PH=/GLIBC\s(\d+\.\d+)/,Ba="musl",r0e=ro.toUpperCase(),n0e=Ba.toLowerCase(),i0e=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),zH=()=>{let e=$H();if(e.header&&e.header.glibcVersionRuntime)return ro;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(i0e))return Ba}return null},NH=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(ro))return ro;if(r&&r.includes(Ba))return Ba;return null},DH=(e)=>{if(e.includes(n0e))return Ba;if(e.includes(r0e))return ro;return null},o0e=async()=>{if(Si!==void 0)return Si;Si=null;try{let e=await CH(Db);Si=DH(e)}catch(e){}return Si},s0e=()=>{if(Si!==void 0)return Si;Si=null;try{let e=TH(Db);Si=DH(e)}catch(e){}return Si},LH=async()=>{let e=null;if(ru()){if(e=await o0e(),!e)e=zH();if(!e){let t=await OH();e=NH(t)}}return e},BH=()=>{let e=null;if(ru()){if(e=s0e(),!e)e=zH();if(!e){let t=RH();e=NH(t)}}return e},a0e=async()=>ru()&&await LH()!==ro,c0e=()=>ru()&&BH()!==ro,l0e=async()=>{if(wi!==void 0)return wi;wi=null;try{let t=(await CH(Db)).match(PH);if(t)wi=t[1]}catch(e){}return wi},u0e=()=>{if(wi!==void 0)return wi;wi=null;try{let t=TH(Db).match(PH);if(t)wi=t[1]}catch(e){}return wi},jH=()=>{let e=$H();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},IH=(e)=>e.trim().split(/\s+/)[1],qH=(e)=>{let[t,r,i]=e.split(/[\r\n]+/);if(t&&t.includes(ro))return IH(t);if(r&&i&&r.includes(Ba))return IH(i);return null},d0e=async()=>{let e=null;if(ru()){if(e=await l0e(),!e)e=jH();if(!e){let t=await OH();e=qH(t)}}return e},f0e=()=>{let e=null;if(ru()){if(e=u0e(),!e)e=jH();if(!e){let t=RH();e=qH(t)}}return e};UH.exports={GLIBC:ro,MUSL:Ba,family:LH,familySync:BH,isNonGlibcLinux:a0e,isNonGlibcLinuxSync:c0e,version:d0e,versionSync:f0e}});var ZH=te(function(M5e,MH){var p0e={ALLOW:0,DENY:1};MH.exports=p0e});var JH=te(function(Z5e,HH){var sT={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function ja(e,t,r){if(new.target!==ja)return new ja(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),sT.value=""+e,Object.defineProperty(this,"message",sT),Error.captureStackTrace(this,ja),this.code=t,this.rawCode=r}Object.setPrototypeOf(ja,Error);Object.setPrototypeOf(ja.prototype,Error.prototype);Object.defineProperty(ja.prototype,"name",sT);HH.exports=ja});var eJ=te(function(H5e,Lb){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:m0e,currentTarget:h0e}=xH(),{familySync:KH,GLIBC:g0e,MUSL:y0e}=FH();function b0e(){if(process.env.LIBSQL_JS_DEV)return m0e(__dirname);let e=h0e();if(KH()==g0e)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"&&KH()==y0e)e="linux-arm-musleabihf";return Ct(`@libsql/${e}`)}var{databaseOpen:x0e,databaseOpenWithSync:S0e,databaseInTransaction:w0e,databaseInterrupt:v0e,databaseClose:_0e,databaseSyncSync:k0e,databaseSyncUntilSync:E0e,databaseExecSync:I0e,databasePrepareSync:A0e,databaseDefaultSafeIntegers:$0e,databaseAuthorizer:C0e,databaseLoadExtension:T0e,databaseMaxWriteReplicationIndex:O0e,statementRaw:R0e,statementIsReader:P0e,statementGet:VH,statementRun:WH,statementInterrupt:z0e,statementRowsSync:GH,statementColumns:N0e,statementSafeIntegers:D0e,rowsNext:L0e}=b0e(),B0e=ZH(),QH=JH();function nu(e){if(e.libsqlError)return new QH(e.message,e.code,e.rawCode);return e}class YH{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var i="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),i=t.syncAuth;else if(t.authToken)i=t.authToken;let o=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,c=t?.offline??!1,l=t?.remoteEncryptionKey??"";this.db=S0e(e,t.syncUrl,i,r,o,s,a,c,l)}else{let o=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,c=t?.remoteEncryptionKey??"";this.db=x0e(e,o,r,s,a,c)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let n=this.db;Object.defineProperties(this,{inTransaction:{get(){return w0e(n)}}})}sync(){return k0e.call(this.db)}syncUntil(e){return E0e.call(this.db,e)}prepare(e){try{let t=A0e.call(this.db,e);return new XH(t)}catch(t){throw nu(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...o)=>{t.exec("BEGIN "+n);try{let s=e(...o);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},i={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(i.default.value,i),Object.defineProperties(i.deferred.value,i),Object.defineProperties(i.immediate.value,i),Object.defineProperties(i.exclusive.value,i),i.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,i=this.prepare(`PRAGMA ${e}`,this,!0);return r?i.pluck().get():i.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){C0e.call(this.db,e)}loadExtension(...e){T0e.call(this.db,...e)}maxWriteReplicationIndex(){return O0e.call(this.db)}exec(e){try{I0e.call(this.db,e)}catch(t){throw nu(t)}}interrupt(){v0e.call(this.db)}close(){_0e.call(this.db),this.open=!1}defaultSafeIntegers(e){return $0e.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class XH{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return R0e.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return P0e.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return WH.call(this.stmt,e[0]);else return WH.call(this.stmt,e.flat())}catch(t){throw nu(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return VH.call(this.stmt,e[0]);else return VH.call(this.stmt,e.flat())}catch(t){throw nu(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=GH.call(this.stmt,e[0]);else t=GH.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)L0e.call(t,this.nextRows),this.nextRowIndex=0;let i=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!i)return{done:!0};return this.nextRowIndex++,{value:i,done:!1}}catch(i){throw nu(i)}},[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 nu(t)}}interrupt(){z0e.call(this.stmt)}columns(){return N0e.call(this.stmt)}safeIntegers(e){return D0e.call(this.stmt,e??!0),this}}Lb.exports=YH;Lb.exports.Authorization=B0e;Lb.exports.SqliteError=QH});import{Buffer as rJ}from"buffer";function nJ(e){if(e.scheme!=="file")throw new Me(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${xi}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Me(`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 ${xi}`,"URL_INVALID");if(t.port!==void 0)throw new Me("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Me("File URL cannot have username and password","URL_INVALID")}let r=yH(e);if(r&&e.syncUrl)throw new Me(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let i=e.path;if(r)i=`${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},o=new ap.default(i,n);return Kt(o,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new iJ(i,n,o,e.intMode)}class iJ{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,i){this.#e=e,this.#t=t,this.#r=r,this.#n=i,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.#i(),Kt(this.#o(),r,this.#n)}async batch(e,t="deferred"){this.#i();let r=this.#o();try{Kt(r,gs(t),this.#n);let i=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new fr("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let o=e[n],s=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;i.push(Kt(r,s,this.#n))}catch(o){if(o instanceof fr)throw o;if(o instanceof Me)throw new fr(o.message,n,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return Kt(r,"COMMIT",this.#n),i}finally{if(r.inTransaction)Kt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#i();let t=this.#o();try{Kt(t,"PRAGMA foreign_keys=off",this.#n),Kt(t,gs("deferred"),this.#n);let r=[];for(let i=0;i<e.length;i++)try{if(!t.inTransaction)throw new fr("The transaction has been rolled back",i,"TRANSACTION_CLOSED");r.push(Kt(t,e[i],this.#n))}catch(n){if(n instanceof fr)throw n;if(n instanceof Me)throw new fr(n.message,i,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return Kt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)Kt(t,"ROLLBACK",this.#n);Kt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#o();return Kt(t,gs(e),this.#n),this.#r=null,new oJ(t,this.#n)}async executeMultiple(e){this.#i();let t=this.#o();try{return sJ(t,e)}finally{if(t.inTransaction)Kt(t,"ROLLBACK",this.#n)}}async sync(){this.#i();let e=await this.#o().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 ap.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#i(){if(this.closed)throw new Me("The client is closed","CLIENT_CLOSED")}#o(){if(this.#r===null)this.#r=new ap.default(this.#e,this.#t);return this.#r}}class oJ{#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(),Kt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let i=e[r],n=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;t.push(Kt(this.#e,n,this.#t))}catch(i){if(i instanceof fr)throw i;if(i instanceof Me)throw new fr(i.message,r,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return t}async executeMultiple(e){return this.#r(),sJ(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),Kt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),Kt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)Kt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Me("The transaction is closed","TRANSACTION_CLOSED")}}function Kt(e,t,r){let i,n;if(typeof t==="string")i=t,n=[];else if(i=t.sql,Array.isArray(t.args))n=t.args.map((o)=>tJ(o,r));else{n={};for(let o in t.args){let s=o[0]==="@"||o[0]==="$"||o[0]===":"?o.substring(1):o;n[s]=tJ(t.args[o],r)}}try{let o=e.prepare(i);o.safeIntegers(!0);let s=!0;try{o.raw(!0)}catch{s=!1}if(s){let a=Array.from(o.columns().map((p)=>p.name)),c=Array.from(o.columns().map((p)=>p.type??"")),l=o.all(n).map((p)=>j0e(p,a,r)),u=0,d=void 0;return new eu(a,c,l,0,void 0)}else{let a=o.run(n),c=a.changes,l=BigInt(a.lastInsertRowid);return new eu([],[],[],c,l)}}catch(o){throw aJ(o)}}function j0e(e,t,r){let i={};Object.defineProperty(i,"length",{value:e.length});for(let n=0;n<e.length;++n){let o=q0e(e[n],r);Object.defineProperty(i,n,{value:o});let s=t[n];if(!Object.hasOwn(i,s))Object.defineProperty(i,s,{value:o,enumerable:!0,configurable:!0,writable:!0})}return i}function q0e(e,t){if(typeof e==="bigint")if(t==="number"){if(e<U0e||e>F0e)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 rJ)return e.buffer;return e}function tJ(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<M0e||e>Z0e)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 rJ.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 sJ(e,t){try{e.exec(t)}catch(r){throw aJ(r)}}function aJ(e){if(e instanceof ap.default.SqliteError){let t=e.code,r=H0e(e.rawCode);return new Me(e.message,r,t,e.rawCode,e)}return e}function H0e(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return J0e[t]??`SQLITE_UNKNOWN_${t.toString()}`}var ap,U0e,F0e=9007199254740991n,M0e,Z0e=9223372036854775807n,J0e;var cJ=x(()=>{Jn();sp();tu();ap=ic(eJ(),1);Jn();U0e=-9007199254740991n;M0e=-9223372036854775808n;J0e={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 bs;var aT=x(()=>{if(typeof WebSocket<"u")bs=WebSocket;else if(typeof global<"u")bs=global.WebSocket;else if(typeof window<"u")bs=window.WebSocket;else if(typeof self<"u")bs=self.WebSocket});class iu{constructor(){this.intMode="number"}intMode}var at,qe,cp,zt,lp,ou,qa,Kn,kr,vi;var Nt=x(()=>{at=class at extends Error{constructor(e){super(e);this.name="ClientError"}};qe=class qe extends at{constructor(e){super(e);this.name="ProtoError"}};cp=class cp extends at{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};zt=class zt extends at{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};lp=class lp extends at{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};ou=class ou extends at{constructor(e){super(e);this.name="WebSocketError"}};qa=class qa extends at{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};Kn=class Kn extends at{constructor(e){super(e);this.name="ProtocolVersionError"}};kr=class kr extends at{constructor(e){super(e);this.name="InternalError"}};vi=class vi extends at{constructor(e){super(e);this.name="MisuseError"}}});function Gr(e){if(typeof e==="string")return e;throw su(e,"string")}function pn(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw su(e,"string or null")}function no(e){if(typeof e==="number")return e;throw su(e,"number")}function xs(e){if(typeof e==="boolean")return e;throw su(e,"boolean")}function up(e){if(Array.isArray(e))return e;throw su(e,"array")}function Ut(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw su(e,"object")}function Vn(e,t){return up(e).map((r)=>t(Ut(r)))}function su(e,t){if(e===void 0)return new qe(`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 qe(`Expected ${t}, received ${r}`)}function Ua(e,t){return t(Ut(e))}var au=x(()=>{Nt()});class lJ{#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 i=0;i<t.length;++i){if(i!==0)this.#e.push(",");this.begin(),r(this,t[i]),this.end()}this.#e.push("]")}}function dp(e,t){let r=[],i=new lJ(r);return i.begin(),t(i,e),i.end(),r.join("")}var Fa=0,fp=1,pp=2,uJ=5;class dJ{#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 fJ{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new qe(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(pp);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return Ss(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(fp),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===Fa)this.#e.skipVarint();else if(this.#t===fp)this.#e.skip(8);else if(this.#t===pp){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===uJ)this.#e.skip(4);else throw new qe(`Unexpected wire type ${this.#t}`);this.#t=-1}}function Ss(e,t){let r=new dJ(e),i=new fJ(r),n=t.default();while(!r.eof()){let o=r.varint(),s=o>>3,a=o&7;i.setup(a);let c=t[s];if(c!==void 0){let l=c(i,n);if(l!==void 0)n=l}i.maybeSkip()}return n}var cT=x(()=>{Nt()});class lT{#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}#i(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),i=new Uint8Array(r),n=new DataView(r);i.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=i,this.#r=n}#o(e){this.#i(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.#i(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.#o(e<<3|t)}bytes(e,t){this.#s(e,pp),this.#o(t.byteLength),this.#i(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 i=new lT;r(i,t),this.bytes(e,i.data())}int32(e,t){this.#s(e,Fa),this.#o(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,fp),this.#i(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function mp(e,t){let r=new lT;return t(r,e),r.data()}var pJ=()=>{};var uT=x(()=>{au();cT();pJ()});class ws{#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 kr("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var dT=x(()=>{Nt()});function nt(e,t){throw new kr(t)}var $n=x(()=>{Nt()});function cu(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<V0e||e>W0e)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 fT(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 vi("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new qe("Received unrecognized type of Value");else throw nt(e,"Impossible type of Value")}var V0e,W0e=9223372036854775807n;var pT=x(()=>{Nt();$n();V0e=-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 jb(e,t){let r=Ma(e),i=e.rows.map((n)=>mJ(r.columnNames,n,t));return{...r,rows:i}}function qb(e,t){let r=Ma(e),i;if(e.rows.length>0)i=mJ(r.columnNames,e.rows[0],t);return{...r,row:i}}function Ub(e,t){let r=Ma(e),i;if(e.rows.length>0&&r.columnNames.length>0)i=fT(e.rows[0][0],t);return{...r,value:i}}function mJ(e,t,r){let i={};Object.defineProperty(i,"length",{value:t.length});for(let n=0;n<t.length;++n){let o=fT(t[n],r);Object.defineProperty(i,n,{value:o});let s=e[n];if(s!==void 0&&!Object.hasOwn(i,s))Object.defineProperty(i,s,{value:o,enumerable:!0,configurable:!0,writable:!0})}return i}function io(e){return new cp(e.message,e)}var hp=x(()=>{Nt();pT()});class Za{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new vi("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new zt("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new at("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 gp(e,t){if(t instanceof Za)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var lu=x(()=>{Nt()});class vs{#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 yp{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(cu(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]=cu(t),this}bindName(e,t){return this._namedArgs.set(e,cu(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function Fb(e,t,r){let i,n=[],o=[];if(t instanceof yp){i=t.sql,n=t._args;for(let[c,l]of t._namedArgs.entries())o.push({name:c,value:l})}else if(Array.isArray(t))if(i=t[0],Array.isArray(t[1]))n=t[1].map((c)=>cu(c));else o=Object.entries(t[1]).map(([c,l])=>({name:c,value:cu(l)}));else i=t;let{sql:s,sqlId:a}=gp(e,i);return{sql:s,sqlId:a,args:n,namedArgs:o,wantRows:r}}var Mb=x(()=>{lu();pT()});class Zb{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new mT(this)}execute(){if(this.#t)throw new vi("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return Q0e(this._stream,this._steps,e);else return G0e(this._stream,this._steps,e)}}function G0e(e,t,r){return e._batch(r).then((i)=>{for(let n=0;n<t.length;++n){let o=i.stepResults.get(n),s=i.stepErrors.get(n);t[n].callback(o,s)}})}async function Q0e(e,t,r){let i=await e._openCursor(r);try{let n=0,o=void 0,s=[];for(;;){let a=await i.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new qe("Server produced StepBeginEntry for unexpected step");else if(o!==void 0)throw new qe("Server produced StepBeginEntry before terminating previous step");for(let c=n;c<a.step;++c)t[c].callback(void 0,void 0);n=a.step+1,o=a,s=[]}else if(a.type==="step_end"){if(o===void 0)throw new qe("Server produced StepEndEntry but no step is active");let c={cols:o.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[o.step].callback(c,void 0),o=void 0,s=[]}else if(a.type==="step_error"){if(o===void 0){if(a.step>=t.length)throw new qe("Server produced StepErrorEntry for unexpected step");for(let c=n;c<a.step;++c)t[c].callback(void 0,void 0)}else{if(a.step!==o.step)throw new qe("Server produced StepErrorEntry for unexpected step");o=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(o===void 0)throw new qe("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw io(a.error);else if(a.type==="none")throw new qe("Server produced unrecognized CursorEntry");else throw nt(a,"Impossible CursorEntry")}if(o!==void 0)throw new qe("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{i.close()}}class mT{_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,jb)}queryRow(e){return this.#t(e,!0,qb)}queryValue(e){return this.#t(e,!0,Ub)}run(e){return this.#t(e,!1,Ma)}#t(e,t,r){if(this._index!==void 0)throw new vi("This BatchStep has already been added to the batch");let i=Fb(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 o={stmt:i,condition:n};return new Promise((s,a)=>{let c=(l,u)=>{if(l!==void 0&&u!==void 0)a(new qe("Server returned both result and error"));else if(u!==void 0)a(io(u));else if(l!==void 0)s(r(l,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:o,callback:c})})}}class wt{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new wt(e._batch,{type:"ok",step:hJ(e)})}static error(e){return new wt(e._batch,{type:"error",step:hJ(e)})}static not(e){return new wt(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)gJ(e,r);return new wt(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)gJ(e,r);return new wt(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new wt(e,{type:"is_autocommit"})}}function hJ(e){if(e._index===void 0)throw new vi("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function gJ(e,t){if(t._batch!==e)throw new vi("Cannot mix BatchCond objects for different Batch objects")}var hT=x(()=>{Nt();hp();Mb();$n()});function yJ(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class uu{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,jb)}queryRow(e){return this.#e(e,!0,qb)}queryValue(e){return this.#e(e,!0,Ub)}run(e){return this.#e(e,!1,Ma)}#e(e,t,r){let i=Fb(this._sqlOwner(),e,t);return this._execute(i).then((n)=>r(n,this.intMode))}batch(e=!1){return new Zb(this,e)}describe(e){let t=gp(this._sqlOwner(),e);return this._describe(t).then(yJ)}sequence(e){let t=gp(this._sqlOwner(),e);return this._sequence(t)}intMode}var Hb=x(()=>{hT();hp();lu();Mb()});class bp{}var Y0e=1000,X0e=10,gT;var bJ=x(()=>{Nt();gT=class gT extends bp{#e;#t;#r;#n;#i;#o;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new vs,this.#i=new vs,this.#o=void 0,this.#a=!1}async next(){for(;;){if(this.#o!==void 0)throw new zt("Cursor is closed",this.#o);while(!this.#a&&this.#i.length<X0e)this.#i.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#i.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:Y0e}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#o!==void 0)return;this.#o=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new at("Cursor was manually closed"))}get closed(){return this.#o!==void 0}}});var xp;var yT=x(()=>{Nt();Hb();bJ();xp=class xp extends uu{#e;#t;#r;#n;#i;#o;static open(e){let t=e._streamIdAlloc.alloc(),r=new xp(e,t),i=()=>{return},n=(s)=>r.#l(s),o={type:"open_stream",streamId:t};return e._sendRequest(o,{responseCallback:i,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new vs,this.#n=void 0,this.#i=!1,this.#o=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 kr("Cursor not associated with the stream attempted to execute a request");return new Promise((r,i)=>{if(this.#o!==void 0)i(new zt("Stream is closed",this.#o));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})})}_cursorClosed(e){if(e!==this.#n)throw new kr("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#o!==void 0)e.errorCallback(new zt("Stream is closed",this.#o));else if(this.#i)e.errorCallback(new zt("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.#i){this.#l(new at("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:i}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let i=this.#e._cursorIdAlloc.alloc(),n=new gT(this.#e,this,i),o={type:"open_cursor",streamId:this.#t,cursorId:i,batch:t},s=()=>{return},a=(c)=>n._setClosed(c);this.#e._sendRequest(o,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#o!==void 0)return;if(this.#o=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),i=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})}close(){this.#l(new at("Stream was manually closed"))}closeGracefully(){this.#i=!0,this.#c()}get closed(){return this.#o!==void 0||this.#i}}});function Sp(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,xJ),e.arrayObjects("named_args",t.namedArgs,eve),e.boolean("want_rows",t.wantRows)}function eve(e,t){e.string("name",t.name),e.object("value",t.value,xJ)}function du(e,t){e.arrayObjects("steps",t.steps,tve)}function tve(e,t){if(t.condition!==void 0)e.object("condition",t.condition,bT);e.object("stmt",t.stmt,Sp)}function bT(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,bT);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,bT);else if(t.type==="is_autocommit");else throw nt(t,"Impossible type of BatchCond")}function xJ(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",Xl.fromUint8Array(t));else if(t===void 0);else throw nt(t,"Impossible type of Value")}var xT=x(()=>{Nb();$n()});function SJ(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,rve);else throw nt(t,"Impossible type of ClientMsg")}function rve(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,Sp);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,du);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,du);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 nt(t,"Impossible type of Request")}var wJ=x(()=>{xT();$n()});function wp(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,_J);for(let r of t.namedArgs)e.message(4,r,nve);e.bool(5,t.wantRows)}function nve(e,t){e.string(1,t.name),e.message(2,t.value,_J)}function fu(e,t){for(let r of t.steps)e.message(1,r,ive)}function ive(e,t){if(t.condition!==void 0)e.message(1,t.condition,ST);e.message(2,t.stmt,wp)}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,vJ);else if(t.type==="or")e.message(5,t.conds,vJ);else if(t.type==="is_autocommit")e.message(6,void 0,kJ);else throw nt(t,"Impossible type of BatchCond")}function vJ(e,t){for(let r of t)e.message(1,r,ST)}function _J(e,t){if(t===null)e.message(1,void 0,kJ);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 nt(t,"Impossible type of Value")}function kJ(e,t){}var wT=x(()=>{$n()});function EJ(e,t){if(t.type==="hello")e.message(1,t,ove);else if(t.type==="request")e.message(2,t,sve);else throw nt(t,"Impossible type of ClientMsg")}function ove(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function sve(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,ave);else if(r.type==="close_stream")e.message(3,r,cve);else if(r.type==="execute")e.message(4,r,lve);else if(r.type==="batch")e.message(5,r,uve);else if(r.type==="open_cursor")e.message(6,r,dve);else if(r.type==="close_cursor")e.message(7,r,fve);else if(r.type==="fetch_cursor")e.message(8,r,pve);else if(r.type==="sequence")e.message(9,r,mve);else if(r.type==="describe")e.message(10,r,hve);else if(r.type==="store_sql")e.message(11,r,gve);else if(r.type==="close_sql")e.message(12,r,yve);else if(r.type==="get_autocommit")e.message(13,r,bve);else throw nt(r,"Impossible type of Request")}function ave(e,t){e.int32(1,t.streamId)}function cve(e,t){e.int32(1,t.streamId)}function lve(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,wp)}function uve(e,t){e.int32(1,t.streamId),e.message(2,t.batch,fu)}function dve(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,fu)}function fve(e,t){e.int32(1,t.cursorId)}function pve(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function mve(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 hve(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 gve(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function yve(e,t){e.int32(1,t.sqlId)}function bve(e,t){e.int32(1,t.streamId)}var IJ=x(()=>{wT();$n()});function _s(e){let t=Gr(e.message),r=pn(e.code);return{message:t,code:r}}function vp(e){let t=Vn(e.cols,AJ),r=up(e.rows).map((s)=>Vn(s,$J)),i=no(e.affected_row_count),n=pn(e.last_insert_rowid),o=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:i,lastInsertRowid:o}}function AJ(e){let t=pn(e.name),r=pn(e.decltype);return{name:t,decltype:r}}function Jb(e){let t=new Map;up(e.step_results).forEach((i,n)=>{if(i!==null)t.set(n,vp(Ut(i)))});let r=new Map;return up(e.step_errors).forEach((i,n)=>{if(i!==null)r.set(n,_s(Ut(i)))}),{stepResults:t,stepErrors:r}}function Kb(e){let t=Gr(e.type);if(t==="step_begin"){let r=no(e.step),i=Vn(e.cols,AJ);return{type:"step_begin",step:r,cols:i}}else if(t==="step_end"){let r=no(e.affected_row_count),i=pn(e.last_insert_rowid),n=i!==void 0?BigInt(i):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=no(e.step),i=_s(Ut(e.error));return{type:"step_error",step:r,error:i}}else if(t==="row")return{type:"row",row:Vn(e.row,$J)};else if(t==="error")return{type:"error",error:_s(Ut(e.error))};else throw new qe("Unexpected type of CursorEntry")}function Vb(e){let t=Vn(e.params,xve),r=Vn(e.cols,Sve),i=xs(e.is_explain),n=xs(e.is_readonly);return{params:t,cols:r,isExplain:i,isReadonly:n}}function xve(e){return{name:pn(e.name)}}function Sve(e){let t=Gr(e.name),r=pn(e.decltype);return{name:t,decltype:r}}function $J(e){let t=Gr(e.type);if(t==="null")return null;else if(t==="integer"){let r=Gr(e.value);return BigInt(r)}else if(t==="float")return no(e.value);else if(t==="text")return Gr(e.value);else if(t==="blob")return Xl.toUint8Array(Gr(e.base64));else throw new qe("Unexpected type of Value")}var Wb=x(()=>{Nb();Nt();au()});function CJ(e){let t=Gr(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:_s(Ut(e.error))};else if(t==="response_ok"){let r=no(e.request_id),i=wve(Ut(e.response));return{type:"response_ok",requestId:r,response:i}}else if(t==="response_error"){let r=no(e.request_id),i=_s(Ut(e.error));return{type:"response_error",requestId:r,error:i}}else throw new qe("Unexpected type of ServerMsg")}function wve(e){let t=Gr(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:vp(Ut(e.result))};else if(t==="batch")return{type:"batch",result:Jb(Ut(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=Vn(e.entries,Kb),i=xs(e.done);return{type:"fetch_cursor",entries:r,done:i}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:Vb(Ut(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:xs(e.is_autocommit)};else throw new qe("Unexpected type of Response")}var TJ=x(()=>{Nt();au();Wb()});var Cn,ks,OJ,RJ,pu,vve,_ve,Gb,kve,Eve,Ive,mu,Ave,$ve,Cve;var Qb=x(()=>{Cn={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},ks={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(OJ))},2(e,t){t.rows.push(e.message(RJ))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},OJ={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},RJ={default(){return[]},1(e,t){t.push(e.message(Cve))}},pu={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,i]=e.message(vve);t.stepResults.set(r,i)},2(e,t){let[r,i]=e.message(_ve);t.stepErrors.set(r,i)}},vve={default(){return[0,ks.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(ks)}},_ve={default(){return[0,Cn.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(Cn)}},Gb={default(){return{type:"none"}},1(e){return e.message(kve)},2(e){return e.message(Eve)},3(e){return e.message(Ive)},4(e){return{type:"row",row:e.message(RJ)}},5(e){return{type:"error",error:e.message(Cn)}}},kve={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(OJ))}},Eve={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},Ive={default(){return{type:"step_error",step:0,error:Cn.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(Cn)}},mu={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(Ave))},2(e,t){t.cols.push(e.message($ve))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},Ave={default(){return{name:void 0}},1(e,t){t.name=e.string()}},$ve={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},Cve={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 PJ,Tve,Ove,Rve,Pve,zve,Nve,Dve,Lve;var zJ=x(()=>{Qb();PJ={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(Tve)},3(e){return e.message(Rve)},4(e){return e.message(Ove)}},Tve={default(){return{type:"hello_error",error:Cn.default()}},1(e,t){t.error=e.message(Cn)}},Ove={default(){return{type:"response_error",requestId:0,error:Cn.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(Cn)}},Rve={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(Pve)},5(e,t){t.response=e.message(zve)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(Nve)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(Dve)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(Lve)}},Pve={default(){return{type:"execute",result:ks.default()}},1(e,t){t.result=e.message(ks)}},zve={default(){return{type:"batch",result:pu.default()}},1(e,t){t.result=e.message(pu)}},Nve={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(Gb))},2(e,t){t.done=e.bool()}},Dve={default(){return{type:"describe",result:mu.default()}},1(e,t){t.result=e.message(mu)}},Lve={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var NJ,vT,Yb;var Xb=x(()=>{uT();Nt();dT();hp();lu();$n();yT();wJ();IJ();TJ();zJ();NJ=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),vT=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);Yb=class Yb extends iu{#e;#t;#r;#n;#i;#o;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#i=!1,this.#o=void 0,this.#a=!1,this.#s=new Map,this.#c=new ws,this._streamIdAlloc=new ws,this._cursorIdAlloc=new ws,this.#l=new ws,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#f()),this.#e.addEventListener("close",(r)=>this.#g(r)),this.#e.addEventListener("error",(r)=>this.#p(r)),this.#e.addEventListener("message",(r)=>this.#y(r)),this.#d({type:"hello",jwt:t})}#d(e){if(this.#n!==void 0)throw new kr("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})}}#f(){let e=this.#e.protocol;if(e===void 0){this.#u(new at("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.#o={version:1,encoding:"json"};else if(this.#o=vT.get(e),this.#o===void 0){this.#u(new qe(`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.#o.encoding;if(t==="json"){let r=dp(e,SJ);this.#e.send(r)}else if(t==="protobuf"){let r=mp(e,EJ);this.#e.send(r)}else throw nt(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.#o.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#o.version)})}_ensureVersion(e,t){if(this.#o===void 0||!this.#a)throw new Kn(`${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.#o.version<e)throw new Kn(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#o.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new zt("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})}#p(e){let r=e.message??"WebSocket was closed due to an error";this.#u(new ou(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new ou(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.#o.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new qe("Received non-text message from server with JSON encoding"));return}t=Ua(JSON.parse(e.data),CJ)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new qe("Received non-binary message from server with Protobuf encoding"));return}t=Ss(new Uint8Array(e.data),PJ)}else throw nt(r,"Impossible encoding");this.#h(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#h(e){if(e.type==="none")throw new qe("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#i)throw new qe("Received a duplicated hello response");if(this.#i=!0,e.type==="hello_error")throw io(e.error);return}else if(!this.#i)throw new qe("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 qe("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new qe("Received unexpected type of response");r.responseCallback(e.response)}catch(i){throw r.errorCallback(i),i}}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 qe("Received unexpected error response");this.#c.free(t),r.errorCallback(io(e.error))}else throw nt(e,"Impossible ServerMsg type")}openStream(){return xp.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new Za(this,t),i=()=>{return},n=(s)=>r._setClosed(s),o={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(o,{responseCallback:i,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),i={type:"close_sql",sqlId:e};this._sendRequest(i,{responseCallback:t,errorCallback:r})}close(){this.#u(new at("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var Ha;var DJ=x(()=>{if(typeof queueMicrotask<"u")Ha=queueMicrotask;else{let e=Promise.resolve();Ha=(t)=>{e.then(t)}}});class _T{#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 i=new Uint8Array(new ArrayBuffer(r));i.set(this.#e.slice(this.#t,this.#r),0),this.#e=i}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function LJ(e){let t=pn(e.baton),r=pn(e.base_url),i=Vn(e.results,Bve);return{baton:t,baseUrl:r,results:i}}function Bve(e){let t=Gr(e.type);if(t==="ok")return{type:"ok",response:jve(Ut(e.response))};else if(t==="error")return{type:"error",error:_s(Ut(e.error))};else throw new qe("Unexpected type of StreamResult")}function jve(e){let t=Gr(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:vp(Ut(e.result))};else if(t==="batch")return{type:"batch",result:Jb(Ut(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:Vb(Ut(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:xs(e.is_autocommit)};else throw new qe("Unexpected type of StreamResponse")}function BJ(e){let t=pn(e.baton),r=pn(e.base_url);return{baton:t,baseUrl:r}}var kT=x(()=>{Nt();au();Wb()});var jJ,qve,Uve,Fve,Mve,Zve,Hve,qJ;var ET=x(()=>{Qb();jJ={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(qve))}},qve={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(Uve)}},2(e){return{type:"error",error:e.message(Cn)}}},Uve={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(Fve)},3(e){return e.message(Mve)},4(e){return{type:"sequence"}},5(e){return e.message(Zve)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(Hve)}},Fve={default(){return{type:"execute",result:ks.default()}},1(e,t){t.result=e.message(ks)}},Mve={default(){return{type:"batch",result:pu.default()}},1(e,t){t.result=e.message(pu)}},Zve={default(){return{type:"describe",result:mu.default()}},1(e,t){t.result=e.message(mu)}},Hve={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},qJ={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var IT;var UJ=x(()=>{au();cT();Nt();$n();kT();ET();Wb();Qb();IT=class IT extends bp{#e;#t;#r;#n;#i;#o;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new _T(16384),this.#i=void 0,this.#o=!1}async open(e){if(e.body===null)throw new qe("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(BJ,qJ);if(t===void 0)throw new qe("Empty response to cursor request");return t}next(){return this.#a(Kb,Gb)}close(){this._setClosed(new at("Cursor was manually closed"))}_setClosed(e){if(this.#i!==void 0)return;if(this.#i=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#i!==void 0}async#a(e,t){for(;;){if(this.#o)return;else if(this.#i!==void 0)throw new zt("Cursor is closed",this.#i);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let o=new TextDecoder().decode(n),s=JSON.parse(o);return Ua(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return Ss(n,t)}else throw nt(this.#t,"Impossible encoding");if(this.#r===void 0)throw new kr("Attempted to read from HTTP cursor before it was opened");let{value:r,done:i}=await this.#r.next();if(i&&this.#n.length===0)this.#o=!0;else if(i)throw new qe("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 i=e.slice(0,r);return this.#n.shift(r+1),i}#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 i=e.slice(r,r+t);return this.#n.shift(r+t),i}}});function FJ(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,Jve)}function Jve(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,Sp);else if(t.type==="batch")e.object("batch",t.batch,du);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 nt(t,"Impossible type of StreamRequest")}function MJ(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,du)}var AT=x(()=>{xT();$n()});function ZJ(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,Kve)}function Kve(e,t){if(t.type==="close")e.message(1,t,Vve);else if(t.type==="execute")e.message(2,t,Wve);else if(t.type==="batch")e.message(3,t,Gve);else if(t.type==="sequence")e.message(4,t,Qve);else if(t.type==="describe")e.message(5,t,Yve);else if(t.type==="store_sql")e.message(6,t,Xve);else if(t.type==="close_sql")e.message(7,t,e_e);else if(t.type==="get_autocommit")e.message(8,t,t_e);else throw nt(t,"Impossible type of StreamRequest")}function Vve(e,t){}function Wve(e,t){e.message(1,t.stmt,wp)}function Gve(e,t){e.message(1,t.batch,fu)}function Qve(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function Yve(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function Xve(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function e_e(e,t){e.int32(1,t.sqlId)}function t_e(e,t){}function HJ(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,fu)}var $T=x(()=>{wT();$n()});function r_e(e,t){if(t.results.length!==e.length)throw new qe("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let i=t.results[r],n=e[r];if(i.type==="ok"){if(i.response.type!==n.request.type)throw new qe("Received unexpected type of response");n.responseCallback(i.response)}else if(i.type==="error")n.errorCallback(io(i.error));else if(i.type==="none")throw new qe("Received unrecognized type of StreamResult");else throw nt(i,"Received impossible type of StreamResult")}}async function n_e(e,t){if(t==="json"){let r=await e.json();return Ua(r,LJ)}if(t==="protobuf"){let r=await e.arrayBuffer();return Ss(new Uint8Array(r),jJ)}throw await e.body?.cancel(),nt(t,"Impossible encoding")}async function i_e(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let i=await e.json();if("message"in i)return io(i);return new qa(r,e.status)}if(t==="text/plain"){let i=(await e.text()).trim();if(i!=="")r+=`: ${i}`;return new qa(r,e.status)}return await e.body?.cancel(),new qa(r,e.status)}var ex;var CT=x(()=>{Nt();uT();dT();DJ();hp();lu();Hb();$n();UJ();AT();$T();AT();$T();kT();ET();ex=class ex extends uu{#e;#t;#r;#n;#i;#o;#a;#s;#c;#l;#d;#f;#m;constructor(e,t,r,i,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=i,this.#i=n,this.#o=void 0,this.#a=new vs,this.#s=!1,this.#l=!1,this.#d=!1,this.#f=void 0,this.#m=new ws}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let t=this.#m.alloc();return this.#p({type:"store_sql",sqlId:t,sql:e}).then(()=>{return},(r)=>this._setClosed(r)),new Za(this,t)}_closeSql(e){if(this.#f!==void 0)return;this.#p({type:"close_sql",sqlId:e}).then(()=>this.#m.free(e),(t)=>this._setClosed(t))}_execute(e){return this.#p({type:"execute",stmt:e}).then((t)=>t.result)}_batch(e){return this.#p({type:"batch",batch:e}).then((t)=>t.result)}_describe(e){return this.#p({type:"describe",sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#p({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#p({type:"get_autocommit"}).then((e)=>e.isAutocommit)}#p(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 kr("Cursor was closed, but it was not associated with the stream");this.#c=void 0,Ha(()=>this.#u())}close(){this._setClosed(new at("Stream was manually closed"))}closeGracefully(){this.#l=!0,Ha(()=>this.#u())}get closed(){return this.#f!==void 0||this.#l}_setClosed(e){if(this.#f!==void 0)return;if(this.#f=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.#o!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,Ha(()=>this.#u())}#g(e){if(this.#f!==void 0)throw new zt("Stream is closed",this.#f);else if(this.#l)throw new zt("Stream is closing",void 0);else this.#a.push(e),Ha(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new at("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 i=this.#a.first();if(i!==void 0&&i.type==="pipeline")r.push(i),this.#a.shift();else if(i===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.#h(e,t);else throw nt(t,"Impossible type of QueueEntry")}#y(e,t){this.#b(()=>this.#x(t,e),(r)=>n_e(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>r_e(t,r),(r)=>t.forEach((i)=>i.errorCallback(r)))}#h(e,t){let r=new IT(this,e.encoding);this.#c=r,this.#b(()=>this.#w(t,e),(i)=>r.open(i),(i)=>i.baton,(i)=>i.baseUrl,(i)=>t.cursorCallback(r),(i)=>t.errorCallback(i))}#b(e,t,r,i,n,o){let s;try{let a=e(),c=this.#n;s=c(a)}catch(a){s=Promise.reject(a)}this.#s=!0,s.then((a)=>{if(!a.ok)return i_e(a).then((c)=>{throw c});return t(a)}).then((a)=>{this.#o=r(a),this.#t=i(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),o(a)}).finally(()=>{this.#s=!1,this.#u()})}#x(e,t){return this.#S(new URL(t.pipelinePath,this.#t),{baton:this.#o,requests:e.map((r)=>r.request)},t.encoding,FJ,ZJ)}#w(e,t){if(t.cursorPath===void 0)throw new Kn(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#S(new URL(t.cursorPath,this.#t),{baton:this.#o,batch:e.batch},t.encoding,MJ,HJ)}#S(e,t,r,i,n){let o,s;if(r==="json")o=dp(t,i),s="application/json";else if(r==="protobuf")o=mp(t,n),s="application/x-protobuf";else throw nt(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.#i!==void 0)a.set("x-turso-encryption-key",this.#i);return new Request(e.toString(),{method:"POST",headers:a,body:o})}}});async function s_e(e,t){let r=e;for(let i of o_e){let n=new URL(i.versionPath,t),o=new Request(n.toString(),{method:"GET"}),s=await r(o);if(await s.arrayBuffer(),s.ok)return i}return TT}var o_e,TT,tx;var OT=x(()=>{Nt();CT();o_e=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],TT={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};tx=class tx extends iu{#e;#t;#r;#n;#i;#o;_endpointPromise;_endpoint;constructor(e,t,r,i,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=i,this.#i=void 0,this.#o=new Set,n==3)this._endpointPromise=s_e(this.#r,this.#e),this._endpointPromise.then((o)=>this._endpoint=o,(o)=>this.#a(o));else this._endpointPromise=Promise.resolve(TT),this._endpointPromise.then((o)=>this._endpoint=o,(o)=>this.#a(o))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=TT.version)return;else if(this._endpoint===void 0)throw new Kn(`${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 Kn(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#i!==void 0)throw new zt("Client is closed",this.#i);let e=new ex(this,this.#e,this.#t,this.#r,this.#n);return this.#o.add(e),e}_streamClosed(e){this.#o.delete(e)}close(){this.#a(new at("Client was manually closed"))}get closed(){return this.#i!==void 0}#a(e){if(this.#i!==void 0)return;this.#i=e;for(let t of Array.from(this.#o))t._setClosed(new zt("Client was closed",e))}}});var JJ=x(()=>{Nt()});function RT(e,t,r=2){if(typeof bs>"u")throw new lp("WebSockets are not supported in this environment");var i=void 0;if(r==3)i=Array.from(vT.keys());else i=Array.from(NJ.keys());let n=new bs(e,i);return new Yb(n,t)}function PT(e,t,r,i,n=2){return new tx(e instanceof URL?e:new URL(e),t,r,i,n)}var rx=x(()=>{aT();Xb();Nt();OT();Xb();aT();hT();JJ();lu();Mb();Hb();OT();CT();Xb();yT();Nt()});class _p{#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 Me("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(oo),i;if(this.#r===void 0){this._getSqlCache().apply(r);let o=t.batch(this.#t>=3),s=o.step(),a=s.run(gs(this.#e)),c=s;i=r.map((l)=>{let u=o.step().condition(wt.ok(c));if(this.#t>=3)u.condition(wt.not(wt.isAutocommit(o)));let d=u.query(l);return d.catch(()=>{return}),c=u,d}),this.#r=o.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(l){throw this.close(),l}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let o=t.batch(this.#t>=3),s=void 0;i=r.map((a)=>{let c=o.step();if(s!==void 0)c.condition(wt.ok(s));if(this.#t>=3)c.condition(wt.not(wt.isAutocommit(o)));let l=c.query(a);return l.catch(()=>{return}),s=c,l}),await o.execute()}let n=[];for(let o=0;o<i.length;o++)try{let s=await i[o];if(s===void 0)throw new fr("Statement in a transaction was not executed, probably because the transaction has been rolled back",o,"TRANSACTION_CLOSED");n.push(gu(s))}catch(s){if(s instanceof fr)throw s;let a=yt(s);if(a instanceof Me)throw new fr(a.message,o,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw yt(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Me("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(gs(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 yt(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 yt(r)});e.closeGracefully(),await t}catch(e){throw yt(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Me("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 yt(r)});e.closeGracefully(),await t}catch(e){throw yt(e)}finally{this.close()}}}async function hu(e,t,r,i,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let o=r.step(),s=o.run(gs(e)),a=o,c=i.map((m)=>{let y=r.step().condition(wt.ok(a));if(t>=3)y.condition(wt.not(wt.isAutocommit(r)));let g=y.query(m);return a=y,g}),l=r.step().condition(wt.ok(a));if(t>=3)l.condition(wt.not(wt.isAutocommit(r)));let u=l.run("COMMIT");if(r.step().condition(wt.not(wt.ok(l))).run("ROLLBACK").catch((m)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let p=[];await s;for(let m=0;m<c.length;m++)try{let y=await c[m];if(y===void 0)throw new fr("Statement in a batch was not executed, probably because the transaction has been rolled back",m,"TRANSACTION_CLOSED");p.push(gu(y))}catch(y){if(y instanceof fr)throw y;let g=yt(y);if(g instanceof Me)throw new fr(g.message,m,g.code,g.extendedCode,g.rawCode,g.cause instanceof Error?g.cause:void 0);throw g}return await u,p}function oo(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 i=new yp(t);if(r)if(Array.isArray(r))i.bindIndexes(r);else for(let[n,o]of Object.entries(r))i.bindName(n,o);return i}function gu(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),i=e.rows,n=e.affectedRowCount,o=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new eu(t,r,i,n,o)}function yt(e){if(e instanceof at){let t=KJ(e);return new Me(e.message,t,void 0,void 0,e)}return e}function KJ(e){if(e instanceof cp&&e.code!==void 0)return e.code;else if(e instanceof qe)return"HRANA_PROTO_ERROR";else if(e instanceof zt)return e.cause instanceof at?KJ(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof ou)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof qa)return"SERVER_ERROR";else if(e instanceof Kn)return"PROTOCOL_VERSION_ERROR";else if(e instanceof kr)return"INTERNAL_ERROR";else return"UNKNOWN"}var NT=x(()=>{rx();Jn();tu()});class yu{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new VJ,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 i=r.sql;if(i.length>=5000)continue;let n=this.#t.get(i);if(n===void 0){while(this.#t.size+1>this.capacity){let[o,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(o)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(i),this.#t.set(i,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class VJ{#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 DT=te(function(HJe,GJ){function a_e(e){var t=0,r=[];function i(){if(t--,t<e)n()}function n(){var c=r.shift();if(a.queue=r.length,c)s(c.fn).then(c.resolve).catch(c.reject)}function o(c){return new Promise(function(l,u){r.push({fn:c,resolve:l,reject:u}),a.queue=r.length})}function s(c){t++;try{return Promise.resolve(c()).then(function(l){return i(),l},function(l){throw i(),l})}catch(l){return i(),Promise.reject(l)}}var a=function(c){if(t>=e)return o(c);else return s(c)};return a}function c_e(e,t){var r=!1,i=this;return Promise.all(e.map(function(){var n=arguments;return i(function(){if(!r)return t.apply(void 0,n).catch(function(o){throw r=!0,o})})}))}function WJ(e){return e.queue=0,e.map=c_e,e}GJ.exports=function(e){if(e)return WJ(a_e(e));else return WJ(function(t){return t()})}});function XJ(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Me(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${xi}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Me("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Me('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Me('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=np(e.scheme,e.authority,e.path),r;try{r=RT(t,e.authToken)}catch(i){if(i instanceof lp){let n=e.scheme==="wss"?"https":"http",o=np(n,e.authority,e.path);throw new Me(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(o)}). For more information, please read ${xi}`,"WEBSOCKETS_NOT_SUPPORTED")}throw yt(i)}return new eK(r,t,e.authToken,e.intMode,e.concurrency)}class eK{#e;#t;#r;#n;#i;closed;protocol;#o;#a;constructor(e,t,r,i,n){this.#e=t,this.#t=r,this.#r=i,this.#n=this.#c(e),this.#i=void 0,this.closed=!1,this.protocol="ws",this.#a=YJ.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 i=await this.#s();try{let n=oo(r);i.conn.sqlCache.apply([n]);let o=i.stream.query(n);i.stream.closeGracefully();let s=await o;return gu(s)}catch(n){throw yt(n)}finally{this._closeStream(i)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((l)=>{if(Array.isArray(l))return{sql:l[0],args:l[1]||[]};return l}).map(oo),o=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(o>=3);return await hu(t,o,s,n)}catch(i){throw yt(i)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(oo),i=await t.conn.client.getVersion(),n=t.stream.batch(i>=3);return await hu("deferred",i,n,r,!0)}catch(r){throw yt(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 tK(this,t,e,r)}catch(r){throw this._closeStream(t),yt(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 yt(r)}finally{this._closeStream(t)}})}sync(){throw new Me("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Me("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>l_e&&this.#i===void 0){let i=this.#c();this.#i=i,i.client.getVersion().then((n)=>{if(this.#n!==i){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=i,this.#i=void 0},(n)=>{this.#i=void 0})}if(this.#n.client.closed)try{if(this.#i!==void 0)this.#n=this.#i;else this.#n=this.#c()}catch(i){throw yt(i)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=QJ}let i=r.client.openStream();i.intMode=this.#r;let n={conn:r,stream:i};return r.streamStates.add(n),n}catch(i){throw yt(i)}}#c(e){try{return e??=RT(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new yu(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw yt(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.#i){try{this.#i.client.close()}catch{}this.#i=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=QJ;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.#i){try{this.#i.client.close()}catch{}this.#i=void 0}this.closed=!0}}var YJ,l_e=60000,QJ=100,tK;var rK=x(()=>{rx();Jn();sp();NT();Rb();tu();YJ=ic(DT(),1);Jn();tK=class tK extends _p{#e;#t;constructor(e,t,r,i){super(r,i);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 iK(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Me(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${xi}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Me("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Me('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Me('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=np(e.scheme,e.authority,e.path);return new sK(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class sK{#e;protocol;#t;#r;#n;#i;#o;#a;#s;constructor(e,t,r,i,n,o){this.#t=e,this.#o=t,this.#r=r,this.#n=i,this.#i=n,this.#a=o,this.#e=PT(this.#t,this.#o,this.#n,o),this.#e.intMode=this.#r,this.protocol="http",this.#s=nK.default(this.#i)}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 i=oo(r),n,o=this.#e.openStream();try{n=o.query(i)}finally{o.closeGracefully()}let s=await n;return gu(s)}catch(i){throw yt(i)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let i=e.map((c)=>{if(Array.isArray(c))return{sql:c[0],args:c[1]||[]};return c}).map(oo),n=await this.#e.getVersion(),o,s=this.#e.openStream();try{new yu(s,oK).apply(i);let l=s.batch(!1);o=hu(t,n,l,i)}finally{s.closeGracefully()}return await o}catch(r){throw yt(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(oo),r=await this.#e.getVersion(),i,n=this.#e.openStream();try{let s=n.batch(!1);i=hu("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await i}catch(t){throw yt(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new aK(this.#e.openStream(),e,t)}catch(t){throw yt(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 yt(t)}})}sync(){throw new Me("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=PT(this.#t,this.#o,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var nK,oK=30,aK;var cK=x(()=>{rx();Jn();sp();NT();Rb();tu();nK=ic(DT(),1);Jn();aK=class aK extends _p{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new yu(e,oK)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function Ja(e){return u_e(op(e,!0))}function u_e(e){if(e.scheme==="wss"||e.scheme==="ws")return XJ(e);else if(e.scheme==="https"||e.scheme==="http")return iK(e);else return nJ(e)}var LT=x(()=>{sp();cJ();rK();cK();Jn()});function ce(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,K))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(K in r&&r[K]===t[K])return!0;r=Object.getPrototypeOf(r)}return!1}var K;var De=x(()=>{K=Symbol.for("drizzle:entityKind")});var it;var Wn=x(()=>{De();it=class it{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[K]="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 kp;var nx=x(()=>{De();kp=class kp{static[K]="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 Er;var bu=x(()=>{Er=Symbol.for("drizzle:Name")});var BT,lK;var uK=x(()=>{De();bu();BT=class BT{static[K]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:i,foreignColumns:n}=e();return{name:r,columns:i,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 lK(e,this)}};lK=class lK{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[K]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),i=t.map((s)=>s.name),n=r.map((s)=>s.name),o=[this.table[Er],...i,r[0].table[Er],...n];return e??`${o.join("_")}_fk`}}});function ix(e,...t){return e(...t)}var jT=()=>{};function qT(e,t){return`${e[Er]}_${t.join("_")}_unique`}var dK,d_e,fK;var pK=x(()=>{De();bu();dK=class dK{constructor(e,t){this.name=t,this.columns=e}static[K]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new fK(e,this.columns,this.nullsNotDistinctConfig,this.name)}};d_e=class d_e{static[K]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new dK(e,this.name)}};fK=class fK{constructor(e,t,r,i){this.table=e,this.columns=t,this.name=i??qT(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[K]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function mK(e,t,r){for(let i=t;i<e.length;i++){let n=e[i];if(n==="\\"){i++;continue}if(n==='"')return[e.slice(t,i).replace(/\\/g,""),i+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,i).replace(/\\/g,""),i]}return[e.slice(t).replace(/\\/g,""),e.length]}function hK(e,t=0){let r=[],i=t,n=!1;while(i<e.length){let o=e[i];if(o===","){if(n||i===t)r.push("");n=!0,i++;continue}if(n=!1,o==="\\"){i+=2;continue}if(o==='"'){let[c,l]=mK(e,i+1,!0);r.push(c),i=l;continue}if(o==="}")return[r,i+1];if(o==="{"){let[c,l]=hK(e,i+1);r.push(c),i=l;continue}let[s,a]=mK(e,i,!1);r.push(s),i=a}return[r,i]}function gK(e){let[t]=hK(e,1);return t}function UT(e){return`{${e.map((t)=>{if(Array.isArray(t))return UT(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var yK=()=>{};var Ep,xu,bK,f_e,xK,FT;var SK=x(()=>{nx();Wn();De();uK();jT();pK();yK();Ep=class Ep extends kp{foreignKeyConfigs=[];static[K]="PgColumnBuilder";array(e){return new xK(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:i})=>ix((n,o)=>{let s=new BT(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(o.onUpdate)s.onUpdate(o.onUpdate);if(o.onDelete)s.onDelete(o.onDelete);return s.build(t)},r,i))}buildExtraConfigColumn(e){return new bK(e,this.config)}};xu=class xu extends it{constructor(e,t){if(!t.uniqueName)t.uniqueName=qT(e,[t.name]);super(e,t);this.table=e}static[K]="PgColumn"};bK=class bK extends xu{static[K]="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}};f_e=class f_e{static[K]="IndexedColumn";constructor(e,t,r,i){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=i}name;keyAsName;type;indexConfig};xK=class xK extends Ep{static[K]="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 FT(e,this.config,t)}};FT=class FT extends xu{constructor(e,t,r,i){super(e,t);this.baseColumn=r,this.range=i,this.size=t.size}size;static[K]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=gK(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((i)=>i===null?null:ce(this.baseColumn,FT)?this.baseColumn.mapToDriverValue(i,!0):this.baseColumn.mapToDriverValue(i));if(t)return r;return UT(r)}}});function _K(e){return!!e&&typeof e==="function"&&wK in e&&e[wK]===!0}var p_e,vK,wK,m_e,kK;var EK=x(()=>{De();SK();p_e=class p_e extends Ep{static[K]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new vK(e,this.config)}};vK=class vK extends xu{static[K]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};wK=Symbol.for("drizzle:isPgEnum");m_e=class m_e extends Ep{static[K]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new kK(e,this.config)}};kK=class kK extends xu{static[K]="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 vt,Ip;var Gn=x(()=>{De();vt=class vt{static[K]="Subquery";constructor(e,t,r,i=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:i,usedTables:n}}};Ip=class Ip extends vt{static[K]="WithSubquery"}});var IK="0.45.2";var AK=()=>{};var MT,ZT,$K;var CK=x(()=>{jT();AK();$K={startActiveSpan(e,t){if(!MT)return t();if(!ZT)ZT=MT.trace.getTracer("drizzle-orm",IK);return ix((r,i)=>i.startActiveSpan(e,(n)=>{try{return t(n)}catch(o){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:o instanceof Error?o.message:"Unknown error"}),o}finally{n.end()}}),MT,ZT)}}});var _t;var so=x(()=>{_t=Symbol.for("drizzle:ViewBaseConfig")});function Es(e){return e[Er]}function Ka(e){return`${e[ox]??"public"}.${e[Er]}`}var ox,sx,TK,HT,JT,Ap,OK,h_e,we;var Ir=x(()=>{De();bu();ox=Symbol.for("drizzle:Schema"),sx=Symbol.for("drizzle:Columns"),TK=Symbol.for("drizzle:ExtraConfigColumns"),HT=Symbol.for("drizzle:OriginalName"),JT=Symbol.for("drizzle:BaseName"),Ap=Symbol.for("drizzle:IsAlias"),OK=Symbol.for("drizzle:ExtraConfigBuilder"),h_e=Symbol.for("drizzle:IsDrizzleTable");we=class we{static[K]="Table";static Symbol={Name:Er,Schema:ox,OriginalName:HT,Columns:sx,ExtraConfigColumns:TK,BaseName:JT,IsAlias:Ap,ExtraConfigBuilder:OK};[Er];[HT];[ox];[sx];[TK];[JT];[Ap]=!1;[h_e]=!0;[OK]=void 0;constructor(e,t,r){this[Er]=this[HT]=e,this[ox]=t,this[JT]=r}}});function KT(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function y_e(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 RK(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function q(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Vt(e[0]));for(let[i,n]of t.entries())r.push(n,new Vt(e[i+1]));return new $e(r)}function $p(e,t){return e.map((r)=>{if(ce(r,Is)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(ce(r,mn)&&ce(r.value,Is)){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 g_e,Vt,$e,ax,PK,zK,r9e,mn,Is,b_e,Tn;var mr=x(()=>{De();EK();Gn();CK();so();Wn();Ir();g_e=class g_e{static[K]="FakePrimitiveParam"};Vt=class Vt{static[K]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new $e([this])}};$e=class $e{constructor(e){this.queryChunks=e;for(let t of e)if(ce(t,we)){let r=t[we.Symbol.Schema];this.usedTables.push(r===void 0?t[we.Symbol.Name]:r+"."+t[we.Symbol.Name])}}static[K]="SQL";decoder=PK;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return $K.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:i,escapeName:n,escapeParam:o,prepareTyping:s,inlineParams:a,paramStartIndex:c}=r;return y_e(e.map((l)=>{if(ce(l,Vt))return{sql:l.value.join(""),params:[]};if(ce(l,ax))return{sql:n(l.value),params:[]};if(l===void 0)return{sql:"",params:[]};if(Array.isArray(l)){let u=[new Vt("(")];for(let[d,p]of l.entries())if(u.push(p),d<l.length-1)u.push(new Vt(", "));return u.push(new Vt(")")),this.buildQueryFromSourceParams(u,r)}if(ce(l,$e))return this.buildQueryFromSourceParams(l.queryChunks,{...r,inlineParams:a||l.shouldInlineParams});if(ce(l,we)){let u=l[we.Symbol.Schema],d=l[we.Symbol.Name];return{sql:u===void 0||l[Ap]?n(d):n(u)+"."+n(d),params:[]}}if(ce(l,it)){let u=i.getColumnCasing(l);if(t.invokeSource==="indexes")return{sql:n(u),params:[]};let d=l.table[we.Symbol.Schema];return{sql:l.table[Ap]||d===void 0?n(l.table[we.Symbol.Name])+"."+n(u):n(d)+"."+n(l.table[we.Symbol.Name])+"."+n(u),params:[]}}if(ce(l,Tn)){let u=l[_t].schema,d=l[_t].name;return{sql:u===void 0||l[_t].isAlias?n(d):n(u)+"."+n(d),params:[]}}if(ce(l,mn)){if(ce(l.value,Is))return{sql:o(c.value++,l),params:[l],typings:["none"]};let u=l.value===null?null:l.encoder.mapToDriverValue(l.value);if(ce(u,$e))return this.buildQueryFromSourceParams([u],r);if(a)return{sql:this.mapInlineParam(u,r),params:[]};let d=["none"];if(s)d=[s(l.encoder)];return{sql:o(c.value++,u),params:[u],typings:d}}if(ce(l,Is))return{sql:o(c.value++,l),params:[l],typings:["none"]};if(ce(l,$e.Aliased)&&l.fieldAlias!==void 0)return{sql:n(l.fieldAlias),params:[]};if(ce(l,vt)){if(l._.isWith)return{sql:n(l._.alias),params:[]};return this.buildQueryFromSourceParams([new Vt("("),l._.sql,new Vt(") "),new ax(l._.alias)],r)}if(_K(l)){if(l.schema)return{sql:n(l.schema)+"."+n(l.enumName),params:[]};return{sql:n(l.enumName),params:[]}}if(KT(l)){if(l.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([l.getSQL()],r);return this.buildQueryFromSourceParams([new Vt("("),l.getSQL(),new Vt(")")],r)}if(a)return{sql:this.mapInlineParam(l,r),params:[]};return{sql:o(c.value++,l),params:[l],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 $e.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}};ax=class ax{constructor(e){this.value=e}static[K]="Name";brand;getSQL(){return new $e([this])}};PK={mapFromDriverValue:(e)=>e},zK={mapToDriverValue:(e)=>e},r9e={...PK,...zK};mn=class mn{constructor(e,t=zK){this.value=e,this.encoder=t}static[K]="Param";brand;getSQL(){return new $e([this])}};((e)=>{function t(){return new $e([])}e.empty=t;function r(c){return new $e(c)}e.fromList=r;function i(c){return new $e([new Vt(c)])}e.raw=i;function n(c,l){let u=[];for(let[d,p]of c.entries()){if(d>0&&l!==void 0)u.push(l);u.push(p)}return new $e(u)}e.join=n;function o(c){return new ax(c)}e.identifier=o;function s(c){return new Is(c)}e.placeholder=s;function a(c,l){return new mn(c,l)}e.param=a})(q||(q={}));((e)=>{class t{constructor(r,i){this.sql=r,this.fieldAlias=i}static[K]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})($e||($e={}));Is=class Is{constructor(e){this.name=e}static[K]="Placeholder";getSQL(){return new $e([this])}};b_e=Symbol.for("drizzle:IsDrizzleView");Tn=class Tn{static[K]="View";[_t];[b_e]=!0;constructor({name:e,schema:t,selectedFields:r,query:i}){this[_t]={name:e,originalName:e,schema:t,selectedFields:r,query:i,isExisting:!i,isAlias:!1}}getSQL(){return new $e([this])}};it.prototype.getSQL=function(){return new $e([this])};we.prototype.getSQL=function(){return new $e([this])};vt.prototype.getSQL=function(){return new $e([this])}});function VT(e,t,r){let i={},n=e.reduce((o,{path:s,field:a},c)=>{let l;if(ce(a,it))l=a;else if(ce(a,$e))l=a.decoder;else if(ce(a,vt))l=a._.sql.decoder;else l=a.sql.decoder;let u=o;for(let[d,p]of s.entries())if(d<s.length-1){if(!(p in u))u[p]={};u=u[p]}else{let m=t[c],y=u[p]=m===null?null:l.mapFromDriverValue(m);if(r&&ce(a,it)&&s.length===2){let g=s[0];if(!(g in i))i[g]=y===null?Es(a.table):!1;else if(typeof i[g]==="string"&&i[g]!==Es(a.table))i[g]=!1}}return o},{});if(r&&Object.keys(i).length>0){for(let[o,s]of Object.entries(i))if(typeof s==="string"&&!r[s])n[o]=null}return n}function On(e,t){return Object.entries(e).reduce((r,[i,n])=>{if(typeof i!=="string")return r;let o=t?[...t,i]:[i];if(ce(n,it)||ce(n,$e)||ce(n,$e.Aliased)||ce(n,vt))r.push({path:o,field:n});else if(ce(n,we))r.push(...On(n[we.Symbol.Columns],o));else r.push(...On(n,o));return r},[])}function Cp(e,t){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let[n,o]of r.entries())if(o!==i[n])return!1;return!0}function cx(e,t){let r=Object.entries(t).filter(([,i])=>i!==void 0).map(([i,n])=>{if(ce(n,$e)||ce(n,it))return[i,n];else return[i,new mn(n,e[we.Symbol.Columns][i])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function NK(e,t){for(let r of t)for(let i of Object.getOwnPropertyNames(r.prototype)){if(i==="constructor")continue;Object.defineProperty(e.prototype,i,Object.getOwnPropertyDescriptor(r.prototype,i)||Object.create(null))}}function lx(e){return e[we.Symbol.Columns]}function Tp(e){return ce(e,vt)?e._.alias:ce(e,Tn)?e[_t].name:ce(e,$e)?void 0:e[we.Symbol.IsAlias]?e[we.Symbol.Name]:e[we.Symbol.BaseName]}function _i(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function DK(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 WT;var Ur=x(()=>{Wn();De();mr();Gn();Ir();so();WT=typeof TextDecoder>"u"?null:new TextDecoder});var LK,GT,QT;var ux=x(()=>{De();LK=class LK{static[K]="ConsoleLogWriter";write(e){console.log(e)}};GT=class GT{static[K]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new LK}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),i=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${i}`)}};QT=class QT{static[K]="NoopLogger";logQuery(){}}});var BK,jK,YT;var qK=x(()=>{De();Ir();BK=Symbol.for("drizzle:PgInlineForeignKeys"),jK=Symbol.for("drizzle:EnableRLS");YT=class YT extends we{static[K]="PgTable";static Symbol=Object.assign({},we.Symbol,{InlineForeignKeys:BK,EnableRLS:jK});[BK]=[];[jK]=!1;[we.Symbol.ExtraConfigBuilder]=void 0;[we.Symbol.ExtraConfigColumns]={}}});var XT,UK;var FK=x(()=>{De();qK();XT=class XT{static[K]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new UK(e,this.columns,this.name)}};UK=class UK{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[K]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[YT.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Qr(e,t){if(RK(t)&&!KT(e)&&!ce(e,mn)&&!ce(e,Is)&&!ce(e,it)&&!ce(e,we)&&!ce(e,Tn))return new mn(e,t);return e}function kt(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new $e(t);return new $e([new Vt("("),q.join(t,new Vt(" and ")),new Vt(")")])}function ao(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new $e(t);return new $e([new Vt("("),q.join(t,new Vt(" or ")),new Vt(")")])}function ZK(e){return q`not ${e}`}function As(e,t){if(Array.isArray(t)){if(t.length===0)return q`false`;return q`${e} in ${t.map((r)=>Qr(r,e))}`}return q`${e} in ${Qr(t,e)}`}function KK(e,t){if(Array.isArray(t)){if(t.length===0)return q`true`;return q`${e} not in ${t.map((r)=>Qr(r,e))}`}return q`${e} not in ${Qr(t,e)}`}function Rn(e){return q`${e} is null`}function VK(e){return q`${e} is not null`}function Op(e){return q`exists ${e}`}function fx(e){return q`not exists ${e}`}function WK(e,t,r){return q`${e} between ${Qr(t,e)} and ${Qr(r,e)}`}function GK(e,t,r){return q`${e} not between ${Qr(t,e)} and ${Qr(r,e)}`}function QK(e,t){return q`${e} like ${t}`}function YK(e,t){return q`${e} not like ${t}`}function XK(e,t){return q`${e} ilike ${t}`}function e9(e,t){return q`${e} not ilike ${t}`}var Qe=(e,t)=>q`${e} = ${Qr(t,e)}`,MK=(e,t)=>q`${e} <> ${Qr(t,e)}`,dx=(e,t)=>q`${e} > ${Qr(t,e)}`,HK=(e,t)=>q`${e} >= ${Qr(t,e)}`,JK=(e,t)=>q`${e} < ${Qr(t,e)}`,Va=(e,t)=>q`${e} <= ${Qr(t,e)}`;var t9=x(()=>{Wn();De();Ir();mr()});function co(e){return q`${e} asc`}function Wa(e){return q`${e} desc`}var r9=x(()=>{mr()});var eO=x(()=>{t9();r9()});function i9(){return{and:kt,between:WK,eq:Qe,exists:Op,gt:dx,gte:HK,ilike:XK,inArray:As,isNull:Rn,isNotNull:VK,like:QK,lt:JK,lte:Va,ne:MK,not:ZK,notBetween:GK,notExists:fx,notLike:YK,notIlike:e9,notInArray:KK,or:ao,sql:q}}function o9(){return{sql:q,asc:co,desc:Wa}}function s9(e,t){if(Object.keys(e).length===1&&"default"in e&&!ce(e.default,we))e=e.default;let r={},i={},n={};for(let[o,s]of Object.entries(e))if(ce(s,we)){let a=Ka(s),c=i[a];r[a]=o,n[o]={tsName:o,dbName:s[we.Symbol.Name],schema:s[we.Symbol.Schema],columns:s[we.Symbol.Columns],relations:c?.relations??{},primaryKey:c?.primaryKey??[]};for(let u of Object.values(s[we.Symbol.Columns]))if(u.primary)n[o].primaryKey.push(u);let l=s[we.Symbol.ExtraConfigBuilder]?.(s[we.Symbol.ExtraConfigColumns]);if(l){for(let u of Object.values(l))if(ce(u,XT))n[o].primaryKey.push(...u.columns)}}else if(ce(s,n9)){let a=Ka(s.table),c=r[a],l=s.config(t(s.table)),u;for(let[d,p]of Object.entries(l))if(c){let m=n[c];if(m.relations[d]=p,u)m.primaryKey.push(...u)}else{if(!(a in i))i[a]={relations:{},primaryKey:u};i[a].relations[d]=p}}return{tables:n,tableNamesMap:r}}function x_e(e){return function(r,i){return new $s(e,r,i,i?.fields.reduce((n,o)=>n&&o.notNull,!0)??!1)}}function S_e(e){return function(r,i){return new Rp(e,r,i)}}function a9(e,t,r){if(ce(r,$s)&&r.config)return{fields:r.config.fields,references:r.config.references};let i=t[Ka(r.referencedTable)];if(!i)throw Error(`Table "${r.referencedTable[we.Symbol.Name]}" not found in schema`);let n=e[i];if(!n)throw Error(`Table "${i}" not found in schema`);let o=r.sourceTable,s=t[Ka(o)];if(!s)throw Error(`Table "${o[we.Symbol.Name]}" not found in schema`);let a=[];for(let c of Object.values(n.relations))if(r.relationName&&r!==c&&c.relationName===r.relationName||!r.relationName&&c.referencedTable===r.sourceTable)a.push(c);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${i}"`):Error(`There are multiple relations between "${i}" and "${r.sourceTable[we.Symbol.Name]}". Please specify relation name`);if(a[0]&&ce(a[0],$s)&&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 c9(e){return{one:x_e(e),many:S_e(e)}}function px(e,t,r,i,n=(o)=>o){let o={};for(let[s,a]of i.entries())if(a.isJson){let c=t.relations[a.tsKey],l=r[s],u=typeof l==="string"?JSON.parse(l):l;o[a.tsKey]=ce(c,$s)?u&&px(e,e[a.relationTableTsKey],u,a.selection,n):u.map((d)=>px(e,e[a.relationTableTsKey],d,a.selection,n))}else{let c=n(r[s]),l=a.field,u;if(ce(l,it))u=l;else if(ce(l,$e))u=l.decoder;else u=l.sql.decoder;o[a.tsKey]=c===null?null:u.mapFromDriverValue(c)}return o}var tO,n9,$s,Rp;var Pp=x(()=>{Ir();Wn();De();FK();eO();mr();tO=class tO{constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[we.Symbol.Name]}static[K]="Relation";referencedTableName;fieldName};n9=class n9{constructor(e,t){this.table=e,this.config=t}static[K]="Relations"};$s=class $s extends tO{constructor(e,t,r,i){super(e,t,r?.relationName);this.config=r,this.isNullable=i}static[K]="One";withFieldName(e){let t=new $s(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};Rp=class Rp extends tO{constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[K]="Many";withFieldName(e){let t=new Rp(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function Np(e,t){return new Proxy(e,new zp(t,!1))}function ki(e,t){return new Proxy(e,new Su(new Proxy(e.table,new zp(t,!1))))}function rO(e,t){return new $e.Aliased(Dp(e.sql,t),e.fieldAlias)}function Dp(e,t){return q.join(e.queryChunks.map((r)=>{if(ce(r,it))return ki(r,t);if(ce(r,$e))return Dp(r,t);if(ce(r,$e.Aliased))return rO(r,t);return r}))}var Su,zp,w_e;var mx=x(()=>{Wn();De();mr();Ir();so();Su=class Su{constructor(e){this.table=e}static[K]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};zp=class zp{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[K]="TableAliasProxyHandler";get(e,t){if(t===we.Symbol.IsAlias)return!0;if(t===we.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===we.Symbol.OriginalName)return this.alias;if(t===_t)return{...e[_t],name:this.alias,isAlias:!0};if(t===we.Symbol.Columns){let i=e[we.Symbol.Columns];if(!i)return i;let n={};return Object.keys(i).map((o)=>{n[o]=new Proxy(i[o],new Su(new Proxy(e,this)))}),n}let r=e[t];if(ce(r,it))return new Proxy(r,new Su(new Proxy(e,this)));return r}};w_e=class w_e{constructor(e){this.alias=e}static[K]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return Np(e.sourceTable,this.alias);return e[t]}}});var bt;var Ga=x(()=>{mx();Wn();De();mr();Gn();so();bt=class bt{static[K]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===_t)return{...e[_t],selectedFields:new Proxy(e[_t].selectedFields,this)};if(typeof t==="symbol")return e[t];let i=(ce(e,vt)?e._.selectedFields:ce(e,Tn)?e[_t].selectedFields:e)[t];if(ce(i,$e.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!i.isSelectionField)return i.sql;let n=i.clone();return n.isSelectionField=!0,n}if(ce(i,$e)){if(this.config.sqlBehavior==="sql")return i;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(ce(i,it)){if(this.config.alias)return new Proxy(i,new Su(new Proxy(i.table,new zp(this.config.alias,this.config.replaceOriginalName??!1))));return i}if(typeof i!=="object"||i===null)return i;return new Proxy(i,new bt(this.config))}}});var Fr;var lo=x(()=>{De();Fr=class Fr{static[K]="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 nO,l9;var iO=x(()=>{De();bu();nO=class nO{static[K]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:i,foreignColumns:n}=e();return{name:r,columns:i,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 l9(e,this)}};l9=class l9{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[K]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),i=t.map((s)=>s.name),n=r.map((s)=>s.name),o=[this.table[Er],...i,r[0].table[Er],...n];return e??`${o.join("_")}_fk`}}});function oO(e,t){return`${e[Er]}_${t.join("_")}_unique`}var u9,v_e,d9;var sO=x(()=>{De();bu();u9=class u9{constructor(e,t){this.name=t,this.columns=e}static[K]="SQLiteUniqueConstraintBuilder";columns;build(e){return new d9(e,this.columns,this.name)}};v_e=class v_e{static[K]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new u9(e,this.name)}};d9=class d9{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??oO(this.table,this.columns.map((i)=>i.name))}static[K]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Xt,$t;var Cs=x(()=>{nx();Wn();De();iO();sO();Xt=class Xt extends kp{static[K]="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:i})=>((n,o)=>{let s=new nO(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(o.onUpdate)s.onUpdate(o.onUpdate);if(o.onDelete)s.onDelete(o.onDelete);return s.build(t)})(r,i))}};$t=class $t extends it{constructor(e,t){if(!t.uniqueName)t.uniqueName=oO(e,[t.name]);super(e,t);this.table=e}static[K]="SQLiteColumn"}});function b9(e,t){let{name:r,config:i}=_i(e,t);if(i?.mode==="json")return new m9(r);if(i?.mode==="bigint")return new f9(r);return new g9(r)}var f9,p9,m9,h9,g9,y9;var aO=x(()=>{De();Ur();Cs();f9=class f9 extends Xt{static[K]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new p9(e,this.config)}};p9=class p9 extends $t{static[K]="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(WT.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};m9=class m9 extends Xt{static[K]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new h9(e,this.config)}};h9=class h9 extends $t{static[K]="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(WT.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};g9=class g9 extends Xt{static[K]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new y9(e,this.config)}};y9=class y9 extends $t{static[K]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function w9(e){return(t,r)=>{let{name:i,config:n}=_i(t,r);return new x9(i,n,e)}}var x9,S9;var cO=x(()=>{De();Ur();Cs();x9=class x9 extends Xt{static[K]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new S9(e,this.config)}};S9=class S9 extends $t{static[K]="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:i}=_i(e,t);if(i?.mode==="timestamp"||i?.mode==="timestamp_ms")return new k9(r,i.mode);if(i?.mode==="boolean")return new I9(r,i.mode);return new v9(r)}var hx,gx,v9,_9,k9,E9,I9,A9;var lO=x(()=>{De();mr();Ur();Cs();hx=class hx extends Xt{static[K]="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()}};gx=class gx extends $t{static[K]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};v9=class v9 extends hx{static[K]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new _9(e,this.config)}};_9=class _9 extends gx{static[K]="SQLiteInteger"};k9=class k9 extends hx{static[K]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(q`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new E9(e,this.config)}};E9=class E9 extends gx{static[K]="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}};I9=class I9 extends hx{static[K]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new A9(e,this.config)}};A9=class A9 extends gx{static[K]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function z9(e,t){let{name:r,config:i}=_i(e,t),n=i?.mode;return n==="number"?new T9(r):n==="bigint"?new R9(r):new $9(r)}var $9,C9,T9,O9,R9,P9;var uO=x(()=>{De();Ur();Cs();$9=class $9 extends Xt{static[K]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new C9(e,this.config)}};C9=class C9 extends $t{static[K]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};T9=class T9 extends Xt{static[K]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new O9(e,this.config)}};O9=class O9 extends $t{static[K]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};R9=class R9 extends Xt{static[K]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new P9(e,this.config)}};P9=class P9 extends $t{static[K]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function L9(e){return new N9(e??"")}var N9,D9;var dO=x(()=>{De();Cs();N9=class N9 extends Xt{static[K]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new D9(e,this.config)}};D9=class D9 extends $t{static[K]="SQLiteReal";getSQLType(){return"real"}}});function hr(e,t={}){let{name:r,config:i}=_i(e,t);if(i.mode==="json")return new q9(r);return new B9(r,i)}var B9,j9,q9,U9;var fO=x(()=>{De();Ur();Cs();B9=class B9 extends Xt{static[K]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new j9(e,this.config)}};j9=class j9 extends $t{static[K]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};q9=class q9 extends Xt{static[K]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new U9(e,this.config)}};U9=class U9 extends $t{static[K]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function F9(){return{blob:b9,customType:w9,integer:Ar,numeric:z9,real:L9,text:hr}}var M9=x(()=>{aO();cO();lO();uO();dO();fO()});function __e(e,t,r,i,n=e){let o=new Ft(e,i,n),s=typeof t==="function"?t(F9()):t,a=Object.fromEntries(Object.entries(s).map(([l,u])=>{let d=u;d.setName(l);let p=d.build(o);return o[pO].push(...d.buildForeignKeys(p,o)),[l,p]})),c=Object.assign(o,a);if(c[we.Symbol.Columns]=a,c[we.Symbol.ExtraConfigColumns]=a,r)c[Ft.Symbol.ExtraConfigBuilder]=r;return c}var pO,Ft,Lp=(e,t,r)=>__e(e,t,r);var uo=x(()=>{De();Ir();M9();pO=Symbol.for("drizzle:SQLiteInlineForeignKeys");Ft=class Ft extends we{static[K]="SQLiteTable";static Symbol=Object.assign({},we.Symbol,{InlineForeignKeys:pO});[we.Symbol.Columns];[pO]=[];[we.Symbol.ExtraConfigBuilder]=void 0}});var k_e,Z9;var H9=x(()=>{De();k_e=class k_e{constructor(e,t){this.name=e,this.value=t}static[K]="SQLiteCheckBuilder";brand;build(e){return new Z9(e,this)}};Z9=class Z9{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[K]="SQLiteCheck";name;value}});function Qa(e){return new J9(e,!1)}var J9,K9,V9;var W9=x(()=>{De();J9=class J9{constructor(e,t){this.name=e,this.unique=t}static[K]="SQLiteIndexBuilderOn";on(...e){return new K9(this.name,e,this.unique)}};K9=class K9{static[K]="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 V9(this.config,e)}};V9=class V9{static[K]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var E_e,G9;var Q9=x(()=>{De();uo();E_e=class E_e{static[K]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new G9(e,this.columns,this.name)}};G9=class G9{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[K]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[Ft.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Qn(e){if(ce(e,Ft))return[`${e[we.Symbol.BaseName]}`];if(ce(e,vt))return e._.usedTables??[];if(ce(e,$e))return e.usedTables??[];return[]}var wu=x(()=>{De();mr();Gn();Ir();uo()});var yx;var Y9=x(()=>{De();lo();Ga();uo();Ir();Ur();wu();yx=class yx extends Fr{constructor(e,t,r,i){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:i}}static[K]="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[we.Symbol.Columns],new bt({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[Ft.Symbol.Columns]){return this.config.returning=On(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:Qn(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 I_e(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function A_e(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,i,n)=>{let o=n===0?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`;return r+o},"")}function $_e(e){return e}var mO;var X9=x(()=>{De();Ir();mO=class mO{static[K]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?I_e:e==="camelCase"?A_e:$_e}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[we.Symbol.Schema]??"public",r=e.table[we.Symbol.OriginalName],i=`${t}.${r}.${e.name}`;if(!this.cache[i])this.cacheTable(e.table);return this.cache[i]}cacheTable(e){let t=e[we.Symbol.Schema]??"public",r=e[we.Symbol.OriginalName],i=`${t}.${r}`;if(!this.cachedTables[i]){for(let n of Object.values(e[we.Symbol.Columns])){let o=`${i}.${n.name}`;this.cache[o]=this.convert(n.name)}this.cachedTables[i]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var vu,fo,hO;var bx=x(()=>{De();vu=class vu extends Error{static[K]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};fo=class fo extends Error{constructor(e,t,r){super(`Failed query: ${e}
|
|
441
|
-
params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrace(this,fo),r)this.cause=r}};hO=class hO extends vu{static[K]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var eV=()=>{};var tV=()=>{};var rV=x(()=>{eV();tV()});var gO=x(()=>{eO();rV();mr()});var yO=x(()=>{aO();Cs();cO();lO();uO();dO();fO()});var po;var Bp=x(()=>{De();mr();po=class po extends Tn{static[K]="SQLiteViewBase"}});var _u,bO,xO;var xx=x(()=>{mx();X9();Wn();De();bx();Pp();gO();mr();yO();uo();Gn();Ir();Ur();so();Bp();_u=class _u{static[K]="SQLiteDialect";casing;constructor(e){this.casing=new mO(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=[q`with `];for(let[r,i]of e.entries())if(t.push(q`${q.identifier(i._.alias)} as (${i._.sql})`),r<e.length-1)t.push(q`, `);return t.push(q` `),q.join(t)}buildDeleteQuery({table:e,where:t,returning:r,withList:i,limit:n,orderBy:o}){let s=this.buildWithCTE(i),a=r?q` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,c=t?q` where ${t}`:void 0,l=this.buildOrderBy(o),u=this.buildLimit(n);return q`${s}delete from ${e}${c}${a}${l}${u}`}buildUpdateSet(e,t){let r=e[we.Symbol.Columns],i=Object.keys(r).filter((o)=>t[o]!==void 0||r[o]?.onUpdateFn!==void 0),n=i.length;return q.join(i.flatMap((o,s)=>{let a=r[o],c=a.onUpdateFn?.(),l=t[o]??(ce(c,$e)?c:q.param(c,a)),u=q`${q.identifier(this.casing.getColumnCasing(a))} = ${l}`;if(s<n-1)return[u,q.raw(", ")];return[u]}))}buildUpdateQuery({table:e,set:t,where:r,returning:i,withList:n,joins:o,from:s,limit:a,orderBy:c}){let l=this.buildWithCTE(n),u=this.buildUpdateSet(e,t),d=s&&q.join([q.raw(" from "),this.buildFromTable(s)]),p=this.buildJoins(o),m=i?q` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,y=r?q` where ${r}`:void 0,g=this.buildOrderBy(c),b=this.buildLimit(a);return q`${l}update ${e} set ${u}${d}${p}${y}${m}${g}${b}`}buildSelection(e,{isSingleTable:t=!1}={}){let r=e.length,i=e.flatMap(({field:n},o)=>{let s=[];if(ce(n,$e.Aliased)&&n.isSelectionField)s.push(q.identifier(n.fieldAlias));else if(ce(n,$e.Aliased)||ce(n,$e)){let a=ce(n,$e.Aliased)?n.sql:n;if(t)s.push(new $e(a.queryChunks.map((c)=>{if(ce(c,it))return q.identifier(this.casing.getColumnCasing(c));return c})));else s.push(a);if(ce(n,$e.Aliased))s.push(q` as ${q.identifier(n.fieldAlias)}`)}else if(ce(n,it)){let a=n.table[we.Symbol.Name];if(n.columnType==="SQLiteNumericBigInt")if(t)s.push(q`cast(${q.identifier(this.casing.getColumnCasing(n))} as text)`);else s.push(q`cast(${q.identifier(a)}.${q.identifier(this.casing.getColumnCasing(n))} as text)`);else if(t)s.push(q.identifier(this.casing.getColumnCasing(n)));else s.push(q`${q.identifier(a)}.${q.identifier(this.casing.getColumnCasing(n))}`)}else if(ce(n,vt)){let a=Object.entries(n._.selectedFields);if(a.length===1){let c=a[0][1],l=ce(c,$e)?c.decoder:ce(c,it)?{mapFromDriverValue:(u)=>c.mapFromDriverValue(u)}:c.sql.decoder;if(l)n._.sql.decoder=l}s.push(n)}if(o<r-1)s.push(q`, `);return s});return q.join(i)}buildJoins(e){if(!e||e.length===0)return;let t=[];if(e)for(let[r,i]of e.entries()){if(r===0)t.push(q` `);let n=i.table,o=i.on?q` on ${i.on}`:void 0;if(ce(n,Ft)){let s=n[Ft.Symbol.Name],a=n[Ft.Symbol.Schema],c=n[Ft.Symbol.OriginalName],l=s===c?void 0:i.alias;t.push(q`${q.raw(i.joinType)} join ${a?q`${q.identifier(a)}.`:void 0}${q.identifier(c)}${l&&q` ${q.identifier(l)}`}${o}`)}else t.push(q`${q.raw(i.joinType)} join ${n}${o}`);if(r<e.length-1)t.push(q` `)}return q.join(t)}buildLimit(e){return typeof e==="object"||typeof e==="number"&&e>=0?q` limit ${e}`:void 0}buildOrderBy(e){let t=[];if(e){for(let[r,i]of e.entries())if(t.push(i),r<e.length-1)t.push(q`, `)}return t.length>0?q` order by ${q.join(t)}`:void 0}buildFromTable(e){if(ce(e,we)&&e[we.Symbol.IsAlias])return q`${q`${q.identifier(e[we.Symbol.Schema]??"")}.`.if(e[we.Symbol.Schema])}${q.identifier(e[we.Symbol.OriginalName])} ${q.identifier(e[we.Symbol.Name])}`;return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:r,where:i,having:n,table:o,joins:s,orderBy:a,groupBy:c,limit:l,offset:u,distinct:d,setOperators:p}){let m=r??On(t);for(let P of m)if(ce(P.field,it)&&Es(P.field.table)!==(ce(o,vt)?o._.alias:ce(o,po)?o[_t].name:ce(o,$e)?void 0:Es(o))&&!((N)=>s?.some(({alias:I})=>I===(N[we.Symbol.IsAlias]?Es(N):N[we.Symbol.BaseName])))(P.field.table)){let N=Es(P.field.table);throw Error(`Your "${P.path.join("->")}" field references a column "${N}"."${P.field.name}", but the table "${N}" is not part of the query! Did you forget to join it?`)}let y=!s||s.length===0,g=this.buildWithCTE(e),b=d?q` distinct`:void 0,v=this.buildSelection(m,{isSingleTable:y}),A=this.buildFromTable(o),C=this.buildJoins(s),z=i?q` where ${i}`:void 0,j=n?q` having ${n}`:void 0,E=[];if(c){for(let[P,N]of c.entries())if(E.push(N),P<c.length-1)E.push(q`, `)}let Z=E.length>0?q` group by ${q.join(E)}`:void 0,D=this.buildOrderBy(a),H=this.buildLimit(l),ee=u?q` offset ${u}`:void 0,F=q`${g}select${b} ${v} from ${A}${C}${z}${Z}${j}${D}${H}${ee}`;if(p.length>0)return this.buildSetOperations(F,p);return F}buildSetOperations(e,t){let[r,...i]=t;if(!r)throw Error("Cannot pass undefined values to any set operator");if(i.length===0)return this.buildSetOperationQuery({leftSelect:e,setOperator:r});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:r}),i)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:r,rightSelect:i,limit:n,orderBy:o,offset:s}}){let a=q`${e.getSQL()} `,c=q`${i.getSQL()}`,l;if(o&&o.length>0){let m=[];for(let y of o)if(ce(y,$t))m.push(q.identifier(y.name));else if(ce(y,$e)){for(let g=0;g<y.queryChunks.length;g++){let b=y.queryChunks[g];if(ce(b,$t))y.queryChunks[g]=q.identifier(this.casing.getColumnCasing(b))}m.push(q`${y}`)}else m.push(q`${y}`);l=q` order by ${q.join(m,q`, `)}`}let u=typeof n==="object"||typeof n==="number"&&n>=0?q` limit ${n}`:void 0,d=q.raw(`${t} ${r?"all ":""}`),p=s?q` offset ${s}`:void 0;return q`${a}${d}${c}${l}${u}${p}`}buildInsertQuery({table:e,values:t,onConflict:r,returning:i,withList:n,select:o}){let s=[],a=e[we.Symbol.Columns],c=Object.entries(a).filter(([y,g])=>!g.shouldDisableInsert()),l=c.map(([,y])=>q.identifier(this.casing.getColumnCasing(y)));if(o){let y=t;if(ce(y,$e))s.push(y);else s.push(y.getSQL())}else{let y=t;s.push(q.raw("values "));for(let[g,b]of y.entries()){let v=[];for(let[A,C]of c){let z=b[A];if(z===void 0||ce(z,mn)&&z.value===void 0){let j;if(C.default!==null&&C.default!==void 0)j=ce(C.default,$e)?C.default:q.param(C.default,C);else if(C.defaultFn!==void 0){let E=C.defaultFn();j=ce(E,$e)?E:q.param(E,C)}else if(!C.default&&C.onUpdateFn!==void 0){let E=C.onUpdateFn();j=ce(E,$e)?E:q.param(E,C)}else j=q`null`;v.push(j)}else v.push(z)}if(s.push(v),g<y.length-1)s.push(q`, `)}}let u=this.buildWithCTE(n),d=q.join(s),p=i?q` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,m=r?.length?q.join(r):void 0;return q`${u}insert into ${e} ${l} ${d}${m}${p}`}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:i,tableConfig:n,queryConfig:o,tableAlias:s,nestedQueryRelation:a,joinOn:c}){let l=[],u,d,p=[],m,y=[];if(o===!0)l=Object.entries(n.columns).map(([v,A])=>({dbKey:A.name,tsKey:v,field:ki(A,s),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let b=Object.fromEntries(Object.entries(n.columns).map(([E,Z])=>[E,ki(Z,s)]));if(o.where){let E=typeof o.where==="function"?o.where(b,i9()):o.where;m=E&&Dp(E,s)}let v=[],A=[];if(o.columns){let E=!1;for(let[Z,D]of Object.entries(o.columns)){if(D===void 0)continue;if(Z in n.columns){if(!E&&D===!0)E=!0;A.push(Z)}}if(A.length>0)A=E?A.filter((Z)=>o.columns?.[Z]===!0):Object.keys(n.columns).filter((Z)=>!A.includes(Z))}else A=Object.keys(n.columns);for(let E of A){let Z=n.columns[E];v.push({tsKey:E,value:Z})}let C=[];if(o.with)C=Object.entries(o.with).filter((E)=>!!E[1]).map(([E,Z])=>({tsKey:E,queryConfig:Z,relation:n.relations[E]}));let z;if(o.extras){z=typeof o.extras==="function"?o.extras(b,{sql:q}):o.extras;for(let[E,Z]of Object.entries(z))v.push({tsKey:E,value:rO(Z,s)})}for(let{tsKey:E,value:Z}of v)l.push({dbKey:ce(Z,$e.Aliased)?Z.fieldAlias:n.columns[E].name,tsKey:E,field:ce(Z,it)?ki(Z,s):Z,relationTableTsKey:void 0,isJson:!1,selection:[]});let j=typeof o.orderBy==="function"?o.orderBy(b,o9()):o.orderBy??[];if(!Array.isArray(j))j=[j];p=j.map((E)=>{if(ce(E,it))return ki(E,s);return Dp(E,s)}),u=o.limit,d=o.offset;for(let{tsKey:E,queryConfig:Z,relation:D}of C){let H=a9(t,r,D),ee=Ka(D.referencedTable),F=r[ee],P=`${s}_${E}`,N=kt(...H.fields.map((O,M)=>Qe(ki(H.references[M],P),ki(O,s)))),I=this.buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:e[F],tableConfig:t[F],queryConfig:ce(D,$s)?Z===!0?{limit:1}:{...Z,limit:1}:Z,tableAlias:P,joinOn:N,nestedQueryRelation:D}),R=q`(${I.sql})`.as(E);l.push({dbKey:E,tsKey:E,field:R,relationTableTsKey:F,isJson:!0,selection:I.selection})}}if(l.length===0)throw new vu({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 g;if(m=kt(c,m),a){let b=q`json_array(${q.join(l.map(({field:C})=>ce(C,$t)?q.identifier(this.casing.getColumnCasing(C)):ce(C,$e.Aliased)?C.sql:C),q`, `)})`;if(ce(a,Rp))b=q`coalesce(json_group_array(${b}), json_array())`;let v=[{dbKey:"data",tsKey:"data",field:b.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:l}];if(u!==void 0||d!==void 0||p.length>0)g=this.buildSelectQuery({table:Np(i,s),fields:{},fieldsFlat:[{path:[],field:q.raw("*")}],where:m,limit:u,offset:d,orderBy:p,setOperators:[]}),m=void 0,u=void 0,d=void 0,p=void 0;else g=Np(i,s);g=this.buildSelectQuery({table:ce(g,Ft)?g:new vt(g,{},s),fields:{},fieldsFlat:v.map(({field:C})=>({path:[],field:ce(C,it)?ki(C,s):C})),joins:y,where:m,limit:u,offset:d,orderBy:p,setOperators:[]})}else g=this.buildSelectQuery({table:Np(i,s),fields:{},fieldsFlat:l.map(({field:b})=>({path:[],field:ce(b,it)?ki(b,s):b})),joins:y,where:m,limit:u,offset:d,orderBy:p,setOperators:[]});return{tableTsKey:n.tsName,sql:g,selection:l}}};bO=class bO extends _u{static[K]="SQLiteSyncDialect";migrate(e,t,r){let i=r===void 0?"__drizzle_migrations":typeof r==="string"?"__drizzle_migrations":r.migrationsTable??"__drizzle_migrations",n=q`
|
|
440
|
+
`)}catch{}}}formatJsonEntry(e,t,r){let i={ts:new Date().toISOString(),level:e,msg:t};if(this.context)i.ctx=this.context;if(r.length>0)i.data=r;return JSON.stringify(i)}silly(e,...t){if(this.level<=Da.SILLY)this.write(console.debug.bind(console),"silly",e,t)}verbose(e,...t){if(this.level<=Da.VERBOSE)this.write(console.debug.bind(console),"verbose",e,t)}debug(e,...t){if(this.level<=Da.DEBUG)this.write(console.debug.bind(console),"debug",e,t)}info(e,...t){if(this.level<=Da.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<=Da.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=Da.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new fn({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var Da,g5e;var YC=x(()=>{Da={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};g5e=fn.getInstance()});var XC,kwe,Gl,S5e;var tp=x(()=>{jo();Ne();XC=f.enum(["file_operations","content_operations","data_processing","batch_processing"]),kwe=f.looseObject({pluginId:f.string().optional(),progressToken:f.union([f.string(),f.number()]).optional(),operationType:XC,operationTarget:f.string().optional(),interfaceType:f.string().optional(),conversationId:f.string().optional(),channelId:f.string().optional(),requestedByActor:ol.optional(),requestedByUserId:f.string().optional(),requestedByInterface:f.string().optional(),silent:f.boolean().optional(),provenance:Bo.optional()}),Gl=f.looseObject({pluginId:f.string().optional(),progressToken:f.union([f.string(),f.number()]).optional(),operationType:XC,operationTarget:f.string().optional(),interfaceType:f.string().optional(),conversationId:f.string().optional(),channelId:f.string().optional(),requestedByActor:ol.optional(),requestedByUserId:f.string().optional(),requestedByInterface:f.string().optional(),silent:f.boolean().optional(),provenance:Bo.optional(),rootJobId:f.string()}),S5e=f.enum(["none","skip","replace","coalesce"])});var Ewe,ms=15000;var rp=x(()=>{tp();Ne();Ewe=f.object({id:f.string(),type:f.string(),data:f.string(),status:f.enum(["pending","processing","completed","failed"]),source:f.string().nullable(),priority:f.number(),retryCount:f.number(),maxRetries:f.number(),lastError:f.string().nullable(),createdAt:f.number(),scheduledFor:f.number(),startedAt:f.number().nullable(),completedAt:f.number().nullable(),attemptId:f.string().nullable(),workerSlotId:f.string().nullable(),workerSessionId:f.string().nullable(),leaseExpiresAt:f.number().nullable(),attemptHeartbeatAt:f.number().nullable(),runtimeUpdatedAt:f.number().nullable(),metadata:Gl,progress:f.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:f.unknown().nullable().optional()})});var eT,G8,je,Iwe,Awe,Q8,$we;var hs=x(()=>{Ne();tp();eT=f.enum(["pending","processing","completed","failed"]),G8=f.enum(["completed","failed"]),je={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},Iwe=f.object({id:f.string(),type:f.string(),status:eT,data:f.unknown(),result:f.unknown().optional(),lastError:f.string().optional().nullable(),attempts:f.number(),maxRetries:f.number(),priority:f.number(),createdAt:f.date(),updatedAt:f.date(),processedAt:f.date().optional().nullable(),completedAt:f.date().optional().nullable(),failedAt:f.date().optional().nullable()}),Awe=f.object({jobId:f.string(),type:f.string(),status:G8,result:f.unknown().optional(),error:f.string().optional()}),Q8=f.object({success:f.literal(!1),error:f.string().optional()}),$we=f.object({id:f.string(),type:f.enum(["job","batch"]),status:eT,message:f.string().optional(),progress:f.object({current:f.number(),total:f.number(),percentage:f.number()}).optional(),aggregationKey:f.string().optional(),batchDetails:f.object({totalOperations:f.number(),completedOperations:f.number(),failedOperations:f.number(),currentOperation:f.string().optional(),errors:f.array(f.string()).optional()}).optional(),jobDetails:f.object({jobType:f.string(),priority:f.number(),retryCount:f.number()}).optional(),metadata:Gl})});var Me,fr;var Jn=x(()=>{Me=class Me extends Error{code;extendedCode;rawCode;constructor(e,t,r,i,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=i,this.name="LibsqlError"}};fr=class fr extends Me{statementIndex;constructor(e,t,r,i,n,o){super(e,r,i,n,o);this.statementIndex=t,this.name="LibsqlBatchError"}}});function Y8(e){let t=Cwe.exec(e);if(t===null)throw new Me(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,i=r.scheme,n=r.authority!==void 0?Twe(r.authority):void 0,o=La(r.path),s=r.query!==void 0?Rwe(r.query):void 0,a=r.fragment!==void 0?La(r.fragment):void 0;return{scheme:i,authority:n,path:o,query:s,fragment:a}}function Twe(e){let t=Owe.exec(e);if(t===null)throw new Me("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,i=La(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,o=r.username!==void 0?{username:La(r.username),password:r.password!==void 0?La(r.password):void 0}:void 0;return{host:i,port:n,userinfo:o}}function Rwe(e){let t=e.split("&"),r=[];for(let i of t){if(i==="")continue;let n,o,s=i.indexOf("=");if(s<0)n=i,o="";else n=i.substring(0,s),o=i.substring(s+1);r.push({key:La(n.replaceAll("+"," ")),value:La(o.replaceAll("+"," "))})}return{pairs:r}}function La(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Me(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function np(e,t,r){if(t===void 0)throw new Me(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let i=`${e}:`,n=Pwe(t.host),o=zwe(t.port),a=`//${Nwe(t.userinfo)}${n}${o}`,c=r.split("/").map(encodeURIComponent).join("/");if(c!==""&&!c.startsWith("/"))c="/"+c;return new URL(`${i}${a}${c}`)}function Pwe(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function zwe(e){return e!==void 0?`:${e}`:""}function Nwe(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var Cwe,Owe;var Rb=x(()=>{Jn();Cwe=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();Owe=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var Yl,X8,eH,ip,Pb,Dwe,pr,tH,iH=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),oH=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),sH=(e)=>{let t,r,i,n,o="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(i=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|i<<8|n,o+=ip[t>>18&63]+ip[t>>12&63]+ip[t>>6&63]+ip[t&63]}return s?o.slice(0,s-3)+"===".substring(s):o},nT,tT,zb=(e,t=!1)=>t?iH(tT(e)):tT(e),Lwe=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?pr(192|t>>>6)+pr(128|t&63):pr(224|t>>>12&15)+pr(128|t>>>6&63)+pr(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return pr(240|t>>>18&7)+pr(128|t>>>12&63)+pr(128|t>>>6&63)+pr(128|t&63)}},Bwe,aH=(e)=>e.replace(Bwe,Lwe),rH,Ql=(e,t=!1)=>t?iH(rH(e)):rH(e),nH=(e)=>Ql(e,!0),jwe,qwe=(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 pr((r>>>10)+55296)+pr((r&1023)+56320);case 3:return pr((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return pr((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},cH=(e)=>e.replace(jwe,qwe),lH=(e)=>{if(e=e.replace(/\s+/g,""),!Dwe.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,i,n=[];for(let o=0;o<e.length;)if(t=Pb[e.charAt(o++)]<<18|Pb[e.charAt(o++)]<<12|(r=Pb[e.charAt(o++)])<<6|(i=Pb[e.charAt(o++)]),r===64)n.push(pr(t>>16&255));else if(i===64)n.push(pr(t>>16&255,t>>8&255));else n.push(pr(t>>16&255,t>>8&255,t&255));return n.join("")},iT,uH,dH=(e)=>uH(fH(e)),Uwe,fH=(e)=>oH(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),rT=(e)=>Uwe(fH(e)),Fwe=(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)},pH=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),mH=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,pH(r));e("fromBase64",function(){return rT(this)}),e("toBase64",function(t){return Ql(this,t)}),e("toBase64URI",function(){return Ql(this,!0)}),e("toBase64URL",function(){return Ql(this,!0)}),e("toUint8Array",function(){return dH(this)})},hH=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,pH(r));e("toBase64",function(t){return zb(this,t)}),e("toBase64URI",function(){return zb(this,!0)}),e("toBase64URL",function(){return zb(this,!0)})},Mwe=()=>{mH(),hH()},Xl;var Nb=x(()=>{Yl=typeof Buffer==="function",X8=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,eH=typeof TextEncoder==="function"?new TextEncoder:void 0,ip=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),Pb=((e)=>{let t={};return e.forEach((r,i)=>t[r]=i),t})(ip),Dwe=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,pr=String.fromCharCode.bind(String),tH=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),nT=typeof btoa==="function"?(e)=>btoa(e):Yl?(e)=>Buffer.from(e,"binary").toString("base64"):sH,tT=Yl?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let i=0,n=e.length;i<n;i+=4096)r.push(pr.apply(null,e.subarray(i,i+4096)));return nT(r.join(""))},Bwe=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,rH=Yl?(e)=>Buffer.from(e,"utf8").toString("base64"):eH?(e)=>tT(eH.encode(e)):(e)=>nT(aH(e)),jwe=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,iT=typeof atob==="function"?(e)=>atob(oH(e)):Yl?(e)=>Buffer.from(e,"base64").toString("binary"):lH,uH=Yl?(e)=>tH(Buffer.from(e,"base64")):(e)=>tH(iT(e).split("").map((t)=>t.charCodeAt(0))),Uwe=Yl?(e)=>Buffer.from(e,"base64").toString("utf8"):X8?(e)=>X8.decode(uH(e)):(e)=>cH(iT(e)),Xl={version:"3.8.0",VERSION:"3.8.0",atob:iT,atobPolyfill:lH,btoa:nT,btoaPolyfill:sH,fromBase64:rT,toBase64:Ql,encode:Ql,encodeURI:nH,encodeURL:nH,utob:aH,btou:cH,decode:rT,isValid:Fwe,fromUint8Array:zb,toUint8Array:dH,extendString:mH,extendUint8Array:hH,extendBuiltins:Mwe}});function gs(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 eu{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,i,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=i,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(Zwe),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function Zwe(e){return Array.prototype.map.call(e,Hwe)}function Hwe(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return Xl.fromUint8Array(new Uint8Array(e));else return e}var xi="https://github.com/libsql/libsql-client-ts#supported-urls";var tu=x(()=>{Nb()});function yH(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function op(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:i,tls:n,intMode:o,concurrency:s}=e;s=Math.max(0,s||20),o??="number";let a=[];if(r===gH)r="file::memory:";let c=Y8(r),l=c.scheme.toLowerCase(),u=l==="file"&&c.path===gH&&c.authority===void 0,d;if(u)d={cache:{values:["shared","private"],update:(g,b)=>a.push(`${g}=${b}`)}};else d={tls:{values:["0","1"],update:(g,b)=>n=b==="1"},authToken:{update:(g,b)=>i=b}};for(let{key:g,value:b}of c.query?.pairs??[]){if(!Object.hasOwn(d,g))throw new Me(`Unsupported URL query parameter ${JSON.stringify(g)}`,"URL_PARAM_NOT_SUPPORTED");let v=d[g];if(v.values!==void 0&&!v.values.includes(b))throw new Me(`Unknown value for the "${g}" query argument: ${JSON.stringify(b)}. Supported values are: [${v.values.map((A)=>'"'+A+'"').join(", ")}]`,"URL_INVALID");if(v.update!==void 0)v?.update(g,b)}let p=a.length===0?"":`?${a.join("&")}`,m=c.path+p,y;if(l==="libsql")if(n===!1){if(c.authority?.port===void 0)throw new Me('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");y=t?"http":"ws"}else y=t?"https":"wss";else y=l;if(y==="http"||y==="ws")n??=!1;else n??=!0;if(y!=="http"&&y!=="ws"&&y!=="https"&&y!=="wss"&&y!=="file")throw new Me(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(c.scheme+":")}. For more information, please read ${xi}`,"URL_SCHEME_NOT_SUPPORTED");if(o!=="number"&&o!=="bigint"&&o!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(o)}`);if(c.fragment!==void 0)throw new Me(`URL fragments are not supported: ${JSON.stringify("#"+c.fragment)}`,"URL_INVALID");if(u)return{scheme:"file",tls:!1,path:m,intMode:o,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:y,tls:n,authority:c.authority,path:m,authToken:i,intMode:o,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 gH=":memory:";var sp=x(()=>{Jn();Rb();tu()});var xH=te(function(An){var Jwe=An&&An.__createBinding||(Object.create?function(e,t,r,i){if(i===void 0)i=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,i,n)}:function(e,t,r,i){if(i===void 0)i=r;e[i]=t[r]}),Kwe=An&&An.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),bH=An&&An.__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))Jwe(t,e,r)}return Kwe(t,e),t};Object.defineProperty(An,"__esModule",{value:!0});An.load=An.currentTarget=void 0;var Vwe=bH(Ct("path")),Wwe=bH(Ct("fs"));function Gwe(){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 Qwe()?`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}`)}An.currentTarget=Gwe;function Qwe(){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 Ywe(e){let t=Vwe.join(e,"index.node");return Wwe.existsSync(t)?Ct(t):null}An.load=Ywe});var vH=te(function(q5e,wH){var SH=()=>process.platform==="linux",oT=null,Xwe=()=>{if(!oT)oT=SH()&&process.report?process.report.getReport():{};return oT};wH.exports={isLinux:SH,getReport:Xwe}});var EH=te(function(U5e,kH){var _H=Ct("fs"),e0e=(e)=>_H.readFileSync(e,"utf-8"),t0e=(e)=>new Promise((t,r)=>{_H.readFile(e,"utf-8",(i,n)=>{if(i)r(i);else t(n)})});kH.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:e0e,readFile:t0e}});var FH=te(function(F5e,UH){var AH=Ct("child_process"),{isLinux:ru,getReport:$H}=vH(),{LDD_PATH:Db,readFile:CH,readFileSync:TH}=EH(),Si,wi,ys="",OH=()=>{if(!ys)return new Promise((e)=>{AH.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{ys=t?" ":r,e(ys)})});return ys},RH=()=>{if(!ys)try{ys=AH.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){ys=" "}return ys},ro="glibc",PH=/GLIBC\s(\d+\.\d+)/,Ba="musl",r0e=ro.toUpperCase(),n0e=Ba.toLowerCase(),i0e=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),zH=()=>{let e=$H();if(e.header&&e.header.glibcVersionRuntime)return ro;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(i0e))return Ba}return null},NH=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(ro))return ro;if(r&&r.includes(Ba))return Ba;return null},DH=(e)=>{if(e.includes(n0e))return Ba;if(e.includes(r0e))return ro;return null},o0e=async()=>{if(Si!==void 0)return Si;Si=null;try{let e=await CH(Db);Si=DH(e)}catch(e){}return Si},s0e=()=>{if(Si!==void 0)return Si;Si=null;try{let e=TH(Db);Si=DH(e)}catch(e){}return Si},LH=async()=>{let e=null;if(ru()){if(e=await o0e(),!e)e=zH();if(!e){let t=await OH();e=NH(t)}}return e},BH=()=>{let e=null;if(ru()){if(e=s0e(),!e)e=zH();if(!e){let t=RH();e=NH(t)}}return e},a0e=async()=>ru()&&await LH()!==ro,c0e=()=>ru()&&BH()!==ro,l0e=async()=>{if(wi!==void 0)return wi;wi=null;try{let t=(await CH(Db)).match(PH);if(t)wi=t[1]}catch(e){}return wi},u0e=()=>{if(wi!==void 0)return wi;wi=null;try{let t=TH(Db).match(PH);if(t)wi=t[1]}catch(e){}return wi},jH=()=>{let e=$H();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},IH=(e)=>e.trim().split(/\s+/)[1],qH=(e)=>{let[t,r,i]=e.split(/[\r\n]+/);if(t&&t.includes(ro))return IH(t);if(r&&i&&r.includes(Ba))return IH(i);return null},d0e=async()=>{let e=null;if(ru()){if(e=await l0e(),!e)e=jH();if(!e){let t=await OH();e=qH(t)}}return e},f0e=()=>{let e=null;if(ru()){if(e=u0e(),!e)e=jH();if(!e){let t=RH();e=qH(t)}}return e};UH.exports={GLIBC:ro,MUSL:Ba,family:LH,familySync:BH,isNonGlibcLinux:a0e,isNonGlibcLinuxSync:c0e,version:d0e,versionSync:f0e}});var ZH=te(function(M5e,MH){var p0e={ALLOW:0,DENY:1};MH.exports=p0e});var JH=te(function(Z5e,HH){var sT={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function ja(e,t,r){if(new.target!==ja)return new ja(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),sT.value=""+e,Object.defineProperty(this,"message",sT),Error.captureStackTrace(this,ja),this.code=t,this.rawCode=r}Object.setPrototypeOf(ja,Error);Object.setPrototypeOf(ja.prototype,Error.prototype);Object.defineProperty(ja.prototype,"name",sT);HH.exports=ja});var eJ=te(function(H5e,Lb){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:m0e,currentTarget:h0e}=xH(),{familySync:KH,GLIBC:g0e,MUSL:y0e}=FH();function b0e(){if(process.env.LIBSQL_JS_DEV)return m0e(__dirname);let e=h0e();if(KH()==g0e)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"&&KH()==y0e)e="linux-arm-musleabihf";return Ct(`@libsql/${e}`)}var{databaseOpen:x0e,databaseOpenWithSync:S0e,databaseInTransaction:w0e,databaseInterrupt:v0e,databaseClose:_0e,databaseSyncSync:k0e,databaseSyncUntilSync:E0e,databaseExecSync:I0e,databasePrepareSync:A0e,databaseDefaultSafeIntegers:$0e,databaseAuthorizer:C0e,databaseLoadExtension:T0e,databaseMaxWriteReplicationIndex:O0e,statementRaw:R0e,statementIsReader:P0e,statementGet:VH,statementRun:WH,statementInterrupt:z0e,statementRowsSync:GH,statementColumns:N0e,statementSafeIntegers:D0e,rowsNext:L0e}=b0e(),B0e=ZH(),QH=JH();function nu(e){if(e.libsqlError)return new QH(e.message,e.code,e.rawCode);return e}class YH{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var i="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),i=t.syncAuth;else if(t.authToken)i=t.authToken;let o=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,c=t?.offline??!1,l=t?.remoteEncryptionKey??"";this.db=S0e(e,t.syncUrl,i,r,o,s,a,c,l)}else{let o=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,c=t?.remoteEncryptionKey??"";this.db=x0e(e,o,r,s,a,c)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let n=this.db;Object.defineProperties(this,{inTransaction:{get(){return w0e(n)}}})}sync(){return k0e.call(this.db)}syncUntil(e){return E0e.call(this.db,e)}prepare(e){try{let t=A0e.call(this.db,e);return new XH(t)}catch(t){throw nu(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...o)=>{t.exec("BEGIN "+n);try{let s=e(...o);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},i={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(i.default.value,i),Object.defineProperties(i.deferred.value,i),Object.defineProperties(i.immediate.value,i),Object.defineProperties(i.exclusive.value,i),i.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,i=this.prepare(`PRAGMA ${e}`,this,!0);return r?i.pluck().get():i.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){C0e.call(this.db,e)}loadExtension(...e){T0e.call(this.db,...e)}maxWriteReplicationIndex(){return O0e.call(this.db)}exec(e){try{I0e.call(this.db,e)}catch(t){throw nu(t)}}interrupt(){v0e.call(this.db)}close(){_0e.call(this.db),this.open=!1}defaultSafeIntegers(e){return $0e.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class XH{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return R0e.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return P0e.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return WH.call(this.stmt,e[0]);else return WH.call(this.stmt,e.flat())}catch(t){throw nu(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return VH.call(this.stmt,e[0]);else return VH.call(this.stmt,e.flat())}catch(t){throw nu(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=GH.call(this.stmt,e[0]);else t=GH.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)L0e.call(t,this.nextRows),this.nextRowIndex=0;let i=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!i)return{done:!0};return this.nextRowIndex++,{value:i,done:!1}}catch(i){throw nu(i)}},[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 nu(t)}}interrupt(){z0e.call(this.stmt)}columns(){return N0e.call(this.stmt)}safeIntegers(e){return D0e.call(this.stmt,e??!0),this}}Lb.exports=YH;Lb.exports.Authorization=B0e;Lb.exports.SqliteError=QH});import{Buffer as rJ}from"buffer";function nJ(e){if(e.scheme!=="file")throw new Me(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${xi}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Me(`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 ${xi}`,"URL_INVALID");if(t.port!==void 0)throw new Me("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Me("File URL cannot have username and password","URL_INVALID")}let r=yH(e);if(r&&e.syncUrl)throw new Me(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let i=e.path;if(r)i=`${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},o=new ap.default(i,n);return Kt(o,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new iJ(i,n,o,e.intMode)}class iJ{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,i){this.#e=e,this.#t=t,this.#r=r,this.#n=i,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.#i(),Kt(this.#o(),r,this.#n)}async batch(e,t="deferred"){this.#i();let r=this.#o();try{Kt(r,gs(t),this.#n);let i=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new fr("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let o=e[n],s=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;i.push(Kt(r,s,this.#n))}catch(o){if(o instanceof fr)throw o;if(o instanceof Me)throw new fr(o.message,n,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return Kt(r,"COMMIT",this.#n),i}finally{if(r.inTransaction)Kt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#i();let t=this.#o();try{Kt(t,"PRAGMA foreign_keys=off",this.#n),Kt(t,gs("deferred"),this.#n);let r=[];for(let i=0;i<e.length;i++)try{if(!t.inTransaction)throw new fr("The transaction has been rolled back",i,"TRANSACTION_CLOSED");r.push(Kt(t,e[i],this.#n))}catch(n){if(n instanceof fr)throw n;if(n instanceof Me)throw new fr(n.message,i,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return Kt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)Kt(t,"ROLLBACK",this.#n);Kt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#o();return Kt(t,gs(e),this.#n),this.#r=null,new oJ(t,this.#n)}async executeMultiple(e){this.#i();let t=this.#o();try{return sJ(t,e)}finally{if(t.inTransaction)Kt(t,"ROLLBACK",this.#n)}}async sync(){this.#i();let e=await this.#o().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 ap.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#i(){if(this.closed)throw new Me("The client is closed","CLIENT_CLOSED")}#o(){if(this.#r===null)this.#r=new ap.default(this.#e,this.#t);return this.#r}}class oJ{#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(),Kt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let i=e[r],n=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;t.push(Kt(this.#e,n,this.#t))}catch(i){if(i instanceof fr)throw i;if(i instanceof Me)throw new fr(i.message,r,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return t}async executeMultiple(e){return this.#r(),sJ(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),Kt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),Kt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)Kt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Me("The transaction is closed","TRANSACTION_CLOSED")}}function Kt(e,t,r){let i,n;if(typeof t==="string")i=t,n=[];else if(i=t.sql,Array.isArray(t.args))n=t.args.map((o)=>tJ(o,r));else{n={};for(let o in t.args){let s=o[0]==="@"||o[0]==="$"||o[0]===":"?o.substring(1):o;n[s]=tJ(t.args[o],r)}}try{let o=e.prepare(i);o.safeIntegers(!0);let s=!0;try{o.raw(!0)}catch{s=!1}if(s){let a=Array.from(o.columns().map((p)=>p.name)),c=Array.from(o.columns().map((p)=>p.type??"")),l=o.all(n).map((p)=>j0e(p,a,r)),u=0,d=void 0;return new eu(a,c,l,0,void 0)}else{let a=o.run(n),c=a.changes,l=BigInt(a.lastInsertRowid);return new eu([],[],[],c,l)}}catch(o){throw aJ(o)}}function j0e(e,t,r){let i={};Object.defineProperty(i,"length",{value:e.length});for(let n=0;n<e.length;++n){let o=q0e(e[n],r);Object.defineProperty(i,n,{value:o});let s=t[n];if(!Object.hasOwn(i,s))Object.defineProperty(i,s,{value:o,enumerable:!0,configurable:!0,writable:!0})}return i}function q0e(e,t){if(typeof e==="bigint")if(t==="number"){if(e<U0e||e>F0e)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 rJ)return e.buffer;return e}function tJ(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<M0e||e>Z0e)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 rJ.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 sJ(e,t){try{e.exec(t)}catch(r){throw aJ(r)}}function aJ(e){if(e instanceof ap.default.SqliteError){let t=e.code,r=H0e(e.rawCode);return new Me(e.message,r,t,e.rawCode,e)}return e}function H0e(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return J0e[t]??`SQLITE_UNKNOWN_${t.toString()}`}var ap,U0e,F0e=9007199254740991n,M0e,Z0e=9223372036854775807n,J0e;var cJ=x(()=>{Jn();sp();tu();ap=ic(eJ(),1);Jn();U0e=-9007199254740991n;M0e=-9223372036854775808n;J0e={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 bs;var aT=x(()=>{if(typeof WebSocket<"u")bs=WebSocket;else if(typeof global<"u")bs=global.WebSocket;else if(typeof window<"u")bs=window.WebSocket;else if(typeof self<"u")bs=self.WebSocket});class iu{constructor(){this.intMode="number"}intMode}var at,qe,cp,zt,lp,ou,qa,Kn,kr,vi;var Nt=x(()=>{at=class at extends Error{constructor(e){super(e);this.name="ClientError"}};qe=class qe extends at{constructor(e){super(e);this.name="ProtoError"}};cp=class cp extends at{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};zt=class zt extends at{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};lp=class lp extends at{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};ou=class ou extends at{constructor(e){super(e);this.name="WebSocketError"}};qa=class qa extends at{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};Kn=class Kn extends at{constructor(e){super(e);this.name="ProtocolVersionError"}};kr=class kr extends at{constructor(e){super(e);this.name="InternalError"}};vi=class vi extends at{constructor(e){super(e);this.name="MisuseError"}}});function Gr(e){if(typeof e==="string")return e;throw su(e,"string")}function pn(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw su(e,"string or null")}function no(e){if(typeof e==="number")return e;throw su(e,"number")}function xs(e){if(typeof e==="boolean")return e;throw su(e,"boolean")}function up(e){if(Array.isArray(e))return e;throw su(e,"array")}function Ut(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw su(e,"object")}function Vn(e,t){return up(e).map((r)=>t(Ut(r)))}function su(e,t){if(e===void 0)return new qe(`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 qe(`Expected ${t}, received ${r}`)}function Ua(e,t){return t(Ut(e))}var au=x(()=>{Nt()});class lJ{#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 i=0;i<t.length;++i){if(i!==0)this.#e.push(",");this.begin(),r(this,t[i]),this.end()}this.#e.push("]")}}function dp(e,t){let r=[],i=new lJ(r);return i.begin(),t(i,e),i.end(),r.join("")}var Fa=0,fp=1,pp=2,uJ=5;class dJ{#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 fJ{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new qe(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(pp);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return Ss(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(fp),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===Fa)this.#e.skipVarint();else if(this.#t===fp)this.#e.skip(8);else if(this.#t===pp){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===uJ)this.#e.skip(4);else throw new qe(`Unexpected wire type ${this.#t}`);this.#t=-1}}function Ss(e,t){let r=new dJ(e),i=new fJ(r),n=t.default();while(!r.eof()){let o=r.varint(),s=o>>3,a=o&7;i.setup(a);let c=t[s];if(c!==void 0){let l=c(i,n);if(l!==void 0)n=l}i.maybeSkip()}return n}var cT=x(()=>{Nt()});class lT{#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}#i(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),i=new Uint8Array(r),n=new DataView(r);i.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=i,this.#r=n}#o(e){this.#i(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.#i(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.#o(e<<3|t)}bytes(e,t){this.#s(e,pp),this.#o(t.byteLength),this.#i(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 i=new lT;r(i,t),this.bytes(e,i.data())}int32(e,t){this.#s(e,Fa),this.#o(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,fp),this.#i(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function mp(e,t){let r=new lT;return t(r,e),r.data()}var pJ=()=>{};var uT=x(()=>{au();cT();pJ()});class ws{#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 kr("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var dT=x(()=>{Nt()});function nt(e,t){throw new kr(t)}var $n=x(()=>{Nt()});function cu(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<V0e||e>W0e)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 fT(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 vi("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new qe("Received unrecognized type of Value");else throw nt(e,"Impossible type of Value")}var V0e,W0e=9223372036854775807n;var pT=x(()=>{Nt();$n();V0e=-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 jb(e,t){let r=Ma(e),i=e.rows.map((n)=>mJ(r.columnNames,n,t));return{...r,rows:i}}function qb(e,t){let r=Ma(e),i;if(e.rows.length>0)i=mJ(r.columnNames,e.rows[0],t);return{...r,row:i}}function Ub(e,t){let r=Ma(e),i;if(e.rows.length>0&&r.columnNames.length>0)i=fT(e.rows[0][0],t);return{...r,value:i}}function mJ(e,t,r){let i={};Object.defineProperty(i,"length",{value:t.length});for(let n=0;n<t.length;++n){let o=fT(t[n],r);Object.defineProperty(i,n,{value:o});let s=e[n];if(s!==void 0&&!Object.hasOwn(i,s))Object.defineProperty(i,s,{value:o,enumerable:!0,configurable:!0,writable:!0})}return i}function io(e){return new cp(e.message,e)}var hp=x(()=>{Nt();pT()});class Za{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new vi("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new zt("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new at("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 gp(e,t){if(t instanceof Za)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var lu=x(()=>{Nt()});class vs{#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 yp{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(cu(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]=cu(t),this}bindName(e,t){return this._namedArgs.set(e,cu(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function Fb(e,t,r){let i,n=[],o=[];if(t instanceof yp){i=t.sql,n=t._args;for(let[c,l]of t._namedArgs.entries())o.push({name:c,value:l})}else if(Array.isArray(t))if(i=t[0],Array.isArray(t[1]))n=t[1].map((c)=>cu(c));else o=Object.entries(t[1]).map(([c,l])=>({name:c,value:cu(l)}));else i=t;let{sql:s,sqlId:a}=gp(e,i);return{sql:s,sqlId:a,args:n,namedArgs:o,wantRows:r}}var Mb=x(()=>{lu();pT()});class Zb{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new mT(this)}execute(){if(this.#t)throw new vi("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return Q0e(this._stream,this._steps,e);else return G0e(this._stream,this._steps,e)}}function G0e(e,t,r){return e._batch(r).then((i)=>{for(let n=0;n<t.length;++n){let o=i.stepResults.get(n),s=i.stepErrors.get(n);t[n].callback(o,s)}})}async function Q0e(e,t,r){let i=await e._openCursor(r);try{let n=0,o=void 0,s=[];for(;;){let a=await i.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new qe("Server produced StepBeginEntry for unexpected step");else if(o!==void 0)throw new qe("Server produced StepBeginEntry before terminating previous step");for(let c=n;c<a.step;++c)t[c].callback(void 0,void 0);n=a.step+1,o=a,s=[]}else if(a.type==="step_end"){if(o===void 0)throw new qe("Server produced StepEndEntry but no step is active");let c={cols:o.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[o.step].callback(c,void 0),o=void 0,s=[]}else if(a.type==="step_error"){if(o===void 0){if(a.step>=t.length)throw new qe("Server produced StepErrorEntry for unexpected step");for(let c=n;c<a.step;++c)t[c].callback(void 0,void 0)}else{if(a.step!==o.step)throw new qe("Server produced StepErrorEntry for unexpected step");o=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(o===void 0)throw new qe("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw io(a.error);else if(a.type==="none")throw new qe("Server produced unrecognized CursorEntry");else throw nt(a,"Impossible CursorEntry")}if(o!==void 0)throw new qe("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{i.close()}}class mT{_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,jb)}queryRow(e){return this.#t(e,!0,qb)}queryValue(e){return this.#t(e,!0,Ub)}run(e){return this.#t(e,!1,Ma)}#t(e,t,r){if(this._index!==void 0)throw new vi("This BatchStep has already been added to the batch");let i=Fb(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 o={stmt:i,condition:n};return new Promise((s,a)=>{let c=(l,u)=>{if(l!==void 0&&u!==void 0)a(new qe("Server returned both result and error"));else if(u!==void 0)a(io(u));else if(l!==void 0)s(r(l,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:o,callback:c})})}}class wt{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new wt(e._batch,{type:"ok",step:hJ(e)})}static error(e){return new wt(e._batch,{type:"error",step:hJ(e)})}static not(e){return new wt(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)gJ(e,r);return new wt(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)gJ(e,r);return new wt(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new wt(e,{type:"is_autocommit"})}}function hJ(e){if(e._index===void 0)throw new vi("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function gJ(e,t){if(t._batch!==e)throw new vi("Cannot mix BatchCond objects for different Batch objects")}var hT=x(()=>{Nt();hp();Mb();$n()});function yJ(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class uu{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,jb)}queryRow(e){return this.#e(e,!0,qb)}queryValue(e){return this.#e(e,!0,Ub)}run(e){return this.#e(e,!1,Ma)}#e(e,t,r){let i=Fb(this._sqlOwner(),e,t);return this._execute(i).then((n)=>r(n,this.intMode))}batch(e=!1){return new Zb(this,e)}describe(e){let t=gp(this._sqlOwner(),e);return this._describe(t).then(yJ)}sequence(e){let t=gp(this._sqlOwner(),e);return this._sequence(t)}intMode}var Hb=x(()=>{hT();hp();lu();Mb()});class bp{}var Y0e=1000,X0e=10,gT;var bJ=x(()=>{Nt();gT=class gT extends bp{#e;#t;#r;#n;#i;#o;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new vs,this.#i=new vs,this.#o=void 0,this.#a=!1}async next(){for(;;){if(this.#o!==void 0)throw new zt("Cursor is closed",this.#o);while(!this.#a&&this.#i.length<X0e)this.#i.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#i.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:Y0e}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#o!==void 0)return;this.#o=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new at("Cursor was manually closed"))}get closed(){return this.#o!==void 0}}});var xp;var yT=x(()=>{Nt();Hb();bJ();xp=class xp extends uu{#e;#t;#r;#n;#i;#o;static open(e){let t=e._streamIdAlloc.alloc(),r=new xp(e,t),i=()=>{return},n=(s)=>r.#l(s),o={type:"open_stream",streamId:t};return e._sendRequest(o,{responseCallback:i,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new vs,this.#n=void 0,this.#i=!1,this.#o=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 kr("Cursor not associated with the stream attempted to execute a request");return new Promise((r,i)=>{if(this.#o!==void 0)i(new zt("Stream is closed",this.#o));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})})}_cursorClosed(e){if(e!==this.#n)throw new kr("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#o!==void 0)e.errorCallback(new zt("Stream is closed",this.#o));else if(this.#i)e.errorCallback(new zt("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.#i){this.#l(new at("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:i}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let i=this.#e._cursorIdAlloc.alloc(),n=new gT(this.#e,this,i),o={type:"open_cursor",streamId:this.#t,cursorId:i,batch:t},s=()=>{return},a=(c)=>n._setClosed(c);this.#e._sendRequest(o,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#o!==void 0)return;if(this.#o=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),i=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:i})}close(){this.#l(new at("Stream was manually closed"))}closeGracefully(){this.#i=!0,this.#c()}get closed(){return this.#o!==void 0||this.#i}}});function Sp(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,xJ),e.arrayObjects("named_args",t.namedArgs,eve),e.boolean("want_rows",t.wantRows)}function eve(e,t){e.string("name",t.name),e.object("value",t.value,xJ)}function du(e,t){e.arrayObjects("steps",t.steps,tve)}function tve(e,t){if(t.condition!==void 0)e.object("condition",t.condition,bT);e.object("stmt",t.stmt,Sp)}function bT(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,bT);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,bT);else if(t.type==="is_autocommit");else throw nt(t,"Impossible type of BatchCond")}function xJ(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",Xl.fromUint8Array(t));else if(t===void 0);else throw nt(t,"Impossible type of Value")}var xT=x(()=>{Nb();$n()});function SJ(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,rve);else throw nt(t,"Impossible type of ClientMsg")}function rve(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,Sp);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,du);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,du);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 nt(t,"Impossible type of Request")}var wJ=x(()=>{xT();$n()});function wp(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,_J);for(let r of t.namedArgs)e.message(4,r,nve);e.bool(5,t.wantRows)}function nve(e,t){e.string(1,t.name),e.message(2,t.value,_J)}function fu(e,t){for(let r of t.steps)e.message(1,r,ive)}function ive(e,t){if(t.condition!==void 0)e.message(1,t.condition,ST);e.message(2,t.stmt,wp)}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,vJ);else if(t.type==="or")e.message(5,t.conds,vJ);else if(t.type==="is_autocommit")e.message(6,void 0,kJ);else throw nt(t,"Impossible type of BatchCond")}function vJ(e,t){for(let r of t)e.message(1,r,ST)}function _J(e,t){if(t===null)e.message(1,void 0,kJ);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 nt(t,"Impossible type of Value")}function kJ(e,t){}var wT=x(()=>{$n()});function EJ(e,t){if(t.type==="hello")e.message(1,t,ove);else if(t.type==="request")e.message(2,t,sve);else throw nt(t,"Impossible type of ClientMsg")}function ove(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function sve(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,ave);else if(r.type==="close_stream")e.message(3,r,cve);else if(r.type==="execute")e.message(4,r,lve);else if(r.type==="batch")e.message(5,r,uve);else if(r.type==="open_cursor")e.message(6,r,dve);else if(r.type==="close_cursor")e.message(7,r,fve);else if(r.type==="fetch_cursor")e.message(8,r,pve);else if(r.type==="sequence")e.message(9,r,mve);else if(r.type==="describe")e.message(10,r,hve);else if(r.type==="store_sql")e.message(11,r,gve);else if(r.type==="close_sql")e.message(12,r,yve);else if(r.type==="get_autocommit")e.message(13,r,bve);else throw nt(r,"Impossible type of Request")}function ave(e,t){e.int32(1,t.streamId)}function cve(e,t){e.int32(1,t.streamId)}function lve(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,wp)}function uve(e,t){e.int32(1,t.streamId),e.message(2,t.batch,fu)}function dve(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,fu)}function fve(e,t){e.int32(1,t.cursorId)}function pve(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function mve(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 hve(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 gve(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function yve(e,t){e.int32(1,t.sqlId)}function bve(e,t){e.int32(1,t.streamId)}var IJ=x(()=>{wT();$n()});function _s(e){let t=Gr(e.message),r=pn(e.code);return{message:t,code:r}}function vp(e){let t=Vn(e.cols,AJ),r=up(e.rows).map((s)=>Vn(s,$J)),i=no(e.affected_row_count),n=pn(e.last_insert_rowid),o=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:i,lastInsertRowid:o}}function AJ(e){let t=pn(e.name),r=pn(e.decltype);return{name:t,decltype:r}}function Jb(e){let t=new Map;up(e.step_results).forEach((i,n)=>{if(i!==null)t.set(n,vp(Ut(i)))});let r=new Map;return up(e.step_errors).forEach((i,n)=>{if(i!==null)r.set(n,_s(Ut(i)))}),{stepResults:t,stepErrors:r}}function Kb(e){let t=Gr(e.type);if(t==="step_begin"){let r=no(e.step),i=Vn(e.cols,AJ);return{type:"step_begin",step:r,cols:i}}else if(t==="step_end"){let r=no(e.affected_row_count),i=pn(e.last_insert_rowid),n=i!==void 0?BigInt(i):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=no(e.step),i=_s(Ut(e.error));return{type:"step_error",step:r,error:i}}else if(t==="row")return{type:"row",row:Vn(e.row,$J)};else if(t==="error")return{type:"error",error:_s(Ut(e.error))};else throw new qe("Unexpected type of CursorEntry")}function Vb(e){let t=Vn(e.params,xve),r=Vn(e.cols,Sve),i=xs(e.is_explain),n=xs(e.is_readonly);return{params:t,cols:r,isExplain:i,isReadonly:n}}function xve(e){return{name:pn(e.name)}}function Sve(e){let t=Gr(e.name),r=pn(e.decltype);return{name:t,decltype:r}}function $J(e){let t=Gr(e.type);if(t==="null")return null;else if(t==="integer"){let r=Gr(e.value);return BigInt(r)}else if(t==="float")return no(e.value);else if(t==="text")return Gr(e.value);else if(t==="blob")return Xl.toUint8Array(Gr(e.base64));else throw new qe("Unexpected type of Value")}var Wb=x(()=>{Nb();Nt();au()});function CJ(e){let t=Gr(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:_s(Ut(e.error))};else if(t==="response_ok"){let r=no(e.request_id),i=wve(Ut(e.response));return{type:"response_ok",requestId:r,response:i}}else if(t==="response_error"){let r=no(e.request_id),i=_s(Ut(e.error));return{type:"response_error",requestId:r,error:i}}else throw new qe("Unexpected type of ServerMsg")}function wve(e){let t=Gr(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:vp(Ut(e.result))};else if(t==="batch")return{type:"batch",result:Jb(Ut(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=Vn(e.entries,Kb),i=xs(e.done);return{type:"fetch_cursor",entries:r,done:i}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:Vb(Ut(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:xs(e.is_autocommit)};else throw new qe("Unexpected type of Response")}var TJ=x(()=>{Nt();au();Wb()});var Cn,ks,OJ,RJ,pu,vve,_ve,Gb,kve,Eve,Ive,mu,Ave,$ve,Cve;var Qb=x(()=>{Cn={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},ks={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(OJ))},2(e,t){t.rows.push(e.message(RJ))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},OJ={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},RJ={default(){return[]},1(e,t){t.push(e.message(Cve))}},pu={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,i]=e.message(vve);t.stepResults.set(r,i)},2(e,t){let[r,i]=e.message(_ve);t.stepErrors.set(r,i)}},vve={default(){return[0,ks.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(ks)}},_ve={default(){return[0,Cn.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(Cn)}},Gb={default(){return{type:"none"}},1(e){return e.message(kve)},2(e){return e.message(Eve)},3(e){return e.message(Ive)},4(e){return{type:"row",row:e.message(RJ)}},5(e){return{type:"error",error:e.message(Cn)}}},kve={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(OJ))}},Eve={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},Ive={default(){return{type:"step_error",step:0,error:Cn.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(Cn)}},mu={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(Ave))},2(e,t){t.cols.push(e.message($ve))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},Ave={default(){return{name:void 0}},1(e,t){t.name=e.string()}},$ve={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},Cve={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 PJ,Tve,Ove,Rve,Pve,zve,Nve,Dve,Lve;var zJ=x(()=>{Qb();PJ={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(Tve)},3(e){return e.message(Rve)},4(e){return e.message(Ove)}},Tve={default(){return{type:"hello_error",error:Cn.default()}},1(e,t){t.error=e.message(Cn)}},Ove={default(){return{type:"response_error",requestId:0,error:Cn.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(Cn)}},Rve={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(Pve)},5(e,t){t.response=e.message(zve)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(Nve)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(Dve)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(Lve)}},Pve={default(){return{type:"execute",result:ks.default()}},1(e,t){t.result=e.message(ks)}},zve={default(){return{type:"batch",result:pu.default()}},1(e,t){t.result=e.message(pu)}},Nve={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(Gb))},2(e,t){t.done=e.bool()}},Dve={default(){return{type:"describe",result:mu.default()}},1(e,t){t.result=e.message(mu)}},Lve={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var NJ,vT,Yb;var Xb=x(()=>{uT();Nt();dT();hp();lu();$n();yT();wJ();IJ();TJ();zJ();NJ=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),vT=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);Yb=class Yb extends iu{#e;#t;#r;#n;#i;#o;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#i=!1,this.#o=void 0,this.#a=!1,this.#s=new Map,this.#c=new ws,this._streamIdAlloc=new ws,this._cursorIdAlloc=new ws,this.#l=new ws,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#f()),this.#e.addEventListener("close",(r)=>this.#g(r)),this.#e.addEventListener("error",(r)=>this.#p(r)),this.#e.addEventListener("message",(r)=>this.#y(r)),this.#d({type:"hello",jwt:t})}#d(e){if(this.#n!==void 0)throw new kr("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})}}#f(){let e=this.#e.protocol;if(e===void 0){this.#u(new at("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.#o={version:1,encoding:"json"};else if(this.#o=vT.get(e),this.#o===void 0){this.#u(new qe(`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.#o.encoding;if(t==="json"){let r=dp(e,SJ);this.#e.send(r)}else if(t==="protobuf"){let r=mp(e,EJ);this.#e.send(r)}else throw nt(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.#o.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#o.version)})}_ensureVersion(e,t){if(this.#o===void 0||!this.#a)throw new Kn(`${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.#o.version<e)throw new Kn(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#o.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new zt("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})}#p(e){let r=e.message??"WebSocket was closed due to an error";this.#u(new ou(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new ou(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.#o.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new qe("Received non-text message from server with JSON encoding"));return}t=Ua(JSON.parse(e.data),CJ)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new qe("Received non-binary message from server with Protobuf encoding"));return}t=Ss(new Uint8Array(e.data),PJ)}else throw nt(r,"Impossible encoding");this.#h(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#h(e){if(e.type==="none")throw new qe("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#i)throw new qe("Received a duplicated hello response");if(this.#i=!0,e.type==="hello_error")throw io(e.error);return}else if(!this.#i)throw new qe("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 qe("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new qe("Received unexpected type of response");r.responseCallback(e.response)}catch(i){throw r.errorCallback(i),i}}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 qe("Received unexpected error response");this.#c.free(t),r.errorCallback(io(e.error))}else throw nt(e,"Impossible ServerMsg type")}openStream(){return xp.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new Za(this,t),i=()=>{return},n=(s)=>r._setClosed(s),o={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(o,{responseCallback:i,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),i={type:"close_sql",sqlId:e};this._sendRequest(i,{responseCallback:t,errorCallback:r})}close(){this.#u(new at("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var Ha;var DJ=x(()=>{if(typeof queueMicrotask<"u")Ha=queueMicrotask;else{let e=Promise.resolve();Ha=(t)=>{e.then(t)}}});class _T{#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 i=new Uint8Array(new ArrayBuffer(r));i.set(this.#e.slice(this.#t,this.#r),0),this.#e=i}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function LJ(e){let t=pn(e.baton),r=pn(e.base_url),i=Vn(e.results,Bve);return{baton:t,baseUrl:r,results:i}}function Bve(e){let t=Gr(e.type);if(t==="ok")return{type:"ok",response:jve(Ut(e.response))};else if(t==="error")return{type:"error",error:_s(Ut(e.error))};else throw new qe("Unexpected type of StreamResult")}function jve(e){let t=Gr(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:vp(Ut(e.result))};else if(t==="batch")return{type:"batch",result:Jb(Ut(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:Vb(Ut(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:xs(e.is_autocommit)};else throw new qe("Unexpected type of StreamResponse")}function BJ(e){let t=pn(e.baton),r=pn(e.base_url);return{baton:t,baseUrl:r}}var kT=x(()=>{Nt();au();Wb()});var jJ,qve,Uve,Fve,Mve,Zve,Hve,qJ;var ET=x(()=>{Qb();jJ={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(qve))}},qve={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(Uve)}},2(e){return{type:"error",error:e.message(Cn)}}},Uve={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(Fve)},3(e){return e.message(Mve)},4(e){return{type:"sequence"}},5(e){return e.message(Zve)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(Hve)}},Fve={default(){return{type:"execute",result:ks.default()}},1(e,t){t.result=e.message(ks)}},Mve={default(){return{type:"batch",result:pu.default()}},1(e,t){t.result=e.message(pu)}},Zve={default(){return{type:"describe",result:mu.default()}},1(e,t){t.result=e.message(mu)}},Hve={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},qJ={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var IT;var UJ=x(()=>{au();cT();Nt();$n();kT();ET();Wb();Qb();IT=class IT extends bp{#e;#t;#r;#n;#i;#o;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new _T(16384),this.#i=void 0,this.#o=!1}async open(e){if(e.body===null)throw new qe("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(BJ,qJ);if(t===void 0)throw new qe("Empty response to cursor request");return t}next(){return this.#a(Kb,Gb)}close(){this._setClosed(new at("Cursor was manually closed"))}_setClosed(e){if(this.#i!==void 0)return;if(this.#i=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#i!==void 0}async#a(e,t){for(;;){if(this.#o)return;else if(this.#i!==void 0)throw new zt("Cursor is closed",this.#i);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let o=new TextDecoder().decode(n),s=JSON.parse(o);return Ua(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return Ss(n,t)}else throw nt(this.#t,"Impossible encoding");if(this.#r===void 0)throw new kr("Attempted to read from HTTP cursor before it was opened");let{value:r,done:i}=await this.#r.next();if(i&&this.#n.length===0)this.#o=!0;else if(i)throw new qe("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 i=e.slice(0,r);return this.#n.shift(r+1),i}#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 i=e.slice(r,r+t);return this.#n.shift(r+t),i}}});function FJ(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,Jve)}function Jve(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,Sp);else if(t.type==="batch")e.object("batch",t.batch,du);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 nt(t,"Impossible type of StreamRequest")}function MJ(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,du)}var AT=x(()=>{xT();$n()});function ZJ(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,Kve)}function Kve(e,t){if(t.type==="close")e.message(1,t,Vve);else if(t.type==="execute")e.message(2,t,Wve);else if(t.type==="batch")e.message(3,t,Gve);else if(t.type==="sequence")e.message(4,t,Qve);else if(t.type==="describe")e.message(5,t,Yve);else if(t.type==="store_sql")e.message(6,t,Xve);else if(t.type==="close_sql")e.message(7,t,e_e);else if(t.type==="get_autocommit")e.message(8,t,t_e);else throw nt(t,"Impossible type of StreamRequest")}function Vve(e,t){}function Wve(e,t){e.message(1,t.stmt,wp)}function Gve(e,t){e.message(1,t.batch,fu)}function Qve(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function Yve(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function Xve(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function e_e(e,t){e.int32(1,t.sqlId)}function t_e(e,t){}function HJ(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,fu)}var $T=x(()=>{wT();$n()});function r_e(e,t){if(t.results.length!==e.length)throw new qe("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let i=t.results[r],n=e[r];if(i.type==="ok"){if(i.response.type!==n.request.type)throw new qe("Received unexpected type of response");n.responseCallback(i.response)}else if(i.type==="error")n.errorCallback(io(i.error));else if(i.type==="none")throw new qe("Received unrecognized type of StreamResult");else throw nt(i,"Received impossible type of StreamResult")}}async function n_e(e,t){if(t==="json"){let r=await e.json();return Ua(r,LJ)}if(t==="protobuf"){let r=await e.arrayBuffer();return Ss(new Uint8Array(r),jJ)}throw await e.body?.cancel(),nt(t,"Impossible encoding")}async function i_e(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let i=await e.json();if("message"in i)return io(i);return new qa(r,e.status)}if(t==="text/plain"){let i=(await e.text()).trim();if(i!=="")r+=`: ${i}`;return new qa(r,e.status)}return await e.body?.cancel(),new qa(r,e.status)}var ex;var CT=x(()=>{Nt();uT();dT();DJ();hp();lu();Hb();$n();UJ();AT();$T();AT();$T();kT();ET();ex=class ex extends uu{#e;#t;#r;#n;#i;#o;#a;#s;#c;#l;#d;#f;#m;constructor(e,t,r,i,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=i,this.#i=n,this.#o=void 0,this.#a=new vs,this.#s=!1,this.#l=!1,this.#d=!1,this.#f=void 0,this.#m=new ws}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let t=this.#m.alloc();return this.#p({type:"store_sql",sqlId:t,sql:e}).then(()=>{return},(r)=>this._setClosed(r)),new Za(this,t)}_closeSql(e){if(this.#f!==void 0)return;this.#p({type:"close_sql",sqlId:e}).then(()=>this.#m.free(e),(t)=>this._setClosed(t))}_execute(e){return this.#p({type:"execute",stmt:e}).then((t)=>t.result)}_batch(e){return this.#p({type:"batch",batch:e}).then((t)=>t.result)}_describe(e){return this.#p({type:"describe",sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#p({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#p({type:"get_autocommit"}).then((e)=>e.isAutocommit)}#p(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 kr("Cursor was closed, but it was not associated with the stream");this.#c=void 0,Ha(()=>this.#u())}close(){this._setClosed(new at("Stream was manually closed"))}closeGracefully(){this.#l=!0,Ha(()=>this.#u())}get closed(){return this.#f!==void 0||this.#l}_setClosed(e){if(this.#f!==void 0)return;if(this.#f=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.#o!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,Ha(()=>this.#u())}#g(e){if(this.#f!==void 0)throw new zt("Stream is closed",this.#f);else if(this.#l)throw new zt("Stream is closing",void 0);else this.#a.push(e),Ha(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new at("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 i=this.#a.first();if(i!==void 0&&i.type==="pipeline")r.push(i),this.#a.shift();else if(i===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.#h(e,t);else throw nt(t,"Impossible type of QueueEntry")}#y(e,t){this.#b(()=>this.#x(t,e),(r)=>n_e(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>r_e(t,r),(r)=>t.forEach((i)=>i.errorCallback(r)))}#h(e,t){let r=new IT(this,e.encoding);this.#c=r,this.#b(()=>this.#w(t,e),(i)=>r.open(i),(i)=>i.baton,(i)=>i.baseUrl,(i)=>t.cursorCallback(r),(i)=>t.errorCallback(i))}#b(e,t,r,i,n,o){let s;try{let a=e(),c=this.#n;s=c(a)}catch(a){s=Promise.reject(a)}this.#s=!0,s.then((a)=>{if(!a.ok)return i_e(a).then((c)=>{throw c});return t(a)}).then((a)=>{this.#o=r(a),this.#t=i(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),o(a)}).finally(()=>{this.#s=!1,this.#u()})}#x(e,t){return this.#S(new URL(t.pipelinePath,this.#t),{baton:this.#o,requests:e.map((r)=>r.request)},t.encoding,FJ,ZJ)}#w(e,t){if(t.cursorPath===void 0)throw new Kn(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#S(new URL(t.cursorPath,this.#t),{baton:this.#o,batch:e.batch},t.encoding,MJ,HJ)}#S(e,t,r,i,n){let o,s;if(r==="json")o=dp(t,i),s="application/json";else if(r==="protobuf")o=mp(t,n),s="application/x-protobuf";else throw nt(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.#i!==void 0)a.set("x-turso-encryption-key",this.#i);return new Request(e.toString(),{method:"POST",headers:a,body:o})}}});async function s_e(e,t){let r=e;for(let i of o_e){let n=new URL(i.versionPath,t),o=new Request(n.toString(),{method:"GET"}),s=await r(o);if(await s.arrayBuffer(),s.ok)return i}return TT}var o_e,TT,tx;var OT=x(()=>{Nt();CT();o_e=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],TT={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};tx=class tx extends iu{#e;#t;#r;#n;#i;#o;_endpointPromise;_endpoint;constructor(e,t,r,i,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=i,this.#i=void 0,this.#o=new Set,n==3)this._endpointPromise=s_e(this.#r,this.#e),this._endpointPromise.then((o)=>this._endpoint=o,(o)=>this.#a(o));else this._endpointPromise=Promise.resolve(TT),this._endpointPromise.then((o)=>this._endpoint=o,(o)=>this.#a(o))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=TT.version)return;else if(this._endpoint===void 0)throw new Kn(`${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 Kn(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#i!==void 0)throw new zt("Client is closed",this.#i);let e=new ex(this,this.#e,this.#t,this.#r,this.#n);return this.#o.add(e),e}_streamClosed(e){this.#o.delete(e)}close(){this.#a(new at("Client was manually closed"))}get closed(){return this.#i!==void 0}#a(e){if(this.#i!==void 0)return;this.#i=e;for(let t of Array.from(this.#o))t._setClosed(new zt("Client was closed",e))}}});var JJ=x(()=>{Nt()});function RT(e,t,r=2){if(typeof bs>"u")throw new lp("WebSockets are not supported in this environment");var i=void 0;if(r==3)i=Array.from(vT.keys());else i=Array.from(NJ.keys());let n=new bs(e,i);return new Yb(n,t)}function PT(e,t,r,i,n=2){return new tx(e instanceof URL?e:new URL(e),t,r,i,n)}var rx=x(()=>{aT();Xb();Nt();OT();Xb();aT();hT();JJ();lu();Mb();Hb();OT();CT();Xb();yT();Nt()});class _p{#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 Me("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(oo),i;if(this.#r===void 0){this._getSqlCache().apply(r);let o=t.batch(this.#t>=3),s=o.step(),a=s.run(gs(this.#e)),c=s;i=r.map((l)=>{let u=o.step().condition(wt.ok(c));if(this.#t>=3)u.condition(wt.not(wt.isAutocommit(o)));let d=u.query(l);return d.catch(()=>{return}),c=u,d}),this.#r=o.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(l){throw this.close(),l}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let o=t.batch(this.#t>=3),s=void 0;i=r.map((a)=>{let c=o.step();if(s!==void 0)c.condition(wt.ok(s));if(this.#t>=3)c.condition(wt.not(wt.isAutocommit(o)));let l=c.query(a);return l.catch(()=>{return}),s=c,l}),await o.execute()}let n=[];for(let o=0;o<i.length;o++)try{let s=await i[o];if(s===void 0)throw new fr("Statement in a transaction was not executed, probably because the transaction has been rolled back",o,"TRANSACTION_CLOSED");n.push(gu(s))}catch(s){if(s instanceof fr)throw s;let a=yt(s);if(a instanceof Me)throw new fr(a.message,o,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw yt(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Me("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(gs(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 yt(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 yt(r)});e.closeGracefully(),await t}catch(e){throw yt(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Me("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 yt(r)});e.closeGracefully(),await t}catch(e){throw yt(e)}finally{this.close()}}}async function hu(e,t,r,i,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let o=r.step(),s=o.run(gs(e)),a=o,c=i.map((m)=>{let y=r.step().condition(wt.ok(a));if(t>=3)y.condition(wt.not(wt.isAutocommit(r)));let g=y.query(m);return a=y,g}),l=r.step().condition(wt.ok(a));if(t>=3)l.condition(wt.not(wt.isAutocommit(r)));let u=l.run("COMMIT");if(r.step().condition(wt.not(wt.ok(l))).run("ROLLBACK").catch((m)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let p=[];await s;for(let m=0;m<c.length;m++)try{let y=await c[m];if(y===void 0)throw new fr("Statement in a batch was not executed, probably because the transaction has been rolled back",m,"TRANSACTION_CLOSED");p.push(gu(y))}catch(y){if(y instanceof fr)throw y;let g=yt(y);if(g instanceof Me)throw new fr(g.message,m,g.code,g.extendedCode,g.rawCode,g.cause instanceof Error?g.cause:void 0);throw g}return await u,p}function oo(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 i=new yp(t);if(r)if(Array.isArray(r))i.bindIndexes(r);else for(let[n,o]of Object.entries(r))i.bindName(n,o);return i}function gu(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),i=e.rows,n=e.affectedRowCount,o=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new eu(t,r,i,n,o)}function yt(e){if(e instanceof at){let t=KJ(e);return new Me(e.message,t,void 0,void 0,e)}return e}function KJ(e){if(e instanceof cp&&e.code!==void 0)return e.code;else if(e instanceof qe)return"HRANA_PROTO_ERROR";else if(e instanceof zt)return e.cause instanceof at?KJ(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof ou)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof qa)return"SERVER_ERROR";else if(e instanceof Kn)return"PROTOCOL_VERSION_ERROR";else if(e instanceof kr)return"INTERNAL_ERROR";else return"UNKNOWN"}var NT=x(()=>{rx();Jn();tu()});class yu{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new VJ,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 i=r.sql;if(i.length>=5000)continue;let n=this.#t.get(i);if(n===void 0){while(this.#t.size+1>this.capacity){let[o,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(o)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(i),this.#t.set(i,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class VJ{#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 DT=te(function(HJe,GJ){function a_e(e){var t=0,r=[];function i(){if(t--,t<e)n()}function n(){var c=r.shift();if(a.queue=r.length,c)s(c.fn).then(c.resolve).catch(c.reject)}function o(c){return new Promise(function(l,u){r.push({fn:c,resolve:l,reject:u}),a.queue=r.length})}function s(c){t++;try{return Promise.resolve(c()).then(function(l){return i(),l},function(l){throw i(),l})}catch(l){return i(),Promise.reject(l)}}var a=function(c){if(t>=e)return o(c);else return s(c)};return a}function c_e(e,t){var r=!1,i=this;return Promise.all(e.map(function(){var n=arguments;return i(function(){if(!r)return t.apply(void 0,n).catch(function(o){throw r=!0,o})})}))}function WJ(e){return e.queue=0,e.map=c_e,e}GJ.exports=function(e){if(e)return WJ(a_e(e));else return WJ(function(t){return t()})}});function XJ(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Me(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${xi}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Me("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Me('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Me('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=np(e.scheme,e.authority,e.path),r;try{r=RT(t,e.authToken)}catch(i){if(i instanceof lp){let n=e.scheme==="wss"?"https":"http",o=np(n,e.authority,e.path);throw new Me(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(o)}). For more information, please read ${xi}`,"WEBSOCKETS_NOT_SUPPORTED")}throw yt(i)}return new e9(r,t,e.authToken,e.intMode,e.concurrency)}class e9{#e;#t;#r;#n;#i;closed;protocol;#o;#a;constructor(e,t,r,i,n){this.#e=t,this.#t=r,this.#r=i,this.#n=this.#c(e),this.#i=void 0,this.closed=!1,this.protocol="ws",this.#a=YJ.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 i=await this.#s();try{let n=oo(r);i.conn.sqlCache.apply([n]);let o=i.stream.query(n);i.stream.closeGracefully();let s=await o;return gu(s)}catch(n){throw yt(n)}finally{this._closeStream(i)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((l)=>{if(Array.isArray(l))return{sql:l[0],args:l[1]||[]};return l}).map(oo),o=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(o>=3);return await hu(t,o,s,n)}catch(i){throw yt(i)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(oo),i=await t.conn.client.getVersion(),n=t.stream.batch(i>=3);return await hu("deferred",i,n,r,!0)}catch(r){throw yt(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 t9(this,t,e,r)}catch(r){throw this._closeStream(t),yt(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 yt(r)}finally{this._closeStream(t)}})}sync(){throw new Me("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Me("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>l_e&&this.#i===void 0){let i=this.#c();this.#i=i,i.client.getVersion().then((n)=>{if(this.#n!==i){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=i,this.#i=void 0},(n)=>{this.#i=void 0})}if(this.#n.client.closed)try{if(this.#i!==void 0)this.#n=this.#i;else this.#n=this.#c()}catch(i){throw yt(i)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=QJ}let i=r.client.openStream();i.intMode=this.#r;let n={conn:r,stream:i};return r.streamStates.add(n),n}catch(i){throw yt(i)}}#c(e){try{return e??=RT(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new yu(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw yt(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.#i){try{this.#i.client.close()}catch{}this.#i=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=QJ;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.#i){try{this.#i.client.close()}catch{}this.#i=void 0}this.closed=!0}}var YJ,l_e=60000,QJ=100,t9;var r9=x(()=>{rx();Jn();sp();NT();Rb();tu();YJ=ic(DT(),1);Jn();t9=class t9 extends _p{#e;#t;constructor(e,t,r,i){super(r,i);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 i9(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Me(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${xi}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Me("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Me('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Me('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=np(e.scheme,e.authority,e.path);return new s9(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class s9{#e;protocol;#t;#r;#n;#i;#o;#a;#s;constructor(e,t,r,i,n,o){this.#t=e,this.#o=t,this.#r=r,this.#n=i,this.#i=n,this.#a=o,this.#e=PT(this.#t,this.#o,this.#n,o),this.#e.intMode=this.#r,this.protocol="http",this.#s=n9.default(this.#i)}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 i=oo(r),n,o=this.#e.openStream();try{n=o.query(i)}finally{o.closeGracefully()}let s=await n;return gu(s)}catch(i){throw yt(i)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let i=e.map((c)=>{if(Array.isArray(c))return{sql:c[0],args:c[1]||[]};return c}).map(oo),n=await this.#e.getVersion(),o,s=this.#e.openStream();try{new yu(s,o9).apply(i);let l=s.batch(!1);o=hu(t,n,l,i)}finally{s.closeGracefully()}return await o}catch(r){throw yt(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(oo),r=await this.#e.getVersion(),i,n=this.#e.openStream();try{let s=n.batch(!1);i=hu("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await i}catch(t){throw yt(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new a9(this.#e.openStream(),e,t)}catch(t){throw yt(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 yt(t)}})}sync(){throw new Me("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=PT(this.#t,this.#o,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var n9,o9=30,a9;var c9=x(()=>{rx();Jn();sp();NT();Rb();tu();n9=ic(DT(),1);Jn();a9=class a9 extends _p{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new yu(e,o9)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function Ja(e){return u_e(op(e,!0))}function u_e(e){if(e.scheme==="wss"||e.scheme==="ws")return XJ(e);else if(e.scheme==="https"||e.scheme==="http")return i9(e);else return nJ(e)}var LT=x(()=>{sp();cJ();r9();c9();Jn()});function ce(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,K))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(K in r&&r[K]===t[K])return!0;r=Object.getPrototypeOf(r)}return!1}var K;var De=x(()=>{K=Symbol.for("drizzle:entityKind")});var it;var Wn=x(()=>{De();it=class it{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[K]="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 kp;var nx=x(()=>{De();kp=class kp{static[K]="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 Er;var bu=x(()=>{Er=Symbol.for("drizzle:Name")});var BT,l9;var u9=x(()=>{De();bu();BT=class BT{static[K]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:i,foreignColumns:n}=e();return{name:r,columns:i,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 l9(e,this)}};l9=class l9{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[K]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),i=t.map((s)=>s.name),n=r.map((s)=>s.name),o=[this.table[Er],...i,r[0].table[Er],...n];return e??`${o.join("_")}_fk`}}});function ix(e,...t){return e(...t)}var jT=()=>{};function qT(e,t){return`${e[Er]}_${t.join("_")}_unique`}var d9,d_e,f9;var p9=x(()=>{De();bu();d9=class d9{constructor(e,t){this.name=t,this.columns=e}static[K]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new f9(e,this.columns,this.nullsNotDistinctConfig,this.name)}};d_e=class d_e{static[K]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new d9(e,this.name)}};f9=class f9{constructor(e,t,r,i){this.table=e,this.columns=t,this.name=i??qT(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[K]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function m9(e,t,r){for(let i=t;i<e.length;i++){let n=e[i];if(n==="\\"){i++;continue}if(n==='"')return[e.slice(t,i).replace(/\\/g,""),i+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,i).replace(/\\/g,""),i]}return[e.slice(t).replace(/\\/g,""),e.length]}function h9(e,t=0){let r=[],i=t,n=!1;while(i<e.length){let o=e[i];if(o===","){if(n||i===t)r.push("");n=!0,i++;continue}if(n=!1,o==="\\"){i+=2;continue}if(o==='"'){let[c,l]=m9(e,i+1,!0);r.push(c),i=l;continue}if(o==="}")return[r,i+1];if(o==="{"){let[c,l]=h9(e,i+1);r.push(c),i=l;continue}let[s,a]=m9(e,i,!1);r.push(s),i=a}return[r,i]}function g9(e){let[t]=h9(e,1);return t}function UT(e){return`{${e.map((t)=>{if(Array.isArray(t))return UT(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var y9=()=>{};var Ep,xu,b9,f_e,x9,FT;var S9=x(()=>{nx();Wn();De();u9();jT();p9();y9();Ep=class Ep extends kp{foreignKeyConfigs=[];static[K]="PgColumnBuilder";array(e){return new x9(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:i})=>ix((n,o)=>{let s=new BT(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(o.onUpdate)s.onUpdate(o.onUpdate);if(o.onDelete)s.onDelete(o.onDelete);return s.build(t)},r,i))}buildExtraConfigColumn(e){return new b9(e,this.config)}};xu=class xu extends it{constructor(e,t){if(!t.uniqueName)t.uniqueName=qT(e,[t.name]);super(e,t);this.table=e}static[K]="PgColumn"};b9=class b9 extends xu{static[K]="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}};f_e=class f_e{static[K]="IndexedColumn";constructor(e,t,r,i){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=i}name;keyAsName;type;indexConfig};x9=class x9 extends Ep{static[K]="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 FT(e,this.config,t)}};FT=class FT extends xu{constructor(e,t,r,i){super(e,t);this.baseColumn=r,this.range=i,this.size=t.size}size;static[K]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=g9(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((i)=>i===null?null:ce(this.baseColumn,FT)?this.baseColumn.mapToDriverValue(i,!0):this.baseColumn.mapToDriverValue(i));if(t)return r;return UT(r)}}});function _9(e){return!!e&&typeof e==="function"&&w9 in e&&e[w9]===!0}var p_e,v9,w9,m_e,k9;var E9=x(()=>{De();S9();p_e=class p_e extends Ep{static[K]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new v9(e,this.config)}};v9=class v9 extends xu{static[K]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};w9=Symbol.for("drizzle:isPgEnum");m_e=class m_e extends Ep{static[K]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new k9(e,this.config)}};k9=class k9 extends xu{static[K]="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 vt,Ip;var Gn=x(()=>{De();vt=class vt{static[K]="Subquery";constructor(e,t,r,i=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:i,usedTables:n}}};Ip=class Ip extends vt{static[K]="WithSubquery"}});var I9="0.45.2";var A9=()=>{};var MT,ZT,$9;var C9=x(()=>{jT();A9();$9={startActiveSpan(e,t){if(!MT)return t();if(!ZT)ZT=MT.trace.getTracer("drizzle-orm",I9);return ix((r,i)=>i.startActiveSpan(e,(n)=>{try{return t(n)}catch(o){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:o instanceof Error?o.message:"Unknown error"}),o}finally{n.end()}}),MT,ZT)}}});var _t;var so=x(()=>{_t=Symbol.for("drizzle:ViewBaseConfig")});function Es(e){return e[Er]}function Ka(e){return`${e[ox]??"public"}.${e[Er]}`}var ox,sx,T9,HT,JT,Ap,O9,h_e,we;var Ir=x(()=>{De();bu();ox=Symbol.for("drizzle:Schema"),sx=Symbol.for("drizzle:Columns"),T9=Symbol.for("drizzle:ExtraConfigColumns"),HT=Symbol.for("drizzle:OriginalName"),JT=Symbol.for("drizzle:BaseName"),Ap=Symbol.for("drizzle:IsAlias"),O9=Symbol.for("drizzle:ExtraConfigBuilder"),h_e=Symbol.for("drizzle:IsDrizzleTable");we=class we{static[K]="Table";static Symbol={Name:Er,Schema:ox,OriginalName:HT,Columns:sx,ExtraConfigColumns:T9,BaseName:JT,IsAlias:Ap,ExtraConfigBuilder:O9};[Er];[HT];[ox];[sx];[T9];[JT];[Ap]=!1;[h_e]=!0;[O9]=void 0;constructor(e,t,r){this[Er]=this[HT]=e,this[ox]=t,this[JT]=r}}});function KT(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function y_e(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 R9(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function q(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Vt(e[0]));for(let[i,n]of t.entries())r.push(n,new Vt(e[i+1]));return new $e(r)}function $p(e,t){return e.map((r)=>{if(ce(r,Is)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(ce(r,mn)&&ce(r.value,Is)){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 g_e,Vt,$e,ax,P9,z9,rKe,mn,Is,b_e,Tn;var mr=x(()=>{De();E9();Gn();C9();so();Wn();Ir();g_e=class g_e{static[K]="FakePrimitiveParam"};Vt=class Vt{static[K]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new $e([this])}};$e=class $e{constructor(e){this.queryChunks=e;for(let t of e)if(ce(t,we)){let r=t[we.Symbol.Schema];this.usedTables.push(r===void 0?t[we.Symbol.Name]:r+"."+t[we.Symbol.Name])}}static[K]="SQL";decoder=P9;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return $9.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:i,escapeName:n,escapeParam:o,prepareTyping:s,inlineParams:a,paramStartIndex:c}=r;return y_e(e.map((l)=>{if(ce(l,Vt))return{sql:l.value.join(""),params:[]};if(ce(l,ax))return{sql:n(l.value),params:[]};if(l===void 0)return{sql:"",params:[]};if(Array.isArray(l)){let u=[new Vt("(")];for(let[d,p]of l.entries())if(u.push(p),d<l.length-1)u.push(new Vt(", "));return u.push(new Vt(")")),this.buildQueryFromSourceParams(u,r)}if(ce(l,$e))return this.buildQueryFromSourceParams(l.queryChunks,{...r,inlineParams:a||l.shouldInlineParams});if(ce(l,we)){let u=l[we.Symbol.Schema],d=l[we.Symbol.Name];return{sql:u===void 0||l[Ap]?n(d):n(u)+"."+n(d),params:[]}}if(ce(l,it)){let u=i.getColumnCasing(l);if(t.invokeSource==="indexes")return{sql:n(u),params:[]};let d=l.table[we.Symbol.Schema];return{sql:l.table[Ap]||d===void 0?n(l.table[we.Symbol.Name])+"."+n(u):n(d)+"."+n(l.table[we.Symbol.Name])+"."+n(u),params:[]}}if(ce(l,Tn)){let u=l[_t].schema,d=l[_t].name;return{sql:u===void 0||l[_t].isAlias?n(d):n(u)+"."+n(d),params:[]}}if(ce(l,mn)){if(ce(l.value,Is))return{sql:o(c.value++,l),params:[l],typings:["none"]};let u=l.value===null?null:l.encoder.mapToDriverValue(l.value);if(ce(u,$e))return this.buildQueryFromSourceParams([u],r);if(a)return{sql:this.mapInlineParam(u,r),params:[]};let d=["none"];if(s)d=[s(l.encoder)];return{sql:o(c.value++,u),params:[u],typings:d}}if(ce(l,Is))return{sql:o(c.value++,l),params:[l],typings:["none"]};if(ce(l,$e.Aliased)&&l.fieldAlias!==void 0)return{sql:n(l.fieldAlias),params:[]};if(ce(l,vt)){if(l._.isWith)return{sql:n(l._.alias),params:[]};return this.buildQueryFromSourceParams([new Vt("("),l._.sql,new Vt(") "),new ax(l._.alias)],r)}if(_9(l)){if(l.schema)return{sql:n(l.schema)+"."+n(l.enumName),params:[]};return{sql:n(l.enumName),params:[]}}if(KT(l)){if(l.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([l.getSQL()],r);return this.buildQueryFromSourceParams([new Vt("("),l.getSQL(),new Vt(")")],r)}if(a)return{sql:this.mapInlineParam(l,r),params:[]};return{sql:o(c.value++,l),params:[l],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 $e.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}};ax=class ax{constructor(e){this.value=e}static[K]="Name";brand;getSQL(){return new $e([this])}};P9={mapFromDriverValue:(e)=>e},z9={mapToDriverValue:(e)=>e},rKe={...P9,...z9};mn=class mn{constructor(e,t=z9){this.value=e,this.encoder=t}static[K]="Param";brand;getSQL(){return new $e([this])}};((e)=>{function t(){return new $e([])}e.empty=t;function r(c){return new $e(c)}e.fromList=r;function i(c){return new $e([new Vt(c)])}e.raw=i;function n(c,l){let u=[];for(let[d,p]of c.entries()){if(d>0&&l!==void 0)u.push(l);u.push(p)}return new $e(u)}e.join=n;function o(c){return new ax(c)}e.identifier=o;function s(c){return new Is(c)}e.placeholder=s;function a(c,l){return new mn(c,l)}e.param=a})(q||(q={}));((e)=>{class t{constructor(r,i){this.sql=r,this.fieldAlias=i}static[K]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})($e||($e={}));Is=class Is{constructor(e){this.name=e}static[K]="Placeholder";getSQL(){return new $e([this])}};b_e=Symbol.for("drizzle:IsDrizzleView");Tn=class Tn{static[K]="View";[_t];[b_e]=!0;constructor({name:e,schema:t,selectedFields:r,query:i}){this[_t]={name:e,originalName:e,schema:t,selectedFields:r,query:i,isExisting:!i,isAlias:!1}}getSQL(){return new $e([this])}};it.prototype.getSQL=function(){return new $e([this])};we.prototype.getSQL=function(){return new $e([this])};vt.prototype.getSQL=function(){return new $e([this])}});function VT(e,t,r){let i={},n=e.reduce((o,{path:s,field:a},c)=>{let l;if(ce(a,it))l=a;else if(ce(a,$e))l=a.decoder;else if(ce(a,vt))l=a._.sql.decoder;else l=a.sql.decoder;let u=o;for(let[d,p]of s.entries())if(d<s.length-1){if(!(p in u))u[p]={};u=u[p]}else{let m=t[c],y=u[p]=m===null?null:l.mapFromDriverValue(m);if(r&&ce(a,it)&&s.length===2){let g=s[0];if(!(g in i))i[g]=y===null?Es(a.table):!1;else if(typeof i[g]==="string"&&i[g]!==Es(a.table))i[g]=!1}}return o},{});if(r&&Object.keys(i).length>0){for(let[o,s]of Object.entries(i))if(typeof s==="string"&&!r[s])n[o]=null}return n}function On(e,t){return Object.entries(e).reduce((r,[i,n])=>{if(typeof i!=="string")return r;let o=t?[...t,i]:[i];if(ce(n,it)||ce(n,$e)||ce(n,$e.Aliased)||ce(n,vt))r.push({path:o,field:n});else if(ce(n,we))r.push(...On(n[we.Symbol.Columns],o));else r.push(...On(n,o));return r},[])}function Cp(e,t){let r=Object.keys(e),i=Object.keys(t);if(r.length!==i.length)return!1;for(let[n,o]of r.entries())if(o!==i[n])return!1;return!0}function cx(e,t){let r=Object.entries(t).filter(([,i])=>i!==void 0).map(([i,n])=>{if(ce(n,$e)||ce(n,it))return[i,n];else return[i,new mn(n,e[we.Symbol.Columns][i])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function N9(e,t){for(let r of t)for(let i of Object.getOwnPropertyNames(r.prototype)){if(i==="constructor")continue;Object.defineProperty(e.prototype,i,Object.getOwnPropertyDescriptor(r.prototype,i)||Object.create(null))}}function lx(e){return e[we.Symbol.Columns]}function Tp(e){return ce(e,vt)?e._.alias:ce(e,Tn)?e[_t].name:ce(e,$e)?void 0:e[we.Symbol.IsAlias]?e[we.Symbol.Name]:e[we.Symbol.BaseName]}function _i(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function D9(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 WT;var Ur=x(()=>{Wn();De();mr();Gn();Ir();so();WT=typeof TextDecoder>"u"?null:new TextDecoder});var L9,GT,QT;var ux=x(()=>{De();L9=class L9{static[K]="ConsoleLogWriter";write(e){console.log(e)}};GT=class GT{static[K]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new L9}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),i=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${i}`)}};QT=class QT{static[K]="NoopLogger";logQuery(){}}});var B9,j9,YT;var q9=x(()=>{De();Ir();B9=Symbol.for("drizzle:PgInlineForeignKeys"),j9=Symbol.for("drizzle:EnableRLS");YT=class YT extends we{static[K]="PgTable";static Symbol=Object.assign({},we.Symbol,{InlineForeignKeys:B9,EnableRLS:j9});[B9]=[];[j9]=!1;[we.Symbol.ExtraConfigBuilder]=void 0;[we.Symbol.ExtraConfigColumns]={}}});var XT,U9;var F9=x(()=>{De();q9();XT=class XT{static[K]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new U9(e,this.columns,this.name)}};U9=class U9{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[K]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[YT.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Qr(e,t){if(R9(t)&&!KT(e)&&!ce(e,mn)&&!ce(e,Is)&&!ce(e,it)&&!ce(e,we)&&!ce(e,Tn))return new mn(e,t);return e}function kt(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new $e(t);return new $e([new Vt("("),q.join(t,new Vt(" and ")),new Vt(")")])}function ao(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new $e(t);return new $e([new Vt("("),q.join(t,new Vt(" or ")),new Vt(")")])}function Z9(e){return q`not ${e}`}function As(e,t){if(Array.isArray(t)){if(t.length===0)return q`false`;return q`${e} in ${t.map((r)=>Qr(r,e))}`}return q`${e} in ${Qr(t,e)}`}function K9(e,t){if(Array.isArray(t)){if(t.length===0)return q`true`;return q`${e} not in ${t.map((r)=>Qr(r,e))}`}return q`${e} not in ${Qr(t,e)}`}function Rn(e){return q`${e} is null`}function V9(e){return q`${e} is not null`}function Op(e){return q`exists ${e}`}function fx(e){return q`not exists ${e}`}function W9(e,t,r){return q`${e} between ${Qr(t,e)} and ${Qr(r,e)}`}function G9(e,t,r){return q`${e} not between ${Qr(t,e)} and ${Qr(r,e)}`}function Q9(e,t){return q`${e} like ${t}`}function Y9(e,t){return q`${e} not like ${t}`}function X9(e,t){return q`${e} ilike ${t}`}function eK(e,t){return q`${e} not ilike ${t}`}var Qe=(e,t)=>q`${e} = ${Qr(t,e)}`,M9=(e,t)=>q`${e} <> ${Qr(t,e)}`,dx=(e,t)=>q`${e} > ${Qr(t,e)}`,H9=(e,t)=>q`${e} >= ${Qr(t,e)}`,J9=(e,t)=>q`${e} < ${Qr(t,e)}`,Va=(e,t)=>q`${e} <= ${Qr(t,e)}`;var tK=x(()=>{Wn();De();Ir();mr()});function co(e){return q`${e} asc`}function Wa(e){return q`${e} desc`}var rK=x(()=>{mr()});var eO=x(()=>{tK();rK()});function iK(){return{and:kt,between:W9,eq:Qe,exists:Op,gt:dx,gte:H9,ilike:X9,inArray:As,isNull:Rn,isNotNull:V9,like:Q9,lt:J9,lte:Va,ne:M9,not:Z9,notBetween:G9,notExists:fx,notLike:Y9,notIlike:eK,notInArray:K9,or:ao,sql:q}}function oK(){return{sql:q,asc:co,desc:Wa}}function sK(e,t){if(Object.keys(e).length===1&&"default"in e&&!ce(e.default,we))e=e.default;let r={},i={},n={};for(let[o,s]of Object.entries(e))if(ce(s,we)){let a=Ka(s),c=i[a];r[a]=o,n[o]={tsName:o,dbName:s[we.Symbol.Name],schema:s[we.Symbol.Schema],columns:s[we.Symbol.Columns],relations:c?.relations??{},primaryKey:c?.primaryKey??[]};for(let u of Object.values(s[we.Symbol.Columns]))if(u.primary)n[o].primaryKey.push(u);let l=s[we.Symbol.ExtraConfigBuilder]?.(s[we.Symbol.ExtraConfigColumns]);if(l){for(let u of Object.values(l))if(ce(u,XT))n[o].primaryKey.push(...u.columns)}}else if(ce(s,nK)){let a=Ka(s.table),c=r[a],l=s.config(t(s.table)),u;for(let[d,p]of Object.entries(l))if(c){let m=n[c];if(m.relations[d]=p,u)m.primaryKey.push(...u)}else{if(!(a in i))i[a]={relations:{},primaryKey:u};i[a].relations[d]=p}}return{tables:n,tableNamesMap:r}}function x_e(e){return function(r,i){return new $s(e,r,i,i?.fields.reduce((n,o)=>n&&o.notNull,!0)??!1)}}function S_e(e){return function(r,i){return new Rp(e,r,i)}}function aK(e,t,r){if(ce(r,$s)&&r.config)return{fields:r.config.fields,references:r.config.references};let i=t[Ka(r.referencedTable)];if(!i)throw Error(`Table "${r.referencedTable[we.Symbol.Name]}" not found in schema`);let n=e[i];if(!n)throw Error(`Table "${i}" not found in schema`);let o=r.sourceTable,s=t[Ka(o)];if(!s)throw Error(`Table "${o[we.Symbol.Name]}" not found in schema`);let a=[];for(let c of Object.values(n.relations))if(r.relationName&&r!==c&&c.relationName===r.relationName||!r.relationName&&c.referencedTable===r.sourceTable)a.push(c);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${i}"`):Error(`There are multiple relations between "${i}" and "${r.sourceTable[we.Symbol.Name]}". Please specify relation name`);if(a[0]&&ce(a[0],$s)&&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 cK(e){return{one:x_e(e),many:S_e(e)}}function px(e,t,r,i,n=(o)=>o){let o={};for(let[s,a]of i.entries())if(a.isJson){let c=t.relations[a.tsKey],l=r[s],u=typeof l==="string"?JSON.parse(l):l;o[a.tsKey]=ce(c,$s)?u&&px(e,e[a.relationTableTsKey],u,a.selection,n):u.map((d)=>px(e,e[a.relationTableTsKey],d,a.selection,n))}else{let c=n(r[s]),l=a.field,u;if(ce(l,it))u=l;else if(ce(l,$e))u=l.decoder;else u=l.sql.decoder;o[a.tsKey]=c===null?null:u.mapFromDriverValue(c)}return o}var tO,nK,$s,Rp;var Pp=x(()=>{Ir();Wn();De();F9();eO();mr();tO=class tO{constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[we.Symbol.Name]}static[K]="Relation";referencedTableName;fieldName};nK=class nK{constructor(e,t){this.table=e,this.config=t}static[K]="Relations"};$s=class $s extends tO{constructor(e,t,r,i){super(e,t,r?.relationName);this.config=r,this.isNullable=i}static[K]="One";withFieldName(e){let t=new $s(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};Rp=class Rp extends tO{constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[K]="Many";withFieldName(e){let t=new Rp(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function Np(e,t){return new Proxy(e,new zp(t,!1))}function ki(e,t){return new Proxy(e,new Su(new Proxy(e.table,new zp(t,!1))))}function rO(e,t){return new $e.Aliased(Dp(e.sql,t),e.fieldAlias)}function Dp(e,t){return q.join(e.queryChunks.map((r)=>{if(ce(r,it))return ki(r,t);if(ce(r,$e))return Dp(r,t);if(ce(r,$e.Aliased))return rO(r,t);return r}))}var Su,zp,w_e;var mx=x(()=>{Wn();De();mr();Ir();so();Su=class Su{constructor(e){this.table=e}static[K]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};zp=class zp{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[K]="TableAliasProxyHandler";get(e,t){if(t===we.Symbol.IsAlias)return!0;if(t===we.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===we.Symbol.OriginalName)return this.alias;if(t===_t)return{...e[_t],name:this.alias,isAlias:!0};if(t===we.Symbol.Columns){let i=e[we.Symbol.Columns];if(!i)return i;let n={};return Object.keys(i).map((o)=>{n[o]=new Proxy(i[o],new Su(new Proxy(e,this)))}),n}let r=e[t];if(ce(r,it))return new Proxy(r,new Su(new Proxy(e,this)));return r}};w_e=class w_e{constructor(e){this.alias=e}static[K]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return Np(e.sourceTable,this.alias);return e[t]}}});var bt;var Ga=x(()=>{mx();Wn();De();mr();Gn();so();bt=class bt{static[K]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===_t)return{...e[_t],selectedFields:new Proxy(e[_t].selectedFields,this)};if(typeof t==="symbol")return e[t];let i=(ce(e,vt)?e._.selectedFields:ce(e,Tn)?e[_t].selectedFields:e)[t];if(ce(i,$e.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!i.isSelectionField)return i.sql;let n=i.clone();return n.isSelectionField=!0,n}if(ce(i,$e)){if(this.config.sqlBehavior==="sql")return i;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(ce(i,it)){if(this.config.alias)return new Proxy(i,new Su(new Proxy(i.table,new zp(this.config.alias,this.config.replaceOriginalName??!1))));return i}if(typeof i!=="object"||i===null)return i;return new Proxy(i,new bt(this.config))}}});var Fr;var lo=x(()=>{De();Fr=class Fr{static[K]="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 nO,lK;var iO=x(()=>{De();bu();nO=class nO{static[K]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:i,foreignColumns:n}=e();return{name:r,columns:i,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 lK(e,this)}};lK=class lK{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[K]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),i=t.map((s)=>s.name),n=r.map((s)=>s.name),o=[this.table[Er],...i,r[0].table[Er],...n];return e??`${o.join("_")}_fk`}}});function oO(e,t){return`${e[Er]}_${t.join("_")}_unique`}var uK,v_e,dK;var sO=x(()=>{De();bu();uK=class uK{constructor(e,t){this.name=t,this.columns=e}static[K]="SQLiteUniqueConstraintBuilder";columns;build(e){return new dK(e,this.columns,this.name)}};v_e=class v_e{static[K]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new uK(e,this.name)}};dK=class dK{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??oO(this.table,this.columns.map((i)=>i.name))}static[K]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Xt,$t;var Cs=x(()=>{nx();Wn();De();iO();sO();Xt=class Xt extends kp{static[K]="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:i})=>((n,o)=>{let s=new nO(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(o.onUpdate)s.onUpdate(o.onUpdate);if(o.onDelete)s.onDelete(o.onDelete);return s.build(t)})(r,i))}};$t=class $t extends it{constructor(e,t){if(!t.uniqueName)t.uniqueName=oO(e,[t.name]);super(e,t);this.table=e}static[K]="SQLiteColumn"}});function bK(e,t){let{name:r,config:i}=_i(e,t);if(i?.mode==="json")return new mK(r);if(i?.mode==="bigint")return new fK(r);return new gK(r)}var fK,pK,mK,hK,gK,yK;var aO=x(()=>{De();Ur();Cs();fK=class fK extends Xt{static[K]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new pK(e,this.config)}};pK=class pK extends $t{static[K]="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(WT.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};mK=class mK extends Xt{static[K]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new hK(e,this.config)}};hK=class hK extends $t{static[K]="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(WT.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};gK=class gK extends Xt{static[K]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new yK(e,this.config)}};yK=class yK extends $t{static[K]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function wK(e){return(t,r)=>{let{name:i,config:n}=_i(t,r);return new xK(i,n,e)}}var xK,SK;var cO=x(()=>{De();Ur();Cs();xK=class xK extends Xt{static[K]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new SK(e,this.config)}};SK=class SK extends $t{static[K]="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:i}=_i(e,t);if(i?.mode==="timestamp"||i?.mode==="timestamp_ms")return new kK(r,i.mode);if(i?.mode==="boolean")return new IK(r,i.mode);return new vK(r)}var hx,gx,vK,_K,kK,EK,IK,AK;var lO=x(()=>{De();mr();Ur();Cs();hx=class hx extends Xt{static[K]="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()}};gx=class gx extends $t{static[K]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};vK=class vK extends hx{static[K]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new _K(e,this.config)}};_K=class _K extends gx{static[K]="SQLiteInteger"};kK=class kK extends hx{static[K]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(q`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new EK(e,this.config)}};EK=class EK extends gx{static[K]="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}};IK=class IK extends hx{static[K]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new AK(e,this.config)}};AK=class AK extends gx{static[K]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function zK(e,t){let{name:r,config:i}=_i(e,t),n=i?.mode;return n==="number"?new TK(r):n==="bigint"?new RK(r):new $K(r)}var $K,CK,TK,OK,RK,PK;var uO=x(()=>{De();Ur();Cs();$K=class $K extends Xt{static[K]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new CK(e,this.config)}};CK=class CK extends $t{static[K]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};TK=class TK extends Xt{static[K]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new OK(e,this.config)}};OK=class OK extends $t{static[K]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};RK=class RK extends Xt{static[K]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new PK(e,this.config)}};PK=class PK extends $t{static[K]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function LK(e){return new NK(e??"")}var NK,DK;var dO=x(()=>{De();Cs();NK=class NK extends Xt{static[K]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new DK(e,this.config)}};DK=class DK extends $t{static[K]="SQLiteReal";getSQLType(){return"real"}}});function hr(e,t={}){let{name:r,config:i}=_i(e,t);if(i.mode==="json")return new qK(r);return new BK(r,i)}var BK,jK,qK,UK;var fO=x(()=>{De();Ur();Cs();BK=class BK extends Xt{static[K]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new jK(e,this.config)}};jK=class jK extends $t{static[K]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};qK=class qK extends Xt{static[K]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new UK(e,this.config)}};UK=class UK extends $t{static[K]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function FK(){return{blob:bK,customType:wK,integer:Ar,numeric:zK,real:LK,text:hr}}var MK=x(()=>{aO();cO();lO();uO();dO();fO()});function __e(e,t,r,i,n=e){let o=new Ft(e,i,n),s=typeof t==="function"?t(FK()):t,a=Object.fromEntries(Object.entries(s).map(([l,u])=>{let d=u;d.setName(l);let p=d.build(o);return o[pO].push(...d.buildForeignKeys(p,o)),[l,p]})),c=Object.assign(o,a);if(c[we.Symbol.Columns]=a,c[we.Symbol.ExtraConfigColumns]=a,r)c[Ft.Symbol.ExtraConfigBuilder]=r;return c}var pO,Ft,Lp=(e,t,r)=>__e(e,t,r);var uo=x(()=>{De();Ir();MK();pO=Symbol.for("drizzle:SQLiteInlineForeignKeys");Ft=class Ft extends we{static[K]="SQLiteTable";static Symbol=Object.assign({},we.Symbol,{InlineForeignKeys:pO});[we.Symbol.Columns];[pO]=[];[we.Symbol.ExtraConfigBuilder]=void 0}});var k_e,ZK;var HK=x(()=>{De();k_e=class k_e{constructor(e,t){this.name=e,this.value=t}static[K]="SQLiteCheckBuilder";brand;build(e){return new ZK(e,this)}};ZK=class ZK{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[K]="SQLiteCheck";name;value}});function Qa(e){return new JK(e,!1)}var JK,KK,VK;var WK=x(()=>{De();JK=class JK{constructor(e,t){this.name=e,this.unique=t}static[K]="SQLiteIndexBuilderOn";on(...e){return new KK(this.name,e,this.unique)}};KK=class KK{static[K]="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 VK(this.config,e)}};VK=class VK{static[K]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var E_e,GK;var QK=x(()=>{De();uo();E_e=class E_e{static[K]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new GK(e,this.columns,this.name)}};GK=class GK{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[K]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[Ft.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Qn(e){if(ce(e,Ft))return[`${e[we.Symbol.BaseName]}`];if(ce(e,vt))return e._.usedTables??[];if(ce(e,$e))return e.usedTables??[];return[]}var wu=x(()=>{De();mr();Gn();Ir();uo()});var yx;var YK=x(()=>{De();lo();Ga();uo();Ir();Ur();wu();yx=class yx extends Fr{constructor(e,t,r,i){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:i}}static[K]="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[we.Symbol.Columns],new bt({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[Ft.Symbol.Columns]){return this.config.returning=On(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:Qn(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 I_e(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function A_e(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,i,n)=>{let o=n===0?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`;return r+o},"")}function $_e(e){return e}var mO;var XK=x(()=>{De();Ir();mO=class mO{static[K]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?I_e:e==="camelCase"?A_e:$_e}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[we.Symbol.Schema]??"public",r=e.table[we.Symbol.OriginalName],i=`${t}.${r}.${e.name}`;if(!this.cache[i])this.cacheTable(e.table);return this.cache[i]}cacheTable(e){let t=e[we.Symbol.Schema]??"public",r=e[we.Symbol.OriginalName],i=`${t}.${r}`;if(!this.cachedTables[i]){for(let n of Object.values(e[we.Symbol.Columns])){let o=`${i}.${n.name}`;this.cache[o]=this.convert(n.name)}this.cachedTables[i]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var vu,fo,hO;var bx=x(()=>{De();vu=class vu extends Error{static[K]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};fo=class fo extends Error{constructor(e,t,r){super(`Failed query: ${e}
|
|
441
|
+
params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrace(this,fo),r)this.cause=r}};hO=class hO extends vu{static[K]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var eV=()=>{};var tV=()=>{};var rV=x(()=>{eV();tV()});var gO=x(()=>{eO();rV();mr()});var yO=x(()=>{aO();Cs();cO();lO();uO();dO();fO()});var po;var Bp=x(()=>{De();mr();po=class po extends Tn{static[K]="SQLiteViewBase"}});var _u,bO,xO;var xx=x(()=>{mx();XK();Wn();De();bx();Pp();gO();mr();yO();uo();Gn();Ir();Ur();so();Bp();_u=class _u{static[K]="SQLiteDialect";casing;constructor(e){this.casing=new mO(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=[q`with `];for(let[r,i]of e.entries())if(t.push(q`${q.identifier(i._.alias)} as (${i._.sql})`),r<e.length-1)t.push(q`, `);return t.push(q` `),q.join(t)}buildDeleteQuery({table:e,where:t,returning:r,withList:i,limit:n,orderBy:o}){let s=this.buildWithCTE(i),a=r?q` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,c=t?q` where ${t}`:void 0,l=this.buildOrderBy(o),u=this.buildLimit(n);return q`${s}delete from ${e}${c}${a}${l}${u}`}buildUpdateSet(e,t){let r=e[we.Symbol.Columns],i=Object.keys(r).filter((o)=>t[o]!==void 0||r[o]?.onUpdateFn!==void 0),n=i.length;return q.join(i.flatMap((o,s)=>{let a=r[o],c=a.onUpdateFn?.(),l=t[o]??(ce(c,$e)?c:q.param(c,a)),u=q`${q.identifier(this.casing.getColumnCasing(a))} = ${l}`;if(s<n-1)return[u,q.raw(", ")];return[u]}))}buildUpdateQuery({table:e,set:t,where:r,returning:i,withList:n,joins:o,from:s,limit:a,orderBy:c}){let l=this.buildWithCTE(n),u=this.buildUpdateSet(e,t),d=s&&q.join([q.raw(" from "),this.buildFromTable(s)]),p=this.buildJoins(o),m=i?q` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,y=r?q` where ${r}`:void 0,g=this.buildOrderBy(c),b=this.buildLimit(a);return q`${l}update ${e} set ${u}${d}${p}${y}${m}${g}${b}`}buildSelection(e,{isSingleTable:t=!1}={}){let r=e.length,i=e.flatMap(({field:n},o)=>{let s=[];if(ce(n,$e.Aliased)&&n.isSelectionField)s.push(q.identifier(n.fieldAlias));else if(ce(n,$e.Aliased)||ce(n,$e)){let a=ce(n,$e.Aliased)?n.sql:n;if(t)s.push(new $e(a.queryChunks.map((c)=>{if(ce(c,it))return q.identifier(this.casing.getColumnCasing(c));return c})));else s.push(a);if(ce(n,$e.Aliased))s.push(q` as ${q.identifier(n.fieldAlias)}`)}else if(ce(n,it)){let a=n.table[we.Symbol.Name];if(n.columnType==="SQLiteNumericBigInt")if(t)s.push(q`cast(${q.identifier(this.casing.getColumnCasing(n))} as text)`);else s.push(q`cast(${q.identifier(a)}.${q.identifier(this.casing.getColumnCasing(n))} as text)`);else if(t)s.push(q.identifier(this.casing.getColumnCasing(n)));else s.push(q`${q.identifier(a)}.${q.identifier(this.casing.getColumnCasing(n))}`)}else if(ce(n,vt)){let a=Object.entries(n._.selectedFields);if(a.length===1){let c=a[0][1],l=ce(c,$e)?c.decoder:ce(c,it)?{mapFromDriverValue:(u)=>c.mapFromDriverValue(u)}:c.sql.decoder;if(l)n._.sql.decoder=l}s.push(n)}if(o<r-1)s.push(q`, `);return s});return q.join(i)}buildJoins(e){if(!e||e.length===0)return;let t=[];if(e)for(let[r,i]of e.entries()){if(r===0)t.push(q` `);let n=i.table,o=i.on?q` on ${i.on}`:void 0;if(ce(n,Ft)){let s=n[Ft.Symbol.Name],a=n[Ft.Symbol.Schema],c=n[Ft.Symbol.OriginalName],l=s===c?void 0:i.alias;t.push(q`${q.raw(i.joinType)} join ${a?q`${q.identifier(a)}.`:void 0}${q.identifier(c)}${l&&q` ${q.identifier(l)}`}${o}`)}else t.push(q`${q.raw(i.joinType)} join ${n}${o}`);if(r<e.length-1)t.push(q` `)}return q.join(t)}buildLimit(e){return typeof e==="object"||typeof e==="number"&&e>=0?q` limit ${e}`:void 0}buildOrderBy(e){let t=[];if(e){for(let[r,i]of e.entries())if(t.push(i),r<e.length-1)t.push(q`, `)}return t.length>0?q` order by ${q.join(t)}`:void 0}buildFromTable(e){if(ce(e,we)&&e[we.Symbol.IsAlias])return q`${q`${q.identifier(e[we.Symbol.Schema]??"")}.`.if(e[we.Symbol.Schema])}${q.identifier(e[we.Symbol.OriginalName])} ${q.identifier(e[we.Symbol.Name])}`;return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:r,where:i,having:n,table:o,joins:s,orderBy:a,groupBy:c,limit:l,offset:u,distinct:d,setOperators:p}){let m=r??On(t);for(let P of m)if(ce(P.field,it)&&Es(P.field.table)!==(ce(o,vt)?o._.alias:ce(o,po)?o[_t].name:ce(o,$e)?void 0:Es(o))&&!((N)=>s?.some(({alias:I})=>I===(N[we.Symbol.IsAlias]?Es(N):N[we.Symbol.BaseName])))(P.field.table)){let N=Es(P.field.table);throw Error(`Your "${P.path.join("->")}" field references a column "${N}"."${P.field.name}", but the table "${N}" is not part of the query! Did you forget to join it?`)}let y=!s||s.length===0,g=this.buildWithCTE(e),b=d?q` distinct`:void 0,v=this.buildSelection(m,{isSingleTable:y}),A=this.buildFromTable(o),C=this.buildJoins(s),z=i?q` where ${i}`:void 0,j=n?q` having ${n}`:void 0,E=[];if(c){for(let[P,N]of c.entries())if(E.push(N),P<c.length-1)E.push(q`, `)}let Z=E.length>0?q` group by ${q.join(E)}`:void 0,D=this.buildOrderBy(a),H=this.buildLimit(l),ee=u?q` offset ${u}`:void 0,F=q`${g}select${b} ${v} from ${A}${C}${z}${Z}${j}${D}${H}${ee}`;if(p.length>0)return this.buildSetOperations(F,p);return F}buildSetOperations(e,t){let[r,...i]=t;if(!r)throw Error("Cannot pass undefined values to any set operator");if(i.length===0)return this.buildSetOperationQuery({leftSelect:e,setOperator:r});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:r}),i)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:r,rightSelect:i,limit:n,orderBy:o,offset:s}}){let a=q`${e.getSQL()} `,c=q`${i.getSQL()}`,l;if(o&&o.length>0){let m=[];for(let y of o)if(ce(y,$t))m.push(q.identifier(y.name));else if(ce(y,$e)){for(let g=0;g<y.queryChunks.length;g++){let b=y.queryChunks[g];if(ce(b,$t))y.queryChunks[g]=q.identifier(this.casing.getColumnCasing(b))}m.push(q`${y}`)}else m.push(q`${y}`);l=q` order by ${q.join(m,q`, `)}`}let u=typeof n==="object"||typeof n==="number"&&n>=0?q` limit ${n}`:void 0,d=q.raw(`${t} ${r?"all ":""}`),p=s?q` offset ${s}`:void 0;return q`${a}${d}${c}${l}${u}${p}`}buildInsertQuery({table:e,values:t,onConflict:r,returning:i,withList:n,select:o}){let s=[],a=e[we.Symbol.Columns],c=Object.entries(a).filter(([y,g])=>!g.shouldDisableInsert()),l=c.map(([,y])=>q.identifier(this.casing.getColumnCasing(y)));if(o){let y=t;if(ce(y,$e))s.push(y);else s.push(y.getSQL())}else{let y=t;s.push(q.raw("values "));for(let[g,b]of y.entries()){let v=[];for(let[A,C]of c){let z=b[A];if(z===void 0||ce(z,mn)&&z.value===void 0){let j;if(C.default!==null&&C.default!==void 0)j=ce(C.default,$e)?C.default:q.param(C.default,C);else if(C.defaultFn!==void 0){let E=C.defaultFn();j=ce(E,$e)?E:q.param(E,C)}else if(!C.default&&C.onUpdateFn!==void 0){let E=C.onUpdateFn();j=ce(E,$e)?E:q.param(E,C)}else j=q`null`;v.push(j)}else v.push(z)}if(s.push(v),g<y.length-1)s.push(q`, `)}}let u=this.buildWithCTE(n),d=q.join(s),p=i?q` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,m=r?.length?q.join(r):void 0;return q`${u}insert into ${e} ${l} ${d}${m}${p}`}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:i,tableConfig:n,queryConfig:o,tableAlias:s,nestedQueryRelation:a,joinOn:c}){let l=[],u,d,p=[],m,y=[];if(o===!0)l=Object.entries(n.columns).map(([v,A])=>({dbKey:A.name,tsKey:v,field:ki(A,s),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let b=Object.fromEntries(Object.entries(n.columns).map(([E,Z])=>[E,ki(Z,s)]));if(o.where){let E=typeof o.where==="function"?o.where(b,iK()):o.where;m=E&&Dp(E,s)}let v=[],A=[];if(o.columns){let E=!1;for(let[Z,D]of Object.entries(o.columns)){if(D===void 0)continue;if(Z in n.columns){if(!E&&D===!0)E=!0;A.push(Z)}}if(A.length>0)A=E?A.filter((Z)=>o.columns?.[Z]===!0):Object.keys(n.columns).filter((Z)=>!A.includes(Z))}else A=Object.keys(n.columns);for(let E of A){let Z=n.columns[E];v.push({tsKey:E,value:Z})}let C=[];if(o.with)C=Object.entries(o.with).filter((E)=>!!E[1]).map(([E,Z])=>({tsKey:E,queryConfig:Z,relation:n.relations[E]}));let z;if(o.extras){z=typeof o.extras==="function"?o.extras(b,{sql:q}):o.extras;for(let[E,Z]of Object.entries(z))v.push({tsKey:E,value:rO(Z,s)})}for(let{tsKey:E,value:Z}of v)l.push({dbKey:ce(Z,$e.Aliased)?Z.fieldAlias:n.columns[E].name,tsKey:E,field:ce(Z,it)?ki(Z,s):Z,relationTableTsKey:void 0,isJson:!1,selection:[]});let j=typeof o.orderBy==="function"?o.orderBy(b,oK()):o.orderBy??[];if(!Array.isArray(j))j=[j];p=j.map((E)=>{if(ce(E,it))return ki(E,s);return Dp(E,s)}),u=o.limit,d=o.offset;for(let{tsKey:E,queryConfig:Z,relation:D}of C){let H=aK(t,r,D),ee=Ka(D.referencedTable),F=r[ee],P=`${s}_${E}`,N=kt(...H.fields.map((O,M)=>Qe(ki(H.references[M],P),ki(O,s)))),I=this.buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:e[F],tableConfig:t[F],queryConfig:ce(D,$s)?Z===!0?{limit:1}:{...Z,limit:1}:Z,tableAlias:P,joinOn:N,nestedQueryRelation:D}),R=q`(${I.sql})`.as(E);l.push({dbKey:E,tsKey:E,field:R,relationTableTsKey:F,isJson:!0,selection:I.selection})}}if(l.length===0)throw new vu({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 g;if(m=kt(c,m),a){let b=q`json_array(${q.join(l.map(({field:C})=>ce(C,$t)?q.identifier(this.casing.getColumnCasing(C)):ce(C,$e.Aliased)?C.sql:C),q`, `)})`;if(ce(a,Rp))b=q`coalesce(json_group_array(${b}), json_array())`;let v=[{dbKey:"data",tsKey:"data",field:b.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:l}];if(u!==void 0||d!==void 0||p.length>0)g=this.buildSelectQuery({table:Np(i,s),fields:{},fieldsFlat:[{path:[],field:q.raw("*")}],where:m,limit:u,offset:d,orderBy:p,setOperators:[]}),m=void 0,u=void 0,d=void 0,p=void 0;else g=Np(i,s);g=this.buildSelectQuery({table:ce(g,Ft)?g:new vt(g,{},s),fields:{},fieldsFlat:v.map(({field:C})=>({path:[],field:ce(C,it)?ki(C,s):C})),joins:y,where:m,limit:u,offset:d,orderBy:p,setOperators:[]})}else g=this.buildSelectQuery({table:Np(i,s),fields:{},fieldsFlat:l.map(({field:b})=>({path:[],field:ce(b,it)?ki(b,s):b})),joins:y,where:m,limit:u,offset:d,orderBy:p,setOperators:[]});return{tableTsKey:n.tsName,sql:g,selection:l}}};bO=class bO extends _u{static[K]="SQLiteSyncDialect";migrate(e,t,r){let i=r===void 0?"__drizzle_migrations":typeof r==="string"?"__drizzle_migrations":r.migrationsTable??"__drizzle_migrations",n=q`
|
|
442
442
|
CREATE TABLE IF NOT EXISTS ${q.identifier(i)} (
|
|
443
443
|
id SERIAL PRIMARY KEY,
|
|
444
444
|
hash text NOT NULL,
|
|
@@ -450,7 +450,7 @@ params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrac
|
|
|
450
450
|
hash text NOT NULL,
|
|
451
451
|
created_at numeric
|
|
452
452
|
)
|
|
453
|
-
`;await t.run(n);let s=(await t.values(q`SELECT id, hash, created_at FROM ${q.identifier(i)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(a)=>{for(let c of e)if(!s||Number(s[2])<c.folderMillis){for(let l of c.sql)await a.run(q.raw(l));await a.run(q`INSERT INTO ${q.identifier(i)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}})}}});var SO;var nV=x(()=>{De();SO=class SO{static[K]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function Sx(e,t){return(r,i,...n)=>{let o=[i,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of o)if(!Cp(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(o)}}var Yn,iV,wO,C_e=()=>({union:T_e,unionAll:O_e,intersect:R_e,except:P_e}),T_e,O_e,R_e,P_e;var vO=x(()=>{De();nV();lo();Ga();mr();Gn();Ir();Ur();so();wu();Bp();Yn=class Yn{static[K]="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(ce(e,vt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((i)=>[i,e[i]]));else if(ce(e,po))r=e[_t].selectedFields;else if(ce(e,$e))r={};else r=lx(e);return new wO({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};iV=class iV extends SO{static[K]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:i,dialect:n,withList:o,distinct:s}){super();this.config={withList:o,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=r,this.session=i,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=Tp(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of Qn(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let i=this.tableName,n=Tp(t);for(let o of Qn(t))this.usedTables.add(o);if(typeof n==="string"&&this.config.joins?.some((o)=>o.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof i==="string")this.config.fields={[i]:this.config.fields};if(typeof n==="string"&&!ce(t,$e)){let o=ce(t,vt)?t._.selectedFields:ce(t,Tn)?t[_t].selectedFields:t[we.Symbol.Columns];this.config.fields[n]=o}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new bt({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(([o])=>[o,!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(([o])=>[o,!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 i=typeof r==="function"?r(C_e()):r;if(!Cp(this.getSelectedFields(),i.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:i}),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 bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new bt({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 bt({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 bt({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(...Qn(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...Qn(r.table));return new Proxy(new vt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new bt({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};wO=class wO extends iV{static[K]="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=On(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()}};NK(wO,[Fr]);T_e=Sx("union",!1),O_e=Sx("union",!0),R_e=Sx("intersect",!1),P_e=Sx("except",!1)});var Ya;var wx=x(()=>{De();Ga();xx();Gn();vO();Ya=class Ya{static[K]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=ce(e,_u)?e:void 0,this.dialectConfig=ce(e,_u)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new Ip(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new Yn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function i(n){return new Yn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:i}}select(e){return new Yn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Yn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new bO(this.dialectConfig);return this.dialect}}});var vx,_O;var oV=x(()=>{De();lo();mr();uo();Ir();Ur();wu();wx();vx=class vx{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[K]="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 i={},n=this.table[we.Symbol.Columns];for(let o of Object.keys(r)){let s=r[o];i[o]=ce(s,$e)?s:new mn(s,n[o])}return i});return new _O(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new Ya):e;if(!ce(t,$e)&&!Cp(this.table[sx],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 _O(this.table,t,this.session,this.dialect,this.withList,!0)}};_O=class _O extends Fr{constructor(e,t,r,i,n,o){super();this.session=r,this.dialect=i,this.config={table:e,values:t,withList:n,select:o}}static[K]="SQLiteInsert";config;returning(e=this.config.table[Ft.Symbol.Columns]){return this.config.returning=On(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(q` on conflict do nothing`);else{let t=Array.isArray(e.target)?q`${e.target}`:q`${[e.target]}`,r=e.where?q` where ${e.where}`:q``;this.config.onConflict.push(q` 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?q` where ${e.where}`:void 0,r=e.targetWhere?q` where ${e.targetWhere}`:void 0,i=e.setWhere?q` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?q`${e.target}`:q`${[e.target]}`,o=this.dialect.buildUpdateSet(this.config.table,cx(this.config.table,e.set));return this.config.onConflict.push(q` on conflict ${n}${r} do update set ${o}${t}${i}`),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:Qn(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 _x,sV;var aV=x(()=>{De();lo();Ga();uo();Gn();Ir();Ur();so();wu();Bp();_x=class _x{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[K]="SQLiteUpdateBuilder";set(e){return new sV(this.table,cx(this.table,e),this.session,this.dialect,this.withList)}};sV=class sV extends Fr{constructor(e,t,r,i,n){super();this.session=r,this.dialect=i,this.config={set:t,table:e,withList:n,joins:[]}}static[K]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let i=Tp(t);if(typeof i==="string"&&this.config.joins.some((n)=>n.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?ce(t,Ft)?t[we.Symbol.Columns]:ce(t,vt)?t._.selectedFields:ce(t,po)?t[_t].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[we.Symbol.Columns],new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:i}),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[we.Symbol.Columns],new bt({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[Ft.Symbol.Columns]){return this.config.returning=On(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:Qn(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 kO=x(()=>{Y9();oV();wx();vO();aV()});var jp;var cV=x(()=>{De();mr();jp=class jp extends $e{constructor(e){super(jp.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=jp.buildCount(e.source,e.filters)}sql;static[K]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return q`(select count(*) from ${e}${q.raw(" where ").if(t)}${t})`}static buildCount(e,t){return q`select count(*) from ${e}${q.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 IO,kx,EO;var lV=x(()=>{De();lo();Pp();IO=class IO{constructor(e,t,r,i,n,o,s,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=i,this.table=n,this.tableConfig=o,this.dialect=s,this.session=a}static[K]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new EO(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new kx(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new EO(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new kx(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};kx=class kx extends Fr{constructor(e,t,r,i,n,o,s,a,c){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=i,this.tableConfig=n,this.dialect=o,this.session=s,this.config=a,this.mode=c}static[K]="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,(i,n)=>{let o=i.map((s)=>px(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return o[0];return o})}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()}};EO=class EO extends kx{static[K]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var ku;var uV=x(()=>{De();lo();ku=class ku extends Fr{constructor(e,t,r,i,n){super();this.execute=e,this.getSQL=t,this.dialect=i,this.mapBatchResult=n,this.config={action:r}}static[K]="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 qp;var Ex=x(()=>{De();Ga();mr();kO();Gn();cV();lV();uV();qp=class qp{constructor(e,t,r,i){this.resultKind=e,this.dialect=t,this.session=r,this._=i?{schema:i.schema,fullSchema:i.fullSchema,tableNamesMap:i.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let n=this.query;if(this._.schema)for(let[o,s]of Object.entries(this._.schema))n[o]=new IO(e,i.fullSchema,this._.schema,this._.tableNamesMap,i.fullSchema[o],s,t,r);this.$cache={invalidate:async(o)=>{}}}static[K]="BaseSQLiteDatabase";query;$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(new Ya(r.dialect));return new Proxy(new Ip(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new jp({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Yn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function i(a){return new Yn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new _x(a,t.session,t.dialect,e)}function o(a){return new vx(a,t.session,t.dialect,e)}function s(a){return new yx(a,t.session,t.dialect,e)}return{select:r,selectDistinct:i,update:n,insert:o,delete:s}}select(e){return new Yn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Yn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new _x(e,this.session,this.dialect)}$cache;insert(e){return new vx(e,this.session,this.dialect)}delete(e){return new yx(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new ku(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"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new ku(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"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new ku(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"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new ku(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 AO(e,t){let r=`${e}-${JSON.stringify(t)}`,n=new TextEncoder().encode(r),o=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(o)].map((c)=>c.toString(16).padStart(2,"0")).join("")}var dV,Up;var $O=x(()=>{De();dV=class dV{static[K]="Cache"};Up=class Up extends dV{strategy(){return"all"}static[K]="NoopCache";async get(e){return}async put(e,t,r,i){}async onMutate(e){}}});var fV=x(()=>{$O()});var pV=()=>{};var mV,CO,TO,OO;var RO=x(()=>{$O();De();bx();lo();Ex();mV=class mV extends Fr{constructor(e){super();this.resultCb=e}static[K]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};CO=class CO{constructor(e,t,r,i,n,o){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=i,this.queryMetadata=n,this.cacheConfig=o,i&&i.strategy()==="all"&&o===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[K]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||ce(this.cache,Up)||this.queryMetadata===void 0)try{return await r()}catch(i){throw new fo(e,t,i)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(i){throw new fo(e,t,i)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[i]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return i}catch(i){throw new fo(e,t,i)}if(!this.cacheConfig)try{return await r()}catch(i){throw new fo(e,t,i)}if(this.queryMetadata.type==="select"){let i=await this.cache.get(this.cacheConfig.tag??await AO(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(i===void 0){let n;try{n=await r()}catch(o){throw new fo(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await AO(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return i}try{return await r()}catch(i){throw new fo(e,t,i)}}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 mV(()=>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)}}};TO=class TO{constructor(e){this.dialect=e}static[K]="SQLiteSession";prepareOneTimeQuery(e,t,r,i,n,o,s){return this.prepareQuery(e,t,r,i,n,o,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(r){throw new vu({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")}};OO=class OO extends qp{constructor(e,t,r,i,n=0){super(e,t,r,i);this.schema=i,this.nestedIndex=n}static[K]="SQLiteTransaction";rollback(){throw new hO}}});var PO,z_e,N_e,Ix;var hV=x(()=>{De();Ga();Ur();wx();uo();Bp();PO=class PO{constructor(e){this.name=e}static[K]="SQLiteViewBuilderCore";config={}};z_e=class z_e extends PO{static[K]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new Ya);let t=new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new Ix({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};N_e=class N_e extends PO{static[K]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=lx(Lp(e,t))}existing(){return new Proxy(new Ix({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new Ix({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};Ix=class Ix extends po{static[K]="SQLiteView";constructor({config:e}){super(e)}}});var zO=x(()=>{pV();H9();yO();Ex();xx();iO();W9();Q9();kO();RO();uo();sO();wu();hV()});function gV(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function Ax(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 $x,NO,yV;var DO=x(()=>{fV();De();ux();mr();zO();RO();Ur();$x=class $x extends TO{constructor(e,t,r,i,n){super(t);this.client=e,this.schema=r,this.options=i,this.tx=n,this.logger=i.logger??new QT,this.cache=i.cache??new Up}static[K]="LibSQLSession";logger;cache;prepareQuery(e,t,r,i,n,o,s){return new yV(this.client,e,this.logger,this.cache,o,s,t,this.tx,r,i,n)}async batch(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,o)=>t[o].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,o)=>t[o].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),i=new $x(this.client,this.dialect,this.schema,this.options,r),n=new NO("async",this.dialect,i,this.schema);try{let o=await e(n);return await r.commit(),o}catch(o){throw await r.rollback(),o}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}};NO=class NO extends OO{static[K]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new NO("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(q.raw(`savepoint ${t}`));try{let i=await e(r);return await this.session.run(q.raw(`release savepoint ${t}`)),i}catch(i){throw await this.session.run(q.raw(`rollback to savepoint ${t}`)),i}}};yV=class yV extends CO{constructor(e,t,r,i,n,o,s,a,c,l,u){super("async",c,t,i,n,o);this.client=e,this.logger=r,this.fields=s,this.tx=a,this._isResponseInArrayMode=l,this.customResultMapper=u,this.customResultMapper=u,this.fields=s}static[K]="LibSQLPreparedQuery";async run(e){let t=$p(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:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=$p(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapAllResult(u))})}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)=>gV(r));if(this.customResultMapper)return this.customResultMapper(e,Ax);return e.map((r)=>VT(this.fields,Array.prototype.slice.call(r).map((i)=>Ax(i)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=$p(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapGetResult(u))})}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 gV(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,Ax);return VT(this.fields,Array.prototype.slice.call(r).map((i)=>Ax(i)),this.joinsNotNullableMap)}async values(e){let t=$p(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:i})=>i)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}});function Eu(e,t={}){let r=new xO({casing:t.casing}),i;if(t.logger===!0)i=new GT;else if(t.logger!==!1)i=t.logger;let n;if(t.schema){let a=s9(t.schema,c9);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let o=new $x(e,r,n,{logger:i,cache:t.cache},void 0),s=new bV("async",r,o,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var bV;var xV=x(()=>{De();ux();Pp();Ex();xx();DO();bV=class bV extends qp{static[K]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function Cx(...e){if(typeof e[0]==="string"){let t=Ja({url:e[0]});return Eu(t,e[1])}if(DK(e[0])){let{connection:t,client:r,...i}=e[0];if(r)return Eu(r,i);let n=typeof t==="string"?Ja({url:t}):Ja(t);return Eu(n,i)}return Eu(e[0],e[1])}var SV=x(()=>{LT();Ur();xV();((e)=>{function t(r){return Eu({},r)}e.mock=t})(Cx||(Cx={}))});var wV=x(()=>{SV();DO()});function vV(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function Tx(e){let{url:t,schema:r}=e,i=vV(e),n=i?Ja({url:t,authToken:i}):Ja({url:t});return{db:Cx(n,{schema:r}),client:n,url:t}}async function Ox(e,t){if(!t.startsWith("file:"))return;await e.execute("PRAGMA busy_timeout = 5000"),await e.execute("PRAGMA journal_mode = WAL")}var LO=x(()=>{LT();wV()});var _V=x(()=>{YC();LO()});var BO=x(()=>{LO();_V()});var X,Ye;var jO=x(()=>{zO();ep();X=Lp("job_queue",{id:hr("id").primaryKey().$defaultFn(()=>to()),type:hr("type").notNull(),data:hr("data").notNull(),result:hr("result",{mode:"json"}),progress:hr("progress",{mode:"json"}).$type(),source:hr("source"),metadata:hr("metadata",{mode:"json"}).$type().notNull(),status:hr("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:hr("lastError"),createdAt:Ar("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:Ar("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:Ar("startedAt"),completedAt:Ar("completedAt"),attemptId:hr("attemptId"),workerSlotId:hr("workerSlotId"),workerSessionId:hr("workerSessionId"),leaseExpiresAt:Ar("leaseExpiresAt"),attemptHeartbeatAt:Ar("attemptHeartbeatAt"),runtimeUpdatedAt:Ar("runtimeUpdatedAt")},(e)=>({queueReadyIdx:Qa("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:Qa("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:Qa("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:Qa("idx_job_queue_source").on(e.source)})),Ye=Lp("job_worker_sessions",{slotId:hr("slotId").primaryKey(),sessionId:hr("sessionId").notNull().unique(),startedAt:Ar("startedAt").notNull(),heartbeatAt:Ar("heartbeatAt").notNull(),expiresAt:Ar("expiresAt").notNull().default(0)},(e)=>({heartbeatIdx:Qa("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:Qa("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function kV(e){return Tx({url:e.url,schema:{jobQueue:X,jobWorkerSessions:Ye},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN"})}var EV=x(()=>{BO();jO()});class qO{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(){if(!this.finalizedRegistrations)throw Error("Job handler registrations are not finalized");return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}var IV=x(()=>{mx();nx();Wn();De();bx();ux();lo();Pp();gO();Gn();Ir();Ur();so()});class UO{tails=new Map;async run(e,t){let r=this.tails.get(e),i=()=>{},n=new Promise((o)=>{i=o});this.tails.set(e,n),await r;try{return await t()}finally{if(i(),this.tails.get(e)===n)this.tails.delete(e)}}}class FO{findDuplicate(e,t,r){if(!t||t==="none")return null;let i=this.filterByDeduplicationKey(e,r).sort((o,s)=>s.createdAt-o.createdAt||s.id.localeCompare(o.id)),n=i.find((o)=>o.status===je.PENDING)??null;if(t==="skip"||t==="replace")return n;return n??i[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((r)=>{let i=D_e.safeParse(r.metadata);return i.success&&i.data.deduplicationKey===t})}}var D_e;var AV=x(()=>{Ne();hs();D_e=f.looseObject({deduplicationKey:f.string().optional()})});class MO{db;transactionClient;databaseUrl;logger;deduplicator=new FO;writeRetryBudgetMs;constructor(e,t,r,i,n){this.db=e,this.transactionClient=t,this.databaseUrl=r,this.logger=i.child("JobQueueRepository"),this.writeRetryBudgetMs=n?.writeRetryBudgetMs??L_e}async insert(e){await this.db.insert(X).values(e)}async enqueueAtomic(e){return q_e.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs,r=1;for(;;){let i=await this.acquireWriteTransaction(e,t),n={prepared:!1},o=!1;try{let s=await this.decideEnqueue(i,e,()=>{n.prepared=!0});return o=!0,await i.commit(),s}catch(s){let a=o&&this.isSerializationConflict(s)&&!i.closed,c=!0;if(!i.closed)try{await i.rollback()}catch(l){c=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:l})}if(n.prepared)e.onInsertRollback?.();if(!a||!c)throw s;await this.waitForConflictRetry("commit",e,t,r,s),r++}finally{i.close()}}})}async decideEnqueue(e,t,r){let{jobData:i,strategy:n,deduplicationKey:o,beforeInsert:s}=t,a=n??"none",c=async()=>{await s?.(),r()},l=async()=>{await c(),await this.insertJob(e,i)};if(a==="none")return await l(),{kind:"inserted",jobId:i.id};let u=await this.getActiveDeduplicationCandidates(e,i.type),d=this.deduplicator.findDuplicate(u,a,o);if(!d)return await l(),{kind:"inserted",jobId:i.id};if(a==="skip")return{kind:"skipped",jobId:d.id};if(a==="coalesce"){if((await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),d.id,d.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${d.id}`);return{kind:"coalesced",jobId:d.id}}await c();let p=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[je.FAILED,"Replaced by newer job",p,p,d.id,je.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${d.id}`);return await this.insertJob(e,i),{kind:"replaced",jobId:i.id,replacedJobId:d.id}}async getActiveDeduplicationCandidates(e,t){return(await e.execute({sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,je.PENDING,je.PROCESSING]})).rows.map((i)=>this.parseDeduplicationCandidate(i))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:i,metadata:n}=e;if(typeof t!=="string"||r!==je.PENDING&&r!==je.PROCESSING||typeof i!=="number"&&typeof i!=="bigint"||typeof n!=="string")throw Error("Invalid active job row returned during atomic enqueue");let o=JSON.parse(n);return{id:t,status:r,createdAt:Number(i),metadata: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`\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]})).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,i,n){let o=Math.min(B_e*2**(i-1),j_e),s=o/2+Math.random()*(o/2);if(Date.now()+s>=r)throw this.transactionConflictError(e,t,i,n);await new Promise((a)=>setTimeout(a,s))}async retryOnConflict(e,t,r,i,n=Date.now()+this.writeRetryBudgetMs,o=1){try{return await r()}catch(s){if(!i(s))throw s;return await this.waitForConflictRetry(e,t,n,o,s),this.retryOnConflict(e,t,r,i,n,o+1)}}transactionConflictError(e,t,r,i){let n=t.strategy??"none",o=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: ${o})`,{cause:i})}isSerializationConflict(e){for(let t=e;t!==void 0;){let r=typeof t==="object"&&t!==null&&"code"in t?String(t.code):"",i=ct(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(r)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(i))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,r=Date.now(),i=ms){let n=r+i;await this.db.insert(Ye).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}).onConflictDoUpdate({target:Ye.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}})}async heartbeatWorkerSession(e,t,r=Date.now(),i=ms){return(await this.db.update(Ye).set({heartbeatAt:r,expiresAt:r+i}).where(kt(Qe(Ye.slotId,e),Qe(Ye.sessionId,t))).returning({slotId:Ye.slotId})).length===1}async endWorkerSession(e,t){return(await this.db.delete(Ye).where(kt(Qe(Ye.slotId,e),Qe(Ye.sessionId,t))).returning({slotId:Ye.slotId})).length===1}async complete(e,t,r){let i=Date.now(),o=(await this.db.update(X).set({status:je.COMPLETED,result:t,lastError:null,completedAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i)}).where(this.attemptWriteGuard(e,r)).returning({id:X.id})).length===1;if(o)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return o}async update(e,t,r){let n=(await this.db.update(X).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:X.id})).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,i=Date.now()){return(await this.db.update(X).set({attemptHeartbeatAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:X.id})).length===1}async renewAttemptLease(e,t,r,i){return(await this.db.update(X).set({attemptHeartbeatAt:r,leaseExpiresAt:r+i}).where(this.attemptWriteGuard(e,t)).returning({id:X.id})).length===1}async fail(e,t,r,i=Date.now()){let o=(await this.db.select({retryCount:X.retryCount,maxRetries:X.maxRetries,type:X.type,scheduledFor:X.scheduledFor,startedAt:X.startedAt,runtimeUpdatedAt:X.runtimeUpdatedAt}).from(X).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!o)return!1;let s=o.retryCount<o.maxRetries,a=s?o.retryCount+1:o.retryCount,c=Math.min(1000*2**o.retryCount,60000),l=s?i+c:o.scheduledFor;if((await this.db.update(X).set({status:s?je.PENDING:je.FAILED,retryCount:a,lastError:t.message,scheduledFor:l,completedAt:s?null:i,runtimeUpdatedAt:s?o.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),startedAt:s?null:o.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(kt(this.attemptWriteGuard(e,r),Qe(X.retryCount,o.retryCount))).returning({id:X.id})).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:c,scheduledFor:new Date(l).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:o.type,retryCount:o.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 i=(await this.db.update(X).set({status:je.FAILED,lastError:t,completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(kt(Qe(X.id,e.jobId),Qe(X.type,e.expectedType),ao(Qe(X.status,je.PENDING),Qe(X.status,je.PROCESSING)),Rn(X.attemptId),Rn(X.workerSlotId),Rn(X.workerSessionId),Rn(X.leaseExpiresAt),Rn(X.attemptHeartbeatAt),Rn(X.progress),Rn(X.result))).returning())[0]??null;if(i)this.logger.warn("Retired unowned legacy job",{jobId:i.id,type:i.type,reason:t});return i}async getStatus(e){return(await this.db.select().from(X).where(Qe(X.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(X).where(q`json_extract(${X.metadata}, '$.rootJobId') = ${e}`).orderBy(co(X.createdAt),co(X.id))}async getStatusByEntityId(e){return(await this.db.select().from(X).where(q`json_extract(${X.data}, '$.id') = ${e}`).orderBy(Wa(X.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:X.status,count:q`count(*)`}).from(X).groupBy(X.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let i=Number(r.count);t[r.status]=i,t.total+=i}return t}async getDiagnostics(e=Date.now()){let[t,r,i]=await Promise.all([this.db.select({type:X.type,status:X.status,count:q`count(*)`}).from(X).groupBy(X.type,X.status),this.db.select({oldestPendingAt:q`min(case when ${X.status} = ${je.PENDING} then ${X.createdAt} end)`,duePending:q`coalesce(sum(case when ${X.status} = ${je.PENDING} and ${X.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:q`min(case when ${X.status} = ${je.PENDING} and ${X.scheduledFor} <= ${e} then ${X.scheduledFor} end)`,latestClaimAt:q`max(${X.startedAt})`,oldestProcessingAt:q`min(case when ${X.status} = ${je.PROCESSING} then ${X.startedAt} end)`,staleLeaseCount:q`coalesce(sum(case when ${X.status} = ${je.PROCESSING} and ${X.leaseExpiresAt} is not null and ${X.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(X),this.db.select({total:q`count(*)`,active:q`coalesce(sum(case when ${Ye.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:q`coalesce(sum(case when ${Ye.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:q`max(${Ye.heartbeatAt})`}).from(Ye)]),n={pending:0,processing:0,completed:0,failed:0},o=t.map((l)=>{let u=Number(l.count);return n[l.status]+=u,{type:l.type,status:l.status,count:u}}),s=r[0],a=i[0],c=(l)=>l===null||l===void 0?null:Math.max(0,e-Number(l));return{totals:n,byType:o,oldestPendingAgeMs:c(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:c(s?.oldestDuePendingAt),latestClaimAgeMs:c(s?.latestClaimAt),oldestProcessingAgeMs:c(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(a?.total??0),active:Number(a?.active??0),stale:Number(a?.stale??0),latestHeartbeatAgeMs:c(a?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){return(await this.db.select().from(X).where(q`(${X.runtimeUpdatedAt}, ${X.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(co(X.runtimeUpdatedAt),co(X.id)).limit(t)).map((i)=>({job:i,cursor:{updatedAt:i.runtimeUpdatedAt??0,jobId:i.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.db.delete(X).where(kt(ao(Qe(X.status,je.COMPLETED),Qe(X.status,je.FAILED)),Va(X.completedAt,t)))).rowsAffected}async getActiveJobs(e){let t=ao(Qe(X.status,je.PENDING),Qe(X.status,je.PROCESSING)),r=e&&e.length>0?kt(t,As(X.type,e)):t;return this.db.select().from(X).where(r).orderBy(Wa(X.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?As(X.type,e):void 0;return this.db.select().from(X).where(r).orderBy(Wa(X.createdAt)).limit(t)}async getFailedJobs(e){let t=Qe(X.status,je.FAILED),r=e&&e.length>0?kt(t,As(X.type,e)):t;return this.db.select().from(X).where(r).orderBy(Wa(X.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:i,workerSessionId:n,leaseDurationMs:o,executableTypes:s}=e,a=this.db.select({slotId:Ye.slotId}).from(Ye).where(kt(Qe(Ye.slotId,i),Qe(Ye.sessionId,n),dx(Ye.expiresAt,t))),c=this.db.select({slotId:Ye.slotId}).from(Ye).where(kt(Qe(Ye.slotId,X.workerSlotId),Qe(Ye.sessionId,X.workerSessionId))),l=this.db.select({slotId:Ye.slotId}).from(Ye).where(kt(Qe(Ye.slotId,X.workerSlotId),Qe(Ye.sessionId,X.workerSessionId),Va(Ye.expiresAt,t))),u=kt(Qe(X.status,je.PROCESSING),ao(Rn(X.attemptId),fx(c),kt(Va(X.leaseExpiresAt,t),Op(l)))),d=q`${X.status} = ${je.PROCESSING} AND ${X.retryCount} + 1 > ${X.maxRetries}`,p=this.db.select({id:X.id}).from(X).where(kt(As(X.type,s),ao(kt(Qe(X.status,je.PENDING),Va(X.scheduledFor,t)),u))).orderBy(co(X.priority),co(X.createdAt)).limit(1),y=(await this.db.update(X).set({status:q`CASE WHEN ${d} THEN ${je.FAILED} ELSE ${je.PROCESSING} END`,retryCount:q`CASE WHEN ${X.status} = ${je.PROCESSING} THEN ${X.retryCount} + 1 ELSE ${X.retryCount} END`,lastError:q`CASE WHEN ${X.status} = ${je.PROCESSING} THEN 'Attempt lease expired' ELSE ${X.lastError} END`,startedAt:q`CASE WHEN ${d} THEN ${X.startedAt} ELSE ${t} END`,completedAt:q`CASE WHEN ${d} THEN ${t} ELSE NULL END`,attemptId:q`CASE WHEN ${d} THEN ${X.attemptId} ELSE ${r} END`,workerSlotId:q`CASE WHEN ${d} THEN ${X.workerSlotId} ELSE ${i} END`,workerSessionId:q`CASE WHEN ${d} THEN ${X.workerSessionId} ELSE ${n} END`,leaseExpiresAt:q`CASE WHEN ${d} THEN ${X.leaseExpiresAt} ELSE ${t+o} END`,attemptHeartbeatAt:q`CASE WHEN ${d} THEN ${X.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:q`CASE WHEN ${d} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${X.runtimeUpdatedAt} END`}).where(kt(As(X.id,p),Op(a))).returning())[0];if(y?.status!==je.PROCESSING)return null;return this.logger.debug("Job claimed",{jobId:y.id,attemptId:y.attemptId,workerSlotId:i,workerSessionId:n}),y}nextRuntimeUpdatedAt(e){return q`max(${e}, coalesce((select max(${X.runtimeUpdatedAt}) from ${X}), 0) + 1)`}attemptWriteGuard(e,t){return t?kt(Qe(X.id,e),Qe(X.status,je.PROCESSING),Qe(X.attemptId,t)):kt(Qe(X.id,e),Rn(X.attemptId),ao(Qe(X.status,je.PENDING),Qe(X.status,je.PROCESSING)))}}var L_e=2000,B_e=5,j_e=40,q_e;var $V=x(()=>{IV();jO();hs();rp();AV();q_e=new UO});import{AsyncLocalStorage as U_e}from"async_hooks";class Fp{storage=new U_e;static createFresh(){return new Fp}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let i=Bo.parse(e),n=F_e(i);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function F_e(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var ZO=x(()=>{jo()});class Mp{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${to()}`;directWorkerSessionId=to();directLeaseDurationMs;directSessionStart=null;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new Mp(e,t??fn.getInstance(),r)}constructor(e,t,r){let{db:i,client:n,url:o}=kV(e);this.client=n,this.databaseUrl=o,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??Fp.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new qO(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new MO(i,n,o,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 Ox(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:i}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let o=n.validateAndParse(r);if(o===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=to(),c=i?.rootJobId??this.operationContext.current()?.provenance.rootJobId??a,l=this.createJobProvenance(a,c,i),u=i?.metadata??{operationType:"data_processing"},{provenance:d,...p}=u,m={id:a,type:t,data:JSON.stringify(o),status:je.PENDING,priority:i?.priority??0,maxRetries:i?.maxRetries??3,retryCount:0,source:i?.source??null,metadata:{...p,...i?.deduplicationKey&&{deduplicationKey:i.deduplicationKey},rootJobId:c,provenance:l},createdAt:s,scheduledFor:i?.delayMs?s+i.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null},y,g=()=>{y?.rollback(),y=void 0};try{let b=await this.repository.enqueueAtomic({jobData:m,strategy:i?.deduplication,deduplicationKey:i?.deduplicationKey,beforeInsert:async()=>{y=await this.projectionAdmission?.reserveJobAdmission(l)},onInsertRollback:g});if(y?.commit(),y=void 0,b.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:b.jobId});else if(b.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:b.jobId});else{if(b.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:b.replacedJobId});this.logger.debug("Job enqueued",{id:b.jobId,type:t,priority:m.priority,rootJobId:m.metadata.rootJobId})}return b.jobId}catch(b){throw g(),this.logger.error("Failed to enqueue job",{type:t,error:ct(b)}),b}}createJobProvenance(e,t,r){let i=this.operationContext.current(),n=r?.metadata.provenance??i?.provenance,o=n?.rootJobId===t?n:void 0,s=i?.provenance.rootJobId===t?i.operationId:void 0,a=r?.projection,c=a?[...o?.projectionLineage??[],a.id]:[...o?.projectionLineage??[]],l=a?.id??o?.projectionId;return Bo.parse({rootJobId:t,causationId:s??o?.causationId??e,...l?{projectionId:l}:{},projectionLineage:c,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:o?.sourceEntity?{sourceEntity:o.sourceEntity}:{},derivationDepth:c.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let r=e??await this.getDirectClaimOptions(),i=Date.now(),n=await this.repository.claimNextReady({...r,now:i,attemptId:to(),executableTypes:t});if(!n)return null;return this.logger.debug("Job dequeued",{id:n.id,type:n.type,priority:n.priority,retryCount:n.retryCount,attemptId:n.attemptId,workerSlotId:n.workerSlotId,workerSessionId:n.workerSessionId}),n}async startWorkerSession(e,t,r=ms){await this.repository.startWorkerSession(e,t,Date.now(),r)}heartbeatWorkerSession(e,t,r=ms){return this.repository.heartbeatWorkerSession(e,t,Date.now(),r)}endWorkerSession(e,t){return this.repository.endWorkerSession(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)}retireUnownedActiveJob(e){return this.repository.retireUnownedActiveJob(e)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.directWorkerSlotId,this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs),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,i=Date.now()+(e.timeoutMs??30000),n=async(o)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),c=s.pending===0&&s.processing===0?o??Date.now():null;if(c!==null&&Date.now()-c>=t)return;if(Date.now()>=i)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(r),n(c)};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 CV=x(()=>{ep();YC();rp();hs();BO();EV();$V();jo();ZO()});var HO=()=>{};var TV=x(()=>{ep();hs();rp();hs();HO();ZO()});var OV=x(()=>{hs();HO()});var qYe;var RV=x(()=>{jo();Ne();tp();qYe=f.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},f.record(f.string(),f.unknown()))});var MYe;var PV=x(()=>{Ne();MYe=f.record(f.string(),f.unknown())});var zV=x(()=>{jo();ep()});var NV=x(()=>{CV();TV();OV();RV();PV();rp();hs();tp();zV()});var JO={};tr(JO,{LEGACY_PROJECTION_JOB_TYPES:()=>LV,LEGACY_PROJECTION_RETIREMENT_REASON:()=>jV,legacyProjectionJobTypeSchema:()=>BV,retireLegacyProjectionJob:()=>Q_e});import{existsSync as V_e}from"fs";import{resolve as W_e}from"path";function DV(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 G_e(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 Q_e(e){let t=W_e(e.databasePath);if(!V_e(t))throw Error(`Job database does not exist: ${t}`);let r=BV.parse(e.jobType),i=Mp.createFresh({url:`file:${t}`});try{let n=await i.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(G_e(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:DV(n),retired:!1}}let o=`retire:${n.id}`;if(e.confirmation!==o)throw Error(`Refusing to retire ${n.id}; expected --confirm ${o}`);let s=await i.retireUnownedActiveJob({jobId:n.id,expectedType:r,reason:jV,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:DV(s),retired:!0}}finally{i.close()}}var LV,BV,jV="Retired legacy projection job superseded by scheduler-owned projections";var KO=x(()=>{NV();Ne();LV=["conversation-memory:project","skill:project","swot:derive","topic:project"],BV=f.enum(LV)});function er(e,t,r,i,n){return UV.parse({id:e,operation:t,count:r,targetProbeCount:i,settleMs:n})}function WO(e){return Hp.parse(structuredClone(tke[e]))}function Jp(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 Px(e,t={}){let r=t.fetchImpl??fetch,i=t.now??(()=>new Date),n=t.timeoutMs??20000,o=i(),s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let c=await r(e,{method:"GET",signal:s.signal});return await c.arrayBuffer(),VO.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:c.status,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:c.ok})}catch(c){return VO.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:!1,error:rke(c)})}finally{clearTimeout(a)}}async function GO(e,t){let r=Hp.parse(e),i=[],n,o=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(c){n=`monitor: ${Rx(c)}`}if(!n)for(let c of r.phases)try{let l=FV.parse(await t.executePhase(c,o));if(i.push(l),!l.success){n=`${c.id}: ${l.error??"phase failed"}`;break}}catch(l){let u=Rx(l);i.push({id:c.id,operation:c.operation,count:c.count,success:!1,error:u}),n=`${c.id}: ${u}`;break}}finally{try{if(s=MV.parse(await t.cleanup(o)),!s.success&&!n)n=s.error??"cleanup failed"}catch(c){let l=Rx(c);s={success:!1,probesRemaining:0,error:l},n??=`cleanup: ${l}`}try{a=ZV.parse(await t.stopMonitoring())}catch(c){let l=Rx(c);a={health:[],runtime:[]},n??=`monitor: ${l}`}}return n??=JV(a,r.maximumExternalAiCalls??0),HV.parse({profile:r.profile,success:n===void 0&&i.length===r.phases.length&&s.success,baseline:o,phases:i,cleanup:s,metrics:a,...n?{failure:n}:{}})}function JV(e,t=0){let r=e.health.find((o)=>!o.ok);if(r)return`health: ${r.endpoint} unavailable`;let i=e.externalAiCalls??0;if(i>t)return t===0?`external AI: observed ${i} call(s)`:`external AI: observed ${i} 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 rke(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function Rx(e){return ct(e)}var Zp,qV,UV,Hp,Y_e,VO,X_e,FV,MV,eke,ZV,HV,tke;var zx=x(()=>{Ne();Zp=f.enum(["regression","load","stress"]),qV=f.enum(["add","update","rename","delete"]),UV=f.object({id:f.string().min(1),operation:qV,count:f.number().int().positive().max(700),targetProbeCount:f.number().int().min(0).max(700),settleMs:f.number().int().nonnegative().max(300000)}),Hp=f.object({profile:Zp,maximumProbeCount:f.number().int().positive().max(700),maximumExternalAiCalls:f.number().int().nonnegative().max(1e4).optional(),phases:f.array(UV).min(1)}),Y_e=f.object({entities:f.number().int().nonnegative(),notes:f.number().int().nonnegative(),version:f.string().min(1)}),VO=f.object({timestamp:f.iso.datetime(),endpoint:f.string().startsWith("/"),status:f.number().int().nonnegative(),durationMs:f.number().nonnegative(),ok:f.boolean(),error:f.string().optional()}),X_e=f.object({timestamp:f.iso.datetime(),cpuPercent:f.number().nonnegative(),memoryPercent:f.number().nonnegative(),pids:f.number().int().nonnegative()}),FV=f.object({id:f.string().min(1),operation:qV,count:f.number().int().positive(),success:f.boolean(),commitLatencyMs:f.number().nonnegative().optional(),persistenceLatencyMs:f.number().nonnegative().optional(),error:f.string().optional()}),MV=f.object({success:f.boolean(),probesRemaining:f.number().int().nonnegative(),finalEntities:f.number().int().nonnegative().optional(),finalNotes:f.number().int().nonnegative().optional(),contentTreeRestored:f.boolean().optional(),error:f.string().optional()}),eke=f.object({status:f.string(),restartCount:f.number().int().nonnegative(),oomKilled:f.boolean()}),ZV=f.object({health:f.array(VO),runtime:f.array(X_e),externalAiCalls:f.number().int().nonnegative().optional(),container:eke.optional()}),HV=f.object({profile:Zp,success:f.boolean(),baseline:Y_e,phases:f.array(FV),cleanup:MV,metrics:ZV,failure:f.string().optional()}),tke={regression:{profile:"regression",maximumProbeCount:20,phases:[er("add20","add",20,20,0),er("update20","update",20,20,30000),er("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[er("add50","add",50,50,0),er("add150","add",100,150,0),er("add350","add",200,350,0),er("update350a","update",350,350,45000),er("rename100","rename",100,350,45000),er("update350b","update",350,350,45000),er("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[er("add50","add",50,50,0),er("add150","add",100,150,0),er("add350","add",200,350,0),er("add700","add",350,700,0),er("update700a","update",700,700,45000),er("rename200","rename",200,700,45000),er("update700b","update",700,700,45000),er("delete700","delete",700,0,150000)]}}});import{spawn as nke}from"child_process";async function KV(e,t,r,i){let n=await e(t,r,i);if(n.exitCode!==0)throw Ei(t,r,n);return n}function Ei(e,t,r){let i=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${i?`: ${i}`:""}`)}var mo=async(e,t,r={})=>new Promise((i,n)=>{let o=nke(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",(c)=>{s+=c}),o.stderr.on("data",(c)=>{a+=c}),o.on("error",n),o.on("close",(c)=>{i({exitCode:c??1,stdout:s,stderr:a})}),o.stdin.end(r.stdin)});var Kp=()=>{};class Iu{#e;#t;dir;constructor(e,t,r){this.#e=e,this.dir=t,this.#t=r}static async clone(e,t,r,i){let n=new Iu(e,r,i);return await KV(e,"git",["-c","credential.helper=","-c",`credential.helper=${VV}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",VV]),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 Ei("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 VV='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var WV=x(()=>{Kp()});function Vp(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class QO{#e;#t=[];#r=[];#n=new Set(["/health/ready"]);#i=!0;#o;#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 Px(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:5000})).status!==404)this.#n.add(e)}start(){this.#i=!1,this.#a=void 0,this.#c=this.#t.length,this.#l=void 0,this.#s=this.#e.now().toISOString(),this.#o=Promise.all([this.#f(),this.#m()]).then(()=>{return}).catch((e)=>{this.#a=e,this.#i=!0})}async stop(){this.#i=!0,await this.#o}async waitForHealthSnapshot(e){return this.waitForEntityBaseline(void 0,void 0,e)}async waitForEntityBaseline(e,t,r){let i=this.#e.now().getTime();while(this.#e.now().getTime()-i<r){let n=await this.fetchHealthPayload();if(this.#d(n,e,t))return n;await this.#e.sleep(5000)}return}async waitForStableEntityBaseline(e,t,r){let i=this.#e.now().getTime(),n=0;while(this.#e.now().getTime()-i<r){let o=await this.fetchHealthPayload();if(this.#d(o,e,t)){if(n+=1,n===2)return o}else n=0;await this.#e.sleep(5000)}return}async fetchHealthPayload(){let e=this.#e.now(),t=new AbortController,r=setTimeout(()=>t.abort(),20000);try{let i=await this.#e.fetchImpl(`https://${this.#e.domain}/health/operate`,{signal:t.signal}),n=await i.text();if(this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:i.status,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:i.ok}),!i.ok)return;return ike.parse(JSON.parse(n)).app}catch(i){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:i instanceof Error?`${i.name}: ${i.message}`:String(i)});return}finally{clearTimeout(r)}}#d(e,t,r){return e!==void 0&&(t===void 0||Vp(e)===t)&&(r===void 0||e.entities===r)}async#f(){while(!this.#i){for(let e of this.#n)this.#t.push(await Px(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:20000}));await this.#e.sleep(4000)}}async#m(){while(!this.#i){let e=await this.#e.sampleRuntime();if(e)this.#r.push(e);await this.#e.sleep(1000)}}}var ike;var GV=x(()=>{Ne();zx();ike=f.object({status:f.literal("ready"),operationalStatus:f.literal("operational"),app:f.object({version:f.string(),entities:f.number().int().nonnegative(),entityCounts:f.array(f.object({entityType:f.string(),count:f.number().int().nonnegative()})).default([])})})});var Nx={};tr(Nx,{applyDirectorySyncStressPhase:()=>n7,cleanupDirectorySyncStress:()=>e7,listProbeFiles:()=>Xa,parseStressRuntimeSample:()=>i7,removeProbeFiles:()=>iR,runDeployedDirectorySyncStress:()=>YV,runStressCommand:()=>mo,verifyDirectorySyncStressAccess:()=>XV});import{chmod as oke,mkdir as XO,mkdtemp as eR,readFile as ske,readdir as ake,rename as cke,rm as Gp,writeFile as Xn}from"fs/promises";import{tmpdir as tR}from"os";import{join as xt,resolve as rR}from"path";async function YV(e){let t=e.now??(()=>new Date),r=t().toISOString(),i=oR(r),n=rR(e.artifactsDir??xt(e.rootDir,".brains-ops","stress",i));await XO(n,{recursive:!0});let{pilot:o,user:s}=await nR(e.rootDir,e.handle);Jp({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=Zp.parse(e.profile),c=e.plan?Hp.parse(e.plan):WO(a);if(c.profile!==a)throw Error(`Directory-sync stress plan profile ${c.profile} does not match requested profile ${a}`);if((c.maximumExternalAiCalls??0)===0)r7(s);let l=lke.parse(e.env??process.env),u=new t7({runId:i,artifactsDir:n,user:s,githubOrg:o.githubOrg,serverLabel:`${o.contentRepoPrefix}${s.handle}`,environment:l,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??mo,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),d;try{d=await GO(c,u)}finally{await u.dispose()}let p={runId:i,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:d};return await mke(p),p}async function XV(e){let r=(e.now??(()=>new Date))().toISOString(),i=oR(r),n=rR(e.artifactsDir??xt(e.rootDir,".brains-ops","stress",`access-check-${i}`));await XO(n,{recursive:!0});let{pilot:o,user:s}=await nR(e.rootDir,e.handle);Jp({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),r7(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let c=await eR(xt(tR(),"brains-ops-directory-sync-access-check-"));try{let l=await Iu.clone(e.commandRunner??mo,`${o.githubOrg}/${s.contentRepo}`,xt(c,"content"),a),u=await l.output(["rev-parse","HEAD"]);await l.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${i}`]);let d={success:!0,artifactsDir:n,checkedAt:r,remoteHead:u,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`}};return await Xn(xt(n,"access-check.json"),`${JSON.stringify(d,null,2)}
|
|
453
|
+
`;await t.run(n);let s=(await t.values(q`SELECT id, hash, created_at FROM ${q.identifier(i)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await t.transaction(async(a)=>{for(let c of e)if(!s||Number(s[2])<c.folderMillis){for(let l of c.sql)await a.run(q.raw(l));await a.run(q`INSERT INTO ${q.identifier(i)} ("hash", "created_at") VALUES(${c.hash}, ${c.folderMillis})`)}})}}});var SO;var nV=x(()=>{De();SO=class SO{static[K]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}});function Sx(e,t){return(r,i,...n)=>{let o=[i,...n].map((s)=>({type:e,isAll:t,rightSelect:s}));for(let s of o)if(!Cp(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(o)}}var Yn,iV,wO,C_e=()=>({union:T_e,unionAll:O_e,intersect:R_e,except:P_e}),T_e,O_e,R_e,P_e;var vO=x(()=>{De();nV();lo();Ga();mr();Gn();Ir();Ur();so();wu();Bp();Yn=class Yn{static[K]="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(ce(e,vt))r=Object.fromEntries(Object.keys(e._.selectedFields).map((i)=>[i,e[i]]));else if(ce(e,po))r=e[_t].selectedFields;else if(ce(e,$e))r={};else r=lx(e);return new wO({table:e,fields:r,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}};iV=class iV extends SO{static[K]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:r,session:i,dialect:n,withList:o,distinct:s}){super();this.config={withList:o,table:e,fields:{...t},distinct:s,setOperators:[]},this.isPartialSelect=r,this.session=i,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=Tp(e),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let a of Qn(e))this.usedTables.add(a)}getUsedTables(){return[...this.usedTables]}createJoin(e){return(t,r)=>{let i=this.tableName,n=Tp(t);for(let o of Qn(t))this.usedTables.add(o);if(typeof n==="string"&&this.config.joins?.some((o)=>o.alias===n))throw Error(`Alias "${n}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof i==="string")this.config.fields={[i]:this.config.fields};if(typeof n==="string"&&!ce(t,$e)){let o=ce(t,vt)?t._.selectedFields:ce(t,Tn)?t[_t].selectedFields:t[we.Symbol.Columns];this.config.fields[n]=o}}if(typeof r==="function")r=r(new Proxy(this.config.fields,new bt({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(([o])=>[o,!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(([o])=>[o,!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 i=typeof r==="function"?r(C_e()):r;if(!Cp(this.getSelectedFields(),i.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:i}),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 bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=e,this}having(e){if(typeof e==="function")e=e(new Proxy(this.config.fields,new bt({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 bt({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 bt({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(...Qn(this.config.table)),this.config.joins)for(let r of this.config.joins)t.push(...Qn(r.table));return new Proxy(new vt(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new bt({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}};wO=class wO extends iV{static[K]="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=On(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()}};N9(wO,[Fr]);T_e=Sx("union",!1),O_e=Sx("union",!0),R_e=Sx("intersect",!1),P_e=Sx("except",!1)});var Ya;var wx=x(()=>{De();Ga();xx();Gn();vO();Ya=class Ya{static[K]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=ce(e,_u)?e:void 0,this.dialectConfig=ce(e,_u)?void 0:e}$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(r);return new Proxy(new Ip(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...e){let t=this;function r(n){return new Yn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function i(n){return new Yn({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:!0})}return{select:r,selectDistinct:i}}select(e){return new Yn({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Yn({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new bO(this.dialectConfig);return this.dialect}}});var vx,_O;var oV=x(()=>{De();lo();mr();uo();Ir();Ur();wu();wx();vx=class vx{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[K]="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 i={},n=this.table[we.Symbol.Columns];for(let o of Object.keys(r)){let s=r[o];i[o]=ce(s,$e)?s:new mn(s,n[o])}return i});return new _O(this.table,t,this.session,this.dialect,this.withList)}select(e){let t=typeof e==="function"?e(new Ya):e;if(!ce(t,$e)&&!Cp(this.table[sx],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 _O(this.table,t,this.session,this.dialect,this.withList,!0)}};_O=class _O extends Fr{constructor(e,t,r,i,n,o){super();this.session=r,this.dialect=i,this.config={table:e,values:t,withList:n,select:o}}static[K]="SQLiteInsert";config;returning(e=this.config.table[Ft.Symbol.Columns]){return this.config.returning=On(e),this}onConflictDoNothing(e={}){if(!this.config.onConflict)this.config.onConflict=[];if(e.target===void 0)this.config.onConflict.push(q` on conflict do nothing`);else{let t=Array.isArray(e.target)?q`${e.target}`:q`${[e.target]}`,r=e.where?q` where ${e.where}`:q``;this.config.onConflict.push(q` 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?q` where ${e.where}`:void 0,r=e.targetWhere?q` where ${e.targetWhere}`:void 0,i=e.setWhere?q` where ${e.setWhere}`:void 0,n=Array.isArray(e.target)?q`${e.target}`:q`${[e.target]}`,o=this.dialect.buildUpdateSet(this.config.table,cx(this.config.table,e.set));return this.config.onConflict.push(q` on conflict ${n}${r} do update set ${o}${t}${i}`),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:Qn(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 _x,sV;var aV=x(()=>{De();lo();Ga();uo();Gn();Ir();Ur();so();wu();Bp();_x=class _x{constructor(e,t,r,i){this.table=e,this.session=t,this.dialect=r,this.withList=i}static[K]="SQLiteUpdateBuilder";set(e){return new sV(this.table,cx(this.table,e),this.session,this.dialect,this.withList)}};sV=class sV extends Fr{constructor(e,t,r,i,n){super();this.session=r,this.dialect=i,this.config={set:t,table:e,withList:n,joins:[]}}static[K]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return(t,r)=>{let i=Tp(t);if(typeof i==="string"&&this.config.joins.some((n)=>n.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(typeof r==="function"){let n=this.config.from?ce(t,Ft)?t[we.Symbol.Columns]:ce(t,vt)?t._.selectedFields:ce(t,po)?t[_t].selectedFields:void 0:void 0;r=r(new Proxy(this.config.table[we.Symbol.Columns],new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new bt({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:r,table:t,joinType:e,alias:i}),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[we.Symbol.Columns],new bt({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[Ft.Symbol.Columns]){return this.config.returning=On(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:Qn(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 kO=x(()=>{YK();oV();wx();vO();aV()});var jp;var cV=x(()=>{De();mr();jp=class jp extends $e{constructor(e){super(jp.buildEmbeddedCount(e.source,e.filters).queryChunks);this.params=e,this.session=e.session,this.sql=jp.buildCount(e.source,e.filters)}sql;static[K]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return q`(select count(*) from ${e}${q.raw(" where ").if(t)}${t})`}static buildCount(e,t){return q`select count(*) from ${e}${q.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 IO,kx,EO;var lV=x(()=>{De();lo();Pp();IO=class IO{constructor(e,t,r,i,n,o,s,a){this.mode=e,this.fullSchema=t,this.schema=r,this.tableNamesMap=i,this.table=n,this.tableConfig=o,this.dialect=s,this.session=a}static[K]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new EO(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many"):new kx(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?e:{},"many")}findFirst(e){return this.mode==="sync"?new EO(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new kx(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}};kx=class kx extends Fr{constructor(e,t,r,i,n,o,s,a,c){super();this.fullSchema=e,this.schema=t,this.tableNamesMap=r,this.table=i,this.tableConfig=n,this.dialect=o,this.session=s,this.config=a,this.mode=c}static[K]="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,(i,n)=>{let o=i.map((s)=>px(this.schema,this.tableConfig,s,t.selection,n));if(this.mode==="first")return o[0];return o})}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()}};EO=class EO extends kx{static[K]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}});var ku;var uV=x(()=>{De();lo();ku=class ku extends Fr{constructor(e,t,r,i,n){super();this.execute=e,this.getSQL=t,this.dialect=i,this.mapBatchResult=n,this.config={action:r}}static[K]="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 qp;var Ex=x(()=>{De();Ga();mr();kO();Gn();cV();lV();uV();qp=class qp{constructor(e,t,r,i){this.resultKind=e,this.dialect=t,this.session=r,this._=i?{schema:i.schema,fullSchema:i.fullSchema,tableNamesMap:i.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let n=this.query;if(this._.schema)for(let[o,s]of Object.entries(this._.schema))n[o]=new IO(e,i.fullSchema,this._.schema,this._.tableNamesMap,i.fullSchema[o],s,t,r);this.$cache={invalidate:async(o)=>{}}}static[K]="BaseSQLiteDatabase";query;$with=(e,t)=>{let r=this;return{as:(n)=>{if(typeof n==="function")n=n(new Ya(r.dialect));return new Proxy(new Ip(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,!0),new bt({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(e,t){return new jp({source:e,filters:t,session:this.session})}with(...e){let t=this;function r(a){return new Yn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e})}function i(a){return new Yn({fields:a??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function n(a){return new _x(a,t.session,t.dialect,e)}function o(a){return new vx(a,t.session,t.dialect,e)}function s(a){return new yx(a,t.session,t.dialect,e)}return{select:r,selectDistinct:i,update:n,insert:o,delete:s}}select(e){return new Yn({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Yn({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(e){return new _x(e,this.session,this.dialect)}$cache;insert(e){return new vx(e,this.session,this.dialect)}delete(e){return new yx(e,this.session,this.dialect)}run(e){let t=typeof e==="string"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new ku(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"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new ku(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"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new ku(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"?q.raw(e):e.getSQL();if(this.resultKind==="async")return new ku(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 AO(e,t){let r=`${e}-${JSON.stringify(t)}`,n=new TextEncoder().encode(r),o=await crypto.subtle.digest("SHA-256",n);return[...new Uint8Array(o)].map((c)=>c.toString(16).padStart(2,"0")).join("")}var dV,Up;var $O=x(()=>{De();dV=class dV{static[K]="Cache"};Up=class Up extends dV{strategy(){return"all"}static[K]="NoopCache";async get(e){return}async put(e,t,r,i){}async onMutate(e){}}});var fV=x(()=>{$O()});var pV=()=>{};var mV,CO,TO,OO;var RO=x(()=>{$O();De();bx();lo();Ex();mV=class mV extends Fr{constructor(e){super();this.resultCb=e}static[K]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}};CO=class CO{constructor(e,t,r,i,n,o){if(this.mode=e,this.executeMethod=t,this.query=r,this.cache=i,this.queryMetadata=n,this.cacheConfig=o,i&&i.strategy()==="all"&&o===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[K]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e,t,r){if(this.cache===void 0||ce(this.cache,Up)||this.queryMetadata===void 0)try{return await r()}catch(i){throw new fo(e,t,i)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await r()}catch(i){throw new fo(e,t,i)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[i]=await Promise.all([r(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return i}catch(i){throw new fo(e,t,i)}if(!this.cacheConfig)try{return await r()}catch(i){throw new fo(e,t,i)}if(this.queryMetadata.type==="select"){let i=await this.cache.get(this.cacheConfig.tag??await AO(e,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(i===void 0){let n;try{n=await r()}catch(o){throw new fo(e,t,o)}return await this.cache.put(this.cacheConfig.tag??await AO(e,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return i}try{return await r()}catch(i){throw new fo(e,t,i)}}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 mV(()=>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)}}};TO=class TO{constructor(e){this.dialect=e}static[K]="SQLiteSession";prepareOneTimeQuery(e,t,r,i,n,o,s){return this.prepareQuery(e,t,r,i,n,o,s)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(r){throw new vu({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")}};OO=class OO extends qp{constructor(e,t,r,i,n=0){super(e,t,r,i);this.schema=i,this.nestedIndex=n}static[K]="SQLiteTransaction";rollback(){throw new hO}}});var PO,z_e,N_e,Ix;var hV=x(()=>{De();Ga();Ur();wx();uo();Bp();PO=class PO{constructor(e){this.name=e}static[K]="SQLiteViewBuilderCore";config={}};z_e=class z_e extends PO{static[K]="SQLiteViewBuilder";as(e){if(typeof e==="function")e=e(new Ya);let t=new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}),r=e.getSelectedFields();return new Proxy(new Ix({config:{name:this.name,schema:void 0,selectedFields:r,query:e.getSQL().inlineParams()}}),t)}};N_e=class N_e extends PO{static[K]="SQLiteManualViewBuilder";columns;constructor(e,t){super(e);this.columns=lx(Lp(e,t))}existing(){return new Proxy(new Ix({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:void 0}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}as(e){return new Proxy(new Ix({config:{name:this.name,schema:void 0,selectedFields:this.columns,query:e.inlineParams()}}),new bt({alias:this.name,sqlBehavior:"error",sqlAliasedBehavior:"alias",replaceOriginalName:!0}))}};Ix=class Ix extends po{static[K]="SQLiteView";constructor({config:e}){super(e)}}});var zO=x(()=>{pV();HK();yO();Ex();xx();iO();WK();QK();kO();RO();uo();sO();wu();hV()});function gV(e){return Object.keys(e).reduce((t,r)=>{if(Object.prototype.propertyIsEnumerable.call(e,r))t[r]=e[r];return t},{})}function Ax(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 $x,NO,yV;var DO=x(()=>{fV();De();ux();mr();zO();RO();Ur();$x=class $x extends TO{constructor(e,t,r,i,n){super(t);this.client=e,this.schema=r,this.options=i,this.tx=n,this.logger=i.logger??new QT,this.cache=i.cache??new Up}static[K]="LibSQLSession";logger;cache;prepareQuery(e,t,r,i,n,o,s){return new yV(this.client,e,this.logger,this.cache,o,s,t,this.tx,r,i,n)}async batch(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.batch(r)).map((n,o)=>t[o].mapResult(n,!0))}async migrate(e){let t=[],r=[];for(let n of e){let o=n._prepare(),s=o.getQuery();t.push(o),r.push({sql:s.sql,args:s.params})}return(await this.client.migrate(r)).map((n,o)=>t[o].mapResult(n,!0))}async transaction(e,t){let r=await this.client.transaction(),i=new $x(this.client,this.dialect,this.schema,this.options,r),n=new NO("async",this.dialect,i,this.schema);try{let o=await e(n);return await r.commit(),o}catch(o){throw await r.rollback(),o}}extractRawAllValueFromBatchResult(e){return e.rows}extractRawGetValueFromBatchResult(e){return e.rows[0]}extractRawValuesValueFromBatchResult(e){return e.rows}};NO=class NO extends OO{static[K]="LibSQLTransaction";async transaction(e){let t=`sp${this.nestedIndex}`,r=new NO("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(q.raw(`savepoint ${t}`));try{let i=await e(r);return await this.session.run(q.raw(`release savepoint ${t}`)),i}catch(i){throw await this.session.run(q.raw(`rollback to savepoint ${t}`)),i}}};yV=class yV extends CO{constructor(e,t,r,i,n,o,s,a,c,l,u){super("async",c,t,i,n,o);this.client=e,this.logger=r,this.fields=s,this.tx=a,this._isResponseInArrayMode=l,this.customResultMapper=u,this.customResultMapper=u,this.fields=s}static[K]="LibSQLPreparedQuery";async run(e){let t=$p(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:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=$p(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapAllResult(u))})}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)=>gV(r));if(this.customResultMapper)return this.customResultMapper(e,Ax);return e.map((r)=>VT(this.fields,Array.prototype.slice.call(r).map((i)=>Ax(i)),this.joinsNotNullableMap))}async get(e){let{fields:t,logger:r,query:i,tx:n,client:o,customResultMapper:s}=this;if(!t&&!s){let c=$p(i.params,e??{});return r.logQuery(i.sql,c),await this.queryWithCache(i.sql,c,async()=>{let l={sql:i.sql,args:c};return(n?n.execute(l):o.execute(l)).then(({rows:u})=>this.mapGetResult(u))})}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 gV(r);if(!r)return;if(this.customResultMapper)return this.customResultMapper(e,Ax);return VT(this.fields,Array.prototype.slice.call(r).map((i)=>Ax(i)),this.joinsNotNullableMap)}async values(e){let t=$p(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:i})=>i)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}});function Eu(e,t={}){let r=new xO({casing:t.casing}),i;if(t.logger===!0)i=new GT;else if(t.logger!==!1)i=t.logger;let n;if(t.schema){let a=sK(t.schema,cK);n={fullSchema:t.schema,schema:a.tables,tableNamesMap:a.tableNamesMap}}let o=new $x(e,r,n,{logger:i,cache:t.cache},void 0),s=new bV("async",r,o,n);if(s.$client=e,s.$cache=t.cache,s.$cache)s.$cache.invalidate=t.cache?.onMutate;return s}var bV;var xV=x(()=>{De();ux();Pp();Ex();xx();DO();bV=class bV extends qp{static[K]="LibSQLDatabase";async batch(e){return this.session.batch(e)}}});function Cx(...e){if(typeof e[0]==="string"){let t=Ja({url:e[0]});return Eu(t,e[1])}if(D9(e[0])){let{connection:t,client:r,...i}=e[0];if(r)return Eu(r,i);let n=typeof t==="string"?Ja({url:t}):Ja(t);return Eu(n,i)}return Eu(e[0],e[1])}var SV=x(()=>{LT();Ur();xV();((e)=>{function t(r){return Eu({},r)}e.mock=t})(Cx||(Cx={}))});var wV=x(()=>{SV();DO()});function vV(e){if(e.authToken!==void 0)return e.authToken;if(e.authTokenEnv===void 0)return;return process.env[e.authTokenEnv]}function Tx(e){let{url:t,schema:r}=e,i=vV(e),n=i?Ja({url:t,authToken:i}):Ja({url:t});return{db:Cx(n,{schema:r}),client:n,url:t}}async function Ox(e,t){if(!t.startsWith("file:"))return;await e.execute("PRAGMA busy_timeout = 5000"),await e.execute("PRAGMA journal_mode = WAL")}var LO=x(()=>{LT();wV()});var _V=x(()=>{YC();LO()});var BO=x(()=>{LO();_V()});var X,Ye;var jO=x(()=>{zO();ep();X=Lp("job_queue",{id:hr("id").primaryKey().$defaultFn(()=>to()),type:hr("type").notNull(),data:hr("data").notNull(),result:hr("result",{mode:"json"}),progress:hr("progress",{mode:"json"}).$type(),source:hr("source"),metadata:hr("metadata",{mode:"json"}).$type().notNull(),status:hr("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:hr("lastError"),createdAt:Ar("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:Ar("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:Ar("startedAt"),completedAt:Ar("completedAt"),attemptId:hr("attemptId"),workerSlotId:hr("workerSlotId"),workerSessionId:hr("workerSessionId"),leaseExpiresAt:Ar("leaseExpiresAt"),attemptHeartbeatAt:Ar("attemptHeartbeatAt"),runtimeUpdatedAt:Ar("runtimeUpdatedAt")},(e)=>({queueReadyIdx:Qa("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:Qa("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:Qa("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:Qa("idx_job_queue_source").on(e.source)})),Ye=Lp("job_worker_sessions",{slotId:hr("slotId").primaryKey(),sessionId:hr("sessionId").notNull().unique(),startedAt:Ar("startedAt").notNull(),heartbeatAt:Ar("heartbeatAt").notNull(),expiresAt:Ar("expiresAt").notNull().default(0)},(e)=>({heartbeatIdx:Qa("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:Qa("idx_job_worker_sessions_expires").on(e.expiresAt)}))});function kV(e){return Tx({url:e.url,schema:{jobQueue:X,jobWorkerSessions:Ye},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN"})}var EV=x(()=>{BO();jO()});class qO{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(){if(!this.finalizedRegistrations)throw Error("Job handler registrations are not finalized");return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}var IV=x(()=>{mx();nx();Wn();De();bx();ux();lo();Pp();gO();Gn();Ir();Ur();so()});class UO{tails=new Map;async run(e,t){let r=this.tails.get(e),i=()=>{},n=new Promise((o)=>{i=o});this.tails.set(e,n),await r;try{return await t()}finally{if(i(),this.tails.get(e)===n)this.tails.delete(e)}}}class FO{findDuplicate(e,t,r){if(!t||t==="none")return null;let i=this.filterByDeduplicationKey(e,r).sort((o,s)=>s.createdAt-o.createdAt||s.id.localeCompare(o.id)),n=i.find((o)=>o.status===je.PENDING)??null;if(t==="skip"||t==="replace")return n;return n??i[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((r)=>{let i=D_e.safeParse(r.metadata);return i.success&&i.data.deduplicationKey===t})}}var D_e;var AV=x(()=>{Ne();hs();D_e=f.looseObject({deduplicationKey:f.string().optional()})});class MO{db;transactionClient;databaseUrl;logger;deduplicator=new FO;writeRetryBudgetMs;constructor(e,t,r,i,n){this.db=e,this.transactionClient=t,this.databaseUrl=r,this.logger=i.child("JobQueueRepository"),this.writeRetryBudgetMs=n?.writeRetryBudgetMs??L_e}async insert(e){await this.db.insert(X).values(e)}async enqueueAtomic(e){return q_e.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs,r=1;for(;;){let i=await this.acquireWriteTransaction(e,t),n={prepared:!1},o=!1;try{let s=await this.decideEnqueue(i,e,()=>{n.prepared=!0});return o=!0,await i.commit(),s}catch(s){let a=o&&this.isSerializationConflict(s)&&!i.closed,c=!0;if(!i.closed)try{await i.rollback()}catch(l){c=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:l})}if(n.prepared)e.onInsertRollback?.();if(!a||!c)throw s;await this.waitForConflictRetry("commit",e,t,r,s),r++}finally{i.close()}}})}async decideEnqueue(e,t,r){let{jobData:i,strategy:n,deduplicationKey:o,beforeInsert:s}=t,a=n??"none",c=async()=>{await s?.(),r()},l=async()=>{await c(),await this.insertJob(e,i)};if(a==="none")return await l(),{kind:"inserted",jobId:i.id};let u=await this.getActiveDeduplicationCandidates(e,i.type),d=this.deduplicator.findDuplicate(u,a,o);if(!d)return await l(),{kind:"inserted",jobId:i.id};if(a==="skip")return{kind:"skipped",jobId:d.id};if(a==="coalesce"){if((await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),d.id,d.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${d.id}`);return{kind:"coalesced",jobId:d.id}}await c();let p=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[je.FAILED,"Replaced by newer job",p,p,d.id,je.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${d.id}`);return await this.insertJob(e,i),{kind:"replaced",jobId:i.id,replacedJobId:d.id}}async getActiveDeduplicationCandidates(e,t){return(await e.execute({sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,je.PENDING,je.PROCESSING]})).rows.map((i)=>this.parseDeduplicationCandidate(i))}parseDeduplicationCandidate(e){let{id:t,status:r,createdAt:i,metadata:n}=e;if(typeof t!=="string"||r!==je.PENDING&&r!==je.PROCESSING||typeof i!=="number"&&typeof i!=="bigint"||typeof n!=="string")throw Error("Invalid active job row returned during atomic enqueue");let o=JSON.parse(n);return{id:t,status:r,createdAt:Number(i),metadata: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`\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]})).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,i,n){let o=Math.min(B_e*2**(i-1),j_e),s=o/2+Math.random()*(o/2);if(Date.now()+s>=r)throw this.transactionConflictError(e,t,i,n);await new Promise((a)=>setTimeout(a,s))}async retryOnConflict(e,t,r,i,n=Date.now()+this.writeRetryBudgetMs,o=1){try{return await r()}catch(s){if(!i(s))throw s;return await this.waitForConflictRetry(e,t,n,o,s),this.retryOnConflict(e,t,r,i,n,o+1)}}transactionConflictError(e,t,r,i){let n=t.strategy??"none",o=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: ${o})`,{cause:i})}isSerializationConflict(e){for(let t=e;t!==void 0;){let r=typeof t==="object"&&t!==null&&"code"in t?String(t.code):"",i=ct(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(r)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(i))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,r=Date.now(),i=ms){let n=r+i;await this.db.insert(Ye).values({slotId:e,sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}).onConflictDoUpdate({target:Ye.slotId,set:{sessionId:t,startedAt:r,heartbeatAt:r,expiresAt:n}})}async heartbeatWorkerSession(e,t,r=Date.now(),i=ms){return(await this.db.update(Ye).set({heartbeatAt:r,expiresAt:r+i}).where(kt(Qe(Ye.slotId,e),Qe(Ye.sessionId,t))).returning({slotId:Ye.slotId})).length===1}async endWorkerSession(e,t){return(await this.db.delete(Ye).where(kt(Qe(Ye.slotId,e),Qe(Ye.sessionId,t))).returning({slotId:Ye.slotId})).length===1}async complete(e,t,r){let i=Date.now(),o=(await this.db.update(X).set({status:je.COMPLETED,result:t,lastError:null,completedAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i)}).where(this.attemptWriteGuard(e,r)).returning({id:X.id})).length===1;if(o)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return o}async update(e,t,r){let n=(await this.db.update(X).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,r)).returning({id:X.id})).length===1;if(n)this.logger.debug("Job data updated",{jobId:e});return n}async recordAttemptProgress(e,t,r,i=Date.now()){return(await this.db.update(X).set({attemptHeartbeatAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),progress:r}).where(this.attemptWriteGuard(e,t)).returning({id:X.id})).length===1}async renewAttemptLease(e,t,r,i){return(await this.db.update(X).set({attemptHeartbeatAt:r,leaseExpiresAt:r+i}).where(this.attemptWriteGuard(e,t)).returning({id:X.id})).length===1}async fail(e,t,r,i=Date.now()){let o=(await this.db.select({retryCount:X.retryCount,maxRetries:X.maxRetries,type:X.type,scheduledFor:X.scheduledFor,startedAt:X.startedAt,runtimeUpdatedAt:X.runtimeUpdatedAt}).from(X).where(this.attemptWriteGuard(e,r)).limit(1))[0];if(!o)return!1;let s=o.retryCount<o.maxRetries,a=s?o.retryCount+1:o.retryCount,c=Math.min(1000*2**o.retryCount,60000),l=s?i+c:o.scheduledFor;if((await this.db.update(X).set({status:s?je.PENDING:je.FAILED,retryCount:a,lastError:t.message,scheduledFor:l,completedAt:s?null:i,runtimeUpdatedAt:s?o.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),startedAt:s?null:o.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(kt(this.attemptWriteGuard(e,r),Qe(X.retryCount,o.retryCount))).returning({id:X.id})).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:a,backoffMs:c,scheduledFor:new Date(l).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:o.type,retryCount:o.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 i=(await this.db.update(X).set({status:je.FAILED,lastError:t,completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(kt(Qe(X.id,e.jobId),Qe(X.type,e.expectedType),ao(Qe(X.status,je.PENDING),Qe(X.status,je.PROCESSING)),Rn(X.attemptId),Rn(X.workerSlotId),Rn(X.workerSessionId),Rn(X.leaseExpiresAt),Rn(X.attemptHeartbeatAt),Rn(X.progress),Rn(X.result))).returning())[0]??null;if(i)this.logger.warn("Retired unowned legacy job",{jobId:i.id,type:i.type,reason:t});return i}async getStatus(e){return(await this.db.select().from(X).where(Qe(X.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(X).where(q`json_extract(${X.metadata}, '$.rootJobId') = ${e}`).orderBy(co(X.createdAt),co(X.id))}async getStatusByEntityId(e){return(await this.db.select().from(X).where(q`json_extract(${X.data}, '$.id') = ${e}`).orderBy(Wa(X.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:X.status,count:q`count(*)`}).from(X).groupBy(X.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let r of e){let i=Number(r.count);t[r.status]=i,t.total+=i}return t}async getDiagnostics(e=Date.now()){let[t,r,i]=await Promise.all([this.db.select({type:X.type,status:X.status,count:q`count(*)`}).from(X).groupBy(X.type,X.status),this.db.select({oldestPendingAt:q`min(case when ${X.status} = ${je.PENDING} then ${X.createdAt} end)`,duePending:q`coalesce(sum(case when ${X.status} = ${je.PENDING} and ${X.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:q`min(case when ${X.status} = ${je.PENDING} and ${X.scheduledFor} <= ${e} then ${X.scheduledFor} end)`,latestClaimAt:q`max(${X.startedAt})`,oldestProcessingAt:q`min(case when ${X.status} = ${je.PROCESSING} then ${X.startedAt} end)`,staleLeaseCount:q`coalesce(sum(case when ${X.status} = ${je.PROCESSING} and ${X.leaseExpiresAt} is not null and ${X.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(X),this.db.select({total:q`count(*)`,active:q`coalesce(sum(case when ${Ye.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:q`coalesce(sum(case when ${Ye.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:q`max(${Ye.heartbeatAt})`}).from(Ye)]),n={pending:0,processing:0,completed:0,failed:0},o=t.map((l)=>{let u=Number(l.count);return n[l.status]+=u,{type:l.type,status:l.status,count:u}}),s=r[0],a=i[0],c=(l)=>l===null||l===void 0?null:Math.max(0,e-Number(l));return{totals:n,byType:o,oldestPendingAgeMs:c(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:c(s?.oldestDuePendingAt),latestClaimAgeMs:c(s?.latestClaimAt),oldestProcessingAgeMs:c(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(a?.total??0),active:Number(a?.active??0),stale:Number(a?.stale??0),latestHeartbeatAgeMs:c(a?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){return(await this.db.select().from(X).where(q`(${X.runtimeUpdatedAt}, ${X.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(co(X.runtimeUpdatedAt),co(X.id)).limit(t)).map((i)=>({job:i,cursor:{updatedAt:i.runtimeUpdatedAt??0,jobId:i.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.db.delete(X).where(kt(ao(Qe(X.status,je.COMPLETED),Qe(X.status,je.FAILED)),Va(X.completedAt,t)))).rowsAffected}async getActiveJobs(e){let t=ao(Qe(X.status,je.PENDING),Qe(X.status,je.PROCESSING)),r=e&&e.length>0?kt(t,As(X.type,e)):t;return this.db.select().from(X).where(r).orderBy(Wa(X.createdAt))}async getRecentJobs(e,t=20){let r=e&&e.length>0?As(X.type,e):void 0;return this.db.select().from(X).where(r).orderBy(Wa(X.createdAt)).limit(t)}async getFailedJobs(e){let t=Qe(X.status,je.FAILED),r=e&&e.length>0?kt(t,As(X.type,e)):t;return this.db.select().from(X).where(r).orderBy(Wa(X.createdAt))}async claimNextReady(e){let{now:t,attemptId:r,workerSlotId:i,workerSessionId:n,leaseDurationMs:o,executableTypes:s}=e,a=this.db.select({slotId:Ye.slotId}).from(Ye).where(kt(Qe(Ye.slotId,i),Qe(Ye.sessionId,n),dx(Ye.expiresAt,t))),c=this.db.select({slotId:Ye.slotId}).from(Ye).where(kt(Qe(Ye.slotId,X.workerSlotId),Qe(Ye.sessionId,X.workerSessionId))),l=this.db.select({slotId:Ye.slotId}).from(Ye).where(kt(Qe(Ye.slotId,X.workerSlotId),Qe(Ye.sessionId,X.workerSessionId),Va(Ye.expiresAt,t))),u=kt(Qe(X.status,je.PROCESSING),ao(Rn(X.attemptId),fx(c),kt(Va(X.leaseExpiresAt,t),Op(l)))),d=q`${X.status} = ${je.PROCESSING} AND ${X.retryCount} + 1 > ${X.maxRetries}`,p=this.db.select({id:X.id}).from(X).where(kt(As(X.type,s),ao(kt(Qe(X.status,je.PENDING),Va(X.scheduledFor,t)),u))).orderBy(co(X.priority),co(X.createdAt)).limit(1),y=(await this.db.update(X).set({status:q`CASE WHEN ${d} THEN ${je.FAILED} ELSE ${je.PROCESSING} END`,retryCount:q`CASE WHEN ${X.status} = ${je.PROCESSING} THEN ${X.retryCount} + 1 ELSE ${X.retryCount} END`,lastError:q`CASE WHEN ${X.status} = ${je.PROCESSING} THEN 'Attempt lease expired' ELSE ${X.lastError} END`,startedAt:q`CASE WHEN ${d} THEN ${X.startedAt} ELSE ${t} END`,completedAt:q`CASE WHEN ${d} THEN ${t} ELSE NULL END`,attemptId:q`CASE WHEN ${d} THEN ${X.attemptId} ELSE ${r} END`,workerSlotId:q`CASE WHEN ${d} THEN ${X.workerSlotId} ELSE ${i} END`,workerSessionId:q`CASE WHEN ${d} THEN ${X.workerSessionId} ELSE ${n} END`,leaseExpiresAt:q`CASE WHEN ${d} THEN ${X.leaseExpiresAt} ELSE ${t+o} END`,attemptHeartbeatAt:q`CASE WHEN ${d} THEN ${X.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:q`CASE WHEN ${d} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${X.runtimeUpdatedAt} END`}).where(kt(As(X.id,p),Op(a))).returning())[0];if(y?.status!==je.PROCESSING)return null;return this.logger.debug("Job claimed",{jobId:y.id,attemptId:y.attemptId,workerSlotId:i,workerSessionId:n}),y}nextRuntimeUpdatedAt(e){return q`max(${e}, coalesce((select max(${X.runtimeUpdatedAt}) from ${X}), 0) + 1)`}attemptWriteGuard(e,t){return t?kt(Qe(X.id,e),Qe(X.status,je.PROCESSING),Qe(X.attemptId,t)):kt(Qe(X.id,e),Rn(X.attemptId),ao(Qe(X.status,je.PENDING),Qe(X.status,je.PROCESSING)))}}var L_e=2000,B_e=5,j_e=40,q_e;var $V=x(()=>{IV();jO();hs();rp();AV();q_e=new UO});import{AsyncLocalStorage as U_e}from"async_hooks";class Fp{storage=new U_e;static createFresh(){return new Fp}constructor(){}current(){return this.storage.getStore()}run(e,t,r){if(t.length===0)throw Error("Operation ID must not be empty");let i=Bo.parse(e),n=F_e(i);return this.storage.run(Object.freeze({provenance:n,operationId:t}),r)}}function F_e(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}var ZO=x(()=>{jo()});class Mp{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${to()}`;directWorkerSessionId=to();directLeaseDurationMs;directSessionStart=null;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,r){return new Mp(e,t??fn.getInstance(),r)}constructor(e,t,r){let{db:i,client:n,url:o}=kV(e);this.client=n,this.databaseUrl=o,this.logger=t.child("JobQueueService"),this.operationContext=r?.operationContext??Fp.createFresh(),this.projectionAdmission=r?.projectionAdmission,this.handlerRegistry=new qO(this.logger,r?.handlerRegistrationMode??"combined"),this.repository=new MO(i,n,o,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 Ox(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:i}=e,n=this.handlerRegistry.getValidator(t);if(!n)throw Error(`No job type declared: ${t}`);let o=n.validateAndParse(r);if(o===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),a=to(),c=i?.rootJobId??this.operationContext.current()?.provenance.rootJobId??a,l=this.createJobProvenance(a,c,i),u=i?.metadata??{operationType:"data_processing"},{provenance:d,...p}=u,m={id:a,type:t,data:JSON.stringify(o),status:je.PENDING,priority:i?.priority??0,maxRetries:i?.maxRetries??3,retryCount:0,source:i?.source??null,metadata:{...p,...i?.deduplicationKey&&{deduplicationKey:i.deduplicationKey},rootJobId:c,provenance:l},createdAt:s,scheduledFor:i?.delayMs?s+i.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null},y,g=()=>{y?.rollback(),y=void 0};try{let b=await this.repository.enqueueAtomic({jobData:m,strategy:i?.deduplication,deduplicationKey:i?.deduplicationKey,beforeInsert:async()=>{y=await this.projectionAdmission?.reserveJobAdmission(l)},onInsertRollback:g});if(y?.commit(),y=void 0,b.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:b.jobId});else if(b.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:b.jobId});else{if(b.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:b.replacedJobId});this.logger.debug("Job enqueued",{id:b.jobId,type:t,priority:m.priority,rootJobId:m.metadata.rootJobId})}return b.jobId}catch(b){throw g(),this.logger.error("Failed to enqueue job",{type:t,error:ct(b)}),b}}createJobProvenance(e,t,r){let i=this.operationContext.current(),n=r?.metadata.provenance??i?.provenance,o=n?.rootJobId===t?n:void 0,s=i?.provenance.rootJobId===t?i.operationId:void 0,a=r?.projection,c=a?[...o?.projectionLineage??[],a.id]:[...o?.projectionLineage??[]],l=a?.id??o?.projectionId;return Bo.parse({rootJobId:t,causationId:s??o?.causationId??e,...l?{projectionId:l}:{},projectionLineage:c,...a?.sourceEntity?{sourceEntity:a.sourceEntity}:o?.sourceEntity?{sourceEntity:o.sourceEntity}:{},derivationDepth:c.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let r=e??await this.getDirectClaimOptions(),i=Date.now(),n=await this.repository.claimNextReady({...r,now:i,attemptId:to(),executableTypes:t});if(!n)return null;return this.logger.debug("Job dequeued",{id:n.id,type:n.type,priority:n.priority,retryCount:n.retryCount,attemptId:n.attemptId,workerSlotId:n.workerSlotId,workerSessionId:n.workerSessionId}),n}async startWorkerSession(e,t,r=ms){await this.repository.startWorkerSession(e,t,Date.now(),r)}heartbeatWorkerSession(e,t,r=ms){return this.repository.heartbeatWorkerSession(e,t,Date.now(),r)}endWorkerSession(e,t){return this.repository.endWorkerSession(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)}retireUnownedActiveJob(e){return this.repository.retireUnownedActiveJob(e)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.directWorkerSlotId,this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs),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,i=Date.now()+(e.timeoutMs??30000),n=async(o)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),c=s.pending===0&&s.processing===0?o??Date.now():null;if(c!==null&&Date.now()-c>=t)return;if(Date.now()>=i)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(r),n(c)};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 CV=x(()=>{ep();YC();rp();hs();BO();EV();$V();jo();ZO()});var HO=()=>{};var TV=x(()=>{ep();hs();rp();hs();HO();ZO()});var OV=x(()=>{hs();HO()});var qYe;var RV=x(()=>{jo();Ne();tp();qYe=f.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},f.record(f.string(),f.unknown()))});var MYe;var PV=x(()=>{Ne();MYe=f.record(f.string(),f.unknown())});var zV=x(()=>{jo();ep()});var NV=x(()=>{CV();TV();OV();RV();PV();rp();hs();tp();zV()});var JO={};tr(JO,{LEGACY_PROJECTION_JOB_TYPES:()=>LV,LEGACY_PROJECTION_RETIREMENT_REASON:()=>jV,legacyProjectionJobTypeSchema:()=>BV,retireLegacyProjectionJob:()=>Q_e});import{existsSync as V_e}from"fs";import{resolve as W_e}from"path";function DV(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 G_e(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 Q_e(e){let t=W_e(e.databasePath);if(!V_e(t))throw Error(`Job database does not exist: ${t}`);let r=BV.parse(e.jobType),i=Mp.createFresh({url:`file:${t}`});try{let n=await i.getStatus(e.jobId);if(!n)throw Error(`Job not found: ${e.jobId}`);if(G_e(n,r),e.dryRun){if(e.confirmation!==void 0)throw Error("Dry-run recovery must not include confirmation");return{databasePath:t,job:DV(n),retired:!1}}let o=`retire:${n.id}`;if(e.confirmation!==o)throw Error(`Refusing to retire ${n.id}; expected --confirm ${o}`);let s=await i.retireUnownedActiveJob({jobId:n.id,expectedType:r,reason:jV,now:e.now?.()??Date.now()});if(!s)throw Error(`Job ${n.id} changed or acquired ownership before retirement`);return{databasePath:t,job:DV(s),retired:!0}}finally{i.close()}}var LV,BV,jV="Retired legacy projection job superseded by scheduler-owned projections";var KO=x(()=>{NV();Ne();LV=["conversation-memory:project","skill:project","swot:derive","topic:project"],BV=f.enum(LV)});function er(e,t,r,i,n){return UV.parse({id:e,operation:t,count:r,targetProbeCount:i,settleMs:n})}function WO(e){return Hp.parse(structuredClone(tke[e]))}function Jp(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 Px(e,t={}){let r=t.fetchImpl??fetch,i=t.now??(()=>new Date),n=t.timeoutMs??20000,o=i(),s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let c=await r(e,{method:"GET",signal:s.signal});return await c.arrayBuffer(),VO.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:c.status,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:c.ok})}catch(c){return VO.parse({timestamp:o.toISOString(),endpoint:new URL(e).pathname,status:0,durationMs:Math.max(0,i().getTime()-o.getTime()),ok:!1,error:rke(c)})}finally{clearTimeout(a)}}async function GO(e,t){let r=Hp.parse(e),i=[],n,o=await t.prepare(r),s,a;try{try{await t.startMonitoring()}catch(c){n=`monitor: ${Rx(c)}`}if(!n)for(let c of r.phases)try{let l=FV.parse(await t.executePhase(c,o));if(i.push(l),!l.success){n=`${c.id}: ${l.error??"phase failed"}`;break}}catch(l){let u=Rx(l);i.push({id:c.id,operation:c.operation,count:c.count,success:!1,error:u}),n=`${c.id}: ${u}`;break}}finally{try{if(s=MV.parse(await t.cleanup(o)),!s.success&&!n)n=s.error??"cleanup failed"}catch(c){let l=Rx(c);s={success:!1,probesRemaining:0,error:l},n??=`cleanup: ${l}`}try{a=ZV.parse(await t.stopMonitoring())}catch(c){let l=Rx(c);a={health:[],runtime:[]},n??=`monitor: ${l}`}}return n??=JV(a,r.maximumExternalAiCalls??0),HV.parse({profile:r.profile,success:n===void 0&&i.length===r.phases.length&&s.success,baseline:o,phases:i,cleanup:s,metrics:a,...n?{failure:n}:{}})}function JV(e,t=0){let r=e.health.find((o)=>!o.ok);if(r)return`health: ${r.endpoint} unavailable`;let i=e.externalAiCalls??0;if(i>t)return t===0?`external AI: observed ${i} call(s)`:`external AI: observed ${i} 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 rke(e){if(e instanceof Error)return`${e.name}: ${e.message}`;return String(e)}function Rx(e){return ct(e)}var Zp,qV,UV,Hp,Y_e,VO,X_e,FV,MV,eke,ZV,HV,tke;var zx=x(()=>{Ne();Zp=f.enum(["regression","load","stress"]),qV=f.enum(["add","update","rename","delete"]),UV=f.object({id:f.string().min(1),operation:qV,count:f.number().int().positive().max(700),targetProbeCount:f.number().int().min(0).max(700),settleMs:f.number().int().nonnegative().max(300000)}),Hp=f.object({profile:Zp,maximumProbeCount:f.number().int().positive().max(700),maximumExternalAiCalls:f.number().int().nonnegative().max(1e4).optional(),phases:f.array(UV).min(1)}),Y_e=f.object({entities:f.number().int().nonnegative(),notes:f.number().int().nonnegative(),version:f.string().min(1)}),VO=f.object({timestamp:f.iso.datetime(),endpoint:f.string().startsWith("/"),status:f.number().int().nonnegative(),durationMs:f.number().nonnegative(),ok:f.boolean(),error:f.string().optional()}),X_e=f.object({timestamp:f.iso.datetime(),cpuPercent:f.number().nonnegative(),memoryPercent:f.number().nonnegative(),pids:f.number().int().nonnegative()}),FV=f.object({id:f.string().min(1),operation:qV,count:f.number().int().positive(),success:f.boolean(),commitLatencyMs:f.number().nonnegative().optional(),persistenceLatencyMs:f.number().nonnegative().optional(),error:f.string().optional()}),MV=f.object({success:f.boolean(),probesRemaining:f.number().int().nonnegative(),finalEntities:f.number().int().nonnegative().optional(),finalNotes:f.number().int().nonnegative().optional(),contentTreeRestored:f.boolean().optional(),error:f.string().optional()}),eke=f.object({status:f.string(),restartCount:f.number().int().nonnegative(),oomKilled:f.boolean()}),ZV=f.object({health:f.array(VO),runtime:f.array(X_e),externalAiCalls:f.number().int().nonnegative().optional(),container:eke.optional()}),HV=f.object({profile:Zp,success:f.boolean(),baseline:Y_e,phases:f.array(FV),cleanup:MV,metrics:ZV,failure:f.string().optional()}),tke={regression:{profile:"regression",maximumProbeCount:20,phases:[er("add20","add",20,20,0),er("update20","update",20,20,30000),er("delete20","delete",20,0,150000)]},load:{profile:"load",maximumProbeCount:350,phases:[er("add50","add",50,50,0),er("add150","add",100,150,0),er("add350","add",200,350,0),er("update350a","update",350,350,45000),er("rename100","rename",100,350,45000),er("update350b","update",350,350,45000),er("delete350","delete",350,0,150000)]},stress:{profile:"stress",maximumProbeCount:700,phases:[er("add50","add",50,50,0),er("add150","add",100,150,0),er("add350","add",200,350,0),er("add700","add",350,700,0),er("update700a","update",700,700,45000),er("rename200","rename",200,700,45000),er("update700b","update",700,700,45000),er("delete700","delete",700,0,150000)]}}});import{spawn as nke}from"child_process";async function KV(e,t,r,i){let n=await e(t,r,i);if(n.exitCode!==0)throw Ei(t,r,n);return n}function Ei(e,t,r){let i=r.stderr.trim()||r.stdout.trim();return Error(`${e} ${t.join(" ")} exited with ${r.exitCode}${i?`: ${i}`:""}`)}var mo=async(e,t,r={})=>new Promise((i,n)=>{let o=nke(e,[...t],{cwd:r.cwd,env:r.env?{...process.env,...r.env}:process.env,stdio:["pipe","pipe","pipe"]}),s="",a="";o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",(c)=>{s+=c}),o.stderr.on("data",(c)=>{a+=c}),o.on("error",n),o.on("close",(c)=>{i({exitCode:c??1,stdout:s,stderr:a})}),o.stdin.end(r.stdin)});var Kp=()=>{};class Iu{#e;#t;dir;constructor(e,t,r){this.#e=e,this.dir=t,this.#t=r}static async clone(e,t,r,i){let n=new Iu(e,r,i);return await KV(e,"git",["-c","credential.helper=","-c",`credential.helper=${VV}`,"clone","--branch","main","--single-branch",`https://github.com/${t}.git`,r],{env:n.environment()}),await n.run(["config","--local","credential.helper",VV]),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 Ei("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 VV='!f() { test "$1" = get && echo username=x-access-token && echo "password=$GH_TOKEN"; }; f';var WV=x(()=>{Kp()});function Vp(e){return e.entityCounts.find((t)=>t.entityType==="note")?.count??0}class QO{#e;#t=[];#r=[];#n=new Set(["/health/ready"]);#i=!0;#o;#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 Px(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:5000})).status!==404)this.#n.add(e)}start(){this.#i=!1,this.#a=void 0,this.#c=this.#t.length,this.#l=void 0,this.#s=this.#e.now().toISOString(),this.#o=Promise.all([this.#f(),this.#m()]).then(()=>{return}).catch((e)=>{this.#a=e,this.#i=!0})}async stop(){this.#i=!0,await this.#o}async waitForHealthSnapshot(e){return this.waitForEntityBaseline(void 0,void 0,e)}async waitForEntityBaseline(e,t,r){let i=this.#e.now().getTime();while(this.#e.now().getTime()-i<r){let n=await this.fetchHealthPayload();if(this.#d(n,e,t))return n;await this.#e.sleep(5000)}return}async waitForStableEntityBaseline(e,t,r){let i=this.#e.now().getTime(),n=0;while(this.#e.now().getTime()-i<r){let o=await this.fetchHealthPayload();if(this.#d(o,e,t)){if(n+=1,n===2)return o}else n=0;await this.#e.sleep(5000)}return}async fetchHealthPayload(){let e=this.#e.now(),t=new AbortController,r=setTimeout(()=>t.abort(),20000);try{let i=await this.#e.fetchImpl(`https://${this.#e.domain}/health/operate`,{signal:t.signal}),n=await i.text();if(this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:i.status,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:i.ok}),!i.ok)return;return ike.parse(JSON.parse(n)).app}catch(i){this.#t.push({timestamp:e.toISOString(),endpoint:"/health/operate",status:0,durationMs:Math.max(0,this.#e.now().getTime()-e.getTime()),ok:!1,error:i instanceof Error?`${i.name}: ${i.message}`:String(i)});return}finally{clearTimeout(r)}}#d(e,t,r){return e!==void 0&&(t===void 0||Vp(e)===t)&&(r===void 0||e.entities===r)}async#f(){while(!this.#i){for(let e of this.#n)this.#t.push(await Px(`https://${this.#e.domain}${e}`,{fetchImpl:this.#e.fetchImpl,now:this.#e.now,timeoutMs:20000}));await this.#e.sleep(4000)}}async#m(){while(!this.#i){let e=await this.#e.sampleRuntime();if(e)this.#r.push(e);await this.#e.sleep(1000)}}}var ike;var GV=x(()=>{Ne();zx();ike=f.object({status:f.literal("ready"),operationalStatus:f.literal("operational"),app:f.object({version:f.string(),entities:f.number().int().nonnegative(),entityCounts:f.array(f.object({entityType:f.string(),count:f.number().int().nonnegative()})).default([])})})});var Nx={};tr(Nx,{applyDirectorySyncStressPhase:()=>n7,cleanupDirectorySyncStress:()=>e7,listProbeFiles:()=>Xa,parseStressRuntimeSample:()=>i7,removeProbeFiles:()=>iR,runDeployedDirectorySyncStress:()=>YV,runStressCommand:()=>mo,verifyDirectorySyncStressAccess:()=>XV});import{chmod as oke,mkdir as XO,mkdtemp as eR,readFile as ske,readdir as ake,rename as cke,rm as Gp,writeFile as Xn}from"fs/promises";import{tmpdir as tR}from"os";import{join as xt,resolve as rR}from"path";async function YV(e){let t=e.now??(()=>new Date),r=t().toISOString(),i=oR(r),n=rR(e.artifactsDir??xt(e.rootDir,".brains-ops","stress",i));await XO(n,{recursive:!0});let{pilot:o,user:s}=await nR(e.rootDir,e.handle);Jp({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation});let a=Zp.parse(e.profile),c=e.plan?Hp.parse(e.plan):WO(a);if(c.profile!==a)throw Error(`Directory-sync stress plan profile ${c.profile} does not match requested profile ${a}`);if((c.maximumExternalAiCalls??0)===0)r7(s);let l=lke.parse(e.env??process.env),u=new t7({runId:i,artifactsDir:n,user:s,githubOrg:o.githubOrg,serverLabel:`${o.contentRepoPrefix}${s.handle}`,environment:l,fetchImpl:e.fetchImpl??fetch,commandRunner:e.commandRunner??mo,logger:e.logger??console.info,now:t,sleep:e.sleep??Bun.sleep}),d;try{d=await GO(c,u)}finally{await u.dispose()}let p={runId:i,artifactsDir:n,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`},startedAt:r,completedAt:t().toISOString(),report:d};return await mke(p),p}async function XV(e){let r=(e.now??(()=>new Date))().toISOString(),i=oR(r),n=rR(e.artifactsDir??xt(e.rootDir,".brains-ops","stress",`access-check-${i}`));await XO(n,{recursive:!0});let{pilot:o,user:s}=await nR(e.rootDir,e.handle);Jp({handle:s.handle,domain:s.domain,contentRepo:s.contentRepo,confirmation:e.confirmation}),r7(s);let a=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!a)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let c=await eR(xt(tR(),"brains-ops-directory-sync-access-check-"));try{let l=await Iu.clone(e.commandRunner??mo,`${o.githubOrg}/${s.contentRepo}`,xt(c,"content"),a),u=await l.output(["rev-parse","HEAD"]);await l.run(["push","--dry-run","origin",`HEAD:refs/heads/ops/directory-sync-stress-access-check-${i}`]);let d={success:!0,artifactsDir:n,checkedAt:r,remoteHead:u,target:{handle:s.handle,domain:s.domain,contentRepo:`${o.githubOrg}/${s.contentRepo}`}};return await Xn(xt(n,"access-check.json"),`${JSON.stringify(d,null,2)}
|
|
454
454
|
`),d}finally{await Gp(c,{recursive:!0,force:!0})}}async function e7(e){let t=e.now??(()=>new Date),r=rR(e.artifactsDir??xt(e.rootDir,".brains-ops","stress",`cleanup-${oR(t().toISOString())}`));await XO(r,{recursive:!0});let{pilot:i,user:n}=await nR(e.rootDir,e.handle);Jp({handle:n.handle,domain:n.domain,contentRepo:n.contentRepo,confirmation:e.confirmation});let o=(e.env??process.env).CONTENT_REPO_ADMIN_TOKEN;if(!o)throw Error("Missing CONTENT_REPO_ADMIN_TOKEN");let s=e.commandRunner??mo,a=e.logger??console.info,c=await eR(xt(tR(),"brains-ops-directory-sync-cleanup-")),l=xt(c,"content");try{let u=await Iu.clone(s,`${i.githubOrg}/${n.contentRepo}`,l,o),d=await iR(u.dir),p;if(d>0)await u.commitAll("test(directory-sync): clean residual stress probes"),await u.pushMainWithRebase(),p=await u.output(["rev-parse","HEAD"]),a(`Removed ${d} directory-sync stress probes`);let m=(await Xa(u.dir)).length,y=m===0?await u.pruneStressBackupBranches():[],g={success:m===0,artifactsDir:r,probesRemoved:d,probesRemaining:m,backupBranchesDeleted:y,...p?{cleanupCommit:p}:{}};return await Xn(xt(r,"cleanup.json"),`${JSON.stringify(g,null,2)}
|
|
455
455
|
`),g}finally{await Gp(c,{recursive:!0,force:!0})}}class t7{#e;#t;#r;#n;#i;#o;#a;#s;#c;#l;#d;constructor(e){this.#e=e,this.#t=new QO({domain:e.user.domain,fetchImpl:e.fetchImpl,now:e.now,sleep:e.sleep,sampleRuntime:()=>this.#y()})}async prepare(e){this.#r=await eR(xt(tR(),"brains-ops-directory-sync-stress-"));let t=xt(this.#r,"content");this.#i=xt(this.#r,"id_ed25519"),this.#o=xt(this.#r,"known_hosts"),this.#a=await this.#m(),await Xn(this.#i,pke(this.#e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await oke(this.#i,384);let r=await this.#b("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 Xn(this.#o,r.stdout,{mode:384});let i=await this.#h(["docker","ps","--filter","label=service=rover","--filter","label=role=web","--format","{{.Names}}"]);if(this.#s=i.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 Iu.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 o=await n.output(["rev-parse","HEAD"]);this.#l=await n.output(["rev-parse","HEAD^{tree}"]),this.#d=await this.#f();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 Xn(xt(this.#e.artifactsDir,"state.json"),`${JSON.stringify({runId:this.#e.runId,profile:e.profile,originalHead:o,originalTree:this.#l,backupBranch:this.#c,baseline:{entities:s.entities,notes:Vp(s),version:s.version}},null,2)}
|
|
456
456
|
`),this.#e.logger(`Prepared ${e.profile} directory-sync stress run for ${this.#e.user.handle}`),{entities:s.entities,notes:Vp(s),version:s.version}}async startMonitoring(){this.#x(),this.#t.start()}async executePhase(e,t){this.#x();let r=this.#n;if(!r)throw Error("Directory-sync stress checkout is not prepared");await r.sync();let i=this.#t.healthSamples.length,n=this.#e.now().getTime(),o=await this.#g();if(o?.pending!==0||o.processing!==0)return Au(e,"health did not provide a drained queue before the phase");await n7(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"]),c=await this.#p(a,900000);if(c===void 0)return Au(e,"runtime did not pull the phase commit");let l;if(e.operation==="rename"){let m=t.notes+e.targetProbeCount;if(e.settleMs>0)await this.#e.sleep(e.settleMs);let y=await this.#t.waitForStableEntityBaseline(m,void 0,1200000);if(l=this.#e.now().getTime()-s,!y)return Au(e,`health did not stabilize at ${m} notes`,c,l)}else if(e.operation==="add"||e.operation==="delete"){let m=t.notes+e.targetProbeCount,y=this.#e.now().getTime(),g=await this.#t.waitForEntityBaseline(m,void 0,1200000);if(l=this.#e.now().getTime()-y,!g)return Au(e,`health did not reach ${m} notes`,c,l)}if(e.operation!=="rename"&&e.settleMs>0)await this.#e.sleep(e.settleMs);let u=e.operation==="delete"?0:Math.ceil(e.count/50);if(!await this.#u(o.completedImports+u,1200000))return Au(e,`health did not observe ${u} completed import job(s) with a drained queue`,c,l);let p=this.#t.healthSamples.slice(i).find((m)=>!m.ok);if(p)return Au(e,`${p.endpoint} unavailable (${p.status===0?p.error??"unknown":p.status})`,c,l);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:c,...l===void 0?{}:{persistenceLatencyMs:l}}}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 iR(t.dir)>0)await t.commitAll("test(directory-sync): remove stress probes"),await t.pushMainWithRebase();let i=(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=i===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:i,...n?{finalEntities:n.entities,finalNotes:Vp(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:ct(r)}}}async stopMonitoring(){await this.#t.stop(),await Xn(xt(this.#e.artifactsDir,"health-samples.json"),`${JSON.stringify(this.#t.healthSamples,null,2)}
|
|
@@ -763,7 +763,7 @@ printf 'REMOTE_ARTIFACT_DIR=%s\\n' "$remote_dir"
|
|
|
763
763
|
`),o}async function h7(e,t){let r=await Tt(e),i=r.users.find((n)=>n.handle===t);if(!i)throw Error(`Unknown pilot user: ${t}`);return{pilot:r.pilot,user:i}}async function g7(e){let t=await vke(Ii(_ke(),"brains-ops-watchdog-smoke-")),r=Ii(t,"id_ed25519"),i=Ii(t,"known_hosts");try{let n=encodeURIComponent(`brain=${e.target.pilot.contentRepoPrefix}${e.target.user.handle}`),o=await e.fetchImpl(`https://api.hetzner.cloud/v1/servers?label_selector=${n}`,{headers:{Authorization:`Bearer ${e.environment.HCLOUD_TOKEN}`}});if(!o.ok)throw Error(`Hetzner server lookup failed with ${o.status}`);let s=kke.parse(await o.json());if(s.servers.length!==1)throw Error(`Expected one smoke server, found ${s.servers.length}`);let a=s.servers[0];if(a?.status!=="running")throw Error("Smoke server is not running");await $u(r,Ake(e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await wke(r,384);let c=await e.commandRunner("ssh-keyscan",["-T","10","-t","ed25519",a.public_net.ipv4.ip]);if(c.exitCode!==0||!c.stdout.trim())throw Error("Unable to resolve watchdog smoke SSH host key");return await $u(i,c.stdout,{mode:384}),{temporaryRoot:t,sshKeyPath:r,knownHostsPath:i,serverIp:a.public_net.ipv4.ip,commandRunner:e.commandRunner}}catch(n){throw await cR(t,{recursive:!0,force:!0}),n}}async function aR(e,t,r){return e.commandRunner("ssh",[...y7(e),`root@${e.serverIp}`,"bash","-s","--",t,r],{stdin:lR()})}async function Eke(e,t,r){return e.commandRunner("scp",[...y7(e),"-r",`root@${e.serverIp}:${t}/.`,r])}function y7(e){return["-i",e.sshKeyPath,"-o","BatchMode=yes","-o","IdentitiesOnly=yes","-o","ConnectTimeout=10","-o","StrictHostKeyChecking=yes","-o",`UserKnownHostsFile=${e.knownHostsPath}`]}async function Ike(e){try{return await Ske(e),!0}catch{return!1}}async function Dx(e,t,r){await Promise.all([$u(Ii(e,`${t}.stdout.log`),r.stdout),$u(Ii(e,`${t}.stderr.log`),r.stderr)])}function Ake(e){return`${e.replace(/\r\n/g,`
|
|
764
764
|
`).replace(/\\n/g,`
|
|
765
765
|
`).trimEnd()}
|
|
766
|
-
`}var f7,kke;var Bx=x(async()=>{Ne();c7();Ln();Kp();await a7();f7=f.object({HCLOUD_TOKEN:f.string().min(1),KAMAL_SSH_PRIVATE_KEY:f.string().min(1)}),kke=f.object({servers:f.array(f.object({status:f.string(),public_net:f.object({ipv4:f.object({ip:f.string().min(1)})})}))})});import{access as $N,chmod as OE,mkdir as Uh,readFile as TN,writeFile as CN}from"fs/promises";import{dirname as LY,join as jc}from"path";import{fileURLToPath as BY}from"url";var Yp={name:"@rizom/ops",version:"0.2.0-alpha.
|
|
766
|
+
`}var f7,kke;var Bx=x(async()=>{Ne();c7();Ln();Kp();await a7();f7=f.object({HCLOUD_TOKEN:f.string().min(1),KAMAL_SSH_PRIVATE_KEY:f.string().min(1)}),kke=f.object({servers:f.array(f.object({status:f.string(),public_net:f.object({ipv4:f.object({ip:f.string().min(1)})})}))})});import{access as $N,chmod as OE,mkdir as Uh,readFile as TN,writeFile as CN}from"fs/promises";import{dirname as LY,join as jc}from"path";import{fileURLToPath as BY}from"url";var Yp={name:"@rizom/ops",version:"0.2.0-alpha.399",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/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 run build && 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"};Os();Bc();var jY=["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/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"],RE=new Set([".kamal/hooks/pre-deploy"]),qY=new Set(["cohorts/cohort-1.yaml","users/alice.yaml","docs/canonical-crossover-record.md"]),UY=BY(new URL("../templates/rover-pilot/",import.meta.url)),FY=[`service: rover
|
|
767
767
|
image: <%= ENV['IMAGE_REPOSITORY'] %>
|
|
768
768
|
|
|
769
769
|
servers:
|