@rizom/ops 0.2.0-alpha.729 → 0.2.0-alpha.730
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 +2 -2
- package/dist/index.js +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -421,7 +421,7 @@ agePublicKey: ${t}
|
|
|
421
421
|
`;jue(x,S);let _=EM(S);if(r.dryRun){if(s(`Dry run: would encrypt ${_.length} secrets to ${d}.`),s(_.length>0?`Keys: ${_.join(", ")}`:"Keys: (none \u2014 shared defaults only)"),b)s(`Would remove plaintext file ${p}.`);return{encryptedPath:d,plaintextPath:p,deletedPlaintext:b,encryptedKeys:_,dryRun:!0}}let A=new np;A.addRecipient(o.pilot.agePublicKey);let O=await A.encrypt(x),L=Mi.encode(O);if(await TM(l,L),await zue(u,{force:!0}),s(`Encrypted ${_.length} secrets to ${d}.`),b)s(`Removed plaintext file ${p}.`);return{encryptedPath:d,plaintextPath:p,deletedPlaintext:b,encryptedKeys:_}}function Nue(e,t,r,o,n,i){let s=IM(e,t,r,o,n,"openaiApiKey",i.effectiveOpenaiApiKeySelector,i.sharedOpenaiApiKeySelector),a=IM(e,t,r,o,n,"gitSyncToken",i.effectiveGitSyncTokenSelector,i.sharedGitSyncTokenSelector),l=i.discordEnabled?hy(e,t,r,o,n,"discordBotToken","DISCORD_BOT_TOKEN"):void 0,u=i.discordEnabled?hy(e,t,r,o,n,"discordPublicKey","DISCORD_PUBLIC_KEY"):void 0,d=i.discordEnabled?hy(e,t,r,o,n,"discordApplicationId","DISCORD_APPLICATION_ID"):void 0,p=gy(e,t,r,o,n,"atprotoAppPassword","ATPROTO_APP_PASSWORD"),m=AM(gy(e,t,r,o,n,"certificatePem","CERTIFICATE_PEM")),h=AM(gy(e,t,r,o,n,"privateKeyPem","PRIVATE_KEY_PEM"));return $M.parse({...s?{openaiApiKey:s}:{},...a?{gitSyncToken:a}:{},...l?{discordBotToken:l}:{},...u?{discordPublicKey:u}:{},...d?{discordApplicationId:d}:{},...p?{atprotoAppPassword:p}:{},...m?{certificatePem:m}:{},...h?{privateKeyPem:h}:{}})}function IM(e,t,r,o,n,i,s,a){if(s===a)return;return hy(e,t,r,o,n,i,s)}function hy(e,t,r,o,n,i,s){let a=gy(e,t,r,o,n,i,s);if(a===void 0||a.trim().length===0)throw Error(`Missing required secret value for ${String(i)}. Set it in users/<handle>.secrets.yaml or fall back to ${s}/${s}_FILE before running secrets:encrypt.`);return a}function AM(e){return e?.replace(/\r\n?|\n/g,"\\n")}function gy(e,t,r,o,n,i,s){return Due(o,n,i,s,t,r,e)}function Due(e,t,r,o,n,i,s){let a=e?.[r];if(a!==void 0&&a.trim().length>0)return a;let l=Bt(`${o}_FILE`,n,i);if(l&&l.trim().length>0)return cp(Qo(l,s),"utf8");let u=Bt(o,n,i);if(u!==void 0&&u.trim().length>0)return u;let d=t?.[r];if(d!==void 0&&d.trim().length>0)return d;return}function Lue(e){let t;try{t=cp(e,"utf8")}catch{return}try{return BR(t)}catch(r){throw Error(`Unable to parse plaintext secrets file ${e}: ${Ve(r)}`,{cause:r})}}async function Bue(e,t,r,o){if(!await OM(e))return;let n=LR(t,r,o);if(!n)return;let i;try{let s=cp(e,"utf8"),a=Mi.decode(s),l=new op;l.addIdentity(n),i=await l.decrypt(a,"text")}catch{return}try{return BR(i)}catch(s){throw Error(`Unable to parse decrypted secrets from ${e}: ${Ve(s)}`,{cause:s})}}function LR(e,t,r){let o=Bt("AGE_SECRET_KEY_FILE",t,r);if(o&&o.trim().length>0)return el(cp(Qo(o,e),"utf8"));let n=Bt("AGE_SECRET_KEY",t,r);if(n&&n.trim().length>0)return el(n);try{return el(cp(NR(e,".brains-ops","age","identity.txt"),"utf8"))}catch{return}}function BR(e){let t=mC(e),r={};if(t!==null&&typeof t==="object"&&!Array.isArray(t)){for(let[o,n]of Object.entries(t))if(typeof n==="string")r[o]=n}return $M.partial().parse(r)}function jue(e,t){let r={...t},o={...BR(e)},n=new Set([...Object.keys(r),...Object.keys(o)]);for(let i of n)if(r[i]!==o[i])throw Error(`secrets:encrypt round-trip verification failed for ${i}; refusing to write a corrupted encrypted payload`)}function Zue(e){return[...e.effectiveOpenaiApiKeySelector!==e.sharedOpenaiApiKeySelector?["openaiApiKey"]:[],...e.effectiveGitSyncTokenSelector!==e.sharedGitSyncTokenSelector?["gitSyncToken"]:[],...e.discordEnabled?["discordBotToken","discordPublicKey","discordApplicationId"]:[]]}async function Uue(e,t){let r=["# local per-user secret staging file","# fill values, run `bunx brains-ops secrets:encrypt . <handle>`, then the plaintext file will be removed",...t.map((o)=>`${o}: `),""].join(`
|
|
422
422
|
`);await TM(e,r,{flag:"wx"})}async function OM(e){try{return await Pue(e),!0}catch{return!1}}function RM(e){return e.replaceAll("\\","/")}var $M;var yy=v(()=>{Ui();Yo();Cn();pe();my();Ju();$M=c.strictObject({gitSyncToken:c.string().min(1).optional(),discordBotToken:c.string().min(1).optional(),discordPublicKey:c.string().min(1).optional(),discordApplicationId:c.string().min(1).optional(),openaiApiKey:c.string().min(1).optional(),atprotoAppPassword:c.string().min(1).optional(),certificatePem:c.string().min(1).optional(),privateKeyPem:c.string().min(1).optional()})});var LM={};Lt(LM,{upgradePilotRepo:()=>pde});import{readFile as cde}from"fs/promises";import{join as lde}from"path";async function DM(e){let t=lde(e,"package.json"),o=ude.parse(JSON.parse(await cde(t,"utf8"))).devDependencies?.["@rizom/ops"];if(!o)throw Error(`${t} does not pin @rizom/ops as a devDependency`);return o}async function dde(e,t){let o=await Bun.spawn(e,{cwd:t,stdout:"inherit",stderr:"inherit"}).exited;if(o!==0)throw Error(`${e.join(" ")} failed with exit ${o}`)}async function pde(e,t={}){let r=t.exec??dde,o=await DM(e),n=t.version??"latest";await r(["bun","add","--dev","--exact",`@rizom/ops@${n}`],e);let i=await DM(e);return await r(["bun","x","brains-ops","init","."],e),{from:o,to:i}}var ude;var BM=v(()=>{pe();ude=c.object({devDependencies:c.record(c.string(),c.string()).optional()})});var MM={};Lt(MM,{migratePilotDeploySecrets:()=>ZM,migratePilotEnvSchema:()=>UM,migratePilotRepoProviderKeys:()=>vde,migrateProviderKeyFieldsYaml:()=>KR,openaiSelectorFor:()=>JR,renameProviderKeyFields:()=>Fi});import{readdir as fde,readFile as qR,writeFile as jM}from"fs/promises";import{join as No}from"path";function KR(e){let t=Wr(e,{keepSourceTokens:!0});return Fi(t)?t.toString({lineWidth:0}):e}function Fi(e){if(!mn(e.contents))return!1;return e.contents.items.filter((r)=>{if(!So(r.key)||typeof r.key.value!=="string")return!1;let o=mde[r.key.value];if(!o)return!1;if(r.key.value==="aiApiKey"&&So(r.value)&&r.value.value===wy)r.value.value=xy;return r.key.value=o,!0}).length>0}function JR(e){return e===wy?xy:e}function ZM(e){return e.replace(new RegExp(`^(\\s+- )${wy}$`,"m"),`$1${xy}`)}function UM(e){return e.replace(new RegExp(`^${wy}=`,"m"),`${xy}=`)}async function vy(e){try{return(await fde(e)).filter((r)=>r.endsWith(".yaml")).sort()}catch{return[]}}async function FR(e){try{return await qR(e,"utf8")}catch{return}}async function bde(e){let t=await vy(No(e,"cohorts")),r=await Promise.all(t.map(async(i)=>{let s=lr(await qR(No(e,"cohorts",i),"utf8"),gde);return s.ok&&s.data.aiApiKeyOverride?s.data.members:[]})),o=(await vy(No(e,"users"))).filter((i)=>!i.endsWith(".secrets.yaml")),n=await Promise.all(o.map(async(i)=>{let s=lr(await qR(No(e,"users",i),"utf8"),hde);return s.ok&&s.data.aiApiKeyOverride?[i.replace(/\.yaml$/,"")]:[]}));return[...new Set([...r.flat(),...n.flat()])]}async function Sde(e,t,r,o){let n=No(e,"users",`${t}.secrets.yaml.age`),i=await FR(n);if(i===void 0)return!1;if(!r)throw Error(`users/${t}.secrets.yaml.age may hold the legacy AI key; set AGE_SECRET_KEY or AGE_SECRET_KEY_FILE to migrate it`);let s=new op;s.addIdentity(r);let a=await s.decrypt(Mi.decode(i),"text"),l=KR(a);if(l===a)return!1;let u=new np;return u.addRecipient(o),await jM(n,Mi.encode(await u.encrypt(l))),!0}async function vde(e,t){let r=["pilot.yaml",...(await vy(No(e,"cohorts"))).map((l)=>`cohorts/${l}`),...(await vy(No(e,"users"))).filter((l)=>!l.endsWith(".secrets.yaml")).map((l)=>`users/${l}`)],o=await bde(e),n=await Promise.all([...r.map((l)=>({file:l,migrate:KR})),{file:".env.schema",migrate:UM},{file:"deploy/kamal/deploy.yml",migrate:ZM}].map(async({file:l,migrate:u})=>{let d=No(e,l),p=await FR(d);if(p===void 0)return[];let m=u(p);if(m===p)return[];return await jM(d,m),[l]})),i=lr(await FR(No(e,"pilot.yaml"))??"",yde),s=LR(e,t,Or(e)),a=o.length===0?[]:await Promise.all(o.map(async(l)=>{if(!i.ok)throw Error("pilot.yaml needs agePublicKey to re-encrypt secrets");return await Sde(e,l,s,i.data.agePublicKey)?[`users/${l}.secrets.yaml.age`]:[]}));return[...n.flat(),...a.flat()]}var wy="AI_API_KEY",xy="OPENAI_API_KEY",mde,hde,gde,yde;var _y=v(()=>{Ui();Yo();Cn();pe();Ac();yy();mde={aiApiKey:"openaiApiKey",aiApiKeyOverride:"openaiApiKeyOverride"};hde=c.looseObject({aiApiKeyOverride:c.string().optional()}),gde=c.looseObject({members:c.array(c.string()).default([]),aiApiKeyOverride:c.string().optional()}),yde=c.looseObject({agePublicKey:c.string()})});function JM(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:[..._de]};return{bundles:["core","media","automation","web","chat","site","publishing","federation"],add:["obsidian-vault"]}}function Ede(e){let t=wde.parse(e);return pi.parse({brainVersion:t.brainVersion,bundleContract:di,...JM(t.preset),githubOrg:t.githubOrg,contentRepoPrefix:t.contentRepoPrefix,domainSuffix:t.domainSuffix,openaiApiKey:JR(t.aiApiKey),gitSyncToken:t.gitSyncToken,contentRepoAdminToken:t.contentRepoAdminToken,agePublicKey:t.agePublicKey})}function kde(e){let t=xde.parse(e),r=t.presetOverride?JM(t.presetOverride):void 0;return Kr.parse({members:[...t.members],...t.brainVersionOverride?{brainVersionOverride:t.brainVersionOverride}:{},...r?{bundlesOverride:r.bundles,...r.add?{addOverride:r.add}:{},...r.remove?{removeOverride:r.remove}:{}}:{},...t.aiApiKeyOverride?{openaiApiKeyOverride:t.aiApiKeyOverride}:{},...t.gitSyncTokenOverride?{gitSyncTokenOverride:t.gitSyncTokenOverride}:{}})}function HM(e){let t=Wr(e,{keepSourceTokens:!0});if(t.errors.length>0)throw Error(`Invalid desired-state YAML: ${t.errors[0]?.message}`);if(!mn(t.contents))throw Error("Desired-state YAML must contain a mapping");return t}function HR(e,t){if(!mn(e.contents))return;return e.contents.items.find((r)=>So(r.key)&&r.key.value===t)}function qM(e,t){if(!bo(e)||!bo(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 FM(e,t){if(!e||!bo(t))return;let r=[bo(e.key)?e.key.commentBefore:void 0,bo(e.key)?e.key.comment:void 0,bo(e.value)?e.value.commentBefore:void 0,bo(e.value)?e.value.comment:void 0].filter((o)=>o!==void 0);if(r.length===0)return;t.commentBefore=[t.commentBefore,...r].filter((o)=>o!==void 0).join(`
|
|
423
423
|
`)}function VM(e,t,r,o){if(!mn(e.contents))throw Error("Desired-state YAML must contain a mapping");let n=e.contents.items.findIndex((s)=>So(s.key)&&s.key.value===t),i=e.createPair(r,[...o]);if(n>=0){let s=e.contents.items[n];qM(s?.key,i.key),qM(s?.value,i.value),e.contents.items.splice(n,1,i)}else e.contents.add(i);return i}function WM(e){let t=HM(e),r=Ede(t.toJS()),o=HR(t,"schemaVersion"),n=HR(t,"model");FM(o,HR(t,"brainVersion")?.key),t.delete("schemaVersion"),t.set("bundleContract",di);let i=VM(t,"preset","bundles",r.bundles);if(FM(n,i.key),t.delete("model"),r.add)t.set("add",r.add);else t.delete("add");if(r.remove)t.set("remove",r.remove);else t.delete("remove");return Fi(t),pi.parse(t.toJS()),t.toString({lineWidth:0})}function GM(e){let t=HM(e),r=kde(t.toJS());if(r.bundlesOverride)VM(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 Fi(t),Kr.parse(t.toJS()),t.toString({lineWidth:0})}var KM,lp,wde,xde,_de;var QM=v(()=>{_y();Cn();pe();Ac();jn();KM=c.enum(["core","default","pro"]),lp=c.string().min(1),wde=c.strictObject({schemaVersion:c.literal(1),brainVersion:$t,model:c.literal("rover"),githubOrg:c.string().min(1),contentRepoPrefix:c.string().min(1),domainSuffix:c.string().min(1),preset:KM,aiApiKey:lp,gitSyncToken:lp,contentRepoAdminToken:lp,agePublicKey:c.string().startsWith("age1").min(1)}),xde=c.strictObject({members:c.array(mr).min(1),brainVersionOverride:$t.optional(),presetOverride:KM.optional(),aiApiKeyOverride:lp.optional(),gitSyncTokenOverride:lp.optional()}).superRefine((e,t)=>{if(new Set(e.members).size!==e.members.length)t.addIssue({code:c.ZodIssueCode.custom,path:["members"],message:"cohort members must be unique"})}),_de=["series","portfolio","content-pipeline","social-media","newsletter","stock-photo"]});function XM(e,t){let r=Wr(e,{keepSourceTokens:!0});if(r.errors.length>0||!mn(r.contents))throw Error(`Invalid ${t} YAML`);return r}function $de(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}function eq(e,t,r){if(!$de(t,r.sourceBundles))throw Error(`${e} source bundles changed after review: expected [${r.sourceBundles.join(", ")}], received [${t.join(", ")}]`)}function tq(e){let t=lr(e,Tde);if(!t.ok)throw Error(`Invalid capability bundle review: ${t.error}`);return t.data}function rq(e,t){let r=XM(e,"pilot desired-state"),o=Ade.parse(r.toJS());return eq("pilot.yaml",o.bundles,t),r.set("bundleContract",di),r.set("bundles",t.targetBundles),Fi(r),pi.parse(r.toJS()),r.toString({lineWidth:0})}function nq(e,t,r){let o=XM(e,`cohort ${t}`),n=Rde.parse(o.toJS());if(n.bundlesOverride===void 0){if(r!==void 0)throw Error(`Capability bundle review names inheriting cohort ${t}`)}else{if(r===void 0)throw Error(`Cohort ${t} has an explicit legacy bundle selection but no reviewed mapping`);eq(`cohort ${t}`,n.bundlesOverride,r),o.set("bundlesOverride",r.targetBundles)}return Fi(o),Kr.parse(o.toJS()),o.toString({lineWidth:0})}var Ide,VR,Ey,Ade,Rde,YM,Tde;var oq=v(()=>{_y();Cn();pe();Ac();jn();Ide=c.enum(["core","site","publishing","team"]),VR=c.array(Ide).min(1),Ey=c.array(c.string().min(1)),Ade=c.strictObject({brainVersion:$t,bundles:VR,add:Ey.optional(),remove:Ey.optional(),githubOrg:c.string().min(1),contentRepoPrefix:c.string().min(1),domainSuffix:c.string().min(1),aiApiKey:c.string().min(1),gitSyncToken:c.string().min(1),contentRepoAdminToken:c.string().min(1),agePublicKey:c.string().startsWith("age1").min(1)}),Rde=c.strictObject({members:c.array(mr).min(1),brainVersionOverride:$t.optional(),bundlesOverride:VR.optional(),addOverride:Ey.optional(),removeOverride:Ey.optional(),aiApiKeyOverride:c.string().min(1).optional(),gitSyncTokenOverride:c.string().min(1).optional()}),YM=c.strictObject({sourceBundles:VR,targetBundles:c.array(ih).min(1)}),Tde=c.strictObject({bundleContract:c.literal(di),pilot:YM,cohorts:c.record(mr,YM)})});var lq={};Lt(lq,{loadCapabilityBundleReview:()=>jde,loadReviewedSitePins:()=>Bde,parseReviewedSitePins:()=>cq,stageLegacyCrossover:()=>Ude});import{access as Ode,cp as Cde,mkdir as iq,readFile as ol,readdir as aq,writeFile as nl}from"fs/promises";import{basename as Pde,join as Yn,relative as ky,resolve as sq}from"path";import{fileURLToPath as zde}from"url";function cq(e){let t=lr(e,Nde);if(!t.ok)throw Error(`Invalid reviewed site pins: ${t.error}`);return t.data.sites}async function Bde(e){return cq(await ol(e,"utf8"))}async function jde(e){return tq(await ol(e,"utf8"))}async function Zde(e,t){let r=Yn(e,"users"),o=(await aq(r,{withFileTypes:!0})).filter((s)=>s.isFile()&&/\.ya?ml$/.test(s.name)).map((s)=>s.name).sort(),n=new Set(Object.keys(t??{})),i=[];for(let s of o){let a=Yn(r,s),l=await ol(a,"utf8"),u=Wr(l,{keepSourceTokens:!0});if(u.errors.length>0||!mn(u.contents))throw Error(`Invalid user desired-state YAML: ${s}`);let d=Dde.parse(u.toJS());if(!d.siteOverride)continue;let p=t?.[d.handle];if(!p)throw Error(`User ${d.handle} has a siteOverride but no reviewed site pin`);if(n.delete(d.handle),p.package!==d.siteOverride.package||p.theme!==d.siteOverride.theme)throw Error(`Reviewed site pin identity does not match user ${d.handle}`);if(d.siteOverride.version!==void 0&&d.siteOverride.version!==p.version)throw Error(`Reviewed site version does not match the existing pin for user ${d.handle}`);if(d.siteOverride.themeVersion!==void 0&&d.siteOverride.themeVersion!==p.themeVersion)throw Error(`Reviewed theme version does not match the existing pin for user ${d.handle}`);if(u.setIn(["siteOverride","version"],p.version),p.themeVersion!==void 0)u.setIn(["siteOverride","themeVersion"],p.themeVersion);else u.deleteIn(["siteOverride","themeVersion"]);sh.parse(u.toJS());let m=u.toString({lineWidth:0});if(m!==l)await nl(a,m),i.push(ky(e,a))}if(n.size>0)throw Error(`Reviewed site pins do not match site users: ${[...n].sort().join(", ")}`);return i}async function Ude(e,t,r={}){let o=sq(e),n=sq(t);if(o===n||n.startsWith(`${o}/`))throw Error("Crossover output must be outside the source repository");await Cde(o,n,{recursive:!0,errorOnExist:!0,force:!1,filter:(A)=>{let O=Pde(A);return O!==".git"&&O!==".operator"&&O!==".brains-ops"&&O!==".turbo"&&O!=="dist"&&O!=="node_modules"&&O!==".env"&&O!==".env.local"&&!O.endsWith(".secrets.yaml")}});let i=[],s=Yn(n,"docs","canonical-crossover-record.md");try{await Ode(s)}catch{await iq(Yn(n,"docs"),{recursive:!0}),await nl(s,await ol(Lde,"utf8")),i.push("docs/canonical-crossover-record.md")}let a=Yn(n,"pilot.yaml"),l=await ol(a,"utf8"),d=Wr(l).toJS();if(!Uu(d))throw Error(`${a} is not a YAML mapping`);let p=Array.isArray(d.bundles),m=r.bundleReview,h;if(p){if(!m)throw Error("Current canonical desired state requires an explicit capability bundle review manifest");h=rq(l,m.pilot)}else h=WM(l);await nl(a,h),i.push("pilot.yaml");let b=Yn(n,"cohorts"),y=(await aq(b,{withFileTypes:!0})).filter((A)=>A.isFile()&&/\.ya?ml$/.test(A.name)).map((A)=>A.name).sort(),S=new Set(Object.keys(m?.cohorts??{}));for(let A of y){let O=Yn(b,A),L=await ol(O,"utf8"),z=A.replace(/\.ya?ml$/,""),J=m?.cohorts[z];if(J)S.delete(z);await nl(O,p?nq(L,z,J):GM(L)),i.push(ky(n,O))}if(p&&S.size>0)throw Error(`Capability bundle review names unknown cohorts: ${[...S].sort().join(", ")}`);i.push(...await Zde(n,r.sitePins));let x=await ut(n),_=xh(x.pilot.githubOrg);for(let A of x.users){let O=await _(A),L=Yn(n,"users",A.handle);if(await iq(L,{recursive:!0}),O.brainYaml){let z=Yn(L,"brain.yaml");await nl(z,O.brainYaml),i.push(ky(n,z))}if(O.envFile){let z=Yn(L,".env");await nl(z,O.envFile),i.push(ky(n,z))}}return await fo(n,{registry:x}),i.push("views/users.md"),{outputDir:n,changedFiles:[...new Set(i)].sort()}}var Nde,Dde,Lde;var uq=v(()=>{Cn();Mu();pe();Ac();Sk();QM();oq();Jr();uc();jn();Nde=c.strictObject({sites:c.record(mr,JE)}),Dde=c.object({handle:mr,siteOverride:c.object({package:c.string().min(1),version:$t.optional(),theme:c.string().min(1).optional(),themeVersion:$t.optional()}).optional()}).passthrough(),Lde=zde(new URL("../templates/rover-pilot/docs/canonical-crossover-record.md",import.meta.url))});var dq="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";import{webcrypto as pq}from"crypto";function qde(e){if(e<0)throw RangeError("Wrong ID size");try{if(!Ki||Ki.length<e)Ki=Buffer.allocUnsafe(e*Mde),pq.getRandomValues(Ki),il=0;else if(il+e>Ki.length)pq.getRandomValues(Ki),il=0}catch(t){throw Ki=void 0,t}il+=e}function fq(e=21){qde(e|=0);let t="";for(let r=il-e;r<il;r++)t+=dq[Ki[r]&63];return t}var Mde=128,Ki,il;var mq=()=>{};function Do(e=12){return fq(e)}var up=v(()=>{mq()});import{openSync as Fde,writeSync as Kde}from"fs";function Jde(e){return sl?`[${sl}] ${e}`:e}class Ar{static instance=null;level;context;useStderr;format;logFile;fileHandle;constructor(e={},t){if(this.level=e.level??ia.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=Fde(this.logFile,"a")}catch{}}static getInstance(e){if(!Ar.instance)Ar.instance=new Ar(e);else{if(e?.useStderr!==void 0)Ar.instance.useStderr=e.useStderr;if(e?.level!==void 0)Ar.instance.level=e.level}return Ar.instance}static resetInstance(){Ar.instance=null,sl=void 0}static setProcessRole(e){sl=e}static createFresh(e){return new Ar(e)}formatEntry(e,t,r){if(this.format==="json")return this.formatJsonEntry(e,t,r);return Jde([`[${new Date().toISOString()}]`,...this.context?[`[${this.context}]`]:[],t].join(" "))}write(e,t,r,o){if(this.format==="json")e(this.formatEntry(t,r,o));else if(o.length>0)e(this.formatEntry(t,r,[]),...o);else e(this.formatEntry(t,r,[]));if(this.fileHandle!==void 0){let n=this.formatJsonEntry(t,r,o);try{Kde(this.fileHandle,n+`
|
|
424
|
-
`)}catch{}}}formatJsonEntry(e,t,r){let o={ts:new Date().toISOString(),level:e,...sl&&{role:sl},msg:t};if(this.context)o.ctx=this.context;if(r.length>0)o.data=r;return JSON.stringify(o)}debugStream(){return this.useStderr?console.error.bind(console):console.debug.bind(console)}silly(e,...t){if(this.level<=ia.SILLY)this.write(this.debugStream(),"silly",e,t)}verbose(e,...t){if(this.level<=ia.VERBOSE)this.write(this.debugStream(),"verbose",e,t)}debug(e,...t){if(this.level<=ia.DEBUG)this.write(this.debugStream(),"debug",e,t)}info(e,...t){if(this.level<=ia.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<=ia.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=ia.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new Ar({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var ia,sl,VNe;var WR=v(()=>{ia={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};VNe=Ar.getInstance()});var GR,Hde,al,YNe;var dp=v(()=>{Tt();pe();GR=c.enum(["file_operations","content_operations","data_processing","batch_processing"]),Hde=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:GR,operationTarget:c.string().optional(),interfaceType:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:Bn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:po.optional()}),al=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:GR,operationTarget:c.string().optional(),interfaceType:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:Bn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:po.optional(),rootJobId:c.string()}),YNe=c.enum(["none","skip","replace","coalesce"])});var Vde,Ji=15000;var pp=v(()=>{dp();pe();Vde=c.object({id:c.string(),type:c.string(),data:c.string(),status:c.enum(["pending","processing","completed","failed"]),source:c.string().nullable(),priority:c.number(),retryCount:c.number(),maxRetries:c.number(),lastError:c.string().nullable(),lastErrorPublic:c.unknown(),createdAt:c.number(),scheduledFor:c.number(),startedAt:c.number().nullable(),completedAt:c.number().nullable(),attemptId:c.string().nullable(),workerSlotId:c.string().nullable(),workerSessionId:c.string().nullable(),leaseExpiresAt:c.number().nullable(),attemptHeartbeatAt:c.number().nullable(),runtimeUpdatedAt:c.number().nullable(),metadata:al,progress:c.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:c.unknown().nullable().optional()})});var QR,hq,Oe,Wde,Gde,gq,yq,bq;var Lo=v(()=>{Tt();pe();dp();QR=c.enum(["pending","processing","completed","failed"]),hq=c.enum(["completed","failed"]),Oe={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},Wde=c.object({id:c.string(),type:c.string(),status:QR,data:c.unknown(),result:c.unknown().optional(),lastError:c.string().optional().nullable(),attempts:c.number(),maxRetries:c.number(),priority:c.number(),createdAt:c.date(),updatedAt:c.date(),processedAt:c.date().optional().nullable(),completedAt:c.date().optional().nullable(),failedAt:c.date().optional().nullable()}),Gde=c.object({jobId:c.string(),type:c.string(),status:hq,result:c.unknown().optional(),error:c.string().optional()}),gq=c.object({success:c.literal(!1),error:c.string().optional()}),yq=c.object({id:c.string(),type:c.enum(["job","batch"]),status:QR,message:c.string().optional(),progress:c.object({current:c.number(),total:c.number(),percentage:c.number()}).optional(),aggregationKey:c.string().optional(),batchDetails:c.object({totalOperations:c.number(),completedOperations:c.number(),failedOperations:c.number(),currentOperation:c.string().optional(),errors:c.array(c.string()).optional()}).optional(),jobDetails:c.object({jobType:c.string(),priority:c.number(),retryCount:c.number()}).optional(),metadata:al}),bq=ui(UE.progress,yq)});var Ce,Gt;var vn=v(()=>{Ce=class Ce extends Error{code;extendedCode;rawCode;constructor(e,t,r,o,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=o,this.name="LibsqlError"}};Gt=class Gt extends Ce{statementIndex;constructor(e,t,r,o,n,i){super(e,r,o,n,i);this.statementIndex=t,this.name="LibsqlBatchError"}}});function Sq(e){let t=Qde.exec(e);if(t===null)throw new Ce(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,o=r.scheme,n=r.authority!==void 0?Yde(r.authority):void 0,i=sa(r.path),s=r.query!==void 0?epe(r.query):void 0,a=r.fragment!==void 0?sa(r.fragment):void 0;return{scheme:o,authority:n,path:i,query:s,fragment:a}}function Yde(e){let t=Xde.exec(e);if(t===null)throw new Ce("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,o=sa(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,i=r.username!==void 0?{username:sa(r.username),password:r.password!==void 0?sa(r.password):void 0}:void 0;return{host:o,port:n,userinfo:i}}function epe(e){let t=e.split("&"),r=[];for(let o of t){if(o==="")continue;let n,i,s=o.indexOf("=");if(s<0)n=o,i="";else n=o.substring(0,s),i=o.substring(s+1);r.push({key:sa(n.replaceAll("+"," ")),value:sa(i.replaceAll("+"," "))})}return{pairs:r}}function sa(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Ce(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function fp(e,t,r){if(t===void 0)throw new Ce(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let o=`${e}:`,n=tpe(t.host),i=rpe(t.port),a=`//${npe(t.userinfo)}${n}${i}`,l=r.split("/").map(encodeURIComponent).join("/");if(l!==""&&!l.startsWith("/"))l="/"+l;return new URL(`${o}${a}${l}`)}function tpe(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function rpe(e){return e!==void 0?`:${e}`:""}function npe(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var Qde,Xde;var Iy=v(()=>{vn();Qde=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();Xde=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var ll,vq,wq,mp,Ay,ope,Qt,xq,kq=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),Iq=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),Aq=(e)=>{let t,r,o,n,i="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(o=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|o<<8|n,i+=mp[t>>18&63]+mp[t>>12&63]+mp[t>>6&63]+mp[t&63]}return s?i.slice(0,s-3)+"===".substring(s):i},eT,YR,Ry=(e,t=!1)=>t?kq(YR(e)):YR(e),ipe=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?Qt(192|t>>>6)+Qt(128|t&63):Qt(224|t>>>12&15)+Qt(128|t>>>6&63)+Qt(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return Qt(240|t>>>18&7)+Qt(128|t>>>12&63)+Qt(128|t>>>6&63)+Qt(128|t&63)}},spe,Rq=(e)=>e.replace(spe,ipe),_q,cl=(e,t=!1)=>t?kq(_q(e)):_q(e),Eq=(e)=>cl(e,!0),ape,cpe=(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 Qt((r>>>10)+55296)+Qt((r&1023)+56320);case 3:return Qt((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return Qt((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},Tq=(e)=>e.replace(ape,cpe),$q=(e)=>{if(e=e.replace(/\s+/g,""),!ope.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,o,n=[];for(let i=0;i<e.length;)if(t=Ay[e.charAt(i++)]<<18|Ay[e.charAt(i++)]<<12|(r=Ay[e.charAt(i++)])<<6|(o=Ay[e.charAt(i++)]),r===64)n.push(Qt(t>>16&255));else if(o===64)n.push(Qt(t>>16&255,t>>8&255));else n.push(Qt(t>>16&255,t>>8&255,t&255));return n.join("")},tT,Oq,Cq=(e)=>Oq(Pq(e)),lpe,Pq=(e)=>Iq(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),XR=(e)=>lpe(Pq(e)),upe=(e)=>{if(typeof e!=="string")return!1;let t=e.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},zq=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),Nq=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,zq(r));e("fromBase64",function(){return XR(this)}),e("toBase64",function(t){return cl(this,t)}),e("toBase64URI",function(){return cl(this,!0)}),e("toBase64URL",function(){return cl(this,!0)}),e("toUint8Array",function(){return Cq(this)})},Dq=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,zq(r));e("toBase64",function(t){return Ry(this,t)}),e("toBase64URI",function(){return Ry(this,!0)}),e("toBase64URL",function(){return Ry(this,!0)})},dpe=()=>{Nq(),Dq()},ul;var Ty=v(()=>{ll=typeof Buffer==="function",vq=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,wq=typeof TextEncoder==="function"?new TextEncoder:void 0,mp=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),Ay=((e)=>{let t={};return e.forEach((r,o)=>t[r]=o),t})(mp),ope=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,Qt=String.fromCharCode.bind(String),xq=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),eT=typeof btoa==="function"?(e)=>btoa(e):ll?(e)=>Buffer.from(e,"binary").toString("base64"):Aq,YR=ll?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let o=0,n=e.length;o<n;o+=4096)r.push(Qt.apply(null,e.subarray(o,o+4096)));return eT(r.join(""))},spe=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,_q=ll?(e)=>Buffer.from(e,"utf8").toString("base64"):wq?(e)=>YR(wq.encode(e)):(e)=>eT(Rq(e)),ape=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,tT=typeof atob==="function"?(e)=>atob(Iq(e)):ll?(e)=>Buffer.from(e,"base64").toString("binary"):$q,Oq=ll?(e)=>xq(Buffer.from(e,"base64")):(e)=>xq(tT(e).split("").map((t)=>t.charCodeAt(0))),lpe=ll?(e)=>Buffer.from(e,"base64").toString("utf8"):vq?(e)=>vq.decode(Oq(e)):(e)=>Tq(tT(e)),ul={version:"3.8.0",VERSION:"3.8.0",atob:tT,atobPolyfill:$q,btoa:eT,btoaPolyfill:Aq,fromBase64:XR,toBase64:cl,encode:cl,encodeURI:Eq,encodeURL:Eq,utob:Rq,btou:Tq,decode:XR,isValid:upe,fromUint8Array:Ry,toUint8Array:Cq,extendString:Nq,extendUint8Array:Dq,extendBuiltins:dpe}});function Hi(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 dl{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,o,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=o,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(ppe),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function ppe(e){return Array.prototype.map.call(e,fpe)}function fpe(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return ul.fromUint8Array(new Uint8Array(e));else return e}var Xn="https://github.com/libsql/libsql-client-ts#supported-urls";var pl=v(()=>{Ty()});function Bq(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function hp(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:o,tls:n,intMode:i,concurrency:s}=e;s=Math.max(0,s||20),i??="number";let a=[];if(r===Lq)r="file::memory:";let l=Sq(r),u=l.scheme.toLowerCase(),d=u==="file"&&l.path===Lq&&l.authority===void 0,p;if(d)p={cache:{values:["shared","private"],update:(y,S)=>a.push(`${y}=${S}`)}};else p={tls:{values:["0","1"],update:(y,S)=>n=S==="1"},authToken:{update:(y,S)=>o=S}};for(let{key:y,value:S}of l.query?.pairs??[]){if(!Object.hasOwn(p,y))throw new Ce(`Unsupported URL query parameter ${JSON.stringify(y)}`,"URL_PARAM_NOT_SUPPORTED");let x=p[y];if(x.values!==void 0&&!x.values.includes(S))throw new Ce(`Unknown value for the "${y}" query argument: ${JSON.stringify(S)}. Supported values are: [${x.values.map((_)=>'"'+_+'"').join(", ")}]`,"URL_INVALID");if(x.update!==void 0)x?.update(y,S)}let m=a.length===0?"":`?${a.join("&")}`,h=l.path+m,b;if(u==="libsql")if(n===!1){if(l.authority?.port===void 0)throw new Ce('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");b=t?"http":"ws"}else b=t?"https":"wss";else b=u;if(b==="http"||b==="ws")n??=!1;else n??=!0;if(b!=="http"&&b!=="ws"&&b!=="https"&&b!=="wss"&&b!=="file")throw new Ce(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(l.scheme+":")}. For more information, please read ${Xn}`,"URL_SCHEME_NOT_SUPPORTED");if(i!=="number"&&i!=="bigint"&&i!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(i)}`);if(l.fragment!==void 0)throw new Ce(`URL fragments are not supported: ${JSON.stringify("#"+l.fragment)}`,"URL_INVALID");if(d)return{scheme:"file",tls:!1,path:h,intMode:i,concurrency:s,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout,authToken:void 0,encryptionKey:void 0,remoteEncryptionKey:void 0,authority:void 0};return{scheme:b,tls:n,authority:l.authority,path:h,authToken:o,intMode:i,concurrency:s,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout}}var Lq=":memory:";var gp=v(()=>{vn();Iy();pl()});var Zq=ge(function(nn){var mpe=nn&&nn.__createBinding||(Object.create?function(e,t,r,o){if(o===void 0)o=r;var n=Object.getOwnPropertyDescriptor(t,r);if(!n||("get"in n?!t.__esModule:n.writable||n.configurable))n={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,o,n)}:function(e,t,r,o){if(o===void 0)o=r;e[o]=t[r]}),hpe=nn&&nn.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),jq=nn&&nn.__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))mpe(t,e,r)}return hpe(t,e),t};Object.defineProperty(nn,"__esModule",{value:!0});nn.load=nn.currentTarget=void 0;var gpe=jq(qr("path")),ype=jq(qr("fs"));function bpe(){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 Spe()?`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}`)}nn.currentTarget=bpe;function Spe(){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 vpe(e){let t=gpe.join(e,"index.node");return ype.existsSync(t)?qr(t):null}nn.load=vpe});var qq=ge(function(S2e,Mq){var Uq=()=>process.platform==="linux",rT=null,wpe=()=>{if(!rT)rT=Uq()&&process.report?process.report.getReport():{};return rT};Mq.exports={isLinux:Uq,getReport:wpe}});var Jq=ge(function(v2e,Kq){var Fq=qr("fs"),xpe=(e)=>Fq.readFileSync(e,"utf-8"),_pe=(e)=>new Promise((t,r)=>{Fq.readFile(e,"utf-8",(o,n)=>{if(o)r(o);else t(n)})});Kq.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:xpe,readFile:_pe}});var l4=ge(function(w2e,c4){var Vq=qr("child_process"),{isLinux:fl,getReport:Wq}=qq(),{LDD_PATH:$y,readFile:Gq,readFileSync:Qq}=Jq(),eo,to,Vi="",Yq=()=>{if(!Vi)return new Promise((e)=>{Vq.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{Vi=t?" ":r,e(Vi)})});return Vi},Xq=()=>{if(!Vi)try{Vi=Vq.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){Vi=" "}return Vi},Bo="glibc",e4=/GLIBC\s(\d+\.\d+)/,aa="musl",Epe=Bo.toUpperCase(),kpe=aa.toLowerCase(),Ipe=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),t4=()=>{let e=Wq();if(e.header&&e.header.glibcVersionRuntime)return Bo;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(Ipe))return aa}return null},r4=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(Bo))return Bo;if(r&&r.includes(aa))return aa;return null},n4=(e)=>{if(e.includes(kpe))return aa;if(e.includes(Epe))return Bo;return null},Ape=async()=>{if(eo!==void 0)return eo;eo=null;try{let e=await Gq($y);eo=n4(e)}catch(e){}return eo},Rpe=()=>{if(eo!==void 0)return eo;eo=null;try{let e=Qq($y);eo=n4(e)}catch(e){}return eo},o4=async()=>{let e=null;if(fl()){if(e=await Ape(),!e)e=t4();if(!e){let t=await Yq();e=r4(t)}}return e},i4=()=>{let e=null;if(fl()){if(e=Rpe(),!e)e=t4();if(!e){let t=Xq();e=r4(t)}}return e},Tpe=async()=>fl()&&await o4()!==Bo,$pe=()=>fl()&&i4()!==Bo,Ope=async()=>{if(to!==void 0)return to;to=null;try{let t=(await Gq($y)).match(e4);if(t)to=t[1]}catch(e){}return to},Cpe=()=>{if(to!==void 0)return to;to=null;try{let t=Qq($y).match(e4);if(t)to=t[1]}catch(e){}return to},s4=()=>{let e=Wq();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},Hq=(e)=>e.trim().split(/\s+/)[1],a4=(e)=>{let[t,r,o]=e.split(/[\r\n]+/);if(t&&t.includes(Bo))return Hq(t);if(r&&o&&r.includes(aa))return Hq(o);return null},Ppe=async()=>{let e=null;if(fl()){if(e=await Ope(),!e)e=s4();if(!e){let t=await Yq();e=a4(t)}}return e},zpe=()=>{let e=null;if(fl()){if(e=Cpe(),!e)e=s4();if(!e){let t=Xq();e=a4(t)}}return e};c4.exports={GLIBC:Bo,MUSL:aa,family:o4,familySync:i4,isNonGlibcLinux:Tpe,isNonGlibcLinuxSync:$pe,version:Ppe,versionSync:zpe}});var d4=ge(function(x2e,u4){var Npe={ALLOW:0,DENY:1};u4.exports=Npe});var f4=ge(function(_2e,p4){var nT={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function ca(e,t,r){if(new.target!==ca)return new ca(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),nT.value=""+e,Object.defineProperty(this,"message",nT),Error.captureStackTrace(this,ca),this.code=t,this.rawCode=r}Object.setPrototypeOf(ca,Error);Object.setPrototypeOf(ca.prototype,Error.prototype);Object.defineProperty(ca.prototype,"name",nT);p4.exports=ca});var w4=ge(function(E2e,Oy){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:Dpe,currentTarget:Lpe}=Zq(),{familySync:m4,GLIBC:Bpe,MUSL:jpe}=l4();function Zpe(){if(process.env.LIBSQL_JS_DEV)return Dpe(__dirname);let e=Lpe();if(m4()==Bpe)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"&&m4()==jpe)e="linux-arm-musleabihf";return qr(`@libsql/${e}`)}var{databaseOpen:Upe,databaseOpenWithSync:Mpe,databaseInTransaction:qpe,databaseInterrupt:Fpe,databaseClose:Kpe,databaseSyncSync:Jpe,databaseSyncUntilSync:Hpe,databaseExecSync:Vpe,databasePrepareSync:Wpe,databaseDefaultSafeIntegers:Gpe,databaseAuthorizer:Qpe,databaseLoadExtension:Ype,databaseMaxWriteReplicationIndex:Xpe,statementRaw:efe,statementIsReader:tfe,statementGet:h4,statementRun:g4,statementInterrupt:rfe,statementRowsSync:y4,statementColumns:nfe,statementSafeIntegers:ofe,rowsNext:ife}=Zpe(),sfe=d4(),b4=f4();function ml(e){if(e.libsqlError)return new b4(e.message,e.code,e.rawCode);return e}class S4{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var o="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),o=t.syncAuth;else if(t.authToken)o=t.authToken;let i=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,l=t?.offline??!1,u=t?.remoteEncryptionKey??"";this.db=Mpe(e,t.syncUrl,o,r,i,s,a,l,u)}else{let i=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,l=t?.remoteEncryptionKey??"";this.db=Upe(e,i,r,s,a,l)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let n=this.db;Object.defineProperties(this,{inTransaction:{get(){return qpe(n)}}})}sync(){return Jpe.call(this.db)}syncUntil(e){return Hpe.call(this.db,e)}prepare(e){try{let t=Wpe.call(this.db,e);return new v4(t)}catch(t){throw ml(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...i)=>{t.exec("BEGIN "+n);try{let s=e(...i);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},o={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(o.default.value,o),Object.defineProperties(o.deferred.value,o),Object.defineProperties(o.immediate.value,o),Object.defineProperties(o.exclusive.value,o),o.default.value}pragma(e,t){if(t==null)t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");let r=t.simple,o=this.prepare(`PRAGMA ${e}`,this,!0);return r?o.pluck().get():o.all()}backup(e,t){throw Error("not implemented")}serialize(e){throw Error("not implemented")}function(e,t,r){if(t==null)t={};if(typeof t==="function")r=t,t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof r!=="function")throw TypeError("Expected last argument to be a function");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}aggregate(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object"||t===null)throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}table(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(!e)throw TypeError("Virtual table module name cannot be an empty string");throw Error("not implemented")}authorizer(e){Qpe.call(this.db,e)}loadExtension(...e){Ype.call(this.db,...e)}maxWriteReplicationIndex(){return Xpe.call(this.db)}exec(e){try{Vpe.call(this.db,e)}catch(t){throw ml(t)}}interrupt(){Fpe.call(this.db)}close(){Kpe.call(this.db),this.open=!1}defaultSafeIntegers(e){return Gpe.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class v4{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return efe.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return tfe.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return g4.call(this.stmt,e[0]);else return g4.call(this.stmt,e.flat())}catch(t){throw ml(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return h4.call(this.stmt,e[0]);else return h4.call(this.stmt,e.flat())}catch(t){throw ml(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=y4.call(this.stmt,e[0]);else t=y4.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)ife.call(t,this.nextRows),this.nextRowIndex=0;let o=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!o)return{done:!0};return this.nextRowIndex++,{value:o,done:!1}}catch(o){throw ml(o)}},[Symbol.iterator](){return this}}}all(...e){try{let t=[];for(let r of this.iterate(...e))if(this.pluckMode)t.push(r[Object.keys(r)[0]]);else t.push(r);return t}catch(t){throw ml(t)}}interrupt(){rfe.call(this.stmt)}columns(){return nfe.call(this.stmt)}safeIntegers(e){return ofe.call(this.stmt,e??!0),this}}Oy.exports=S4;Oy.exports.Authorization=sfe;Oy.exports.SqliteError=b4});import{Buffer as _4}from"buffer";function E4(e){if(e.scheme!=="file")throw new Ce(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${Xn}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Ce(`Invalid host in file URL: ${JSON.stringify(t.host)}. A "file:" URL with an absolute path should start with one slash ("file:/absolute/path.db") or with three slashes ("file:///absolute/path.db"). For more information, please read ${Xn}`,"URL_INVALID");if(t.port!==void 0)throw new Ce("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Ce("File URL cannot have username and password","URL_INVALID")}let r=Bq(e);if(r&&e.syncUrl)throw new Ce(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let o=e.path;if(r)o=`${e.scheme}:${e.path}`;let n={authToken:e.authToken,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncPeriod:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,timeout:e.timeout},i=new yp.default(o,n);return zt(i,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new k4(o,n,i,e.intMode)}class k4{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,o){this.#e=e,this.#t=t,this.#r=r,this.#n=o,this.closed=!1,this.protocol="file"}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#o(),zt(this.#i(),r,this.#n)}async batch(e,t="deferred"){this.#o();let r=this.#i();try{zt(r,Hi(t),this.#n);let o=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new Gt("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let i=e[n],s=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;o.push(zt(r,s,this.#n))}catch(i){if(i instanceof Gt)throw i;if(i instanceof Ce)throw new Gt(i.message,n,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return zt(r,"COMMIT",this.#n),o}finally{if(r.inTransaction)zt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#o();let t=this.#i();try{zt(t,"PRAGMA foreign_keys=off",this.#n),zt(t,Hi("deferred"),this.#n);let r=[];for(let o=0;o<e.length;o++)try{if(!t.inTransaction)throw new Gt("The transaction has been rolled back",o,"TRANSACTION_CLOSED");r.push(zt(t,e[o],this.#n))}catch(n){if(n instanceof Gt)throw n;if(n instanceof Ce)throw new Gt(n.message,o,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return zt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)zt(t,"ROLLBACK",this.#n);zt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#i();return zt(t,Hi(e),this.#n),this.#r=null,new I4(t,this.#n)}async executeMultiple(e){this.#o();let t=this.#i();try{return A4(t,e)}finally{if(t.inTransaction)zt(t,"ROLLBACK",this.#n)}}async sync(){this.#o();let e=await this.#i().sync();return{frames_synced:e.frames_synced,frame_no:e.frame_no}}async reconnect(){try{if(!this.closed&&this.#r!==null)this.#r.close()}finally{this.#r=new yp.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#o(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED")}#i(){if(this.#r===null)this.#r=new yp.default(this.#e,this.#t);return this.#r}}class I4{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#r(),zt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let o=e[r],n=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;t.push(zt(this.#e,n,this.#t))}catch(o){if(o instanceof Gt)throw o;if(o instanceof Ce)throw new Gt(o.message,r,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return t}async executeMultiple(e){return this.#r(),A4(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),zt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),zt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)zt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Ce("The transaction is closed","TRANSACTION_CLOSED")}}function zt(e,t,r){let o,n;if(typeof t==="string")o=t,n=[];else if(o=t.sql,Array.isArray(t.args))n=t.args.map((i)=>x4(i,r));else{n={};for(let i in t.args){let s=i[0]==="@"||i[0]==="$"||i[0]===":"?i.substring(1):i;n[s]=x4(t.args[i],r)}}try{let i=e.prepare(o);i.safeIntegers(!0);let s=!0;try{i.raw(!0)}catch{s=!1}if(s){let a=Array.from(i.columns().map((m)=>m.name)),l=Array.from(i.columns().map((m)=>m.type??"")),u=i.all(n).map((m)=>afe(m,a,r)),d=0,p=void 0;return new dl(a,l,u,0,void 0)}else{let a=i.run(n),l=a.changes,u=BigInt(a.lastInsertRowid);return new dl([],[],[],l,u)}}catch(i){throw R4(i)}}function afe(e,t,r){let o={};Object.defineProperty(o,"length",{value:e.length});for(let n=0;n<e.length;++n){let i=cfe(e[n],r);Object.defineProperty(o,n,{value:i});let s=t[n];if(!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function cfe(e,t){if(typeof e==="bigint")if(t==="number"){if(e<lfe||e>ufe)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 _4)return e.buffer;return e}function x4(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<dfe||e>pfe)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 _4.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 A4(e,t){try{e.exec(t)}catch(r){throw R4(r)}}function R4(e){if(e instanceof yp.default.SqliteError){let t=e.code,r=ffe(e.rawCode);return new Ce(e.message,r,t,e.rawCode,e)}return e}function ffe(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return mfe[t]??`SQLITE_UNKNOWN_${t.toString()}`}var yp,lfe,ufe=9007199254740991n,dfe,pfe=9223372036854775807n,mfe;var T4=v(()=>{vn();gp();pl();yp=Fl(w4(),1);vn();lfe=-9007199254740991n;dfe=-9223372036854775808n;mfe={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 Wi;var oT=v(()=>{if(typeof WebSocket<"u")Wi=WebSocket;else if(typeof global<"u")Wi=global.WebSocket;else if(typeof window<"u")Wi=window.WebSocket;else if(typeof self<"u")Wi=self.WebSocket});class hl{constructor(){this.intMode="number"}intMode}var Ge,Pe,bp,xt,Sp,gl,la,wn,or,ro;var _t=v(()=>{Ge=class Ge extends Error{constructor(e){super(e);this.name="ClientError"}};Pe=class Pe extends Ge{constructor(e){super(e);this.name="ProtoError"}};bp=class bp extends Ge{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};xt=class xt extends Ge{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};Sp=class Sp extends Ge{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};gl=class gl extends Ge{constructor(e){super(e);this.name="WebSocketError"}};la=class la extends Ge{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};wn=class wn extends Ge{constructor(e){super(e);this.name="ProtocolVersionError"}};or=class or extends Ge{constructor(e){super(e);this.name="InternalError"}};ro=class ro extends Ge{constructor(e){super(e);this.name="MisuseError"}}});function Rr(e){if(typeof e==="string")return e;throw yl(e,"string")}function Zr(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw yl(e,"string or null")}function jo(e){if(typeof e==="number")return e;throw yl(e,"number")}function Gi(e){if(typeof e==="boolean")return e;throw yl(e,"boolean")}function vp(e){if(Array.isArray(e))return e;throw yl(e,"array")}function It(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw yl(e,"object")}function xn(e,t){return vp(e).map((r)=>t(It(r)))}function yl(e,t){if(e===void 0)return new Pe(`Expected ${t}, but the property was missing`);let r=typeof e;if(e===null)r="null";else if(Array.isArray(e))r="array";return new Pe(`Expected ${t}, received ${r}`)}function ua(e,t){return t(It(e))}var bl=v(()=>{_t()});class $4{#e;#t;constructor(e){this.#e=e,this.#t=!1}begin(){this.#e.push("{"),this.#t=!0}end(){this.#e.push("}"),this.#t=!1}#r(e){if(this.#t)this.#e.push('"'),this.#t=!1;else this.#e.push(',"');this.#e.push(e),this.#e.push('":')}string(e,t){this.#r(e),this.#e.push(JSON.stringify(t))}stringRaw(e,t){this.#r(e),this.#e.push('"'),this.#e.push(t),this.#e.push('"')}number(e,t){this.#r(e),this.#e.push(""+t)}boolean(e,t){this.#r(e),this.#e.push(t?"true":"false")}object(e,t,r){this.#r(e),this.begin(),r(this,t),this.end()}arrayObjects(e,t,r){this.#r(e),this.#e.push("[");for(let o=0;o<t.length;++o){if(o!==0)this.#e.push(",");this.begin(),r(this,t[o]),this.end()}this.#e.push("]")}}function wp(e,t){let r=[],o=new $4(r);return o.begin(),t(o,e),o.end(),r.join("")}var da=0,xp=1,_p=2,O4=5;class C4{#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 P4{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new Pe(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(_p);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return Qi(this.bytes(),e)}int32(){return this.#r(da),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r(da),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(xp),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===da)this.#e.skipVarint();else if(this.#t===xp)this.#e.skip(8);else if(this.#t===_p){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===O4)this.#e.skip(4);else throw new Pe(`Unexpected wire type ${this.#t}`);this.#t=-1}}function Qi(e,t){let r=new C4(e),o=new P4(r),n=t.default();while(!r.eof()){let i=r.varint(),s=i>>3,a=i&7;o.setup(a);let l=t[s];if(l!==void 0){let u=l(o,n);if(u!==void 0)n=u}o.maybeSkip()}return n}var iT=v(()=>{_t()});class sT{#e;#t;#r;#n;constructor(){this.#e=new ArrayBuffer(256),this.#t=new Uint8Array(this.#e),this.#r=new DataView(this.#e),this.#n=0}#o(e){if(this.#n+e<=this.#e.byteLength)return;let t=this.#e.byteLength;while(t<this.#n+e)t*=2;let r=new ArrayBuffer(t),o=new Uint8Array(r),n=new DataView(r);o.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=o,this.#r=n}#i(e){this.#o(5),e=0|e;do{let t=e&127;e>>>=7,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#a(e){this.#o(10),e=e&0xffffffffffffffffn;do{let t=Number(e&0x7fn);e>>=7n,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#s(e,t){this.#i(e<<3|t)}bytes(e,t){this.#s(e,_p),this.#i(t.byteLength),this.#o(t.byteLength),this.#t.set(t,this.#n),this.#n+=t.byteLength}string(e,t){this.bytes(e,new TextEncoder().encode(t))}message(e,t,r){let o=new sT;r(o,t),this.bytes(e,o.data())}int32(e,t){this.#s(e,da),this.#i(t)}uint32(e,t){this.int32(e,t)}bool(e,t){this.int32(e,t?1:0)}sint64(e,t){this.#s(e,da),this.#a(t<<1n^t>>63n)}double(e,t){this.#s(e,xp),this.#o(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function Ep(e,t){let r=new sT;return t(r,e),r.data()}var z4=()=>{};var aT=v(()=>{bl();iT();z4()});class Yi{#e;#t;constructor(){this.#e=new Set,this.#t=new Set}alloc(){for(let t of this.#t){if(this.#t.delete(t),this.#e.add(t),!this.#e.has(this.#e.size-1))this.#t.add(this.#e.size-1);return t}let e=this.#e.size;return this.#e.add(e),e}free(e){if(!this.#e.delete(e))throw new or("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var cT=v(()=>{_t()});function Je(e,t){throw new or(t)}var on=v(()=>{_t()});function Sl(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<gfe||e>yfe)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 lT(e,t){if(e===null)return null;else if(typeof e==="number")return e;else if(typeof e==="string")return e;else if(typeof e==="bigint")if(t==="number"){let r=Number(e);if(!Number.isSafeInteger(r))throw RangeError("Received integer which is too large to be safely represented as a JavaScript number");return r}else if(t==="bigint")return e;else if(t==="string")return""+e;else throw new ro("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new Pe("Received unrecognized type of Value");else throw Je(e,"Impossible type of Value")}var gfe,yfe=9223372036854775807n;var uT=v(()=>{_t();on();gfe=-9223372036854775808n});function pa(e){return{affectedRowCount:e.affectedRowCount,lastInsertRowid:e.lastInsertRowid,columnNames:e.cols.map((t)=>t.name),columnDecltypes:e.cols.map((t)=>t.decltype)}}function Py(e,t){let r=pa(e),o=e.rows.map((n)=>N4(r.columnNames,n,t));return{...r,rows:o}}function zy(e,t){let r=pa(e),o;if(e.rows.length>0)o=N4(r.columnNames,e.rows[0],t);return{...r,row:o}}function Ny(e,t){let r=pa(e),o;if(e.rows.length>0&&r.columnNames.length>0)o=lT(e.rows[0][0],t);return{...r,value:o}}function N4(e,t,r){let o={};Object.defineProperty(o,"length",{value:t.length});for(let n=0;n<t.length;++n){let i=lT(t[n],r);Object.defineProperty(o,n,{value:i});let s=e[n];if(s!==void 0&&!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function Zo(e){return new bp(e.message,e)}var kp=v(()=>{_t();uT()});class fa{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new ro("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new xt("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new Ge("SQL text was manually closed"))}_setClosed(e){if(this.#r===void 0)this.#r=e,this.#e._closeSql(this.#t)}get closed(){return this.#r!==void 0}}function Ip(e,t){if(t instanceof fa)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var vl=v(()=>{_t()});class Xi{#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 Ap{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(Sl(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]=Sl(t),this}bindName(e,t){return this._namedArgs.set(e,Sl(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function Dy(e,t,r){let o,n=[],i=[];if(t instanceof Ap){o=t.sql,n=t._args;for(let[l,u]of t._namedArgs.entries())i.push({name:l,value:u})}else if(Array.isArray(t))if(o=t[0],Array.isArray(t[1]))n=t[1].map((l)=>Sl(l));else i=Object.entries(t[1]).map(([l,u])=>({name:l,value:Sl(u)}));else o=t;let{sql:s,sqlId:a}=Ip(e,o);return{sql:s,sqlId:a,args:n,namedArgs:i,wantRows:r}}var Ly=v(()=>{vl();uT()});class By{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new dT(this)}execute(){if(this.#t)throw new ro("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return Sfe(this._stream,this._steps,e);else return bfe(this._stream,this._steps,e)}}function bfe(e,t,r){return e._batch(r).then((o)=>{for(let n=0;n<t.length;++n){let i=o.stepResults.get(n),s=o.stepErrors.get(n);t[n].callback(i,s)}})}async function Sfe(e,t,r){let o=await e._openCursor(r);try{let n=0,i=void 0,s=[];for(;;){let a=await o.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new Pe("Server produced StepBeginEntry for unexpected step");else if(i!==void 0)throw new Pe("Server produced StepBeginEntry before terminating previous step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0);n=a.step+1,i=a,s=[]}else if(a.type==="step_end"){if(i===void 0)throw new Pe("Server produced StepEndEntry but no step is active");let l={cols:i.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[i.step].callback(l,void 0),i=void 0,s=[]}else if(a.type==="step_error"){if(i===void 0){if(a.step>=t.length)throw new Pe("Server produced StepErrorEntry for unexpected step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0)}else{if(a.step!==i.step)throw new Pe("Server produced StepErrorEntry for unexpected step");i=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(i===void 0)throw new Pe("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw Zo(a.error);else if(a.type==="none")throw new Pe("Server produced unrecognized CursorEntry");else throw Je(a,"Impossible CursorEntry")}if(i!==void 0)throw new Pe("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{o.close()}}class dT{_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,Py)}queryRow(e){return this.#t(e,!0,zy)}queryValue(e){return this.#t(e,!0,Ny)}run(e){return this.#t(e,!1,pa)}#t(e,t,r){if(this._index!==void 0)throw new ro("This BatchStep has already been added to the batch");let o=Dy(this._batch._stream._sqlOwner(),e,t),n;if(this.#e.length===0)n=void 0;else if(this.#e.length===1)n=this.#e[0];else n={type:"and",conds:this.#e.slice()};let i={stmt:o,condition:n};return new Promise((s,a)=>{let l=(u,d)=>{if(u!==void 0&&d!==void 0)a(new Pe("Server returned both result and error"));else if(d!==void 0)a(Zo(d));else if(u!==void 0)s(r(u,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:i,callback:l})})}}class dt{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new dt(e._batch,{type:"ok",step:D4(e)})}static error(e){return new dt(e._batch,{type:"error",step:D4(e)})}static not(e){return new dt(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)L4(e,r);return new dt(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)L4(e,r);return new dt(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new dt(e,{type:"is_autocommit"})}}function D4(e){if(e._index===void 0)throw new ro("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function L4(e,t){if(t._batch!==e)throw new ro("Cannot mix BatchCond objects for different Batch objects")}var pT=v(()=>{_t();kp();Ly();on()});function B4(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class wl{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,Py)}queryRow(e){return this.#e(e,!0,zy)}queryValue(e){return this.#e(e,!0,Ny)}run(e){return this.#e(e,!1,pa)}#e(e,t,r){let o=Dy(this._sqlOwner(),e,t);return this._execute(o).then((n)=>r(n,this.intMode))}batch(e=!1){return new By(this,e)}describe(e){let t=Ip(this._sqlOwner(),e);return this._describe(t).then(B4)}sequence(e){let t=Ip(this._sqlOwner(),e);return this._sequence(t)}intMode}var jy=v(()=>{pT();kp();vl();Ly()});class Rp{}var vfe=1000,wfe=10,fT;var j4=v(()=>{_t();fT=class fT extends Rp{#e;#t;#r;#n;#o;#i;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new Xi,this.#o=new Xi,this.#i=void 0,this.#a=!1}async next(){for(;;){if(this.#i!==void 0)throw new xt("Cursor is closed",this.#i);while(!this.#a&&this.#o.length<wfe)this.#o.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#o.shift().then((t)=>{if(t===void 0)return;for(let r of t.entries)this.#n.push(r);this.#a||=t.done})}}#s(){return this.#t._sendCursorRequest(this,{type:"fetch_cursor",cursorId:this.#r,maxCount:vfe}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#i!==void 0)return;this.#i=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new Ge("Cursor was manually closed"))}get closed(){return this.#i!==void 0}}});var Tp;var mT=v(()=>{_t();jy();j4();Tp=class Tp extends wl{#e;#t;#r;#n;#o;#i;static open(e){let t=e._streamIdAlloc.alloc(),r=new Tp(e,t),o=()=>{return},n=(s)=>r.#l(s),i={type:"open_stream",streamId:t};return e._sendRequest(i,{responseCallback:o,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new Xi,this.#n=void 0,this.#o=!1,this.#i=void 0}client(){return this.#e}_sqlOwner(){return this.#e}_execute(e){return this.#a({type:"execute",streamId:this.#t,stmt:e}).then((t)=>t.result)}_batch(e){return this.#a({type:"batch",streamId:this.#t,batch:e}).then((t)=>t.result)}_describe(e){return this.#e._ensureVersion(2,"describe()"),this.#a({type:"describe",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#e._ensureVersion(2,"sequence()"),this.#a({type:"sequence",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#a({type:"get_autocommit",streamId:this.#t}).then((e)=>e.isAutocommit)}#a(e){return new Promise((t,r)=>{this.#s({type:"request",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return this.#e._ensureVersion(3,"cursor"),new Promise((t,r)=>{this.#s({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_sendCursorRequest(e,t){if(e!==this.#n)throw new or("Cursor not associated with the stream attempted to execute a request");return new Promise((r,o)=>{if(this.#i!==void 0)o(new xt("Stream is closed",this.#i));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})})}_cursorClosed(e){if(e!==this.#n)throw new or("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#i!==void 0)e.errorCallback(new xt("Stream is closed",this.#i));else if(this.#o)e.errorCallback(new xt("Stream is closing",void 0));else this.#r.push(e),this.#c()}#c(){for(;;){let e=this.#r.first();if(e===void 0&&this.#n===void 0&&this.#o){this.#l(new Ge("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:o}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let o=this.#e._cursorIdAlloc.alloc(),n=new fT(this.#e,this,o),i={type:"open_cursor",streamId:this.#t,cursorId:o,batch:t},s=()=>{return},a=(l)=>n._setClosed(l);this.#e._sendRequest(i,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#i!==void 0)return;if(this.#i=e,this.#n!==void 0)this.#n._setClosed(e);for(;;){let n=this.#r.shift();if(n!==void 0)n.errorCallback(e);else break}let t={type:"close_stream",streamId:this.#t},r=()=>this.#e._streamIdAlloc.free(this.#t),o=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}close(){this.#l(new Ge("Stream was manually closed"))}closeGracefully(){this.#o=!0,this.#c()}get closed(){return this.#i!==void 0||this.#o}}});function $p(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,Z4),e.arrayObjects("named_args",t.namedArgs,xfe),e.boolean("want_rows",t.wantRows)}function xfe(e,t){e.string("name",t.name),e.object("value",t.value,Z4)}function xl(e,t){e.arrayObjects("steps",t.steps,_fe)}function _fe(e,t){if(t.condition!==void 0)e.object("condition",t.condition,hT);e.object("stmt",t.stmt,$p)}function hT(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,hT);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,hT);else if(t.type==="is_autocommit");else throw Je(t,"Impossible type of BatchCond")}function Z4(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",ul.fromUint8Array(t));else if(t===void 0);else throw Je(t,"Impossible type of Value")}var gT=v(()=>{Ty();on()});function U4(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,Efe);else throw Je(t,"Impossible type of ClientMsg")}function Efe(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,$p);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,xl);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,xl);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 Je(t,"Impossible type of Request")}var M4=v(()=>{gT();on()});function Op(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,F4);for(let r of t.namedArgs)e.message(4,r,kfe);e.bool(5,t.wantRows)}function kfe(e,t){e.string(1,t.name),e.message(2,t.value,F4)}function _l(e,t){for(let r of t.steps)e.message(1,r,Ife)}function Ife(e,t){if(t.condition!==void 0)e.message(1,t.condition,yT);e.message(2,t.stmt,Op)}function yT(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,yT);else if(t.type==="and")e.message(4,t.conds,q4);else if(t.type==="or")e.message(5,t.conds,q4);else if(t.type==="is_autocommit")e.message(6,void 0,K4);else throw Je(t,"Impossible type of BatchCond")}function q4(e,t){for(let r of t)e.message(1,r,yT)}function F4(e,t){if(t===null)e.message(1,void 0,K4);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 Je(t,"Impossible type of Value")}function K4(e,t){}var bT=v(()=>{on()});function J4(e,t){if(t.type==="hello")e.message(1,t,Afe);else if(t.type==="request")e.message(2,t,Rfe);else throw Je(t,"Impossible type of ClientMsg")}function Afe(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function Rfe(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,Tfe);else if(r.type==="close_stream")e.message(3,r,$fe);else if(r.type==="execute")e.message(4,r,Ofe);else if(r.type==="batch")e.message(5,r,Cfe);else if(r.type==="open_cursor")e.message(6,r,Pfe);else if(r.type==="close_cursor")e.message(7,r,zfe);else if(r.type==="fetch_cursor")e.message(8,r,Nfe);else if(r.type==="sequence")e.message(9,r,Dfe);else if(r.type==="describe")e.message(10,r,Lfe);else if(r.type==="store_sql")e.message(11,r,Bfe);else if(r.type==="close_sql")e.message(12,r,jfe);else if(r.type==="get_autocommit")e.message(13,r,Zfe);else throw Je(r,"Impossible type of Request")}function Tfe(e,t){e.int32(1,t.streamId)}function $fe(e,t){e.int32(1,t.streamId)}function Ofe(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,Op)}function Cfe(e,t){e.int32(1,t.streamId),e.message(2,t.batch,_l)}function Pfe(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,_l)}function zfe(e,t){e.int32(1,t.cursorId)}function Nfe(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function Dfe(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 Lfe(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 Bfe(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function jfe(e,t){e.int32(1,t.sqlId)}function Zfe(e,t){e.int32(1,t.streamId)}var H4=v(()=>{bT();on()});function es(e){let t=Rr(e.message),r=Zr(e.code);return{message:t,code:r}}function Cp(e){let t=xn(e.cols,V4),r=vp(e.rows).map((s)=>xn(s,W4)),o=jo(e.affected_row_count),n=Zr(e.last_insert_rowid),i=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:o,lastInsertRowid:i}}function V4(e){let t=Zr(e.name),r=Zr(e.decltype);return{name:t,decltype:r}}function Zy(e){let t=new Map;vp(e.step_results).forEach((o,n)=>{if(o!==null)t.set(n,Cp(It(o)))});let r=new Map;return vp(e.step_errors).forEach((o,n)=>{if(o!==null)r.set(n,es(It(o)))}),{stepResults:t,stepErrors:r}}function Uy(e){let t=Rr(e.type);if(t==="step_begin"){let r=jo(e.step),o=xn(e.cols,V4);return{type:"step_begin",step:r,cols:o}}else if(t==="step_end"){let r=jo(e.affected_row_count),o=Zr(e.last_insert_rowid),n=o!==void 0?BigInt(o):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=jo(e.step),o=es(It(e.error));return{type:"step_error",step:r,error:o}}else if(t==="row")return{type:"row",row:xn(e.row,W4)};else if(t==="error")return{type:"error",error:es(It(e.error))};else throw new Pe("Unexpected type of CursorEntry")}function My(e){let t=xn(e.params,Ufe),r=xn(e.cols,Mfe),o=Gi(e.is_explain),n=Gi(e.is_readonly);return{params:t,cols:r,isExplain:o,isReadonly:n}}function Ufe(e){return{name:Zr(e.name)}}function Mfe(e){let t=Rr(e.name),r=Zr(e.decltype);return{name:t,decltype:r}}function W4(e){let t=Rr(e.type);if(t==="null")return null;else if(t==="integer"){let r=Rr(e.value);return BigInt(r)}else if(t==="float")return jo(e.value);else if(t==="text")return Rr(e.value);else if(t==="blob")return ul.toUint8Array(Rr(e.base64));else throw new Pe("Unexpected type of Value")}var qy=v(()=>{Ty();_t();bl()});function G4(e){let t=Rr(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:es(It(e.error))};else if(t==="response_ok"){let r=jo(e.request_id),o=qfe(It(e.response));return{type:"response_ok",requestId:r,response:o}}else if(t==="response_error"){let r=jo(e.request_id),o=es(It(e.error));return{type:"response_error",requestId:r,error:o}}else throw new Pe("Unexpected type of ServerMsg")}function qfe(e){let t=Rr(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:Cp(It(e.result))};else if(t==="batch")return{type:"batch",result:Zy(It(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=xn(e.entries,Uy),o=Gi(e.done);return{type:"fetch_cursor",entries:r,done:o}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:My(It(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:Gi(e.is_autocommit)};else throw new Pe("Unexpected type of Response")}var Q4=v(()=>{_t();bl();qy()});var sn,ts,Y4,X4,El,Ffe,Kfe,Fy,Jfe,Hfe,Vfe,kl,Wfe,Gfe,Qfe;var Ky=v(()=>{sn={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},ts={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(Y4))},2(e,t){t.rows.push(e.message(X4))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},Y4={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},X4={default(){return[]},1(e,t){t.push(e.message(Qfe))}},El={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,o]=e.message(Ffe);t.stepResults.set(r,o)},2(e,t){let[r,o]=e.message(Kfe);t.stepErrors.set(r,o)}},Ffe={default(){return[0,ts.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(ts)}},Kfe={default(){return[0,sn.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(sn)}},Fy={default(){return{type:"none"}},1(e){return e.message(Jfe)},2(e){return e.message(Hfe)},3(e){return e.message(Vfe)},4(e){return{type:"row",row:e.message(X4)}},5(e){return{type:"error",error:e.message(sn)}}},Jfe={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(Y4))}},Hfe={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},Vfe={default(){return{type:"step_error",step:0,error:sn.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(sn)}},kl={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(Wfe))},2(e,t){t.cols.push(e.message(Gfe))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},Wfe={default(){return{name:void 0}},1(e,t){t.name=e.string()}},Gfe={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},Qfe={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 eF,Yfe,Xfe,eme,tme,rme,nme,ome,ime;var tF=v(()=>{Ky();eF={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(Yfe)},3(e){return e.message(eme)},4(e){return e.message(Xfe)}},Yfe={default(){return{type:"hello_error",error:sn.default()}},1(e,t){t.error=e.message(sn)}},Xfe={default(){return{type:"response_error",requestId:0,error:sn.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(sn)}},eme={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(tme)},5(e,t){t.response=e.message(rme)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(nme)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(ome)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(ime)}},tme={default(){return{type:"execute",result:ts.default()}},1(e,t){t.result=e.message(ts)}},rme={default(){return{type:"batch",result:El.default()}},1(e,t){t.result=e.message(El)}},nme={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(Fy))},2(e,t){t.done=e.bool()}},ome={default(){return{type:"describe",result:kl.default()}},1(e,t){t.result=e.message(kl)}},ime={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var rF,ST,Jy;var Hy=v(()=>{aT();_t();cT();kp();vl();on();mT();M4();H4();Q4();tF();rF=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),ST=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);Jy=class Jy extends hl{#e;#t;#r;#n;#o;#i;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#o=!1,this.#i=void 0,this.#a=!1,this.#s=new Map,this.#c=new Yi,this._streamIdAlloc=new Yi,this._cursorIdAlloc=new Yi,this.#l=new Yi,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#p()),this.#e.addEventListener("close",(r)=>this.#g(r)),this.#e.addEventListener("error",(r)=>this.#f(r)),this.#e.addEventListener("message",(r)=>this.#y(r)),this.#d({type:"hello",jwt:t})}#d(e){if(this.#n!==void 0)throw new or("Trying to send a message on a closed client");if(this.#r)this.#m(e);else{let t=()=>this.#m(e),r=()=>{return};this.#t.push({openCallback:t,errorCallback:r})}}#p(){let e=this.#e.protocol;if(e===void 0){this.#u(new Ge("The `WebSocket.protocol` property is undefined. This most likely means that the WebSocket implementation provided by the environment is broken. If you are using Miniflare 2, please update to Miniflare 3, which fixes this problem."));return}else if(e==="")this.#i={version:1,encoding:"json"};else if(this.#i=ST.get(e),this.#i===void 0){this.#u(new Pe(`Unrecognized WebSocket subprotocol: ${JSON.stringify(e)}`));return}for(let t of this.#t)t.openCallback();this.#t.length=0,this.#r=!0}#m(e){let t=this.#i.encoding;if(t==="json"){let r=wp(e,U4);this.#e.send(r)}else if(t==="protobuf"){let r=Ep(e,J4);this.#e.send(r)}else throw Je(t,"Impossible encoding")}getVersion(){return new Promise((e,t)=>{if(this.#a=!0,this.#n!==void 0)t(this.#n);else if(!this.#r){let r=()=>e(this.#i.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#i.version)})}_ensureVersion(e,t){if(this.#i===void 0||!this.#a)throw new wn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the WebSocket server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this.#i.version<e)throw new wn(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#i.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new xt("Client is closed",this.#n));return}let r=this.#c.alloc();this.#s.set(r,{...t,type:e.type}),this.#d({type:"request",requestId:r,request:e})}#f(e){let r=e.message??"WebSocket was closed due to an error";this.#u(new gl(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new gl(t))}#u(e){if(this.#n!==void 0)return;this.#n=e;for(let t of this.#t)t.errorCallback(e);this.#t.length=0;for(let[t,r]of this.#s.entries())r.errorCallback(e),this.#c.free(t);this.#s.clear(),this.#e.close()}#y(e){if(this.#n!==void 0)return;try{let t,r=this.#i.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new Pe("Received non-text message from server with JSON encoding"));return}t=ua(JSON.parse(e.data),G4)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new Pe("Received non-binary message from server with Protobuf encoding"));return}t=Qi(new Uint8Array(e.data),eF)}else throw Je(r,"Impossible encoding");this.#b(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#b(e){if(e.type==="none")throw new Pe("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#o)throw new Pe("Received a duplicated hello response");if(this.#o=!0,e.type==="hello_error")throw Zo(e.error);return}else if(!this.#o)throw new Pe("Received a non-hello message before a hello response");if(e.type==="response_ok"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new Pe("Received unexpected type of response");r.responseCallback(e.response)}catch(o){throw r.errorCallback(o),o}}else if(e.type==="response_error"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected error response");this.#c.free(t),r.errorCallback(Zo(e.error))}else throw Je(e,"Impossible ServerMsg type")}openStream(){return Tp.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new fa(this,t),o=()=>{return},n=(s)=>r._setClosed(s),i={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(i,{responseCallback:o,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),o={type:"close_sql",sqlId:e};this._sendRequest(o,{responseCallback:t,errorCallback:r})}close(){this.#u(new Ge("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var ma;var nF=v(()=>{if(typeof queueMicrotask<"u")ma=queueMicrotask;else{let e=Promise.resolve();ma=(t)=>{e.then(t)}}});class vT{#e;#t;#r;constructor(e){this.#e=new Uint8Array(new ArrayBuffer(e)),this.#t=0,this.#r=0}get length(){return this.#r-this.#t}data(){return this.#e.slice(this.#t,this.#r)}push(e){this.#n(e.byteLength),this.#e.set(e,this.#r),this.#r+=e.byteLength}#n(e){if(this.#r+e<=this.#e.byteLength)return;let t=this.#r-this.#t;if(t+e<=this.#e.byteLength&&2*this.#r>=this.#e.byteLength)this.#e.copyWithin(0,this.#t,this.#r);else{let r=this.#e.byteLength;do r*=2;while(t+e>r);let o=new Uint8Array(new ArrayBuffer(r));o.set(this.#e.slice(this.#t,this.#r),0),this.#e=o}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function oF(e){let t=Zr(e.baton),r=Zr(e.base_url),o=xn(e.results,sme);return{baton:t,baseUrl:r,results:o}}function sme(e){let t=Rr(e.type);if(t==="ok")return{type:"ok",response:ame(It(e.response))};else if(t==="error")return{type:"error",error:es(It(e.error))};else throw new Pe("Unexpected type of StreamResult")}function ame(e){let t=Rr(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:Cp(It(e.result))};else if(t==="batch")return{type:"batch",result:Zy(It(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:My(It(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:Gi(e.is_autocommit)};else throw new Pe("Unexpected type of StreamResponse")}function iF(e){let t=Zr(e.baton),r=Zr(e.base_url);return{baton:t,baseUrl:r}}var wT=v(()=>{_t();bl();qy()});var sF,cme,lme,ume,dme,pme,fme,aF;var xT=v(()=>{Ky();sF={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(cme))}},cme={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(lme)}},2(e){return{type:"error",error:e.message(sn)}}},lme={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(ume)},3(e){return e.message(dme)},4(e){return{type:"sequence"}},5(e){return e.message(pme)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(fme)}},ume={default(){return{type:"execute",result:ts.default()}},1(e,t){t.result=e.message(ts)}},dme={default(){return{type:"batch",result:El.default()}},1(e,t){t.result=e.message(El)}},pme={default(){return{type:"describe",result:kl.default()}},1(e,t){t.result=e.message(kl)}},fme={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},aF={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var _T;var cF=v(()=>{bl();iT();_t();on();wT();xT();qy();Ky();_T=class _T extends Rp{#e;#t;#r;#n;#o;#i;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new vT(16384),this.#o=void 0,this.#i=!1}async open(e){if(e.body===null)throw new Pe("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(iF,aF);if(t===void 0)throw new Pe("Empty response to cursor request");return t}next(){return this.#a(Uy,Fy)}close(){this._setClosed(new Ge("Cursor was manually closed"))}_setClosed(e){if(this.#o!==void 0)return;if(this.#o=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#o!==void 0}async#a(e,t){for(;;){if(this.#i)return;else if(this.#o!==void 0)throw new xt("Cursor is closed",this.#o);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let i=new TextDecoder().decode(n),s=JSON.parse(i);return ua(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return Qi(n,t)}else throw Je(this.#t,"Impossible encoding");if(this.#r===void 0)throw new or("Attempted to read from HTTP cursor before it was opened");let{value:r,done:o}=await this.#r.next();if(o&&this.#n.length===0)this.#i=!0;else if(o)throw new Pe("Unexpected end of cursor stream");else this.#n.push(r)}}#s(){let e=this.#n.data(),t=10,r=e.indexOf(10);if(r<0)return;let o=e.slice(0,r);return this.#n.shift(r+1),o}#c(){let e=this.#n.data(),t=0,r=0;for(;;){if(r>=e.byteLength)return;let n=e[r];if(t|=(n&127)<<7*r,r+=1,!(n&128))break}if(e.byteLength<r+t)return;let o=e.slice(r,r+t);return this.#n.shift(r+t),o}}});function lF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,mme)}function mme(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,$p);else if(t.type==="batch")e.object("batch",t.batch,xl);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 Je(t,"Impossible type of StreamRequest")}function uF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,xl)}var ET=v(()=>{gT();on()});function dF(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,hme)}function hme(e,t){if(t.type==="close")e.message(1,t,gme);else if(t.type==="execute")e.message(2,t,yme);else if(t.type==="batch")e.message(3,t,bme);else if(t.type==="sequence")e.message(4,t,Sme);else if(t.type==="describe")e.message(5,t,vme);else if(t.type==="store_sql")e.message(6,t,wme);else if(t.type==="close_sql")e.message(7,t,xme);else if(t.type==="get_autocommit")e.message(8,t,_me);else throw Je(t,"Impossible type of StreamRequest")}function gme(e,t){}function yme(e,t){e.message(1,t.stmt,Op)}function bme(e,t){e.message(1,t.batch,_l)}function Sme(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function vme(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function wme(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function xme(e,t){e.int32(1,t.sqlId)}function _me(e,t){}function pF(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,_l)}var kT=v(()=>{bT();on()});function Eme(e,t){if(t.results.length!==e.length)throw new Pe("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let o=t.results[r],n=e[r];if(o.type==="ok"){if(o.response.type!==n.request.type)throw new Pe("Received unexpected type of response");n.responseCallback(o.response)}else if(o.type==="error")n.errorCallback(Zo(o.error));else if(o.type==="none")throw new Pe("Received unrecognized type of StreamResult");else throw Je(o,"Received impossible type of StreamResult")}}async function kme(e,t){if(t==="json"){let r=await e.json();return ua(r,oF)}if(t==="protobuf"){let r=await e.arrayBuffer();return Qi(new Uint8Array(r),sF)}throw await e.body?.cancel(),Je(t,"Impossible encoding")}async function Ime(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let o=await e.json();if("message"in o)return Zo(o);return new la(r,e.status)}if(t==="text/plain"){let o=(await e.text()).trim();if(o!=="")r+=`: ${o}`;return new la(r,e.status)}return await e.body?.cancel(),new la(r,e.status)}var Vy;var IT=v(()=>{_t();aT();cT();nF();kp();vl();jy();on();cF();ET();kT();ET();kT();wT();xT();Vy=class Vy extends wl{#e;#t;#r;#n;#o;#i;#a;#s;#c;#l;#d;#p;#m;constructor(e,t,r,o,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=o,this.#o=n,this.#i=void 0,this.#a=new Xi,this.#s=!1,this.#l=!1,this.#d=!1,this.#p=void 0,this.#m=new Yi}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let t=this.#m.alloc();return this.#f({type:"store_sql",sqlId:t,sql:e}).then(()=>{return},(r)=>this._setClosed(r)),new fa(this,t)}_closeSql(e){if(this.#p!==void 0)return;this.#f({type:"close_sql",sqlId:e}).then(()=>this.#m.free(e),(t)=>this._setClosed(t))}_execute(e){return this.#f({type:"execute",stmt:e}).then((t)=>t.result)}_batch(e){return this.#f({type:"batch",batch:e}).then((t)=>t.result)}_describe(e){return this.#f({type:"describe",sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#f({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#f({type:"get_autocommit"}).then((e)=>e.isAutocommit)}#f(e){return new Promise((t,r)=>{this.#g({type:"pipeline",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return new Promise((t,r)=>{this.#g({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_cursorClosed(e){if(e!==this.#c)throw new or("Cursor was closed, but it was not associated with the stream");this.#c=void 0,ma(()=>this.#u())}close(){this._setClosed(new Ge("Stream was manually closed"))}closeGracefully(){this.#l=!0,ma(()=>this.#u())}get closed(){return this.#p!==void 0||this.#l}_setClosed(e){if(this.#p!==void 0)return;if(this.#p=e,this.#c!==void 0)this.#c._setClosed(e);this.#e._streamClosed(this);for(;;){let t=this.#a.shift();if(t!==void 0)t.errorCallback(e);else break}if((this.#i!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,ma(()=>this.#u())}#g(e){if(this.#p!==void 0)throw new xt("Stream is closed",this.#p);else if(this.#l)throw new xt("Stream is closing",void 0);else this.#a.push(e),ma(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new Ge("Stream was gracefully closed"));return}let e=this.#e._endpoint;if(e===void 0){this.#e._endpointPromise.then(()=>this.#u(),(r)=>this._setClosed(r));return}let t=this.#a.shift();if(t===void 0)return;else if(t.type==="pipeline"){let r=[t];for(;;){let o=this.#a.first();if(o!==void 0&&o.type==="pipeline")r.push(o),this.#a.shift();else if(o===void 0&&this.#l&&!this.#d){r.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0;break}else break}this.#y(e,r)}else if(t.type==="cursor")this.#b(e,t);else throw Je(t,"Impossible type of QueueEntry")}#y(e,t){this.#h(()=>this.#S(t,e),(r)=>kme(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>Eme(t,r),(r)=>t.forEach((o)=>o.errorCallback(r)))}#b(e,t){let r=new _T(this,e.encoding);this.#c=r,this.#h(()=>this.#v(t,e),(o)=>r.open(o),(o)=>o.baton,(o)=>o.baseUrl,(o)=>t.cursorCallback(r),(o)=>t.errorCallback(o))}#h(e,t,r,o,n,i){let s;try{let a=e(),l=this.#n;s=l(a)}catch(a){s=Promise.reject(a)}this.#s=!0,s.then((a)=>{if(!a.ok)return Ime(a).then((l)=>{throw l});return t(a)}).then((a)=>{this.#i=r(a),this.#t=o(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),i(a)}).finally(()=>{this.#s=!1,this.#u()})}#S(e,t){return this.#w(new URL(t.pipelinePath,this.#t),{baton:this.#i,requests:e.map((r)=>r.request)},t.encoding,lF,dF)}#v(e,t){if(t.cursorPath===void 0)throw new wn(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#w(new URL(t.cursorPath,this.#t),{baton:this.#i,batch:e.batch},t.encoding,uF,pF)}#w(e,t,r,o,n){let i,s;if(r==="json")i=wp(t,o),s="application/json";else if(r==="protobuf")i=Ep(t,n),s="application/x-protobuf";else throw Je(r,"Impossible encoding");let a=new Headers;if(a.set("content-type",s),this.#r!==void 0)a.set("authorization",`Bearer ${this.#r}`);if(this.#o!==void 0)a.set("x-turso-encryption-key",this.#o);return new Request(e.toString(),{method:"POST",headers:a,body:i})}}});async function Rme(e,t){let r=e;for(let o of Ame){let n=new URL(o.versionPath,t),i=new Request(n.toString(),{method:"GET"}),s=await r(i);if(await s.arrayBuffer(),s.ok)return o}return AT}var Ame,AT,Wy;var RT=v(()=>{_t();IT();Ame=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],AT={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};Wy=class Wy extends hl{#e;#t;#r;#n;#o;#i;_endpointPromise;_endpoint;constructor(e,t,r,o,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=o,this.#o=void 0,this.#i=new Set,n==3)this._endpointPromise=Rme(this.#r,this.#e),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i));else this._endpointPromise=Promise.resolve(AT),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=AT.version)return;else if(this._endpoint===void 0)throw new wn(`${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 wn(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#o!==void 0)throw new xt("Client is closed",this.#o);let e=new Vy(this,this.#e,this.#t,this.#r,this.#n);return this.#i.add(e),e}_streamClosed(e){this.#i.delete(e)}close(){this.#a(new Ge("Client was manually closed"))}get closed(){return this.#o!==void 0}#a(e){if(this.#o!==void 0)return;this.#o=e;for(let t of Array.from(this.#i))t._setClosed(new xt("Client was closed",e))}}});var fF=v(()=>{_t()});function TT(e,t,r=2){if(typeof Wi>"u")throw new Sp("WebSockets are not supported in this environment");var o=void 0;if(r==3)o=Array.from(ST.keys());else o=Array.from(rF.keys());let n=new Wi(e,o);return new Jy(n,t)}function $T(e,t,r,o,n=2){return new Wy(e instanceof URL?e:new URL(e),t,r,o,n)}var Gy=v(()=>{oT();Hy();_t();RT();Hy();oT();pT();fF();vl();Ly();jy();RT();IT();Hy();mT();_t()});class Pp{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}execute(e){return this.batch([e]).then((t)=>t[0])}async batch(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(Uo),o;if(this.#r===void 0){this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=i.step(),a=s.run(Hi(this.#e)),l=s;o=r.map((u)=>{let d=i.step().condition(dt.ok(l));if(this.#t>=3)d.condition(dt.not(dt.isAutocommit(i)));let p=d.query(u);return p.catch(()=>{return}),l=d,p}),this.#r=i.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(u){throw this.close(),u}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=void 0;o=r.map((a)=>{let l=i.step();if(s!==void 0)l.condition(dt.ok(s));if(this.#t>=3)l.condition(dt.not(dt.isAutocommit(i)));let u=l.query(a);return u.catch(()=>{return}),s=l,u}),await i.execute()}let n=[];for(let i=0;i<o.length;i++)try{let s=await o[i];if(s===void 0)throw new Gt("Statement in a transaction was not executed, probably because the transaction has been rolled back",i,"TRANSACTION_CLOSED");n.push(Al(s))}catch(s){if(s instanceof Gt)throw s;let a=st(s);if(a instanceof Ce)throw new Gt(a.message,i,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw st(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(Hi(this.#e)).then(()=>{return});try{await this.#r}catch(r){throw this.close(),r}}else await this.#r;await t.sequence(e)}catch(r){throw st(r)}}async rollback(){try{let e=this._getStream();if(e.closed)return;if(this.#r!==void 0);else return;let t=e.run("ROLLBACK").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Ce("Cannot commit the transaction because it is already closed","TRANSACTION_CLOSED");if(this.#r!==void 0)await this.#r;else return;let t=e.run("COMMIT").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}}async function Il(e,t,r,o,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let i=r.step(),s=i.run(Hi(e)),a=i,l=o.map((h)=>{let b=r.step().condition(dt.ok(a));if(t>=3)b.condition(dt.not(dt.isAutocommit(r)));let y=b.query(h);return a=b,y}),u=r.step().condition(dt.ok(a));if(t>=3)u.condition(dt.not(dt.isAutocommit(r)));let d=u.run("COMMIT");if(r.step().condition(dt.not(dt.ok(u))).run("ROLLBACK").catch((h)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let m=[];await s;for(let h=0;h<l.length;h++)try{let b=await l[h];if(b===void 0)throw new Gt("Statement in a batch was not executed, probably because the transaction has been rolled back",h,"TRANSACTION_CLOSED");m.push(Al(b))}catch(b){if(b instanceof Gt)throw b;let y=st(b);if(y instanceof Ce)throw new Gt(y.message,h,y.code,y.extendedCode,y.rawCode,y.cause instanceof Error?y.cause:void 0);throw y}return await d,m}function Uo(e){let t,r;if(Array.isArray(e))[t,r]=e;else if(typeof e==="string")t=e;else t=e.sql,r=e.args;let o=new Ap(t);if(r)if(Array.isArray(r))o.bindIndexes(r);else for(let[n,i]of Object.entries(r))o.bindName(n,i);return o}function Al(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),o=e.rows,n=e.affectedRowCount,i=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new dl(t,r,o,n,i)}function st(e){if(e instanceof Ge){let t=mF(e);return new Ce(e.message,t,void 0,void 0,e)}return e}function mF(e){if(e instanceof bp&&e.code!==void 0)return e.code;else if(e instanceof Pe)return"HRANA_PROTO_ERROR";else if(e instanceof xt)return e.cause instanceof Ge?mF(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof gl)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof la)return"SERVER_ERROR";else if(e instanceof wn)return"PROTOCOL_VERSION_ERROR";else if(e instanceof or)return"INTERNAL_ERROR";else return"UNKNOWN"}var CT=v(()=>{Gy();vn();pl()});class Rl{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new hF,this.capacity=t}apply(e){if(this.capacity<=0)return;let t=new Set;for(let r of e){if(typeof r.sql!=="string")continue;let o=r.sql;if(o.length>=5000)continue;let n=this.#t.get(o);if(n===void 0){while(this.#t.size+1>this.capacity){let[i,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(i)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(o),this.#t.set(o,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class hF{#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 PT=ge(function(EBe,yF){function Tme(e){var t=0,r=[];function o(){if(t--,t<e)n()}function n(){var l=r.shift();if(a.queue=r.length,l)s(l.fn).then(l.resolve).catch(l.reject)}function i(l){return new Promise(function(u,d){r.push({fn:l,resolve:u,reject:d}),a.queue=r.length})}function s(l){t++;try{return Promise.resolve(l()).then(function(u){return o(),u},function(u){throw o(),u})}catch(u){return o(),Promise.reject(u)}}var a=function(l){if(t>=e)return i(l);else return s(l)};return a}function $me(e,t){var r=!1,o=this;return Promise.all(e.map(function(){var n=arguments;return o(function(){if(!r)return t.apply(void 0,n).catch(function(i){throw r=!0,i})})}))}function gF(e){return e.queue=0,e.map=$me,e}yF.exports=function(e){if(e)return gF(Tme(e));else return gF(function(t){return t()})}});function vF(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Ce(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${Xn}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Ce('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Ce('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=fp(e.scheme,e.authority,e.path),r;try{r=TT(t,e.authToken)}catch(o){if(o instanceof Sp){let n=e.scheme==="wss"?"https":"http",i=fp(n,e.authority,e.path);throw new Ce(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(i)}). For more information, please read ${Xn}`,"WEBSOCKETS_NOT_SUPPORTED")}throw st(o)}return new wF(r,t,e.authToken,e.intMode,e.concurrency)}class wF{#e;#t;#r;#n;#o;closed;protocol;#i;#a;constructor(e,t,r,o,n){this.#e=t,this.#t=r,this.#r=o,this.#n=this.#c(e),this.#o=void 0,this.closed=!1,this.protocol="ws",this.#a=SF.default(n)}async limit(e){return this.#a(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{let o=await this.#s();try{let n=Uo(r);o.conn.sqlCache.apply([n]);let i=o.stream.query(n);o.stream.closeGracefully();let s=await i;return Al(s)}catch(n){throw st(n)}finally{this._closeStream(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((u)=>{if(Array.isArray(u))return{sql:u[0],args:u[1]||[]};return u}).map(Uo),i=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(i>=3);return await Il(t,i,s,n)}catch(o){throw st(o)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(Uo),o=await t.conn.client.getVersion(),n=t.stream.batch(o>=3);return await Il("deferred",o,n,r,!0)}catch(r){throw st(r)}finally{this._closeStream(t)}})}async transaction(e="write"){return this.limit(async()=>{let t=await this.#s();try{let r=await t.conn.client.getVersion();return new xF(this,t,e,r)}catch(r){throw this._closeStream(t),st(r)}})}async executeMultiple(e){return this.limit(async()=>{let t=await this.#s();try{let r=t.stream.sequence(e);t.stream.closeGracefully(),await r}catch(r){throw st(r)}finally{this._closeStream(t)}})}sync(){throw new Ce("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>Ome&&this.#o===void 0){let o=this.#c();this.#o=o,o.client.getVersion().then((n)=>{if(this.#n!==o){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=o,this.#o=void 0},(n)=>{this.#o=void 0})}if(this.#n.client.closed)try{if(this.#o!==void 0)this.#n=this.#o;else this.#n=this.#c()}catch(o){throw st(o)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=bF}let o=r.client.openStream();o.intMode=this.#r;let n={conn:r,stream:o};return r.streamStates.add(n),n}catch(o){throw st(o)}}#c(e){try{return e??=TT(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new Rl(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw st(t)}}async reconnect(){try{for(let r of Array.from(this.#n.streamStates))try{r.stream.close()}catch{}this.#n.client.close()}catch{}if(this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=bF;this.#n=e,this.closed=!1}_closeStream(e){e.stream.close();let t=e.conn;if(t.streamStates.delete(e),t.streamStates.size===0&&t!==this.#n)t.client.close()}close(){if(this.#n.client.close(),this.closed=!0,this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}this.closed=!0}}var SF,Ome=60000,bF=100,xF;var _F=v(()=>{Gy();vn();gp();CT();Iy();pl();SF=Fl(PT(),1);vn();xF=class xF extends Pp{#e;#t;constructor(e,t,r,o){super(r,o);this.#e=e,this.#t=t}_getStream(){return this.#t.stream}_getSqlCache(){return this.#t.conn.sqlCache}close(){this.#e._closeStream(this.#t)}get closed(){return this.#t.stream.closed}}});function kF(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Ce(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${Xn}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Ce('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Ce('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=fp(e.scheme,e.authority,e.path);return new AF(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class AF{#e;protocol;#t;#r;#n;#o;#i;#a;#s;constructor(e,t,r,o,n,i){this.#t=e,this.#i=t,this.#r=r,this.#n=o,this.#o=n,this.#a=i,this.#e=$T(this.#t,this.#i,this.#n,i),this.#e.intMode=this.#r,this.protocol="http",this.#s=EF.default(this.#o)}async limit(e){return this.#s(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{try{let o=Uo(r),n,i=this.#e.openStream();try{n=i.query(o)}finally{i.closeGracefully()}let s=await n;return Al(s)}catch(o){throw st(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let o=e.map((l)=>{if(Array.isArray(l))return{sql:l[0],args:l[1]||[]};return l}).map(Uo),n=await this.#e.getVersion(),i,s=this.#e.openStream();try{new Rl(s,IF).apply(o);let u=s.batch(!1);i=Il(t,n,u,o)}finally{s.closeGracefully()}return await i}catch(r){throw st(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(Uo),r=await this.#e.getVersion(),o,n=this.#e.openStream();try{let s=n.batch(!1);o=Il("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await o}catch(t){throw st(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new RF(this.#e.openStream(),e,t)}catch(t){throw st(t)}})}async executeMultiple(e){return this.limit(async()=>{try{let t,r=this.#e.openStream();try{t=r.sequence(e)}finally{r.closeGracefully()}await t}catch(t){throw st(t)}})}sync(){throw new Ce("sync not supported in http mode","SYNC_NOT_SUPPORTED")}close(){this.#e.close()}async reconnect(){try{if(!this.closed)this.#e.close()}finally{this.#e=$T(this.#t,this.#i,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var EF,IF=30,RF;var TF=v(()=>{Gy();vn();gp();CT();Iy();pl();EF=Fl(PT(),1);vn();RF=class RF extends Pp{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new Rl(e,IF)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function Tl(e){return Cme(hp(e,!0))}function Cme(e){if(e.scheme==="wss"||e.scheme==="ws")return vF(e);else if(e.scheme==="https"||e.scheme==="http")return kF(e);else return E4(e)}var zT=v(()=>{gp();T4();_F();TF();vn()});function oe(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,F))throw Error(`Class "${t.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let r=Object.getPrototypeOf(e).constructor;if(r)while(r){if(F in r&&r[F]===t[F])return!0;r=Object.getPrototypeOf(r)}return!1}var F;var $e=v(()=>{F=Symbol.for("drizzle:entityKind")});var He;var _n=v(()=>{$e();He=class He{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[F]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var zp;var Qy=v(()=>{$e();zp=class zp{static[F]="ColumnBuilder";config;constructor(e,t,r){this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:r,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){if(this.config.name!=="")return;this.config.name=e}}});var ir;var $l=v(()=>{ir=Symbol.for("drizzle:Name")});var NT,$F;var OF=v(()=>{$e();$l();NT=class NT{static[F]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e===void 0?"no action":e,this}onDelete(e){return this._onDelete=e===void 0?"no action":e,this}build(e){return new $F(e,this)}};$F=class $F{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function Yy(e,...t){return e(...t)}var DT=()=>{};function LT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var CF,Pme,PF;var zF=v(()=>{$e();$l();CF=class CF{constructor(e,t){this.name=t,this.columns=e}static[F]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new PF(e,this.columns,this.nullsNotDistinctConfig,this.name)}};Pme=class Pme{static[F]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new CF(e,this.name)}};PF=class PF{constructor(e,t,r,o){this.table=e,this.columns=t,this.name=o??LT(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[F]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function NF(e,t,r){for(let o=t;o<e.length;o++){let n=e[o];if(n==="\\"){o++;continue}if(n==='"')return[e.slice(t,o).replace(/\\/g,""),o+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,o).replace(/\\/g,""),o]}return[e.slice(t).replace(/\\/g,""),e.length]}function DF(e,t=0){let r=[],o=t,n=!1;while(o<e.length){let i=e[o];if(i===","){if(n||o===t)r.push("");n=!0,o++;continue}if(n=!1,i==="\\"){o+=2;continue}if(i==='"'){let[l,u]=NF(e,o+1,!0);r.push(l),o=u;continue}if(i==="}")return[r,o+1];if(i==="{"){let[l,u]=DF(e,o+1);r.push(l),o=u;continue}let[s,a]=NF(e,o,!1);r.push(s),o=a}return[r,o]}function LF(e){let[t]=DF(e,1);return t}function BT(e){return`{${e.map((t)=>{if(Array.isArray(t))return BT(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var BF=()=>{};var Np,Ol,jF,zme,ZF,jT;var UF=v(()=>{Qy();_n();$e();OF();DT();zF();BF();Np=class Np extends zp{foreignKeyConfigs=[];static[F]="PgColumnBuilder";array(e){return new ZF(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>Yy((n,i)=>{let s=new NT(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)},r,o))}buildExtraConfigColumn(e){return new jF(e,this.config)}};Ol=class Ol extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=LT(e,[t.name]);super(e,t);this.table=e}static[F]="PgColumn"};jF=class jF extends Ol{static[F]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}};zme=class zme{static[F]="IndexedColumn";constructor(e,t,r,o){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=o}name;keyAsName;type;indexConfig};ZF=class ZF extends Np{static[F]="PgArrayBuilder";constructor(e,t,r){super(e,"array","PgArray");this.config.baseBuilder=t,this.config.size=r}build(e){let t=this.config.baseBuilder.build(e);return new jT(e,this.config,t)}};jT=class jT extends Ol{constructor(e,t,r,o){super(e,t);this.baseColumn=r,this.range=o,this.size=t.size}size;static[F]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=LF(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((o)=>o===null?null:oe(this.baseColumn,jT)?this.baseColumn.mapToDriverValue(o,!0):this.baseColumn.mapToDriverValue(o));if(t)return r;return BT(r)}}});function FF(e){return!!e&&typeof e==="function"&&MF in e&&e[MF]===!0}var Nme,qF,MF,Dme,KF;var JF=v(()=>{$e();UF();Nme=class Nme extends Np{static[F]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new qF(e,this.config)}};qF=class qF extends Ol{static[F]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};MF=Symbol.for("drizzle:isPgEnum");Dme=class Dme extends Np{static[F]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new KF(e,this.config)}};KF=class KF extends Ol{static[F]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}}});var pt,Dp;var En=v(()=>{$e();pt=class pt{static[F]="Subquery";constructor(e,t,r,o=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:o,usedTables:n}}};Dp=class Dp extends pt{static[F]="WithSubquery"}});var HF="0.45.2";var VF=()=>{};var ZT,UT,WF;var GF=v(()=>{DT();VF();WF={startActiveSpan(e,t){if(!ZT)return t();if(!UT)UT=ZT.trace.getTracer("drizzle-orm",HF);return Yy((r,o)=>o.startActiveSpan(e,(n)=>{try{return t(n)}catch(i){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:i instanceof Error?i.message:"Unknown error"}),i}finally{n.end()}}),ZT,UT)}}});var ft;var Mo=v(()=>{ft=Symbol.for("drizzle:ViewBaseConfig")});function rs(e){return e[ir]}function ha(e){return`${e[Xy]??"public"}.${e[ir]}`}var Xy,eb,QF,MT,qT,Lp,YF,Lme,he;var sr=v(()=>{$e();$l();Xy=Symbol.for("drizzle:Schema"),eb=Symbol.for("drizzle:Columns"),QF=Symbol.for("drizzle:ExtraConfigColumns"),MT=Symbol.for("drizzle:OriginalName"),qT=Symbol.for("drizzle:BaseName"),Lp=Symbol.for("drizzle:IsAlias"),YF=Symbol.for("drizzle:ExtraConfigBuilder"),Lme=Symbol.for("drizzle:IsDrizzleTable");he=class he{static[F]="Table";static Symbol={Name:ir,Schema:Xy,OriginalName:MT,Columns:eb,ExtraConfigColumns:QF,BaseName:qT,IsAlias:Lp,ExtraConfigBuilder:YF};[ir];[MT];[Xy];[eb];[QF];[qT];[Lp]=!1;[Lme]=!0;[YF]=void 0;constructor(e,t,r){this[ir]=this[MT]=e,this[Xy]=t,this[qT]=r}}});function FT(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function jme(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 XF(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function C(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Nt(e[0]));for(let[o,n]of t.entries())r.push(n,new Nt(e[o+1]));return new _e(r)}function Bp(e,t){return e.map((r)=>{if(oe(r,ns)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(oe(r,Ur)&&oe(r.value,ns)){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 Bme,Nt,_e,tb,e3,t3,Nje,Ur,ns,Zme,an;var Yt=v(()=>{$e();JF();En();GF();Mo();_n();sr();Bme=class Bme{static[F]="FakePrimitiveParam"};Nt=class Nt{static[F]="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(oe(t,he)){let r=t[he.Symbol.Schema];this.usedTables.push(r===void 0?t[he.Symbol.Name]:r+"."+t[he.Symbol.Name])}}static[F]="SQL";decoder=e3;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return WF.startActiveSpan("drizzle.buildSQL",(t)=>{let r=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(e,t){let r=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:o,escapeName:n,escapeParam:i,prepareTyping:s,inlineParams:a,paramStartIndex:l}=r;return jme(e.map((u)=>{if(oe(u,Nt))return{sql:u.value.join(""),params:[]};if(oe(u,tb))return{sql:n(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){let d=[new Nt("(")];for(let[p,m]of u.entries())if(d.push(m),p<u.length-1)d.push(new Nt(", "));return d.push(new Nt(")")),this.buildQueryFromSourceParams(d,r)}if(oe(u,_e))return this.buildQueryFromSourceParams(u.queryChunks,{...r,inlineParams:a||u.shouldInlineParams});if(oe(u,he)){let d=u[he.Symbol.Schema],p=u[he.Symbol.Name];return{sql:d===void 0||u[Lp]?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,He)){let d=o.getColumnCasing(u);if(t.invokeSource==="indexes")return{sql:n(d),params:[]};let p=u.table[he.Symbol.Schema];return{sql:u.table[Lp]||p===void 0?n(u.table[he.Symbol.Name])+"."+n(d):n(p)+"."+n(u.table[he.Symbol.Name])+"."+n(d),params:[]}}if(oe(u,an)){let d=u[ft].schema,p=u[ft].name;return{sql:d===void 0||u[ft].isAlias?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,Ur)){if(oe(u.value,ns))return{sql:i(l.value++,u),params:[u],typings:["none"]};let d=u.value===null?null:u.encoder.mapToDriverValue(u.value);if(oe(d,_e))return this.buildQueryFromSourceParams([d],r);if(a)return{sql:this.mapInlineParam(d,r),params:[]};let p=["none"];if(s)p=[s(u.encoder)];return{sql:i(l.value++,d),params:[d],typings:p}}if(oe(u,ns))return{sql:i(l.value++,u),params:[u],typings:["none"]};if(oe(u,_e.Aliased)&&u.fieldAlias!==void 0)return{sql:n(u.fieldAlias),params:[]};if(oe(u,pt)){if(u._.isWith)return{sql:n(u._.alias),params:[]};return this.buildQueryFromSourceParams([new Nt("("),u._.sql,new Nt(") "),new tb(u._.alias)],r)}if(FF(u)){if(u.schema)return{sql:n(u.schema)+"."+n(u.enumName),params:[]};return{sql:n(u.enumName),params:[]}}if(FT(u)){if(u.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([u.getSQL()],r);return this.buildQueryFromSourceParams([new Nt("("),u.getSQL(),new Nt(")")],r)}if(a)return{sql:this.mapInlineParam(u,r),params:[]};return{sql:i(l.value++,u),params:[u],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e==="number"||typeof e==="boolean")return e.toString();if(typeof e==="string")return t(e);if(typeof e==="object"){let r=e.toString();if(r==="[object Object]")return t(JSON.stringify(e));return t(r)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){if(e===void 0)return this;return new _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}};tb=class tb{constructor(e){this.value=e}static[F]="Name";brand;getSQL(){return new _e([this])}};e3={mapFromDriverValue:(e)=>e},t3={mapToDriverValue:(e)=>e},Nje={...e3,...t3};Ur=class Ur{constructor(e,t=t3){this.value=e,this.encoder=t}static[F]="Param";brand;getSQL(){return new _e([this])}};((e)=>{function t(){return new _e([])}e.empty=t;function r(l){return new _e(l)}e.fromList=r;function o(l){return new _e([new Nt(l)])}e.raw=o;function n(l,u){let d=[];for(let[p,m]of l.entries()){if(p>0&&u!==void 0)d.push(u);d.push(m)}return new _e(d)}e.join=n;function i(l){return new tb(l)}e.identifier=i;function s(l){return new ns(l)}e.placeholder=s;function a(l,u){return new Ur(l,u)}e.param=a})(C||(C={}));((e)=>{class t{constructor(r,o){this.sql=r,this.fieldAlias=o}static[F]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(_e||(_e={}));ns=class ns{constructor(e){this.name=e}static[F]="Placeholder";getSQL(){return new _e([this])}};Zme=Symbol.for("drizzle:IsDrizzleView");an=class an{static[F]="View";[ft];[Zme]=!0;constructor({name:e,schema:t,selectedFields:r,query:o}){this[ft]={name:e,originalName:e,schema:t,selectedFields:r,query:o,isExisting:!o,isAlias:!1}}getSQL(){return new _e([this])}};He.prototype.getSQL=function(){return new _e([this])};he.prototype.getSQL=function(){return new _e([this])};pt.prototype.getSQL=function(){return new _e([this])}});function KT(e,t,r){let o={},n=e.reduce((i,{path:s,field:a},l)=>{let u;if(oe(a,He))u=a;else if(oe(a,_e))u=a.decoder;else if(oe(a,pt))u=a._.sql.decoder;else u=a.sql.decoder;let d=i;for(let[p,m]of s.entries())if(p<s.length-1){if(!(m in d))d[m]={};d=d[m]}else{let h=t[l],b=d[m]=h===null?null:u.mapFromDriverValue(h);if(r&&oe(a,He)&&s.length===2){let y=s[0];if(!(y in o))o[y]=b===null?rs(a.table):!1;else if(typeof o[y]==="string"&&o[y]!==rs(a.table))o[y]=!1}}return i},{});if(r&&Object.keys(o).length>0){for(let[i,s]of Object.entries(o))if(typeof s==="string"&&!r[s])n[i]=null}return n}function cn(e,t){return Object.entries(e).reduce((r,[o,n])=>{if(typeof o!=="string")return r;let i=t?[...t,o]:[o];if(oe(n,He)||oe(n,_e)||oe(n,_e.Aliased)||oe(n,pt))r.push({path:i,field:n});else if(oe(n,he))r.push(...cn(n[he.Symbol.Columns],i));else r.push(...cn(n,i));return r},[])}function jp(e,t){let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(let[n,i]of r.entries())if(i!==o[n])return!1;return!0}function rb(e,t){let r=Object.entries(t).filter(([,o])=>o!==void 0).map(([o,n])=>{if(oe(n,_e)||oe(n,He))return[o,n];else return[o,new Ur(n,e[he.Symbol.Columns][o])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function r3(e,t){for(let r of t)for(let o of Object.getOwnPropertyNames(r.prototype)){if(o==="constructor")continue;Object.defineProperty(e.prototype,o,Object.getOwnPropertyDescriptor(r.prototype,o)||Object.create(null))}}function nb(e){return e[he.Symbol.Columns]}function Zp(e){return oe(e,pt)?e._.alias:oe(e,an)?e[ft].name:oe(e,_e)?void 0:e[he.Symbol.IsAlias]?e[he.Symbol.Name]:e[he.Symbol.BaseName]}function no(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function n3(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 JT;var Sr=v(()=>{_n();$e();Yt();En();sr();Mo();JT=typeof TextDecoder>"u"?null:new TextDecoder});var o3,HT,VT;var ob=v(()=>{$e();o3=class o3{static[F]="ConsoleLogWriter";write(e){console.log(e)}};HT=class HT{static[F]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new o3}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),o=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${o}`)}};VT=class VT{static[F]="NoopLogger";logQuery(){}}});var i3,s3,WT;var a3=v(()=>{$e();sr();i3=Symbol.for("drizzle:PgInlineForeignKeys"),s3=Symbol.for("drizzle:EnableRLS");WT=class WT extends he{static[F]="PgTable";static Symbol=Object.assign({},he.Symbol,{InlineForeignKeys:i3,EnableRLS:s3});[i3]=[];[s3]=!1;[he.Symbol.ExtraConfigBuilder]=void 0;[he.Symbol.ExtraConfigColumns]={}}});var GT,c3;var l3=v(()=>{$e();a3();GT=class GT{static[F]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new c3(e,this.columns,this.name)}};c3=class c3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[WT.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Tr(e,t){if(XF(t)&&!FT(e)&&!oe(e,Ur)&&!oe(e,ns)&&!oe(e,He)&&!oe(e,he)&&!oe(e,an))return new Ur(e,t);return e}function tt(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new _e(t);return new _e([new Nt("("),C.join(t,new Nt(" and ")),new Nt(")")])}function ln(...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 Nt("("),C.join(t,new Nt(" or ")),new Nt(")")])}function d3(e){return C`not ${e}`}function is(e,t){if(Array.isArray(t)){if(t.length===0)return C`false`;return C`${e} in ${t.map((r)=>Tr(r,e))}`}return C`${e} in ${Tr(t,e)}`}function ib(e,t){if(Array.isArray(t)){if(t.length===0)return C`true`;return C`${e} not in ${t.map((r)=>Tr(r,e))}`}return C`${e} not in ${Tr(t,e)}`}function Mr(e){return C`${e} is null`}function m3(e){return C`${e} is not null`}function sb(e){return C`exists ${e}`}function ss(e){return C`not exists ${e}`}function h3(e,t,r){return C`${e} between ${Tr(t,e)} and ${Tr(r,e)}`}function g3(e,t,r){return C`${e} not between ${Tr(t,e)} and ${Tr(r,e)}`}function y3(e,t){return C`${e} like ${t}`}function b3(e,t){return C`${e} not like ${t}`}function S3(e,t){return C`${e} ilike ${t}`}function v3(e,t){return C`${e} not ilike ${t}`}var je=(e,t)=>C`${e} = ${Tr(t,e)}`,u3=(e,t)=>C`${e} <> ${Tr(t,e)}`,kn=(e,t)=>C`${e} > ${Tr(t,e)}`,p3=(e,t)=>C`${e} >= ${Tr(t,e)}`,f3=(e,t)=>C`${e} < ${Tr(t,e)}`,os=(e,t)=>C`${e} <= ${Tr(t,e)}`;var w3=v(()=>{_n();$e();sr();Yt()});function qo(e){return C`${e} asc`}function ga(e){return C`${e} desc`}var x3=v(()=>{Yt()});var QT=v(()=>{w3();x3()});function E3(){return{and:tt,between:h3,eq:je,exists:sb,gt:kn,gte:p3,ilike:S3,inArray:is,isNull:Mr,isNotNull:m3,like:y3,lt:f3,lte:os,ne:u3,not:d3,notBetween:g3,notExists:ss,notLike:b3,notIlike:v3,notInArray:ib,or:ln,sql:C}}function k3(){return{sql:C,asc:qo,desc:ga}}function I3(e,t){if(Object.keys(e).length===1&&"default"in e&&!oe(e.default,he))e=e.default;let r={},o={},n={};for(let[i,s]of Object.entries(e))if(oe(s,he)){let a=ha(s),l=o[a];r[a]=i,n[i]={tsName:i,dbName:s[he.Symbol.Name],schema:s[he.Symbol.Schema],columns:s[he.Symbol.Columns],relations:l?.relations??{},primaryKey:l?.primaryKey??[]};for(let d of Object.values(s[he.Symbol.Columns]))if(d.primary)n[i].primaryKey.push(d);let u=s[he.Symbol.ExtraConfigBuilder]?.(s[he.Symbol.ExtraConfigColumns]);if(u){for(let d of Object.values(u))if(oe(d,GT))n[i].primaryKey.push(...d.columns)}}else if(oe(s,_3)){let a=ha(s.table),l=r[a],u=s.config(t(s.table)),d;for(let[p,m]of Object.entries(u))if(l){let h=n[l];if(h.relations[p]=m,d)h.primaryKey.push(...d)}else{if(!(a in o))o[a]={relations:{},primaryKey:d};o[a].relations[p]=m}}return{tables:n,tableNamesMap:r}}function Ume(e){return function(r,o){return new as(e,r,o,o?.fields.reduce((n,i)=>n&&i.notNull,!0)??!1)}}function Mme(e){return function(r,o){return new Up(e,r,o)}}function A3(e,t,r){if(oe(r,as)&&r.config)return{fields:r.config.fields,references:r.config.references};let o=t[ha(r.referencedTable)];if(!o)throw Error(`Table "${r.referencedTable[he.Symbol.Name]}" not found in schema`);let n=e[o];if(!n)throw Error(`Table "${o}" not found in schema`);let i=r.sourceTable,s=t[ha(i)];if(!s)throw Error(`Table "${i[he.Symbol.Name]}" not found in schema`);let a=[];for(let l of Object.values(n.relations))if(r.relationName&&r!==l&&l.relationName===r.relationName||!r.relationName&&l.referencedTable===r.sourceTable)a.push(l);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${o}"`):Error(`There are multiple relations between "${o}" and "${r.sourceTable[he.Symbol.Name]}". Please specify relation name`);if(a[0]&&oe(a[0],as)&&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 R3(e){return{one:Ume(e),many:Mme(e)}}function ab(e,t,r,o,n=(i)=>i){let i={};for(let[s,a]of o.entries())if(a.isJson){let l=t.relations[a.tsKey],u=r[s],d=typeof u==="string"?JSON.parse(u):u;i[a.tsKey]=oe(l,as)?d&&ab(e,e[a.relationTableTsKey],d,a.selection,n):d.map((p)=>ab(e,e[a.relationTableTsKey],p,a.selection,n))}else{let l=n(r[s]),u=a.field,d;if(oe(u,He))d=u;else if(oe(u,_e))d=u.decoder;else d=u.sql.decoder;i[a.tsKey]=l===null?null:d.mapFromDriverValue(l)}return i}var YT,_3,as,Up;var Mp=v(()=>{sr();_n();$e();l3();QT();Yt();YT=class YT{constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[he.Symbol.Name]}static[F]="Relation";referencedTableName;fieldName};_3=class _3{constructor(e,t){this.table=e,this.config=t}static[F]="Relations"};as=class as extends YT{constructor(e,t,r,o){super(e,t,r?.relationName);this.config=r,this.isNullable=o}static[F]="One";withFieldName(e){let t=new as(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};Up=class Up extends YT{constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[F]="Many";withFieldName(e){let t=new Up(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function qp(e,t){return new Proxy(e,new ya(t,!1))}function oo(e,t){return new Proxy(e,new Cl(new Proxy(e.table,new ya(t,!1))))}function XT(e,t){return new _e.Aliased(Fp(e.sql,t),e.fieldAlias)}function Fp(e,t){return C.join(e.queryChunks.map((r)=>{if(oe(r,He))return oo(r,t);if(oe(r,_e))return Fp(r,t);if(oe(r,_e.Aliased))return XT(r,t);return r}))}var Cl,ya,qme;var Kp=v(()=>{_n();$e();Yt();sr();Mo();Cl=class Cl{constructor(e){this.table=e}static[F]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};ya=class ya{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[F]="TableAliasProxyHandler";get(e,t){if(t===he.Symbol.IsAlias)return!0;if(t===he.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===he.Symbol.OriginalName)return this.alias;if(t===ft)return{...e[ft],name:this.alias,isAlias:!0};if(t===he.Symbol.Columns){let o=e[he.Symbol.Columns];if(!o)return o;let n={};return Object.keys(o).map((i)=>{n[i]=new Proxy(o[i],new Cl(new Proxy(e,this)))}),n}let r=e[t];if(oe(r,He))return new Proxy(r,new Cl(new Proxy(e,this)));return r}};qme=class qme{constructor(e){this.alias=e}static[F]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return qp(e.sourceTable,this.alias);return e[t]}}});var at;var ba=v(()=>{Kp();_n();$e();Yt();En();Mo();at=class at{static[F]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===ft)return{...e[ft],selectedFields:new Proxy(e[ft].selectedFields,this)};if(typeof t==="symbol")return e[t];let o=(oe(e,pt)?e._.selectedFields:oe(e,an)?e[ft].selectedFields:e)[t];if(oe(o,_e.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!o.isSelectionField)return o.sql;let n=o.clone();return n.isSelectionField=!0,n}if(oe(o,_e)){if(this.config.sqlBehavior==="sql")return o;throw Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(oe(o,He)){if(this.config.alias)return new Proxy(o,new Cl(new Proxy(o.table,new ya(this.config.alias,this.config.replaceOriginalName??!1))));return o}if(typeof o!=="object"||o===null)return o;return new Proxy(o,new at(this.config))}}});var vr;var Fo=v(()=>{$e();vr=class vr{static[F]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}});var e$,T3;var t$=v(()=>{$e();$l();e$=class e${static[F]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new T3(e,this)}};T3=class T3{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function r$(e,t){return`${e[ir]}_${t.join("_")}_unique`}var $3,Fme,O3;var n$=v(()=>{$e();$l();$3=class $3{constructor(e,t){this.name=t,this.columns=e}static[F]="SQLiteUniqueConstraintBuilder";columns;build(e){return new O3(e,this.columns,this.name)}};Fme=class Fme{static[F]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new $3(e,this.name)}};O3=class O3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??r$(this.table,this.columns.map((o)=>o.name))}static[F]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Ut,bt;var cs=v(()=>{Qy();_n();$e();t$();n$();Ut=class Ut extends zp{static[F]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:"always",mode:t?.mode??"virtual"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>((n,i)=>{let s=new e$(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)})(r,o))}};bt=class bt extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=r$(e,[t.name]);super(e,t);this.table=e}static[F]="SQLiteColumn"}});function B3(e,t){let{name:r,config:o}=no(e,t);if(o?.mode==="json")return new z3(r);if(o?.mode==="bigint")return new C3(r);return new D3(r)}var C3,P3,z3,N3,D3,L3;var o$=v(()=>{$e();Sr();cs();C3=class C3 extends Ut{static[F]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new P3(e,this.config)}};P3=class P3 extends bt{static[F]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return BigInt(t.toString("utf8"))}return BigInt(JT.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};z3=class z3 extends Ut{static[F]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new N3(e,this.config)}};N3=class N3 extends bt{static[F]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return JSON.parse(t.toString("utf8"))}return JSON.parse(JT.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};D3=class D3 extends Ut{static[F]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new L3(e,this.config)}};L3=class L3 extends bt{static[F]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function U3(e){return(t,r)=>{let{name:o,config:n}=no(t,r);return new j3(o,n,e)}}var j3,Z3;var i$=v(()=>{$e();Sr();cs();j3=class j3 extends Ut{static[F]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new Z3(e,this.config)}};Z3=class Z3 extends bt{static[F]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(e,t){super(e,t);this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom==="function"?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo==="function"?this.mapTo(e):e}}});function ar(e,t){let{name:r,config:o}=no(e,t);if(o?.mode==="timestamp"||o?.mode==="timestamp_ms")return new F3(r,o.mode);if(o?.mode==="boolean")return new J3(r,o.mode);return new M3(r)}var cb,lb,M3,q3,F3,K3,J3,H3;var s$=v(()=>{$e();Yt();Sr();cs();cb=class cb extends Ut{static[F]="SQLiteBaseIntegerBuilder";constructor(e,t,r){super(e,t,r);this.config.autoIncrement=!1}primaryKey(e){if(e?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};lb=class lb extends bt{static[F]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};M3=class M3 extends cb{static[F]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new q3(e,this.config)}};q3=class q3 extends lb{static[F]="SQLiteInteger"};F3=class F3 extends cb{static[F]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(C`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new K3(e,this.config)}};K3=class K3 extends lb{static[F]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(e){if(this.config.mode==="timestamp")return new Date(e*1000);return new Date(e)}mapToDriverValue(e){let t=e.getTime();if(this.config.mode==="timestamp")return Math.floor(t/1000);return t}};J3=class J3 extends cb{static[F]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new H3(e,this.config)}};H3=class H3 extends lb{static[F]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function e5(e,t){let{name:r,config:o}=no(e,t),n=o?.mode;return n==="number"?new G3(r):n==="bigint"?new Y3(r):new V3(r)}var V3,W3,G3,Q3,Y3,X3;var a$=v(()=>{$e();Sr();cs();V3=class V3 extends Ut{static[F]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new W3(e,this.config)}};W3=class W3 extends bt{static[F]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};G3=class G3 extends Ut{static[F]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new Q3(e,this.config)}};Q3=class Q3 extends bt{static[F]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};Y3=class Y3 extends Ut{static[F]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new X3(e,this.config)}};X3=class X3 extends bt{static[F]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function n5(e){return new t5(e??"")}var t5,r5;var c$=v(()=>{$e();cs();t5=class t5 extends Ut{static[F]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new r5(e,this.config)}};r5=class r5 extends bt{static[F]="SQLiteReal";getSQLType(){return"real"}}});function mt(e,t={}){let{name:r,config:o}=no(e,t);if(o.mode==="json")return new s5(r);return new o5(r,o)}var o5,i5,s5,a5;var l$=v(()=>{$e();Sr();cs();o5=class o5 extends Ut{static[F]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new i5(e,this.config)}};i5=class i5 extends bt{static[F]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};s5=class s5 extends Ut{static[F]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new a5(e,this.config)}};a5=class a5 extends bt{static[F]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function c5(){return{blob:B3,customType:U3,integer:ar,numeric:e5,real:n5,text:mt}}var l5=v(()=>{o$();i$();s$();a$();c$();l$()});function Kme(e,t,r,o,n=e){let i=new At(e,o,n),s=typeof t==="function"?t(c5()):t,a=Object.fromEntries(Object.entries(s).map(([u,d])=>{let p=d;p.setName(u);let m=p.build(i);return i[u$].push(...p.buildForeignKeys(m,i)),[u,m]})),l=Object.assign(i,a);if(l[he.Symbol.Columns]=a,l[he.Symbol.ExtraConfigColumns]=a,r)l[At.Symbol.ExtraConfigBuilder]=r;return l}var u$,At,Jp=(e,t,r)=>Kme(e,t,r);var Ko=v(()=>{$e();sr();l5();u$=Symbol.for("drizzle:SQLiteInlineForeignKeys");At=class At extends he{static[F]="SQLiteTable";static Symbol=Object.assign({},he.Symbol,{InlineForeignKeys:u$});[he.Symbol.Columns];[u$]=[];[he.Symbol.ExtraConfigBuilder]=void 0}});var Jme,u5;var d5=v(()=>{$e();Jme=class Jme{constructor(e,t){this.name=e,this.value=t}static[F]="SQLiteCheckBuilder";brand;build(e){return new u5(e,this)}};u5=class u5{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[F]="SQLiteCheck";name;value}});function Jo(e){return new p5(e,!1)}var p5,f5,m5;var h5=v(()=>{$e();p5=class p5{constructor(e,t){this.name=e,this.unique=t}static[F]="SQLiteIndexBuilderOn";on(...e){return new f5(this.name,e,this.unique)}};f5=class f5{static[F]="SQLiteIndexBuilder";config;constructor(e,t,r){this.config={name:e,columns:t,unique:r,where:void 0}}where(e){return this.config.where=e,this}build(e){return new m5(this.config,e)}};m5=class m5{static[F]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var Hme,g5;var y5=v(()=>{$e();Ko();Hme=class Hme{static[F]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new g5(e,this.columns,this.name)}};g5=class g5{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[At.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function In(e){if(oe(e,At))return[`${e[he.Symbol.BaseName]}`];if(oe(e,pt))return e._.usedTables??[];if(oe(e,_e))return e.usedTables??[];return[]}var Pl=v(()=>{$e();Yt();En();sr();Ko()});var ub;var b5=v(()=>{$e();Fo();ba();Ko();sr();Sr();Pl();ub=class ub extends vr{constructor(e,t,r,o){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:o}}static[F]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[he.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[At.Symbol.Columns]){return this.config.returning=cn(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:In(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 Vme(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function Wme(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,o,n)=>{let i=n===0?o.toLowerCase():`${o[0].toUpperCase()}${o.slice(1)}`;return r+i},"")}function Gme(e){return e}var d$;var S5=v(()=>{$e();sr();d$=class d${static[F]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Vme:e==="camelCase"?Wme:Gme}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[he.Symbol.Schema]??"public",r=e.table[he.Symbol.OriginalName],o=`${t}.${r}.${e.name}`;if(!this.cache[o])this.cacheTable(e.table);return this.cache[o]}cacheTable(e){let t=e[he.Symbol.Schema]??"public",r=e[he.Symbol.OriginalName],o=`${t}.${r}`;if(!this.cachedTables[o]){for(let n of Object.values(e[he.Symbol.Columns])){let i=`${o}.${n.name}`;this.cache[i]=this.convert(n.name)}this.cachedTables[o]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var zl,Ho,p$;var db=v(()=>{$e();zl=class zl extends Error{static[F]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};Ho=class Ho extends Error{constructor(e,t,r){super(`Failed query: ${e}
|
|
424
|
+
`)}catch{}}}formatJsonEntry(e,t,r){let o={ts:new Date().toISOString(),level:e,...sl&&{role:sl},msg:t};if(this.context)o.ctx=this.context;if(r.length>0)o.data=r;return JSON.stringify(o)}debugStream(){return this.useStderr?console.error.bind(console):console.debug.bind(console)}silly(e,...t){if(this.level<=ia.SILLY)this.write(this.debugStream(),"silly",e,t)}verbose(e,...t){if(this.level<=ia.VERBOSE)this.write(this.debugStream(),"verbose",e,t)}debug(e,...t){if(this.level<=ia.DEBUG)this.write(this.debugStream(),"debug",e,t)}info(e,...t){if(this.level<=ia.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<=ia.WARN)this.write(console.warn.bind(console),"warn",e,t)}error(e,...t){if(this.level<=ia.ERROR)this.write(console.error.bind(console),"error",e,t)}child(e){return new Ar({level:this.level,context:e,useStderr:this.useStderr,format:this.format},this.fileHandle)}setUseStderr(e){this.useStderr=e}}var ia,sl,VNe;var WR=v(()=>{ia={SILLY:0,VERBOSE:1,DEBUG:2,INFO:3,WARN:4,ERROR:5,NONE:6};VNe=Ar.getInstance()});var GR,Hde,al,YNe;var dp=v(()=>{Tt();pe();GR=c.enum(["file_operations","content_operations","data_processing","batch_processing"]),Hde=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:GR,operationTarget:c.string().optional(),interfaceType:c.string().optional(),interfaceId:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:Bn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:po.optional()}),al=c.looseObject({pluginId:c.string().optional(),progressToken:c.union([c.string(),c.number()]).optional(),operationType:GR,operationTarget:c.string().optional(),interfaceType:c.string().optional(),interfaceId:c.string().optional(),conversationId:c.string().optional(),channelId:c.string().optional(),requestedByActor:Bn.optional(),requestedByUserId:c.string().optional(),requestedByInterface:c.string().optional(),silent:c.boolean().optional(),provenance:po.optional(),rootJobId:c.string()}),YNe=c.enum(["none","skip","replace","coalesce"])});var Vde,Ji=15000;var pp=v(()=>{dp();pe();Vde=c.object({id:c.string(),type:c.string(),data:c.string(),status:c.enum(["pending","processing","completed","failed"]),source:c.string().nullable(),priority:c.number(),retryCount:c.number(),maxRetries:c.number(),lastError:c.string().nullable(),lastErrorPublic:c.unknown(),createdAt:c.number(),scheduledFor:c.number(),startedAt:c.number().nullable(),completedAt:c.number().nullable(),attemptId:c.string().nullable(),workerSlotId:c.string().nullable(),workerSessionId:c.string().nullable(),leaseExpiresAt:c.number().nullable(),attemptHeartbeatAt:c.number().nullable(),runtimeUpdatedAt:c.number().nullable(),metadata:al,progress:c.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:c.unknown().nullable().optional()})});var QR,hq,Oe,Wde,Gde,gq,yq,bq;var Lo=v(()=>{Tt();pe();dp();QR=c.enum(["pending","processing","completed","failed"]),hq=c.enum(["completed","failed"]),Oe={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},Wde=c.object({id:c.string(),type:c.string(),status:QR,data:c.unknown(),result:c.unknown().optional(),lastError:c.string().optional().nullable(),attempts:c.number(),maxRetries:c.number(),priority:c.number(),createdAt:c.date(),updatedAt:c.date(),processedAt:c.date().optional().nullable(),completedAt:c.date().optional().nullable(),failedAt:c.date().optional().nullable()}),Gde=c.object({jobId:c.string(),type:c.string(),status:hq,result:c.unknown().optional(),error:c.string().optional()}),gq=c.object({success:c.literal(!1),error:c.string().optional()}),yq=c.object({id:c.string(),type:c.enum(["job","batch"]),status:QR,message:c.string().optional(),progress:c.object({current:c.number(),total:c.number(),percentage:c.number()}).optional(),aggregationKey:c.string().optional(),batchDetails:c.object({totalOperations:c.number(),completedOperations:c.number(),failedOperations:c.number(),currentOperation:c.string().optional(),errors:c.array(c.string()).optional()}).optional(),jobDetails:c.object({jobType:c.string(),priority:c.number(),retryCount:c.number()}).optional(),metadata:al}),bq=ui(UE.progress,yq)});var Ce,Gt;var vn=v(()=>{Ce=class Ce extends Error{code;extendedCode;rawCode;constructor(e,t,r,o,n){if(t!==void 0)e=`${t}: ${e}`;super(e,{cause:n});this.code=t,this.extendedCode=r,this.rawCode=o,this.name="LibsqlError"}};Gt=class Gt extends Ce{statementIndex;constructor(e,t,r,o,n,i){super(e,r,o,n,i);this.statementIndex=t,this.name="LibsqlBatchError"}}});function Sq(e){let t=Qde.exec(e);if(t===null)throw new Ce(`The URL '${e}' is not in a valid format`,"URL_INVALID");let r=t.groups,o=r.scheme,n=r.authority!==void 0?Yde(r.authority):void 0,i=sa(r.path),s=r.query!==void 0?epe(r.query):void 0,a=r.fragment!==void 0?sa(r.fragment):void 0;return{scheme:o,authority:n,path:i,query:s,fragment:a}}function Yde(e){let t=Xde.exec(e);if(t===null)throw new Ce("The authority part of the URL is not in a valid format","URL_INVALID");let r=t.groups,o=sa(r.host_br??r.host),n=r.port?parseInt(r.port,10):void 0,i=r.username!==void 0?{username:sa(r.username),password:r.password!==void 0?sa(r.password):void 0}:void 0;return{host:o,port:n,userinfo:i}}function epe(e){let t=e.split("&"),r=[];for(let o of t){if(o==="")continue;let n,i,s=o.indexOf("=");if(s<0)n=o,i="";else n=o.substring(0,s),i=o.substring(s+1);r.push({key:sa(n.replaceAll("+"," ")),value:sa(i.replaceAll("+"," "))})}return{pairs:r}}function sa(e){try{return decodeURIComponent(e)}catch(t){if(t instanceof URIError)throw new Ce(`URL component has invalid percent encoding: ${t}`,"URL_INVALID",void 0,void 0,t);throw t}}function fp(e,t,r){if(t===void 0)throw new Ce(`URL with scheme ${JSON.stringify(e+":")} requires authority (the "//" part)`,"URL_INVALID");let o=`${e}:`,n=tpe(t.host),i=rpe(t.port),a=`//${npe(t.userinfo)}${n}${i}`,l=r.split("/").map(encodeURIComponent).join("/");if(l!==""&&!l.startsWith("/"))l="/"+l;return new URL(`${o}${a}${l}`)}function tpe(e){return e.includes(":")?`[${encodeURI(e)}]`:encodeURI(e)}function rpe(e){return e!==void 0?`:${e}`:""}function npe(e){if(e===void 0)return"";let t=encodeURIComponent(e.username),r=e.password!==void 0?`:${encodeURIComponent(e.password)}`:"";return`${t}${r}@`}var Qde,Xde;var Iy=v(()=>{vn();Qde=(()=>new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su"))();Xde=(()=>new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su"))()});var ll,vq,wq,mp,Ay,ope,Qt,xq,kq=(e)=>e.replace(/=/g,"").replace(/[+\/]/g,(t)=>t=="+"?"-":"_"),Iq=(e)=>e.replace(/[^A-Za-z0-9\+\/]/g,""),Aq=(e)=>{let t,r,o,n,i="",s=e.length%3;for(let a=0;a<e.length;){if((r=e.charCodeAt(a++))>255||(o=e.charCodeAt(a++))>255||(n=e.charCodeAt(a++))>255)throw TypeError("invalid character found");t=r<<16|o<<8|n,i+=mp[t>>18&63]+mp[t>>12&63]+mp[t>>6&63]+mp[t&63]}return s?i.slice(0,s-3)+"===".substring(s):i},eT,YR,Ry=(e,t=!1)=>t?kq(YR(e)):YR(e),ipe=(e)=>{if(e.length<2){var t=e.charCodeAt(0);return t<128?e:t<2048?Qt(192|t>>>6)+Qt(128|t&63):Qt(224|t>>>12&15)+Qt(128|t>>>6&63)+Qt(128|t&63)}else{var t=65536+(e.charCodeAt(0)-55296)*1024+(e.charCodeAt(1)-56320);return Qt(240|t>>>18&7)+Qt(128|t>>>12&63)+Qt(128|t>>>6&63)+Qt(128|t&63)}},spe,Rq=(e)=>e.replace(spe,ipe),_q,cl=(e,t=!1)=>t?kq(_q(e)):_q(e),Eq=(e)=>cl(e,!0),ape,cpe=(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 Qt((r>>>10)+55296)+Qt((r&1023)+56320);case 3:return Qt((15&e.charCodeAt(0))<<12|(63&e.charCodeAt(1))<<6|63&e.charCodeAt(2));default:return Qt((31&e.charCodeAt(0))<<6|63&e.charCodeAt(1))}},Tq=(e)=>e.replace(ape,cpe),$q=(e)=>{if(e=e.replace(/\s+/g,""),!ope.test(e))throw TypeError("malformed base64.");e+="==".slice(2-(e.length&3));let t,r,o,n=[];for(let i=0;i<e.length;)if(t=Ay[e.charAt(i++)]<<18|Ay[e.charAt(i++)]<<12|(r=Ay[e.charAt(i++)])<<6|(o=Ay[e.charAt(i++)]),r===64)n.push(Qt(t>>16&255));else if(o===64)n.push(Qt(t>>16&255,t>>8&255));else n.push(Qt(t>>16&255,t>>8&255,t&255));return n.join("")},tT,Oq,Cq=(e)=>Oq(Pq(e)),lpe,Pq=(e)=>Iq(e.replace(/[-_]/g,(t)=>t=="-"?"+":"/")),XR=(e)=>lpe(Pq(e)),upe=(e)=>{if(typeof e!=="string")return!1;let t=e.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(t)||!/[^\s0-9a-zA-Z\-_]/.test(t)},zq=(e)=>({value:e,enumerable:!1,writable:!0,configurable:!0}),Nq=function(){let e=(t,r)=>Object.defineProperty(String.prototype,t,zq(r));e("fromBase64",function(){return XR(this)}),e("toBase64",function(t){return cl(this,t)}),e("toBase64URI",function(){return cl(this,!0)}),e("toBase64URL",function(){return cl(this,!0)}),e("toUint8Array",function(){return Cq(this)})},Dq=function(){let e=(t,r)=>Object.defineProperty(Uint8Array.prototype,t,zq(r));e("toBase64",function(t){return Ry(this,t)}),e("toBase64URI",function(){return Ry(this,!0)}),e("toBase64URL",function(){return Ry(this,!0)})},dpe=()=>{Nq(),Dq()},ul;var Ty=v(()=>{ll=typeof Buffer==="function",vq=typeof TextDecoder==="function"?new TextDecoder("utf-8",{ignoreBOM:!0}):void 0,wq=typeof TextEncoder==="function"?new TextEncoder:void 0,mp=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),Ay=((e)=>{let t={};return e.forEach((r,o)=>t[r]=o),t})(mp),ope=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,Qt=String.fromCharCode.bind(String),xq=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(e)=>new Uint8Array(Array.prototype.slice.call(e,0)),eT=typeof btoa==="function"?(e)=>btoa(e):ll?(e)=>Buffer.from(e,"binary").toString("base64"):Aq,YR=ll?(e)=>Buffer.from(e).toString("base64"):(e)=>{let r=[];for(let o=0,n=e.length;o<n;o+=4096)r.push(Qt.apply(null,e.subarray(o,o+4096)));return eT(r.join(""))},spe=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,_q=ll?(e)=>Buffer.from(e,"utf8").toString("base64"):wq?(e)=>YR(wq.encode(e)):(e)=>eT(Rq(e)),ape=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,tT=typeof atob==="function"?(e)=>atob(Iq(e)):ll?(e)=>Buffer.from(e,"base64").toString("binary"):$q,Oq=ll?(e)=>xq(Buffer.from(e,"base64")):(e)=>xq(tT(e).split("").map((t)=>t.charCodeAt(0))),lpe=ll?(e)=>Buffer.from(e,"base64").toString("utf8"):vq?(e)=>vq.decode(Oq(e)):(e)=>Tq(tT(e)),ul={version:"3.8.0",VERSION:"3.8.0",atob:tT,atobPolyfill:$q,btoa:eT,btoaPolyfill:Aq,fromBase64:XR,toBase64:cl,encode:cl,encodeURI:Eq,encodeURL:Eq,utob:Rq,btou:Tq,decode:XR,isValid:upe,fromUint8Array:Ry,toUint8Array:Cq,extendString:Nq,extendUint8Array:Dq,extendBuiltins:dpe}});function Hi(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 dl{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(e,t,r,o,n){this.columns=e,this.columnTypes=t,this.rows=r,this.rowsAffected=o,this.lastInsertRowid=n}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(ppe),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function ppe(e){return Array.prototype.map.call(e,fpe)}function fpe(e){if(typeof e==="bigint")return""+e;else if(e instanceof ArrayBuffer)return ul.fromUint8Array(new Uint8Array(e));else return e}var Xn="https://github.com/libsql/libsql-client-ts#supported-urls";var pl=v(()=>{Ty()});function Bq(e){return e.scheme==="file"&&(e.path===":memory:"||e.path.startsWith(":memory:?"))}function hp(e,t){if(typeof e!=="object")throw TypeError(`Expected client configuration as object, got ${typeof e}`);let{url:r,authToken:o,tls:n,intMode:i,concurrency:s}=e;s=Math.max(0,s||20),i??="number";let a=[];if(r===Lq)r="file::memory:";let l=Sq(r),u=l.scheme.toLowerCase(),d=u==="file"&&l.path===Lq&&l.authority===void 0,p;if(d)p={cache:{values:["shared","private"],update:(y,S)=>a.push(`${y}=${S}`)}};else p={tls:{values:["0","1"],update:(y,S)=>n=S==="1"},authToken:{update:(y,S)=>o=S}};for(let{key:y,value:S}of l.query?.pairs??[]){if(!Object.hasOwn(p,y))throw new Ce(`Unsupported URL query parameter ${JSON.stringify(y)}`,"URL_PARAM_NOT_SUPPORTED");let x=p[y];if(x.values!==void 0&&!x.values.includes(S))throw new Ce(`Unknown value for the "${y}" query argument: ${JSON.stringify(S)}. Supported values are: [${x.values.map((_)=>'"'+_+'"').join(", ")}]`,"URL_INVALID");if(x.update!==void 0)x?.update(y,S)}let m=a.length===0?"":`?${a.join("&")}`,h=l.path+m,b;if(u==="libsql")if(n===!1){if(l.authority?.port===void 0)throw new Ce('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");b=t?"http":"ws"}else b=t?"https":"wss";else b=u;if(b==="http"||b==="ws")n??=!1;else n??=!0;if(b!=="http"&&b!=="ws"&&b!=="https"&&b!=="wss"&&b!=="file")throw new Ce(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(l.scheme+":")}. For more information, please read ${Xn}`,"URL_SCHEME_NOT_SUPPORTED");if(i!=="number"&&i!=="bigint"&&i!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(i)}`);if(l.fragment!==void 0)throw new Ce(`URL fragments are not supported: ${JSON.stringify("#"+l.fragment)}`,"URL_INVALID");if(d)return{scheme:"file",tls:!1,path:h,intMode:i,concurrency:s,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout,authToken:void 0,encryptionKey:void 0,remoteEncryptionKey:void 0,authority:void 0};return{scheme:b,tls:n,authority:l.authority,path:h,authToken:o,intMode:i,concurrency:s,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncInterval:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,fetch:e.fetch,timeout:e.timeout}}var Lq=":memory:";var gp=v(()=>{vn();Iy();pl()});var Zq=ge(function(nn){var mpe=nn&&nn.__createBinding||(Object.create?function(e,t,r,o){if(o===void 0)o=r;var n=Object.getOwnPropertyDescriptor(t,r);if(!n||("get"in n?!t.__esModule:n.writable||n.configurable))n={enumerable:!0,get:function(){return t[r]}};Object.defineProperty(e,o,n)}:function(e,t,r,o){if(o===void 0)o=r;e[o]=t[r]}),hpe=nn&&nn.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),jq=nn&&nn.__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))mpe(t,e,r)}return hpe(t,e),t};Object.defineProperty(nn,"__esModule",{value:!0});nn.load=nn.currentTarget=void 0;var gpe=jq(qr("path")),ype=jq(qr("fs"));function bpe(){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 Spe()?`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}`)}nn.currentTarget=bpe;function Spe(){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 vpe(e){let t=gpe.join(e,"index.node");return ype.existsSync(t)?qr(t):null}nn.load=vpe});var qq=ge(function(S2e,Mq){var Uq=()=>process.platform==="linux",rT=null,wpe=()=>{if(!rT)rT=Uq()&&process.report?process.report.getReport():{};return rT};Mq.exports={isLinux:Uq,getReport:wpe}});var Jq=ge(function(v2e,Kq){var Fq=qr("fs"),xpe=(e)=>Fq.readFileSync(e,"utf-8"),_pe=(e)=>new Promise((t,r)=>{Fq.readFile(e,"utf-8",(o,n)=>{if(o)r(o);else t(n)})});Kq.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:xpe,readFile:_pe}});var l4=ge(function(w2e,c4){var Vq=qr("child_process"),{isLinux:fl,getReport:Wq}=qq(),{LDD_PATH:$y,readFile:Gq,readFileSync:Qq}=Jq(),eo,to,Vi="",Yq=()=>{if(!Vi)return new Promise((e)=>{Vq.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",(t,r)=>{Vi=t?" ":r,e(Vi)})});return Vi},Xq=()=>{if(!Vi)try{Vi=Vq.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(e){Vi=" "}return Vi},Bo="glibc",e4=/GLIBC\s(\d+\.\d+)/,aa="musl",Epe=Bo.toUpperCase(),kpe=aa.toLowerCase(),Ipe=(e)=>e.includes("libc.musl-")||e.includes("ld-musl-"),t4=()=>{let e=Wq();if(e.header&&e.header.glibcVersionRuntime)return Bo;if(Array.isArray(e.sharedObjects)){if(e.sharedObjects.some(Ipe))return aa}return null},r4=(e)=>{let[t,r]=e.split(/[\r\n]+/);if(t&&t.includes(Bo))return Bo;if(r&&r.includes(aa))return aa;return null},n4=(e)=>{if(e.includes(kpe))return aa;if(e.includes(Epe))return Bo;return null},Ape=async()=>{if(eo!==void 0)return eo;eo=null;try{let e=await Gq($y);eo=n4(e)}catch(e){}return eo},Rpe=()=>{if(eo!==void 0)return eo;eo=null;try{let e=Qq($y);eo=n4(e)}catch(e){}return eo},o4=async()=>{let e=null;if(fl()){if(e=await Ape(),!e)e=t4();if(!e){let t=await Yq();e=r4(t)}}return e},i4=()=>{let e=null;if(fl()){if(e=Rpe(),!e)e=t4();if(!e){let t=Xq();e=r4(t)}}return e},Tpe=async()=>fl()&&await o4()!==Bo,$pe=()=>fl()&&i4()!==Bo,Ope=async()=>{if(to!==void 0)return to;to=null;try{let t=(await Gq($y)).match(e4);if(t)to=t[1]}catch(e){}return to},Cpe=()=>{if(to!==void 0)return to;to=null;try{let t=Qq($y).match(e4);if(t)to=t[1]}catch(e){}return to},s4=()=>{let e=Wq();if(e.header&&e.header.glibcVersionRuntime)return e.header.glibcVersionRuntime;return null},Hq=(e)=>e.trim().split(/\s+/)[1],a4=(e)=>{let[t,r,o]=e.split(/[\r\n]+/);if(t&&t.includes(Bo))return Hq(t);if(r&&o&&r.includes(aa))return Hq(o);return null},Ppe=async()=>{let e=null;if(fl()){if(e=await Ope(),!e)e=s4();if(!e){let t=await Yq();e=a4(t)}}return e},zpe=()=>{let e=null;if(fl()){if(e=Cpe(),!e)e=s4();if(!e){let t=Xq();e=a4(t)}}return e};c4.exports={GLIBC:Bo,MUSL:aa,family:o4,familySync:i4,isNonGlibcLinux:Tpe,isNonGlibcLinuxSync:$pe,version:Ppe,versionSync:zpe}});var d4=ge(function(x2e,u4){var Npe={ALLOW:0,DENY:1};u4.exports=Npe});var f4=ge(function(_2e,p4){var nT={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function ca(e,t,r){if(new.target!==ca)return new ca(e,t);if(typeof t!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,e),nT.value=""+e,Object.defineProperty(this,"message",nT),Error.captureStackTrace(this,ca),this.code=t,this.rawCode=r}Object.setPrototypeOf(ca,Error);Object.setPrototypeOf(ca.prototype,Error.prototype);Object.defineProperty(ca.prototype,"name",nT);p4.exports=ca});var w4=ge(function(E2e,Oy){var __dirname="/home/runner/work/brains/brains/node_modules/libsql",{load:Dpe,currentTarget:Lpe}=Zq(),{familySync:m4,GLIBC:Bpe,MUSL:jpe}=l4();function Zpe(){if(process.env.LIBSQL_JS_DEV)return Dpe(__dirname);let e=Lpe();if(m4()==Bpe)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"&&m4()==jpe)e="linux-arm-musleabihf";return qr(`@libsql/${e}`)}var{databaseOpen:Upe,databaseOpenWithSync:Mpe,databaseInTransaction:qpe,databaseInterrupt:Fpe,databaseClose:Kpe,databaseSyncSync:Jpe,databaseSyncUntilSync:Hpe,databaseExecSync:Vpe,databasePrepareSync:Wpe,databaseDefaultSafeIntegers:Gpe,databaseAuthorizer:Qpe,databaseLoadExtension:Ype,databaseMaxWriteReplicationIndex:Xpe,statementRaw:efe,statementIsReader:tfe,statementGet:h4,statementRun:g4,statementInterrupt:rfe,statementRowsSync:y4,statementColumns:nfe,statementSafeIntegers:ofe,rowsNext:ife}=Zpe(),sfe=d4(),b4=f4();function ml(e){if(e.libsqlError)return new b4(e.message,e.code,e.rawCode);return e}class S4{constructor(e,t){let r=t?.encryptionCipher??"aes256cbc";if(t&&t.syncUrl){var o="";if(t.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),o=t.syncAuth;else if(t.authToken)o=t.authToken;let i=t?.encryptionKey??"",s=t?.syncPeriod??0,a=t?.readYourWrites??!0,l=t?.offline??!1,u=t?.remoteEncryptionKey??"";this.db=Mpe(e,t.syncUrl,o,r,i,s,a,l,u)}else{let i=t?.authToken??"",s=t?.encryptionKey??"",a=t?.timeout??0,l=t?.remoteEncryptionKey??"";this.db=Upe(e,i,r,s,a,l)}this.memory=e===":memory:",this.readonly=!1,this.name="",this.open=!0;let n=this.db;Object.defineProperties(this,{inTransaction:{get(){return qpe(n)}}})}sync(){return Jpe.call(this.db)}syncUntil(e){return Hpe.call(this.db,e)}prepare(e){try{let t=Wpe.call(this.db,e);return new v4(t)}catch(t){throw ml(t)}}transaction(e){if(typeof e!=="function")throw TypeError("Expected first argument to be a function");let t=this,r=(n)=>(...i)=>{t.exec("BEGIN "+n);try{let s=e(...i);return t.exec("COMMIT"),s}catch(s){throw t.exec("ROLLBACK"),s}},o={default:{value:r("")},deferred:{value:r("DEFERRED")},immediate:{value:r("IMMEDIATE")},exclusive:{value:r("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(o.default.value,o),Object.defineProperties(o.deferred.value,o),Object.defineProperties(o.immediate.value,o),Object.defineProperties(o.exclusive.value,o),o.default.value}pragma(e,t){if(t==null)t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");let r=t.simple,o=this.prepare(`PRAGMA ${e}`,this,!0);return r?o.pluck().get():o.all()}backup(e,t){throw Error("not implemented")}serialize(e){throw Error("not implemented")}function(e,t,r){if(t==null)t={};if(typeof t==="function")r=t,t={};if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof r!=="function")throw TypeError("Expected last argument to be a function");if(typeof t!=="object")throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}aggregate(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(typeof t!=="object"||t===null)throw TypeError("Expected second argument to be an options object");if(!e)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}table(e,t){if(typeof e!=="string")throw TypeError("Expected first argument to be a string");if(!e)throw TypeError("Virtual table module name cannot be an empty string");throw Error("not implemented")}authorizer(e){Qpe.call(this.db,e)}loadExtension(...e){Ype.call(this.db,...e)}maxWriteReplicationIndex(){return Xpe.call(this.db)}exec(e){try{Vpe.call(this.db,e)}catch(t){throw ml(t)}}interrupt(){Fpe.call(this.db)}close(){Kpe.call(this.db),this.open=!1}defaultSafeIntegers(e){return Gpe.call(this.db,e??!0),this}unsafeMode(...e){throw Error("not implemented")}}class v4{constructor(e){this.stmt=e,this.pluckMode=!1}raw(e){return efe.call(this.stmt,e??!0),this}pluck(e){return this.pluckMode=e??!0,this}get reader(){return tfe.call(this.stmt)}run(...e){try{if(e.length==1&&typeof e[0]==="object")return g4.call(this.stmt,e[0]);else return g4.call(this.stmt,e.flat())}catch(t){throw ml(t)}}get(...e){try{if(e.length==1&&typeof e[0]==="object")return h4.call(this.stmt,e[0]);else return h4.call(this.stmt,e.flat())}catch(t){throw ml(t)}}iterate(...e){var t=void 0;if(e.length==1&&typeof e[0]==="object")t=y4.call(this.stmt,e[0]);else t=y4.call(this.stmt,e.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)ife.call(t,this.nextRows),this.nextRowIndex=0;let o=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!o)return{done:!0};return this.nextRowIndex++,{value:o,done:!1}}catch(o){throw ml(o)}},[Symbol.iterator](){return this}}}all(...e){try{let t=[];for(let r of this.iterate(...e))if(this.pluckMode)t.push(r[Object.keys(r)[0]]);else t.push(r);return t}catch(t){throw ml(t)}}interrupt(){rfe.call(this.stmt)}columns(){return nfe.call(this.stmt)}safeIntegers(e){return ofe.call(this.stmt,e??!0),this}}Oy.exports=S4;Oy.exports.Authorization=sfe;Oy.exports.SqliteError=b4});import{Buffer as _4}from"buffer";function E4(e){if(e.scheme!=="file")throw new Ce(`URL scheme ${JSON.stringify(e.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${Xn}`,"URL_SCHEME_NOT_SUPPORTED");let t=e.authority;if(t!==void 0){let s=t.host.toLowerCase();if(s!==""&&s!=="localhost")throw new Ce(`Invalid host in file URL: ${JSON.stringify(t.host)}. A "file:" URL with an absolute path should start with one slash ("file:/absolute/path.db") or with three slashes ("file:///absolute/path.db"). For more information, please read ${Xn}`,"URL_INVALID");if(t.port!==void 0)throw new Ce("File URL cannot have a port","URL_INVALID");if(t.userinfo!==void 0)throw new Ce("File URL cannot have username and password","URL_INVALID")}let r=Bq(e);if(r&&e.syncUrl)throw new Ce(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${e.path}`,"URL_INVALID");let o=e.path;if(r)o=`${e.scheme}:${e.path}`;let n={authToken:e.authToken,encryptionKey:e.encryptionKey,remoteEncryptionKey:e.remoteEncryptionKey,syncUrl:e.syncUrl,syncPeriod:e.syncInterval,readYourWrites:e.readYourWrites,offline:e.offline,timeout:e.timeout},i=new yp.default(o,n);return zt(i,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",e.intMode),new k4(o,n,i,e.intMode)}class k4{#e;#t;#r;#n;closed;protocol;constructor(e,t,r,o){this.#e=e,this.#t=t,this.#r=r,this.#n=o,this.closed=!1,this.protocol="file"}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#o(),zt(this.#i(),r,this.#n)}async batch(e,t="deferred"){this.#o();let r=this.#i();try{zt(r,Hi(t),this.#n);let o=[];for(let n=0;n<e.length;n++)try{if(!r.inTransaction)throw new Gt("The transaction has been rolled back",n,"TRANSACTION_CLOSED");let i=e[n],s=Array.isArray(i)?{sql:i[0],args:i[1]||[]}:i;o.push(zt(r,s,this.#n))}catch(i){if(i instanceof Gt)throw i;if(i instanceof Ce)throw new Gt(i.message,n,i.code,i.extendedCode,i.rawCode,i.cause instanceof Error?i.cause:void 0);throw i}return zt(r,"COMMIT",this.#n),o}finally{if(r.inTransaction)zt(r,"ROLLBACK",this.#n)}}async migrate(e){this.#o();let t=this.#i();try{zt(t,"PRAGMA foreign_keys=off",this.#n),zt(t,Hi("deferred"),this.#n);let r=[];for(let o=0;o<e.length;o++)try{if(!t.inTransaction)throw new Gt("The transaction has been rolled back",o,"TRANSACTION_CLOSED");r.push(zt(t,e[o],this.#n))}catch(n){if(n instanceof Gt)throw n;if(n instanceof Ce)throw new Gt(n.message,o,n.code,n.extendedCode,n.rawCode,n.cause instanceof Error?n.cause:void 0);throw n}return zt(t,"COMMIT",this.#n),r}finally{if(t.inTransaction)zt(t,"ROLLBACK",this.#n);zt(t,"PRAGMA foreign_keys=on",this.#n)}}async transaction(e="write"){let t=this.#i();return zt(t,Hi(e),this.#n),this.#r=null,new I4(t,this.#n)}async executeMultiple(e){this.#o();let t=this.#i();try{return A4(t,e)}finally{if(t.inTransaction)zt(t,"ROLLBACK",this.#n)}}async sync(){this.#o();let e=await this.#i().sync();return{frames_synced:e.frames_synced,frame_no:e.frame_no}}async reconnect(){try{if(!this.closed&&this.#r!==null)this.#r.close()}finally{this.#r=new yp.default(this.#e,this.#t),this.closed=!1}}close(){if(this.closed=!0,this.#r!==null)this.#r.close(),this.#r=null}#o(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED")}#i(){if(this.#r===null)this.#r=new yp.default(this.#e,this.#t);return this.#r}}class I4{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.#r(),zt(this.#e,r,this.#t)}async batch(e){let t=[];for(let r=0;r<e.length;r++)try{this.#r();let o=e[r],n=Array.isArray(o)?{sql:o[0],args:o[1]||[]}:o;t.push(zt(this.#e,n,this.#t))}catch(o){if(o instanceof Gt)throw o;if(o instanceof Ce)throw new Gt(o.message,r,o.code,o.extendedCode,o.rawCode,o.cause instanceof Error?o.cause:void 0);throw o}return t}async executeMultiple(e){return this.#r(),A4(this.#e,e)}async rollback(){if(!this.#e.open)return;this.#r(),zt(this.#e,"ROLLBACK",this.#t)}async commit(){this.#r(),zt(this.#e,"COMMIT",this.#t)}close(){if(this.#e.inTransaction)zt(this.#e,"ROLLBACK",this.#t)}get closed(){return!this.#e.inTransaction}#r(){if(this.closed)throw new Ce("The transaction is closed","TRANSACTION_CLOSED")}}function zt(e,t,r){let o,n;if(typeof t==="string")o=t,n=[];else if(o=t.sql,Array.isArray(t.args))n=t.args.map((i)=>x4(i,r));else{n={};for(let i in t.args){let s=i[0]==="@"||i[0]==="$"||i[0]===":"?i.substring(1):i;n[s]=x4(t.args[i],r)}}try{let i=e.prepare(o);i.safeIntegers(!0);let s=!0;try{i.raw(!0)}catch{s=!1}if(s){let a=Array.from(i.columns().map((m)=>m.name)),l=Array.from(i.columns().map((m)=>m.type??"")),u=i.all(n).map((m)=>afe(m,a,r)),d=0,p=void 0;return new dl(a,l,u,0,void 0)}else{let a=i.run(n),l=a.changes,u=BigInt(a.lastInsertRowid);return new dl([],[],[],l,u)}}catch(i){throw R4(i)}}function afe(e,t,r){let o={};Object.defineProperty(o,"length",{value:e.length});for(let n=0;n<e.length;++n){let i=cfe(e[n],r);Object.defineProperty(o,n,{value:i});let s=t[n];if(!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function cfe(e,t){if(typeof e==="bigint")if(t==="number"){if(e<lfe||e>ufe)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 _4)return e.buffer;return e}function x4(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<dfe||e>pfe)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 _4.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 A4(e,t){try{e.exec(t)}catch(r){throw R4(r)}}function R4(e){if(e instanceof yp.default.SqliteError){let t=e.code,r=ffe(e.rawCode);return new Ce(e.message,r,t,e.rawCode,e)}return e}function ffe(e){if(e===void 0)return"SQLITE_UNKNOWN";let t=e&255;return mfe[t]??`SQLITE_UNKNOWN_${t.toString()}`}var yp,lfe,ufe=9007199254740991n,dfe,pfe=9223372036854775807n,mfe;var T4=v(()=>{vn();gp();pl();yp=Fl(w4(),1);vn();lfe=-9007199254740991n;dfe=-9223372036854775808n;mfe={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 Wi;var oT=v(()=>{if(typeof WebSocket<"u")Wi=WebSocket;else if(typeof global<"u")Wi=global.WebSocket;else if(typeof window<"u")Wi=window.WebSocket;else if(typeof self<"u")Wi=self.WebSocket});class hl{constructor(){this.intMode="number"}intMode}var Ge,Pe,bp,xt,Sp,gl,la,wn,or,ro;var _t=v(()=>{Ge=class Ge extends Error{constructor(e){super(e);this.name="ClientError"}};Pe=class Pe extends Ge{constructor(e){super(e);this.name="ProtoError"}};bp=class bp extends Ge{code;proto;constructor(e,t){super(e);this.name="ResponseError",this.code=t.code,this.proto=t,this.stack=void 0}};xt=class xt extends Ge{constructor(e,t){if(t!==void 0){super(`${e}: ${t}`);this.cause=t}else super(e);this.name="ClosedError"}};Sp=class Sp extends Ge{constructor(e){super(e);this.name="WebSocketUnsupportedError"}};gl=class gl extends Ge{constructor(e){super(e);this.name="WebSocketError"}};la=class la extends Ge{status;constructor(e,t){super(e);this.status=t,this.name="HttpServerError"}};wn=class wn extends Ge{constructor(e){super(e);this.name="ProtocolVersionError"}};or=class or extends Ge{constructor(e){super(e);this.name="InternalError"}};ro=class ro extends Ge{constructor(e){super(e);this.name="MisuseError"}}});function Rr(e){if(typeof e==="string")return e;throw yl(e,"string")}function Zr(e){if(e===null||e===void 0)return;else if(typeof e==="string")return e;throw yl(e,"string or null")}function jo(e){if(typeof e==="number")return e;throw yl(e,"number")}function Gi(e){if(typeof e==="boolean")return e;throw yl(e,"boolean")}function vp(e){if(Array.isArray(e))return e;throw yl(e,"array")}function It(e){if(e!==null&&typeof e==="object"&&!Array.isArray(e))return e;throw yl(e,"object")}function xn(e,t){return vp(e).map((r)=>t(It(r)))}function yl(e,t){if(e===void 0)return new Pe(`Expected ${t}, but the property was missing`);let r=typeof e;if(e===null)r="null";else if(Array.isArray(e))r="array";return new Pe(`Expected ${t}, received ${r}`)}function ua(e,t){return t(It(e))}var bl=v(()=>{_t()});class $4{#e;#t;constructor(e){this.#e=e,this.#t=!1}begin(){this.#e.push("{"),this.#t=!0}end(){this.#e.push("}"),this.#t=!1}#r(e){if(this.#t)this.#e.push('"'),this.#t=!1;else this.#e.push(',"');this.#e.push(e),this.#e.push('":')}string(e,t){this.#r(e),this.#e.push(JSON.stringify(t))}stringRaw(e,t){this.#r(e),this.#e.push('"'),this.#e.push(t),this.#e.push('"')}number(e,t){this.#r(e),this.#e.push(""+t)}boolean(e,t){this.#r(e),this.#e.push(t?"true":"false")}object(e,t,r){this.#r(e),this.begin(),r(this,t),this.end()}arrayObjects(e,t,r){this.#r(e),this.#e.push("[");for(let o=0;o<t.length;++o){if(o!==0)this.#e.push(",");this.begin(),r(this,t[o]),this.end()}this.#e.push("]")}}function wp(e,t){let r=[],o=new $4(r);return o.begin(),t(o,e),o.end(),r.join("")}var da=0,xp=1,_p=2,O4=5;class C4{#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 P4{#e;#t;constructor(e){this.#e=e,this.#t=-1}setup(e){this.#t=e}#r(e){if(this.#t!==e)throw new Pe(`Expected wire type ${e}, got ${this.#t}`);this.#t=-1}bytes(){this.#r(_p);let e=this.#e.varint();return this.#e.bytes(e)}string(){return new TextDecoder().decode(this.bytes())}message(e){return Qi(this.bytes(),e)}int32(){return this.#r(da),this.#e.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#r(da),this.#e.varintBig()}sint64(){let e=this.uint64();return e>>1n^-(e&1n)}double(){return this.#r(xp),this.#e.double()}maybeSkip(){if(this.#t<0)return;else if(this.#t===da)this.#e.skipVarint();else if(this.#t===xp)this.#e.skip(8);else if(this.#t===_p){let e=this.#e.varint();this.#e.skip(e)}else if(this.#t===O4)this.#e.skip(4);else throw new Pe(`Unexpected wire type ${this.#t}`);this.#t=-1}}function Qi(e,t){let r=new C4(e),o=new P4(r),n=t.default();while(!r.eof()){let i=r.varint(),s=i>>3,a=i&7;o.setup(a);let l=t[s];if(l!==void 0){let u=l(o,n);if(u!==void 0)n=u}o.maybeSkip()}return n}var iT=v(()=>{_t()});class sT{#e;#t;#r;#n;constructor(){this.#e=new ArrayBuffer(256),this.#t=new Uint8Array(this.#e),this.#r=new DataView(this.#e),this.#n=0}#o(e){if(this.#n+e<=this.#e.byteLength)return;let t=this.#e.byteLength;while(t<this.#n+e)t*=2;let r=new ArrayBuffer(t),o=new Uint8Array(r),n=new DataView(r);o.set(new Uint8Array(this.#e,0,this.#n)),this.#e=r,this.#t=o,this.#r=n}#i(e){this.#o(5),e=0|e;do{let t=e&127;e>>>=7,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#a(e){this.#o(10),e=e&0xffffffffffffffffn;do{let t=Number(e&0x7fn);e>>=7n,t|=e?128:0,this.#t[this.#n++]=t}while(e)}#s(e,t){this.#i(e<<3|t)}bytes(e,t){this.#s(e,_p),this.#i(t.byteLength),this.#o(t.byteLength),this.#t.set(t,this.#n),this.#n+=t.byteLength}string(e,t){this.bytes(e,new TextEncoder().encode(t))}message(e,t,r){let o=new sT;r(o,t),this.bytes(e,o.data())}int32(e,t){this.#s(e,da),this.#i(t)}uint32(e,t){this.int32(e,t)}bool(e,t){this.int32(e,t?1:0)}sint64(e,t){this.#s(e,da),this.#a(t<<1n^t>>63n)}double(e,t){this.#s(e,xp),this.#o(8),this.#r.setFloat64(this.#n,t,!0),this.#n+=8}data(){return new Uint8Array(this.#e,0,this.#n)}}function Ep(e,t){let r=new sT;return t(r,e),r.data()}var z4=()=>{};var aT=v(()=>{bl();iT();z4()});class Yi{#e;#t;constructor(){this.#e=new Set,this.#t=new Set}alloc(){for(let t of this.#t){if(this.#t.delete(t),this.#e.add(t),!this.#e.has(this.#e.size-1))this.#t.add(this.#e.size-1);return t}let e=this.#e.size;return this.#e.add(e),e}free(e){if(!this.#e.delete(e))throw new or("Freeing an id that is not allocated");if(this.#t.delete(this.#e.size),e<this.#e.size)this.#t.add(e)}}var cT=v(()=>{_t()});function Je(e,t){throw new or(t)}var on=v(()=>{_t()});function Sl(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<gfe||e>yfe)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 lT(e,t){if(e===null)return null;else if(typeof e==="number")return e;else if(typeof e==="string")return e;else if(typeof e==="bigint")if(t==="number"){let r=Number(e);if(!Number.isSafeInteger(r))throw RangeError("Received integer which is too large to be safely represented as a JavaScript number");return r}else if(t==="bigint")return e;else if(t==="string")return""+e;else throw new ro("Invalid value for IntMode");else if(e instanceof Uint8Array)return e.slice().buffer;else if(e===void 0)throw new Pe("Received unrecognized type of Value");else throw Je(e,"Impossible type of Value")}var gfe,yfe=9223372036854775807n;var uT=v(()=>{_t();on();gfe=-9223372036854775808n});function pa(e){return{affectedRowCount:e.affectedRowCount,lastInsertRowid:e.lastInsertRowid,columnNames:e.cols.map((t)=>t.name),columnDecltypes:e.cols.map((t)=>t.decltype)}}function Py(e,t){let r=pa(e),o=e.rows.map((n)=>N4(r.columnNames,n,t));return{...r,rows:o}}function zy(e,t){let r=pa(e),o;if(e.rows.length>0)o=N4(r.columnNames,e.rows[0],t);return{...r,row:o}}function Ny(e,t){let r=pa(e),o;if(e.rows.length>0&&r.columnNames.length>0)o=lT(e.rows[0][0],t);return{...r,value:o}}function N4(e,t,r){let o={};Object.defineProperty(o,"length",{value:t.length});for(let n=0;n<t.length;++n){let i=lT(t[n],r);Object.defineProperty(o,n,{value:i});let s=e[n];if(s!==void 0&&!Object.hasOwn(o,s))Object.defineProperty(o,s,{value:i,enumerable:!0,configurable:!0,writable:!0})}return o}function Zo(e){return new bp(e.message,e)}var kp=v(()=>{_t();uT()});class fa{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}_getSqlId(e){if(this.#e!==e)throw new ro("Attempted to use SQL text opened with other object");else if(this.#r!==void 0)throw new xt("SQL text is closed",this.#r);return this.#t}close(){this._setClosed(new Ge("SQL text was manually closed"))}_setClosed(e){if(this.#r===void 0)this.#r=e,this.#e._closeSql(this.#t)}get closed(){return this.#r!==void 0}}function Ip(e,t){if(t instanceof fa)return{sqlId:t._getSqlId(e)};else return{sql:""+t}}var vl=v(()=>{_t()});class Xi{#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 Ap{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(Sl(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]=Sl(t),this}bindName(e,t){return this._namedArgs.set(e,Sl(t)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function Dy(e,t,r){let o,n=[],i=[];if(t instanceof Ap){o=t.sql,n=t._args;for(let[l,u]of t._namedArgs.entries())i.push({name:l,value:u})}else if(Array.isArray(t))if(o=t[0],Array.isArray(t[1]))n=t[1].map((l)=>Sl(l));else i=Object.entries(t[1]).map(([l,u])=>({name:l,value:Sl(u)}));else o=t;let{sql:s,sqlId:a}=Ip(e,o);return{sql:s,sqlId:a,args:n,namedArgs:i,wantRows:r}}var Ly=v(()=>{vl();uT()});class By{_stream;#e;_steps;#t;constructor(e,t){this._stream=e,this.#e=t,this._steps=[],this.#t=!1}step(){return new dT(this)}execute(){if(this.#t)throw new ro("This batch has already been executed");this.#t=!0;let e={steps:this._steps.map((t)=>t.proto)};if(this.#e)return Sfe(this._stream,this._steps,e);else return bfe(this._stream,this._steps,e)}}function bfe(e,t,r){return e._batch(r).then((o)=>{for(let n=0;n<t.length;++n){let i=o.stepResults.get(n),s=o.stepErrors.get(n);t[n].callback(i,s)}})}async function Sfe(e,t,r){let o=await e._openCursor(r);try{let n=0,i=void 0,s=[];for(;;){let a=await o.next();if(a===void 0)break;if(a.type==="step_begin"){if(a.step<n||a.step>=t.length)throw new Pe("Server produced StepBeginEntry for unexpected step");else if(i!==void 0)throw new Pe("Server produced StepBeginEntry before terminating previous step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0);n=a.step+1,i=a,s=[]}else if(a.type==="step_end"){if(i===void 0)throw new Pe("Server produced StepEndEntry but no step is active");let l={cols:i.cols,rows:s,affectedRowCount:a.affectedRowCount,lastInsertRowid:a.lastInsertRowid};t[i.step].callback(l,void 0),i=void 0,s=[]}else if(a.type==="step_error"){if(i===void 0){if(a.step>=t.length)throw new Pe("Server produced StepErrorEntry for unexpected step");for(let l=n;l<a.step;++l)t[l].callback(void 0,void 0)}else{if(a.step!==i.step)throw new Pe("Server produced StepErrorEntry for unexpected step");i=void 0,s=[]}t[a.step].callback(void 0,a.error),n=a.step+1}else if(a.type==="row"){if(i===void 0)throw new Pe("Server produced RowEntry but no step is active");s.push(a.row)}else if(a.type==="error")throw Zo(a.error);else if(a.type==="none")throw new Pe("Server produced unrecognized CursorEntry");else throw Je(a,"Impossible CursorEntry")}if(i!==void 0)throw new Pe("Server closed Cursor before terminating active step");for(let a=n;a<t.length;++a)t[a].callback(void 0,void 0)}finally{o.close()}}class dT{_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,Py)}queryRow(e){return this.#t(e,!0,zy)}queryValue(e){return this.#t(e,!0,Ny)}run(e){return this.#t(e,!1,pa)}#t(e,t,r){if(this._index!==void 0)throw new ro("This BatchStep has already been added to the batch");let o=Dy(this._batch._stream._sqlOwner(),e,t),n;if(this.#e.length===0)n=void 0;else if(this.#e.length===1)n=this.#e[0];else n={type:"and",conds:this.#e.slice()};let i={stmt:o,condition:n};return new Promise((s,a)=>{let l=(u,d)=>{if(u!==void 0&&d!==void 0)a(new Pe("Server returned both result and error"));else if(d!==void 0)a(Zo(d));else if(u!==void 0)s(r(u,this._batch._stream.intMode));else s(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:i,callback:l})})}}class dt{_batch;_proto;constructor(e,t){this._batch=e,this._proto=t}static ok(e){return new dt(e._batch,{type:"ok",step:D4(e)})}static error(e){return new dt(e._batch,{type:"error",step:D4(e)})}static not(e){return new dt(e._batch,{type:"not",cond:e._proto})}static and(e,t){for(let r of t)L4(e,r);return new dt(e,{type:"and",conds:t.map((r)=>r._proto)})}static or(e,t){for(let r of t)L4(e,r);return new dt(e,{type:"or",conds:t.map((r)=>r._proto)})}static isAutocommit(e){return e._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new dt(e,{type:"is_autocommit"})}}function D4(e){if(e._index===void 0)throw new ro("Cannot add a condition referencing a step that has not been added to the batch");return e._index}function L4(e,t){if(t._batch!==e)throw new ro("Cannot mix BatchCond objects for different Batch objects")}var pT=v(()=>{_t();kp();Ly();on()});function B4(e){return{paramNames:e.params.map((t)=>t.name),columns:e.cols,isExplain:e.isExplain,isReadonly:e.isReadonly}}class wl{constructor(e){this.intMode=e}query(e){return this.#e(e,!0,Py)}queryRow(e){return this.#e(e,!0,zy)}queryValue(e){return this.#e(e,!0,Ny)}run(e){return this.#e(e,!1,pa)}#e(e,t,r){let o=Dy(this._sqlOwner(),e,t);return this._execute(o).then((n)=>r(n,this.intMode))}batch(e=!1){return new By(this,e)}describe(e){let t=Ip(this._sqlOwner(),e);return this._describe(t).then(B4)}sequence(e){let t=Ip(this._sqlOwner(),e);return this._sequence(t)}intMode}var jy=v(()=>{pT();kp();vl();Ly()});class Rp{}var vfe=1000,wfe=10,fT;var j4=v(()=>{_t();fT=class fT extends Rp{#e;#t;#r;#n;#o;#i;#a;constructor(e,t,r){super();this.#e=e,this.#t=t,this.#r=r,this.#n=new Xi,this.#o=new Xi,this.#i=void 0,this.#a=!1}async next(){for(;;){if(this.#i!==void 0)throw new xt("Cursor is closed",this.#i);while(!this.#a&&this.#o.length<wfe)this.#o.push(this.#s());let e=this.#n.shift();if(this.#a||e!==void 0)return e;await this.#o.shift().then((t)=>{if(t===void 0)return;for(let r of t.entries)this.#n.push(r);this.#a||=t.done})}}#s(){return this.#t._sendCursorRequest(this,{type:"fetch_cursor",cursorId:this.#r,maxCount:vfe}).then((e)=>e,(e)=>{this._setClosed(e);return})}_setClosed(e){if(this.#i!==void 0)return;this.#i=e,this.#t._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#r}).catch(()=>{return}),this.#t._cursorClosed(this)}close(){this._setClosed(new Ge("Cursor was manually closed"))}get closed(){return this.#i!==void 0}}});var Tp;var mT=v(()=>{_t();jy();j4();Tp=class Tp extends wl{#e;#t;#r;#n;#o;#i;static open(e){let t=e._streamIdAlloc.alloc(),r=new Tp(e,t),o=()=>{return},n=(s)=>r.#l(s),i={type:"open_stream",streamId:t};return e._sendRequest(i,{responseCallback:o,errorCallback:n}),r}constructor(e,t){super(e.intMode);this.#e=e,this.#t=t,this.#r=new Xi,this.#n=void 0,this.#o=!1,this.#i=void 0}client(){return this.#e}_sqlOwner(){return this.#e}_execute(e){return this.#a({type:"execute",streamId:this.#t,stmt:e}).then((t)=>t.result)}_batch(e){return this.#a({type:"batch",streamId:this.#t,batch:e}).then((t)=>t.result)}_describe(e){return this.#e._ensureVersion(2,"describe()"),this.#a({type:"describe",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#e._ensureVersion(2,"sequence()"),this.#a({type:"sequence",streamId:this.#t,sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#a({type:"get_autocommit",streamId:this.#t}).then((e)=>e.isAutocommit)}#a(e){return new Promise((t,r)=>{this.#s({type:"request",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return this.#e._ensureVersion(3,"cursor"),new Promise((t,r)=>{this.#s({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_sendCursorRequest(e,t){if(e!==this.#n)throw new or("Cursor not associated with the stream attempted to execute a request");return new Promise((r,o)=>{if(this.#i!==void 0)o(new xt("Stream is closed",this.#i));else this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})})}_cursorClosed(e){if(e!==this.#n)throw new or("Cursor was closed, but it was not associated with the stream");this.#n=void 0,this.#c()}#s(e){if(this.#i!==void 0)e.errorCallback(new xt("Stream is closed",this.#i));else if(this.#o)e.errorCallback(new xt("Stream is closing",void 0));else this.#r.push(e),this.#c()}#c(){for(;;){let e=this.#r.first();if(e===void 0&&this.#n===void 0&&this.#o){this.#l(new Ge("Stream was gracefully closed"));break}else if(e?.type==="request"&&this.#n===void 0){let{request:t,responseCallback:r,errorCallback:o}=e;this.#r.shift(),this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}else if(e?.type==="cursor"&&this.#n===void 0){let{batch:t,cursorCallback:r}=e;this.#r.shift();let o=this.#e._cursorIdAlloc.alloc(),n=new fT(this.#e,this,o),i={type:"open_cursor",streamId:this.#t,cursorId:o,batch:t},s=()=>{return},a=(l)=>n._setClosed(l);this.#e._sendRequest(i,{responseCallback:s,errorCallback:a}),this.#n=n,r(n)}else break}}#l(e){if(this.#i!==void 0)return;if(this.#i=e,this.#n!==void 0)this.#n._setClosed(e);for(;;){let n=this.#r.shift();if(n!==void 0)n.errorCallback(e);else break}let t={type:"close_stream",streamId:this.#t},r=()=>this.#e._streamIdAlloc.free(this.#t),o=()=>{return};this.#e._sendRequest(t,{responseCallback:r,errorCallback:o})}close(){this.#l(new Ge("Stream was manually closed"))}closeGracefully(){this.#o=!0,this.#c()}get closed(){return this.#i!==void 0||this.#o}}});function $p(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,Z4),e.arrayObjects("named_args",t.namedArgs,xfe),e.boolean("want_rows",t.wantRows)}function xfe(e,t){e.string("name",t.name),e.object("value",t.value,Z4)}function xl(e,t){e.arrayObjects("steps",t.steps,_fe)}function _fe(e,t){if(t.condition!==void 0)e.object("condition",t.condition,hT);e.object("stmt",t.stmt,$p)}function hT(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,hT);else if(t.type==="and"||t.type==="or")e.arrayObjects("conds",t.conds,hT);else if(t.type==="is_autocommit");else throw Je(t,"Impossible type of BatchCond")}function Z4(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",ul.fromUint8Array(t));else if(t===void 0);else throw Je(t,"Impossible type of Value")}var gT=v(()=>{Ty();on()});function U4(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,Efe);else throw Je(t,"Impossible type of ClientMsg")}function Efe(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,$p);else if(t.type==="batch")e.number("stream_id",t.streamId),e.object("batch",t.batch,xl);else if(t.type==="open_cursor")e.number("stream_id",t.streamId),e.number("cursor_id",t.cursorId),e.object("batch",t.batch,xl);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 Je(t,"Impossible type of Request")}var M4=v(()=>{gT();on()});function Op(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,F4);for(let r of t.namedArgs)e.message(4,r,kfe);e.bool(5,t.wantRows)}function kfe(e,t){e.string(1,t.name),e.message(2,t.value,F4)}function _l(e,t){for(let r of t.steps)e.message(1,r,Ife)}function Ife(e,t){if(t.condition!==void 0)e.message(1,t.condition,yT);e.message(2,t.stmt,Op)}function yT(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,yT);else if(t.type==="and")e.message(4,t.conds,q4);else if(t.type==="or")e.message(5,t.conds,q4);else if(t.type==="is_autocommit")e.message(6,void 0,K4);else throw Je(t,"Impossible type of BatchCond")}function q4(e,t){for(let r of t)e.message(1,r,yT)}function F4(e,t){if(t===null)e.message(1,void 0,K4);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 Je(t,"Impossible type of Value")}function K4(e,t){}var bT=v(()=>{on()});function J4(e,t){if(t.type==="hello")e.message(1,t,Afe);else if(t.type==="request")e.message(2,t,Rfe);else throw Je(t,"Impossible type of ClientMsg")}function Afe(e,t){if(t.jwt!==void 0)e.string(1,t.jwt)}function Rfe(e,t){e.int32(1,t.requestId);let r=t.request;if(r.type==="open_stream")e.message(2,r,Tfe);else if(r.type==="close_stream")e.message(3,r,$fe);else if(r.type==="execute")e.message(4,r,Ofe);else if(r.type==="batch")e.message(5,r,Cfe);else if(r.type==="open_cursor")e.message(6,r,Pfe);else if(r.type==="close_cursor")e.message(7,r,zfe);else if(r.type==="fetch_cursor")e.message(8,r,Nfe);else if(r.type==="sequence")e.message(9,r,Dfe);else if(r.type==="describe")e.message(10,r,Lfe);else if(r.type==="store_sql")e.message(11,r,Bfe);else if(r.type==="close_sql")e.message(12,r,jfe);else if(r.type==="get_autocommit")e.message(13,r,Zfe);else throw Je(r,"Impossible type of Request")}function Tfe(e,t){e.int32(1,t.streamId)}function $fe(e,t){e.int32(1,t.streamId)}function Ofe(e,t){e.int32(1,t.streamId),e.message(2,t.stmt,Op)}function Cfe(e,t){e.int32(1,t.streamId),e.message(2,t.batch,_l)}function Pfe(e,t){e.int32(1,t.streamId),e.int32(2,t.cursorId),e.message(3,t.batch,_l)}function zfe(e,t){e.int32(1,t.cursorId)}function Nfe(e,t){e.int32(1,t.cursorId),e.uint32(2,t.maxCount)}function Dfe(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 Lfe(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 Bfe(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function jfe(e,t){e.int32(1,t.sqlId)}function Zfe(e,t){e.int32(1,t.streamId)}var H4=v(()=>{bT();on()});function es(e){let t=Rr(e.message),r=Zr(e.code);return{message:t,code:r}}function Cp(e){let t=xn(e.cols,V4),r=vp(e.rows).map((s)=>xn(s,W4)),o=jo(e.affected_row_count),n=Zr(e.last_insert_rowid),i=n!==void 0?BigInt(n):void 0;return{cols:t,rows:r,affectedRowCount:o,lastInsertRowid:i}}function V4(e){let t=Zr(e.name),r=Zr(e.decltype);return{name:t,decltype:r}}function Zy(e){let t=new Map;vp(e.step_results).forEach((o,n)=>{if(o!==null)t.set(n,Cp(It(o)))});let r=new Map;return vp(e.step_errors).forEach((o,n)=>{if(o!==null)r.set(n,es(It(o)))}),{stepResults:t,stepErrors:r}}function Uy(e){let t=Rr(e.type);if(t==="step_begin"){let r=jo(e.step),o=xn(e.cols,V4);return{type:"step_begin",step:r,cols:o}}else if(t==="step_end"){let r=jo(e.affected_row_count),o=Zr(e.last_insert_rowid),n=o!==void 0?BigInt(o):void 0;return{type:"step_end",affectedRowCount:r,lastInsertRowid:n}}else if(t==="step_error"){let r=jo(e.step),o=es(It(e.error));return{type:"step_error",step:r,error:o}}else if(t==="row")return{type:"row",row:xn(e.row,W4)};else if(t==="error")return{type:"error",error:es(It(e.error))};else throw new Pe("Unexpected type of CursorEntry")}function My(e){let t=xn(e.params,Ufe),r=xn(e.cols,Mfe),o=Gi(e.is_explain),n=Gi(e.is_readonly);return{params:t,cols:r,isExplain:o,isReadonly:n}}function Ufe(e){return{name:Zr(e.name)}}function Mfe(e){let t=Rr(e.name),r=Zr(e.decltype);return{name:t,decltype:r}}function W4(e){let t=Rr(e.type);if(t==="null")return null;else if(t==="integer"){let r=Rr(e.value);return BigInt(r)}else if(t==="float")return jo(e.value);else if(t==="text")return Rr(e.value);else if(t==="blob")return ul.toUint8Array(Rr(e.base64));else throw new Pe("Unexpected type of Value")}var qy=v(()=>{Ty();_t();bl()});function G4(e){let t=Rr(e.type);if(t==="hello_ok")return{type:"hello_ok"};else if(t==="hello_error")return{type:"hello_error",error:es(It(e.error))};else if(t==="response_ok"){let r=jo(e.request_id),o=qfe(It(e.response));return{type:"response_ok",requestId:r,response:o}}else if(t==="response_error"){let r=jo(e.request_id),o=es(It(e.error));return{type:"response_error",requestId:r,error:o}}else throw new Pe("Unexpected type of ServerMsg")}function qfe(e){let t=Rr(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:Cp(It(e.result))};else if(t==="batch")return{type:"batch",result:Zy(It(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=xn(e.entries,Uy),o=Gi(e.done);return{type:"fetch_cursor",entries:r,done:o}}else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:My(It(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:Gi(e.is_autocommit)};else throw new Pe("Unexpected type of Response")}var Q4=v(()=>{_t();bl();qy()});var sn,ts,Y4,X4,El,Ffe,Kfe,Fy,Jfe,Hfe,Vfe,kl,Wfe,Gfe,Qfe;var Ky=v(()=>{sn={default(){return{message:"",code:void 0}},1(e,t){t.message=e.string()},2(e,t){t.code=e.string()}},ts={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.cols.push(e.message(Y4))},2(e,t){t.rows.push(e.message(X4))},3(e,t){t.affectedRowCount=Number(e.uint64())},4(e,t){t.lastInsertRowid=e.sint64()}},Y4={default(){return{name:void 0,decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},X4={default(){return[]},1(e,t){t.push(e.message(Qfe))}},El={default(){return{stepResults:new Map,stepErrors:new Map}},1(e,t){let[r,o]=e.message(Ffe);t.stepResults.set(r,o)},2(e,t){let[r,o]=e.message(Kfe);t.stepErrors.set(r,o)}},Ffe={default(){return[0,ts.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(ts)}},Kfe={default(){return[0,sn.default()]},1(e,t){t[0]=e.uint32()},2(e,t){t[1]=e.message(sn)}},Fy={default(){return{type:"none"}},1(e){return e.message(Jfe)},2(e){return e.message(Hfe)},3(e){return e.message(Vfe)},4(e){return{type:"row",row:e.message(X4)}},5(e){return{type:"error",error:e.message(sn)}}},Jfe={default(){return{type:"step_begin",step:0,cols:[]}},1(e,t){t.step=e.uint32()},2(e,t){t.cols.push(e.message(Y4))}},Hfe={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(e,t){t.affectedRowCount=e.uint32()},2(e,t){t.lastInsertRowid=e.uint64()}},Vfe={default(){return{type:"step_error",step:0,error:sn.default()}},1(e,t){t.step=e.uint32()},2(e,t){t.error=e.message(sn)}},kl={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(e,t){t.params.push(e.message(Wfe))},2(e,t){t.cols.push(e.message(Gfe))},3(e,t){t.isExplain=e.bool()},4(e,t){t.isReadonly=e.bool()}},Wfe={default(){return{name:void 0}},1(e,t){t.name=e.string()}},Gfe={default(){return{name:"",decltype:void 0}},1(e,t){t.name=e.string()},2(e,t){t.decltype=e.string()}},Qfe={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 eF,Yfe,Xfe,eme,tme,rme,nme,ome,ime;var tF=v(()=>{Ky();eF={default(){return{type:"none"}},1(e){return{type:"hello_ok"}},2(e){return e.message(Yfe)},3(e){return e.message(eme)},4(e){return e.message(Xfe)}},Yfe={default(){return{type:"hello_error",error:sn.default()}},1(e,t){t.error=e.message(sn)}},Xfe={default(){return{type:"response_error",requestId:0,error:sn.default()}},1(e,t){t.requestId=e.int32()},2(e,t){t.error=e.message(sn)}},eme={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(tme)},5(e,t){t.response=e.message(rme)},6(e,t){t.response={type:"open_cursor"}},7(e,t){t.response={type:"close_cursor"}},8(e,t){t.response=e.message(nme)},9(e,t){t.response={type:"sequence"}},10(e,t){t.response=e.message(ome)},11(e,t){t.response={type:"store_sql"}},12(e,t){t.response={type:"close_sql"}},13(e,t){t.response=e.message(ime)}},tme={default(){return{type:"execute",result:ts.default()}},1(e,t){t.result=e.message(ts)}},rme={default(){return{type:"batch",result:El.default()}},1(e,t){t.result=e.message(El)}},nme={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(e,t){t.entries.push(e.message(Fy))},2(e,t){t.done=e.bool()}},ome={default(){return{type:"describe",result:kl.default()}},1(e,t){t.result=e.message(kl)}},ime={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}}});var rF,ST,Jy;var Hy=v(()=>{aT();_t();cT();kp();vl();on();mT();M4();H4();Q4();tF();rF=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),ST=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);Jy=class Jy extends hl{#e;#t;#r;#n;#o;#i;#a;#s;#c;_streamIdAlloc;_cursorIdAlloc;#l;constructor(e,t){super();this.#e=e,this.#t=[],this.#r=!1,this.#n=void 0,this.#o=!1,this.#i=void 0,this.#a=!1,this.#s=new Map,this.#c=new Yi,this._streamIdAlloc=new Yi,this._cursorIdAlloc=new Yi,this.#l=new Yi,this.#e.binaryType="arraybuffer",this.#e.addEventListener("open",()=>this.#p()),this.#e.addEventListener("close",(r)=>this.#g(r)),this.#e.addEventListener("error",(r)=>this.#f(r)),this.#e.addEventListener("message",(r)=>this.#y(r)),this.#d({type:"hello",jwt:t})}#d(e){if(this.#n!==void 0)throw new or("Trying to send a message on a closed client");if(this.#r)this.#m(e);else{let t=()=>this.#m(e),r=()=>{return};this.#t.push({openCallback:t,errorCallback:r})}}#p(){let e=this.#e.protocol;if(e===void 0){this.#u(new Ge("The `WebSocket.protocol` property is undefined. This most likely means that the WebSocket implementation provided by the environment is broken. If you are using Miniflare 2, please update to Miniflare 3, which fixes this problem."));return}else if(e==="")this.#i={version:1,encoding:"json"};else if(this.#i=ST.get(e),this.#i===void 0){this.#u(new Pe(`Unrecognized WebSocket subprotocol: ${JSON.stringify(e)}`));return}for(let t of this.#t)t.openCallback();this.#t.length=0,this.#r=!0}#m(e){let t=this.#i.encoding;if(t==="json"){let r=wp(e,U4);this.#e.send(r)}else if(t==="protobuf"){let r=Ep(e,J4);this.#e.send(r)}else throw Je(t,"Impossible encoding")}getVersion(){return new Promise((e,t)=>{if(this.#a=!0,this.#n!==void 0)t(this.#n);else if(!this.#r){let r=()=>e(this.#i.version);this.#t.push({openCallback:r,errorCallback:t})}else e(this.#i.version)})}_ensureVersion(e,t){if(this.#i===void 0||!this.#a)throw new wn(`${t} is supported only on protocol version ${e} and higher, but the version supported by the WebSocket server is not yet known. Use Client.getVersion() to wait until the version is available.`);else if(this.#i.version<e)throw new wn(`${t} is supported on protocol version ${e} and higher, but the WebSocket server only supports version ${this.#i.version}`)}_sendRequest(e,t){if(this.#n!==void 0){t.errorCallback(new xt("Client is closed",this.#n));return}let r=this.#c.alloc();this.#s.set(r,{...t,type:e.type}),this.#d({type:"request",requestId:r,request:e})}#f(e){let r=e.message??"WebSocket was closed due to an error";this.#u(new gl(r))}#g(e){let t=`WebSocket was closed with code ${e.code}`;if(e.reason)t+=`: ${e.reason}`;this.#u(new gl(t))}#u(e){if(this.#n!==void 0)return;this.#n=e;for(let t of this.#t)t.errorCallback(e);this.#t.length=0;for(let[t,r]of this.#s.entries())r.errorCallback(e),this.#c.free(t);this.#s.clear(),this.#e.close()}#y(e){if(this.#n!==void 0)return;try{let t,r=this.#i.encoding;if(r==="json"){if(typeof e.data!=="string"){this.#e.close(3003,"Only text messages are accepted with JSON encoding"),this.#u(new Pe("Received non-text message from server with JSON encoding"));return}t=ua(JSON.parse(e.data),G4)}else if(r==="protobuf"){if(!(e.data instanceof ArrayBuffer)){this.#e.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#u(new Pe("Received non-binary message from server with Protobuf encoding"));return}t=Qi(new Uint8Array(e.data),eF)}else throw Je(r,"Impossible encoding");this.#b(t)}catch(t){this.#e.close(3007,"Could not handle message"),this.#u(t)}}#b(e){if(e.type==="none")throw new Pe("Received an unrecognized ServerMsg");else if(e.type==="hello_ok"||e.type==="hello_error"){if(this.#o)throw new Pe("Received a duplicated hello response");if(this.#o=!0,e.type==="hello_error")throw Zo(e.error);return}else if(!this.#o)throw new Pe("Received a non-hello message before a hello response");if(e.type==="response_ok"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected OK response");this.#c.free(t);try{if(r.type!==e.response.type)throw console.dir({responseState:r,msg:e}),new Pe("Received unexpected type of response");r.responseCallback(e.response)}catch(o){throw r.errorCallback(o),o}}else if(e.type==="response_error"){let t=e.requestId,r=this.#s.get(t);if(this.#s.delete(t),r===void 0)throw new Pe("Received unexpected error response");this.#c.free(t),r.errorCallback(Zo(e.error))}else throw Je(e,"Impossible ServerMsg type")}openStream(){return Tp.open(this)}storeSql(e){this._ensureVersion(2,"storeSql()");let t=this.#l.alloc(),r=new fa(this,t),o=()=>{return},n=(s)=>r._setClosed(s),i={type:"store_sql",sqlId:t,sql:e};return this._sendRequest(i,{responseCallback:o,errorCallback:n}),r}_closeSql(e){if(this.#n!==void 0)return;let t=()=>this.#l.free(e),r=(n)=>this.#u(n),o={type:"close_sql",sqlId:e};this._sendRequest(o,{responseCallback:t,errorCallback:r})}close(){this.#u(new Ge("Client was manually closed"))}get closed(){return this.#n!==void 0}}});var ma;var nF=v(()=>{if(typeof queueMicrotask<"u")ma=queueMicrotask;else{let e=Promise.resolve();ma=(t)=>{e.then(t)}}});class vT{#e;#t;#r;constructor(e){this.#e=new Uint8Array(new ArrayBuffer(e)),this.#t=0,this.#r=0}get length(){return this.#r-this.#t}data(){return this.#e.slice(this.#t,this.#r)}push(e){this.#n(e.byteLength),this.#e.set(e,this.#r),this.#r+=e.byteLength}#n(e){if(this.#r+e<=this.#e.byteLength)return;let t=this.#r-this.#t;if(t+e<=this.#e.byteLength&&2*this.#r>=this.#e.byteLength)this.#e.copyWithin(0,this.#t,this.#r);else{let r=this.#e.byteLength;do r*=2;while(t+e>r);let o=new Uint8Array(new ArrayBuffer(r));o.set(this.#e.slice(this.#t,this.#r),0),this.#e=o}this.#r=t,this.#t=0}shift(e){this.#t+=e}}function oF(e){let t=Zr(e.baton),r=Zr(e.base_url),o=xn(e.results,sme);return{baton:t,baseUrl:r,results:o}}function sme(e){let t=Rr(e.type);if(t==="ok")return{type:"ok",response:ame(It(e.response))};else if(t==="error")return{type:"error",error:es(It(e.error))};else throw new Pe("Unexpected type of StreamResult")}function ame(e){let t=Rr(e.type);if(t==="close")return{type:"close"};else if(t==="execute")return{type:"execute",result:Cp(It(e.result))};else if(t==="batch")return{type:"batch",result:Zy(It(e.result))};else if(t==="sequence")return{type:"sequence"};else if(t==="describe")return{type:"describe",result:My(It(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:Gi(e.is_autocommit)};else throw new Pe("Unexpected type of StreamResponse")}function iF(e){let t=Zr(e.baton),r=Zr(e.base_url);return{baton:t,baseUrl:r}}var wT=v(()=>{_t();bl();qy()});var sF,cme,lme,ume,dme,pme,fme,aF;var xT=v(()=>{Ky();sF={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(cme))}},cme={default(){return{type:"none"}},1(e){return{type:"ok",response:e.message(lme)}},2(e){return{type:"error",error:e.message(sn)}}},lme={default(){return{type:"none"}},1(e){return{type:"close"}},2(e){return e.message(ume)},3(e){return e.message(dme)},4(e){return{type:"sequence"}},5(e){return e.message(pme)},6(e){return{type:"store_sql"}},7(e){return{type:"close_sql"}},8(e){return e.message(fme)}},ume={default(){return{type:"execute",result:ts.default()}},1(e,t){t.result=e.message(ts)}},dme={default(){return{type:"batch",result:El.default()}},1(e,t){t.result=e.message(El)}},pme={default(){return{type:"describe",result:kl.default()}},1(e,t){t.result=e.message(kl)}},fme={default(){return{type:"get_autocommit",isAutocommit:!1}},1(e,t){t.isAutocommit=e.bool()}},aF={default(){return{baton:void 0,baseUrl:void 0}},1(e,t){t.baton=e.string()},2(e,t){t.baseUrl=e.string()}}});var _T;var cF=v(()=>{bl();iT();_t();on();wT();xT();qy();Ky();_T=class _T extends Rp{#e;#t;#r;#n;#o;#i;constructor(e,t){super();this.#e=e,this.#t=t,this.#r=void 0,this.#n=new vT(16384),this.#o=void 0,this.#i=!1}async open(e){if(e.body===null)throw new Pe("No response body for cursor request");this.#r=e.body[Symbol.asyncIterator]();let t=await this.#a(iF,aF);if(t===void 0)throw new Pe("Empty response to cursor request");return t}next(){return this.#a(Uy,Fy)}close(){this._setClosed(new Ge("Cursor was manually closed"))}_setClosed(e){if(this.#o!==void 0)return;if(this.#o=e,this.#e._cursorClosed(this),this.#r!==void 0)this.#r.return()}get closed(){return this.#o!==void 0}async#a(e,t){for(;;){if(this.#i)return;else if(this.#o!==void 0)throw new xt("Cursor is closed",this.#o);if(this.#t==="json"){let n=this.#s();if(n!==void 0){let i=new TextDecoder().decode(n),s=JSON.parse(i);return ua(s,e)}}else if(this.#t==="protobuf"){let n=this.#c();if(n!==void 0)return Qi(n,t)}else throw Je(this.#t,"Impossible encoding");if(this.#r===void 0)throw new or("Attempted to read from HTTP cursor before it was opened");let{value:r,done:o}=await this.#r.next();if(o&&this.#n.length===0)this.#i=!0;else if(o)throw new Pe("Unexpected end of cursor stream");else this.#n.push(r)}}#s(){let e=this.#n.data(),t=10,r=e.indexOf(10);if(r<0)return;let o=e.slice(0,r);return this.#n.shift(r+1),o}#c(){let e=this.#n.data(),t=0,r=0;for(;;){if(r>=e.byteLength)return;let n=e[r];if(t|=(n&127)<<7*r,r+=1,!(n&128))break}if(e.byteLength<r+t)return;let o=e.slice(r,r+t);return this.#n.shift(r+t),o}}});function lF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.arrayObjects("requests",t.requests,mme)}function mme(e,t){if(e.stringRaw("type",t.type),t.type==="close");else if(t.type==="execute")e.object("stmt",t.stmt,$p);else if(t.type==="batch")e.object("batch",t.batch,xl);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 Je(t,"Impossible type of StreamRequest")}function uF(e,t){if(t.baton!==void 0)e.string("baton",t.baton);e.object("batch",t.batch,xl)}var ET=v(()=>{gT();on()});function dF(e,t){if(t.baton!==void 0)e.string(1,t.baton);for(let r of t.requests)e.message(2,r,hme)}function hme(e,t){if(t.type==="close")e.message(1,t,gme);else if(t.type==="execute")e.message(2,t,yme);else if(t.type==="batch")e.message(3,t,bme);else if(t.type==="sequence")e.message(4,t,Sme);else if(t.type==="describe")e.message(5,t,vme);else if(t.type==="store_sql")e.message(6,t,wme);else if(t.type==="close_sql")e.message(7,t,xme);else if(t.type==="get_autocommit")e.message(8,t,_me);else throw Je(t,"Impossible type of StreamRequest")}function gme(e,t){}function yme(e,t){e.message(1,t.stmt,Op)}function bme(e,t){e.message(1,t.batch,_l)}function Sme(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function vme(e,t){if(t.sql!==void 0)e.string(1,t.sql);if(t.sqlId!==void 0)e.int32(2,t.sqlId)}function wme(e,t){e.int32(1,t.sqlId),e.string(2,t.sql)}function xme(e,t){e.int32(1,t.sqlId)}function _me(e,t){}function pF(e,t){if(t.baton!==void 0)e.string(1,t.baton);e.message(2,t.batch,_l)}var kT=v(()=>{bT();on()});function Eme(e,t){if(t.results.length!==e.length)throw new Pe("Server returned unexpected number of pipeline results");for(let r=0;r<e.length;++r){let o=t.results[r],n=e[r];if(o.type==="ok"){if(o.response.type!==n.request.type)throw new Pe("Received unexpected type of response");n.responseCallback(o.response)}else if(o.type==="error")n.errorCallback(Zo(o.error));else if(o.type==="none")throw new Pe("Received unrecognized type of StreamResult");else throw Je(o,"Received impossible type of StreamResult")}}async function kme(e,t){if(t==="json"){let r=await e.json();return ua(r,oF)}if(t==="protobuf"){let r=await e.arrayBuffer();return Qi(new Uint8Array(r),sF)}throw await e.body?.cancel(),Je(t,"Impossible encoding")}async function Ime(e){let t=e.headers.get("content-type")??"text/plain",r=`Server returned HTTP status ${e.status}`;if(t==="application/json"){let o=await e.json();if("message"in o)return Zo(o);return new la(r,e.status)}if(t==="text/plain"){let o=(await e.text()).trim();if(o!=="")r+=`: ${o}`;return new la(r,e.status)}return await e.body?.cancel(),new la(r,e.status)}var Vy;var IT=v(()=>{_t();aT();cT();nF();kp();vl();jy();on();cF();ET();kT();ET();kT();wT();xT();Vy=class Vy extends wl{#e;#t;#r;#n;#o;#i;#a;#s;#c;#l;#d;#p;#m;constructor(e,t,r,o,n){super(e.intMode);this.#e=e,this.#t=t.toString(),this.#r=r,this.#n=o,this.#o=n,this.#i=void 0,this.#a=new Xi,this.#s=!1,this.#l=!1,this.#d=!1,this.#p=void 0,this.#m=new Yi}client(){return this.#e}_sqlOwner(){return this}storeSql(e){let t=this.#m.alloc();return this.#f({type:"store_sql",sqlId:t,sql:e}).then(()=>{return},(r)=>this._setClosed(r)),new fa(this,t)}_closeSql(e){if(this.#p!==void 0)return;this.#f({type:"close_sql",sqlId:e}).then(()=>this.#m.free(e),(t)=>this._setClosed(t))}_execute(e){return this.#f({type:"execute",stmt:e}).then((t)=>t.result)}_batch(e){return this.#f({type:"batch",batch:e}).then((t)=>t.result)}_describe(e){return this.#f({type:"describe",sql:e.sql,sqlId:e.sqlId}).then((t)=>t.result)}_sequence(e){return this.#f({type:"sequence",sql:e.sql,sqlId:e.sqlId}).then((t)=>{return})}getAutocommit(){return this.#e._ensureVersion(3,"getAutocommit()"),this.#f({type:"get_autocommit"}).then((e)=>e.isAutocommit)}#f(e){return new Promise((t,r)=>{this.#g({type:"pipeline",request:e,responseCallback:t,errorCallback:r})})}_openCursor(e){return new Promise((t,r)=>{this.#g({type:"cursor",batch:e,cursorCallback:t,errorCallback:r})})}_cursorClosed(e){if(e!==this.#c)throw new or("Cursor was closed, but it was not associated with the stream");this.#c=void 0,ma(()=>this.#u())}close(){this._setClosed(new Ge("Stream was manually closed"))}closeGracefully(){this.#l=!0,ma(()=>this.#u())}get closed(){return this.#p!==void 0||this.#l}_setClosed(e){if(this.#p!==void 0)return;if(this.#p=e,this.#c!==void 0)this.#c._setClosed(e);this.#e._streamClosed(this);for(;;){let t=this.#a.shift();if(t!==void 0)t.errorCallback(e);else break}if((this.#i!==void 0||this.#s)&&!this.#d)this.#a.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0,ma(()=>this.#u())}#g(e){if(this.#p!==void 0)throw new xt("Stream is closed",this.#p);else if(this.#l)throw new xt("Stream is closing",void 0);else this.#a.push(e),ma(()=>this.#u())}#u(){if(this.#s||this.#c!==void 0)return;if(this.#l&&this.#a.length===0){this._setClosed(new Ge("Stream was gracefully closed"));return}let e=this.#e._endpoint;if(e===void 0){this.#e._endpointPromise.then(()=>this.#u(),(r)=>this._setClosed(r));return}let t=this.#a.shift();if(t===void 0)return;else if(t.type==="pipeline"){let r=[t];for(;;){let o=this.#a.first();if(o!==void 0&&o.type==="pipeline")r.push(o),this.#a.shift();else if(o===void 0&&this.#l&&!this.#d){r.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#d=!0;break}else break}this.#y(e,r)}else if(t.type==="cursor")this.#b(e,t);else throw Je(t,"Impossible type of QueueEntry")}#y(e,t){this.#h(()=>this.#S(t,e),(r)=>kme(r,e.encoding),(r)=>r.baton,(r)=>r.baseUrl,(r)=>Eme(t,r),(r)=>t.forEach((o)=>o.errorCallback(r)))}#b(e,t){let r=new _T(this,e.encoding);this.#c=r,this.#h(()=>this.#v(t,e),(o)=>r.open(o),(o)=>o.baton,(o)=>o.baseUrl,(o)=>t.cursorCallback(r),(o)=>t.errorCallback(o))}#h(e,t,r,o,n,i){let s;try{let a=e(),l=this.#n;s=l(a)}catch(a){s=Promise.reject(a)}this.#s=!0,s.then((a)=>{if(!a.ok)return Ime(a).then((l)=>{throw l});return t(a)}).then((a)=>{this.#i=r(a),this.#t=o(a)??this.#t,n(a)}).catch((a)=>{this._setClosed(a),i(a)}).finally(()=>{this.#s=!1,this.#u()})}#S(e,t){return this.#w(new URL(t.pipelinePath,this.#t),{baton:this.#i,requests:e.map((r)=>r.request)},t.encoding,lF,dF)}#v(e,t){if(t.cursorPath===void 0)throw new wn(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${t.version}.`);return this.#w(new URL(t.cursorPath,this.#t),{baton:this.#i,batch:e.batch},t.encoding,uF,pF)}#w(e,t,r,o,n){let i,s;if(r==="json")i=wp(t,o),s="application/json";else if(r==="protobuf")i=Ep(t,n),s="application/x-protobuf";else throw Je(r,"Impossible encoding");let a=new Headers;if(a.set("content-type",s),this.#r!==void 0)a.set("authorization",`Bearer ${this.#r}`);if(this.#o!==void 0)a.set("x-turso-encryption-key",this.#o);return new Request(e.toString(),{method:"POST",headers:a,body:i})}}});async function Rme(e,t){let r=e;for(let o of Ame){let n=new URL(o.versionPath,t),i=new Request(n.toString(),{method:"GET"}),s=await r(i);if(await s.arrayBuffer(),s.ok)return o}return AT}var Ame,AT,Wy;var RT=v(()=>{_t();IT();Ame=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],AT={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};Wy=class Wy extends hl{#e;#t;#r;#n;#o;#i;_endpointPromise;_endpoint;constructor(e,t,r,o,n=2){super();if(this.#e=e,this.#t=t,this.#r=r??globalThis.fetch,this.#n=o,this.#o=void 0,this.#i=new Set,n==3)this._endpointPromise=Rme(this.#r,this.#e),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i));else this._endpointPromise=Promise.resolve(AT),this._endpointPromise.then((i)=>this._endpoint=i,(i)=>this.#a(i))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(e,t){if(e<=AT.version)return;else if(this._endpoint===void 0)throw new wn(`${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 wn(`${t} is supported only on protocol version ${e} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#o!==void 0)throw new xt("Client is closed",this.#o);let e=new Vy(this,this.#e,this.#t,this.#r,this.#n);return this.#i.add(e),e}_streamClosed(e){this.#i.delete(e)}close(){this.#a(new Ge("Client was manually closed"))}get closed(){return this.#o!==void 0}#a(e){if(this.#o!==void 0)return;this.#o=e;for(let t of Array.from(this.#i))t._setClosed(new xt("Client was closed",e))}}});var fF=v(()=>{_t()});function TT(e,t,r=2){if(typeof Wi>"u")throw new Sp("WebSockets are not supported in this environment");var o=void 0;if(r==3)o=Array.from(ST.keys());else o=Array.from(rF.keys());let n=new Wi(e,o);return new Jy(n,t)}function $T(e,t,r,o,n=2){return new Wy(e instanceof URL?e:new URL(e),t,r,o,n)}var Gy=v(()=>{oT();Hy();_t();RT();Hy();oT();pT();fF();vl();Ly();jy();RT();IT();Hy();mT();_t()});class Pp{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=t,this.#r=void 0}execute(e){return this.batch([e]).then((t)=>t[0])}async batch(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let r=e.map(Uo),o;if(this.#r===void 0){this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=i.step(),a=s.run(Hi(this.#e)),l=s;o=r.map((u)=>{let d=i.step().condition(dt.ok(l));if(this.#t>=3)d.condition(dt.not(dt.isAutocommit(i)));let p=d.query(u);return p.catch(()=>{return}),l=d,p}),this.#r=i.execute().then(()=>a).then(()=>{return});try{await this.#r}catch(u){throw this.close(),u}}else{if(this.#t<3)await this.#r;this._getSqlCache().apply(r);let i=t.batch(this.#t>=3),s=void 0;o=r.map((a)=>{let l=i.step();if(s!==void 0)l.condition(dt.ok(s));if(this.#t>=3)l.condition(dt.not(dt.isAutocommit(i)));let u=l.query(a);return u.catch(()=>{return}),s=l,u}),await i.execute()}let n=[];for(let i=0;i<o.length;i++)try{let s=await o[i];if(s===void 0)throw new Gt("Statement in a transaction was not executed, probably because the transaction has been rolled back",i,"TRANSACTION_CLOSED");n.push(Al(s))}catch(s){if(s instanceof Gt)throw s;let a=st(s);if(a instanceof Ce)throw new Gt(a.message,i,a.code,a.extendedCode,a.rawCode,a.cause instanceof Error?a.cause:void 0);throw a}return n}catch(r){throw st(r)}}async executeMultiple(e){let t=this._getStream();if(t.closed)throw new Ce("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#r===void 0){this.#r=t.run(Hi(this.#e)).then(()=>{return});try{await this.#r}catch(r){throw this.close(),r}}else await this.#r;await t.sequence(e)}catch(r){throw st(r)}}async rollback(){try{let e=this._getStream();if(e.closed)return;if(this.#r!==void 0);else return;let t=e.run("ROLLBACK").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}async commit(){try{let e=this._getStream();if(e.closed)throw new Ce("Cannot commit the transaction because it is already closed","TRANSACTION_CLOSED");if(this.#r!==void 0)await this.#r;else return;let t=e.run("COMMIT").catch((r)=>{throw st(r)});e.closeGracefully(),await t}catch(e){throw st(e)}finally{this.close()}}}async function Il(e,t,r,o,n=!1){if(n)r.step().run("PRAGMA foreign_keys=off");let i=r.step(),s=i.run(Hi(e)),a=i,l=o.map((h)=>{let b=r.step().condition(dt.ok(a));if(t>=3)b.condition(dt.not(dt.isAutocommit(r)));let y=b.query(h);return a=b,y}),u=r.step().condition(dt.ok(a));if(t>=3)u.condition(dt.not(dt.isAutocommit(r)));let d=u.run("COMMIT");if(r.step().condition(dt.not(dt.ok(u))).run("ROLLBACK").catch((h)=>{return}),n)r.step().run("PRAGMA foreign_keys=on");await r.execute();let m=[];await s;for(let h=0;h<l.length;h++)try{let b=await l[h];if(b===void 0)throw new Gt("Statement in a batch was not executed, probably because the transaction has been rolled back",h,"TRANSACTION_CLOSED");m.push(Al(b))}catch(b){if(b instanceof Gt)throw b;let y=st(b);if(y instanceof Ce)throw new Gt(y.message,h,y.code,y.extendedCode,y.rawCode,y.cause instanceof Error?y.cause:void 0);throw y}return await d,m}function Uo(e){let t,r;if(Array.isArray(e))[t,r]=e;else if(typeof e==="string")t=e;else t=e.sql,r=e.args;let o=new Ap(t);if(r)if(Array.isArray(r))o.bindIndexes(r);else for(let[n,i]of Object.entries(r))o.bindName(n,i);return o}function Al(e){let t=e.columnNames.map((s)=>s??""),r=e.columnDecltypes.map((s)=>s??""),o=e.rows,n=e.affectedRowCount,i=e.lastInsertRowid!==void 0?e.lastInsertRowid:void 0;return new dl(t,r,o,n,i)}function st(e){if(e instanceof Ge){let t=mF(e);return new Ce(e.message,t,void 0,void 0,e)}return e}function mF(e){if(e instanceof bp&&e.code!==void 0)return e.code;else if(e instanceof Pe)return"HRANA_PROTO_ERROR";else if(e instanceof xt)return e.cause instanceof Ge?mF(e.cause):"HRANA_CLOSED_ERROR";else if(e instanceof gl)return"HRANA_WEBSOCKET_ERROR";else if(e instanceof la)return"SERVER_ERROR";else if(e instanceof wn)return"PROTOCOL_VERSION_ERROR";else if(e instanceof or)return"INTERNAL_ERROR";else return"UNKNOWN"}var CT=v(()=>{Gy();vn();pl()});class Rl{#e;#t;capacity;constructor(e,t){this.#e=e,this.#t=new hF,this.capacity=t}apply(e){if(this.capacity<=0)return;let t=new Set;for(let r of e){if(typeof r.sql!=="string")continue;let o=r.sql;if(o.length>=5000)continue;let n=this.#t.get(o);if(n===void 0){while(this.#t.size+1>this.capacity){let[i,s]=this.#t.peekLru();if(t.has(s))break;s.close(),this.#t.delete(i)}if(this.#t.size+1<=this.capacity)n=this.#e.storeSql(o),this.#t.set(o,n)}if(n!==void 0)r.sql=n,t.add(n)}}}class hF{#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 PT=ge(function(EBe,yF){function Tme(e){var t=0,r=[];function o(){if(t--,t<e)n()}function n(){var l=r.shift();if(a.queue=r.length,l)s(l.fn).then(l.resolve).catch(l.reject)}function i(l){return new Promise(function(u,d){r.push({fn:l,resolve:u,reject:d}),a.queue=r.length})}function s(l){t++;try{return Promise.resolve(l()).then(function(u){return o(),u},function(u){throw o(),u})}catch(u){return o(),Promise.reject(u)}}var a=function(l){if(t>=e)return i(l);else return s(l)};return a}function $me(e,t){var r=!1,o=this;return Promise.all(e.map(function(){var n=arguments;return o(function(){if(!r)return t.apply(void 0,n).catch(function(i){throw r=!0,i})})}))}function gF(e){return e.queue=0,e.map=$me,e}yF.exports=function(e){if(e)return gF(Tme(e));else return gF(function(t){return t()})}});function vF(e){if(e.scheme!=="wss"&&e.scheme!=="ws")throw new Ce(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${Xn}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="ws"&&e.tls)throw new Ce('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="wss"&&!e.tls)throw new Ce('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=fp(e.scheme,e.authority,e.path),r;try{r=TT(t,e.authToken)}catch(o){if(o instanceof Sp){let n=e.scheme==="wss"?"https":"http",i=fp(n,e.authority,e.path);throw new Ce(`This environment does not support WebSockets, please switch to the HTTP client by using a "${n}:" URL (${JSON.stringify(i)}). For more information, please read ${Xn}`,"WEBSOCKETS_NOT_SUPPORTED")}throw st(o)}return new wF(r,t,e.authToken,e.intMode,e.concurrency)}class wF{#e;#t;#r;#n;#o;closed;protocol;#i;#a;constructor(e,t,r,o,n){this.#e=t,this.#t=r,this.#r=o,this.#n=this.#c(e),this.#o=void 0,this.closed=!1,this.protocol="ws",this.#a=SF.default(n)}async limit(e){return this.#a(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{let o=await this.#s();try{let n=Uo(r);o.conn.sqlCache.apply([n]);let i=o.stream.query(n);o.stream.closeGracefully();let s=await i;return Al(s)}catch(n){throw st(n)}finally{this._closeStream(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{let r=await this.#s();try{let n=e.map((u)=>{if(Array.isArray(u))return{sql:u[0],args:u[1]||[]};return u}).map(Uo),i=await r.conn.client.getVersion();r.conn.sqlCache.apply(n);let s=r.stream.batch(i>=3);return await Il(t,i,s,n)}catch(o){throw st(o)}finally{this._closeStream(r)}})}async migrate(e){return this.limit(async()=>{let t=await this.#s();try{let r=e.map(Uo),o=await t.conn.client.getVersion(),n=t.stream.batch(o>=3);return await Il("deferred",o,n,r,!0)}catch(r){throw st(r)}finally{this._closeStream(t)}})}async transaction(e="write"){return this.limit(async()=>{let t=await this.#s();try{let r=await t.conn.client.getVersion();return new xF(this,t,e,r)}catch(r){throw this._closeStream(t),st(r)}})}async executeMultiple(e){return this.limit(async()=>{let t=await this.#s();try{let r=t.stream.sequence(e);t.stream.closeGracefully(),await r}catch(r){throw st(r)}finally{this._closeStream(t)}})}sync(){throw new Ce("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#s(){if(this.closed)throw new Ce("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#n.openTime.valueOf()>Ome&&this.#o===void 0){let o=this.#c();this.#o=o,o.client.getVersion().then((n)=>{if(this.#n!==o){if(this.#n.streamStates.size===0)this.#n.client.close()}this.#n=o,this.#o=void 0},(n)=>{this.#o=void 0})}if(this.#n.client.closed)try{if(this.#o!==void 0)this.#n=this.#o;else this.#n=this.#c()}catch(o){throw st(o)}let r=this.#n;try{if(r.useSqlCache===void 0){if(r.useSqlCache=await r.client.getVersion()>=2,r.useSqlCache)r.sqlCache.capacity=bF}let o=r.client.openStream();o.intMode=this.#r;let n={conn:r,stream:o};return r.streamStates.add(n),n}catch(o){throw st(o)}}#c(e){try{return e??=TT(this.#e,this.#t),{client:e,useSqlCache:void 0,sqlCache:new Rl(e,0),openTime:new Date,streamStates:new Set}}catch(t){throw st(t)}}async reconnect(){try{for(let r of Array.from(this.#n.streamStates))try{r.stream.close()}catch{}this.#n.client.close()}catch{}if(this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}let e=this.#c(),t=await e.client.getVersion();if(e.useSqlCache=t>=2,e.useSqlCache)e.sqlCache.capacity=bF;this.#n=e,this.closed=!1}_closeStream(e){e.stream.close();let t=e.conn;if(t.streamStates.delete(e),t.streamStates.size===0&&t!==this.#n)t.client.close()}close(){if(this.#n.client.close(),this.closed=!0,this.#o){try{this.#o.client.close()}catch{}this.#o=void 0}this.closed=!0}}var SF,Ome=60000,bF=100,xF;var _F=v(()=>{Gy();vn();gp();CT();Iy();pl();SF=Fl(PT(),1);vn();xF=class xF extends Pp{#e;#t;constructor(e,t,r,o){super(r,o);this.#e=e,this.#t=t}_getStream(){return this.#t.stream}_getSqlCache(){return this.#t.conn.sqlCache}close(){this.#e._closeStream(this.#t)}get closed(){return this.#t.stream.closed}}});function kF(e){if(e.scheme!=="https"&&e.scheme!=="http")throw new Ce(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(e.scheme+":")}. For more information, please read ${Xn}`,"URL_SCHEME_NOT_SUPPORTED");if(e.encryptionKey!==void 0)throw new Ce("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(e.scheme==="http"&&e.tls)throw new Ce('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(e.scheme==="https"&&!e.tls)throw new Ce('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let t=fp(e.scheme,e.authority,e.path);return new AF(t,e.authToken,e.intMode,e.fetch,e.concurrency,e.remoteEncryptionKey)}class AF{#e;protocol;#t;#r;#n;#o;#i;#a;#s;constructor(e,t,r,o,n,i){this.#t=e,this.#i=t,this.#r=r,this.#n=o,this.#o=n,this.#a=i,this.#e=$T(this.#t,this.#i,this.#n,i),this.#e.intMode=this.#r,this.protocol="http",this.#s=EF.default(this.#o)}async limit(e){return this.#s(e)}async execute(e,t){let r;if(typeof e==="string")r={sql:e,args:t||[]};else r=e;return this.limit(async()=>{try{let o=Uo(r),n,i=this.#e.openStream();try{n=i.query(o)}finally{i.closeGracefully()}let s=await n;return Al(s)}catch(o){throw st(o)}})}async batch(e,t="deferred"){return this.limit(async()=>{try{let o=e.map((l)=>{if(Array.isArray(l))return{sql:l[0],args:l[1]||[]};return l}).map(Uo),n=await this.#e.getVersion(),i,s=this.#e.openStream();try{new Rl(s,IF).apply(o);let u=s.batch(!1);i=Il(t,n,u,o)}finally{s.closeGracefully()}return await i}catch(r){throw st(r)}})}async migrate(e){return this.limit(async()=>{try{let t=e.map(Uo),r=await this.#e.getVersion(),o,n=this.#e.openStream();try{let s=n.batch(!1);o=Il("deferred",r,s,t,!0)}finally{n.closeGracefully()}return await o}catch(t){throw st(t)}})}async transaction(e="write"){return this.limit(async()=>{try{let t=await this.#e.getVersion();return new RF(this.#e.openStream(),e,t)}catch(t){throw st(t)}})}async executeMultiple(e){return this.limit(async()=>{try{let t,r=this.#e.openStream();try{t=r.sequence(e)}finally{r.closeGracefully()}await t}catch(t){throw st(t)}})}sync(){throw new Ce("sync not supported in http mode","SYNC_NOT_SUPPORTED")}close(){this.#e.close()}async reconnect(){try{if(!this.closed)this.#e.close()}finally{this.#e=$T(this.#t,this.#i,this.#n,this.#a),this.#e.intMode=this.#r}}get closed(){return this.#e.closed}}var EF,IF=30,RF;var TF=v(()=>{Gy();vn();gp();CT();Iy();pl();EF=Fl(PT(),1);vn();RF=class RF extends Pp{#e;#t;constructor(e,t,r){super(t,r);this.#e=e,this.#t=new Rl(e,IF)}_getStream(){return this.#e}_getSqlCache(){return this.#t}close(){this.#e.close()}get closed(){return this.#e.closed}}});function Tl(e){return Cme(hp(e,!0))}function Cme(e){if(e.scheme==="wss"||e.scheme==="ws")return vF(e);else if(e.scheme==="https"||e.scheme==="http")return kF(e);else return E4(e)}var zT=v(()=>{gp();T4();_F();TF();vn()});function oe(e,t){if(!e||typeof e!=="object")return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,F))throw Error(`Class "${t.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let r=Object.getPrototypeOf(e).constructor;if(r)while(r){if(F in r&&r[F]===t[F])return!0;r=Object.getPrototypeOf(r)}return!1}var F;var $e=v(()=>{F=Symbol.for("drizzle:entityKind")});var He;var _n=v(()=>{$e();He=class He{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[F]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}});var zp;var Qy=v(()=>{$e();zp=class zp{static[F]="ColumnBuilder";config;constructor(e,t,r){this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:r,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){if(this.config.name!=="")return;this.config.name=e}}});var ir;var $l=v(()=>{ir=Symbol.for("drizzle:Name")});var NT,$F;var OF=v(()=>{$e();$l();NT=class NT{static[F]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e===void 0?"no action":e,this}onDelete(e){return this._onDelete=e===void 0?"no action":e,this}build(e){return new $F(e,this)}};$F=class $F{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function Yy(e,...t){return e(...t)}var DT=()=>{};function LT(e,t){return`${e[ir]}_${t.join("_")}_unique`}var CF,Pme,PF;var zF=v(()=>{$e();$l();CF=class CF{constructor(e,t){this.name=t,this.columns=e}static[F]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new PF(e,this.columns,this.nullsNotDistinctConfig,this.name)}};Pme=class Pme{static[F]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new CF(e,this.name)}};PF=class PF{constructor(e,t,r,o){this.table=e,this.columns=t,this.name=o??LT(this.table,this.columns.map((n)=>n.name)),this.nullsNotDistinct=r}static[F]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}});function NF(e,t,r){for(let o=t;o<e.length;o++){let n=e[o];if(n==="\\"){o++;continue}if(n==='"')return[e.slice(t,o).replace(/\\/g,""),o+1];if(r)continue;if(n===","||n==="}")return[e.slice(t,o).replace(/\\/g,""),o]}return[e.slice(t).replace(/\\/g,""),e.length]}function DF(e,t=0){let r=[],o=t,n=!1;while(o<e.length){let i=e[o];if(i===","){if(n||o===t)r.push("");n=!0,o++;continue}if(n=!1,i==="\\"){o+=2;continue}if(i==='"'){let[l,u]=NF(e,o+1,!0);r.push(l),o=u;continue}if(i==="}")return[r,o+1];if(i==="{"){let[l,u]=DF(e,o+1);r.push(l),o=u;continue}let[s,a]=NF(e,o,!1);r.push(s),o=a}return[r,o]}function LF(e){let[t]=DF(e,1);return t}function BT(e){return`{${e.map((t)=>{if(Array.isArray(t))return BT(t);if(typeof t==="string")return`"${t.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`;return`${t}`}).join(",")}}`}var BF=()=>{};var Np,Ol,jF,zme,ZF,jT;var UF=v(()=>{Qy();_n();$e();OF();DT();zF();BF();Np=class Np extends zp{foreignKeyConfigs=[];static[F]="PgColumnBuilder";array(e){return new ZF(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>Yy((n,i)=>{let s=new NT(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)},r,o))}buildExtraConfigColumn(e){return new jF(e,this.config)}};Ol=class Ol extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=LT(e,[t.name]);super(e,t);this.table=e}static[F]="PgColumn"};jF=class jF extends Ol{static[F]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}};zme=class zme{static[F]="IndexedColumn";constructor(e,t,r,o){this.name=e,this.keyAsName=t,this.type=r,this.indexConfig=o}name;keyAsName;type;indexConfig};ZF=class ZF extends Np{static[F]="PgArrayBuilder";constructor(e,t,r){super(e,"array","PgArray");this.config.baseBuilder=t,this.config.size=r}build(e){let t=this.config.baseBuilder.build(e);return new jT(e,this.config,t)}};jT=class jT extends Ol{constructor(e,t,r,o){super(e,t);this.baseColumn=r,this.range=o,this.size=t.size}size;static[F]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.size==="number"?this.size:""}]`}mapFromDriverValue(e){if(typeof e==="string")e=LF(e);return e.map((t)=>this.baseColumn.mapFromDriverValue(t))}mapToDriverValue(e,t=!1){let r=e.map((o)=>o===null?null:oe(this.baseColumn,jT)?this.baseColumn.mapToDriverValue(o,!0):this.baseColumn.mapToDriverValue(o));if(t)return r;return BT(r)}}});function FF(e){return!!e&&typeof e==="function"&&MF in e&&e[MF]===!0}var Nme,qF,MF,Dme,KF;var JF=v(()=>{$e();UF();Nme=class Nme extends Np{static[F]="PgEnumObjectColumnBuilder";constructor(e,t){super(e,"string","PgEnumObjectColumn");this.config.enum=t}build(e){return new qF(e,this.config)}};qF=class qF extends Ol{static[F]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}};MF=Symbol.for("drizzle:isPgEnum");Dme=class Dme extends Np{static[F]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn");this.config.enum=t}build(e){return new KF(e,this.config)}};KF=class KF extends Ol{static[F]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t);this.enum=t.enum}getSQLType(){return this.enum.enumName}}});var pt,Dp;var En=v(()=>{$e();pt=class pt{static[F]="Subquery";constructor(e,t,r,o=!1,n=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:o,usedTables:n}}};Dp=class Dp extends pt{static[F]="WithSubquery"}});var HF="0.45.2";var VF=()=>{};var ZT,UT,WF;var GF=v(()=>{DT();VF();WF={startActiveSpan(e,t){if(!ZT)return t();if(!UT)UT=ZT.trace.getTracer("drizzle-orm",HF);return Yy((r,o)=>o.startActiveSpan(e,(n)=>{try{return t(n)}catch(i){throw n.setStatus({code:r.SpanStatusCode.ERROR,message:i instanceof Error?i.message:"Unknown error"}),i}finally{n.end()}}),ZT,UT)}}});var ft;var Mo=v(()=>{ft=Symbol.for("drizzle:ViewBaseConfig")});function rs(e){return e[ir]}function ha(e){return`${e[Xy]??"public"}.${e[ir]}`}var Xy,eb,QF,MT,qT,Lp,YF,Lme,he;var sr=v(()=>{$e();$l();Xy=Symbol.for("drizzle:Schema"),eb=Symbol.for("drizzle:Columns"),QF=Symbol.for("drizzle:ExtraConfigColumns"),MT=Symbol.for("drizzle:OriginalName"),qT=Symbol.for("drizzle:BaseName"),Lp=Symbol.for("drizzle:IsAlias"),YF=Symbol.for("drizzle:ExtraConfigBuilder"),Lme=Symbol.for("drizzle:IsDrizzleTable");he=class he{static[F]="Table";static Symbol={Name:ir,Schema:Xy,OriginalName:MT,Columns:eb,ExtraConfigColumns:QF,BaseName:qT,IsAlias:Lp,ExtraConfigBuilder:YF};[ir];[MT];[Xy];[eb];[QF];[qT];[Lp]=!1;[Lme]=!0;[YF]=void 0;constructor(e,t,r){this[ir]=this[MT]=e,this[Xy]=t,this[qT]=r}}});function FT(e){return e!==null&&e!==void 0&&typeof e.getSQL==="function"}function jme(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 XF(e){return typeof e==="object"&&e!==null&&"mapToDriverValue"in e&&typeof e.mapToDriverValue==="function"}function C(e,...t){let r=[];if(t.length>0||e.length>0&&e[0]!=="")r.push(new Nt(e[0]));for(let[o,n]of t.entries())r.push(n,new Nt(e[o+1]));return new _e(r)}function Bp(e,t){return e.map((r)=>{if(oe(r,ns)){if(!(r.name in t))throw Error(`No value for placeholder "${r.name}" was provided`);return t[r.name]}if(oe(r,Ur)&&oe(r.value,ns)){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 Bme,Nt,_e,tb,e3,t3,Nje,Ur,ns,Zme,an;var Yt=v(()=>{$e();JF();En();GF();Mo();_n();sr();Bme=class Bme{static[F]="FakePrimitiveParam"};Nt=class Nt{static[F]="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(oe(t,he)){let r=t[he.Symbol.Schema];this.usedTables.push(r===void 0?t[he.Symbol.Name]:r+"."+t[he.Symbol.Name])}}static[F]="SQL";decoder=e3;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return WF.startActiveSpan("drizzle.buildSQL",(t)=>{let r=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(e,t){let r=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:o,escapeName:n,escapeParam:i,prepareTyping:s,inlineParams:a,paramStartIndex:l}=r;return jme(e.map((u)=>{if(oe(u,Nt))return{sql:u.value.join(""),params:[]};if(oe(u,tb))return{sql:n(u.value),params:[]};if(u===void 0)return{sql:"",params:[]};if(Array.isArray(u)){let d=[new Nt("(")];for(let[p,m]of u.entries())if(d.push(m),p<u.length-1)d.push(new Nt(", "));return d.push(new Nt(")")),this.buildQueryFromSourceParams(d,r)}if(oe(u,_e))return this.buildQueryFromSourceParams(u.queryChunks,{...r,inlineParams:a||u.shouldInlineParams});if(oe(u,he)){let d=u[he.Symbol.Schema],p=u[he.Symbol.Name];return{sql:d===void 0||u[Lp]?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,He)){let d=o.getColumnCasing(u);if(t.invokeSource==="indexes")return{sql:n(d),params:[]};let p=u.table[he.Symbol.Schema];return{sql:u.table[Lp]||p===void 0?n(u.table[he.Symbol.Name])+"."+n(d):n(p)+"."+n(u.table[he.Symbol.Name])+"."+n(d),params:[]}}if(oe(u,an)){let d=u[ft].schema,p=u[ft].name;return{sql:d===void 0||u[ft].isAlias?n(p):n(d)+"."+n(p),params:[]}}if(oe(u,Ur)){if(oe(u.value,ns))return{sql:i(l.value++,u),params:[u],typings:["none"]};let d=u.value===null?null:u.encoder.mapToDriverValue(u.value);if(oe(d,_e))return this.buildQueryFromSourceParams([d],r);if(a)return{sql:this.mapInlineParam(d,r),params:[]};let p=["none"];if(s)p=[s(u.encoder)];return{sql:i(l.value++,d),params:[d],typings:p}}if(oe(u,ns))return{sql:i(l.value++,u),params:[u],typings:["none"]};if(oe(u,_e.Aliased)&&u.fieldAlias!==void 0)return{sql:n(u.fieldAlias),params:[]};if(oe(u,pt)){if(u._.isWith)return{sql:n(u._.alias),params:[]};return this.buildQueryFromSourceParams([new Nt("("),u._.sql,new Nt(") "),new tb(u._.alias)],r)}if(FF(u)){if(u.schema)return{sql:n(u.schema)+"."+n(u.enumName),params:[]};return{sql:n(u.enumName),params:[]}}if(FT(u)){if(u.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([u.getSQL()],r);return this.buildQueryFromSourceParams([new Nt("("),u.getSQL(),new Nt(")")],r)}if(a)return{sql:this.mapInlineParam(u,r),params:[]};return{sql:i(l.value++,u),params:[u],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e==="number"||typeof e==="boolean")return e.toString();if(typeof e==="string")return t(e);if(typeof e==="object"){let r=e.toString();if(r==="[object Object]")return t(JSON.stringify(e));return t(r)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){if(e===void 0)return this;return new _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}};tb=class tb{constructor(e){this.value=e}static[F]="Name";brand;getSQL(){return new _e([this])}};e3={mapFromDriverValue:(e)=>e},t3={mapToDriverValue:(e)=>e},Nje={...e3,...t3};Ur=class Ur{constructor(e,t=t3){this.value=e,this.encoder=t}static[F]="Param";brand;getSQL(){return new _e([this])}};((e)=>{function t(){return new _e([])}e.empty=t;function r(l){return new _e(l)}e.fromList=r;function o(l){return new _e([new Nt(l)])}e.raw=o;function n(l,u){let d=[];for(let[p,m]of l.entries()){if(p>0&&u!==void 0)d.push(u);d.push(m)}return new _e(d)}e.join=n;function i(l){return new tb(l)}e.identifier=i;function s(l){return new ns(l)}e.placeholder=s;function a(l,u){return new Ur(l,u)}e.param=a})(C||(C={}));((e)=>{class t{constructor(r,o){this.sql=r,this.fieldAlias=o}static[F]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}}e.Aliased=t})(_e||(_e={}));ns=class ns{constructor(e){this.name=e}static[F]="Placeholder";getSQL(){return new _e([this])}};Zme=Symbol.for("drizzle:IsDrizzleView");an=class an{static[F]="View";[ft];[Zme]=!0;constructor({name:e,schema:t,selectedFields:r,query:o}){this[ft]={name:e,originalName:e,schema:t,selectedFields:r,query:o,isExisting:!o,isAlias:!1}}getSQL(){return new _e([this])}};He.prototype.getSQL=function(){return new _e([this])};he.prototype.getSQL=function(){return new _e([this])};pt.prototype.getSQL=function(){return new _e([this])}});function KT(e,t,r){let o={},n=e.reduce((i,{path:s,field:a},l)=>{let u;if(oe(a,He))u=a;else if(oe(a,_e))u=a.decoder;else if(oe(a,pt))u=a._.sql.decoder;else u=a.sql.decoder;let d=i;for(let[p,m]of s.entries())if(p<s.length-1){if(!(m in d))d[m]={};d=d[m]}else{let h=t[l],b=d[m]=h===null?null:u.mapFromDriverValue(h);if(r&&oe(a,He)&&s.length===2){let y=s[0];if(!(y in o))o[y]=b===null?rs(a.table):!1;else if(typeof o[y]==="string"&&o[y]!==rs(a.table))o[y]=!1}}return i},{});if(r&&Object.keys(o).length>0){for(let[i,s]of Object.entries(o))if(typeof s==="string"&&!r[s])n[i]=null}return n}function cn(e,t){return Object.entries(e).reduce((r,[o,n])=>{if(typeof o!=="string")return r;let i=t?[...t,o]:[o];if(oe(n,He)||oe(n,_e)||oe(n,_e.Aliased)||oe(n,pt))r.push({path:i,field:n});else if(oe(n,he))r.push(...cn(n[he.Symbol.Columns],i));else r.push(...cn(n,i));return r},[])}function jp(e,t){let r=Object.keys(e),o=Object.keys(t);if(r.length!==o.length)return!1;for(let[n,i]of r.entries())if(i!==o[n])return!1;return!0}function rb(e,t){let r=Object.entries(t).filter(([,o])=>o!==void 0).map(([o,n])=>{if(oe(n,_e)||oe(n,He))return[o,n];else return[o,new Ur(n,e[he.Symbol.Columns][o])]});if(r.length===0)throw Error("No values to set");return Object.fromEntries(r)}function r3(e,t){for(let r of t)for(let o of Object.getOwnPropertyNames(r.prototype)){if(o==="constructor")continue;Object.defineProperty(e.prototype,o,Object.getOwnPropertyDescriptor(r.prototype,o)||Object.create(null))}}function nb(e){return e[he.Symbol.Columns]}function Zp(e){return oe(e,pt)?e._.alias:oe(e,an)?e[ft].name:oe(e,_e)?void 0:e[he.Symbol.IsAlias]?e[he.Symbol.Name]:e[he.Symbol.BaseName]}function no(e,t){return{name:typeof e==="string"&&e.length>0?e:"",config:typeof e==="object"?e:t}}function n3(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 JT;var Sr=v(()=>{_n();$e();Yt();En();sr();Mo();JT=typeof TextDecoder>"u"?null:new TextDecoder});var o3,HT,VT;var ob=v(()=>{$e();o3=class o3{static[F]="ConsoleLogWriter";write(e){console.log(e)}};HT=class HT{static[F]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new o3}logQuery(e,t){let r=t.map((n)=>{try{return JSON.stringify(n)}catch{return String(n)}}),o=r.length?` -- params: [${r.join(", ")}]`:"";this.writer.write(`Query: ${e}${o}`)}};VT=class VT{static[F]="NoopLogger";logQuery(){}}});var i3,s3,WT;var a3=v(()=>{$e();sr();i3=Symbol.for("drizzle:PgInlineForeignKeys"),s3=Symbol.for("drizzle:EnableRLS");WT=class WT extends he{static[F]="PgTable";static Symbol=Object.assign({},he.Symbol,{InlineForeignKeys:i3,EnableRLS:s3});[i3]=[];[s3]=!1;[he.Symbol.ExtraConfigBuilder]=void 0;[he.Symbol.ExtraConfigColumns]={}}});var GT,c3;var l3=v(()=>{$e();a3();GT=class GT{static[F]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new c3(e,this.columns,this.name)}};c3=class c3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[WT.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function Tr(e,t){if(XF(t)&&!FT(e)&&!oe(e,Ur)&&!oe(e,ns)&&!oe(e,He)&&!oe(e,he)&&!oe(e,an))return new Ur(e,t);return e}function tt(...e){let t=e.filter((r)=>r!==void 0);if(t.length===0)return;if(t.length===1)return new _e(t);return new _e([new Nt("("),C.join(t,new Nt(" and ")),new Nt(")")])}function ln(...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 Nt("("),C.join(t,new Nt(" or ")),new Nt(")")])}function d3(e){return C`not ${e}`}function is(e,t){if(Array.isArray(t)){if(t.length===0)return C`false`;return C`${e} in ${t.map((r)=>Tr(r,e))}`}return C`${e} in ${Tr(t,e)}`}function ib(e,t){if(Array.isArray(t)){if(t.length===0)return C`true`;return C`${e} not in ${t.map((r)=>Tr(r,e))}`}return C`${e} not in ${Tr(t,e)}`}function Mr(e){return C`${e} is null`}function m3(e){return C`${e} is not null`}function sb(e){return C`exists ${e}`}function ss(e){return C`not exists ${e}`}function h3(e,t,r){return C`${e} between ${Tr(t,e)} and ${Tr(r,e)}`}function g3(e,t,r){return C`${e} not between ${Tr(t,e)} and ${Tr(r,e)}`}function y3(e,t){return C`${e} like ${t}`}function b3(e,t){return C`${e} not like ${t}`}function S3(e,t){return C`${e} ilike ${t}`}function v3(e,t){return C`${e} not ilike ${t}`}var je=(e,t)=>C`${e} = ${Tr(t,e)}`,u3=(e,t)=>C`${e} <> ${Tr(t,e)}`,kn=(e,t)=>C`${e} > ${Tr(t,e)}`,p3=(e,t)=>C`${e} >= ${Tr(t,e)}`,f3=(e,t)=>C`${e} < ${Tr(t,e)}`,os=(e,t)=>C`${e} <= ${Tr(t,e)}`;var w3=v(()=>{_n();$e();sr();Yt()});function qo(e){return C`${e} asc`}function ga(e){return C`${e} desc`}var x3=v(()=>{Yt()});var QT=v(()=>{w3();x3()});function E3(){return{and:tt,between:h3,eq:je,exists:sb,gt:kn,gte:p3,ilike:S3,inArray:is,isNull:Mr,isNotNull:m3,like:y3,lt:f3,lte:os,ne:u3,not:d3,notBetween:g3,notExists:ss,notLike:b3,notIlike:v3,notInArray:ib,or:ln,sql:C}}function k3(){return{sql:C,asc:qo,desc:ga}}function I3(e,t){if(Object.keys(e).length===1&&"default"in e&&!oe(e.default,he))e=e.default;let r={},o={},n={};for(let[i,s]of Object.entries(e))if(oe(s,he)){let a=ha(s),l=o[a];r[a]=i,n[i]={tsName:i,dbName:s[he.Symbol.Name],schema:s[he.Symbol.Schema],columns:s[he.Symbol.Columns],relations:l?.relations??{},primaryKey:l?.primaryKey??[]};for(let d of Object.values(s[he.Symbol.Columns]))if(d.primary)n[i].primaryKey.push(d);let u=s[he.Symbol.ExtraConfigBuilder]?.(s[he.Symbol.ExtraConfigColumns]);if(u){for(let d of Object.values(u))if(oe(d,GT))n[i].primaryKey.push(...d.columns)}}else if(oe(s,_3)){let a=ha(s.table),l=r[a],u=s.config(t(s.table)),d;for(let[p,m]of Object.entries(u))if(l){let h=n[l];if(h.relations[p]=m,d)h.primaryKey.push(...d)}else{if(!(a in o))o[a]={relations:{},primaryKey:d};o[a].relations[p]=m}}return{tables:n,tableNamesMap:r}}function Ume(e){return function(r,o){return new as(e,r,o,o?.fields.reduce((n,i)=>n&&i.notNull,!0)??!1)}}function Mme(e){return function(r,o){return new Up(e,r,o)}}function A3(e,t,r){if(oe(r,as)&&r.config)return{fields:r.config.fields,references:r.config.references};let o=t[ha(r.referencedTable)];if(!o)throw Error(`Table "${r.referencedTable[he.Symbol.Name]}" not found in schema`);let n=e[o];if(!n)throw Error(`Table "${o}" not found in schema`);let i=r.sourceTable,s=t[ha(i)];if(!s)throw Error(`Table "${i[he.Symbol.Name]}" not found in schema`);let a=[];for(let l of Object.values(n.relations))if(r.relationName&&r!==l&&l.relationName===r.relationName||!r.relationName&&l.referencedTable===r.sourceTable)a.push(l);if(a.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${o}"`):Error(`There are multiple relations between "${o}" and "${r.sourceTable[he.Symbol.Name]}". Please specify relation name`);if(a[0]&&oe(a[0],as)&&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 R3(e){return{one:Ume(e),many:Mme(e)}}function ab(e,t,r,o,n=(i)=>i){let i={};for(let[s,a]of o.entries())if(a.isJson){let l=t.relations[a.tsKey],u=r[s],d=typeof u==="string"?JSON.parse(u):u;i[a.tsKey]=oe(l,as)?d&&ab(e,e[a.relationTableTsKey],d,a.selection,n):d.map((p)=>ab(e,e[a.relationTableTsKey],p,a.selection,n))}else{let l=n(r[s]),u=a.field,d;if(oe(u,He))d=u;else if(oe(u,_e))d=u.decoder;else d=u.sql.decoder;i[a.tsKey]=l===null?null:d.mapFromDriverValue(l)}return i}var YT,_3,as,Up;var Mp=v(()=>{sr();_n();$e();l3();QT();Yt();YT=class YT{constructor(e,t,r){this.sourceTable=e,this.referencedTable=t,this.relationName=r,this.referencedTableName=t[he.Symbol.Name]}static[F]="Relation";referencedTableName;fieldName};_3=class _3{constructor(e,t){this.table=e,this.config=t}static[F]="Relations"};as=class as extends YT{constructor(e,t,r,o){super(e,t,r?.relationName);this.config=r,this.isNullable=o}static[F]="One";withFieldName(e){let t=new as(this.sourceTable,this.referencedTable,this.config,this.isNullable);return t.fieldName=e,t}};Up=class Up extends YT{constructor(e,t,r){super(e,t,r?.relationName);this.config=r}static[F]="Many";withFieldName(e){let t=new Up(this.sourceTable,this.referencedTable,this.config);return t.fieldName=e,t}}});function qp(e,t){return new Proxy(e,new ya(t,!1))}function oo(e,t){return new Proxy(e,new Cl(new Proxy(e.table,new ya(t,!1))))}function XT(e,t){return new _e.Aliased(Fp(e.sql,t),e.fieldAlias)}function Fp(e,t){return C.join(e.queryChunks.map((r)=>{if(oe(r,He))return oo(r,t);if(oe(r,_e))return Fp(r,t);if(oe(r,_e.Aliased))return XT(r,t);return r}))}var Cl,ya,qme;var Kp=v(()=>{_n();$e();Yt();sr();Mo();Cl=class Cl{constructor(e){this.table=e}static[F]="ColumnAliasProxyHandler";get(e,t){if(t==="table")return this.table;return e[t]}};ya=class ya{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[F]="TableAliasProxyHandler";get(e,t){if(t===he.Symbol.IsAlias)return!0;if(t===he.Symbol.Name)return this.alias;if(this.replaceOriginalName&&t===he.Symbol.OriginalName)return this.alias;if(t===ft)return{...e[ft],name:this.alias,isAlias:!0};if(t===he.Symbol.Columns){let o=e[he.Symbol.Columns];if(!o)return o;let n={};return Object.keys(o).map((i)=>{n[i]=new Proxy(o[i],new Cl(new Proxy(e,this)))}),n}let r=e[t];if(oe(r,He))return new Proxy(r,new Cl(new Proxy(e,this)));return r}};qme=class qme{constructor(e){this.alias=e}static[F]="RelationTableAliasProxyHandler";get(e,t){if(t==="sourceTable")return qp(e.sourceTable,this.alias);return e[t]}}});var at;var ba=v(()=>{Kp();_n();$e();Yt();En();Mo();at=class at{static[F]="SelectionProxyHandler";config;constructor(e){this.config={...e}}get(e,t){if(t==="_")return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(t===ft)return{...e[ft],selectedFields:new Proxy(e[ft].selectedFields,this)};if(typeof t==="symbol")return e[t];let o=(oe(e,pt)?e._.selectedFields:oe(e,an)?e[ft].selectedFields:e)[t];if(oe(o,_e.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!o.isSelectionField)return o.sql;let n=o.clone();return n.isSelectionField=!0,n}if(oe(o,_e)){if(this.config.sqlBehavior==="sql")return o;throw Error(`You tried to reference "${t}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}if(oe(o,He)){if(this.config.alias)return new Proxy(o,new Cl(new Proxy(o.table,new ya(this.config.alias,this.config.replaceOriginalName??!1))));return o}if(typeof o!=="object"||o===null)return o;return new Proxy(o,new at(this.config))}}});var vr;var Fo=v(()=>{$e();vr=class vr{static[F]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then((t)=>(e?.(),t),(t)=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}}});var e$,T3;var t$=v(()=>{$e();$l();e$=class e${static[F]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(e,t){if(this.reference=()=>{let{name:r,columns:o,foreignColumns:n}=e();return{name:r,columns:o,foreignTable:n[0].table,foreignColumns:n}},t)this._onUpdate=t.onUpdate,this._onDelete=t.onDelete}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new T3(e,this)}};T3=class T3{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[F]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),o=t.map((s)=>s.name),n=r.map((s)=>s.name),i=[this.table[ir],...o,r[0].table[ir],...n];return e??`${i.join("_")}_fk`}}});function r$(e,t){return`${e[ir]}_${t.join("_")}_unique`}var $3,Fme,O3;var n$=v(()=>{$e();$l();$3=class $3{constructor(e,t){this.name=t,this.columns=e}static[F]="SQLiteUniqueConstraintBuilder";columns;build(e){return new O3(e,this.columns,this.name)}};Fme=class Fme{static[F]="SQLiteUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new $3(e,this.name)}};O3=class O3{constructor(e,t,r){this.table=e,this.columns=t,this.name=r??r$(this.table,this.columns.map((o)=>o.name))}static[F]="SQLiteUniqueConstraint";columns;name;getName(){return this.name}}});var Ut,bt;var cs=v(()=>{Qy();_n();$e();t$();n$();Ut=class Ut extends zp{static[F]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:"always",mode:t?.mode??"virtual"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>((n,i)=>{let s=new e$(()=>{let a=n();return{columns:[e],foreignColumns:[a]}});if(i.onUpdate)s.onUpdate(i.onUpdate);if(i.onDelete)s.onDelete(i.onDelete);return s.build(t)})(r,o))}};bt=class bt extends He{constructor(e,t){if(!t.uniqueName)t.uniqueName=r$(e,[t.name]);super(e,t);this.table=e}static[F]="SQLiteColumn"}});function B3(e,t){let{name:r,config:o}=no(e,t);if(o?.mode==="json")return new z3(r);if(o?.mode==="bigint")return new C3(r);return new D3(r)}var C3,P3,z3,N3,D3,L3;var o$=v(()=>{$e();Sr();cs();C3=class C3 extends Ut{static[F]="SQLiteBigIntBuilder";constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new P3(e,this.config)}};P3=class P3 extends bt{static[F]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return BigInt(t.toString("utf8"))}return BigInt(JT.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}};z3=class z3 extends Ut{static[F]="SQLiteBlobJsonBuilder";constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new N3(e,this.config)}};N3=class N3 extends bt{static[F]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){let t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return JSON.parse(t.toString("utf8"))}return JSON.parse(JT.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}};D3=class D3 extends Ut{static[F]="SQLiteBlobBufferBuilder";constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new L3(e,this.config)}};L3=class L3 extends bt{static[F]="SQLiteBlobBuffer";mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;return Buffer.from(e)}getSQLType(){return"blob"}}});function U3(e){return(t,r)=>{let{name:o,config:n}=no(t,r);return new j3(o,n,e)}}var j3,Z3;var i$=v(()=>{$e();Sr();cs();j3=class j3 extends Ut{static[F]="SQLiteCustomColumnBuilder";constructor(e,t,r){super(e,"custom","SQLiteCustomColumn");this.config.fieldConfig=t,this.config.customTypeParams=r}build(e){return new Z3(e,this.config)}};Z3=class Z3 extends bt{static[F]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(e,t){super(e,t);this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom==="function"?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo==="function"?this.mapTo(e):e}}});function ar(e,t){let{name:r,config:o}=no(e,t);if(o?.mode==="timestamp"||o?.mode==="timestamp_ms")return new F3(r,o.mode);if(o?.mode==="boolean")return new J3(r,o.mode);return new M3(r)}var cb,lb,M3,q3,F3,K3,J3,H3;var s$=v(()=>{$e();Yt();Sr();cs();cb=class cb extends Ut{static[F]="SQLiteBaseIntegerBuilder";constructor(e,t,r){super(e,t,r);this.config.autoIncrement=!1}primaryKey(e){if(e?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}};lb=class lb extends bt{static[F]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}};M3=class M3 extends cb{static[F]="SQLiteIntegerBuilder";constructor(e){super(e,"number","SQLiteInteger")}build(e){return new q3(e,this.config)}};q3=class q3 extends lb{static[F]="SQLiteInteger"};F3=class F3 extends cb{static[F]="SQLiteTimestampBuilder";constructor(e,t){super(e,"date","SQLiteTimestamp");this.config.mode=t}defaultNow(){return this.default(C`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new K3(e,this.config)}};K3=class K3 extends lb{static[F]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(e){if(this.config.mode==="timestamp")return new Date(e*1000);return new Date(e)}mapToDriverValue(e){let t=e.getTime();if(this.config.mode==="timestamp")return Math.floor(t/1000);return t}};J3=class J3 extends cb{static[F]="SQLiteBooleanBuilder";constructor(e,t){super(e,"boolean","SQLiteBoolean");this.config.mode=t}build(e){return new H3(e,this.config)}};H3=class H3 extends lb{static[F]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}});function e5(e,t){let{name:r,config:o}=no(e,t),n=o?.mode;return n==="number"?new G3(r):n==="bigint"?new Y3(r):new V3(r)}var V3,W3,G3,Q3,Y3,X3;var a$=v(()=>{$e();Sr();cs();V3=class V3 extends Ut{static[F]="SQLiteNumericBuilder";constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new W3(e,this.config)}};W3=class W3 extends bt{static[F]="SQLiteNumeric";mapFromDriverValue(e){if(typeof e==="string")return e;return String(e)}getSQLType(){return"numeric"}};G3=class G3 extends Ut{static[F]="SQLiteNumericNumberBuilder";constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new Q3(e,this.config)}};Q3=class Q3 extends bt{static[F]="SQLiteNumericNumber";mapFromDriverValue(e){if(typeof e==="number")return e;return Number(e)}mapToDriverValue=String;getSQLType(){return"numeric"}};Y3=class Y3 extends Ut{static[F]="SQLiteNumericBigIntBuilder";constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new X3(e,this.config)}};X3=class X3 extends bt{static[F]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}});function n5(e){return new t5(e??"")}var t5,r5;var c$=v(()=>{$e();cs();t5=class t5 extends Ut{static[F]="SQLiteRealBuilder";constructor(e){super(e,"number","SQLiteReal")}build(e){return new r5(e,this.config)}};r5=class r5 extends bt{static[F]="SQLiteReal";getSQLType(){return"real"}}});function mt(e,t={}){let{name:r,config:o}=no(e,t);if(o.mode==="json")return new s5(r);return new o5(r,o)}var o5,i5,s5,a5;var l$=v(()=>{$e();Sr();cs();o5=class o5 extends Ut{static[F]="SQLiteTextBuilder";constructor(e,t){super(e,"string","SQLiteText");this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new i5(e,this.config)}};i5=class i5 extends bt{static[F]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(e,t){super(e,t)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}};s5=class s5 extends Ut{static[F]="SQLiteTextJsonBuilder";constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new a5(e,this.config)}};a5=class a5 extends bt{static[F]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}});function c5(){return{blob:B3,customType:U3,integer:ar,numeric:e5,real:n5,text:mt}}var l5=v(()=>{o$();i$();s$();a$();c$();l$()});function Kme(e,t,r,o,n=e){let i=new At(e,o,n),s=typeof t==="function"?t(c5()):t,a=Object.fromEntries(Object.entries(s).map(([u,d])=>{let p=d;p.setName(u);let m=p.build(i);return i[u$].push(...p.buildForeignKeys(m,i)),[u,m]})),l=Object.assign(i,a);if(l[he.Symbol.Columns]=a,l[he.Symbol.ExtraConfigColumns]=a,r)l[At.Symbol.ExtraConfigBuilder]=r;return l}var u$,At,Jp=(e,t,r)=>Kme(e,t,r);var Ko=v(()=>{$e();sr();l5();u$=Symbol.for("drizzle:SQLiteInlineForeignKeys");At=class At extends he{static[F]="SQLiteTable";static Symbol=Object.assign({},he.Symbol,{InlineForeignKeys:u$});[he.Symbol.Columns];[u$]=[];[he.Symbol.ExtraConfigBuilder]=void 0}});var Jme,u5;var d5=v(()=>{$e();Jme=class Jme{constructor(e,t){this.name=e,this.value=t}static[F]="SQLiteCheckBuilder";brand;build(e){return new u5(e,this)}};u5=class u5{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[F]="SQLiteCheck";name;value}});function Jo(e){return new p5(e,!1)}var p5,f5,m5;var h5=v(()=>{$e();p5=class p5{constructor(e,t){this.name=e,this.unique=t}static[F]="SQLiteIndexBuilderOn";on(...e){return new f5(this.name,e,this.unique)}};f5=class f5{static[F]="SQLiteIndexBuilder";config;constructor(e,t,r){this.config={name:e,columns:t,unique:r,where:void 0}}where(e){return this.config.where=e,this}build(e){return new m5(this.config,e)}};m5=class m5{static[F]="SQLiteIndex";config;constructor(e,t){this.config={...e,table:t}}}});var Hme,g5;var y5=v(()=>{$e();Ko();Hme=class Hme{static[F]="SQLitePrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new g5(e,this.columns,this.name)}};g5=class g5{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static[F]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[At.Symbol.Name]}_${this.columns.map((e)=>e.name).join("_")}_pk`}}});function In(e){if(oe(e,At))return[`${e[he.Symbol.BaseName]}`];if(oe(e,pt))return e._.usedTables??[];if(oe(e,_e))return e.usedTables??[];return[]}var Pl=v(()=>{$e();Yt();En();sr();Ko()});var ub;var b5=v(()=>{$e();Fo();ba();Ko();sr();Sr();Pl();ub=class ub extends vr{constructor(e,t,r,o){super();this.table=e,this.session=t,this.dialect=r,this.config={table:e,withList:o}}static[F]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]==="function"){let t=e[0](new Proxy(this.config.table[he.Symbol.Columns],new at({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),r=Array.isArray(t)?t:[t];this.config.orderBy=r}else{let t=e;this.config.orderBy=t}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[At.Symbol.Columns]){return this.config.returning=cn(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:In(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 Vme(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((r)=>r.toLowerCase()).join("_")}function Wme(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((r,o,n)=>{let i=n===0?o.toLowerCase():`${o[0].toUpperCase()}${o.slice(1)}`;return r+i},"")}function Gme(e){return e}var d$;var S5=v(()=>{$e();sr();d$=class d${static[F]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert=e==="snake_case"?Vme:e==="camelCase"?Wme:Gme}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=e.table[he.Symbol.Schema]??"public",r=e.table[he.Symbol.OriginalName],o=`${t}.${r}.${e.name}`;if(!this.cache[o])this.cacheTable(e.table);return this.cache[o]}cacheTable(e){let t=e[he.Symbol.Schema]??"public",r=e[he.Symbol.OriginalName],o=`${t}.${r}`;if(!this.cachedTables[o]){for(let n of Object.values(e[he.Symbol.Columns])){let i=`${o}.${n.name}`;this.cache[i]=this.convert(n.name)}this.cachedTables[o]=!0}}clearCache(){this.cache={},this.cachedTables={}}}});var zl,Ho,p$;var db=v(()=>{$e();zl=class zl extends Error{static[F]="DrizzleError";constructor({message:e,cause:t}){super(e);this.name="DrizzleError",this.cause=t}};Ho=class Ho extends Error{constructor(e,t,r){super(`Failed query: ${e}
|
|
425
425
|
params: ${t}`);if(this.query=e,this.params=t,this.cause=r,Error.captureStackTrace(this,Ho),r)this.cause=r}};p$=class p$ extends zl{static[F]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}});var v5=()=>{};var w5=()=>{};var x5=v(()=>{v5();w5()});var f$=v(()=>{QT();x5();Yt()});var m$=v(()=>{o$();cs();i$();s$();a$();c$();l$()});var Vo;var Hp=v(()=>{$e();Yt();Vo=class Vo extends an{static[F]="SQLiteViewBase"}});var Nl,h$,g$;var pb=v(()=>{Kp();S5();_n();$e();db();Mp();f$();Yt();m$();Ko();En();sr();Sr();Mo();Hp();Nl=class Nl{static[F]="SQLiteDialect";casing;constructor(e){this.casing=new d$(e?.casing)}escapeName(e){return`"${e.replace(/"/g,'""')}"`}escapeParam(e){return"?"}escapeString(e){return`'${e.replace(/'/g,"''")}'`}buildWithCTE(e){if(!e?.length)return;let t=[C`with `];for(let[r,o]of e.entries())if(t.push(C`${C.identifier(o._.alias)} as (${o._.sql})`),r<e.length-1)t.push(C`, `);return t.push(C` `),C.join(t)}buildDeleteQuery({table:e,where:t,returning:r,withList:o,limit:n,orderBy:i}){let s=this.buildWithCTE(o),a=r?C` returning ${this.buildSelection(r,{isSingleTable:!0})}`:void 0,l=t?C` where ${t}`:void 0,u=this.buildOrderBy(i),d=this.buildLimit(n);return C`${s}delete from ${e}${l}${a}${u}${d}`}buildUpdateSet(e,t){let r=e[he.Symbol.Columns],o=Object.keys(r).filter((i)=>t[i]!==void 0||r[i]?.onUpdateFn!==void 0),n=o.length;return C.join(o.flatMap((i,s)=>{let a=r[i],l=a.onUpdateFn?.(),u=t[i]??(oe(l,_e)?l:C.param(l,a)),d=C`${C.identifier(this.casing.getColumnCasing(a))} = ${u}`;if(s<n-1)return[d,C.raw(", ")];return[d]}))}buildUpdateQuery({table:e,set:t,where:r,returning:o,withList:n,joins:i,from:s,limit:a,orderBy:l}){let u=this.buildWithCTE(n),d=this.buildUpdateSet(e,t),p=s&&C.join([C.raw(" from "),this.buildFromTable(s)]),m=this.buildJoins(i),h=o?C` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,b=r?C` where ${r}`:void 0,y=this.buildOrderBy(l),S=this.buildLimit(a);return C`${u}update ${e} set ${d}${p}${m}${b}${h}${y}${S}`}buildSelection(e,{isSingleTable:t=!1}={}){let r=e.length,o=e.flatMap(({field:n},i)=>{let s=[];if(oe(n,_e.Aliased)&&n.isSelectionField)s.push(C.identifier(n.fieldAlias));else if(oe(n,_e.Aliased)||oe(n,_e)){let a=oe(n,_e.Aliased)?n.sql:n;if(t)s.push(new _e(a.queryChunks.map((l)=>{if(oe(l,He))return C.identifier(this.casing.getColumnCasing(l));return l})));else s.push(a);if(oe(n,_e.Aliased))s.push(C` as ${C.identifier(n.fieldAlias)}`)}else if(oe(n,He)){let a=n.table[he.Symbol.Name];if(n.columnType==="SQLiteNumericBigInt")if(t)s.push(C`cast(${C.identifier(this.casing.getColumnCasing(n))} as text)`);else s.push(C`cast(${C.identifier(a)}.${C.identifier(this.casing.getColumnCasing(n))} as text)`);else if(t)s.push(C.identifier(this.casing.getColumnCasing(n)));else s.push(C`${C.identifier(a)}.${C.identifier(this.casing.getColumnCasing(n))}`)}else if(oe(n,pt)){let a=Object.entries(n._.selectedFields);if(a.length===1){let l=a[0][1],u=oe(l,_e)?l.decoder:oe(l,He)?{mapFromDriverValue:(d)=>l.mapFromDriverValue(d)}:l.sql.decoder;if(u)n._.sql.decoder=u}s.push(n)}if(i<r-1)s.push(C`, `);return s});return C.join(o)}buildJoins(e){if(!e||e.length===0)return;let t=[];if(e)for(let[r,o]of e.entries()){if(r===0)t.push(C` `);let n=o.table,i=o.on?C` on ${o.on}`:void 0;if(oe(n,At)){let s=n[At.Symbol.Name],a=n[At.Symbol.Schema],l=n[At.Symbol.OriginalName],u=s===l?void 0:o.alias;t.push(C`${C.raw(o.joinType)} join ${a?C`${C.identifier(a)}.`:void 0}${C.identifier(l)}${u&&C` ${C.identifier(u)}`}${i}`)}else t.push(C`${C.raw(o.joinType)} join ${n}${i}`);if(r<e.length-1)t.push(C` `)}return C.join(t)}buildLimit(e){return typeof e==="object"||typeof e==="number"&&e>=0?C` limit ${e}`:void 0}buildOrderBy(e){let t=[];if(e){for(let[r,o]of e.entries())if(t.push(o),r<e.length-1)t.push(C`, `)}return t.length>0?C` order by ${C.join(t)}`:void 0}buildFromTable(e){if(oe(e,he)&&e[he.Symbol.IsAlias])return C`${C`${C.identifier(e[he.Symbol.Schema]??"")}.`.if(e[he.Symbol.Schema])}${C.identifier(e[he.Symbol.OriginalName])} ${C.identifier(e[he.Symbol.Name])}`;return e}buildSelectQuery({withList:e,fields:t,fieldsFlat:r,where:o,having:n,table:i,joins:s,orderBy:a,groupBy:l,limit:u,offset:d,distinct:p,setOperators:m}){let h=r??cn(t);for(let T of h)if(oe(T.field,He)&&rs(T.field.table)!==(oe(i,pt)?i._.alias:oe(i,Vo)?i[ft].name:oe(i,_e)?void 0:rs(i))&&!((B)=>s?.some(({alias:k})=>k===(B[he.Symbol.IsAlias]?rs(B):B[he.Symbol.BaseName])))(T.field.table)){let B=rs(T.field.table);throw Error(`Your "${T.path.join("->")}" field references a column "${B}"."${T.field.name}", but the table "${B}" is not part of the query! Did you forget to join it?`)}let b=!s||s.length===0,y=this.buildWithCTE(e),S=p?C` distinct`:void 0,x=this.buildSelection(h,{isSingleTable:b}),_=this.buildFromTable(i),A=this.buildJoins(s),O=o?C` where ${o}`:void 0,L=n?C` having ${n}`:void 0,z=[];if(l){for(let[T,B]of l.entries())if(z.push(B),T<l.length-1)z.push(C`, `)}let J=z.length>0?C` group by ${C.join(z)}`:void 0,P=this.buildOrderBy(a),W=this.buildLimit(u),ee=d?C` offset ${d}`:void 0,j=C`${y}select${S} ${x} from ${_}${A}${O}${J}${L}${P}${W}${ee}`;if(m.length>0)return this.buildSetOperations(j,m);return j}buildSetOperations(e,t){let[r,...o]=t;if(!r)throw Error("Cannot pass undefined values to any set operator");if(o.length===0)return this.buildSetOperationQuery({leftSelect:e,setOperator:r});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:r}),o)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:r,rightSelect:o,limit:n,orderBy:i,offset:s}}){let a=C`${e.getSQL()} `,l=C`${o.getSQL()}`,u;if(i&&i.length>0){let h=[];for(let b of i)if(oe(b,bt))h.push(C.identifier(b.name));else if(oe(b,_e)){for(let y=0;y<b.queryChunks.length;y++){let S=b.queryChunks[y];if(oe(S,bt))b.queryChunks[y]=C.identifier(this.casing.getColumnCasing(S))}h.push(C`${b}`)}else h.push(C`${b}`);u=C` order by ${C.join(h,C`, `)}`}let d=typeof n==="object"||typeof n==="number"&&n>=0?C` limit ${n}`:void 0,p=C.raw(`${t} ${r?"all ":""}`),m=s?C` offset ${s}`:void 0;return C`${a}${p}${l}${u}${d}${m}`}buildInsertQuery({table:e,values:t,onConflict:r,returning:o,withList:n,select:i}){let s=[],a=e[he.Symbol.Columns],l=Object.entries(a).filter(([b,y])=>!y.shouldDisableInsert()),u=l.map(([,b])=>C.identifier(this.casing.getColumnCasing(b)));if(i){let b=t;if(oe(b,_e))s.push(b);else s.push(b.getSQL())}else{let b=t;s.push(C.raw("values "));for(let[y,S]of b.entries()){let x=[];for(let[_,A]of l){let O=S[_];if(O===void 0||oe(O,Ur)&&O.value===void 0){let L;if(A.default!==null&&A.default!==void 0)L=oe(A.default,_e)?A.default:C.param(A.default,A);else if(A.defaultFn!==void 0){let z=A.defaultFn();L=oe(z,_e)?z:C.param(z,A)}else if(!A.default&&A.onUpdateFn!==void 0){let z=A.onUpdateFn();L=oe(z,_e)?z:C.param(z,A)}else L=C`null`;x.push(L)}else x.push(O)}if(s.push(x),y<b.length-1)s.push(C`, `)}}let d=this.buildWithCTE(n),p=C.join(s),m=o?C` returning ${this.buildSelection(o,{isSingleTable:!0})}`:void 0,h=r?.length?C.join(r):void 0;return C`${d}insert into ${e} ${u} ${p}${h}${m}`}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:t})}buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:o,tableConfig:n,queryConfig:i,tableAlias:s,nestedQueryRelation:a,joinOn:l}){let u=[],d,p,m=[],h,b=[];if(i===!0)u=Object.entries(n.columns).map(([x,_])=>({dbKey:_.name,tsKey:x,field:oo(_,s),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let S=Object.fromEntries(Object.entries(n.columns).map(([z,J])=>[z,oo(J,s)]));if(i.where){let z=typeof i.where==="function"?i.where(S,E3()):i.where;h=z&&Fp(z,s)}let x=[],_=[];if(i.columns){let z=!1;for(let[J,P]of Object.entries(i.columns)){if(P===void 0)continue;if(J in n.columns){if(!z&&P===!0)z=!0;_.push(J)}}if(_.length>0)_=z?_.filter((J)=>i.columns?.[J]===!0):Object.keys(n.columns).filter((J)=>!_.includes(J))}else _=Object.keys(n.columns);for(let z of _){let J=n.columns[z];x.push({tsKey:z,value:J})}let A=[];if(i.with)A=Object.entries(i.with).filter((z)=>!!z[1]).map(([z,J])=>({tsKey:z,queryConfig:J,relation:n.relations[z]}));let O;if(i.extras){O=typeof i.extras==="function"?i.extras(S,{sql:C}):i.extras;for(let[z,J]of Object.entries(O))x.push({tsKey:z,value:XT(J,s)})}for(let{tsKey:z,value:J}of x)u.push({dbKey:oe(J,_e.Aliased)?J.fieldAlias:n.columns[z].name,tsKey:z,field:oe(J,He)?oo(J,s):J,relationTableTsKey:void 0,isJson:!1,selection:[]});let L=typeof i.orderBy==="function"?i.orderBy(S,k3()):i.orderBy??[];if(!Array.isArray(L))L=[L];m=L.map((z)=>{if(oe(z,He))return oo(z,s);return Fp(z,s)}),d=i.limit,p=i.offset;for(let{tsKey:z,queryConfig:J,relation:P}of A){let W=A3(t,r,P),ee=ha(P.referencedTable),j=r[ee],T=`${s}_${z}`,B=tt(...W.fields.map((I,q)=>je(oo(W.references[q],T),oo(I,s)))),k=this.buildRelationalQuery({fullSchema:e,schema:t,tableNamesMap:r,table:e[j],tableConfig:t[j],queryConfig:oe(P,as)?J===!0?{limit:1}:{...J,limit:1}:J,tableAlias:T,joinOn:B,nestedQueryRelation:P}),R=C`(${k.sql})`.as(z);u.push({dbKey:z,tsKey:z,field:R,relationTableTsKey:j,isJson:!0,selection:k.selection})}}if(u.length===0)throw new zl({message:`No fields selected for table "${n.tsName}" ("${s}"). You need to have at least one item in "columns", "with" or "extras". If you need to select all columns, omit the "columns" key or set it to undefined.`});let y;if(h=tt(l,h),a){let S=C`json_array(${C.join(u.map(({field:A})=>oe(A,bt)?C.identifier(this.casing.getColumnCasing(A)):oe(A,_e.Aliased)?A.sql:A),C`, `)})`;if(oe(a,Up))S=C`coalesce(json_group_array(${S}), json_array())`;let x=[{dbKey:"data",tsKey:"data",field:S.as("data"),isJson:!0,relationTableTsKey:n.tsName,selection:u}];if(d!==void 0||p!==void 0||m.length>0)y=this.buildSelectQuery({table:qp(o,s),fields:{},fieldsFlat:[{path:[],field:C.raw("*")}],where:h,limit:d,offset:p,orderBy:m,setOperators:[]}),h=void 0,d=void 0,p=void 0,m=void 0;else y=qp(o,s);y=this.buildSelectQuery({table:oe(y,At)?y:new pt(y,{},s),fields:{},fieldsFlat:x.map(({field:A})=>({path:[],field:oe(A,He)?oo(A,s):A})),joins:b,where:h,limit:d,offset:p,orderBy:m,setOperators:[]})}else y=this.buildSelectQuery({table:qp(o,s),fields:{},fieldsFlat:u.map(({field:S})=>({path:[],field:oe(S,He)?oo(S,s):S})),joins:b,where:h,limit:d,offset:p,orderBy:m,setOperators:[]});return{tableTsKey:n.tsName,sql:y,selection:u}}};h$=class h$ extends Nl{static[F]="SQLiteSyncDialect";migrate(e,t,r){let o=r===void 0?"__drizzle_migrations":typeof r==="string"?"__drizzle_migrations":r.migrationsTable??"__drizzle_migrations",n=C`
|
|
426
426
|
CREATE TABLE IF NOT EXISTS ${C.identifier(o)} (
|
|
427
427
|
id SERIAL PRIMARY KEY,
|
|
@@ -747,7 +747,7 @@ printf 'REMOTE_ARTIFACT_DIR=%s\\n' "$remote_dir"
|
|
|
747
747
|
`),i}async function W8(e,t){let r=await ut(e),o=r.users.find((n)=>n.handle===t);if(!o)throw Error(`Unknown pilot user: ${t}`);return{pilot:r.pilot,user:o}}async function G8(e){let t=await age(so(cge(),"brains-ops-watchdog-smoke-")),r=so(t,"id_ed25519"),o=so(t,"known_hosts");try{let n=encodeURIComponent(`brain=${e.target.pilot.contentRepoPrefix}${e.target.user.handle}`),i=await e.fetchImpl(`https://api.hetzner.cloud/v1/servers?label_selector=${n}`,{headers:{Authorization:`Bearer ${e.environment.HCLOUD_TOKEN}`}});if(!i.ok)throw Error(`Hetzner server lookup failed with ${i.status}`);let s=lge.parse(await i.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 Ul(r,pge(e.environment.KAMAL_SSH_PRIVATE_KEY),{mode:384}),await sge(r,384);let l=await e.commandRunner("ssh-keyscan",["-T","10","-t","ed25519",a.public_net.ipv4.ip]);if(l.exitCode!==0||!l.stdout.trim())throw Error("Unable to resolve watchdog smoke SSH host key");return await Ul(o,l.stdout,{mode:384}),{temporaryRoot:t,sshKeyPath:r,knownHostsPath:o,serverIp:a.public_net.ipv4.ip,commandRunner:e.commandRunner}}catch(n){throw await uO(t,{recursive:!0,force:!0}),n}}async function lO(e,t,r){return e.commandRunner("ssh",[...Q8(e),`root@${e.serverIp}`,"bash","-s","--",t,r],{stdin:dO()})}async function uge(e,t,r){return e.commandRunner("scp",[...Q8(e),"-r",`root@${e.serverIp}:${t}/.`,r])}function Q8(e){return["-i",e.sshKeyPath,"-o","BatchMode=yes","-o","IdentitiesOnly=yes","-o","ConnectTimeout=10","-o","StrictHostKeyChecking=yes","-o",`UserKnownHostsFile=${e.knownHostsPath}`]}async function dge(e){try{return await ige(e),!0}catch{return!1}}async function Nb(e,t,r){await Promise.all([Ul(so(e,`${t}.stdout.log`),r.stdout),Ul(so(e,`${t}.stderr.log`),r.stderr)])}function pge(e){return`${e.replace(/\r\n/g,`
|
|
748
748
|
`).replace(/\\n/g,`
|
|
749
749
|
`).trimEnd()}
|
|
750
|
-
`}var J8,lge;var Lb=v(async()=>{pe();M8();Jr();nf();await U8();J8=c.object({HCLOUD_TOKEN:c.string().min(1),KAMAL_SSH_PRIVATE_KEY:c.string().min(1)}),lge=c.object({servers:c.array(c.object({status:c.string(),public_net:c.object({ipv4:c.object({ip:c.string().min(1)})})}))})});import{access as T2,chmod as WE,mkdir as ah,readFile as O2,writeFile as $2}from"fs/promises";import{dirname as MW,join as dc}from"path";import{fileURLToPath as qW}from"url";var lf={name:"@rizom/ops",version:"0.2.0-alpha.
|
|
750
|
+
`}var J8,lge;var Lb=v(async()=>{pe();M8();Jr();nf();await U8();J8=c.object({HCLOUD_TOKEN:c.string().min(1),KAMAL_SSH_PRIVATE_KEY:c.string().min(1)}),lge=c.object({servers:c.array(c.object({status:c.string(),public_net:c.object({ipv4:c.object({ip:c.string().min(1)})})}))})});import{access as T2,chmod as WE,mkdir as ah,readFile as O2,writeFile as $2}from"fs/promises";import{dirname as MW,join as dc}from"path";import{fileURLToPath as qW}from"url";var lf={name:"@rizom/ops",version:"0.2.0-alpha.730",description:"Operator CLI for managing private brain fleet registry repos",keywords:["brains","ops","cli","deploy","fleet","operator"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{"brains-ops":"./dist/brains-ops.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@libsql/client":"^0.17.4","age-encryption":"^0.3.0",yaml:"^2.9.0"},devDependencies:{"@brains/contracts":"workspace:*","@brains/deploy-support":"workspace:*","@brains/eslint-config":"workspace:*","@brains/job-queue":"workspace:*","@brains/profile":"workspace:*","@brains/site-composition":"workspace:*","@brains/test-utils":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"^1.4.0",typescript:"^7.0.2"},engines:{bun:">=1.3.3"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js",bun:"./dist/deploy.js"}},files:["dist","templates"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brains-ops#readme",main:"./dist/index.js",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brains-ops"},scripts:{build:"bun scripts/build.ts",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts",test:"bun test --timeout 20000","test:smoke":"bun run build && RUN_SMOKE_TESTS=1 bun test --timeout 60000",typecheck:"tsc --noEmit"},type:"module",types:"./dist/index.d.ts"};Yo();uc();var FW=["pilot.yaml","package.json",".env.schema",".gitignore","cohorts/cohort-1.yaml","users/alice.yaml",".github/actions/varlock-env/action.yml",".github/workflows/build.yml",".github/workflows/deploy.yml",".github/workflows/directory-sync-stress.yml",".github/workflows/health-watchdog-smoke.yml",".github/workflows/offboard.yml",".github/workflows/reconcile.yml",".github/workflows/upgrade.yml","deploy/Dockerfile","deploy/kamal/deploy.yml","deploy/scripts/helpers.ts","deploy/scripts/create-predeploy-backup.ts","deploy/scripts/install-health-watchdog.ts","deploy/scripts/provision-server.ts","deploy/scripts/pull-local-models.ts","deploy/scripts/update-dns.ts","deploy/scripts/write-ssh-key.ts","deploy/scripts/decrypt-user-secrets.ts","deploy/scripts/validate-secrets.ts","deploy/scripts/write-kamal-secrets.ts","deploy/scripts/resolve-user-config.ts","deploy/scripts/resolve-missing-images.ts","deploy/scripts/verify-runtime-image.ts","deploy/scripts/resolve-deploy-handles.ts","deploy/scripts/sync-content-repo.ts",".kamal/hooks/pre-deploy","docs/onboarding-checklist.md","docs/canonical-crossover-record.md","docs/operator-playbook.md","docs/user-onboarding.md","README.md"],GE=new Set([".kamal/hooks/pre-deploy"]),KW=new Set(["cohorts/cohort-1.yaml","users/alice.yaml","docs/canonical-crossover-record.md"]),JW=qW(new URL("../templates/rover-pilot/",import.meta.url));function mo(e){return(t)=>t.includes(e)}function HW(e){return vO.find((t)=>e===`deploy/scripts/${t}`)}function QE(e){return e.replace(/\n {2}secret:\n(?: {4}- .*\n)+\nvolumes:\n/,`
|
|
751
751
|
secret:
|
|
752
752
|
- __DYNAMIC_SECRETS__
|
|
753
753
|
|