@sylphx/flow 0.2.9 → 0.2.11

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.
@@ -0,0 +1,23 @@
1
+ import{wa as l1}from"./chunk-51kpynby.js";import{Rb as g6,Sb as f2,Ub as k2}from"./chunk-f9yb2zk3.js";var WX=f2((z2)=>{var CZ=z2&&z2.__createBinding||(Object.create?function(X,$,Z,Y){if(Y===void 0)Y=Z;var G=Object.getOwnPropertyDescriptor($,Z);if(!G||("get"in G?!$.__esModule:G.writable||G.configurable))G={enumerable:!0,get:function(){return $[Z]}};Object.defineProperty(X,Y,G)}:function(X,$,Z,Y){if(Y===void 0)Y=Z;X[Y]=$[Z]}),hZ=z2&&z2.__setModuleDefault||(Object.create?function(X,$){Object.defineProperty(X,"default",{enumerable:!0,value:$})}:function(X,$){X.default=$}),_X=z2&&z2.__importStar||function(X){if(X&&X.__esModule)return X;var $={};if(X!=null){for(var Z in X)if(Z!=="default"&&Object.prototype.hasOwnProperty.call(X,Z))CZ($,X,Z)}return hZ($,X),$};Object.defineProperty(z2,"__esModule",{value:!0});z2.load=z2.currentTarget=void 0;var fZ=_X(k2("path")),qZ=_X(k2("fs"));function yZ(){let X=null;switch(process.platform){case"android":switch(process.arch){case"arm":return"android-arm-eabi";case"arm64":return"android-arm64"}X="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"}X="Windows";break;case"darwin":switch(process.arch){case"x64":return"darwin-x64";case"arm64":return"darwin-arm64"}X="macOS";break;case"linux":switch(process.arch){case"x64":case"arm64":return SZ()?`linux-${process.arch}-gnu`:`linux-${process.arch}-musl`;case"arm":return"linux-arm-gnueabihf"}X="Linux";break;case"freebsd":if(process.arch==="x64")return"freebsd-x64";X="FreeBSD";break}if(X)throw Error(`Neon: unsupported ${X} architecture: ${process.arch}`);throw Error(`Neon: unsupported system: ${process.platform}`)}z2.currentTarget=yZ;function SZ(){let X=process.report?.getReport();if(typeof X!=="object"||!X||!("header"in X))return!1;let $=X.header;return typeof $==="object"&&!!$&&"glibcVersionRuntime"in $}function pZ(X){let $=fZ.join(X,"index.node");return qZ.existsSync($)?k2($):null}z2.load=pZ});var OX=f2((ZW,HX)=>{var zX=()=>process.platform==="linux",p6=null,bZ=()=>{if(!p6)p6=zX()&&process.report?process.report.getReport():{};return p6};HX.exports={isLinux:zX,getReport:bZ}});var UX=f2((YW,AX)=>{var DX=k2("fs"),gZ=(X)=>DX.readFileSync(X,"utf-8"),dZ=(X)=>new Promise(($,Z)=>{DX.readFile(X,"utf-8",(Y,G)=>{if(Y)Z(Y);else $(G)})});AX.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:gZ,readFile:dZ}});var LX=f2((GW,BX)=>{var FX=k2("child_process"),{isLinux:U1,getReport:KX}=OX(),{LDD_PATH:q0,readFile:EX,readFileSync:RX}=UX(),M2,N2,q2="",MX=()=>{if(!q2)return new Promise((X)=>{FX.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",($,Z)=>{q2=$?" ":Z,X(q2)})});return q2},NX=()=>{if(!q2)try{q2=FX.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(X){q2=" "}return q2},j2="glibc",IX=/GLIBC\s(\d+\.\d+)/,i2="musl",mZ=j2.toUpperCase(),uZ=i2.toLowerCase(),cZ=(X)=>X.includes("libc.musl-")||X.includes("ld-musl-"),xX=()=>{let X=KX();if(X.header&&X.header.glibcVersionRuntime)return j2;if(Array.isArray(X.sharedObjects)){if(X.sharedObjects.some(cZ))return i2}return null},wX=(X)=>{let[$,Z]=X.split(/[\r\n]+/);if($&&$.includes(j2))return j2;if(Z&&Z.includes(i2))return i2;return null},PX=(X)=>{if(X.includes(uZ))return i2;if(X.includes(mZ))return j2;return null},nZ=async()=>{if(M2!==void 0)return M2;M2=null;try{let X=await EX(q0);M2=PX(X)}catch(X){}return M2},oZ=()=>{if(M2!==void 0)return M2;M2=null;try{let X=RX(q0);M2=PX(X)}catch(X){}return M2},kX=async()=>{let X=null;if(U1()){if(X=await nZ(),!X)X=xX();if(!X){let $=await MX();X=wX($)}}return X},jX=()=>{let X=null;if(U1()){if(X=oZ(),!X)X=xX();if(!X){let $=NX();X=wX($)}}return X},iZ=async()=>U1()&&await kX()!==j2,rZ=()=>U1()&&jX()!==j2,tZ=async()=>{if(N2!==void 0)return N2;N2=null;try{let $=(await EX(q0)).match(IX);if($)N2=$[1]}catch(X){}return N2},lZ=()=>{if(N2!==void 0)return N2;N2=null;try{let $=RX(q0).match(IX);if($)N2=$[1]}catch(X){}return N2},TX=()=>{let X=KX();if(X.header&&X.header.glibcVersionRuntime)return X.header.glibcVersionRuntime;return null},VX=(X)=>X.trim().split(/\s+/)[1],QX=(X)=>{let[$,Z,Y]=X.split(/[\r\n]+/);if($&&$.includes(j2))return VX($);if(Z&&Y&&Z.includes(i2))return VX(Y);return null},sZ=async()=>{let X=null;if(U1()){if(X=await tZ(),!X)X=TX();if(!X){let $=await MX();X=QX($)}}return X},aZ=()=>{let X=null;if(U1()){if(X=lZ(),!X)X=TX();if(!X){let $=NX();X=QX($)}}return X};BX.exports={GLIBC:j2,MUSL:i2,family:kX,familySync:jX,isNonGlibcLinux:iZ,isNonGlibcLinuxSync:rZ,version:sZ,versionSync:aZ}});var CX=f2((JW,vX)=>{var eZ={ALLOW:0,DENY:1};vX.exports=eZ});var fX=f2((_W,hX)=>{var b6={value:"SqliteError",writable:!0,enumerable:!1,configurable:!0};function r2(X,$,Z){if(new.target!==r2)return new r2(X,$);if(typeof $!=="string")throw TypeError("Expected second argument to be a string");Error.call(this,X),b6.value=""+X,Object.defineProperty(this,"message",b6),Error.captureStackTrace(this,r2),this.code=$,this.rawCode=Z}Object.setPrototypeOf(r2,Error);Object.setPrototypeOf(r2.prototype,Error.prototype);Object.defineProperty(r2.prototype,"name",b6);hX.exports=r2});var mX=f2((WW,y0)=>{var __dirname="/Users/kyle/rules/node_modules/libsql",{load:XY,currentTarget:$Y}=WX(),{familySync:qX,GLIBC:ZY,MUSL:YY}=LX();function GY(){if(process.env.LIBSQL_JS_DEV)return XY(__dirname);let X=$Y();if(qX()==ZY)switch(X){case"linux-x64-musl":X="linux-x64-gnu";break;case"linux-arm64-musl":X="linux-arm64-gnu";break}if(X==="linux-arm-gnueabihf"&&qX()==YY)X="linux-arm-musleabihf";return k2(`@libsql/${X}`)}var{databaseOpen:JY,databaseOpenWithSync:_Y,databaseInTransaction:WY,databaseInterrupt:zY,databaseClose:HY,databaseSyncSync:OY,databaseSyncUntilSync:DY,databaseExecSync:AY,databasePrepareSync:UY,databaseDefaultSafeIntegers:VY,databaseAuthorizer:FY,databaseLoadExtension:KY,databaseMaxWriteReplicationIndex:EY,statementRaw:RY,statementIsReader:MY,statementGet:yX,statementRun:SX,statementInterrupt:NY,statementRowsSync:pX,statementColumns:IY,statementSafeIntegers:xY,rowsNext:wY}=GY(),PY=CX(),bX=fX();function V1(X){if(X.libsqlError)return new bX(X.message,X.code,X.rawCode);return X}class gX{constructor(X,$){let Z=$?.encryptionCipher??"aes256cbc";if($&&$.syncUrl){var Y="";if($.syncAuth)console.warn("Warning: The `syncAuth` option is deprecated, please use `authToken` option instead."),Y=$.syncAuth;else if($.authToken)Y=$.authToken;let J=$?.encryptionKey??"",_=$?.syncPeriod??0,W=$?.readYourWrites??!0,H=$?.offline??!1,O=$?.remoteEncryptionKey??"";this.db=_Y(X,$.syncUrl,Y,Z,J,_,W,H,O)}else{let J=$?.authToken??"",_=$?.encryptionKey??"",W=$?.timeout??0,H=$?.remoteEncryptionKey??"";this.db=JY(X,J,Z,_,W,H)}this.memory=X===":memory:",this.readonly=!1,this.name="",this.open=!0;let G=this.db;Object.defineProperties(this,{inTransaction:{get(){return WY(G)}}})}sync(){return OY.call(this.db)}syncUntil(X){return DY.call(this.db,X)}prepare(X){try{let $=UY.call(this.db,X);return new dX($)}catch($){throw V1($)}}transaction(X){if(typeof X!=="function")throw TypeError("Expected first argument to be a function");let $=this,Z=(G)=>{return(...J)=>{$.exec("BEGIN "+G);try{let _=X(...J);return $.exec("COMMIT"),_}catch(_){throw $.exec("ROLLBACK"),_}}},Y={default:{value:Z("")},deferred:{value:Z("DEFERRED")},immediate:{value:Z("IMMEDIATE")},exclusive:{value:Z("EXCLUSIVE")},database:{value:this,enumerable:!0}};return Object.defineProperties(Y.default.value,Y),Object.defineProperties(Y.deferred.value,Y),Object.defineProperties(Y.immediate.value,Y),Object.defineProperties(Y.exclusive.value,Y),Y.default.value}pragma(X,$){if($==null)$={};if(typeof X!=="string")throw TypeError("Expected first argument to be a string");if(typeof $!=="object")throw TypeError("Expected second argument to be an options object");let Z=$.simple,Y=this.prepare(`PRAGMA ${X}`,this,!0);return Z?Y.pluck().get():Y.all()}backup(X,$){throw Error("not implemented")}serialize(X){throw Error("not implemented")}function(X,$,Z){if($==null)$={};if(typeof $==="function")Z=$,$={};if(typeof X!=="string")throw TypeError("Expected first argument to be a string");if(typeof Z!=="function")throw TypeError("Expected last argument to be a function");if(typeof $!=="object")throw TypeError("Expected second argument to be an options object");if(!X)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}aggregate(X,$){if(typeof X!=="string")throw TypeError("Expected first argument to be a string");if(typeof $!=="object"||$===null)throw TypeError("Expected second argument to be an options object");if(!X)throw TypeError("User-defined function name cannot be an empty string");throw Error("not implemented")}table(X,$){if(typeof X!=="string")throw TypeError("Expected first argument to be a string");if(!X)throw TypeError("Virtual table module name cannot be an empty string");throw Error("not implemented")}authorizer(X){FY.call(this.db,X)}loadExtension(...X){KY.call(this.db,...X)}maxWriteReplicationIndex(){return EY.call(this.db)}exec(X){try{AY.call(this.db,X)}catch($){throw V1($)}}interrupt(){zY.call(this.db)}close(){HY.call(this.db),this.open=!1}defaultSafeIntegers(X){return VY.call(this.db,X??!0),this}unsafeMode(...X){throw Error("not implemented")}}class dX{constructor(X){this.stmt=X,this.pluckMode=!1}raw(X){return RY.call(this.stmt,X??!0),this}pluck(X){return this.pluckMode=X??!0,this}get reader(){return MY.call(this.stmt)}run(...X){try{if(X.length==1&&typeof X[0]==="object")return SX.call(this.stmt,X[0]);else return SX.call(this.stmt,X.flat())}catch($){throw V1($)}}get(...X){try{if(X.length==1&&typeof X[0]==="object")return yX.call(this.stmt,X[0]);else return yX.call(this.stmt,X.flat())}catch($){throw V1($)}}iterate(...X){var $=void 0;if(X.length==1&&typeof X[0]==="object")$=pX.call(this.stmt,X[0]);else $=pX.call(this.stmt,X.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)wY.call($,this.nextRows),this.nextRowIndex=0;let Y=this.nextRows[this.nextRowIndex];if(this.nextRows[this.nextRowIndex]=void 0,!Y)return{done:!0};return this.nextRowIndex++,{value:Y,done:!1}}catch(Y){throw V1(Y)}},[Symbol.iterator](){return this}}}all(...X){try{let $=[];for(let Z of this.iterate(...X))if(this.pluckMode)$.push(Z[Object.keys(Z)[0]]);else $.push(Z);return $}catch($){throw V1($)}}interrupt(){NY.call(this.stmt)}columns(){return IY.call(this.stmt)}safeIntegers(X){return xY.call(this.stmt,X??!0),this}}y0.exports=gX;y0.exports.Authorization=PY;y0.exports.SqliteError=bX});var Z4=f2((AH,Q$)=>{function n7(X){var $=0,Z=[];function Y(){if($--,$<X)G()}function G(){var H=Z.shift();if(W.queue=Z.length,H)_(H.fn).then(H.resolve).catch(H.reject)}function J(H){return new Promise(function(O,A){Z.push({fn:H,resolve:O,reject:A}),W.queue=Z.length})}function _(H){$++;try{return Promise.resolve(H()).then(function(O){return Y(),O},function(O){throw Y(),O})}catch(O){return Y(),Promise.reject(O)}}var W=function(H){if($>=X)return J(H);else return _(H)};return W}function o7(X,$){var Z=!1,Y=this;return Promise.all(X.map(function(){var G=arguments;return Y(function(){if(!Z)return $.apply(void 0,G).catch(function(J){throw Z=!0,J})})}))}function T$(X){return X.queue=0,X.map=o7,X}Q$.exports=function(X){if(X)return T$(n7(X));else return T$(function($){return $()})}});import{join as zG}from"node:path";import{homedir as HG}from"node:os";var D=Symbol.for("drizzle:entityKind");function U(X,$){if(!X||typeof X!=="object")return!1;if(X instanceof $)return!0;if(!Object.prototype.hasOwnProperty.call($,D))throw Error(`Class "${$.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 Z=Object.getPrototypeOf(X).constructor;if(Z)while(Z){if(D in Z&&Z[D]===$[D])return!0;Z=Object.getPrototypeOf(Z)}return!1}class T{constructor(X,$){this.table=X,this.config=$,this.name=$.name,this.keyAsName=$.keyAsName,this.notNull=$.notNull,this.default=$.default,this.defaultFn=$.defaultFn,this.onUpdateFn=$.onUpdateFn,this.hasDefault=$.hasDefault,this.primary=$.primaryKey,this.isUnique=$.isUnique,this.uniqueName=$.uniqueName,this.uniqueType=$.uniqueType,this.dataType=$.dataType,this.columnType=$.columnType,this.generated=$.generated,this.generatedIdentity=$.generatedIdentity}static[D]="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(X){return X}mapToDriverValue(X){return X}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class Z6{static[D]="ColumnBuilder";config;constructor(X,$,Z){this.config={name:X,keyAsName:X==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:$,columnType:Z,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(X){return this.config.default=X,this.config.hasDefault=!0,this}$defaultFn(X){return this.config.defaultFn=X,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(X){return this.config.onUpdateFn=X,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(X){if(this.config.name!=="")return;this.config.name=X}}var $2=Symbol.for("drizzle:Name");function D4(X,...$){return X(...$)}function A4(X,$){return`${X[$2]}_${$.join("_")}_unique`}class L1 extends T{constructor(X,$){if(!$.uniqueName)$.uniqueName=A4(X,[$.name]);super(X,$);this.table=X}static[D]="PgColumn"}class a$ extends L1{static[D]="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(X){return this.indexConfig.opClass=X,this}}class e$ extends L1{static[D]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(X,$){super(X,$);this.enum=$.enum}getSQLType(){return this.enum.enumName}}var U4=Symbol.for("drizzle:isPgEnum");function V4(X){return!!X&&typeof X==="function"&&U4 in X&&X[U4]===!0}class XZ extends L1{static[D]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(X,$){super(X,$);this.enum=$.enum}getSQLType(){return this.enum.enumName}}class d{static[D]="Subquery";constructor(X,$,Z,Y=!1,G=[]){this._={brand:"Subquery",sql:X,selectedFields:$,alias:Z,isWith:Y,usedTables:G}}}class v1 extends d{static[D]="WithSubquery"}var F4="0.44.7";var Y6,G6,K4={startActiveSpan(X,$){if(!Y6)return $();if(!G6)G6=Y6.trace.getTracer("drizzle-orm",F4);return D4((Z,Y)=>Y.startActiveSpan(X,(G)=>{try{return $(G)}catch(J){throw G.setStatus({code:Z.SpanStatusCode.ERROR,message:J instanceof Error?J.message:"Unknown error"}),J}finally{G.end()}}),Y6,G6)}};var q=Symbol.for("drizzle:ViewBaseConfig");var K0=Symbol.for("drizzle:Schema"),E0=Symbol.for("drizzle:Columns"),E4=Symbol.for("drizzle:ExtraConfigColumns"),J6=Symbol.for("drizzle:OriginalName"),_6=Symbol.for("drizzle:BaseName"),C1=Symbol.for("drizzle:IsAlias"),R4=Symbol.for("drizzle:ExtraConfigBuilder"),$Z=Symbol.for("drizzle:IsDrizzleTable");class F{static[D]="Table";static Symbol={Name:$2,Schema:K0,OriginalName:J6,Columns:E0,ExtraConfigColumns:E4,BaseName:_6,IsAlias:C1,ExtraConfigBuilder:R4};[$2];[J6];[K0];[E0];[E4];[_6];[C1]=!1;[$Z]=!0;[R4]=void 0;constructor(X,$,Z){this[$2]=this[J6]=X,this[K0]=$,this[_6]=Z}}function L2(X){return X[$2]}function m2(X){return`${X[K0]??"public"}.${X[$2]}`}function W6(X){return X!==null&&X!==void 0&&typeof X.getSQL==="function"}function ZZ(X){let $={sql:"",params:[]};for(let Z of X)if($.sql+=Z.sql,$.params.push(...Z.params),Z.typings?.length){if(!$.typings)$.typings=[];$.typings.push(...Z.typings)}return $}class n{static[D]="StringChunk";value;constructor(X){this.value=Array.isArray(X)?X:[X]}getSQL(){return new K([this])}}class K{constructor(X){this.queryChunks=X;for(let $ of X)if(U($,F)){let Z=$[F.Symbol.Schema];this.usedTables.push(Z===void 0?$[F.Symbol.Name]:Z+"."+$[F.Symbol.Name])}}static[D]="SQL";decoder=N4;shouldInlineParams=!1;usedTables=[];append(X){return this.queryChunks.push(...X.queryChunks),this}toQuery(X){return K4.startActiveSpan("drizzle.buildSQL",($)=>{let Z=this.buildQueryFromSourceParams(this.queryChunks,X);return $?.setAttributes({"drizzle.query.text":Z.sql,"drizzle.query.params":JSON.stringify(Z.params)}),Z})}buildQueryFromSourceParams(X,$){let Z=Object.assign({},$,{inlineParams:$.inlineParams||this.shouldInlineParams,paramStartIndex:$.paramStartIndex||{value:0}}),{casing:Y,escapeName:G,escapeParam:J,prepareTyping:_,inlineParams:W,paramStartIndex:H}=Z;return ZZ(X.map((O)=>{if(U(O,n))return{sql:O.value.join(""),params:[]};if(U(O,R0))return{sql:G(O.value),params:[]};if(O===void 0)return{sql:"",params:[]};if(Array.isArray(O)){let A=[new n("(")];for(let[E,V]of O.entries())if(A.push(V),E<O.length-1)A.push(new n(", "));return A.push(new n(")")),this.buildQueryFromSourceParams(A,Z)}if(U(O,K))return this.buildQueryFromSourceParams(O.queryChunks,{...Z,inlineParams:W||O.shouldInlineParams});if(U(O,F)){let A=O[F.Symbol.Schema],E=O[F.Symbol.Name];return{sql:A===void 0||O[C1]?G(E):G(A)+"."+G(E),params:[]}}if(U(O,T)){let A=Y.getColumnCasing(O);if($.invokeSource==="indexes")return{sql:G(A),params:[]};let E=O.table[F.Symbol.Schema];return{sql:O.table[C1]||E===void 0?G(O.table[F.Symbol.Name])+"."+G(A):G(E)+"."+G(O.table[F.Symbol.Name])+"."+G(A),params:[]}}if(U(O,_2)){let A=O[q].schema,E=O[q].name;return{sql:A===void 0||O[q].isAlias?G(E):G(A)+"."+G(E),params:[]}}if(U(O,Z2)){if(U(O.value,v2))return{sql:J(H.value++,O),params:[O],typings:["none"]};let A=O.value===null?null:O.encoder.mapToDriverValue(O.value);if(U(A,K))return this.buildQueryFromSourceParams([A],Z);if(W)return{sql:this.mapInlineParam(A,Z),params:[]};let E=["none"];if(_)E=[_(O.encoder)];return{sql:J(H.value++,A),params:[A],typings:E}}if(U(O,v2))return{sql:J(H.value++,O),params:[O],typings:["none"]};if(U(O,K.Aliased)&&O.fieldAlias!==void 0)return{sql:G(O.fieldAlias),params:[]};if(U(O,d)){if(O._.isWith)return{sql:G(O._.alias),params:[]};return this.buildQueryFromSourceParams([new n("("),O._.sql,new n(") "),new R0(O._.alias)],Z)}if(V4(O)){if(O.schema)return{sql:G(O.schema)+"."+G(O.enumName),params:[]};return{sql:G(O.enumName),params:[]}}if(W6(O)){if(O.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([O.getSQL()],Z);return this.buildQueryFromSourceParams([new n("("),O.getSQL(),new n(")")],Z)}if(W)return{sql:this.mapInlineParam(O,Z),params:[]};return{sql:J(H.value++,O),params:[O],typings:["none"]}}))}mapInlineParam(X,{escapeString:$}){if(X===null)return"null";if(typeof X==="number"||typeof X==="boolean")return X.toString();if(typeof X==="string")return $(X);if(typeof X==="object"){let Z=X.toString();if(Z==="[object Object]")return $(JSON.stringify(X));return $(Z)}throw Error("Unexpected param value: "+X)}getSQL(){return this}as(X){if(X===void 0)return this;return new K.Aliased(this,X)}mapWith(X){return this.decoder=typeof X==="function"?{mapFromDriverValue:X}:X,this}inlineParams(){return this.shouldInlineParams=!0,this}if(X){return X?this:void 0}}class R0{constructor(X){this.value=X}static[D]="Name";brand;getSQL(){return new K([this])}}function M4(X){return typeof X==="object"&&X!==null&&"mapToDriverValue"in X&&typeof X.mapToDriverValue==="function"}var N4={mapFromDriverValue:(X)=>X},I4={mapToDriverValue:(X)=>X},oG={...N4,...I4};class Z2{constructor(X,$=I4){this.value=X,this.encoder=$}static[D]="Param";brand;getSQL(){return new K([this])}}function z(X,...$){let Z=[];if($.length>0||X.length>0&&X[0]!=="")Z.push(new n(X[0]));for(let[Y,G]of $.entries())Z.push(G,new n(X[Y+1]));return new K(Z)}((X)=>{function $(){return new K([])}X.empty=$;function Z(H){return new K(H)}X.fromList=Z;function Y(H){return new K([new n(H)])}X.raw=Y;function G(H,O){let A=[];for(let[E,V]of H.entries()){if(E>0&&O!==void 0)A.push(O);A.push(V)}return new K(A)}X.join=G;function J(H){return new R0(H)}X.identifier=J;function _(H){return new v2(H)}X.placeholder=_;function W(H,O){return new Z2(H,O)}X.param=W})(z||(z={}));((X)=>{class ${constructor(Z,Y){this.sql=Z,this.fieldAlias=Y}static[D]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new $(this.sql,this.fieldAlias)}}X.Aliased=$})(K||(K={}));class v2{constructor(X){this.name=X}static[D]="Placeholder";getSQL(){return new K([this])}}function h1(X,$){return X.map((Z)=>{if(U(Z,v2)){if(!(Z.name in $))throw Error(`No value for placeholder "${Z.name}" was provided`);return $[Z.name]}if(U(Z,Z2)&&U(Z.value,v2)){if(!(Z.value.name in $))throw Error(`No value for placeholder "${Z.value.name}" was provided`);return Z.encoder.mapToDriverValue($[Z.value.name])}return Z})}var YZ=Symbol.for("drizzle:IsDrizzleView");class _2{static[D]="View";[q];[YZ]=!0;constructor({name:X,schema:$,selectedFields:Z,query:Y}){this[q]={name:X,originalName:X,schema:$,selectedFields:Z,query:Y,isExisting:!Y,isAlias:!1}}getSQL(){return new K([this])}}T.prototype.getSQL=function(){return new K([this])};F.prototype.getSQL=function(){return new K([this])};d.prototype.getSQL=function(){return new K([this])};class Z1{constructor(X){this.table=X}static[D]="ColumnAliasProxyHandler";get(X,$){if($==="table")return this.table;return X[$]}}class f1{constructor(X,$){this.alias=X,this.replaceOriginalName=$}static[D]="TableAliasProxyHandler";get(X,$){if($===F.Symbol.IsAlias)return!0;if($===F.Symbol.Name)return this.alias;if(this.replaceOriginalName&&$===F.Symbol.OriginalName)return this.alias;if($===q)return{...X[q],name:this.alias,isAlias:!0};if($===F.Symbol.Columns){let Y=X[F.Symbol.Columns];if(!Y)return Y;let G={};return Object.keys(Y).map((J)=>{G[J]=new Proxy(Y[J],new Z1(new Proxy(X,this)))}),G}let Z=X[$];if(U(Z,T))return new Proxy(Z,new Z1(new Proxy(X,this)));return Z}}function M0(X,$){return new Proxy(X,new f1($,!1))}function K2(X,$){return new Proxy(X,new Z1(new Proxy(X.table,new f1($,!1))))}function z6(X,$){return new K.Aliased(q1(X.sql,$),X.fieldAlias)}function q1(X,$){return z.join(X.queryChunks.map((Z)=>{if(U(Z,T))return K2(Z,$);if(U(Z,K))return q1(Z,$);if(U(Z,K.Aliased))return z6(Z,$);return Z}))}class Y1 extends Error{static[D]="DrizzleError";constructor({message:X,cause:$}){super(X);this.name="DrizzleError",this.cause=$}}class P2 extends Error{constructor(X,$,Z){super(`Failed query: ${X}
2
+ params: ${$}`);if(this.query=X,this.params=$,this.cause=Z,Error.captureStackTrace(this,P2),Z)this.cause=Z}}class H6 extends Y1{static[D]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class x4{static[D]="ConsoleLogWriter";write(X){console.log(X)}}class O6{static[D]="DefaultLogger";writer;constructor(X){this.writer=X?.writer??new x4}logQuery(X,$){let Z=$.map((G)=>{try{return JSON.stringify(G)}catch{return String(G)}}),Y=Z.length?` -- params: [${Z.join(", ")}]`:"";this.writer.write(`Query: ${X}${Y}`)}}class D6{static[D]="NoopLogger";logQuery(){}}class s{static[D]="QueryPromise";[Symbol.toStringTag]="QueryPromise";catch(X){return this.then(void 0,X)}finally(X){return this.then(($)=>{return X?.(),$},($)=>{throw X?.(),$})}then(X,$){return this.execute().then(X,$)}}function A6(X,$,Z){let Y={},G=X.reduce((J,{path:_,field:W},H)=>{let O;if(U(W,T))O=W;else if(U(W,K))O=W.decoder;else O=W.sql.decoder;let A=J;for(let[E,V]of _.entries())if(E<_.length-1){if(!(V in A))A[V]={};A=A[V]}else{let R=$[H],M=A[V]=R===null?null:O.mapFromDriverValue(R);if(Z&&U(W,T)&&_.length===2){let x=_[0];if(!(x in Y))Y[x]=M===null?L2(W.table):!1;else if(typeof Y[x]==="string"&&Y[x]!==L2(W.table))Y[x]=!1}}return J},{});if(Z&&Object.keys(Y).length>0){for(let[J,_]of Object.entries(Y))if(typeof _==="string"&&!Z[_])G[J]=null}return G}function W2(X,$){return Object.entries(X).reduce((Z,[Y,G])=>{if(typeof Y!=="string")return Z;let J=$?[...$,Y]:[Y];if(U(G,T)||U(G,K)||U(G,K.Aliased))Z.push({path:J,field:G});else if(U(G,F))Z.push(...W2(G[F.Symbol.Columns],J));else Z.push(...W2(G,J));return Z},[])}function y1(X,$){let Z=Object.keys(X),Y=Object.keys($);if(Z.length!==Y.length)return!1;for(let[G,J]of Z.entries())if(J!==Y[G])return!1;return!0}function N0(X,$){let Z=Object.entries($).filter(([,Y])=>Y!==void 0).map(([Y,G])=>{if(U(G,K)||U(G,T))return[Y,G];else return[Y,new Z2(G,X[F.Symbol.Columns][Y])]});if(Z.length===0)throw Error("No values to set");return Object.fromEntries(Z)}function w4(X,$){for(let Z of $)for(let Y of Object.getOwnPropertyNames(Z.prototype)){if(Y==="constructor")continue;Object.defineProperty(X.prototype,Y,Object.getOwnPropertyDescriptor(Z.prototype,Y)||Object.create(null))}}function P4(X){return X[F.Symbol.Columns]}function S1(X){return U(X,d)?X._.alias:U(X,_2)?X[q].name:U(X,K)?void 0:X[F.Symbol.IsAlias]?X[F.Symbol.Name]:X[F.Symbol.BaseName]}function E2(X,$){return{name:typeof X==="string"&&X.length>0?X:"",config:typeof X==="object"?X:$}}function k4(X){if(typeof X!=="object"||X===null)return!1;if(X.constructor.name!=="Object")return!1;if("logger"in X){let $=typeof X.logger;if($!=="boolean"&&($!=="object"||typeof X.logger.logQuery!=="function")&&$!=="undefined")return!1;return!0}if("schema"in X){let $=typeof X.schema;if($!=="object"&&$!=="undefined")return!1;return!0}if("casing"in X){let $=typeof X.casing;if($!=="string"&&$!=="undefined")return!1;return!0}if("mode"in X){if(X.mode!=="default"||X.mode!=="planetscale"||X.mode!==void 0)return!1;return!0}if("connection"in X){let $=typeof X.connection;if($!=="string"&&$!=="object"&&$!=="undefined")return!1;return!0}if("client"in X){let $=typeof X.client;if($!=="object"&&$!=="function"&&$!=="undefined")return!1;return!0}if(Object.keys(X).length===0)return!0;return!1}var U6=typeof TextDecoder>"u"?null:new TextDecoder;var j4=Symbol.for("drizzle:PgInlineForeignKeys"),T4=Symbol.for("drizzle:EnableRLS");class V6 extends F{static[D]="PgTable";static Symbol=Object.assign({},F.Symbol,{InlineForeignKeys:j4,EnableRLS:T4});[j4]=[];[T4]=!1;[F.Symbol.ExtraConfigBuilder]=void 0;[F.Symbol.ExtraConfigColumns]={}}class F6{static[D]="PgPrimaryKeyBuilder";columns;name;constructor(X,$){this.columns=X,this.name=$}build(X){return new Q4(X,this.columns,this.name)}}class Q4{constructor(X,$,Z){this.table=X,this.columns=$,this.name=Z}static[D]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[V6.Symbol.Name]}_${this.columns.map((X)=>X.name).join("_")}_pk`}}function a(X,$){if(M4($)&&!W6(X)&&!U(X,Z2)&&!U(X,v2)&&!U(X,T)&&!U(X,F)&&!U(X,_2))return new Z2(X,$);return X}var r=(X,$)=>{return z`${X} = ${a($,X)}`},B4=(X,$)=>{return z`${X} <> ${a($,X)}`};function p1(...X){let $=X.filter((Z)=>Z!==void 0);if($.length===0)return;if($.length===1)return new K($);return new K([new n("("),z.join($,new n(" and ")),new n(")")])}function L4(...X){let $=X.filter((Z)=>Z!==void 0);if($.length===0)return;if($.length===1)return new K($);return new K([new n("("),z.join($,new n(" or ")),new n(")")])}function v4(X){return z`not ${X}`}var C4=(X,$)=>{return z`${X} > ${a($,X)}`},h4=(X,$)=>{return z`${X} >= ${a($,X)}`},f4=(X,$)=>{return z`${X} < ${a($,X)}`},q4=(X,$)=>{return z`${X} <= ${a($,X)}`};function u2(X,$){if(Array.isArray($)){if($.length===0)return z`false`;return z`${X} in ${$.map((Z)=>a(Z,X))}`}return z`${X} in ${a($,X)}`}function y4(X,$){if(Array.isArray($)){if($.length===0)return z`true`;return z`${X} not in ${$.map((Z)=>a(Z,X))}`}return z`${X} not in ${a($,X)}`}function S4(X){return z`${X} is null`}function p4(X){return z`${X} is not null`}function b4(X){return z`exists ${X}`}function g4(X){return z`not exists ${X}`}function d4(X,$,Z){return z`${X} between ${a($,X)} and ${a(Z,X)}`}function m4(X,$,Z){return z`${X} not between ${a($,X)} and ${a(Z,X)}`}function I0(X,$){return z`${X} like ${$}`}function u4(X,$){return z`${X} not like ${$}`}function c4(X,$){return z`${X} ilike ${$}`}function n4(X,$){return z`${X} not ilike ${$}`}function o4(X){return z`${X} asc`}function G1(X){return z`${X} desc`}class K6{constructor(X,$,Z){this.sourceTable=X,this.referencedTable=$,this.relationName=Z,this.referencedTableName=$[F.Symbol.Name]}static[D]="Relation";referencedTableName;fieldName}class i4{constructor(X,$){this.table=X,this.config=$}static[D]="Relations"}class C2 extends K6{constructor(X,$,Z,Y){super(X,$,Z?.relationName);this.config=Z,this.isNullable=Y}static[D]="One";withFieldName(X){let $=new C2(this.sourceTable,this.referencedTable,this.config,this.isNullable);return $.fieldName=X,$}}class b1 extends K6{constructor(X,$,Z){super(X,$,Z?.relationName);this.config=Z}static[D]="Many";withFieldName(X){let $=new b1(this.sourceTable,this.referencedTable,this.config);return $.fieldName=X,$}}function r4(){return{and:p1,between:d4,eq:r,exists:b4,gt:C4,gte:h4,ilike:c4,inArray:u2,isNull:S4,isNotNull:p4,like:I0,lt:f4,lte:q4,ne:B4,not:v4,notBetween:m4,notExists:g4,notLike:u4,notIlike:n4,notInArray:y4,or:L4,sql:z}}function t4(){return{sql:z,asc:o4,desc:G1}}function l4(X,$){if(Object.keys(X).length===1&&"default"in X&&!U(X.default,F))X=X.default;let Z={},Y={},G={};for(let[J,_]of Object.entries(X))if(U(_,F)){let W=m2(_),H=Y[W];Z[W]=J,G[J]={tsName:J,dbName:_[F.Symbol.Name],schema:_[F.Symbol.Schema],columns:_[F.Symbol.Columns],relations:H?.relations??{},primaryKey:H?.primaryKey??[]};for(let A of Object.values(_[F.Symbol.Columns]))if(A.primary)G[J].primaryKey.push(A);let O=_[F.Symbol.ExtraConfigBuilder]?.(_[F.Symbol.ExtraConfigColumns]);if(O){for(let A of Object.values(O))if(U(A,F6))G[J].primaryKey.push(...A.columns)}}else if(U(_,i4)){let W=m2(_.table),H=Z[W],O=_.config($(_.table)),A;for(let[E,V]of Object.entries(O))if(H){let R=G[H];if(R.relations[E]=V,A)R.primaryKey.push(...A)}else{if(!(W in Y))Y[W]={relations:{},primaryKey:A};Y[W].relations[E]=V}}return{tables:G,tableNamesMap:Z}}function GZ(X){return function(Z,Y){return new C2(X,Z,Y,Y?.fields.reduce((G,J)=>G&&J.notNull,!0)??!1)}}function JZ(X){return function(Z,Y){return new b1(X,Z,Y)}}function s4(X,$,Z){if(U(Z,C2)&&Z.config)return{fields:Z.config.fields,references:Z.config.references};let Y=$[m2(Z.referencedTable)];if(!Y)throw Error(`Table "${Z.referencedTable[F.Symbol.Name]}" not found in schema`);let G=X[Y];if(!G)throw Error(`Table "${Y}" not found in schema`);let J=Z.sourceTable,_=$[m2(J)];if(!_)throw Error(`Table "${J[F.Symbol.Name]}" not found in schema`);let W=[];for(let H of Object.values(G.relations))if(Z.relationName&&Z!==H&&H.relationName===Z.relationName||!Z.relationName&&H.referencedTable===Z.sourceTable)W.push(H);if(W.length>1)throw Z.relationName?Error(`There are multiple relations with name "${Z.relationName}" in table "${Y}"`):Error(`There are multiple relations between "${Y}" and "${Z.sourceTable[F.Symbol.Name]}". Please specify relation name`);if(W[0]&&U(W[0],C2)&&W[0].config)return{fields:W[0].config.references,references:W[0].config.fields};throw Error(`There is not enough information to infer relation "${_}.${Z.fieldName}"`)}function a4(X){return{one:GZ(X),many:JZ(X)}}function x0(X,$,Z,Y,G=(J)=>J){let J={};for(let[_,W]of Y.entries())if(W.isJson){let H=$.relations[W.tsKey],O=Z[_],A=typeof O==="string"?JSON.parse(O):O;J[W.tsKey]=U(H,C2)?A&&x0(X,X[W.relationTableTsKey],A,W.selection,G):A.map((E)=>x0(X,X[W.relationTableTsKey],E,W.selection,G))}else{let H=G(Z[_]),O=W.field,A;if(U(O,T))A=O;else if(U(O,K))A=O.decoder;else A=O.sql.decoder;J[W.tsKey]=H===null?null:A.mapFromDriverValue(H)}return J}import{randomUUID as C0}from"node:crypto";class E6{static[D]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor(X,$){if(this.reference=()=>{let{name:Z,columns:Y,foreignColumns:G}=X();return{name:Z,columns:Y,foreignTable:G[0].table,foreignColumns:G}},$)this._onUpdate=$.onUpdate,this._onDelete=$.onDelete}onUpdate(X){return this._onUpdate=X,this}onDelete(X){return this._onDelete=X,this}build(X){return new e4(X,this)}}class e4{constructor(X,$){this.table=X,this.reference=$.reference,this.onUpdate=$._onUpdate,this.onDelete=$._onDelete}static[D]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:X,columns:$,foreignColumns:Z}=this.reference(),Y=$.map((_)=>_.name),G=Z.map((_)=>_.name),J=[this.table[$2],...Y,Z[0].table[$2],...G];return X??`${J.join("_")}_fk`}}function X8(X,$){return`${X[$2]}_${$.join("_")}_unique`}class i extends Z6{static[D]="SQLiteColumnBuilder";foreignKeyConfigs=[];references(X,$={}){return this.foreignKeyConfigs.push({ref:X,actions:$}),this}unique(X){return this.config.isUnique=!0,this.config.uniqueName=X,this}generatedAlwaysAs(X,$){return this.config.generated={as:X,type:"always",mode:$?.mode??"virtual"},this}buildForeignKeys(X,$){return this.foreignKeyConfigs.map(({ref:Z,actions:Y})=>{return((G,J)=>{let _=new E6(()=>{let W=G();return{columns:[X],foreignColumns:[W]}});if(J.onUpdate)_.onUpdate(J.onUpdate);if(J.onDelete)_.onDelete(J.onDelete);return _.build($)})(Z,Y)})}}class S extends T{constructor(X,$){if(!$.uniqueName)$.uniqueName=X8(X,[$.name]);super(X,$);this.table=X}static[D]="SQLiteColumn"}class $8 extends i{static[D]="SQLiteBigIntBuilder";constructor(X){super(X,"bigint","SQLiteBigInt")}build(X){return new Z8(X,this.config)}}class Z8 extends S{static[D]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue(X){if(typeof Buffer<"u"&&Buffer.from){let $=Buffer.isBuffer(X)?X:X instanceof ArrayBuffer?Buffer.from(X):X.buffer?Buffer.from(X.buffer,X.byteOffset,X.byteLength):Buffer.from(X);return BigInt($.toString("utf8"))}return BigInt(U6.decode(X))}mapToDriverValue(X){return Buffer.from(X.toString())}}class Y8 extends i{static[D]="SQLiteBlobJsonBuilder";constructor(X){super(X,"json","SQLiteBlobJson")}build(X){return new G8(X,this.config)}}class G8 extends S{static[D]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue(X){if(typeof Buffer<"u"&&Buffer.from){let $=Buffer.isBuffer(X)?X:X instanceof ArrayBuffer?Buffer.from(X):X.buffer?Buffer.from(X.buffer,X.byteOffset,X.byteLength):Buffer.from(X);return JSON.parse($.toString("utf8"))}return JSON.parse(U6.decode(X))}mapToDriverValue(X){return Buffer.from(JSON.stringify(X))}}class J8 extends i{static[D]="SQLiteBlobBufferBuilder";constructor(X){super(X,"buffer","SQLiteBlobBuffer")}build(X){return new _8(X,this.config)}}class _8 extends S{static[D]="SQLiteBlobBuffer";mapFromDriverValue(X){if(Buffer.isBuffer(X))return X;return Buffer.from(X)}getSQLType(){return"blob"}}function W8(X,$){let{name:Z,config:Y}=E2(X,$);if(Y?.mode==="json")return new Y8(Z);if(Y?.mode==="bigint")return new $8(Z);return new J8(Z)}class z8 extends i{static[D]="SQLiteCustomColumnBuilder";constructor(X,$,Z){super(X,"custom","SQLiteCustomColumn");this.config.fieldConfig=$,this.config.customTypeParams=Z}build(X){return new H8(X,this.config)}}class H8 extends S{static[D]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor(X,$){super(X,$);this.sqlName=$.customTypeParams.dataType($.fieldConfig),this.mapTo=$.customTypeParams.toDriver,this.mapFrom=$.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(X){return typeof this.mapFrom==="function"?this.mapFrom(X):X}mapToDriverValue(X){return typeof this.mapTo==="function"?this.mapTo(X):X}}function O8(X){return($,Z)=>{let{name:Y,config:G}=E2($,Z);return new z8(Y,G,X)}}class w0 extends i{static[D]="SQLiteBaseIntegerBuilder";constructor(X,$,Z){super(X,$,Z);this.config.autoIncrement=!1}primaryKey(X){if(X?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}}class P0 extends S{static[D]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}}class D8 extends w0{static[D]="SQLiteIntegerBuilder";constructor(X){super(X,"number","SQLiteInteger")}build(X){return new A8(X,this.config)}}class A8 extends P0{static[D]="SQLiteInteger"}class U8 extends w0{static[D]="SQLiteTimestampBuilder";constructor(X,$){super(X,"date","SQLiteTimestamp");this.config.mode=$}defaultNow(){return this.default(z`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(X){return new V8(X,this.config)}}class V8 extends P0{static[D]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue(X){if(this.config.mode==="timestamp")return new Date(X*1000);return new Date(X)}mapToDriverValue(X){let $=X.getTime();if(this.config.mode==="timestamp")return Math.floor($/1000);return $}}class F8 extends w0{static[D]="SQLiteBooleanBuilder";constructor(X,$){super(X,"boolean","SQLiteBoolean");this.config.mode=$}build(X){return new K8(X,this.config)}}class K8 extends P0{static[D]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue(X){return Number(X)===1}mapToDriverValue(X){return X?1:0}}function b(X,$){let{name:Z,config:Y}=E2(X,$);if(Y?.mode==="timestamp"||Y?.mode==="timestamp_ms")return new U8(Z,Y.mode);if(Y?.mode==="boolean")return new F8(Z,Y.mode);return new D8(Z)}class E8 extends i{static[D]="SQLiteNumericBuilder";constructor(X){super(X,"string","SQLiteNumeric")}build(X){return new R8(X,this.config)}}class R8 extends S{static[D]="SQLiteNumeric";mapFromDriverValue(X){if(typeof X==="string")return X;return String(X)}getSQLType(){return"numeric"}}class M8 extends i{static[D]="SQLiteNumericNumberBuilder";constructor(X){super(X,"number","SQLiteNumericNumber")}build(X){return new N8(X,this.config)}}class N8 extends S{static[D]="SQLiteNumericNumber";mapFromDriverValue(X){if(typeof X==="number")return X;return Number(X)}mapToDriverValue=String;getSQLType(){return"numeric"}}class I8 extends i{static[D]="SQLiteNumericBigIntBuilder";constructor(X){super(X,"bigint","SQLiteNumericBigInt")}build(X){return new x8(X,this.config)}}class x8 extends S{static[D]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}function w8(X,$){let{name:Z,config:Y}=E2(X,$),G=Y?.mode;return G==="number"?new M8(Z):G==="bigint"?new I8(Z):new E8(Z)}class P8 extends i{static[D]="SQLiteRealBuilder";constructor(X){super(X,"number","SQLiteReal")}build(X){return new k8(X,this.config)}}class k8 extends S{static[D]="SQLiteReal";getSQLType(){return"real"}}function J1(X){return new P8(X??"")}class j8 extends i{static[D]="SQLiteTextBuilder";constructor(X,$){super(X,"string","SQLiteText");this.config.enumValues=$.enum,this.config.length=$.length}build(X){return new T8(X,this.config)}}class T8 extends S{static[D]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor(X,$){super(X,$)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}}class Q8 extends i{static[D]="SQLiteTextJsonBuilder";constructor(X){super(X,"json","SQLiteTextJson")}build(X){return new B8(X,this.config)}}class B8 extends S{static[D]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue(X){return JSON.parse(X)}mapToDriverValue(X){return JSON.stringify(X)}}function I(X,$={}){let{name:Z,config:Y}=E2(X,$);if(Y.mode==="json")return new Q8(Z);return new j8(Z,Y)}class m{static[D]="SelectionProxyHandler";config;constructor(X){this.config={...X}}get(X,$){if($==="_")return{...X._,selectedFields:new Proxy(X._.selectedFields,this)};if($===q)return{...X[q],selectedFields:new Proxy(X[q].selectedFields,this)};if(typeof $==="symbol")return X[$];let Y=(U(X,d)?X._.selectedFields:U(X,_2)?X[q].selectedFields:X)[$];if(U(Y,K.Aliased)){if(this.config.sqlAliasedBehavior==="sql"&&!Y.isSelectionField)return Y.sql;let G=Y.clone();return G.isSelectionField=!0,G}if(U(Y,K)){if(this.config.sqlBehavior==="sql")return Y;throw Error(`You tried to reference "${$}" 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(U(Y,T)){if(this.config.alias)return new Proxy(Y,new Z1(new Proxy(Y.table,new f1(this.config.alias,this.config.replaceOriginalName??!1))));return Y}if(typeof Y!=="object"||Y===null)return Y;return new Proxy(Y,new m(this.config))}}function L8(){return{blob:W8,customType:O8,integer:b,numeric:w8,real:J1,text:I}}var R6=Symbol.for("drizzle:SQLiteInlineForeignKeys");class u extends F{static[D]="SQLiteTable";static Symbol=Object.assign({},F.Symbol,{InlineForeignKeys:R6});[F.Symbol.Columns];[R6]=[];[F.Symbol.ExtraConfigBuilder]=void 0}function _Z(X,$,Z,Y,G=X){let J=new u(X,Y,G),_=typeof $==="function"?$(L8()):$,W=Object.fromEntries(Object.entries(_).map(([O,A])=>{let E=A;E.setName(O);let V=E.build(J);return J[R6].push(...E.buildForeignKeys(V,J)),[O,V]})),H=Object.assign(J,W);if(H[F.Symbol.Columns]=W,H[F.Symbol.ExtraConfigColumns]=W,Z)H[u.Symbol.ExtraConfigBuilder]=Z;return H}var e=(X,$,Z)=>{return _Z(X,$,Z)};class v8{constructor(X,$){this.name=X,this.unique=$}static[D]="SQLiteIndexBuilderOn";on(...X){return new C8(this.name,X,this.unique)}}class C8{static[D]="SQLiteIndexBuilder";config;constructor(X,$,Z){this.config={name:X,columns:$,unique:Z,where:void 0}}where(X){return this.config.where=X,this}build(X){return new h8(this.config,X)}}class h8{static[D]="SQLiteIndex";config;constructor(X,$){this.config={...X,table:$}}}function f(X){return new v8(X,!1)}function N6(...X){if(X[0].columns)return new M6(X[0].columns,X[0].name);return new M6(X)}class M6{static[D]="SQLitePrimaryKeyBuilder";columns;name;constructor(X,$){this.columns=X,this.name=$}build(X){return new f8(X,this.columns,this.name)}}class f8{constructor(X,$,Z){this.table=X,this.columns=$,this.name=Z}static[D]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[u.Symbol.Name]}_${this.columns.map((X)=>X.name).join("_")}_pk`}}function D2(X){if(U(X,u))return[`${X[F.Symbol.BaseName]}`];if(U(X,d))return X._.usedTables??[];if(U(X,K))return X.usedTables??[];return[]}class k0 extends s{constructor(X,$,Z,Y){super();this.table=X,this.session=$,this.dialect=Z,this.config={table:X,withList:Y}}static[D]="SQLiteDelete";config;where(X){return this.config.where=X,this}orderBy(...X){if(typeof X[0]==="function"){let $=X[0](new Proxy(this.config.table[F.Symbol.Columns],new m({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),Z=Array.isArray($)?$:[$];this.config.orderBy=Z}else{let $=X;this.config.orderBy=$}return this}limit(X){return this.config.limit=X,this}returning(X=this.table[u.Symbol.Columns]){return this.config.returning=W2(X),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:X,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(X=!0){return this.session[X?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"delete",tables:D2(this.config.table)})}prepare(){return this._prepare(!1)}run=(X)=>{return this._prepare().run(X)};all=(X)=>{return this._prepare().all(X)};get=(X)=>{return this._prepare().get(X)};values=(X)=>{return this._prepare().values(X)};async execute(X){return this._prepare().execute(X)}$dynamic(){return this}}function WZ(X){return(X.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((Z)=>Z.toLowerCase()).join("_")}function zZ(X){return(X.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((Z,Y,G)=>{let J=G===0?Y.toLowerCase():`${Y[0].toUpperCase()}${Y.slice(1)}`;return Z+J},"")}function HZ(X){return X}class I6{static[D]="CasingCache";cache={};cachedTables={};convert;constructor(X){this.convert=X==="snake_case"?WZ:X==="camelCase"?zZ:HZ}getColumnCasing(X){if(!X.keyAsName)return X.name;let $=X.table[F.Symbol.Schema]??"public",Z=X.table[F.Symbol.OriginalName],Y=`${$}.${Z}.${X.name}`;if(!this.cache[Y])this.cacheTable(X.table);return this.cache[Y]}cacheTable(X){let $=X[F.Symbol.Schema]??"public",Z=X[F.Symbol.OriginalName],Y=`${$}.${Z}`;if(!this.cachedTables[Y]){for(let G of Object.values(X[F.Symbol.Columns])){let J=`${Y}.${G.name}`;this.cache[J]=this.convert(G.name)}this.cachedTables[Y]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class c2 extends _2{static[D]="SQLiteViewBase"}class _1{static[D]="SQLiteDialect";casing;constructor(X){this.casing=new I6(X?.casing)}escapeName(X){return`"${X}"`}escapeParam(X){return"?"}escapeString(X){return`'${X.replace(/'/g,"''")}'`}buildWithCTE(X){if(!X?.length)return;let $=[z`with `];for(let[Z,Y]of X.entries())if($.push(z`${z.identifier(Y._.alias)} as (${Y._.sql})`),Z<X.length-1)$.push(z`, `);return $.push(z` `),z.join($)}buildDeleteQuery({table:X,where:$,returning:Z,withList:Y,limit:G,orderBy:J}){let _=this.buildWithCTE(Y),W=Z?z` returning ${this.buildSelection(Z,{isSingleTable:!0})}`:void 0,H=$?z` where ${$}`:void 0,O=this.buildOrderBy(J),A=this.buildLimit(G);return z`${_}delete from ${X}${H}${W}${O}${A}`}buildUpdateSet(X,$){let Z=X[F.Symbol.Columns],Y=Object.keys(Z).filter((J)=>$[J]!==void 0||Z[J]?.onUpdateFn!==void 0),G=Y.length;return z.join(Y.flatMap((J,_)=>{let W=Z[J],H=$[J]??z.param(W.onUpdateFn(),W),O=z`${z.identifier(this.casing.getColumnCasing(W))} = ${H}`;if(_<G-1)return[O,z.raw(", ")];return[O]}))}buildUpdateQuery({table:X,set:$,where:Z,returning:Y,withList:G,joins:J,from:_,limit:W,orderBy:H}){let O=this.buildWithCTE(G),A=this.buildUpdateSet(X,$),E=_&&z.join([z.raw(" from "),this.buildFromTable(_)]),V=this.buildJoins(J),R=Y?z` returning ${this.buildSelection(Y,{isSingleTable:!0})}`:void 0,M=Z?z` where ${Z}`:void 0,x=this.buildOrderBy(H),k=this.buildLimit(W);return z`${O}update ${X} set ${A}${E}${V}${M}${R}${x}${k}`}buildSelection(X,{isSingleTable:$=!1}={}){let Z=X.length,Y=X.flatMap(({field:G},J)=>{let _=[];if(U(G,K.Aliased)&&G.isSelectionField)_.push(z.identifier(G.fieldAlias));else if(U(G,K.Aliased)||U(G,K)){let W=U(G,K.Aliased)?G.sql:G;if($)_.push(new K(W.queryChunks.map((H)=>{if(U(H,T))return z.identifier(this.casing.getColumnCasing(H));return H})));else _.push(W);if(U(G,K.Aliased))_.push(z` as ${z.identifier(G.fieldAlias)}`)}else if(U(G,T)){let W=G.table[F.Symbol.Name];if(G.columnType==="SQLiteNumericBigInt")if($)_.push(z`cast(${z.identifier(this.casing.getColumnCasing(G))} as text)`);else _.push(z`cast(${z.identifier(W)}.${z.identifier(this.casing.getColumnCasing(G))} as text)`);else if($)_.push(z.identifier(this.casing.getColumnCasing(G)));else _.push(z`${z.identifier(W)}.${z.identifier(this.casing.getColumnCasing(G))}`)}if(J<Z-1)_.push(z`, `);return _});return z.join(Y)}buildJoins(X){if(!X||X.length===0)return;let $=[];if(X)for(let[Z,Y]of X.entries()){if(Z===0)$.push(z` `);let G=Y.table,J=Y.on?z` on ${Y.on}`:void 0;if(U(G,u)){let _=G[u.Symbol.Name],W=G[u.Symbol.Schema],H=G[u.Symbol.OriginalName],O=_===H?void 0:Y.alias;$.push(z`${z.raw(Y.joinType)} join ${W?z`${z.identifier(W)}.`:void 0}${z.identifier(H)}${O&&z` ${z.identifier(O)}`}${J}`)}else $.push(z`${z.raw(Y.joinType)} join ${G}${J}`);if(Z<X.length-1)$.push(z` `)}return z.join($)}buildLimit(X){return typeof X==="object"||typeof X==="number"&&X>=0?z` limit ${X}`:void 0}buildOrderBy(X){let $=[];if(X){for(let[Z,Y]of X.entries())if($.push(Y),Z<X.length-1)$.push(z`, `)}return $.length>0?z` order by ${z.join($)}`:void 0}buildFromTable(X){if(U(X,F)&&X[F.Symbol.IsAlias])return z`${z`${z.identifier(X[F.Symbol.Schema]??"")}.`.if(X[F.Symbol.Schema])}${z.identifier(X[F.Symbol.OriginalName])} ${z.identifier(X[F.Symbol.Name])}`;return X}buildSelectQuery({withList:X,fields:$,fieldsFlat:Z,where:Y,having:G,table:J,joins:_,orderBy:W,groupBy:H,limit:O,offset:A,distinct:E,setOperators:V}){let R=Z??W2($);for(let O2 of R)if(U(O2.field,T)&&L2(O2.field.table)!==(U(J,d)?J._.alias:U(J,c2)?J[q].name:U(J,K)?void 0:L2(J))&&!((F2)=>_?.some(({alias:F0})=>F0===(F2[F.Symbol.IsAlias]?L2(F2):F2[F.Symbol.BaseName])))(O2.field.table)){let F2=L2(O2.field.table);throw Error(`Your "${O2.path.join("->")}" field references a column "${F2}"."${O2.field.name}", but the table "${F2}" is not part of the query! Did you forget to join it?`)}let M=!_||_.length===0,x=this.buildWithCTE(X),k=E?z` distinct`:void 0,C=this.buildSelection(R,{isSingleTable:M}),B=this.buildFromTable(J),L=this.buildJoins(_),x2=Y?z` where ${Y}`:void 0,J2=G?z` having ${G}`:void 0,P=[];if(H){for(let[O2,F2]of H.entries())if(P.push(F2),O2<H.length-1)P.push(z`, `)}let h=P.length>0?z` group by ${z.join(P)}`:void 0,w2=this.buildOrderBy(W),V0=this.buildLimit(O),$6=A?z` offset ${A}`:void 0,$1=z`${x}select${k} ${C} from ${B}${L}${x2}${h}${J2}${w2}${V0}${$6}`;if(V.length>0)return this.buildSetOperations($1,V);return $1}buildSetOperations(X,$){let[Z,...Y]=$;if(!Z)throw Error("Cannot pass undefined values to any set operator");if(Y.length===0)return this.buildSetOperationQuery({leftSelect:X,setOperator:Z});return this.buildSetOperations(this.buildSetOperationQuery({leftSelect:X,setOperator:Z}),Y)}buildSetOperationQuery({leftSelect:X,setOperator:{type:$,isAll:Z,rightSelect:Y,limit:G,orderBy:J,offset:_}}){let W=z`${X.getSQL()} `,H=z`${Y.getSQL()}`,O;if(J&&J.length>0){let R=[];for(let M of J)if(U(M,S))R.push(z.identifier(M.name));else if(U(M,K)){for(let x=0;x<M.queryChunks.length;x++){let k=M.queryChunks[x];if(U(k,S))M.queryChunks[x]=z.identifier(this.casing.getColumnCasing(k))}R.push(z`${M}`)}else R.push(z`${M}`);O=z` order by ${z.join(R,z`, `)}`}let A=typeof G==="object"||typeof G==="number"&&G>=0?z` limit ${G}`:void 0,E=z.raw(`${$} ${Z?"all ":""}`),V=_?z` offset ${_}`:void 0;return z`${W}${E}${H}${O}${A}${V}`}buildInsertQuery({table:X,values:$,onConflict:Z,returning:Y,withList:G,select:J}){let _=[],W=X[F.Symbol.Columns],H=Object.entries(W).filter(([M,x])=>!x.shouldDisableInsert()),O=H.map(([,M])=>z.identifier(this.casing.getColumnCasing(M)));if(J){let M=$;if(U(M,K))_.push(M);else _.push(M.getSQL())}else{let M=$;_.push(z.raw("values "));for(let[x,k]of M.entries()){let C=[];for(let[B,L]of H){let x2=k[B];if(x2===void 0||U(x2,Z2)&&x2.value===void 0){let J2;if(L.default!==null&&L.default!==void 0)J2=U(L.default,K)?L.default:z.param(L.default,L);else if(L.defaultFn!==void 0){let P=L.defaultFn();J2=U(P,K)?P:z.param(P,L)}else if(!L.default&&L.onUpdateFn!==void 0){let P=L.onUpdateFn();J2=U(P,K)?P:z.param(P,L)}else J2=z`null`;C.push(J2)}else C.push(x2)}if(_.push(C),x<M.length-1)_.push(z`, `)}}let A=this.buildWithCTE(G),E=z.join(_),V=Y?z` returning ${this.buildSelection(Y,{isSingleTable:!0})}`:void 0,R=Z?.length?z.join(Z):void 0;return z`${A}insert into ${X} ${O} ${E}${R}${V}`}sqlToQuery(X,$){return X.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,invokeSource:$})}buildRelationalQuery({fullSchema:X,schema:$,tableNamesMap:Z,table:Y,tableConfig:G,queryConfig:J,tableAlias:_,nestedQueryRelation:W,joinOn:H}){let O=[],A,E,V=[],R,M=[];if(J===!0)O=Object.entries(G.columns).map(([C,B])=>({dbKey:B.name,tsKey:C,field:K2(B,_),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let k=Object.fromEntries(Object.entries(G.columns).map(([P,h])=>[P,K2(h,_)]));if(J.where){let P=typeof J.where==="function"?J.where(k,r4()):J.where;R=P&&q1(P,_)}let C=[],B=[];if(J.columns){let P=!1;for(let[h,w2]of Object.entries(J.columns)){if(w2===void 0)continue;if(h in G.columns){if(!P&&w2===!0)P=!0;B.push(h)}}if(B.length>0)B=P?B.filter((h)=>J.columns?.[h]===!0):Object.keys(G.columns).filter((h)=>!B.includes(h))}else B=Object.keys(G.columns);for(let P of B){let h=G.columns[P];C.push({tsKey:P,value:h})}let L=[];if(J.with)L=Object.entries(J.with).filter((P)=>!!P[1]).map(([P,h])=>({tsKey:P,queryConfig:h,relation:G.relations[P]}));let x2;if(J.extras){x2=typeof J.extras==="function"?J.extras(k,{sql:z}):J.extras;for(let[P,h]of Object.entries(x2))C.push({tsKey:P,value:z6(h,_)})}for(let{tsKey:P,value:h}of C)O.push({dbKey:U(h,K.Aliased)?h.fieldAlias:G.columns[P].name,tsKey:P,field:U(h,T)?K2(h,_):h,relationTableTsKey:void 0,isJson:!1,selection:[]});let J2=typeof J.orderBy==="function"?J.orderBy(k,t4()):J.orderBy??[];if(!Array.isArray(J2))J2=[J2];V=J2.map((P)=>{if(U(P,T))return K2(P,_);return q1(P,_)}),A=J.limit,E=J.offset;for(let{tsKey:P,queryConfig:h,relation:w2}of L){let V0=s4($,Z,w2),$6=m2(w2.referencedTable),$1=Z[$6],O2=`${_}_${P}`,F2=p1(...V0.fields.map((l$,s$)=>r(K2(V0.references[s$],O2),K2(l$,_)))),F0=this.buildRelationalQuery({fullSchema:X,schema:$,tableNamesMap:Z,table:X[$1],tableConfig:$[$1],queryConfig:U(w2,C2)?h===!0?{limit:1}:{...h,limit:1}:h,tableAlias:O2,joinOn:F2,nestedQueryRelation:w2}),t$=z`(${F0.sql})`.as(P);O.push({dbKey:P,tsKey:P,field:t$,relationTableTsKey:$1,isJson:!0,selection:F0.selection})}}if(O.length===0)throw new Y1({message:`No fields selected for table "${G.tsName}" ("${_}"). 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 x;if(R=p1(H,R),W){let k=z`json_array(${z.join(O.map(({field:L})=>U(L,S)?z.identifier(this.casing.getColumnCasing(L)):U(L,K.Aliased)?L.sql:L),z`, `)})`;if(U(W,b1))k=z`coalesce(json_group_array(${k}), json_array())`;let C=[{dbKey:"data",tsKey:"data",field:k.as("data"),isJson:!0,relationTableTsKey:G.tsName,selection:O}];if(A!==void 0||E!==void 0||V.length>0)x=this.buildSelectQuery({table:M0(Y,_),fields:{},fieldsFlat:[{path:[],field:z.raw("*")}],where:R,limit:A,offset:E,orderBy:V,setOperators:[]}),R=void 0,A=void 0,E=void 0,V=void 0;else x=M0(Y,_);x=this.buildSelectQuery({table:U(x,u)?x:new d(x,{},_),fields:{},fieldsFlat:C.map(({field:L})=>({path:[],field:U(L,T)?K2(L,_):L})),joins:M,where:R,limit:A,offset:E,orderBy:V,setOperators:[]})}else x=this.buildSelectQuery({table:M0(Y,_),fields:{},fieldsFlat:O.map(({field:k})=>({path:[],field:U(k,T)?K2(k,_):k})),joins:M,where:R,limit:A,offset:E,orderBy:V,setOperators:[]});return{tableTsKey:G.tsName,sql:x,selection:O}}}class x6 extends _1{static[D]="SQLiteSyncDialect";migrate(X,$,Z){let Y=Z===void 0?"__drizzle_migrations":typeof Z==="string"?"__drizzle_migrations":Z.migrationsTable??"__drizzle_migrations",G=z`
3
+ CREATE TABLE IF NOT EXISTS ${z.identifier(Y)} (
4
+ id SERIAL PRIMARY KEY,
5
+ hash text NOT NULL,
6
+ created_at numeric
7
+ )
8
+ `;$.run(G);let _=$.values(z`SELECT id, hash, created_at FROM ${z.identifier(Y)} ORDER BY created_at DESC LIMIT 1`)[0]??void 0;$.run(z`BEGIN`);try{for(let W of X)if(!_||Number(_[2])<W.folderMillis){for(let H of W.sql)$.run(z.raw(H));$.run(z`INSERT INTO ${z.identifier(Y)} ("hash", "created_at") VALUES(${W.hash}, ${W.folderMillis})`)}$.run(z`COMMIT`)}catch(W){throw $.run(z`ROLLBACK`),W}}}class w6 extends _1{static[D]="SQLiteAsyncDialect";async migrate(X,$,Z){let Y=Z===void 0?"__drizzle_migrations":typeof Z==="string"?"__drizzle_migrations":Z.migrationsTable??"__drizzle_migrations",G=z`
9
+ CREATE TABLE IF NOT EXISTS ${z.identifier(Y)} (
10
+ id SERIAL PRIMARY KEY,
11
+ hash text NOT NULL,
12
+ created_at numeric
13
+ )
14
+ `;await $.run(G);let _=(await $.values(z`SELECT id, hash, created_at FROM ${z.identifier(Y)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0;await $.transaction(async(W)=>{for(let H of X)if(!_||Number(_[2])<H.folderMillis){for(let O of H.sql)await W.run(z.raw(O));await W.run(z`INSERT INTO ${z.identifier(Y)} ("hash", "created_at") VALUES(${H.hash}, ${H.folderMillis})`)}})}}class P6{static[D]="TypedQueryBuilder";getSelectedFields(){return this._.selectedFields}}class A2{static[D]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(X){this.fields=X.fields,this.session=X.session,this.dialect=X.dialect,this.withList=X.withList,this.distinct=X.distinct}from(X){let $=!!this.fields,Z;if(this.fields)Z=this.fields;else if(U(X,d))Z=Object.fromEntries(Object.keys(X._.selectedFields).map((Y)=>[Y,X[Y]]));else if(U(X,c2))Z=X[q].selectedFields;else if(U(X,K))Z={};else Z=P4(X);return new k6({table:X,fields:Z,isPartialSelect:$,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class q8 extends P6{static[D]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:X,fields:$,isPartialSelect:Z,session:Y,dialect:G,withList:J,distinct:_}){super();this.config={withList:J,table:X,fields:{...$},distinct:_,setOperators:[]},this.isPartialSelect=Z,this.session=Y,this.dialect=G,this._={selectedFields:$,config:this.config},this.tableName=S1(X),this.joinsNotNullableMap=typeof this.tableName==="string"?{[this.tableName]:!0}:{};for(let W of D2(X))this.usedTables.add(W)}getUsedTables(){return[...this.usedTables]}createJoin(X){return($,Z)=>{let Y=this.tableName,G=S1($);for(let J of D2($))this.usedTables.add(J);if(typeof G==="string"&&this.config.joins?.some((J)=>J.alias===G))throw Error(`Alias "${G}" is already used in this query`);if(!this.isPartialSelect){if(Object.keys(this.joinsNotNullableMap).length===1&&typeof Y==="string")this.config.fields={[Y]:this.config.fields};if(typeof G==="string"&&!U($,K)){let J=U($,d)?$._.selectedFields:U($,_2)?$[q].selectedFields:$[F.Symbol.Columns];this.config.fields[G]=J}}if(typeof Z==="function")Z=Z(new Proxy(this.config.fields,new m({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));if(!this.config.joins)this.config.joins=[];if(this.config.joins.push({on:Z,table:$,joinType:X,alias:G}),typeof G==="string")switch(X){case"left":{this.joinsNotNullableMap[G]=!1;break}case"right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[G]=!0;break}case"cross":case"inner":{this.joinsNotNullableMap[G]=!0;break}case"full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([J])=>[J,!1])),this.joinsNotNullableMap[G]=!1;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(X,$){return(Z)=>{let Y=typeof Z==="function"?Z(OZ()):Z;if(!y1(this.getSelectedFields(),Y.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:X,isAll:$,rightSelect:Y}),this}}union=this.createSetOperator("union",!1);unionAll=this.createSetOperator("union",!0);intersect=this.createSetOperator("intersect",!1);except=this.createSetOperator("except",!1);addSetOperators(X){return this.config.setOperators.push(...X),this}where(X){if(typeof X==="function")X=X(new Proxy(this.config.fields,new m({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.where=X,this}having(X){if(typeof X==="function")X=X(new Proxy(this.config.fields,new m({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));return this.config.having=X,this}groupBy(...X){if(typeof X[0]==="function"){let $=X[0](new Proxy(this.config.fields,new m({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray($)?$:[$]}else this.config.groupBy=X;return this}orderBy(...X){if(typeof X[0]==="function"){let $=X[0](new Proxy(this.config.fields,new m({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),Z=Array.isArray($)?$:[$];if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=Z;else this.config.orderBy=Z}else{let $=X;if(this.config.setOperators.length>0)this.config.setOperators.at(-1).orderBy=$;else this.config.orderBy=$}return this}limit(X){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).limit=X;else this.config.limit=X;return this}offset(X){if(this.config.setOperators.length>0)this.config.setOperators.at(-1).offset=X;else this.config.offset=X;return this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:X,...$}=this.dialect.sqlToQuery(this.getSQL());return $}as(X){let $=[];if($.push(...D2(this.config.table)),this.config.joins)for(let Z of this.config.joins)$.push(...D2(Z.table));return new Proxy(new d(this.getSQL(),this.config.fields,X,!1,[...new Set($)]),new m({alias:X,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new m({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}}class k6 extends q8{static[D]="SQLiteSelect";_prepare(X=!0){if(!this.session)throw Error("Cannot execute a query on a query builder. Please use a database instance instead.");let $=W2(this.config.fields),Z=this.session[X?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),$,"all",!0,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return Z.joinsNotNullableMap=this.joinsNotNullableMap,Z}$withCache(X){return this.cacheConfig=X===void 0?{config:{},enable:!0,autoInvalidate:!0}:X===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...X},this}prepare(){return this._prepare(!1)}run=(X)=>{return this._prepare().run(X)};all=(X)=>{return this._prepare().all(X)};get=(X)=>{return this._prepare().get(X)};values=(X)=>{return this._prepare().values(X)};async execute(){return this.all()}}w4(k6,[s]);function j0(X,$){return(Z,Y,...G)=>{let J=[Y,...G].map((_)=>({type:X,isAll:$,rightSelect:_}));for(let _ of J)if(!y1(Z.getSelectedFields(),_.rightSelect.getSelectedFields()))throw Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return Z.addSetOperators(J)}}var OZ=()=>({union:DZ,unionAll:AZ,intersect:UZ,except:VZ}),DZ=j0("union",!1),AZ=j0("union",!0),UZ=j0("intersect",!1),VZ=j0("except",!1);class g1{static[D]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(X){this.dialect=U(X,_1)?X:void 0,this.dialectConfig=U(X,_1)?void 0:X}$with=(X,$)=>{let Z=this;return{as:(G)=>{if(typeof G==="function")G=G(Z);return new Proxy(new v1(G.getSQL(),$??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),X,!0),new m({alias:X,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};with(...X){let $=this;function Z(G){return new A2({fields:G??void 0,session:void 0,dialect:$.getDialect(),withList:X})}function Y(G){return new A2({fields:G??void 0,session:void 0,dialect:$.getDialect(),withList:X,distinct:!0})}return{select:Z,selectDistinct:Y}}select(X){return new A2({fields:X??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(X){return new A2({fields:X??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}getDialect(){if(!this.dialect)this.dialect=new x6(this.dialectConfig);return this.dialect}}class T0{constructor(X,$,Z,Y){this.table=X,this.session=$,this.dialect=Z,this.withList=Y}static[D]="SQLiteInsertBuilder";values(X){if(X=Array.isArray(X)?X:[X],X.length===0)throw Error("values() must be called with at least one value");let $=X.map((Z)=>{let Y={},G=this.table[F.Symbol.Columns];for(let J of Object.keys(Z)){let _=Z[J];Y[J]=U(_,K)?_:new Z2(_,G[J])}return Y});return new j6(this.table,$,this.session,this.dialect,this.withList)}select(X){let $=typeof X==="function"?X(new g1):X;if(!U($,K)&&!y1(this.table[E0],$._.selectedFields))throw Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new j6(this.table,$,this.session,this.dialect,this.withList,!0)}}class j6 extends s{constructor(X,$,Z,Y,G,J){super();this.session=Z,this.dialect=Y,this.config={table:X,values:$,withList:G,select:J}}static[D]="SQLiteInsert";config;returning(X=this.config.table[u.Symbol.Columns]){return this.config.returning=W2(X),this}onConflictDoNothing(X={}){if(!this.config.onConflict)this.config.onConflict=[];if(X.target===void 0)this.config.onConflict.push(z` on conflict do nothing`);else{let $=Array.isArray(X.target)?z`${X.target}`:z`${[X.target]}`,Z=X.where?z` where ${X.where}`:z``;this.config.onConflict.push(z` on conflict ${$} do nothing${Z}`)}return this}onConflictDoUpdate(X){if(X.where&&(X.targetWhere||X.setWhere))throw Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');if(!this.config.onConflict)this.config.onConflict=[];let $=X.where?z` where ${X.where}`:void 0,Z=X.targetWhere?z` where ${X.targetWhere}`:void 0,Y=X.setWhere?z` where ${X.setWhere}`:void 0,G=Array.isArray(X.target)?z`${X.target}`:z`${[X.target]}`,J=this.dialect.buildUpdateSet(this.config.table,N0(this.config.table,X.set));return this.config.onConflict.push(z` on conflict ${G}${Z} do update set ${J}${$}${Y}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:X,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(X=!0){return this.session[X?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:D2(this.config.table)})}prepare(){return this._prepare(!1)}run=(X)=>{return this._prepare().run(X)};all=(X)=>{return this._prepare().all(X)};get=(X)=>{return this._prepare().get(X)};values=(X)=>{return this._prepare().values(X)};async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}class Q0{constructor(X,$,Z,Y){this.table=X,this.session=$,this.dialect=Z,this.withList=Y}static[D]="SQLiteUpdateBuilder";set(X){return new y8(this.table,N0(this.table,X),this.session,this.dialect,this.withList)}}class y8 extends s{constructor(X,$,Z,Y,G){super();this.session=Z,this.dialect=Y,this.config={set:$,table:X,withList:G,joins:[]}}static[D]="SQLiteUpdate";config;from(X){return this.config.from=X,this}createJoin(X){return($,Z)=>{let Y=S1($);if(typeof Y==="string"&&this.config.joins.some((G)=>G.alias===Y))throw Error(`Alias "${Y}" is already used in this query`);if(typeof Z==="function"){let G=this.config.from?U($,u)?$[F.Symbol.Columns]:U($,d)?$._.selectedFields:U($,c2)?$[q].selectedFields:void 0:void 0;Z=Z(new Proxy(this.config.table[F.Symbol.Columns],new m({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),G&&new Proxy(G,new m({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))}return this.config.joins.push({on:Z,table:$,joinType:X,alias:Y}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(X){return this.config.where=X,this}orderBy(...X){if(typeof X[0]==="function"){let $=X[0](new Proxy(this.config.table[F.Symbol.Columns],new m({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),Z=Array.isArray($)?$:[$];this.config.orderBy=Z}else{let $=X;this.config.orderBy=$}return this}limit(X){return this.config.limit=X,this}returning(X=this.config.table[u.Symbol.Columns]){return this.config.returning=W2(X),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:X,...$}=this.dialect.sqlToQuery(this.getSQL());return $}_prepare(X=!0){return this.session[X?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",!0,void 0,{type:"insert",tables:D2(this.config.table)})}prepare(){return this._prepare(!1)}run=(X)=>{return this._prepare().run(X)};all=(X)=>{return this._prepare().all(X)};get=(X)=>{return this._prepare().get(X)};values=(X)=>{return this._prepare().values(X)};async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}}class d1 extends K{constructor(X){super(d1.buildEmbeddedCount(X.source,X.filters).queryChunks);this.params=X,this.session=X.session,this.sql=d1.buildCount(X.source,X.filters)}sql;static[D]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(X,$){return z`(select count(*) from ${X}${z.raw(" where ").if($)}${$})`}static buildCount(X,$){return z`select count(*) from ${X}${z.raw(" where ").if($)}${$}`}then(X,$){return Promise.resolve(this.session.count(this.sql)).then(X,$)}catch(X){return this.then(void 0,X)}finally(X){return this.then(($)=>{return X?.(),$},($)=>{throw X?.(),$})}}class Q6{constructor(X,$,Z,Y,G,J,_,W){this.mode=X,this.fullSchema=$,this.schema=Z,this.tableNamesMap=Y,this.table=G,this.tableConfig=J,this.dialect=_,this.session=W}static[D]="SQLiteAsyncRelationalQueryBuilder";findMany(X){return this.mode==="sync"?new T6(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,X?X:{},"many"):new B0(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,X?X:{},"many")}findFirst(X){return this.mode==="sync"?new T6(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,X?{...X,limit:1}:{limit:1},"first"):new B0(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,X?{...X,limit:1}:{limit:1},"first")}}class B0 extends s{constructor(X,$,Z,Y,G,J,_,W,H){super();this.fullSchema=X,this.schema=$,this.tableNamesMap=Z,this.table=Y,this.tableConfig=G,this.dialect=J,this.session=_,this.config=W,this.mode=H}static[D]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(X=!1){let{query:$,builtQuery:Z}=this._toSQL();return this.session[X?"prepareOneTimeQuery":"prepareQuery"](Z,void 0,this.mode==="first"?"get":"all",!0,(Y,G)=>{let J=Y.map((_)=>x0(this.schema,this.tableConfig,_,$.selection,G));if(this.mode==="first")return J[0];return J})}prepare(){return this._prepare(!1)}_toSQL(){let X=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),$=this.dialect.sqlToQuery(X.sql);return{query:X,builtQuery:$}}toSQL(){return this._toSQL().builtQuery}executeRaw(){if(this.mode==="first")return this._prepare(!1).get();return this._prepare(!1).all()}async execute(){return this.executeRaw()}}class T6 extends B0{static[D]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}}class W1 extends s{constructor(X,$,Z,Y,G){super();this.execute=X,this.getSQL=$,this.dialect=Y,this.mapBatchResult=G,this.config={action:Z}}static[D]="SQLiteRaw";config;getQuery(){return{...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(X,$){return $?this.mapBatchResult(X):X}_prepare(){return this}isResponseInArrayMode(){return!1}}class m1{constructor(X,$,Z,Y){this.resultKind=X,this.dialect=$,this.session=Z,this._=Y?{schema:Y.schema,fullSchema:Y.fullSchema,tableNamesMap:Y.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let G=this.query;if(this._.schema)for(let[J,_]of Object.entries(this._.schema))G[J]=new Q6(X,Y.fullSchema,this._.schema,this._.tableNamesMap,Y.fullSchema[J],_,$,Z);this.$cache={invalidate:async(J)=>{}}}static[D]="BaseSQLiteDatabase";query;$with=(X,$)=>{let Z=this;return{as:(G)=>{if(typeof G==="function")G=G(new g1(Z.dialect));return new Proxy(new v1(G.getSQL(),$??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),X,!0),new m({alias:X,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(X,$){return new d1({source:X,filters:$,session:this.session})}with(...X){let $=this;function Z(W){return new A2({fields:W??void 0,session:$.session,dialect:$.dialect,withList:X})}function Y(W){return new A2({fields:W??void 0,session:$.session,dialect:$.dialect,withList:X,distinct:!0})}function G(W){return new Q0(W,$.session,$.dialect,X)}function J(W){return new T0(W,$.session,$.dialect,X)}function _(W){return new k0(W,$.session,$.dialect,X)}return{select:Z,selectDistinct:Y,update:G,insert:J,delete:_}}select(X){return new A2({fields:X??void 0,session:this.session,dialect:this.dialect})}selectDistinct(X){return new A2({fields:X??void 0,session:this.session,dialect:this.dialect,distinct:!0})}update(X){return new Q0(X,this.session,this.dialect)}$cache;insert(X){return new T0(X,this.session,this.dialect)}delete(X){return new k0(X,this.session,this.dialect)}run(X){let $=typeof X==="string"?z.raw(X):X.getSQL();if(this.resultKind==="async")return new W1(async()=>this.session.run($),()=>$,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session));return this.session.run($)}all(X){let $=typeof X==="string"?z.raw(X):X.getSQL();if(this.resultKind==="async")return new W1(async()=>this.session.all($),()=>$,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session));return this.session.all($)}get(X){let $=typeof X==="string"?z.raw(X):X.getSQL();if(this.resultKind==="async")return new W1(async()=>this.session.get($),()=>$,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session));return this.session.get($)}values(X){let $=typeof X==="string"?z.raw(X):X.getSQL();if(this.resultKind==="async")return new W1(async()=>this.session.values($),()=>$,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session));return this.session.values($)}transaction(X,$){return this.session.transaction(X,$)}}class S8{static[D]="Cache"}class u1 extends S8{strategy(){return"all"}static[D]="NoopCache";async get(X){return}async put(X,$,Z,Y){}async onMutate(X){}}async function B6(X,$){let Z=`${X}-${JSON.stringify($)}`,G=new TextEncoder().encode(Z),J=await crypto.subtle.digest("SHA-256",G);return[...new Uint8Array(J)].map((H)=>H.toString(16).padStart(2,"0")).join("")}class p8 extends s{constructor(X){super();this.resultCb=X}static[D]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}}class L6{constructor(X,$,Z,Y,G,J){if(this.mode=X,this.executeMethod=$,this.query=Z,this.cache=Y,this.queryMetadata=G,this.cacheConfig=J,Y&&Y.strategy()==="all"&&J===void 0)this.cacheConfig={enable:!0,autoInvalidate:!0};if(!this.cacheConfig?.enable)this.cacheConfig=void 0}static[D]="PreparedQuery";joinsNotNullableMap;async queryWithCache(X,$,Z){if(this.cache===void 0||U(this.cache,u1)||this.queryMetadata===void 0)try{return await Z()}catch(Y){throw new P2(X,$,Y)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await Z()}catch(Y){throw new P2(X,$,Y)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[Y]=await Promise.all([Z(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return Y}catch(Y){throw new P2(X,$,Y)}if(!this.cacheConfig)try{return await Z()}catch(Y){throw new P2(X,$,Y)}if(this.queryMetadata.type==="select"){let Y=await this.cache.get(this.cacheConfig.tag??await B6(X,$),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(Y===void 0){let G;try{G=await Z()}catch(J){throw new P2(X,$,J)}return await this.cache.put(this.cacheConfig.tag??await B6(X,$),G,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),G}return Y}try{return await Z()}catch(Y){throw new P2(X,$,Y)}}getQuery(){return this.query}mapRunResult(X,$){return X}mapAllResult(X,$){throw Error("Not implemented")}mapGetResult(X,$){throw Error("Not implemented")}execute(X){if(this.mode==="async")return this[this.executeMethod](X);return new p8(()=>this[this.executeMethod](X))}mapResult(X,$){switch(this.executeMethod){case"run":return this.mapRunResult(X,$);case"all":return this.mapAllResult(X,$);case"get":return this.mapGetResult(X,$)}}}class v6{constructor(X){this.dialect=X}static[D]="SQLiteSession";prepareOneTimeQuery(X,$,Z,Y,G,J,_){return this.prepareQuery(X,$,Z,Y,G,J,_)}run(X){let $=this.dialect.sqlToQuery(X);try{return this.prepareOneTimeQuery($,void 0,"run",!1).run()}catch(Z){throw new Y1({cause:Z,message:`Failed to run the query '${$.sql}'`})}}extractRawRunValueFromBatchResult(X){return X}all(X){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(X),void 0,"run",!1).all()}extractRawAllValueFromBatchResult(X){throw Error("Not implemented")}get(X){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(X),void 0,"run",!1).get()}extractRawGetValueFromBatchResult(X){throw Error("Not implemented")}values(X){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(X),void 0,"run",!1).values()}async count(X){return(await this.values(X))[0][0]}extractRawValuesValueFromBatchResult(X){throw Error("Not implemented")}}class C6 extends m1{constructor(X,$,Z,Y,G=0){super(X,$,Z,Y);this.schema=Y,this.nestedIndex=G}static[D]="SQLiteTransaction";rollback(){throw new H6}}var h_=e("memory",{key:I("key").notNull(),namespace:I("namespace").notNull().default("default"),value:I("value").notNull(),timestamp:b("timestamp").notNull(),created_at:I("created_at").notNull(),updated_at:I("updated_at").notNull()},(X)=>({pk:N6({columns:[X.key,X.namespace]}),namespaceIdx:f("idx_memory_namespace").on(X.namespace),timestampIdx:f("idx_memory_timestamp").on(X.timestamp),keyIdx:f("idx_memory_key").on(X.key)})),b8=e("codebase_files",{path:I("path").primaryKey(),mtime:b("mtime").notNull(),hash:I("hash").notNull(),content:I("content"),language:I("language"),size:b("size"),indexedAt:I("indexed_at").notNull()},(X)=>({mtimeIdx:f("idx_codebase_files_mtime").on(X.mtime),hashIdx:f("idx_codebase_files_hash").on(X.hash)})),f_=e("tfidf_terms",{filePath:I("file_path").notNull().references(()=>b8.path,{onDelete:"cascade"}),term:I("term").notNull(),frequency:J1("frequency").notNull()},(X)=>({termIdx:f("idx_tfidf_terms_term").on(X.term),fileIdx:f("idx_tfidf_terms_file").on(X.filePath)})),q_=e("tfidf_documents",{filePath:I("file_path").primaryKey().references(()=>b8.path,{onDelete:"cascade"}),magnitude:J1("magnitude").notNull(),termCount:b("term_count").notNull(),rawTerms:I("raw_terms").notNull()}),y_=e("tfidf_idf",{term:I("term").primaryKey(),idfValue:J1("idf_value").notNull()}),S_=e("codebase_metadata",{key:I("key").primaryKey(),value:I("value").notNull()}),v=e("sessions",{id:I("id").primaryKey(),title:I("title"),provider:I("provider").notNull(),model:I("model").notNull(),nextTodoId:b("next_todo_id").notNull().default(1),created:b("created").notNull(),updated:b("updated").notNull()},(X)=>({updatedIdx:f("idx_sessions_updated").on(X.updated),createdIdx:f("idx_sessions_created").on(X.created),providerIdx:f("idx_sessions_provider").on(X.provider),titleIdx:f("idx_sessions_title").on(X.title)})),Y2=e("messages",{id:I("id").primaryKey(),sessionId:I("session_id").notNull().references(()=>v.id,{onDelete:"cascade"}),role:I("role").notNull(),timestamp:b("timestamp").notNull(),ordering:b("ordering").notNull(),finishReason:I("finish_reason"),metadata:I("metadata")},(X)=>({sessionIdx:f("idx_messages_session").on(X.sessionId),orderingIdx:f("idx_messages_ordering").on(X.sessionId,X.ordering),timestampIdx:f("idx_messages_timestamp").on(X.timestamp)})),c1=e("message_parts",{id:I("id").primaryKey(),messageId:I("message_id").notNull().references(()=>Y2.id,{onDelete:"cascade"}),ordering:b("ordering").notNull(),type:I("type").notNull(),content:I("content").notNull()},(X)=>({messageIdx:f("idx_message_parts_message").on(X.messageId),orderingIdx:f("idx_message_parts_ordering").on(X.messageId,X.ordering),typeIdx:f("idx_message_parts_type").on(X.type)})),L0=e("message_attachments",{id:I("id").primaryKey(),messageId:I("message_id").notNull().references(()=>Y2.id,{onDelete:"cascade"}),path:I("path").notNull(),relativePath:I("relative_path").notNull(),size:b("size")},(X)=>({messageIdx:f("idx_message_attachments_message").on(X.messageId),pathIdx:f("idx_message_attachments_path").on(X.path)})),v0=e("message_usage",{messageId:I("message_id").primaryKey().references(()=>Y2.id,{onDelete:"cascade"}),promptTokens:b("prompt_tokens").notNull(),completionTokens:b("completion_tokens").notNull(),totalTokens:b("total_tokens").notNull()}),n2=e("todos",{id:b("id").notNull(),sessionId:I("session_id").notNull().references(()=>v.id,{onDelete:"cascade"}),content:I("content").notNull(),activeForm:I("active_form").notNull(),status:I("status").notNull(),ordering:b("ordering").notNull()},(X)=>({pk:N6({columns:[X.sessionId,X.id]}),sessionIdx:f("idx_todos_session").on(X.sessionId),statusIdx:f("idx_todos_status").on(X.status),orderingIdx:f("idx_todos_ordering").on(X.sessionId,X.ordering)})),n1=e("message_todo_snapshots",{id:I("id").primaryKey(),messageId:I("message_id").notNull().references(()=>Y2.id,{onDelete:"cascade"}),todoId:b("todo_id").notNull(),content:I("content").notNull(),activeForm:I("active_form").notNull(),status:I("status").notNull(),ordering:b("ordering").notNull()},(X)=>({messageIdx:f("idx_message_todo_snapshots_message").on(X.messageId)}));async function h6(X,$=5){let Z;for(let Y=0;Y<$;Y++)try{return await X()}catch(G){if(Z=G,G.message?.includes("SQLITE_BUSY")||G.code==="SQLITE_BUSY"){let J=50*Math.pow(2,Y);await new Promise((_)=>setTimeout(_,J));continue}throw G}throw Z}class z1{db;constructor(X){this.db=X}async createSession(X,$){let Z=Date.now(),Y=`session-${Z}`,G={id:Y,provider:X,model:$,nextTodoId:1,created:Z,updated:Z};return await this.db.insert(v).values(G),{id:Y,provider:X,model:$,messages:[],todos:[],nextTodoId:1,created:Z,updated:Z}}async createSessionFromData(X){await h6(async()=>{let $={id:X.id,title:X.title||null,provider:X.provider,model:X.model,nextTodoId:X.nextTodoId,created:X.created,updated:X.updated};await this.db.insert(v).values($)})}async getRecentSessions(X=20,$=0){let Z=await this.db.select().from(v).orderBy(G1(v.updated)).limit(X).offset($);return(await Promise.all(Z.map((G)=>this.getSessionById(G.id)))).filter((G)=>G!==null)}async getSessionById(X){let[$]=await this.db.select().from(v).where(r(v.id,X)).limit(1);if(!$)return null;let Z=await this.getSessionMessages(X),Y=await this.getSessionTodos(X);return{id:$.id,title:$.title||void 0,provider:$.provider,model:$.model,messages:Z,todos:Y,nextTodoId:$.nextTodoId,created:$.created,updated:$.updated}}async getSessionMessages(X){let $=await this.db.select().from(Y2).where(r(Y2.sessionId,X)).orderBy(Y2.ordering);if($.length===0)return[];let Z=$.map((V)=>V.id),[Y,G,J,_]=await Promise.all([this.db.select().from(c1).where(u2(c1.messageId,Z)).orderBy(c1.ordering),this.db.select().from(L0).where(u2(L0.messageId,Z)),this.db.select().from(v0).where(u2(v0.messageId,Z)),this.db.select().from(n1).where(u2(n1.messageId,Z)).orderBy(n1.ordering)]),W=new Map,H=new Map,O=new Map,A=new Map;for(let V of Y){if(!W.has(V.messageId))W.set(V.messageId,[]);W.get(V.messageId).push(V)}for(let V of G){if(!H.has(V.messageId))H.set(V.messageId,[]);H.get(V.messageId).push(V)}for(let V of J)O.set(V.messageId,V);for(let V of _){if(!A.has(V.messageId))A.set(V.messageId,[]);A.get(V.messageId).push(V)}return $.map((V)=>{let R=W.get(V.id)||[],M=H.get(V.id)||[],x=O.get(V.id),k=A.get(V.id)||[],C={role:V.role,content:R.map((B)=>JSON.parse(B.content)),timestamp:V.timestamp};if(V.metadata)C.metadata=JSON.parse(V.metadata);if(M.length>0)C.attachments=M.map((B)=>({path:B.path,relativePath:B.relativePath,size:B.size||void 0}));if(x)C.usage={promptTokens:x.promptTokens,completionTokens:x.completionTokens,totalTokens:x.totalTokens};if(V.finishReason)C.finishReason=V.finishReason;if(k.length>0)C.todoSnapshot=k.map((B)=>({id:B.todoId,content:B.content,activeForm:B.activeForm,status:B.status,ordering:B.ordering}));return C})}async getSessionTodos(X){return(await this.db.select().from(n2).where(r(n2.sessionId,X)).orderBy(n2.ordering)).map((Z)=>({id:Z.id,content:Z.content,activeForm:Z.activeForm,status:Z.status,ordering:Z.ordering}))}async addMessage(X,$,Z,Y,G,J,_,W){await h6(async()=>{let H=C0(),O=Date.now(),[{count:A}]=await this.db.select({count:z`count(*)`}).from(Y2).where(r(Y2.sessionId,X)),E=A;await this.db.transaction(async(V)=>{await V.insert(Y2).values({id:H,sessionId:X,role:$,timestamp:O,ordering:E,finishReason:J||null,metadata:_?JSON.stringify(_):null});for(let R=0;R<Z.length;R++)await V.insert(c1).values({id:C0(),messageId:H,ordering:R,type:Z[R].type,content:JSON.stringify(Z[R])});if(Y&&Y.length>0)for(let R of Y)await V.insert(L0).values({id:C0(),messageId:H,path:R.path,relativePath:R.relativePath,size:R.size||null});if(G)await V.insert(v0).values({messageId:H,promptTokens:G.promptTokens,completionTokens:G.completionTokens,totalTokens:G.totalTokens});if(W&&W.length>0)for(let R of W)await V.insert(n1).values({id:C0(),messageId:H,todoId:R.id,content:R.content,activeForm:R.activeForm,status:R.status,ordering:R.ordering});await V.update(v).set({updated:O}).where(r(v.id,X))})})}async updateSessionTitle(X,$){await this.db.update(v).set({title:$,updated:Date.now()}).where(r(v.id,X))}async updateSessionModel(X,$){await this.db.update(v).set({model:$,updated:Date.now()}).where(r(v.id,X))}async updateSessionProvider(X,$,Z){await this.db.update(v).set({provider:$,model:Z,updated:Date.now()}).where(r(v.id,X))}async deleteSession(X){await this.db.delete(v).where(r(v.id,X))}async searchSessionsByTitle(X,$=20){let Z=await this.db.select().from(v).where(I0(v.title,`%${X}%`)).orderBy(G1(v.updated)).limit($);return(await Promise.all(Z.map((G)=>this.getSessionById(G.id)))).filter((G)=>G!==null)}async getSessionCount(){let[{count:X}]=await this.db.select({count:z`count(*)`}).from(v);return X}async getMessageCount(X){let[{count:$}]=await this.db.select({count:z`count(*)`}).from(Y2).where(r(Y2.sessionId,X));return $}async getLastSession(){let[X]=await this.db.select().from(v).orderBy(G1(v.updated)).limit(1);if(!X)return null;return this.getSessionById(X.id)}async updateTodos(X,$,Z){await h6(async()=>{await this.db.transaction(async(Y)=>{await Y.delete(n2).where(r(n2.sessionId,X));for(let G of $)await Y.insert(n2).values({id:G.id,sessionId:X,content:G.content,activeForm:G.activeForm,status:G.status,ordering:G.ordering});await Y.update(v).set({nextTodoId:Z,updated:Date.now()}).where(r(v.id,X))})})}}import{join as B1}from"node:path";import{homedir as i$}from"node:os";import{readdir as W4,mkdir as e7,readFile as XG}from"node:fs/promises";import{existsSync as z4}from"node:fs";import{fileURLToPath as $G}from"node:url";import{dirname as o$}from"node:path";class w extends Error{code;rawCode;constructor(X,$,Z,Y){if($!==void 0)X=`${$}: ${X}`;super(X,{cause:Y});this.code=$,this.rawCode=Z,this.name="LibsqlError"}}function g8(X){let $=FZ.exec(X);if($===null)throw new w(`The URL '${X}' is not in a valid format`,"URL_INVALID");let Z=$.groups,Y=Z.scheme,G=Z.authority!==void 0?KZ(Z.authority):void 0,J=o2(Z.path),_=Z.query!==void 0?RZ(Z.query):void 0,W=Z.fragment!==void 0?o2(Z.fragment):void 0;return{scheme:Y,authority:G,path:J,query:_,fragment:W}}var FZ=(()=>{return new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su")})();function KZ(X){let $=EZ.exec(X);if($===null)throw new w("The authority part of the URL is not in a valid format","URL_INVALID");let Z=$.groups,Y=o2(Z.host_br??Z.host),G=Z.port?parseInt(Z.port,10):void 0,J=Z.username!==void 0?{username:o2(Z.username),password:Z.password!==void 0?o2(Z.password):void 0}:void 0;return{host:Y,port:G,userinfo:J}}var EZ=(()=>{return new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su")})();function RZ(X){let $=X.split("&"),Z=[];for(let Y of $){if(Y==="")continue;let G,J,_=Y.indexOf("=");if(_<0)G=Y,J="";else G=Y.substring(0,_),J=Y.substring(_+1);Z.push({key:o2(G.replaceAll("+"," ")),value:o2(J.replaceAll("+"," "))})}return{pairs:Z}}function o2(X){try{return decodeURIComponent(X)}catch($){if($ instanceof URIError)throw new w(`URL component has invalid percent encoding: ${$}`,"URL_INVALID",void 0,$);throw $}}function o1(X,$,Z){if($===void 0)throw new w(`URL with scheme ${JSON.stringify(X+":")} requires authority (the "//" part)`,"URL_INVALID");let Y=`${X}:`,G=MZ($.host),J=NZ($.port),W=`//${IZ($.userinfo)}${G}${J}`,H=Z.split("/").map(encodeURIComponent).join("/");if(H!==""&&!H.startsWith("/"))H="/"+H;return new URL(`${Y}${W}${H}`)}function MZ(X){return X.includes(":")?`[${encodeURI(X)}]`:encodeURI(X)}function NZ(X){return X!==void 0?`:${X}`:""}function IZ(X){if(X===void 0)return"";let $=encodeURIComponent(X.username),Z=X.password!==void 0?`:${encodeURIComponent(X.password)}`:"";return`${$}${Z}@`}var O1=typeof Buffer==="function",d8=typeof TextDecoder==="function"?new TextDecoder:void 0,m8=typeof TextEncoder==="function"?new TextEncoder:void 0;var i1=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),h0=((X)=>{let $={};return X.forEach((Z,Y)=>$[Z]=Y),$})(i1),xZ=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,t=String.fromCharCode.bind(String),u8=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(X)=>new Uint8Array(Array.prototype.slice.call(X,0)),o8=(X)=>X.replace(/=/g,"").replace(/[+\/]/g,($)=>$=="+"?"-":"_"),i8=(X)=>X.replace(/[^A-Za-z0-9\+\/]/g,""),r8=(X)=>{let $,Z,Y,G,J="",_=X.length%3;for(let W=0;W<X.length;){if((Z=X.charCodeAt(W++))>255||(Y=X.charCodeAt(W++))>255||(G=X.charCodeAt(W++))>255)throw TypeError("invalid character found");$=Z<<16|Y<<8|G,J+=i1[$>>18&63]+i1[$>>12&63]+i1[$>>6&63]+i1[$&63]}return _?J.slice(0,_-3)+"===".substring(_):J},y6=typeof btoa==="function"?(X)=>btoa(X):O1?(X)=>Buffer.from(X,"binary").toString("base64"):r8,f6=O1?(X)=>Buffer.from(X).toString("base64"):(X)=>{let Z=[];for(let Y=0,G=X.length;Y<G;Y+=4096)Z.push(t.apply(null,X.subarray(Y,Y+4096)));return y6(Z.join(""))},f0=(X,$=!1)=>$?o8(f6(X)):f6(X),wZ=(X)=>{if(X.length<2){var $=X.charCodeAt(0);return $<128?X:$<2048?t(192|$>>>6)+t(128|$&63):t(224|$>>>12&15)+t(128|$>>>6&63)+t(128|$&63)}else{var $=65536+(X.charCodeAt(0)-55296)*1024+(X.charCodeAt(1)-56320);return t(240|$>>>18&7)+t(128|$>>>12&63)+t(128|$>>>6&63)+t(128|$&63)}},PZ=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,t8=(X)=>X.replace(PZ,wZ),c8=O1?(X)=>Buffer.from(X,"utf8").toString("base64"):m8?(X)=>f6(m8.encode(X)):(X)=>y6(t8(X)),H1=(X,$=!1)=>$?o8(c8(X)):c8(X),n8=(X)=>H1(X,!0),kZ=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,jZ=(X)=>{switch(X.length){case 4:var $=(7&X.charCodeAt(0))<<18|(63&X.charCodeAt(1))<<12|(63&X.charCodeAt(2))<<6|63&X.charCodeAt(3),Z=$-65536;return t((Z>>>10)+55296)+t((Z&1023)+56320);case 3:return t((15&X.charCodeAt(0))<<12|(63&X.charCodeAt(1))<<6|63&X.charCodeAt(2));default:return t((31&X.charCodeAt(0))<<6|63&X.charCodeAt(1))}},l8=(X)=>X.replace(kZ,jZ),s8=(X)=>{if(X=X.replace(/\s+/g,""),!xZ.test(X))throw TypeError("malformed base64.");X+="==".slice(2-(X.length&3));let $,Z,Y,G=[];for(let J=0;J<X.length;)if($=h0[X.charAt(J++)]<<18|h0[X.charAt(J++)]<<12|(Z=h0[X.charAt(J++)])<<6|(Y=h0[X.charAt(J++)]),Z===64)G.push(t($>>16&255));else if(Y===64)G.push(t($>>16&255,$>>8&255));else G.push(t($>>16&255,$>>8&255,$&255));return G.join("")},S6=typeof atob==="function"?(X)=>atob(i8(X)):O1?(X)=>Buffer.from(X,"base64").toString("binary"):s8,a8=O1?(X)=>u8(Buffer.from(X,"base64")):(X)=>u8(S6(X).split("").map(($)=>$.charCodeAt(0))),e8=(X)=>a8(XX(X)),TZ=O1?(X)=>Buffer.from(X,"base64").toString("utf8"):d8?(X)=>d8.decode(a8(X)):(X)=>l8(S6(X)),XX=(X)=>i8(X.replace(/[-_]/g,($)=>$=="-"?"+":"/")),q6=(X)=>TZ(XX(X)),QZ=(X)=>{if(typeof X!=="string")return!1;let $=X.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test($)||!/[^\s0-9a-zA-Z\-_]/.test($)},$X=(X)=>{return{value:X,enumerable:!1,writable:!0,configurable:!0}},ZX=function(){let X=($,Z)=>Object.defineProperty(String.prototype,$,$X(Z));X("fromBase64",function(){return q6(this)}),X("toBase64",function($){return H1(this,$)}),X("toBase64URI",function(){return H1(this,!0)}),X("toBase64URL",function(){return H1(this,!0)}),X("toUint8Array",function(){return e8(this)})},YX=function(){let X=($,Z)=>Object.defineProperty(Uint8Array.prototype,$,$X(Z));X("toBase64",function($){return f0(this,$)}),X("toBase64URI",function(){return f0(this,!0)}),X("toBase64URL",function(){return f0(this,!0)})},BZ=()=>{ZX(),YX()},D1={version:"3.7.8",VERSION:"3.7.8",atob:S6,atobPolyfill:s8,btoa:y6,btoaPolyfill:r8,fromBase64:q6,toBase64:H1,encode:H1,encodeURI:n8,encodeURL:n8,utob:t8,btou:l8,decode:q6,isValid:QZ,fromUint8Array:f0,toUint8Array:e8,extendString:ZX,extendUint8Array:YX,extendBuiltins:BZ};var R2="https://github.com/libsql/libsql-client-ts#supported-urls";function h2(X){if(X==="write")return"BEGIN IMMEDIATE";else if(X==="read")return"BEGIN TRANSACTION READONLY";else if(X==="deferred")return"BEGIN DEFERRED";else throw RangeError('Unknown transaction mode, supported values are "write", "read" and "deferred"')}class A1{columns;columnTypes;rows;rowsAffected;lastInsertRowid;constructor(X,$,Z,Y,G){this.columns=X,this.columnTypes=$,this.rows=Z,this.rowsAffected=Y,this.lastInsertRowid=G}toJSON(){return{columns:this.columns,columnTypes:this.columnTypes,rows:this.rows.map(LZ),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function LZ(X){return Array.prototype.map.call(X,vZ)}function vZ(X){if(typeof X==="bigint")return""+X;else if(X instanceof ArrayBuffer)return D1.fromUint8Array(new Uint8Array(X));else return X}var GX=":memory:";function JX(X){return X.scheme==="file"&&(X.path===":memory:"||X.path.startsWith(":memory:?"))}function r1(X,$){if(typeof X!=="object")throw TypeError(`Expected client configuration as object, got ${typeof X}`);let{url:Z,authToken:Y,tls:G,intMode:J,concurrency:_}=X;_=Math.max(0,_||20),J??="number";let W=[];if(Z===GX)Z="file::memory:";let H=g8(Z),O=H.scheme.toLowerCase(),A=O==="file"&&H.path===GX&&H.authority===void 0,E;if(A)E={cache:{values:["shared","private"],update:(x,k)=>W.push(`${x}=${k}`)}};else E={tls:{values:["0","1"],update:(x,k)=>G=k==="1"},authToken:{update:(x,k)=>Y=k}};for(let{key:x,value:k}of H.query?.pairs??[]){if(!Object.hasOwn(E,x))throw new w(`Unsupported URL query parameter ${JSON.stringify(x)}`,"URL_PARAM_NOT_SUPPORTED");let C=E[x];if(C.values!==void 0&&!C.values.includes(k))throw new w(`Unknown value for the "${x}" query argument: ${JSON.stringify(k)}. Supported values are: [${C.values.map((B)=>'"'+B+'"').join(", ")}]`,"URL_INVALID");if(C.update!==void 0)C?.update(x,k)}let V=W.length===0?"":`?${W.join("&")}`,R=H.path+V,M;if(O==="libsql")if(G===!1){if(H.authority?.port===void 0)throw new w('A "libsql:" URL with ?tls=0 must specify an explicit port',"URL_INVALID");M=$?"http":"ws"}else M=$?"https":"wss";else M=O;if(M==="http"||M==="ws")G??=!1;else G??=!0;if(M!=="http"&&M!=="ws"&&M!=="https"&&M!=="wss"&&M!=="file")throw new w(`The client supports only "libsql:", "wss:", "ws:", "https:", "http:" and "file:" URLs, got ${JSON.stringify(H.scheme+":")}. For more information, please read ${R2}`,"URL_SCHEME_NOT_SUPPORTED");if(J!=="number"&&J!=="bigint"&&J!=="string")throw TypeError(`Invalid value for intMode, expected "number", "bigint" or "string", got ${JSON.stringify(J)}`);if(H.fragment!==void 0)throw new w(`URL fragments are not supported: ${JSON.stringify("#"+H.fragment)}`,"URL_INVALID");if(A)return{scheme:"file",tls:!1,path:R,intMode:J,concurrency:_,syncUrl:X.syncUrl,syncInterval:X.syncInterval,readYourWrites:X.readYourWrites,offline:X.offline,fetch:X.fetch,authToken:void 0,encryptionKey:void 0,authority:void 0};return{scheme:M,tls:G,authority:H.authority,path:R,authToken:Y,intMode:J,concurrency:_,encryptionKey:X.encryptionKey,syncUrl:X.syncUrl,syncInterval:X.syncInterval,readYourWrites:X.readYourWrites,offline:X.offline,fetch:X.fetch}}var t1=g6(mX(),1);import{Buffer as cX}from"node:buffer";function nX(X){if(X.scheme!=="file")throw new w(`URL scheme ${JSON.stringify(X.scheme+":")} is not supported by the local sqlite3 client. For more information, please read ${R2}`,"URL_SCHEME_NOT_SUPPORTED");let $=X.authority;if($!==void 0){let _=$.host.toLowerCase();if(_!==""&&_!=="localhost")throw new w(`Invalid host in file URL: ${JSON.stringify($.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 ${R2}`,"URL_INVALID");if($.port!==void 0)throw new w("File URL cannot have a port","URL_INVALID");if($.userinfo!==void 0)throw new w("File URL cannot have username and password","URL_INVALID")}let Z=JX(X);if(Z&&X.syncUrl)throw new w(`Embedded replica must use file for local db but URI with in-memory mode were provided instead: ${X.path}`,"URL_INVALID");let Y=X.path;if(Z)Y=`${X.scheme}:${X.path}`;let G={authToken:X.authToken,encryptionKey:X.encryptionKey,syncUrl:X.syncUrl,syncPeriod:X.syncInterval,readYourWrites:X.readYourWrites,offline:X.offline},J=new t1.default(Y,G);return o(J,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",X.intMode),new oX(Y,G,J,X.intMode)}class oX{#X;#$;#Z;#Y;closed;protocol;constructor(X,$,Z,Y){this.#X=X,this.#$=$,this.#Z=Z,this.#Y=Y,this.closed=!1,this.protocol="file"}async execute(X,$){let Z;if(typeof X==="string")Z={sql:X,args:$||[]};else Z=X;return this.#G(),o(this.#J(),Z,this.#Y)}async batch(X,$="deferred"){this.#G();let Z=this.#J();try{o(Z,h2($),this.#Y);let Y=X.map((G)=>{if(!Z.inTransaction)throw new w("The transaction has been rolled back","TRANSACTION_CLOSED");let J=Array.isArray(G)?{sql:G[0],args:G[1]||[]}:G;return o(Z,J,this.#Y)});return o(Z,"COMMIT",this.#Y),Y}finally{if(Z.inTransaction)o(Z,"ROLLBACK",this.#Y)}}async migrate(X){this.#G();let $=this.#J();try{o($,"PRAGMA foreign_keys=off",this.#Y),o($,h2("deferred"),this.#Y);let Z=X.map((Y)=>{if(!$.inTransaction)throw new w("The transaction has been rolled back","TRANSACTION_CLOSED");return o($,Y,this.#Y)});return o($,"COMMIT",this.#Y),Z}finally{if($.inTransaction)o($,"ROLLBACK",this.#Y);o($,"PRAGMA foreign_keys=on",this.#Y)}}async transaction(X="write"){let $=this.#J();return o($,h2(X),this.#Y),this.#Z=null,new iX($,this.#Y)}async executeMultiple(X){this.#G();let $=this.#J();try{return rX($,X)}finally{if($.inTransaction)o($,"ROLLBACK",this.#Y)}}async sync(){this.#G();let X=await this.#J().sync();return{frames_synced:X.frames_synced,frame_no:X.frame_no}}async reconnect(){try{if(!this.closed&&this.#Z!==null)this.#Z.close()}finally{this.#Z=new t1.default(this.#X,this.#$),this.closed=!1}}close(){if(this.closed=!0,this.#Z!==null)this.#Z.close(),this.#Z=null}#G(){if(this.closed)throw new w("The client is closed","CLIENT_CLOSED")}#J(){if(this.#Z===null)this.#Z=new t1.default(this.#X,this.#$);return this.#Z}}class iX{#X;#$;constructor(X,$){this.#X=X,this.#$=$}async execute(X,$){let Z;if(typeof X==="string")Z={sql:X,args:$||[]};else Z=X;return this.#Z(),o(this.#X,Z,this.#$)}async batch(X){return X.map(($)=>{this.#Z();let Z=Array.isArray($)?{sql:$[0],args:$[1]||[]}:$;return o(this.#X,Z,this.#$)})}async executeMultiple(X){return this.#Z(),rX(this.#X,X)}async rollback(){if(!this.#X.open)return;this.#Z(),o(this.#X,"ROLLBACK",this.#$)}async commit(){this.#Z(),o(this.#X,"COMMIT",this.#$)}close(){if(this.#X.inTransaction)o(this.#X,"ROLLBACK",this.#$)}get closed(){return!this.#X.inTransaction}#Z(){if(this.closed)throw new w("The transaction is closed","TRANSACTION_CLOSED")}}function o(X,$,Z){let Y,G;if(typeof $==="string")Y=$,G=[];else if(Y=$.sql,Array.isArray($.args))G=$.args.map((J)=>uX(J,Z));else{G={};for(let J in $.args){let _=J[0]==="@"||J[0]==="$"||J[0]===":"?J.substring(1):J;G[_]=uX($.args[J],Z)}}try{let J=X.prepare(Y);J.safeIntegers(!0);let _=!0;try{J.raw(!0)}catch{_=!1}if(_){let W=Array.from(J.columns().map((V)=>V.name)),H=Array.from(J.columns().map((V)=>V.type??"")),O=J.all(G).map((V)=>{return kY(V,W,Z)}),A=0,E=void 0;return new A1(W,H,O,0,void 0)}else{let W=J.run(G),H=W.changes,O=BigInt(W.lastInsertRowid);return new A1([],[],[],H,O)}}catch(J){throw tX(J)}}function kY(X,$,Z){let Y={};Object.defineProperty(Y,"length",{value:X.length});for(let G=0;G<X.length;++G){let J=jY(X[G],Z);Object.defineProperty(Y,G,{value:J});let _=$[G];if(!Object.hasOwn(Y,_))Object.defineProperty(Y,_,{value:J,enumerable:!0,configurable:!0,writable:!0})}return Y}function jY(X,$){if(typeof X==="bigint")if($==="number"){if(X<TY||X>QY)throw RangeError("Received integer which cannot be safely represented as a JavaScript number");return Number(X)}else if($==="bigint")return X;else if($==="string")return""+X;else throw Error("Invalid value for IntMode");else if(X instanceof cX)return X.buffer;return X}var TY=-9007199254740991n,QY=9007199254740991n;function uX(X,$){if(typeof X==="number"){if(!Number.isFinite(X))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return X}else if(typeof X==="bigint"){if(X<BY||X>LY)throw RangeError("bigint is too large to be represented as a 64-bit integer and passed as argument");return X}else if(typeof X==="boolean")switch($){case"bigint":return X?1n:0n;case"string":return X?"1":"0";default:return X?1:0}else if(X instanceof ArrayBuffer)return cX.from(X);else if(X instanceof Date)return X.valueOf();else if(X===void 0)throw TypeError("undefined cannot be passed as argument to the database");else return X}var BY=-9223372036854775808n,LY=9223372036854775807n;function rX(X,$){try{X.exec($)}catch(Z){throw tX(Z)}}function tX(X){if(X instanceof t1.default.SqliteError)return new w(X.message,X.code,X.rawCode,X);return X}class F1{constructor(){this.intMode="number"}intMode}class Q extends Error{constructor(X){super(X);this.name="ClientError"}}class N extends Q{constructor(X){super(X);this.name="ProtoError"}}class s1 extends Q{code;proto;constructor(X,$){super(X);this.name="ResponseError",this.code=$.code,this.proto=$,this.stack=void 0}}class g extends Q{constructor(X,$){if($!==void 0){super(`${X}: ${$}`);this.cause=$}else super(X);this.name="ClosedError"}}class a1 extends Q{constructor(X){super(X);this.name="WebSocketUnsupportedError"}}class K1 extends Q{constructor(X){super(X);this.name="WebSocketError"}}class t2 extends Q{status;constructor(X,$){super(X);this.status=$,this.name="HttpServerError"}}class U2 extends Q{constructor(X){super(X);this.name="ProtocolVersionError"}}class l extends Q{constructor(X){super(X);this.name="InternalError"}}class I2 extends Q{constructor(X){super(X);this.name="MisuseError"}}function X2(X){if(typeof X==="string")return X;throw E1(X,"string")}function G2(X){if(X===null||X===void 0)return;else if(typeof X==="string")return X;throw E1(X,"string or null")}function T2(X){if(typeof X==="number")return X;throw E1(X,"number")}function y2(X){if(typeof X==="boolean")return X;throw E1(X,"boolean")}function e1(X){if(Array.isArray(X))return X;throw E1(X,"array")}function c(X){if(X!==null&&typeof X==="object"&&!Array.isArray(X))return X;throw E1(X,"object")}function V2(X,$){return e1(X).map((Z)=>$(c(Z)))}function E1(X,$){if(X===void 0)return new N(`Expected ${$}, but the property was missing`);let Z=typeof X;if(X===null)Z="null";else if(Array.isArray(X))Z="array";return new N(`Expected ${$}, received ${Z}`)}function l2(X,$){return $(c(X))}class lX{#X;#$;constructor(X){this.#X=X,this.#$=!1}begin(){this.#X.push("{"),this.#$=!0}end(){this.#X.push("}"),this.#$=!1}#Z(X){if(this.#$)this.#X.push('"'),this.#$=!1;else this.#X.push(',"');this.#X.push(X),this.#X.push('":')}string(X,$){this.#Z(X),this.#X.push(JSON.stringify($))}stringRaw(X,$){this.#Z(X),this.#X.push('"'),this.#X.push($),this.#X.push('"')}number(X,$){this.#Z(X),this.#X.push(""+$)}boolean(X,$){this.#Z(X),this.#X.push($?"true":"false")}object(X,$,Z){this.#Z(X),this.begin(),Z(this,$),this.end()}arrayObjects(X,$,Z){this.#Z(X),this.#X.push("[");for(let Y=0;Y<$.length;++Y){if(Y!==0)this.#X.push(",");this.begin(),Z(this,$[Y]),this.end()}this.#X.push("]")}}function X0(X,$){let Z=[],Y=new lX(Z);return Y.begin(),$(Y,X),Y.end(),Z.join("")}var s2=0,$0=1,Z0=2;var sX=5;class aX{#X;#$;#Z;constructor(X){this.#X=X,this.#$=new DataView(X.buffer,X.byteOffset,X.byteLength),this.#Z=0}varint(){let X=0;for(let $=0;;$+=7){let Z=this.#X[this.#Z++];if(X|=(Z&127)<<$,!(Z&128))break}return X}varintBig(){let X=0n;for(let $=0n;;$+=7n){let Z=this.#X[this.#Z++];if(X|=BigInt(Z&127)<<$,!(Z&128))break}return X}bytes(X){let $=new Uint8Array(this.#X.buffer,this.#X.byteOffset+this.#Z,X);return this.#Z+=X,$}double(){let X=this.#$.getFloat64(this.#Z,!0);return this.#Z+=8,X}skipVarint(){for(;;)if(!(this.#X[this.#Z++]&128))break}skip(X){this.#Z+=X}eof(){return this.#Z>=this.#X.byteLength}}class eX{#X;#$;constructor(X){this.#X=X,this.#$=-1}setup(X){this.#$=X}#Z(X){if(this.#$!==X)throw new N(`Expected wire type ${X}, got ${this.#$}`);this.#$=-1}bytes(){this.#Z(Z0);let X=this.#X.varint();return this.#X.bytes(X)}string(){return new TextDecoder().decode(this.bytes())}message(X){return S2(this.bytes(),X)}int32(){return this.#Z(s2),this.#X.varint()}uint32(){return this.int32()}bool(){return this.int32()!==0}uint64(){return this.#Z(s2),this.#X.varintBig()}sint64(){let X=this.uint64();return X>>1n^-(X&1n)}double(){return this.#Z($0),this.#X.double()}maybeSkip(){if(this.#$<0)return;else if(this.#$===s2)this.#X.skipVarint();else if(this.#$===$0)this.#X.skip(8);else if(this.#$===Z0){let X=this.#X.varint();this.#X.skip(X)}else if(this.#$===sX)this.#X.skip(4);else throw new N(`Unexpected wire type ${this.#$}`);this.#$=-1}}function S2(X,$){let Z=new aX(X),Y=new eX(Z),G=$.default();while(!Z.eof()){let J=Z.varint(),_=J>>3,W=J&7;Y.setup(W);let H=$[_];if(H!==void 0){let O=H(Y,G);if(O!==void 0)G=O}Y.maybeSkip()}return G}class d6{#X;#$;#Z;#Y;constructor(){this.#X=new ArrayBuffer(256),this.#$=new Uint8Array(this.#X),this.#Z=new DataView(this.#X),this.#Y=0}#G(X){if(this.#Y+X<=this.#X.byteLength)return;let $=this.#X.byteLength;while($<this.#Y+X)$*=2;let Z=new ArrayBuffer($),Y=new Uint8Array(Z),G=new DataView(Z);Y.set(new Uint8Array(this.#X,0,this.#Y)),this.#X=Z,this.#$=Y,this.#Z=G}#J(X){this.#G(5),X=0|X;do{let $=X&127;X>>>=7,$|=X?128:0,this.#$[this.#Y++]=$}while(X)}#W(X){this.#G(10),X=X&0xffffffffffffffffn;do{let $=Number(X&0x7fn);X>>=7n,$|=X?128:0,this.#$[this.#Y++]=$}while(X)}#_(X,$){this.#J(X<<3|$)}bytes(X,$){this.#_(X,Z0),this.#J($.byteLength),this.#G($.byteLength),this.#$.set($,this.#Y),this.#Y+=$.byteLength}string(X,$){this.bytes(X,new TextEncoder().encode($))}message(X,$,Z){let Y=new d6;Z(Y,$),this.bytes(X,Y.data())}int32(X,$){this.#_(X,s2),this.#J($)}uint32(X,$){this.int32(X,$)}bool(X,$){this.int32(X,$?1:0)}sint64(X,$){this.#_(X,s2),this.#W($<<1n^$>>63n)}double(X,$){this.#_(X,$0),this.#G(8),this.#Z.setFloat64(this.#Y,$,!0),this.#Y+=8}data(){return new Uint8Array(this.#X,0,this.#Y)}}function Y0(X,$){let Z=new d6;return $(Z,X),Z.data()}class p2{#X;#$;constructor(){this.#X=new Set,this.#$=new Set}alloc(){for(let $ of this.#$){if(this.#$.delete($),this.#X.add($),!this.#X.has(this.#X.size-1))this.#$.add(this.#X.size-1);return $}let X=this.#X.size;return this.#X.add(X),X}free(X){if(!this.#X.delete(X))throw new l("Freeing an id that is not allocated");if(this.#$.delete(this.#X.size),X<this.#X.size)this.#$.add(X)}}function j(X,$){throw new l($)}function R1(X){if(X===null)return null;else if(typeof X==="string")return X;else if(typeof X==="number"){if(!Number.isFinite(X))throw RangeError("Only finite numbers (not Infinity or NaN) can be passed as arguments");return X}else if(typeof X==="bigint"){if(X<CY||X>hY)throw RangeError("This bigint value is too large to be represented as a 64-bit integer and passed as argument");return X}else if(typeof X==="boolean")return X?1n:0n;else if(X instanceof ArrayBuffer)return new Uint8Array(X);else if(X instanceof Uint8Array)return X;else if(X instanceof Date)return+X.valueOf();else if(typeof X==="object")return""+X.toString();else throw TypeError("Unsupported type of value")}var CY=-9223372036854775808n,hY=9223372036854775807n;function m6(X,$){if(X===null)return null;else if(typeof X==="number")return X;else if(typeof X==="string")return X;else if(typeof X==="bigint")if($==="number"){let Z=Number(X);if(!Number.isSafeInteger(Z))throw RangeError("Received integer which is too large to be safely represented as a JavaScript number");return Z}else if($==="bigint")return X;else if($==="string")return""+X;else throw new I2("Invalid value for IntMode");else if(X instanceof Uint8Array)return X.slice().buffer;else if(X===void 0)throw new N("Received unrecognized type of Value");else throw j(X,"Impossible type of Value")}function a2(X){return{affectedRowCount:X.affectedRowCount,lastInsertRowid:X.lastInsertRowid,columnNames:X.cols.map(($)=>$.name),columnDecltypes:X.cols.map(($)=>$.decltype)}}function p0(X,$){let Z=a2(X),Y=X.rows.map((G)=>X$(Z.columnNames,G,$));return{...Z,rows:Y}}function b0(X,$){let Z=a2(X),Y;if(X.rows.length>0)Y=X$(Z.columnNames,X.rows[0],$);return{...Z,row:Y}}function g0(X,$){let Z=a2(X),Y;if(X.rows.length>0&&Z.columnNames.length>0)Y=m6(X.rows[0][0],$);return{...Z,value:Y}}function X$(X,$,Z){let Y={};Object.defineProperty(Y,"length",{value:$.length});for(let G=0;G<$.length;++G){let J=m6($[G],Z);Object.defineProperty(Y,G,{value:J});let _=X[G];if(_!==void 0&&!Object.hasOwn(Y,_))Object.defineProperty(Y,_,{value:J,enumerable:!0,configurable:!0,writable:!0})}return Y}function Q2(X){return new s1(X.message,X)}class e2{#X;#$;#Z;constructor(X,$){this.#X=X,this.#$=$,this.#Z=void 0}_getSqlId(X){if(this.#X!==X)throw new I2("Attempted to use SQL text opened with other object");else if(this.#Z!==void 0)throw new g("SQL text is closed",this.#Z);return this.#$}close(){this._setClosed(new Q("SQL text was manually closed"))}_setClosed(X){if(this.#Z===void 0)this.#Z=X,this.#X._closeSql(this.#$)}get closed(){return this.#Z!==void 0}}function G0(X,$){if($ instanceof e2)return{sqlId:$._getSqlId(X)};else return{sql:""+$}}class b2{#X;#$;constructor(){this.#X=[],this.#$=[]}get length(){return this.#X.length+this.#$.length}push(X){this.#X.push(X)}shift(){if(this.#$.length===0&&this.#X.length>0)this.#$=this.#X.reverse(),this.#X=[];return this.#$.pop()}first(){return this.#$.length!==0?this.#$[this.#$.length-1]:this.#X[0]}}class J0{sql;_args;_namedArgs;constructor(X){this.sql=X,this._args=[],this._namedArgs=new Map}bindIndexes(X){this._args.length=0;for(let $ of X)this._args.push(R1($));return this}bindIndex(X,$){if(X!==(X|0)||X<=0)throw RangeError("Index of a positional argument must be positive integer");while(this._args.length<X)this._args.push(null);return this._args[X-1]=R1($),this}bindName(X,$){return this._namedArgs.set(X,R1($)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function d0(X,$,Z){let Y,G=[],J=[];if($ instanceof J0){Y=$.sql,G=$._args;for(let[H,O]of $._namedArgs.entries())J.push({name:H,value:O})}else if(Array.isArray($))if(Y=$[0],Array.isArray($[1]))G=$[1].map((H)=>R1(H));else J=Object.entries($[1]).map(([H,O])=>{return{name:H,value:R1(O)}});else Y=$;let{sql:_,sqlId:W}=G0(X,Y);return{sql:_,sqlId:W,args:G,namedArgs:J,wantRows:Z}}class m0{_stream;#X;_steps;#$;constructor(X,$){this._stream=X,this.#X=$,this._steps=[],this.#$=!1}step(){return new u6(this)}execute(){if(this.#$)throw new I2("This batch has already been executed");this.#$=!0;let X={steps:this._steps.map(($)=>$.proto)};if(this.#X)return qY(this._stream,this._steps,X);else return fY(this._stream,this._steps,X)}}function fY(X,$,Z){return X._batch(Z).then((Y)=>{for(let G=0;G<$.length;++G){let J=Y.stepResults.get(G),_=Y.stepErrors.get(G);$[G].callback(J,_)}})}async function qY(X,$,Z){let Y=await X._openCursor(Z);try{let G=0,J=void 0,_=[];for(;;){let W=await Y.next();if(W===void 0)break;if(W.type==="step_begin"){if(W.step<G||W.step>=$.length)throw new N("Server produced StepBeginEntry for unexpected step");else if(J!==void 0)throw new N("Server produced StepBeginEntry before terminating previous step");for(let H=G;H<W.step;++H)$[H].callback(void 0,void 0);G=W.step+1,J=W,_=[]}else if(W.type==="step_end"){if(J===void 0)throw new N("Server produced StepEndEntry but no step is active");let H={cols:J.cols,rows:_,affectedRowCount:W.affectedRowCount,lastInsertRowid:W.lastInsertRowid};$[J.step].callback(H,void 0),J=void 0,_=[]}else if(W.type==="step_error"){if(J===void 0){if(W.step>=$.length)throw new N("Server produced StepErrorEntry for unexpected step");for(let H=G;H<W.step;++H)$[H].callback(void 0,void 0)}else{if(W.step!==J.step)throw new N("Server produced StepErrorEntry for unexpected step");J=void 0,_=[]}$[W.step].callback(void 0,W.error),G=W.step+1}else if(W.type==="row"){if(J===void 0)throw new N("Server produced RowEntry but no step is active");_.push(W.row)}else if(W.type==="error")throw Q2(W.error);else if(W.type==="none")throw new N("Server produced unrecognized CursorEntry");else throw j(W,"Impossible CursorEntry")}if(J!==void 0)throw new N("Server closed Cursor before terminating active step");for(let W=G;W<$.length;++W)$[W].callback(void 0,void 0)}finally{Y.close()}}class u6{_batch;#X;_index;constructor(X){this._batch=X,this.#X=[],this._index=void 0}condition(X){return this.#X.push(X._proto),this}query(X){return this.#$(X,!0,p0)}queryRow(X){return this.#$(X,!0,b0)}queryValue(X){return this.#$(X,!0,g0)}run(X){return this.#$(X,!1,a2)}#$(X,$,Z){if(this._index!==void 0)throw new I2("This BatchStep has already been added to the batch");let Y=d0(this._batch._stream._sqlOwner(),X,$),G;if(this.#X.length===0)G=void 0;else if(this.#X.length===1)G=this.#X[0];else G={type:"and",conds:this.#X.slice()};let J={stmt:Y,condition:G};return new Promise((_,W)=>{let H=(O,A)=>{if(O!==void 0&&A!==void 0)W(new N("Server returned both result and error"));else if(A!==void 0)W(Q2(A));else if(O!==void 0)_(Z(O,this._batch._stream.intMode));else _(void 0)};this._index=this._batch._steps.length,this._batch._steps.push({proto:J,callback:H})})}}class y{_batch;_proto;constructor(X,$){this._batch=X,this._proto=$}static ok(X){return new y(X._batch,{type:"ok",step:$$(X)})}static error(X){return new y(X._batch,{type:"error",step:$$(X)})}static not(X){return new y(X._batch,{type:"not",cond:X._proto})}static and(X,$){for(let Z of $)Z$(X,Z);return new y(X,{type:"and",conds:$.map((Z)=>Z._proto)})}static or(X,$){for(let Z of $)Z$(X,Z);return new y(X,{type:"or",conds:$.map((Z)=>Z._proto)})}static isAutocommit(X){return X._stream.client()._ensureVersion(3,"BatchCond.isAutocommit()"),new y(X,{type:"is_autocommit"})}}function $$(X){if(X._index===void 0)throw new I2("Cannot add a condition referencing a step that has not been added to the batch");return X._index}function Z$(X,$){if($._batch!==X)throw new I2("Cannot mix BatchCond objects for different Batch objects")}function Y$(X){return{paramNames:X.params.map(($)=>$.name),columns:X.cols,isExplain:X.isExplain,isReadonly:X.isReadonly}}class M1{constructor(X){this.intMode=X}query(X){return this.#X(X,!0,p0)}queryRow(X){return this.#X(X,!0,b0)}queryValue(X){return this.#X(X,!0,g0)}run(X){return this.#X(X,!1,a2)}#X(X,$,Z){let Y=d0(this._sqlOwner(),X,$);return this._execute(Y).then((G)=>Z(G,this.intMode))}batch(X=!1){return new m0(this,X)}describe(X){let $=G0(this._sqlOwner(),X);return this._describe($).then(Y$)}sequence(X){let $=G0(this._sqlOwner(),X);return this._sequence($)}intMode}class _0{}var yY=1000,SY=10;class c6 extends _0{#X;#$;#Z;#Y;#G;#J;#W;constructor(X,$,Z){super();this.#X=X,this.#$=$,this.#Z=Z,this.#Y=new b2,this.#G=new b2,this.#J=void 0,this.#W=!1}async next(){for(;;){if(this.#J!==void 0)throw new g("Cursor is closed",this.#J);while(!this.#W&&this.#G.length<SY)this.#G.push(this.#_());let X=this.#Y.shift();if(this.#W||X!==void 0)return X;await this.#G.shift().then(($)=>{if($===void 0)return;for(let Z of $.entries)this.#Y.push(Z);this.#W||=$.done})}}#_(){return this.#$._sendCursorRequest(this,{type:"fetch_cursor",cursorId:this.#Z,maxCount:yY}).then((X)=>X,(X)=>{this._setClosed(X);return})}_setClosed(X){if(this.#J!==void 0)return;this.#J=X,this.#$._sendCursorRequest(this,{type:"close_cursor",cursorId:this.#Z}).catch(()=>{return}),this.#$._cursorClosed(this)}close(){this._setClosed(new Q("Cursor was manually closed"))}get closed(){return this.#J!==void 0}}class W0 extends M1{#X;#$;#Z;#Y;#G;#J;static open(X){let $=X._streamIdAlloc.alloc(),Z=new W0(X,$),Y=()=>{return},G=(_)=>Z.#H(_),J={type:"open_stream",streamId:$};return X._sendRequest(J,{responseCallback:Y,errorCallback:G}),Z}constructor(X,$){super(X.intMode);this.#X=X,this.#$=$,this.#Z=new b2,this.#Y=void 0,this.#G=!1,this.#J=void 0}client(){return this.#X}_sqlOwner(){return this.#X}_execute(X){return this.#W({type:"execute",streamId:this.#$,stmt:X}).then(($)=>{return $.result})}_batch(X){return this.#W({type:"batch",streamId:this.#$,batch:X}).then(($)=>{return $.result})}_describe(X){return this.#X._ensureVersion(2,"describe()"),this.#W({type:"describe",streamId:this.#$,sql:X.sql,sqlId:X.sqlId}).then(($)=>{return $.result})}_sequence(X){return this.#X._ensureVersion(2,"sequence()"),this.#W({type:"sequence",streamId:this.#$,sql:X.sql,sqlId:X.sqlId}).then(($)=>{return})}getAutocommit(){return this.#X._ensureVersion(3,"getAutocommit()"),this.#W({type:"get_autocommit",streamId:this.#$}).then((X)=>{return X.isAutocommit})}#W(X){return new Promise(($,Z)=>{this.#_({type:"request",request:X,responseCallback:$,errorCallback:Z})})}_openCursor(X){return this.#X._ensureVersion(3,"cursor"),new Promise(($,Z)=>{this.#_({type:"cursor",batch:X,cursorCallback:$,errorCallback:Z})})}_sendCursorRequest(X,$){if(X!==this.#Y)throw new l("Cursor not associated with the stream attempted to execute a request");return new Promise((Z,Y)=>{if(this.#J!==void 0)Y(new g("Stream is closed",this.#J));else this.#X._sendRequest($,{responseCallback:Z,errorCallback:Y})})}_cursorClosed(X){if(X!==this.#Y)throw new l("Cursor was closed, but it was not associated with the stream");this.#Y=void 0,this.#z()}#_(X){if(this.#J!==void 0)X.errorCallback(new g("Stream is closed",this.#J));else if(this.#G)X.errorCallback(new g("Stream is closing",void 0));else this.#Z.push(X),this.#z()}#z(){for(;;){let X=this.#Z.first();if(X===void 0&&this.#Y===void 0&&this.#G){this.#H(new Q("Stream was gracefully closed"));break}else if(X?.type==="request"&&this.#Y===void 0){let{request:$,responseCallback:Z,errorCallback:Y}=X;this.#Z.shift(),this.#X._sendRequest($,{responseCallback:Z,errorCallback:Y})}else if(X?.type==="cursor"&&this.#Y===void 0){let{batch:$,cursorCallback:Z}=X;this.#Z.shift();let Y=this.#X._cursorIdAlloc.alloc(),G=new c6(this.#X,this,Y),J={type:"open_cursor",streamId:this.#$,cursorId:Y,batch:$},_=()=>{return},W=(H)=>G._setClosed(H);this.#X._sendRequest(J,{responseCallback:_,errorCallback:W}),this.#Y=G,Z(G)}else break}}#H(X){if(this.#J!==void 0)return;if(this.#J=X,this.#Y!==void 0)this.#Y._setClosed(X);for(;;){let G=this.#Z.shift();if(G!==void 0)G.errorCallback(X);else break}let $={type:"close_stream",streamId:this.#$},Z=()=>this.#X._streamIdAlloc.free(this.#$),Y=()=>{return};this.#X._sendRequest($,{responseCallback:Z,errorCallback:Y})}close(){this.#H(new Q("Stream was manually closed"))}closeGracefully(){this.#G=!0,this.#z()}get closed(){return this.#J!==void 0||this.#G}}function z0(X,$){if($.sql!==void 0)X.string("sql",$.sql);if($.sqlId!==void 0)X.number("sql_id",$.sqlId);X.arrayObjects("args",$.args,G$),X.arrayObjects("named_args",$.namedArgs,pY),X.boolean("want_rows",$.wantRows)}function pY(X,$){X.string("name",$.name),X.object("value",$.value,G$)}function N1(X,$){X.arrayObjects("steps",$.steps,bY)}function bY(X,$){if($.condition!==void 0)X.object("condition",$.condition,n6);X.object("stmt",$.stmt,z0)}function n6(X,$){if(X.stringRaw("type",$.type),$.type==="ok"||$.type==="error")X.number("step",$.step);else if($.type==="not")X.object("cond",$.cond,n6);else if($.type==="and"||$.type==="or")X.arrayObjects("conds",$.conds,n6);else if($.type==="is_autocommit");else throw j($,"Impossible type of BatchCond")}function G$(X,$){if($===null)X.stringRaw("type","null");else if(typeof $==="bigint")X.stringRaw("type","integer"),X.stringRaw("value",""+$);else if(typeof $==="number")X.stringRaw("type","float"),X.number("value",$);else if(typeof $==="string")X.stringRaw("type","text"),X.string("value",$);else if($ instanceof Uint8Array)X.stringRaw("type","blob"),X.stringRaw("base64",D1.fromUint8Array($));else if($===void 0);else throw j($,"Impossible type of Value")}function J$(X,$){if(X.stringRaw("type",$.type),$.type==="hello"){if($.jwt!==void 0)X.string("jwt",$.jwt)}else if($.type==="request")X.number("request_id",$.requestId),X.object("request",$.request,gY);else throw j($,"Impossible type of ClientMsg")}function gY(X,$){if(X.stringRaw("type",$.type),$.type==="open_stream")X.number("stream_id",$.streamId);else if($.type==="close_stream")X.number("stream_id",$.streamId);else if($.type==="execute")X.number("stream_id",$.streamId),X.object("stmt",$.stmt,z0);else if($.type==="batch")X.number("stream_id",$.streamId),X.object("batch",$.batch,N1);else if($.type==="open_cursor")X.number("stream_id",$.streamId),X.number("cursor_id",$.cursorId),X.object("batch",$.batch,N1);else if($.type==="close_cursor")X.number("cursor_id",$.cursorId);else if($.type==="fetch_cursor")X.number("cursor_id",$.cursorId),X.number("max_count",$.maxCount);else if($.type==="sequence"){if(X.number("stream_id",$.streamId),$.sql!==void 0)X.string("sql",$.sql);if($.sqlId!==void 0)X.number("sql_id",$.sqlId)}else if($.type==="describe"){if(X.number("stream_id",$.streamId),$.sql!==void 0)X.string("sql",$.sql);if($.sqlId!==void 0)X.number("sql_id",$.sqlId)}else if($.type==="store_sql")X.number("sql_id",$.sqlId),X.string("sql",$.sql);else if($.type==="close_sql")X.number("sql_id",$.sqlId);else if($.type==="get_autocommit")X.number("stream_id",$.streamId);else throw j($,"Impossible type of Request")}function H0(X,$){if($.sql!==void 0)X.string(1,$.sql);if($.sqlId!==void 0)X.int32(2,$.sqlId);for(let Z of $.args)X.message(3,Z,W$);for(let Z of $.namedArgs)X.message(4,Z,dY);X.bool(5,$.wantRows)}function dY(X,$){X.string(1,$.name),X.message(2,$.value,W$)}function I1(X,$){for(let Z of $.steps)X.message(1,Z,mY)}function mY(X,$){if($.condition!==void 0)X.message(1,$.condition,o6);X.message(2,$.stmt,H0)}function o6(X,$){if($.type==="ok")X.uint32(1,$.step);else if($.type==="error")X.uint32(2,$.step);else if($.type==="not")X.message(3,$.cond,o6);else if($.type==="and")X.message(4,$.conds,_$);else if($.type==="or")X.message(5,$.conds,_$);else if($.type==="is_autocommit")X.message(6,void 0,z$);else throw j($,"Impossible type of BatchCond")}function _$(X,$){for(let Z of $)X.message(1,Z,o6)}function W$(X,$){if($===null)X.message(1,void 0,z$);else if(typeof $==="bigint")X.sint64(2,$);else if(typeof $==="number")X.double(3,$);else if(typeof $==="string")X.string(4,$);else if($ instanceof Uint8Array)X.bytes(5,$);else if($===void 0);else throw j($,"Impossible type of Value")}function z$(X,$){}function H$(X,$){if($.type==="hello")X.message(1,$,uY);else if($.type==="request")X.message(2,$,cY);else throw j($,"Impossible type of ClientMsg")}function uY(X,$){if($.jwt!==void 0)X.string(1,$.jwt)}function cY(X,$){X.int32(1,$.requestId);let Z=$.request;if(Z.type==="open_stream")X.message(2,Z,nY);else if(Z.type==="close_stream")X.message(3,Z,oY);else if(Z.type==="execute")X.message(4,Z,iY);else if(Z.type==="batch")X.message(5,Z,rY);else if(Z.type==="open_cursor")X.message(6,Z,tY);else if(Z.type==="close_cursor")X.message(7,Z,lY);else if(Z.type==="fetch_cursor")X.message(8,Z,sY);else if(Z.type==="sequence")X.message(9,Z,aY);else if(Z.type==="describe")X.message(10,Z,eY);else if(Z.type==="store_sql")X.message(11,Z,X7);else if(Z.type==="close_sql")X.message(12,Z,$7);else if(Z.type==="get_autocommit")X.message(13,Z,Z7);else throw j(Z,"Impossible type of Request")}function nY(X,$){X.int32(1,$.streamId)}function oY(X,$){X.int32(1,$.streamId)}function iY(X,$){X.int32(1,$.streamId),X.message(2,$.stmt,H0)}function rY(X,$){X.int32(1,$.streamId),X.message(2,$.batch,I1)}function tY(X,$){X.int32(1,$.streamId),X.int32(2,$.cursorId),X.message(3,$.batch,I1)}function lY(X,$){X.int32(1,$.cursorId)}function sY(X,$){X.int32(1,$.cursorId),X.uint32(2,$.maxCount)}function aY(X,$){if(X.int32(1,$.streamId),$.sql!==void 0)X.string(2,$.sql);if($.sqlId!==void 0)X.int32(3,$.sqlId)}function eY(X,$){if(X.int32(1,$.streamId),$.sql!==void 0)X.string(2,$.sql);if($.sqlId!==void 0)X.int32(3,$.sqlId)}function X7(X,$){X.int32(1,$.sqlId),X.string(2,$.sql)}function $7(X,$){X.int32(1,$.sqlId)}function Z7(X,$){X.int32(1,$.streamId)}function g2(X){let $=X2(X.message),Z=G2(X.code);return{message:$,code:Z}}function O0(X){let $=V2(X.cols,O$),Z=e1(X.rows).map((_)=>V2(_,D$)),Y=T2(X.affected_row_count),G=G2(X.last_insert_rowid),J=G!==void 0?BigInt(G):void 0;return{cols:$,rows:Z,affectedRowCount:Y,lastInsertRowid:J}}function O$(X){let $=G2(X.name),Z=G2(X.decltype);return{name:$,decltype:Z}}function u0(X){let $=new Map;e1(X.step_results).forEach((Y,G)=>{if(Y!==null)$.set(G,O0(c(Y)))});let Z=new Map;return e1(X.step_errors).forEach((Y,G)=>{if(Y!==null)Z.set(G,g2(c(Y)))}),{stepResults:$,stepErrors:Z}}function c0(X){let $=X2(X.type);if($==="step_begin"){let Z=T2(X.step),Y=V2(X.cols,O$);return{type:"step_begin",step:Z,cols:Y}}else if($==="step_end"){let Z=T2(X.affected_row_count),Y=G2(X.last_insert_rowid),G=Y!==void 0?BigInt(Y):void 0;return{type:"step_end",affectedRowCount:Z,lastInsertRowid:G}}else if($==="step_error"){let Z=T2(X.step),Y=g2(c(X.error));return{type:"step_error",step:Z,error:Y}}else if($==="row")return{type:"row",row:V2(X.row,D$)};else if($==="error")return{type:"error",error:g2(c(X.error))};else throw new N("Unexpected type of CursorEntry")}function n0(X){let $=V2(X.params,Y7),Z=V2(X.cols,G7),Y=y2(X.is_explain),G=y2(X.is_readonly);return{params:$,cols:Z,isExplain:Y,isReadonly:G}}function Y7(X){return{name:G2(X.name)}}function G7(X){let $=X2(X.name),Z=G2(X.decltype);return{name:$,decltype:Z}}function D$(X){let $=X2(X.type);if($==="null")return null;else if($==="integer"){let Z=X2(X.value);return BigInt(Z)}else if($==="float")return T2(X.value);else if($==="text")return X2(X.value);else if($==="blob")return D1.toUint8Array(X2(X.base64));else throw new N("Unexpected type of Value")}function A$(X){let $=X2(X.type);if($==="hello_ok")return{type:"hello_ok"};else if($==="hello_error")return{type:"hello_error",error:g2(c(X.error))};else if($==="response_ok"){let Z=T2(X.request_id),Y=J7(c(X.response));return{type:"response_ok",requestId:Z,response:Y}}else if($==="response_error"){let Z=T2(X.request_id),Y=g2(c(X.error));return{type:"response_error",requestId:Z,error:Y}}else throw new N("Unexpected type of ServerMsg")}function J7(X){let $=X2(X.type);if($==="open_stream")return{type:"open_stream"};else if($==="close_stream")return{type:"close_stream"};else if($==="execute")return{type:"execute",result:O0(c(X.result))};else if($==="batch")return{type:"batch",result:u0(c(X.result))};else if($==="open_cursor")return{type:"open_cursor"};else if($==="close_cursor")return{type:"close_cursor"};else if($==="fetch_cursor"){let Z=V2(X.entries,c0),Y=y2(X.done);return{type:"fetch_cursor",entries:Z,done:Y}}else if($==="sequence")return{type:"sequence"};else if($==="describe")return{type:"describe",result:n0(c(X.result))};else if($==="store_sql")return{type:"store_sql"};else if($==="close_sql")return{type:"close_sql"};else if($==="get_autocommit")return{type:"get_autocommit",isAutocommit:y2(X.is_autocommit)};else throw new N("Unexpected type of Response")}var H2={default(){return{message:"",code:void 0}},1(X,$){$.message=X.string()},2(X,$){$.code=X.string()}},d2={default(){return{cols:[],rows:[],affectedRowCount:0,lastInsertRowid:void 0}},1(X,$){$.cols.push(X.message(U$))},2(X,$){$.rows.push(X.message(V$))},3(X,$){$.affectedRowCount=Number(X.uint64())},4(X,$){$.lastInsertRowid=X.sint64()}},U$={default(){return{name:void 0,decltype:void 0}},1(X,$){$.name=X.string()},2(X,$){$.decltype=X.string()}},V$={default(){return[]},1(X,$){$.push(X.message(U7))}},x1={default(){return{stepResults:new Map,stepErrors:new Map}},1(X,$){let[Z,Y]=X.message(_7);$.stepResults.set(Z,Y)},2(X,$){let[Z,Y]=X.message(W7);$.stepErrors.set(Z,Y)}},_7={default(){return[0,d2.default()]},1(X,$){$[0]=X.uint32()},2(X,$){$[1]=X.message(d2)}},W7={default(){return[0,H2.default()]},1(X,$){$[0]=X.uint32()},2(X,$){$[1]=X.message(H2)}},o0={default(){return{type:"none"}},1(X){return X.message(z7)},2(X){return X.message(H7)},3(X){return X.message(O7)},4(X){return{type:"row",row:X.message(V$)}},5(X){return{type:"error",error:X.message(H2)}}},z7={default(){return{type:"step_begin",step:0,cols:[]}},1(X,$){$.step=X.uint32()},2(X,$){$.cols.push(X.message(U$))}},H7={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(X,$){$.affectedRowCount=X.uint32()},2(X,$){$.lastInsertRowid=X.uint64()}},O7={default(){return{type:"step_error",step:0,error:H2.default()}},1(X,$){$.step=X.uint32()},2(X,$){$.error=X.message(H2)}},w1={default(){return{params:[],cols:[],isExplain:!1,isReadonly:!1}},1(X,$){$.params.push(X.message(D7))},2(X,$){$.cols.push(X.message(A7))},3(X,$){$.isExplain=X.bool()},4(X,$){$.isReadonly=X.bool()}},D7={default(){return{name:void 0}},1(X,$){$.name=X.string()}},A7={default(){return{name:"",decltype:void 0}},1(X,$){$.name=X.string()},2(X,$){$.decltype=X.string()}},U7={default(){return},1(X){return null},2(X){return X.sint64()},3(X){return X.double()},4(X){return X.string()},5(X){return X.bytes()}};var F$={default(){return{type:"none"}},1(X){return{type:"hello_ok"}},2(X){return X.message(V7)},3(X){return X.message(K7)},4(X){return X.message(F7)}},V7={default(){return{type:"hello_error",error:H2.default()}},1(X,$){$.error=X.message(H2)}},F7={default(){return{type:"response_error",requestId:0,error:H2.default()}},1(X,$){$.requestId=X.int32()},2(X,$){$.error=X.message(H2)}},K7={default(){return{type:"response_ok",requestId:0,response:{type:"none"}}},1(X,$){$.requestId=X.int32()},2(X,$){$.response={type:"open_stream"}},3(X,$){$.response={type:"close_stream"}},4(X,$){$.response=X.message(E7)},5(X,$){$.response=X.message(R7)},6(X,$){$.response={type:"open_cursor"}},7(X,$){$.response={type:"close_cursor"}},8(X,$){$.response=X.message(M7)},9(X,$){$.response={type:"sequence"}},10(X,$){$.response=X.message(N7)},11(X,$){$.response={type:"store_sql"}},12(X,$){$.response={type:"close_sql"}},13(X,$){$.response=X.message(I7)}},E7={default(){return{type:"execute",result:d2.default()}},1(X,$){$.result=X.message(d2)}},R7={default(){return{type:"batch",result:x1.default()}},1(X,$){$.result=X.message(x1)}},M7={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(X,$){$.entries.push(X.message(o0))},2(X,$){$.done=X.bool()}},N7={default(){return{type:"describe",result:w1.default()}},1(X,$){$.result=X.message(w1)}},I7={default(){return{type:"get_autocommit",isAutocommit:!1}},1(X,$){$.isAutocommit=X.bool()}};var K$=new Map([["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]),i6=new Map([["hrana3-protobuf",{version:3,encoding:"protobuf"}],["hrana3",{version:3,encoding:"json"}],["hrana2",{version:2,encoding:"json"}],["hrana1",{version:1,encoding:"json"}]]);class i0 extends F1{#X;#$;#Z;#Y;#G;#J;#W;#_;#z;_streamIdAlloc;_cursorIdAlloc;#H;constructor(X,$){super();this.#X=X,this.#$=[],this.#Z=!1,this.#Y=void 0,this.#G=!1,this.#J=void 0,this.#W=!1,this.#_=new Map,this.#z=new p2,this._streamIdAlloc=new p2,this._cursorIdAlloc=new p2,this.#H=new p2,this.#X.binaryType="arraybuffer",this.#X.addEventListener("open",()=>this.#V()),this.#X.addEventListener("close",(Z)=>this.#U(Z)),this.#X.addEventListener("error",(Z)=>this.#F(Z)),this.#X.addEventListener("message",(Z)=>this.#E(Z)),this.#D({type:"hello",jwt:$})}#D(X){if(this.#Y!==void 0)throw new l("Trying to send a message on a closed client");if(this.#Z)this.#A(X);else{let $=()=>this.#A(X),Z=()=>{return};this.#$.push({openCallback:$,errorCallback:Z})}}#V(){let X=this.#X.protocol;if(X===void 0){this.#O(new Q("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(X==="")this.#J={version:1,encoding:"json"};else if(this.#J=i6.get(X),this.#J===void 0){this.#O(new N(`Unrecognized WebSocket subprotocol: ${JSON.stringify(X)}`));return}for(let $ of this.#$)$.openCallback();this.#$.length=0,this.#Z=!0}#A(X){let $=this.#J.encoding;if($==="json"){let Z=X0(X,J$);this.#X.send(Z)}else if($==="protobuf"){let Z=Y0(X,H$);this.#X.send(Z)}else throw j($,"Impossible encoding")}getVersion(){return new Promise((X,$)=>{if(this.#W=!0,this.#Y!==void 0)$(this.#Y);else if(!this.#Z){let Z=()=>X(this.#J.version);this.#$.push({openCallback:Z,errorCallback:$})}else X(this.#J.version)})}_ensureVersion(X,$){if(this.#J===void 0||!this.#W)throw new U2(`${$} is supported only on protocol version ${X} 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.#J.version<X)throw new U2(`${$} is supported on protocol version ${X} and higher, but the WebSocket server only supports version ${this.#J.version}`)}_sendRequest(X,$){if(this.#Y!==void 0){$.errorCallback(new g("Client is closed",this.#Y));return}let Z=this.#z.alloc();this.#_.set(Z,{...$,type:X.type}),this.#D({type:"request",requestId:Z,request:X})}#F(X){let Z=X.message??"WebSocket was closed due to an error";this.#O(new K1(Z))}#U(X){let $=`WebSocket was closed with code ${X.code}`;if(X.reason)$+=`: ${X.reason}`;this.#O(new K1($))}#O(X){if(this.#Y!==void 0)return;this.#Y=X;for(let $ of this.#$)$.errorCallback(X);this.#$.length=0;for(let[$,Z]of this.#_.entries())Z.errorCallback(X),this.#z.free($);this.#_.clear(),this.#X.close()}#E(X){if(this.#Y!==void 0)return;try{let $,Z=this.#J.encoding;if(Z==="json"){if(typeof X.data!=="string"){this.#X.close(3003,"Only text messages are accepted with JSON encoding"),this.#O(new N("Received non-text message from server with JSON encoding"));return}$=l2(JSON.parse(X.data),A$)}else if(Z==="protobuf"){if(!(X.data instanceof ArrayBuffer)){this.#X.close(3003,"Only binary messages are accepted with Protobuf encoding"),this.#O(new N("Received non-binary message from server with Protobuf encoding"));return}$=S2(new Uint8Array(X.data),F$)}else throw j(Z,"Impossible encoding");this.#K($)}catch($){this.#X.close(3007,"Could not handle message"),this.#O($)}}#K(X){if(X.type==="none")throw new N("Received an unrecognized ServerMsg");else if(X.type==="hello_ok"||X.type==="hello_error"){if(this.#G)throw new N("Received a duplicated hello response");if(this.#G=!0,X.type==="hello_error")throw Q2(X.error);return}else if(!this.#G)throw new N("Received a non-hello message before a hello response");if(X.type==="response_ok"){let $=X.requestId,Z=this.#_.get($);if(this.#_.delete($),Z===void 0)throw new N("Received unexpected OK response");this.#z.free($);try{if(Z.type!==X.response.type)throw console.dir({responseState:Z,msg:X}),new N("Received unexpected type of response");Z.responseCallback(X.response)}catch(Y){throw Z.errorCallback(Y),Y}}else if(X.type==="response_error"){let $=X.requestId,Z=this.#_.get($);if(this.#_.delete($),Z===void 0)throw new N("Received unexpected error response");this.#z.free($),Z.errorCallback(Q2(X.error))}else throw j(X,"Impossible ServerMsg type")}openStream(){return W0.open(this)}storeSql(X){this._ensureVersion(2,"storeSql()");let $=this.#H.alloc(),Z=new e2(this,$),Y=()=>{return},G=(_)=>Z._setClosed(_),J={type:"store_sql",sqlId:$,sql:X};return this._sendRequest(J,{responseCallback:Y,errorCallback:G}),Z}_closeSql(X){if(this.#Y!==void 0)return;let $=()=>this.#H.free(X),Z=(G)=>this.#O(G),Y={type:"close_sql",sqlId:X};this._sendRequest(Y,{responseCallback:$,errorCallback:Z})}close(){this.#O(new Q("Client was manually closed"))}get closed(){return this.#Y!==void 0}}var D0=Request,r6=Headers,t6=fetch;var X1;if(typeof queueMicrotask<"u")X1=queueMicrotask;else{let X=Promise.resolve();X1=($)=>{X.then($)}}class l6{#X;#$;#Z;constructor(X){this.#X=new Uint8Array(new ArrayBuffer(X)),this.#$=0,this.#Z=0}get length(){return this.#Z-this.#$}data(){return this.#X.slice(this.#$,this.#Z)}push(X){this.#Y(X.byteLength),this.#X.set(X,this.#Z),this.#Z+=X.byteLength}#Y(X){if(this.#Z+X<=this.#X.byteLength)return;let $=this.#Z-this.#$;if($+X<=this.#X.byteLength&&2*this.#Z>=this.#X.byteLength)this.#X.copyWithin(0,this.#$,this.#Z);else{let Z=this.#X.byteLength;do Z*=2;while($+X>Z);let Y=new Uint8Array(new ArrayBuffer(Z));Y.set(this.#X.slice(this.#$,this.#Z),0),this.#X=Y}this.#Z=$,this.#$=0}shift(X){this.#$+=X}}function E$(X){let $=G2(X.baton),Z=G2(X.base_url),Y=V2(X.results,x7);return{baton:$,baseUrl:Z,results:Y}}function x7(X){let $=X2(X.type);if($==="ok")return{type:"ok",response:w7(c(X.response))};else if($==="error")return{type:"error",error:g2(c(X.error))};else throw new N("Unexpected type of StreamResult")}function w7(X){let $=X2(X.type);if($==="close")return{type:"close"};else if($==="execute")return{type:"execute",result:O0(c(X.result))};else if($==="batch")return{type:"batch",result:u0(c(X.result))};else if($==="sequence")return{type:"sequence"};else if($==="describe")return{type:"describe",result:n0(c(X.result))};else if($==="store_sql")return{type:"store_sql"};else if($==="close_sql")return{type:"close_sql"};else if($==="get_autocommit")return{type:"get_autocommit",isAutocommit:y2(X.is_autocommit)};else throw new N("Unexpected type of StreamResponse")}function R$(X){let $=G2(X.baton),Z=G2(X.base_url);return{baton:$,baseUrl:Z}}var M$={default(){return{baton:void 0,baseUrl:void 0,results:[]}},1(X,$){$.baton=X.string()},2(X,$){$.baseUrl=X.string()},3(X,$){$.results.push(X.message(P7))}},P7={default(){return{type:"none"}},1(X){return{type:"ok",response:X.message(k7)}},2(X){return{type:"error",error:X.message(H2)}}},k7={default(){return{type:"none"}},1(X){return{type:"close"}},2(X){return X.message(j7)},3(X){return X.message(T7)},4(X){return{type:"sequence"}},5(X){return X.message(Q7)},6(X){return{type:"store_sql"}},7(X){return{type:"close_sql"}},8(X){return X.message(B7)}},j7={default(){return{type:"execute",result:d2.default()}},1(X,$){$.result=X.message(d2)}},T7={default(){return{type:"batch",result:x1.default()}},1(X,$){$.result=X.message(x1)}},Q7={default(){return{type:"describe",result:w1.default()}},1(X,$){$.result=X.message(w1)}},B7={default(){return{type:"get_autocommit",isAutocommit:!1}},1(X,$){$.isAutocommit=X.bool()}},N$={default(){return{baton:void 0,baseUrl:void 0}},1(X,$){$.baton=X.string()},2(X,$){$.baseUrl=X.string()}};class s6 extends _0{#X;#$;#Z;#Y;#G;#J;constructor(X,$){super();this.#X=X,this.#$=$,this.#Z=void 0,this.#Y=new l6(16384),this.#G=void 0,this.#J=!1}async open(X){if(X.body===null)throw new N("No response body for cursor request");this.#Z=X.body.getReader();let $=await this.#W(R$,N$);if($===void 0)throw new N("Empty response to cursor request");return $}next(){return this.#W(c0,o0)}close(){this._setClosed(new Q("Cursor was manually closed"))}_setClosed(X){if(this.#G!==void 0)return;if(this.#G=X,this.#X._cursorClosed(this),this.#Z!==void 0)this.#Z.cancel()}get closed(){return this.#G!==void 0}async#W(X,$){for(;;){if(this.#J)return;else if(this.#G!==void 0)throw new g("Cursor is closed",this.#G);if(this.#$==="json"){let G=this.#_();if(G!==void 0){let J=new TextDecoder().decode(G),_=JSON.parse(J);return l2(_,X)}}else if(this.#$==="protobuf"){let G=this.#z();if(G!==void 0)return S2(G,$)}else throw j(this.#$,"Impossible encoding");if(this.#Z===void 0)throw new l("Attempted to read from HTTP cursor before it was opened");let{value:Z,done:Y}=await this.#Z.read();if(Y&&this.#Y.length===0)this.#J=!0;else if(Y)throw new N("Unexpected end of cursor stream");else this.#Y.push(Z)}}#_(){let X=this.#Y.data(),$=10,Z=X.indexOf(10);if(Z<0)return;let Y=X.slice(0,Z);return this.#Y.shift(Z+1),Y}#z(){let X=this.#Y.data(),$=0,Z=0;for(;;){if(Z>=X.byteLength)return;let G=X[Z];if($|=(G&127)<<7*Z,Z+=1,!(G&128))break}if(X.byteLength<Z+$)return;let Y=X.slice(Z,Z+$);return this.#Y.shift(Z+$),Y}}function I$(X,$){if($.baton!==void 0)X.string("baton",$.baton);X.arrayObjects("requests",$.requests,L7)}function L7(X,$){if(X.stringRaw("type",$.type),$.type==="close");else if($.type==="execute")X.object("stmt",$.stmt,z0);else if($.type==="batch")X.object("batch",$.batch,N1);else if($.type==="sequence"){if($.sql!==void 0)X.string("sql",$.sql);if($.sqlId!==void 0)X.number("sql_id",$.sqlId)}else if($.type==="describe"){if($.sql!==void 0)X.string("sql",$.sql);if($.sqlId!==void 0)X.number("sql_id",$.sqlId)}else if($.type==="store_sql")X.number("sql_id",$.sqlId),X.string("sql",$.sql);else if($.type==="close_sql")X.number("sql_id",$.sqlId);else if($.type==="get_autocommit");else throw j($,"Impossible type of StreamRequest")}function x$(X,$){if($.baton!==void 0)X.string("baton",$.baton);X.object("batch",$.batch,N1)}function w$(X,$){if($.baton!==void 0)X.string(1,$.baton);for(let Z of $.requests)X.message(2,Z,v7)}function v7(X,$){if($.type==="close")X.message(1,$,C7);else if($.type==="execute")X.message(2,$,h7);else if($.type==="batch")X.message(3,$,f7);else if($.type==="sequence")X.message(4,$,q7);else if($.type==="describe")X.message(5,$,y7);else if($.type==="store_sql")X.message(6,$,S7);else if($.type==="close_sql")X.message(7,$,p7);else if($.type==="get_autocommit")X.message(8,$,b7);else throw j($,"Impossible type of StreamRequest")}function C7(X,$){}function h7(X,$){X.message(1,$.stmt,H0)}function f7(X,$){X.message(1,$.batch,I1)}function q7(X,$){if($.sql!==void 0)X.string(1,$.sql);if($.sqlId!==void 0)X.int32(2,$.sqlId)}function y7(X,$){if($.sql!==void 0)X.string(1,$.sql);if($.sqlId!==void 0)X.int32(2,$.sqlId)}function S7(X,$){X.int32(1,$.sqlId),X.string(2,$.sql)}function p7(X,$){X.int32(1,$.sqlId)}function b7(X,$){}function P$(X,$){if($.baton!==void 0)X.string(1,$.baton);X.message(2,$.batch,I1)}class r0 extends M1{#X;#$;#Z;#Y;#G;#J;#W;#_;#z;#H;#D;#V;constructor(X,$,Z,Y){super(X.intMode);this.#X=X,this.#$=$.toString(),this.#Z=Z,this.#Y=Y,this.#G=void 0,this.#J=new b2,this.#W=!1,this.#z=!1,this.#H=!1,this.#D=void 0,this.#V=new p2}client(){return this.#X}_sqlOwner(){return this}storeSql(X){let $=this.#V.alloc();return this.#A({type:"store_sql",sqlId:$,sql:X}).then(()=>{return},(Z)=>this._setClosed(Z)),new e2(this,$)}_closeSql(X){if(this.#D!==void 0)return;this.#A({type:"close_sql",sqlId:X}).then(()=>this.#V.free(X),($)=>this._setClosed($))}_execute(X){return this.#A({type:"execute",stmt:X}).then(($)=>{return $.result})}_batch(X){return this.#A({type:"batch",batch:X}).then(($)=>{return $.result})}_describe(X){return this.#A({type:"describe",sql:X.sql,sqlId:X.sqlId}).then(($)=>{return $.result})}_sequence(X){return this.#A({type:"sequence",sql:X.sql,sqlId:X.sqlId}).then(($)=>{return})}getAutocommit(){return this.#X._ensureVersion(3,"getAutocommit()"),this.#A({type:"get_autocommit"}).then((X)=>{return X.isAutocommit})}#A(X){return new Promise(($,Z)=>{this.#F({type:"pipeline",request:X,responseCallback:$,errorCallback:Z})})}_openCursor(X){return new Promise(($,Z)=>{this.#F({type:"cursor",batch:X,cursorCallback:$,errorCallback:Z})})}_cursorClosed(X){if(X!==this.#_)throw new l("Cursor was closed, but it was not associated with the stream");this.#_=void 0,X1(()=>this.#U())}close(){this._setClosed(new Q("Stream was manually closed"))}closeGracefully(){this.#z=!0,X1(()=>this.#U())}get closed(){return this.#D!==void 0||this.#z}_setClosed(X){if(this.#D!==void 0)return;if(this.#D=X,this.#_!==void 0)this.#_._setClosed(X);this.#X._streamClosed(this);for(;;){let $=this.#J.shift();if($!==void 0)$.errorCallback(X);else break}if((this.#G!==void 0||this.#W)&&!this.#H)this.#J.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#H=!0,X1(()=>this.#U())}#F(X){if(this.#D!==void 0)throw new g("Stream is closed",this.#D);else if(this.#z)throw new g("Stream is closing",void 0);else this.#J.push(X),X1(()=>this.#U())}#U(){if(this.#W||this.#_!==void 0)return;if(this.#z&&this.#J.length===0){this._setClosed(new Q("Stream was gracefully closed"));return}let X=this.#X._endpoint;if(X===void 0){this.#X._endpointPromise.then(()=>this.#U(),(Z)=>this._setClosed(Z));return}let $=this.#J.shift();if($===void 0)return;else if($.type==="pipeline"){let Z=[$];for(;;){let Y=this.#J.first();if(Y!==void 0&&Y.type==="pipeline")Z.push(Y),this.#J.shift();else if(Y===void 0&&this.#z&&!this.#H){Z.push({type:"pipeline",request:{type:"close"},responseCallback:()=>{return},errorCallback:()=>{return}}),this.#H=!0;break}else break}this.#O(X,Z)}else if($.type==="cursor")this.#E(X,$);else throw j($,"Impossible type of QueueEntry")}#O(X,$){this.#K(()=>this.#M($,X),(Z)=>d7(Z,X.encoding),(Z)=>Z.baton,(Z)=>Z.baseUrl,(Z)=>g7($,Z),(Z)=>$.forEach((Y)=>Y.errorCallback(Z)))}#E(X,$){let Z=new s6(this,X.encoding);this.#_=Z,this.#K(()=>this.#N($,X),(Y)=>Z.open(Y),(Y)=>Y.baton,(Y)=>Y.baseUrl,(Y)=>$.cursorCallback(Z),(Y)=>$.errorCallback(Y))}#K(X,$,Z,Y,G,J){let _;try{let W=X(),H=this.#Y;_=H(W)}catch(W){_=Promise.reject(W)}this.#W=!0,_.then((W)=>{if(!W.ok)return m7(W).then((H)=>{throw H});return $(W)}).then((W)=>{this.#G=Z(W),this.#$=Y(W)??this.#$,G(W)}).catch((W)=>{this._setClosed(W),J(W)}).finally(()=>{this.#W=!1,this.#U()})}#M(X,$){return this.#R(new URL($.pipelinePath,this.#$),{baton:this.#G,requests:X.map((Z)=>Z.request)},$.encoding,I$,w$)}#N(X,$){if($.cursorPath===void 0)throw new U2(`Cursors are supported only on protocol version 3 and higher, but the HTTP server only supports version ${$.version}.`);return this.#R(new URL($.cursorPath,this.#$),{baton:this.#G,batch:X.batch},$.encoding,x$,P$)}#R(X,$,Z,Y,G){let J,_;if(Z==="json")J=X0($,Y),_="application/json";else if(Z==="protobuf")J=Y0($,G),_="application/x-protobuf";else throw j(Z,"Impossible encoding");let W=new r6;if(W.set("content-type",_),this.#Z!==void 0)W.set("authorization",`Bearer ${this.#Z}`);return new D0(X.toString(),{method:"POST",headers:W,body:J})}}function g7(X,$){if($.results.length!==X.length)throw new N("Server returned unexpected number of pipeline results");for(let Z=0;Z<X.length;++Z){let Y=$.results[Z],G=X[Z];if(Y.type==="ok"){if(Y.response.type!==G.request.type)throw new N("Received unexpected type of response");G.responseCallback(Y.response)}else if(Y.type==="error")G.errorCallback(Q2(Y.error));else if(Y.type==="none")throw new N("Received unrecognized type of StreamResult");else throw j(Y,"Received impossible type of StreamResult")}}async function d7(X,$){if($==="json"){let Z=await X.json();return l2(Z,E$)}if($==="protobuf"){let Z=await X.arrayBuffer();return S2(new Uint8Array(Z),M$)}throw await X.body?.cancel(),j($,"Impossible encoding")}async function m7(X){let $=X.headers.get("content-type")??"text/plain",Z=`Server returned HTTP status ${X.status}`;if($==="application/json"){let Y=await X.json();if("message"in Y)return Q2(Y);return new t2(Z,X.status)}if($==="text/plain"){let Y=(await X.text()).trim();if(Y!=="")Z+=`: ${Y}`;return new t2(Z,X.status)}return await X.body?.cancel(),new t2(Z,X.status)}var u7=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],a6={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};class t0 extends F1{#X;#$;#Z;#Y;#G;_endpointPromise;_endpoint;constructor(X,$,Z,Y=2){super();if(this.#X=X,this.#$=$,this.#Z=Z??t6,this.#Y=void 0,this.#G=new Set,Y==3)this._endpointPromise=c7(this.#Z,this.#X),this._endpointPromise.then((G)=>this._endpoint=G,(G)=>this.#J(G));else this._endpointPromise=Promise.resolve(a6),this._endpointPromise.then((G)=>this._endpoint=G,(G)=>this.#J(G))}async getVersion(){if(this._endpoint!==void 0)return this._endpoint.version;return(await this._endpointPromise).version}_ensureVersion(X,$){if(X<=a6.version)return;else if(this._endpoint===void 0)throw new U2(`${$} is supported only on protocol version ${X} 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<X)throw new U2(`${$} is supported only on protocol version ${X} and higher, but the HTTP server only supports version ${this._endpoint.version}.`)}openStream(){if(this.#Y!==void 0)throw new g("Client is closed",this.#Y);let X=new r0(this,this.#X,this.#$,this.#Z);return this.#G.add(X),X}_streamClosed(X){this.#G.delete(X)}close(){this.#J(new Q("Client was manually closed"))}get closed(){return this.#Y!==void 0}#J(X){if(this.#Y!==void 0)return;this.#Y=X;for(let $ of Array.from(this.#G))$._setClosed(new g("Client was closed",X))}}async function c7(X,$){let Z=X;for(let Y of u7){let G=new URL(Y.versionPath,$),J=new D0(G.toString(),{method:"GET"}),_=await Z(J);if(await _.arrayBuffer(),_.ok)return Y}return a6}function e6(X,$,Z=2){if(typeof l1.default>"u")throw new a1("WebSockets are not supported in this environment");var Y=void 0;if(Z==3)Y=Array.from(i6.keys());else Y=Array.from(K$.keys());let G=new l1.default(X,Y);return new i0(G,$)}function X4(X,$,Z,Y=2){return new t0(X instanceof URL?X:new URL(X),$,Z,Y)}class A0{#X;#$;#Z;constructor(X,$){this.#X=X,this.#$=$,this.#Z=void 0}execute(X){return this.batch([X]).then(($)=>$[0])}async batch(X){let $=this._getStream();if($.closed)throw new w("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{let Z=X.map(B2),Y;if(this.#Z===void 0){this._getSqlCache().apply(Z);let J=$.batch(this.#$>=3),_=J.step(),W=_.run(h2(this.#X)),H=_;Y=Z.map((O)=>{let A=J.step().condition(y.ok(H));if(this.#$>=3)A.condition(y.not(y.isAutocommit(J)));let E=A.query(O);return E.catch(()=>{return}),H=A,E}),this.#Z=J.execute().then(()=>W).then(()=>{return});try{await this.#Z}catch(O){throw this.close(),O}}else{if(this.#$<3)await this.#Z;this._getSqlCache().apply(Z);let J=$.batch(this.#$>=3),_=void 0;Y=Z.map((W)=>{let H=J.step();if(_!==void 0)H.condition(y.ok(_));if(this.#$>=3)H.condition(y.not(y.isAutocommit(J)));let O=H.query(W);return O.catch(()=>{return}),_=H,O}),await J.execute()}let G=[];for(let J of Y){let _=await J;if(_===void 0)throw new w("Statement in a transaction was not executed, probably because the transaction has been rolled back","TRANSACTION_CLOSED");G.push(k1(_))}return G}catch(Z){throw p(Z)}}async executeMultiple(X){let $=this._getStream();if($.closed)throw new w("Cannot execute statements because the transaction is closed","TRANSACTION_CLOSED");try{if(this.#Z===void 0){this.#Z=$.run(h2(this.#X)).then(()=>{return});try{await this.#Z}catch(Z){throw this.close(),Z}}else await this.#Z;await $.sequence(X)}catch(Z){throw p(Z)}}async rollback(){try{let X=this._getStream();if(X.closed)return;if(this.#Z!==void 0);else return;let $=X.run("ROLLBACK").catch((Z)=>{throw p(Z)});X.closeGracefully(),await $}catch(X){throw p(X)}finally{this.close()}}async commit(){try{let X=this._getStream();if(X.closed)throw new w("Cannot commit the transaction because it is already closed","TRANSACTION_CLOSED");if(this.#Z!==void 0)await this.#Z;else return;let $=X.run("COMMIT").catch((Z)=>{throw p(Z)});X.closeGracefully(),await $}catch(X){throw p(X)}finally{this.close()}}}async function P1(X,$,Z,Y,G=!1){if(G)Z.step().run("PRAGMA foreign_keys=off");let J=Z.step(),_=J.run(h2(X)),W=J,H=Y.map((R)=>{let M=Z.step().condition(y.ok(W));if($>=3)M.condition(y.not(y.isAutocommit(Z)));let x=M.query(R);return W=M,x}),O=Z.step().condition(y.ok(W));if($>=3)O.condition(y.not(y.isAutocommit(Z)));let A=O.run("COMMIT");if(Z.step().condition(y.not(y.ok(O))).run("ROLLBACK").catch((R)=>{return}),G)Z.step().run("PRAGMA foreign_keys=on");await Z.execute();let V=[];await _;for(let R of H){let M=await R;if(M===void 0)throw new w("Statement in a batch was not executed, probably because the transaction has been rolled back","TRANSACTION_CLOSED");V.push(k1(M))}return await A,V}function B2(X){let $,Z;if(Array.isArray(X))[$,Z]=X;else if(typeof X==="string")$=X;else $=X.sql,Z=X.args;let Y=new J0($);if(Z)if(Array.isArray(Z))Y.bindIndexes(Z);else for(let[G,J]of Object.entries(Z))Y.bindName(G,J);return Y}function k1(X){let $=X.columnNames.map((_)=>_??""),Z=X.columnDecltypes.map((_)=>_??""),Y=X.rows,G=X.affectedRowCount,J=X.lastInsertRowid!==void 0?X.lastInsertRowid:void 0;return new A1($,Z,Y,G,J)}function p(X){if(X instanceof Q){let $=k$(X);return new w(X.message,$,void 0,X)}return X}function k$(X){if(X instanceof s1&&X.code!==void 0)return X.code;else if(X instanceof N)return"HRANA_PROTO_ERROR";else if(X instanceof g)return X.cause instanceof Q?k$(X.cause):"HRANA_CLOSED_ERROR";else if(X instanceof K1)return"HRANA_WEBSOCKET_ERROR";else if(X instanceof t2)return"SERVER_ERROR";else if(X instanceof U2)return"PROTOCOL_VERSION_ERROR";else if(X instanceof l)return"INTERNAL_ERROR";else return"UNKNOWN"}class j1{#X;#$;capacity;constructor(X,$){this.#X=X,this.#$=new j$,this.capacity=$}apply(X){if(this.capacity<=0)return;let $=new Set;for(let Z of X){if(typeof Z.sql!=="string")continue;let Y=Z.sql;if(Y.length>=5000)continue;let G=this.#$.get(Y);if(G===void 0){while(this.#$.size+1>this.capacity){let[J,_]=this.#$.peekLru();if($.has(_))break;_.close(),this.#$.delete(J)}if(this.#$.size+1<=this.capacity)G=this.#X.storeSql(Y),this.#$.set(Y,G)}if(G!==void 0)Z.sql=G,$.add(G)}}}class j${#X;constructor(){this.#X=new Map}get(X){let $=this.#X.get(X);if($!==void 0)this.#X.delete(X),this.#X.set(X,$);return $}set(X,$){this.#X.set(X,$)}peekLru(){for(let X of this.#X.entries())return X;return}delete(X){this.#X.delete(X)}get size(){return this.#X.size}}var L$=g6(Z4(),1);function v$(X){if(X.scheme!=="wss"&&X.scheme!=="ws")throw new w(`The WebSocket client supports only "libsql:", "wss:" and "ws:" URLs, got ${JSON.stringify(X.scheme+":")}. For more information, please read ${R2}`,"URL_SCHEME_NOT_SUPPORTED");if(X.encryptionKey!==void 0)throw new w("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(X.scheme==="ws"&&X.tls)throw new w('A "ws:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(X.scheme==="wss"&&!X.tls)throw new w('A "wss:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let $=o1(X.scheme,X.authority,X.path),Z;try{Z=e6($,X.authToken)}catch(Y){if(Y instanceof a1){let G=X.scheme==="wss"?"https":"http",J=o1(G,X.authority,X.path);throw new w(`This environment does not support WebSockets, please switch to the HTTP client by using a "${G}:" URL (${JSON.stringify(J)}). For more information, please read ${R2}`,"WEBSOCKETS_NOT_SUPPORTED")}throw p(Y)}return new C$(Z,$,X.authToken,X.intMode,X.concurrency)}var i7=60000,B$=100;class C${#X;#$;#Z;#Y;#G;closed;protocol;#J;#W;constructor(X,$,Z,Y,G){this.#X=$,this.#$=Z,this.#Z=Y,this.#Y=this.#z(X),this.#G=void 0,this.closed=!1,this.protocol="ws",this.#W=L$.default(G)}async limit(X){return this.#W(X)}async execute(X,$){let Z;if(typeof X==="string")Z={sql:X,args:$||[]};else Z=X;return this.limit(async()=>{let Y=await this.#_();try{let G=B2(Z);Y.conn.sqlCache.apply([G]);let J=Y.stream.query(G);Y.stream.closeGracefully();let _=await J;return k1(_)}catch(G){throw p(G)}finally{this._closeStream(Y)}})}async batch(X,$="deferred"){return this.limit(async()=>{let Z=await this.#_();try{let G=X.map((O)=>{if(Array.isArray(O))return{sql:O[0],args:O[1]||[]};return O}).map(B2),J=await Z.conn.client.getVersion();Z.conn.sqlCache.apply(G);let _=Z.stream.batch(J>=3);return await P1($,J,_,G)}catch(Y){throw p(Y)}finally{this._closeStream(Z)}})}async migrate(X){return this.limit(async()=>{let $=await this.#_();try{let Z=X.map(B2),Y=await $.conn.client.getVersion(),G=$.stream.batch(Y>=3);return await P1("deferred",Y,G,Z,!0)}catch(Z){throw p(Z)}finally{this._closeStream($)}})}async transaction(X="write"){return this.limit(async()=>{let $=await this.#_();try{let Z=await $.conn.client.getVersion();return new h$(this,$,X,Z)}catch(Z){throw this._closeStream($),p(Z)}})}async executeMultiple(X){return this.limit(async()=>{let $=await this.#_();try{let Z=$.stream.sequence(X);$.stream.closeGracefully(),await Z}catch(Z){throw p(Z)}finally{this._closeStream($)}})}sync(){throw new w("sync not supported in ws mode","SYNC_NOT_SUPPORTED")}async#_(){if(this.closed)throw new w("The client is closed","CLIENT_CLOSED");if(new Date().valueOf()-this.#Y.openTime.valueOf()>i7&&this.#G===void 0){let Y=this.#z();this.#G=Y,Y.client.getVersion().then((G)=>{if(this.#Y!==Y){if(this.#Y.streamStates.size===0)this.#Y.client.close()}this.#Y=Y,this.#G=void 0},(G)=>{this.#G=void 0})}if(this.#Y.client.closed)try{if(this.#G!==void 0)this.#Y=this.#G;else this.#Y=this.#z()}catch(Y){throw p(Y)}let Z=this.#Y;try{if(Z.useSqlCache===void 0){if(Z.useSqlCache=await Z.client.getVersion()>=2,Z.useSqlCache)Z.sqlCache.capacity=B$}let Y=Z.client.openStream();Y.intMode=this.#Z;let G={conn:Z,stream:Y};return Z.streamStates.add(G),G}catch(Y){throw p(Y)}}#z(X){try{return X??=e6(this.#X,this.#$),{client:X,useSqlCache:void 0,sqlCache:new j1(X,0),openTime:new Date,streamStates:new Set}}catch($){throw p($)}}async reconnect(){try{for(let Z of Array.from(this.#Y.streamStates))try{Z.stream.close()}catch{}this.#Y.client.close()}catch{}if(this.#G){try{this.#G.client.close()}catch{}this.#G=void 0}let X=this.#z(),$=await X.client.getVersion();if(X.useSqlCache=$>=2,X.useSqlCache)X.sqlCache.capacity=B$;this.#Y=X,this.closed=!1}_closeStream(X){X.stream.close();let $=X.conn;if($.streamStates.delete(X),$.streamStates.size===0&&$!==this.#Y)$.client.close()}close(){if(this.#Y.client.close(),this.closed=!0,this.#G){try{this.#G.client.close()}catch{}this.#G=void 0}this.closed=!0}}class h$ extends A0{#X;#$;constructor(X,$,Z,Y){super(Z,Y);this.#X=X,this.#$=$}_getStream(){return this.#$.stream}_getSqlCache(){return this.#$.conn.sqlCache}close(){this.#X._closeStream(this.#$)}get closed(){return this.#$.stream.closed}}var f$=g6(Z4(),1);function q$(X){if(X.scheme!=="https"&&X.scheme!=="http")throw new w(`The HTTP client supports only "libsql:", "https:" and "http:" URLs, got ${JSON.stringify(X.scheme+":")}. For more information, please read ${R2}`,"URL_SCHEME_NOT_SUPPORTED");if(X.encryptionKey!==void 0)throw new w("Encryption key is not supported by the remote client.","ENCRYPTION_KEY_NOT_SUPPORTED");if(X.scheme==="http"&&X.tls)throw new w('A "http:" URL cannot opt into TLS by using ?tls=1',"URL_INVALID");else if(X.scheme==="https"&&!X.tls)throw new w('A "https:" URL cannot opt out of TLS by using ?tls=0',"URL_INVALID");let $=o1(X.scheme,X.authority,X.path);return new S$($,X.authToken,X.intMode,X.fetch,X.concurrency)}var y$=30;class S${#X;protocol;#$;#Z;#Y;#G;#J;#W;constructor(X,$,Z,Y,G){this.#$=X,this.#J=$,this.#Z=Z,this.#Y=Y,this.#G=G,this.#X=X4(this.#$,this.#J,this.#Y),this.#X.intMode=this.#Z,this.protocol="http",this.#W=f$.default(this.#G)}async limit(X){return this.#W(X)}async execute(X,$){let Z;if(typeof X==="string")Z={sql:X,args:$||[]};else Z=X;return this.limit(async()=>{try{let Y=B2(Z),G,J=this.#X.openStream();try{G=J.query(Y)}finally{J.closeGracefully()}let _=await G;return k1(_)}catch(Y){throw p(Y)}})}async batch(X,$="deferred"){return this.limit(async()=>{try{let Y=X.map((H)=>{if(Array.isArray(H))return{sql:H[0],args:H[1]||[]};return H}).map(B2),G=await this.#X.getVersion(),J,_=this.#X.openStream();try{new j1(_,y$).apply(Y);let O=_.batch(!1);J=P1($,G,O,Y)}finally{_.closeGracefully()}return await J}catch(Z){throw p(Z)}})}async migrate(X){return this.limit(async()=>{try{let $=X.map(B2),Z=await this.#X.getVersion(),Y,G=this.#X.openStream();try{let _=G.batch(!1);Y=P1("deferred",Z,_,$,!0)}finally{G.closeGracefully()}return await Y}catch($){throw p($)}})}async transaction(X="write"){return this.limit(async()=>{try{let $=await this.#X.getVersion();return new p$(this.#X.openStream(),X,$)}catch($){throw p($)}})}async executeMultiple(X){return this.limit(async()=>{try{let $,Z=this.#X.openStream();try{$=Z.sequence(X)}finally{Z.closeGracefully()}await $}catch($){throw p($)}})}sync(){throw new w("sync not supported in http mode","SYNC_NOT_SUPPORTED")}close(){this.#X.close()}async reconnect(){try{if(!this.closed)this.#X.close()}finally{this.#X=X4(this.#$,this.#J,this.#Y),this.#X.intMode=this.#Z}}get closed(){return this.#X.closed}}class p$ extends A0{#X;#$;constructor(X,$,Z){super($,Z);this.#X=X,this.#$=new j1(X,y$)}_getStream(){return this.#X}_getSqlCache(){return this.#$}close(){this.#X.close()}get closed(){return this.#X.closed}}function T1(X){return r7(r1(X,!0))}function r7(X){if(X.scheme==="wss"||X.scheme==="ws")return v$(X);else if(X.scheme==="https"||X.scheme==="http")return q$(X);else return nX(X)}class s0 extends v6{constructor(X,$,Z,Y,G){super($);this.client=X,this.schema=Z,this.options=Y,this.tx=G,this.logger=Y.logger??new D6,this.cache=Y.cache??new u1}static[D]="LibSQLSession";logger;cache;prepareQuery(X,$,Z,Y,G,J,_){return new g$(this.client,X,this.logger,this.cache,J,_,$,this.tx,Z,Y,G)}async batch(X){let $=[],Z=[];for(let G of X){let J=G._prepare(),_=J.getQuery();$.push(J),Z.push({sql:_.sql,args:_.params})}return(await this.client.batch(Z)).map((G,J)=>$[J].mapResult(G,!0))}async migrate(X){let $=[],Z=[];for(let G of X){let J=G._prepare(),_=J.getQuery();$.push(J),Z.push({sql:_.sql,args:_.params})}return(await this.client.migrate(Z)).map((G,J)=>$[J].mapResult(G,!0))}async transaction(X,$){let Z=await this.client.transaction(),Y=new s0(this.client,this.dialect,this.schema,this.options,Z),G=new Y4("async",this.dialect,Y,this.schema);try{let J=await X(G);return await Z.commit(),J}catch(J){throw await Z.rollback(),J}}extractRawAllValueFromBatchResult(X){return X.rows}extractRawGetValueFromBatchResult(X){return X.rows[0]}extractRawValuesValueFromBatchResult(X){return X.rows}}class Y4 extends C6{static[D]="LibSQLTransaction";async transaction(X){let $=`sp${this.nestedIndex}`,Z=new Y4("async",this.dialect,this.session,this.schema,this.nestedIndex+1);await this.session.run(z.raw(`savepoint ${$}`));try{let Y=await X(Z);return await this.session.run(z.raw(`release savepoint ${$}`)),Y}catch(Y){throw await this.session.run(z.raw(`rollback to savepoint ${$}`)),Y}}}class g$ extends L6{constructor(X,$,Z,Y,G,J,_,W,H,O,A){super("async",H,$,Y,G,J);this.client=X,this.logger=Z,this.fields=_,this.tx=W,this._isResponseInArrayMode=O,this.customResultMapper=A,this.customResultMapper=A,this.fields=_}static[D]="LibSQLPreparedQuery";async run(X){let $=h1(this.query.params,X??{});return this.logger.logQuery(this.query.sql,$),await this.queryWithCache(this.query.sql,$,async()=>{let Z={sql:this.query.sql,args:$};return this.tx?this.tx.execute(Z):this.client.execute(Z)})}async all(X){let{fields:$,logger:Z,query:Y,tx:G,client:J,customResultMapper:_}=this;if(!$&&!_){let H=h1(Y.params,X??{});return Z.logQuery(Y.sql,H),await this.queryWithCache(Y.sql,H,async()=>{let O={sql:Y.sql,args:H};return(G?G.execute(O):J.execute(O)).then(({rows:A})=>this.mapAllResult(A))})}let W=await this.values(X);return this.mapAllResult(W)}mapAllResult(X,$){if($)X=X.rows;if(!this.fields&&!this.customResultMapper)return X.map((Z)=>b$(Z));if(this.customResultMapper)return this.customResultMapper(X,l0);return X.map((Z)=>{return A6(this.fields,Array.prototype.slice.call(Z).map((Y)=>l0(Y)),this.joinsNotNullableMap)})}async get(X){let{fields:$,logger:Z,query:Y,tx:G,client:J,customResultMapper:_}=this;if(!$&&!_){let H=h1(Y.params,X??{});return Z.logQuery(Y.sql,H),await this.queryWithCache(Y.sql,H,async()=>{let O={sql:Y.sql,args:H};return(G?G.execute(O):J.execute(O)).then(({rows:A})=>this.mapGetResult(A))})}let W=await this.values(X);return this.mapGetResult(W)}mapGetResult(X,$){if($)X=X.rows;let Z=X[0];if(!this.fields&&!this.customResultMapper)return b$(Z);if(!Z)return;if(this.customResultMapper)return this.customResultMapper(X,l0);return A6(this.fields,Array.prototype.slice.call(Z).map((Y)=>l0(Y)),this.joinsNotNullableMap)}async values(X){let $=h1(this.query.params,X??{});return this.logger.logQuery(this.query.sql,$),await this.queryWithCache(this.query.sql,$,async()=>{let Z={sql:this.query.sql,args:$};return(this.tx?this.tx.execute(Z):this.client.execute(Z)).then(({rows:Y})=>Y)})}isResponseInArrayMode(){return this._isResponseInArrayMode}}function b$(X){return Object.keys(X).reduce(($,Z)=>{if(Object.prototype.propertyIsEnumerable.call(X,Z))$[Z]=X[Z];return $},{})}function l0(X){if(typeof ArrayBuffer<"u"&&X instanceof ArrayBuffer){if(typeof Buffer<"u"){if(!(X instanceof Buffer))return Buffer.from(X);return X}if(typeof TextDecoder<"u")return new TextDecoder().decode(X);throw Error("TextDecoder is not available. Please provide either Buffer or TextDecoder polyfill.")}return X}class d$ extends m1{static[D]="LibSQLDatabase";async batch(X){return this.session.batch(X)}}function Q1(X,$={}){let Z=new w6({casing:$.casing}),Y;if($.logger===!0)Y=new O6;else if($.logger!==!1)Y=$.logger;let G;if($.schema){let W=l4($.schema,a4);G={fullSchema:$.schema,schema:W.tables,tableNamesMap:W.tableNamesMap}}let J=new s0(X,Z,G,{logger:Y,cache:$.cache},void 0),_=new d$("async",Z,J,G);if(_.$client=X,_.$cache=$.cache,_.$cache)_.$cache.invalidate=$.cache?.onMutate;return _}function a0(...X){if(typeof X[0]==="string"){let $=T1({url:X[0]});return Q1($,X[1])}if(k4(X[0])){let{connection:$,client:Z,...Y}=X[0];if(Z)return Q1(Z,Y);let G=typeof $==="string"?T1({url:$}):T1($);return Q1(G,Y)}return Q1(X[0],X[1])}((X)=>{function $(Z){return Q1({},Z)}X.mock=$})(a0||(a0={}));import t7 from"node:crypto";import G4 from"node:fs";function m$(X){let $=X.migrationsFolder,Z=[],Y=`${$}/meta/_journal.json`;if(!G4.existsSync(Y))throw Error("Can't find meta/_journal.json file");let G=G4.readFileSync(`${$}/meta/_journal.json`).toString(),J=JSON.parse(G);for(let _ of J.entries){let W=`${$}/${_.tag}.sql`;try{let H=G4.readFileSync(`${$}/${_.tag}.sql`).toString(),O=H.split("--> statement-breakpoint").map((A)=>{return A});Z.push({sql:O,bps:_.breakpoints,folderMillis:_.when,hash:t7.createHash("sha256").update(H).digest("hex")})}catch{throw Error(`No file ${W} found in ${$} folder`)}}return Z}async function u$(X,$){let Z=m$($),Y=$.migrationsTable??"__drizzle_migrations",G=z`
15
+ CREATE TABLE IF NOT EXISTS ${z.identifier(Y)} (
16
+ id SERIAL PRIMARY KEY,
17
+ hash text NOT NULL,
18
+ created_at numeric
19
+ )
20
+ `;await X.session.run(G);let _=(await X.values(z`SELECT id, hash, created_at FROM ${z.identifier(Y)} ORDER BY created_at DESC LIMIT 1`))[0]??void 0,W=[];for(let H of Z)if(!_||Number(_[2])<H.folderMillis){for(let O of H.sql)W.push(X.run(z.raw(O)));W.push(X.run(z`INSERT INTO ${z.identifier(Y)} ("hash", "created_at") VALUES(${H.hash}, ${H.folderMillis})`))}await X.session.migrate(W)}import{readFile as l7,writeFile as WO,mkdir as zO}from"node:fs/promises";import{join as J4}from"node:path";import{homedir as s7}from"node:os";var c$=J4(s7(),".sylphx","sessions"),DO=J4(c$,".last-session");function a7(X){return J4(c$,`${X}.json`)}async function n$(X){try{let $=a7(X),Z=await l7($,"utf8"),Y=JSON.parse(Z);if(!Y.todos)Y.todos=[];if(typeof Y.nextTodoId!=="number")Y.nextTodoId=1;if(Array.isArray(Y.messages))Y.messages=Y.messages.map((G)=>{if(typeof G.content==="string")return{...G,content:[{type:"text",content:G.content}]};return G});return Y}catch{return null}}function AO(X,$,Z){return{...X,messages:[...X.messages,{role:$,content:[{type:"text",content:Z}],timestamp:Date.now()}]}}var H4=B1(i$(),".sylphx","sessions"),O4=B1(i$(),".sylphx-flow"),ZG=B1(O4,"memory.db"),_4=B1(O4,".session-migrated");function YG(){let X=$G(import.meta.url),$=o$(X);for(let Z=0;Z<10;Z++){let Y=B1($,"package.json");if(z4(Y))return $;let G=o$($);if(G===$)break;$=G}throw Error("Cannot find package.json - drizzle migrations location unknown")}async function GG(X){try{if((await X.all(z`SELECT name FROM sqlite_master WHERE type='table' AND name='sessions'`)).length===0)return!0;if(z4(_4))return!1;try{let Y=(await W4(H4)).filter((_)=>_.endsWith(".json")&&!_.startsWith("."));if(Y.length===0)return!1;return await new z1(X).getSessionCount()===0&&Y.length>0}catch{return!1}}catch{return!0}}async function JG(X){await e7(O4,{recursive:!0});let $=YG(),Z=B1($,"drizzle");if(!z4(Z))throw Error(`Drizzle migrations not found at ${Z}`);await u$(X,{migrationsFolder:Z})}async function _G(X,$){let Z=new z1(X),G=(await W4(H4)).filter((W)=>W.endsWith(".json")&&!W.startsWith(".")),J=0,_=0;$?.({total:G.length,current:0,status:`Found ${G.length} sessions to migrate`});for(let W=0;W<G.length;W++){let O=G[W].replace(".json","");try{$?.({total:G.length,current:W+1,status:`Migrating session ${W+1}/${G.length}`});let A=await n$(O);if(!A){_++;continue}if(await Z.getSessionById(A.id))continue;await Z.createSessionFromData({id:A.id,provider:A.provider,model:A.model,title:A.title,nextTodoId:A.nextTodoId||1,created:A.created,updated:A.updated});for(let V of A.messages)await Z.addMessage(A.id,V.role,V.content,V.attachments,V.usage,V.finishReason,V.metadata,V.todoSnapshot);if(A.todos&&A.todos.length>0)await Z.updateTodos(A.id,A.todos,A.nextTodoId);J++}catch(A){console.error(`Error migrating ${O}:`,A),_++}}return await XG(_4,"utf8").catch(()=>k2("fs").writeFileSync(_4,new Date().toISOString())),{success:J,errors:_}}async function WG(X){let $=process.env.DATABASE_URL||`file:${ZG}`,Z=T1({url:$}),Y=a0(Z);if(await Z.execute("PRAGMA journal_mode = WAL"),await Z.execute("PRAGMA busy_timeout = 5000"),await Z.execute("PRAGMA synchronous = NORMAL"),!await GG(Y))return Y;X?.({total:2,current:0,status:"Initializing database..."}),await JG(Y),X?.({total:2,current:1,status:"Database initialized"});try{let _=(await W4(H4)).filter((W)=>W.endsWith(".json")&&!W.startsWith("."));if(_.length>0){X?.({total:2+_.length,current:1,status:`Migrating ${_.length} sessions from files...`});let W=await _G(Y,(H)=>{X?.({total:2+H.total,current:1+H.current,status:H.status})});X?.({total:2+_.length,current:2+_.length,status:`Migration complete! ${W.success} sessions migrated`})}}catch{}return Y}async function r$(X){return WG(X)}var OG=zG(HG(),".sylphx-flow","memory.db"),vO=process.env.DATABASE_URL||`file:${OG}`,e0=null,X6=null,U0=null;async function DG(){if(e0)return e0;if(U0)return U0;return U0=r$((X)=>{if(process.env.DEBUG)console.log(`[DB] ${X.current}/${X.total}: ${X.status}`)}),e0=await U0,U0=null,e0}async function CO(){if(X6)return X6;let X=await DG();return X6=new z1(X),X6}
21
+ export{z as fa,r as ga,p1 as ha,L4 as ia,I0 as ja,G1 as ka,b as la,J1 as ma,I as na,e as oa,f as pa,N6 as qa,T1 as ra,a0 as sa,AO as ta,DG as ua,CO as va};
22
+
23
+ //# debugId=B6D18CD7F13586D264756E2164756E21