@sylphx/flow 0.2.3 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-057m762a.js +4 -0
- package/dist/{chunk-7nht27vs.js.map → chunk-057m762a.js.map} +1 -1
- package/dist/chunk-2j2gmjg5.js +107 -0
- package/dist/{chunk-wnaa55wn.js.map → chunk-2j2gmjg5.js.map} +6 -5
- package/dist/{chunk-asr22mbn.js → chunk-2nfq57ym.js} +1 -1
- package/dist/{chunk-cs1s5c3g.js → chunk-372bgp30.js} +3 -3
- package/dist/{chunk-cs1s5c3g.js.map → chunk-372bgp30.js.map} +1 -1
- package/dist/{chunk-m9nt0bj3.js → chunk-51kpynby.js} +3 -3
- package/dist/{chunk-m9nt0bj3.js.map → chunk-51kpynby.js.map} +1 -1
- package/dist/{chunk-1rptg3yg.js → chunk-585jp0rg.js} +1 -1
- package/dist/{chunk-hj6r7703.js → chunk-66qzap9m.js} +2 -2
- package/dist/{chunk-hj6r7703.js.map → chunk-66qzap9m.js.map} +1 -1
- package/dist/{chunk-z2rtyk3d.js → chunk-6eb5a8kv.js} +4 -4
- package/dist/{chunk-z2rtyk3d.js.map → chunk-6eb5a8kv.js.map} +1 -1
- package/dist/chunk-7h737bp8.js +4 -0
- package/dist/{chunk-fs3f7acb.js.map → chunk-7h737bp8.js.map} +2 -2
- package/dist/chunk-8ep9gk6d.js +4 -0
- package/dist/{chunk-5szm4n3x.js.map → chunk-8ep9gk6d.js.map} +2 -2
- package/dist/{chunk-bnxtqetr.js → chunk-9qzv4trv.js} +3 -3
- package/dist/{chunk-bnxtqetr.js.map → chunk-9qzv4trv.js.map} +2 -2
- package/dist/chunk-b0047ggx.js +3 -0
- package/dist/{chunk-w2vbmr93.js.map → chunk-b0047ggx.js.map} +2 -2
- package/dist/{chunk-gyq335sw.js → chunk-ceyg2zjg.js} +3 -3
- package/dist/{chunk-gyq335sw.js.map → chunk-ceyg2zjg.js.map} +1 -1
- package/dist/chunk-cjy100rr.js +6 -0
- package/dist/{chunk-d4hj6d4t.js.map → chunk-cjy100rr.js.map} +2 -2
- package/dist/{chunk-gh83x9ya.js → chunk-d6k94684.js} +1 -1
- package/dist/chunk-e74zv5ct.js +19 -0
- package/dist/chunk-e74zv5ct.js.map +10 -0
- package/dist/{chunk-hxj4eapp.js → chunk-etqfkn4f.js} +3 -3
- package/dist/{chunk-hxj4eapp.js.map → chunk-etqfkn4f.js.map} +1 -1
- package/dist/{chunk-8z1sf25t.js → chunk-f676awyz.js} +3 -3
- package/dist/{chunk-8z1sf25t.js.map → chunk-f676awyz.js.map} +1 -1
- package/dist/{chunk-sxy6vp20.js → chunk-f9yb2zk3.js} +2 -2
- package/dist/{chunk-sxy6vp20.js.map → chunk-f9yb2zk3.js.map} +1 -1
- package/dist/{chunk-hft1735c.js → chunk-fyvtp08n.js} +2 -2
- package/dist/{chunk-hft1735c.js.map → chunk-fyvtp08n.js.map} +1 -1
- package/dist/chunk-gmmm7xpw.js +23 -0
- package/dist/{chunk-jgsq3xax.js.map → chunk-gmmm7xpw.js.map} +4 -4
- package/dist/{chunk-xata5rw6.js → chunk-mtrcdhzn.js} +3 -3
- package/dist/{chunk-xata5rw6.js.map → chunk-mtrcdhzn.js.map} +1 -1
- package/dist/{chunk-8krxe10w.js → chunk-ny1s8fnh.js} +2 -2
- package/dist/{chunk-8krxe10w.js.map → chunk-ny1s8fnh.js.map} +1 -1
- package/dist/{chunk-4fr8q0jy.js → chunk-rsagxdqj.js} +71 -71
- package/dist/{chunk-4fr8q0jy.js.map → chunk-rsagxdqj.js.map} +3 -3
- package/dist/{chunk-vjf57v4h.js → chunk-rvx8bgqk.js} +3 -3
- package/dist/{chunk-vjf57v4h.js.map → chunk-rvx8bgqk.js.map} +1 -1
- package/dist/{chunk-9c2nr2fz.js → chunk-sgafqzer.js} +3 -3
- package/dist/{chunk-9c2nr2fz.js.map → chunk-sgafqzer.js.map} +2 -2
- package/dist/{chunk-s6g21d1g.js → chunk-vc4xy6dm.js} +3 -3
- package/dist/{chunk-s6g21d1g.js.map → chunk-vc4xy6dm.js.map} +1 -1
- package/dist/chunk-weshapwk.js +27 -0
- package/dist/{chunk-wrx1n6q6.js.map → chunk-weshapwk.js.map} +11 -4
- package/dist/{chunk-ndah8mn9.js → chunk-z61qdct1.js} +2 -2
- package/dist/{chunk-ndah8mn9.js.map → chunk-z61qdct1.js.map} +1 -1
- package/dist/index.js +332 -331
- package/dist/index.js.map +14 -11
- package/package.json +1 -1
- package/dist/chunk-5szm4n3x.js +0 -4
- package/dist/chunk-7nht27vs.js +0 -4
- package/dist/chunk-d4hj6d4t.js +0 -6
- package/dist/chunk-f06ma45b.js +0 -15
- package/dist/chunk-f06ma45b.js.map +0 -16
- package/dist/chunk-fs3f7acb.js +0 -4
- package/dist/chunk-jgsq3xax.js +0 -23
- package/dist/chunk-w2vbmr93.js +0 -3
- package/dist/chunk-wd9qbbe5.js +0 -5
- package/dist/chunk-wd9qbbe5.js.map +0 -10
- package/dist/chunk-wnaa55wn.js +0 -108
- package/dist/chunk-wrx1n6q6.js +0 -16
- /package/dist/{chunk-asr22mbn.js.map → chunk-2nfq57ym.js.map} +0 -0
- /package/dist/{chunk-1rptg3yg.js.map → chunk-585jp0rg.js.map} +0 -0
- /package/dist/{chunk-gh83x9ya.js.map → chunk-d6k94684.js.map} +0 -0
package/dist/chunk-jgsq3xax.js
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import{qa as t1}from"./chunk-m9nt0bj3.js";import{Lb as b6,Mb as f2,Ob as k2}from"./chunk-sxy6vp20.js";var JX=f2((z2)=>{var QZ=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]}),LZ=z2&&z2.__setModuleDefault||(Object.create?function(X,$){Object.defineProperty(X,"default",{enumerable:!0,value:$})}:function(X,$){X.default=$}),GX=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))QZ($,X,Z)}return LZ($,X),$};Object.defineProperty(z2,"__esModule",{value:!0});z2.load=z2.currentTarget=void 0;var vZ=GX(k2("path")),CZ=GX(k2("fs"));function hZ(){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 fZ()?`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=hZ;function fZ(){let X=process.report?.getReport();if(typeof X!=="object"||!X||!("header"in X))return!1;let $=X.header;return typeof $==="object"&&!!$&&"glibcVersionRuntime"in $}function qZ(X){let $=vZ.join(X,"index.node");return CZ.existsSync($)?k2($):null}z2.load=qZ});var zX=f2((a_,WX)=>{var _X=()=>process.platform==="linux",S6=null,yZ=()=>{if(!S6)S6=_X()&&process.report?process.report.getReport():{};return S6};WX.exports={isLinux:_X,getReport:yZ}});var DX=f2((e_,OX)=>{var HX=k2("fs"),SZ=(X)=>HX.readFileSync(X,"utf-8"),pZ=(X)=>new Promise(($,Z)=>{HX.readFile(X,"utf-8",(Y,G)=>{if(Y)Z(Y);else $(G)})});OX.exports={LDD_PATH:"/usr/bin/ldd",readFileSync:SZ,readFile:pZ}});var BX=f2((XW,TX)=>{var UX=k2("child_process"),{isLinux:U1,getReport:VX}=zX(),{LDD_PATH:f0,readFile:FX,readFileSync:KX}=DX(),M2,N2,q2="",RX=()=>{if(!q2)return new Promise((X)=>{UX.exec("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",($,Z)=>{q2=$?" ":Z,X(q2)})});return q2},EX=()=>{if(!q2)try{q2=UX.execSync("getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true",{encoding:"utf8"})}catch(X){q2=" "}return q2},j2="glibc",MX=/GLIBC\s(\d+\.\d+)/,o2="musl",bZ=j2.toUpperCase(),gZ=o2.toLowerCase(),dZ=(X)=>X.includes("libc.musl-")||X.includes("ld-musl-"),NX=()=>{let X=VX();if(X.header&&X.header.glibcVersionRuntime)return j2;if(Array.isArray(X.sharedObjects)){if(X.sharedObjects.some(dZ))return o2}return null},IX=(X)=>{let[$,Z]=X.split(/[\r\n]+/);if($&&$.includes(j2))return j2;if(Z&&Z.includes(o2))return o2;return null},xX=(X)=>{if(X.includes(gZ))return o2;if(X.includes(bZ))return j2;return null},mZ=async()=>{if(M2!==void 0)return M2;M2=null;try{let X=await FX(f0);M2=xX(X)}catch(X){}return M2},uZ=()=>{if(M2!==void 0)return M2;M2=null;try{let X=KX(f0);M2=xX(X)}catch(X){}return M2},wX=async()=>{let X=null;if(U1()){if(X=await mZ(),!X)X=NX();if(!X){let $=await RX();X=IX($)}}return X},PX=()=>{let X=null;if(U1()){if(X=uZ(),!X)X=NX();if(!X){let $=EX();X=IX($)}}return X},cZ=async()=>U1()&&await wX()!==j2,nZ=()=>U1()&&PX()!==j2,iZ=async()=>{if(N2!==void 0)return N2;N2=null;try{let $=(await FX(f0)).match(MX);if($)N2=$[1]}catch(X){}return N2},oZ=()=>{if(N2!==void 0)return N2;N2=null;try{let $=KX(f0).match(MX);if($)N2=$[1]}catch(X){}return N2},kX=()=>{let X=VX();if(X.header&&X.header.glibcVersionRuntime)return X.header.glibcVersionRuntime;return null},AX=(X)=>X.trim().split(/\s+/)[1],jX=(X)=>{let[$,Z,Y]=X.split(/[\r\n]+/);if($&&$.includes(j2))return AX($);if(Z&&Y&&Z.includes(o2))return AX(Y);return null},rZ=async()=>{let X=null;if(U1()){if(X=await iZ(),!X)X=kX();if(!X){let $=await RX();X=jX($)}}return X},tZ=()=>{let X=null;if(U1()){if(X=oZ(),!X)X=kX();if(!X){let $=EX();X=jX($)}}return X};TX.exports={GLIBC:j2,MUSL:o2,family:wX,familySync:PX,isNonGlibcLinux:cZ,isNonGlibcLinuxSync:nZ,version:rZ,versionSync:tZ}});var LX=f2(($W,QX)=>{var lZ={ALLOW:0,DENY:1};QX.exports=lZ});var CX=f2((ZW,vX)=>{var p6={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),p6.value=""+X,Object.defineProperty(this,"message",p6),Error.captureStackTrace(this,r2),this.code=$,this.rawCode=Z}Object.setPrototypeOf(r2,Error);Object.setPrototypeOf(r2.prototype,Error.prototype);Object.defineProperty(r2.prototype,"name",p6);vX.exports=r2});var gX=f2((YW,q0)=>{var __dirname="/Users/kyle/rules/node_modules/libsql",{load:sZ,currentTarget:aZ}=JX(),{familySync:hX,GLIBC:eZ,MUSL:XY}=BX();function $Y(){if(process.env.LIBSQL_JS_DEV)return sZ(__dirname);let X=aZ();if(hX()==eZ)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"&&hX()==XY)X="linux-arm-musleabihf";return k2(`@libsql/${X}`)}var{databaseOpen:ZY,databaseOpenWithSync:YY,databaseInTransaction:GY,databaseInterrupt:JY,databaseClose:_Y,databaseSyncSync:WY,databaseSyncUntilSync:zY,databaseExecSync:HY,databasePrepareSync:OY,databaseDefaultSafeIntegers:DY,databaseAuthorizer:AY,databaseLoadExtension:UY,databaseMaxWriteReplicationIndex:VY,statementRaw:FY,statementIsReader:KY,statementGet:fX,statementRun:qX,statementInterrupt:RY,statementRowsSync:yX,statementColumns:EY,statementSafeIntegers:MY,rowsNext:NY}=$Y(),IY=LX(),SX=CX();function V1(X){if(X.libsqlError)return new SX(X.message,X.code,X.rawCode);return X}class pX{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=YY(X,$.syncUrl,Y,Z,J,_,W,H,O)}else{let J=$?.authToken??"",_=$?.encryptionKey??"",W=$?.timeout??0,H=$?.remoteEncryptionKey??"";this.db=ZY(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 GY(G)}}})}sync(){return WY.call(this.db)}syncUntil(X){return zY.call(this.db,X)}prepare(X){try{let $=OY.call(this.db,X);return new bX($)}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){AY.call(this.db,X)}loadExtension(...X){UY.call(this.db,...X)}maxWriteReplicationIndex(){return VY.call(this.db)}exec(X){try{HY.call(this.db,X)}catch($){throw V1($)}}interrupt(){JY.call(this.db)}close(){_Y.call(this.db),this.open=!1}defaultSafeIntegers(X){return DY.call(this.db,X??!0),this}unsafeMode(...X){throw Error("not implemented")}}class bX{constructor(X){this.stmt=X,this.pluckMode=!1}raw(X){return FY.call(this.stmt,X??!0),this}pluck(X){return this.pluckMode=X??!0,this}get reader(){return KY.call(this.stmt)}run(...X){try{if(X.length==1&&typeof X[0]==="object")return qX.call(this.stmt,X[0]);else return qX.call(this.stmt,X.flat())}catch($){throw V1($)}}get(...X){try{if(X.length==1&&typeof X[0]==="object")return fX.call(this.stmt,X[0]);else return fX.call(this.stmt,X.flat())}catch($){throw V1($)}}iterate(...X){var $=void 0;if(X.length==1&&typeof X[0]==="object")$=yX.call(this.stmt,X[0]);else $=yX.call(this.stmt,X.flat());return{nextRows:Array(100),nextRowIndex:100,next(){try{if(this.nextRowIndex===100)NY.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(){RY.call(this.stmt)}columns(){return EY.call(this.stmt)}safeIntegers(X){return MY.call(this.stmt,X??!0),this}}q0.exports=pX;q0.exports.Authorization=IY;q0.exports.SqliteError=SX});var $4=f2((zH,j$)=>{function m7(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 u7(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 k$(X){return X.queue=0,X.map=u7,X}j$.exports=function(X){if(X)return k$(m7(X));else return k$(function($){return $()})}});import{join as GG}from"node:path";import{homedir as JG}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 H4(X,...$){return X(...$)}function O4(X,$){return`${X[$2]}_${$.join("_")}_unique`}class Q1 extends T{constructor(X,$){if(!$.uniqueName)$.uniqueName=O4(X,[$.name]);super(X,$);this.table=X}static[D]="PgColumn"}class t$ extends Q1{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 l$ extends Q1{static[D]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(X,$){super(X,$);this.enum=$.enum}getSQLType(){return this.enum.enumName}}var D4=Symbol.for("drizzle:isPgEnum");function A4(X){return!!X&&typeof X==="function"&&D4 in X&&X[D4]===!0}class s$ extends Q1{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 L1 extends d{static[D]="WithSubquery"}var U4="0.44.7";var Y6,G6,V4={startActiveSpan(X,$){if(!Y6)return $();if(!G6)G6=Y6.trace.getTracer("drizzle-orm",U4);return H4((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 F0=Symbol.for("drizzle:Schema"),K0=Symbol.for("drizzle:Columns"),F4=Symbol.for("drizzle:ExtraConfigColumns"),J6=Symbol.for("drizzle:OriginalName"),_6=Symbol.for("drizzle:BaseName"),v1=Symbol.for("drizzle:IsAlias"),K4=Symbol.for("drizzle:ExtraConfigBuilder"),a$=Symbol.for("drizzle:IsDrizzleTable");class F{static[D]="Table";static Symbol={Name:$2,Schema:F0,OriginalName:J6,Columns:K0,ExtraConfigColumns:F4,BaseName:_6,IsAlias:v1,ExtraConfigBuilder:K4};[$2];[J6];[F0];[K0];[F4];[_6];[v1]=!1;[a$]=!0;[K4]=void 0;constructor(X,$,Z){this[$2]=this[J6]=X,this[F0]=$,this[_6]=Z}}function L2(X){return X[$2]}function m2(X){return`${X[F0]??"public"}.${X[$2]}`}function W6(X){return X!==null&&X!==void 0&&typeof X.getSQL==="function"}function e$(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=E4;shouldInlineParams=!1;usedTables=[];append(X){return this.queryChunks.push(...X.queryChunks),this}toQuery(X){return V4.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 e$(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[R,V]of O.entries())if(A.push(V),R<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],R=O[F.Symbol.Name];return{sql:A===void 0||O[v1]?G(R):G(A)+"."+G(R),params:[]}}if(U(O,T)){let A=Y.getColumnCasing(O);if($.invokeSource==="indexes")return{sql:G(A),params:[]};let R=O.table[F.Symbol.Schema];return{sql:O.table[v1]||R===void 0?G(O.table[F.Symbol.Name])+"."+G(A):G(R)+"."+G(O.table[F.Symbol.Name])+"."+G(A),params:[]}}if(U(O,_2)){let A=O[q].schema,R=O[q].name;return{sql:A===void 0||O[q].isAlias?G(R):G(A)+"."+G(R),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 R=["none"];if(_)R=[_(O.encoder)];return{sql:J(H.value++,A),params:[A],typings:R}}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(A4(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 R4(X){return typeof X==="object"&&X!==null&&"mapToDriverValue"in X&&typeof X.mapToDriverValue==="function"}var E4={mapFromDriverValue:(X)=>X},M4={mapToDriverValue:(X)=>X},mG={...E4,...M4};class Z2{constructor(X,$=M4){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[R,V]of H.entries()){if(R>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 C1(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 XZ=Symbol.for("drizzle:IsDrizzleView");class _2{static[D]="View";[q];[XZ]=!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 h1{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 E0(X,$){return new Proxy(X,new h1($,!1))}function K2(X,$){return new Proxy(X,new Z1(new Proxy(X.table,new h1($,!1))))}function z6(X,$){return new K.Aliased(f1(X.sql,$),X.fieldAlias)}function f1(X,$){return z.join(X.queryChunks.map((Z)=>{if(U(Z,T))return K2(Z,$);if(U(Z,K))return f1(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 N4{static[D]="ConsoleLogWriter";write(X){console.log(X)}}class O6{static[D]="DefaultLogger";writer;constructor(X){this.writer=X?.writer??new N4}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[R,V]of _.entries())if(R<_.length-1){if(!(V in A))A[V]={};A=A[V]}else{let E=$[H],M=A[V]=E===null?null:O.mapFromDriverValue(E);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 q1(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 M0(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 I4(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 x4(X){return X[F.Symbol.Columns]}function y1(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 R2(X,$){return{name:typeof X==="string"&&X.length>0?X:"",config:typeof X==="object"?X:$}}function w4(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 P4=Symbol.for("drizzle:PgInlineForeignKeys"),k4=Symbol.for("drizzle:EnableRLS");class V6 extends F{static[D]="PgTable";static Symbol=Object.assign({},F.Symbol,{InlineForeignKeys:P4,EnableRLS:k4});[P4]=[];[k4]=!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 j4(X,this.columns,this.name)}}class j4{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(R4($)&&!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)}`},T4=(X,$)=>{return z`${X} <> ${a($,X)}`};function S1(...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 B4(...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 Q4(X){return z`not ${X}`}var L4=(X,$)=>{return z`${X} > ${a($,X)}`},v4=(X,$)=>{return z`${X} >= ${a($,X)}`},C4=(X,$)=>{return z`${X} < ${a($,X)}`},h4=(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 f4(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 q4(X){return z`${X} is null`}function y4(X){return z`${X} is not null`}function S4(X){return z`exists ${X}`}function p4(X){return z`not exists ${X}`}function b4(X,$,Z){return z`${X} between ${a($,X)} and ${a(Z,X)}`}function g4(X,$,Z){return z`${X} not between ${a($,X)} and ${a(Z,X)}`}function N0(X,$){return z`${X} like ${$}`}function d4(X,$){return z`${X} not like ${$}`}function m4(X,$){return z`${X} ilike ${$}`}function u4(X,$){return z`${X} not ilike ${$}`}function c4(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 n4{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 p1 extends K6{constructor(X,$,Z){super(X,$,Z?.relationName);this.config=Z}static[D]="Many";withFieldName(X){let $=new p1(this.sourceTable,this.referencedTable,this.config);return $.fieldName=X,$}}function i4(){return{and:S1,between:b4,eq:r,exists:S4,gt:L4,gte:v4,ilike:m4,inArray:u2,isNull:q4,isNotNull:y4,like:N0,lt:C4,lte:h4,ne:T4,not:Q4,notBetween:g4,notExists:p4,notLike:d4,notIlike:u4,notInArray:f4,or:B4,sql:z}}function o4(){return{sql:z,asc:c4,desc:G1}}function r4(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(_,n4)){let W=m2(_.table),H=Z[W],O=_.config($(_.table)),A;for(let[R,V]of Object.entries(O))if(H){let E=G[H];if(E.relations[R]=V,A)E.primaryKey.push(...A)}else{if(!(W in Y))Y[W]={relations:{},primaryKey:A};Y[W].relations[R]=V}}return{tables:G,tableNamesMap:Z}}function $Z(X){return function(Z,Y){return new C2(X,Z,Y,Y?.fields.reduce((G,J)=>G&&J.notNull,!0)??!1)}}function ZZ(X){return function(Z,Y){return new p1(X,Z,Y)}}function t4(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 l4(X){return{one:$Z(X),many:ZZ(X)}}function I0(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&&I0(X,X[W.relationTableTsKey],A,W.selection,G):A.map((R)=>I0(X,X[W.relationTableTsKey],R,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 v0}from"node:crypto";class R6{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 s4(X,this)}}class s4{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 a4(X,$){return`${X[$2]}_${$.join("_")}_unique`}class o 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 R6(()=>{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=a4(X,[$.name]);super(X,$);this.table=X}static[D]="SQLiteColumn"}class e4 extends o{static[D]="SQLiteBigIntBuilder";constructor(X){super(X,"bigint","SQLiteBigInt")}build(X){return new X8(X,this.config)}}class X8 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 $8 extends o{static[D]="SQLiteBlobJsonBuilder";constructor(X){super(X,"json","SQLiteBlobJson")}build(X){return new Z8(X,this.config)}}class Z8 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 Y8 extends o{static[D]="SQLiteBlobBufferBuilder";constructor(X){super(X,"buffer","SQLiteBlobBuffer")}build(X){return new G8(X,this.config)}}class G8 extends S{static[D]="SQLiteBlobBuffer";mapFromDriverValue(X){if(Buffer.isBuffer(X))return X;return Buffer.from(X)}getSQLType(){return"blob"}}function J8(X,$){let{name:Z,config:Y}=R2(X,$);if(Y?.mode==="json")return new $8(Z);if(Y?.mode==="bigint")return new e4(Z);return new Y8(Z)}class _8 extends o{static[D]="SQLiteCustomColumnBuilder";constructor(X,$,Z){super(X,"custom","SQLiteCustomColumn");this.config.fieldConfig=$,this.config.customTypeParams=Z}build(X){return new W8(X,this.config)}}class W8 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 z8(X){return($,Z)=>{let{name:Y,config:G}=R2($,Z);return new _8(Y,G,X)}}class x0 extends o{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 w0 extends S{static[D]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}}class H8 extends x0{static[D]="SQLiteIntegerBuilder";constructor(X){super(X,"number","SQLiteInteger")}build(X){return new O8(X,this.config)}}class O8 extends w0{static[D]="SQLiteInteger"}class D8 extends x0{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 A8(X,this.config)}}class A8 extends w0{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 U8 extends x0{static[D]="SQLiteBooleanBuilder";constructor(X,$){super(X,"boolean","SQLiteBoolean");this.config.mode=$}build(X){return new V8(X,this.config)}}class V8 extends w0{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}=R2(X,$);if(Y?.mode==="timestamp"||Y?.mode==="timestamp_ms")return new D8(Z,Y.mode);if(Y?.mode==="boolean")return new U8(Z,Y.mode);return new H8(Z)}class F8 extends o{static[D]="SQLiteNumericBuilder";constructor(X){super(X,"string","SQLiteNumeric")}build(X){return new K8(X,this.config)}}class K8 extends S{static[D]="SQLiteNumeric";mapFromDriverValue(X){if(typeof X==="string")return X;return String(X)}getSQLType(){return"numeric"}}class R8 extends o{static[D]="SQLiteNumericNumberBuilder";constructor(X){super(X,"number","SQLiteNumericNumber")}build(X){return new E8(X,this.config)}}class E8 extends S{static[D]="SQLiteNumericNumber";mapFromDriverValue(X){if(typeof X==="number")return X;return Number(X)}mapToDriverValue=String;getSQLType(){return"numeric"}}class M8 extends o{static[D]="SQLiteNumericBigIntBuilder";constructor(X){super(X,"bigint","SQLiteNumericBigInt")}build(X){return new N8(X,this.config)}}class N8 extends S{static[D]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}function I8(X,$){let{name:Z,config:Y}=R2(X,$),G=Y?.mode;return G==="number"?new R8(Z):G==="bigint"?new M8(Z):new F8(Z)}class x8 extends o{static[D]="SQLiteRealBuilder";constructor(X){super(X,"number","SQLiteReal")}build(X){return new w8(X,this.config)}}class w8 extends S{static[D]="SQLiteReal";getSQLType(){return"real"}}function J1(X){return new x8(X??"")}class P8 extends o{static[D]="SQLiteTextBuilder";constructor(X,$){super(X,"string","SQLiteText");this.config.enumValues=$.enum,this.config.length=$.length}build(X){return new k8(X,this.config)}}class k8 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 j8 extends o{static[D]="SQLiteTextJsonBuilder";constructor(X){super(X,"json","SQLiteTextJson")}build(X){return new T8(X,this.config)}}class T8 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}=R2(X,$);if(Y.mode==="json")return new j8(Z);return new P8(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 h1(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 B8(){return{blob:J8,customType:z8,integer:b,numeric:I8,real:J1,text:I}}var E6=Symbol.for("drizzle:SQLiteInlineForeignKeys");class u extends F{static[D]="SQLiteTable";static Symbol=Object.assign({},F.Symbol,{InlineForeignKeys:E6});[F.Symbol.Columns];[E6]=[];[F.Symbol.ExtraConfigBuilder]=void 0}function YZ(X,$,Z,Y,G=X){let J=new u(X,Y,G),_=typeof $==="function"?$(B8()):$,W=Object.fromEntries(Object.entries(_).map(([O,A])=>{let R=A;R.setName(O);let V=R.build(J);return J[E6].push(...R.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 YZ(X,$,Z)};class Q8{constructor(X,$){this.name=X,this.unique=$}static[D]="SQLiteIndexBuilderOn";on(...X){return new L8(this.name,X,this.unique)}}class L8{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 v8(this.config,X)}}class v8{static[D]="SQLiteIndex";config;constructor(X,$){this.config={...X,table:$}}}function f(X){return new Q8(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 C8(X,this.columns,this.name)}}class C8{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 P0 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 GZ(X){return(X.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map((Z)=>Z.toLowerCase()).join("_")}function JZ(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 _Z(X){return X}class I6{static[D]="CasingCache";cache={};cachedTables={};convert;constructor(X){this.convert=X==="snake_case"?GZ:X==="camelCase"?JZ:_Z}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,$),R=_&&z.join([z.raw(" from "),this.buildFromTable(_)]),V=this.buildJoins(J),E=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}${R}${V}${M}${E}${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:R,setOperators:V}){let E=Z??W2($);for(let O2 of E)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:V0})=>V0===(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=R?z` distinct`:void 0,C=this.buildSelection(E,{isSingleTable:M}),Q=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),U0=this.buildLimit(O),$6=A?z` offset ${A}`:void 0,$1=z`${x}select${k} ${C} from ${Q}${L}${x2}${h}${J2}${w2}${U0}${$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 E=[];for(let M of J)if(U(M,S))E.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))}E.push(z`${M}`)}else E.push(z`${M}`);O=z` order by ${z.join(E,z`, `)}`}let A=typeof G==="object"||typeof G==="number"&&G>=0?z` limit ${G}`:void 0,R=z.raw(`${$} ${Z?"all ":""}`),V=_?z` offset ${_}`:void 0;return z`${W}${R}${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[Q,L]of H){let x2=k[Q];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),R=z.join(_),V=Y?z` returning ${this.buildSelection(Y,{isSingleTable:!0})}`:void 0,E=Z?.length?z.join(Z):void 0;return z`${A}insert into ${X} ${O} ${R}${E}${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,R,V=[],E,M=[];if(J===!0)O=Object.entries(G.columns).map(([C,Q])=>({dbKey:Q.name,tsKey:C,field:K2(Q,_),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,i4()):J.where;E=P&&f1(P,_)}let C=[],Q=[];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;Q.push(h)}}if(Q.length>0)Q=P?Q.filter((h)=>J.columns?.[h]===!0):Object.keys(G.columns).filter((h)=>!Q.includes(h))}else Q=Object.keys(G.columns);for(let P of Q){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,o4()):J.orderBy??[];if(!Array.isArray(J2))J2=[J2];V=J2.map((P)=>{if(U(P,T))return K2(P,_);return f1(P,_)}),A=J.limit,R=J.offset;for(let{tsKey:P,queryConfig:h,relation:w2}of L){let U0=t4($,Z,w2),$6=m2(w2.referencedTable),$1=Z[$6],O2=`${_}_${P}`,F2=S1(...U0.fields.map((o$,r$)=>r(K2(U0.references[r$],O2),K2(o$,_)))),V0=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}),i$=z`(${V0.sql})`.as(P);O.push({dbKey:P,tsKey:P,field:i$,relationTableTsKey:$1,isJson:!0,selection:V0.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(E=S1(H,E),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,p1))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||R!==void 0||V.length>0)x=this.buildSelectQuery({table:E0(Y,_),fields:{},fieldsFlat:[{path:[],field:z.raw("*")}],where:E,limit:A,offset:R,orderBy:V,setOperators:[]}),E=void 0,A=void 0,R=void 0,V=void 0;else x=E0(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:E,limit:A,offset:R,orderBy:V,setOperators:[]})}else x=this.buildSelectQuery({table:E0(Y,_),fields:{},fieldsFlat:O.map(({field:k})=>({path:[],field:U(k,T)?K2(k,_):k})),joins:M,where:E,limit:A,offset:R,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=x4(X);return new k6({table:X,fields:Z,isPartialSelect:$,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}}class h8 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=y1(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=y1($);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(WZ()):Z;if(!q1(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 h8{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()}}I4(k6,[s]);function k0(X,$){return(Z,Y,...G)=>{let J=[Y,...G].map((_)=>({type:X,isAll:$,rightSelect:_}));for(let _ of J)if(!q1(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 WZ=()=>({union:zZ,unionAll:HZ,intersect:OZ,except:DZ}),zZ=k0("union",!1),HZ=k0("union",!0),OZ=k0("intersect",!1),DZ=k0("except",!1);class b1{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 L1(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 j0{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 b1):X;if(!U($,K)&&!q1(this.table[K0],$._.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,M0(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 T0{constructor(X,$,Z,Y){this.table=X,this.session=$,this.dialect=Z,this.withList=Y}static[D]="SQLiteUpdateBuilder";set(X){return new f8(this.table,M0(this.table,X),this.session,this.dialect,this.withList)}}class f8 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=y1($);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 g1 extends K{constructor(X){super(g1.buildEmbeddedCount(X.source,X.filters).queryChunks);this.params=X,this.session=X.session,this.sql=g1.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 B6{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((_)=>I0(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 d1{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 B6(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 b1(Z.dialect));return new Proxy(new L1(G.getSQL(),$??("getSelectedFields"in G?G.getSelectedFields()??{}:{}),X,!0),new m({alias:X,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}}};$count(X,$){return new g1({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 T0(W,$.session,$.dialect,X)}function J(W){return new j0(W,$.session,$.dialect,X)}function _(W){return new P0(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 T0(X,this.session,this.dialect)}$cache;insert(X){return new j0(X,this.session,this.dialect)}delete(X){return new P0(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 q8{static[D]="Cache"}class m1 extends q8{strategy(){return"all"}static[D]="NoopCache";async get(X){return}async put(X,$,Z,Y){}async onMutate(X){}}async function Q6(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 y8 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,m1)||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 Q6(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 Q6(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 y8(()=>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 d1{constructor(X,$,Z,Y,G=0){super(X,$,Z,Y);this.schema=Y,this.nestedIndex=G}static[D]="SQLiteTransaction";rollback(){throw new H6}}var Q_=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)})),S8=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)})),L_=e("tfidf_terms",{filePath:I("file_path").notNull().references(()=>S8.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)})),v_=e("tfidf_documents",{filePath:I("file_path").primaryKey().references(()=>S8.path,{onDelete:"cascade"}),magnitude:J1("magnitude").notNull(),termCount:b("term_count").notNull(),rawTerms:I("raw_terms").notNull()}),C_=e("tfidf_idf",{term:I("term").primaryKey(),idfValue:J1("idf_value").notNull()}),h_=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)})),u1=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)})),Q0=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)})),L0=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)})),c1=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)}));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){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(u1).where(u2(u1.messageId,Z)).orderBy(u1.ordering),this.db.select().from(Q0).where(u2(Q0.messageId,Z)),this.db.select().from(L0).where(u2(L0.messageId,Z)),this.db.select().from(c1).where(u2(c1.messageId,Z)).orderBy(c1.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 E=W.get(V.id)||[],M=H.get(V.id)||[],x=O.get(V.id),k=A.get(V.id)||[],C={role:V.role,content:E.map((Q)=>JSON.parse(Q.content)),timestamp:V.timestamp};if(V.metadata)C.metadata=JSON.parse(V.metadata);if(M.length>0)C.attachments=M.map((Q)=>({path:Q.path,relativePath:Q.relativePath,size:Q.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((Q)=>({id:Q.todoId,content:Q.content,activeForm:Q.activeForm,status:Q.status,ordering:Q.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){let H=v0(),O=Date.now(),[{count:A}]=await this.db.select({count:z`count(*)`}).from(Y2).where(r(Y2.sessionId,X)),R=A;await this.db.transaction(async(V)=>{await V.insert(Y2).values({id:H,sessionId:X,role:$,timestamp:O,ordering:R,finishReason:J||null,metadata:_?JSON.stringify(_):null});for(let E=0;E<Z.length;E++)await V.insert(u1).values({id:v0(),messageId:H,ordering:E,type:Z[E].type,content:JSON.stringify(Z[E])});if(Y&&Y.length>0)for(let E of Y)await V.insert(Q0).values({id:v0(),messageId:H,path:E.path,relativePath:E.relativePath,size:E.size||null});if(G)await V.insert(L0).values({messageId:H,promptTokens:G.promptTokens,completionTokens:G.completionTokens,totalTokens:G.totalTokens});if(W&&W.length>0)for(let E of W)await V.insert(c1).values({id:v0(),messageId:H,todoId:E.id,content:E.content,activeForm:E.activeForm,status:E.status,ordering:E.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(N0(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 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 a0}from"node:path";import{homedir as c$}from"node:os";import{readdir as _4,mkdir as l7,readFile as s7}from"node:fs/promises";import{existsSync as a7}from"node:fs";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 p8(X){let $=AZ.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?UZ(Z.authority):void 0,J=i2(Z.path),_=Z.query!==void 0?FZ(Z.query):void 0,W=Z.fragment!==void 0?i2(Z.fragment):void 0;return{scheme:Y,authority:G,path:J,query:_,fragment:W}}var AZ=(()=>{return new RegExp("^(?<scheme>[A-Za-z][A-Za-z.+-]*):(//(?<authority>[^/?#]*))?(?<path>[^?#]*)(\\?(?<query>[^#]*))?(#(?<fragment>.*))?$","su")})();function UZ(X){let $=VZ.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=i2(Z.host_br??Z.host),G=Z.port?parseInt(Z.port,10):void 0,J=Z.username!==void 0?{username:i2(Z.username),password:Z.password!==void 0?i2(Z.password):void 0}:void 0;return{host:Y,port:G,userinfo:J}}var VZ=(()=>{return new RegExp("^((?<username>[^:]*)(:(?<password>.*))?@)?((?<host>[^:\\[\\]]*)|(\\[(?<host_br>[^\\[\\]]*)\\]))(:(?<port>[0-9]*))?$","su")})();function FZ(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:i2(G.replaceAll("+"," ")),value:i2(J.replaceAll("+"," "))})}return{pairs:Z}}function i2(X){try{return decodeURIComponent(X)}catch($){if($ instanceof URIError)throw new w(`URL component has invalid percent encoding: ${$}`,"URL_INVALID",void 0,$);throw $}}function n1(X,$,Z){if($===void 0)throw new w(`URL with scheme ${JSON.stringify(X+":")} requires authority (the "//" part)`,"URL_INVALID");let Y=`${X}:`,G=KZ($.host),J=RZ($.port),W=`//${EZ($.userinfo)}${G}${J}`,H=Z.split("/").map(encodeURIComponent).join("/");if(H!==""&&!H.startsWith("/"))H="/"+H;return new URL(`${Y}${W}${H}`)}function KZ(X){return X.includes(":")?`[${encodeURI(X)}]`:encodeURI(X)}function RZ(X){return X!==void 0?`:${X}`:""}function EZ(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",b8=typeof TextDecoder==="function"?new TextDecoder:void 0,g8=typeof TextEncoder==="function"?new TextEncoder:void 0;var i1=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),C0=((X)=>{let $={};return X.forEach((Z,Y)=>$[Z]=Y),$})(i1),MZ=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,t=String.fromCharCode.bind(String),d8=typeof Uint8Array.from==="function"?Uint8Array.from.bind(Uint8Array):(X)=>new Uint8Array(Array.prototype.slice.call(X,0)),c8=(X)=>X.replace(/=/g,"").replace(/[+\/]/g,($)=>$=="+"?"-":"_"),n8=(X)=>X.replace(/[^A-Za-z0-9\+\/]/g,""),i8=(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},q6=typeof btoa==="function"?(X)=>btoa(X):O1?(X)=>Buffer.from(X,"binary").toString("base64"):i8,h6=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 q6(Z.join(""))},h0=(X,$=!1)=>$?c8(h6(X)):h6(X),NZ=(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)}},IZ=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,o8=(X)=>X.replace(IZ,NZ),m8=O1?(X)=>Buffer.from(X,"utf8").toString("base64"):g8?(X)=>h6(g8.encode(X)):(X)=>q6(o8(X)),H1=(X,$=!1)=>$?c8(m8(X)):m8(X),u8=(X)=>H1(X,!0),xZ=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,wZ=(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))}},r8=(X)=>X.replace(xZ,wZ),t8=(X)=>{if(X=X.replace(/\s+/g,""),!MZ.test(X))throw TypeError("malformed base64.");X+="==".slice(2-(X.length&3));let $,Z,Y,G=[];for(let J=0;J<X.length;)if($=C0[X.charAt(J++)]<<18|C0[X.charAt(J++)]<<12|(Z=C0[X.charAt(J++)])<<6|(Y=C0[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("")},y6=typeof atob==="function"?(X)=>atob(n8(X)):O1?(X)=>Buffer.from(X,"base64").toString("binary"):t8,l8=O1?(X)=>d8(Buffer.from(X,"base64")):(X)=>d8(y6(X).split("").map(($)=>$.charCodeAt(0))),s8=(X)=>l8(a8(X)),PZ=O1?(X)=>Buffer.from(X,"base64").toString("utf8"):b8?(X)=>b8.decode(l8(X)):(X)=>r8(y6(X)),a8=(X)=>n8(X.replace(/[-_]/g,($)=>$=="-"?"+":"/")),f6=(X)=>PZ(a8(X)),kZ=(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($)},e8=(X)=>{return{value:X,enumerable:!1,writable:!0,configurable:!0}},XX=function(){let X=($,Z)=>Object.defineProperty(String.prototype,$,e8(Z));X("fromBase64",function(){return f6(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 s8(this)})},$X=function(){let X=($,Z)=>Object.defineProperty(Uint8Array.prototype,$,e8(Z));X("toBase64",function($){return h0(this,$)}),X("toBase64URI",function(){return h0(this,!0)}),X("toBase64URL",function(){return h0(this,!0)})},jZ=()=>{XX(),$X()},D1={version:"3.7.8",VERSION:"3.7.8",atob:y6,atobPolyfill:t8,btoa:q6,btoaPolyfill:i8,fromBase64:f6,toBase64:H1,encode:H1,encodeURI:u8,encodeURL:u8,utob:o8,btou:r8,decode:f6,isValid:kZ,fromUint8Array:h0,toUint8Array:s8,extendString:XX,extendUint8Array:$X,extendBuiltins:jZ};var E2="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(TZ),rowsAffected:this.rowsAffected,lastInsertRowid:this.lastInsertRowid!==void 0?""+this.lastInsertRowid:null}}}function TZ(X){return Array.prototype.map.call(X,BZ)}function BZ(X){if(typeof X==="bigint")return""+X;else if(X instanceof ArrayBuffer)return D1.fromUint8Array(new Uint8Array(X));else return X}var ZX=":memory:";function YX(X){return X.scheme==="file"&&(X.path===":memory:"||X.path.startsWith(":memory:?"))}function o1(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===ZX)Z="file::memory:";let H=p8(Z),O=H.scheme.toLowerCase(),A=O==="file"&&H.path===ZX&&H.authority===void 0,R;if(A)R={cache:{values:["shared","private"],update:(x,k)=>W.push(`${x}=${k}`)}};else R={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(R,x))throw new w(`Unsupported URL query parameter ${JSON.stringify(x)}`,"URL_PARAM_NOT_SUPPORTED");let C=R[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((Q)=>'"'+Q+'"').join(", ")}]`,"URL_INVALID");if(C.update!==void 0)C?.update(x,k)}let V=W.length===0?"":`?${W.join("&")}`,E=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 ${E2}`,"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:E,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:E,authToken:Y,intMode:J,concurrency:_,encryptionKey:X.encryptionKey,syncUrl:X.syncUrl,syncInterval:X.syncInterval,readYourWrites:X.readYourWrites,offline:X.offline,fetch:X.fetch}}var r1=b6(gX(),1);import{Buffer as mX}from"node:buffer";function uX(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 ${E2}`,"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 ${E2}`,"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=YX(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 r1.default(Y,G);return i(J,"SELECT 1 AS checkThatTheDatabaseCanBeOpened",X.intMode),new cX(Y,G,J,X.intMode)}class cX{#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(),i(this.#J(),Z,this.#Y)}async batch(X,$="deferred"){this.#G();let Z=this.#J();try{i(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 i(Z,J,this.#Y)});return i(Z,"COMMIT",this.#Y),Y}finally{if(Z.inTransaction)i(Z,"ROLLBACK",this.#Y)}}async migrate(X){this.#G();let $=this.#J();try{i($,"PRAGMA foreign_keys=off",this.#Y),i($,h2("deferred"),this.#Y);let Z=X.map((Y)=>{if(!$.inTransaction)throw new w("The transaction has been rolled back","TRANSACTION_CLOSED");return i($,Y,this.#Y)});return i($,"COMMIT",this.#Y),Z}finally{if($.inTransaction)i($,"ROLLBACK",this.#Y);i($,"PRAGMA foreign_keys=on",this.#Y)}}async transaction(X="write"){let $=this.#J();return i($,h2(X),this.#Y),this.#Z=null,new nX($,this.#Y)}async executeMultiple(X){this.#G();let $=this.#J();try{return iX($,X)}finally{if($.inTransaction)i($,"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 r1.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 r1.default(this.#X,this.#$);return this.#Z}}class nX{#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(),i(this.#X,Z,this.#$)}async batch(X){return X.map(($)=>{this.#Z();let Z=Array.isArray($)?{sql:$[0],args:$[1]||[]}:$;return i(this.#X,Z,this.#$)})}async executeMultiple(X){return this.#Z(),iX(this.#X,X)}async rollback(){if(!this.#X.open)return;this.#Z(),i(this.#X,"ROLLBACK",this.#$)}async commit(){this.#Z(),i(this.#X,"COMMIT",this.#$)}close(){if(this.#X.inTransaction)i(this.#X,"ROLLBACK",this.#$)}get closed(){return!this.#X.inTransaction}#Z(){if(this.closed)throw new w("The transaction is closed","TRANSACTION_CLOSED")}}function i(X,$,Z){let Y,G;if(typeof $==="string")Y=$,G=[];else if(Y=$.sql,Array.isArray($.args))G=$.args.map((J)=>dX(J,Z));else{G={};for(let J in $.args){let _=J[0]==="@"||J[0]==="$"||J[0]===":"?J.substring(1):J;G[_]=dX($.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 xY(V,W,Z)}),A=0,R=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 oX(J)}}function xY(X,$,Z){let Y={};Object.defineProperty(Y,"length",{value:X.length});for(let G=0;G<X.length;++G){let J=wY(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 wY(X,$){if(typeof X==="bigint")if($==="number"){if(X<PY||X>kY)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 mX)return X.buffer;return X}var PY=-9007199254740991n,kY=9007199254740991n;function dX(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<jY||X>TY)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 mX.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 jY=-9223372036854775808n,TY=9223372036854775807n;function iX(X,$){try{X.exec($)}catch(Z){throw oX(Z)}}function oX(X){if(X instanceof r1.default.SqliteError)return new w(X.message,X.code,X.rawCode,X);return X}class F1{constructor(){this.intMode="number"}intMode}class B extends Error{constructor(X){super(X);this.name="ClientError"}}class N extends B{constructor(X){super(X);this.name="ProtoError"}}class l1 extends B{code;proto;constructor(X,$){super(X);this.name="ResponseError",this.code=$.code,this.proto=$,this.stack=void 0}}class g extends B{constructor(X,$){if($!==void 0){super(`${X}: ${$}`);this.cause=$}else super(X);this.name="ClosedError"}}class s1 extends B{constructor(X){super(X);this.name="WebSocketUnsupportedError"}}class K1 extends B{constructor(X){super(X);this.name="WebSocketError"}}class t2 extends B{status;constructor(X,$){super(X);this.status=$,this.name="HttpServerError"}}class U2 extends B{constructor(X){super(X);this.name="ProtocolVersionError"}}class l extends B{constructor(X){super(X);this.name="InternalError"}}class I2 extends B{constructor(X){super(X);this.name="MisuseError"}}function X2(X){if(typeof X==="string")return X;throw R1(X,"string")}function G2(X){if(X===null||X===void 0)return;else if(typeof X==="string")return X;throw R1(X,"string or null")}function T2(X){if(typeof X==="number")return X;throw R1(X,"number")}function y2(X){if(typeof X==="boolean")return X;throw R1(X,"boolean")}function a1(X){if(Array.isArray(X))return X;throw R1(X,"array")}function c(X){if(X!==null&&typeof X==="object"&&!Array.isArray(X))return X;throw R1(X,"object")}function V2(X,$){return a1(X).map((Z)=>$(c(Z)))}function R1(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 rX{#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 e1(X,$){let Z=[],Y=new rX(Z);return Y.begin(),$(Y,X),Y.end(),Z.join("")}var s2=0,X0=1,$0=2;var tX=5;class lX{#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 sX{#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($0);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(X0),this.#X.double()}maybeSkip(){if(this.#$<0)return;else if(this.#$===s2)this.#X.skipVarint();else if(this.#$===X0)this.#X.skip(8);else if(this.#$===$0){let X=this.#X.varint();this.#X.skip(X)}else if(this.#$===tX)this.#X.skip(4);else throw new N(`Unexpected wire type ${this.#$}`);this.#$=-1}}function S2(X,$){let Z=new lX(X),Y=new sX(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 g6{#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,$0),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 g6;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,X0),this.#G(8),this.#Z.setFloat64(this.#Y,$,!0),this.#Y+=8}data(){return new Uint8Array(this.#X,0,this.#Y)}}function Z0(X,$){let Z=new g6;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 E1(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<QY||X>LY)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 QY=-9223372036854775808n,LY=9223372036854775807n;function d6(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 S0(X,$){let Z=a2(X),Y=X.rows.map((G)=>aX(Z.columnNames,G,$));return{...Z,rows:Y}}function p0(X,$){let Z=a2(X),Y;if(X.rows.length>0)Y=aX(Z.columnNames,X.rows[0],$);return{...Z,row:Y}}function b0(X,$){let Z=a2(X),Y;if(X.rows.length>0&&Z.columnNames.length>0)Y=d6(X.rows[0][0],$);return{...Z,value:Y}}function aX(X,$,Z){let Y={};Object.defineProperty(Y,"length",{value:$.length});for(let G=0;G<$.length;++G){let J=d6($[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 B2(X){return new l1(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 B("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 Y0(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 G0{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(E1($));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]=E1($),this}bindName(X,$){return this._namedArgs.set(X,E1($)),this}unbindAll(){return this._args.length=0,this._namedArgs.clear(),this}}function g0(X,$,Z){let Y,G=[],J=[];if($ instanceof G0){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)=>E1(H));else J=Object.entries($[1]).map(([H,O])=>{return{name:H,value:E1(O)}});else Y=$;let{sql:_,sqlId:W}=Y0(X,Y);return{sql:_,sqlId:W,args:G,namedArgs:J,wantRows:Z}}class d0{_stream;#X;_steps;#$;constructor(X,$){this._stream=X,this.#X=$,this._steps=[],this.#$=!1}step(){return new m6(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 CY(this._stream,this._steps,X);else return vY(this._stream,this._steps,X)}}function vY(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 CY(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 B2(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 m6{_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,S0)}queryRow(X){return this.#$(X,!0,p0)}queryValue(X){return this.#$(X,!0,b0)}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=g0(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(B2(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:eX(X)})}static error(X){return new y(X._batch,{type:"error",step:eX(X)})}static not(X){return new y(X._batch,{type:"not",cond:X._proto})}static and(X,$){for(let Z of $)X$(X,Z);return new y(X,{type:"and",conds:$.map((Z)=>Z._proto)})}static or(X,$){for(let Z of $)X$(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 eX(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 X$(X,$){if($._batch!==X)throw new I2("Cannot mix BatchCond objects for different Batch objects")}function $$(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,S0)}queryRow(X){return this.#X(X,!0,p0)}queryValue(X){return this.#X(X,!0,b0)}run(X){return this.#X(X,!1,a2)}#X(X,$,Z){let Y=g0(this._sqlOwner(),X,$);return this._execute(Y).then((G)=>Z(G,this.intMode))}batch(X=!1){return new d0(this,X)}describe(X){let $=Y0(this._sqlOwner(),X);return this._describe($).then($$)}sequence(X){let $=Y0(this._sqlOwner(),X);return this._sequence($)}intMode}class J0{}var hY=1000,fY=10;class u6 extends J0{#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<fY)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:hY}).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 B("Cursor was manually closed"))}get closed(){return this.#J!==void 0}}class _0 extends M1{#X;#$;#Z;#Y;#G;#J;static open(X){let $=X._streamIdAlloc.alloc(),Z=new _0(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 B("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 u6(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 B("Stream was manually closed"))}closeGracefully(){this.#G=!0,this.#z()}get closed(){return this.#J!==void 0||this.#G}}function W0(X,$){if($.sql!==void 0)X.string("sql",$.sql);if($.sqlId!==void 0)X.number("sql_id",$.sqlId);X.arrayObjects("args",$.args,Z$),X.arrayObjects("named_args",$.namedArgs,qY),X.boolean("want_rows",$.wantRows)}function qY(X,$){X.string("name",$.name),X.object("value",$.value,Z$)}function N1(X,$){X.arrayObjects("steps",$.steps,yY)}function yY(X,$){if($.condition!==void 0)X.object("condition",$.condition,c6);X.object("stmt",$.stmt,W0)}function c6(X,$){if(X.stringRaw("type",$.type),$.type==="ok"||$.type==="error")X.number("step",$.step);else if($.type==="not")X.object("cond",$.cond,c6);else if($.type==="and"||$.type==="or")X.arrayObjects("conds",$.conds,c6);else if($.type==="is_autocommit");else throw j($,"Impossible type of BatchCond")}function Z$(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 Y$(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,SY);else throw j($,"Impossible type of ClientMsg")}function SY(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,W0);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 z0(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,J$);for(let Z of $.namedArgs)X.message(4,Z,pY);X.bool(5,$.wantRows)}function pY(X,$){X.string(1,$.name),X.message(2,$.value,J$)}function I1(X,$){for(let Z of $.steps)X.message(1,Z,bY)}function bY(X,$){if($.condition!==void 0)X.message(1,$.condition,n6);X.message(2,$.stmt,z0)}function n6(X,$){if($.type==="ok")X.uint32(1,$.step);else if($.type==="error")X.uint32(2,$.step);else if($.type==="not")X.message(3,$.cond,n6);else if($.type==="and")X.message(4,$.conds,G$);else if($.type==="or")X.message(5,$.conds,G$);else if($.type==="is_autocommit")X.message(6,void 0,_$);else throw j($,"Impossible type of BatchCond")}function G$(X,$){for(let Z of $)X.message(1,Z,n6)}function J$(X,$){if($===null)X.message(1,void 0,_$);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 _$(X,$){}function W$(X,$){if($.type==="hello")X.message(1,$,gY);else if($.type==="request")X.message(2,$,dY);else throw j($,"Impossible type of ClientMsg")}function gY(X,$){if($.jwt!==void 0)X.string(1,$.jwt)}function dY(X,$){X.int32(1,$.requestId);let Z=$.request;if(Z.type==="open_stream")X.message(2,Z,mY);else if(Z.type==="close_stream")X.message(3,Z,uY);else if(Z.type==="execute")X.message(4,Z,cY);else if(Z.type==="batch")X.message(5,Z,nY);else if(Z.type==="open_cursor")X.message(6,Z,iY);else if(Z.type==="close_cursor")X.message(7,Z,oY);else if(Z.type==="fetch_cursor")X.message(8,Z,rY);else if(Z.type==="sequence")X.message(9,Z,tY);else if(Z.type==="describe")X.message(10,Z,lY);else if(Z.type==="store_sql")X.message(11,Z,sY);else if(Z.type==="close_sql")X.message(12,Z,aY);else if(Z.type==="get_autocommit")X.message(13,Z,eY);else throw j(Z,"Impossible type of Request")}function mY(X,$){X.int32(1,$.streamId)}function uY(X,$){X.int32(1,$.streamId)}function cY(X,$){X.int32(1,$.streamId),X.message(2,$.stmt,z0)}function nY(X,$){X.int32(1,$.streamId),X.message(2,$.batch,I1)}function iY(X,$){X.int32(1,$.streamId),X.int32(2,$.cursorId),X.message(3,$.batch,I1)}function oY(X,$){X.int32(1,$.cursorId)}function rY(X,$){X.int32(1,$.cursorId),X.uint32(2,$.maxCount)}function tY(X,$){if(X.int32(1,$.streamId),$.sql!==void 0)X.string(2,$.sql);if($.sqlId!==void 0)X.int32(3,$.sqlId)}function lY(X,$){if(X.int32(1,$.streamId),$.sql!==void 0)X.string(2,$.sql);if($.sqlId!==void 0)X.int32(3,$.sqlId)}function sY(X,$){X.int32(1,$.sqlId),X.string(2,$.sql)}function aY(X,$){X.int32(1,$.sqlId)}function eY(X,$){X.int32(1,$.streamId)}function g2(X){let $=X2(X.message),Z=G2(X.code);return{message:$,code:Z}}function H0(X){let $=V2(X.cols,z$),Z=a1(X.rows).map((_)=>V2(_,H$)),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 z$(X){let $=G2(X.name),Z=G2(X.decltype);return{name:$,decltype:Z}}function m0(X){let $=new Map;a1(X.step_results).forEach((Y,G)=>{if(Y!==null)$.set(G,H0(c(Y)))});let Z=new Map;return a1(X.step_errors).forEach((Y,G)=>{if(Y!==null)Z.set(G,g2(c(Y)))}),{stepResults:$,stepErrors:Z}}function u0(X){let $=X2(X.type);if($==="step_begin"){let Z=T2(X.step),Y=V2(X.cols,z$);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,H$)};else if($==="error")return{type:"error",error:g2(c(X.error))};else throw new N("Unexpected type of CursorEntry")}function c0(X){let $=V2(X.params,X7),Z=V2(X.cols,$7),Y=y2(X.is_explain),G=y2(X.is_readonly);return{params:$,cols:Z,isExplain:Y,isReadonly:G}}function X7(X){return{name:G2(X.name)}}function $7(X){let $=X2(X.name),Z=G2(X.decltype);return{name:$,decltype:Z}}function H$(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 O$(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=Z7(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 Z7(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:H0(c(X.result))};else if($==="batch")return{type:"batch",result:m0(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,u0),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:c0(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(D$))},2(X,$){$.rows.push(X.message(A$))},3(X,$){$.affectedRowCount=Number(X.uint64())},4(X,$){$.lastInsertRowid=X.sint64()}},D$={default(){return{name:void 0,decltype:void 0}},1(X,$){$.name=X.string()},2(X,$){$.decltype=X.string()}},A$={default(){return[]},1(X,$){$.push(X.message(O7))}},x1={default(){return{stepResults:new Map,stepErrors:new Map}},1(X,$){let[Z,Y]=X.message(Y7);$.stepResults.set(Z,Y)},2(X,$){let[Z,Y]=X.message(G7);$.stepErrors.set(Z,Y)}},Y7={default(){return[0,d2.default()]},1(X,$){$[0]=X.uint32()},2(X,$){$[1]=X.message(d2)}},G7={default(){return[0,H2.default()]},1(X,$){$[0]=X.uint32()},2(X,$){$[1]=X.message(H2)}},n0={default(){return{type:"none"}},1(X){return X.message(J7)},2(X){return X.message(_7)},3(X){return X.message(W7)},4(X){return{type:"row",row:X.message(A$)}},5(X){return{type:"error",error:X.message(H2)}}},J7={default(){return{type:"step_begin",step:0,cols:[]}},1(X,$){$.step=X.uint32()},2(X,$){$.cols.push(X.message(D$))}},_7={default(){return{type:"step_end",affectedRowCount:0,lastInsertRowid:void 0}},1(X,$){$.affectedRowCount=X.uint32()},2(X,$){$.lastInsertRowid=X.uint64()}},W7={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(z7))},2(X,$){$.cols.push(X.message(H7))},3(X,$){$.isExplain=X.bool()},4(X,$){$.isReadonly=X.bool()}},z7={default(){return{name:void 0}},1(X,$){$.name=X.string()}},H7={default(){return{name:"",decltype:void 0}},1(X,$){$.name=X.string()},2(X,$){$.decltype=X.string()}},O7={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 U$={default(){return{type:"none"}},1(X){return{type:"hello_ok"}},2(X){return X.message(D7)},3(X){return X.message(U7)},4(X){return X.message(A7)}},D7={default(){return{type:"hello_error",error:H2.default()}},1(X,$){$.error=X.message(H2)}},A7={default(){return{type:"response_error",requestId:0,error:H2.default()}},1(X,$){$.requestId=X.int32()},2(X,$){$.error=X.message(H2)}},U7={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(V7)},5(X,$){$.response=X.message(F7)},6(X,$){$.response={type:"open_cursor"}},7(X,$){$.response={type:"close_cursor"}},8(X,$){$.response=X.message(K7)},9(X,$){$.response={type:"sequence"}},10(X,$){$.response=X.message(R7)},11(X,$){$.response={type:"store_sql"}},12(X,$){$.response={type:"close_sql"}},13(X,$){$.response=X.message(E7)}},V7={default(){return{type:"execute",result:d2.default()}},1(X,$){$.result=X.message(d2)}},F7={default(){return{type:"batch",result:x1.default()}},1(X,$){$.result=X.message(x1)}},K7={default(){return{type:"fetch_cursor",entries:[],done:!1}},1(X,$){$.entries.push(X.message(n0))},2(X,$){$.done=X.bool()}},R7={default(){return{type:"describe",result:w1.default()}},1(X,$){$.result=X.message(w1)}},E7={default(){return{type:"get_autocommit",isAutocommit:!1}},1(X,$){$.isAutocommit=X.bool()}};var V$=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.#R(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 B("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=e1(X,Y$);this.#X.send(Z)}else if($==="protobuf"){let Z=Z0(X,W$);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()}#R(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),O$)}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),U$)}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 B2(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(B2(X.error))}else throw j(X,"Impossible ServerMsg type")}openStream(){return _0.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 B("Client was manually closed"))}get closed(){return this.#Y!==void 0}}var O0=Request,o6=Headers,r6=fetch;var X1;if(typeof queueMicrotask<"u")X1=queueMicrotask;else{let X=Promise.resolve();X1=($)=>{X.then($)}}class t6{#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 F$(X){let $=G2(X.baton),Z=G2(X.base_url),Y=V2(X.results,M7);return{baton:$,baseUrl:Z,results:Y}}function M7(X){let $=X2(X.type);if($==="ok")return{type:"ok",response:N7(c(X.response))};else if($==="error")return{type:"error",error:g2(c(X.error))};else throw new N("Unexpected type of StreamResult")}function N7(X){let $=X2(X.type);if($==="close")return{type:"close"};else if($==="execute")return{type:"execute",result:H0(c(X.result))};else if($==="batch")return{type:"batch",result:m0(c(X.result))};else if($==="sequence")return{type:"sequence"};else if($==="describe")return{type:"describe",result:c0(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 K$(X){let $=G2(X.baton),Z=G2(X.base_url);return{baton:$,baseUrl:Z}}var R$={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(I7))}},I7={default(){return{type:"none"}},1(X){return{type:"ok",response:X.message(x7)}},2(X){return{type:"error",error:X.message(H2)}}},x7={default(){return{type:"none"}},1(X){return{type:"close"}},2(X){return X.message(w7)},3(X){return X.message(P7)},4(X){return{type:"sequence"}},5(X){return X.message(k7)},6(X){return{type:"store_sql"}},7(X){return{type:"close_sql"}},8(X){return X.message(j7)}},w7={default(){return{type:"execute",result:d2.default()}},1(X,$){$.result=X.message(d2)}},P7={default(){return{type:"batch",result:x1.default()}},1(X,$){$.result=X.message(x1)}},k7={default(){return{type:"describe",result:w1.default()}},1(X,$){$.result=X.message(w1)}},j7={default(){return{type:"get_autocommit",isAutocommit:!1}},1(X,$){$.isAutocommit=X.bool()}},E$={default(){return{baton:void 0,baseUrl:void 0}},1(X,$){$.baton=X.string()},2(X,$){$.baseUrl=X.string()}};class l6 extends J0{#X;#$;#Z;#Y;#G;#J;constructor(X,$){super();this.#X=X,this.#$=$,this.#Z=void 0,this.#Y=new t6(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(K$,E$);if($===void 0)throw new N("Empty response to cursor request");return $}next(){return this.#W(u0,n0)}close(){this._setClosed(new B("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 M$(X,$){if($.baton!==void 0)X.string("baton",$.baton);X.arrayObjects("requests",$.requests,T7)}function T7(X,$){if(X.stringRaw("type",$.type),$.type==="close");else if($.type==="execute")X.object("stmt",$.stmt,W0);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 N$(X,$){if($.baton!==void 0)X.string("baton",$.baton);X.object("batch",$.batch,N1)}function I$(X,$){if($.baton!==void 0)X.string(1,$.baton);for(let Z of $.requests)X.message(2,Z,B7)}function B7(X,$){if($.type==="close")X.message(1,$,Q7);else if($.type==="execute")X.message(2,$,L7);else if($.type==="batch")X.message(3,$,v7);else if($.type==="sequence")X.message(4,$,C7);else if($.type==="describe")X.message(5,$,h7);else if($.type==="store_sql")X.message(6,$,f7);else if($.type==="close_sql")X.message(7,$,q7);else if($.type==="get_autocommit")X.message(8,$,y7);else throw j($,"Impossible type of StreamRequest")}function Q7(X,$){}function L7(X,$){X.message(1,$.stmt,z0)}function v7(X,$){X.message(1,$.batch,I1)}function C7(X,$){if($.sql!==void 0)X.string(1,$.sql);if($.sqlId!==void 0)X.int32(2,$.sqlId)}function h7(X,$){if($.sql!==void 0)X.string(1,$.sql);if($.sqlId!==void 0)X.int32(2,$.sqlId)}function f7(X,$){X.int32(1,$.sqlId),X.string(2,$.sql)}function q7(X,$){X.int32(1,$.sqlId)}function y7(X,$){}function x$(X,$){if($.baton!==void 0)X.string(1,$.baton);X.message(2,$.batch,I1)}class o0 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 B("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 B("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.#R(X,$);else throw j($,"Impossible type of QueueEntry")}#O(X,$){this.#K(()=>this.#M($,X),(Z)=>p7(Z,X.encoding),(Z)=>Z.baton,(Z)=>Z.baseUrl,(Z)=>S7($,Z),(Z)=>$.forEach((Y)=>Y.errorCallback(Z)))}#R(X,$){let Z=new l6(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 b7(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.#E(new URL($.pipelinePath,this.#$),{baton:this.#G,requests:X.map((Z)=>Z.request)},$.encoding,M$,I$)}#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.#E(new URL($.cursorPath,this.#$),{baton:this.#G,batch:X.batch},$.encoding,N$,x$)}#E(X,$,Z,Y,G){let J,_;if(Z==="json")J=e1($,Y),_="application/json";else if(Z==="protobuf")J=Z0($,G),_="application/x-protobuf";else throw j(Z,"Impossible encoding");let W=new o6;if(W.set("content-type",_),this.#Z!==void 0)W.set("authorization",`Bearer ${this.#Z}`);return new O0(X.toString(),{method:"POST",headers:W,body:J})}}function S7(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(B2(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 p7(X,$){if($==="json"){let Z=await X.json();return l2(Z,F$)}if($==="protobuf"){let Z=await X.arrayBuffer();return S2(new Uint8Array(Z),R$)}throw await X.body?.cancel(),j($,"Impossible encoding")}async function b7(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 B2(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 g7=[{versionPath:"v3-protobuf",pipelinePath:"v3-protobuf/pipeline",cursorPath:"v3-protobuf/cursor",version:3,encoding:"protobuf"}],s6={versionPath:"v2",pipelinePath:"v2/pipeline",cursorPath:void 0,version:2,encoding:"json"};class r0 extends F1{#X;#$;#Z;#Y;#G;_endpointPromise;_endpoint;constructor(X,$,Z,Y=2){super();if(this.#X=X,this.#$=$,this.#Z=Z??r6,this.#Y=void 0,this.#G=new Set,Y==3)this._endpointPromise=d7(this.#Z,this.#X),this._endpointPromise.then((G)=>this._endpoint=G,(G)=>this.#J(G));else this._endpointPromise=Promise.resolve(s6),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<=s6.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 o0(this,this.#X,this.#$,this.#Z);return this.#G.add(X),X}_streamClosed(X){this.#G.delete(X)}close(){this.#J(new B("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 d7(X,$){let Z=X;for(let Y of g7){let G=new URL(Y.versionPath,$),J=new O0(G.toString(),{method:"GET"}),_=await Z(J);if(await _.arrayBuffer(),_.ok)return Y}return s6}function a6(X,$,Z=2){if(typeof t1.default>"u")throw new s1("WebSockets are not supported in this environment");var Y=void 0;if(Z==3)Y=Array.from(i6.keys());else Y=Array.from(V$.keys());let G=new t1.default(X,Y);return new i0(G,$)}function e6(X,$,Z,Y=2){return new r0(X instanceof URL?X:new URL(X),$,Z,Y)}class D0{#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(Q2),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 R=A.query(O);return R.catch(()=>{return}),H=A,R}),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((E)=>{let M=Z.step().condition(y.ok(W));if($>=3)M.condition(y.not(y.isAutocommit(Z)));let x=M.query(E);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((E)=>{return}),G)Z.step().run("PRAGMA foreign_keys=on");await Z.execute();let V=[];await _;for(let E of H){let M=await E;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 Q2(X){let $,Z;if(Array.isArray(X))[$,Z]=X;else if(typeof X==="string")$=X;else $=X.sql,Z=X.args;let Y=new G0($);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 B){let $=w$(X);return new w(X.message,$,void 0,X)}return X}function w$(X){if(X instanceof l1&&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 B?w$(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 P$,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 P${#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 B$=b6($4(),1);function Q$(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 ${E2}`,"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 $=n1(X.scheme,X.authority,X.path),Z;try{Z=a6($,X.authToken)}catch(Y){if(Y instanceof s1){let G=X.scheme==="wss"?"https":"http",J=n1(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 ${E2}`,"WEBSOCKETS_NOT_SUPPORTED")}throw p(Y)}return new L$(Z,$,X.authToken,X.intMode,X.concurrency)}var c7=60000,T$=100;class L${#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=B$.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=Q2(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(Q2),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(Q2),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 v$(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()>c7&&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=T$}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??=a6(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=T$;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 v$ extends D0{#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 C$=b6($4(),1);function h$(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 ${E2}`,"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 $=n1(X.scheme,X.authority,X.path);return new q$($,X.authToken,X.intMode,X.fetch,X.concurrency)}var f$=30;class q${#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=e6(this.#$,this.#J,this.#Y),this.#X.intMode=this.#Z,this.protocol="http",this.#W=C$.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=Q2(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(Q2),G=await this.#X.getVersion(),J,_=this.#X.openStream();try{new j1(_,f$).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(Q2),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 y$(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=e6(this.#$,this.#J,this.#Y),this.#X.intMode=this.#Z}}get closed(){return this.#X.closed}}class y$ extends D0{#X;#$;constructor(X,$,Z){super($,Z);this.#X=X,this.#$=new j1(X,f$)}_getStream(){return this.#X}_getSqlCache(){return this.#$}close(){this.#X.close()}get closed(){return this.#X.closed}}function T1(X){return n7(o1(X,!0))}function n7(X){if(X.scheme==="wss"||X.scheme==="ws")return Q$(X);else if(X.scheme==="https"||X.scheme==="http")return h$(X);else return uX(X)}class l0 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 m1}static[D]="LibSQLSession";logger;cache;prepareQuery(X,$,Z,Y,G,J,_){return new p$(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 l0(this.client,this.dialect,this.schema,this.options,Z),G=new Z4("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 Z4 extends C6{static[D]="LibSQLTransaction";async transaction(X){let $=`sp${this.nestedIndex}`,Z=new Z4("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 p$ 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 $=C1(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=C1(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)=>S$(Z));if(this.customResultMapper)return this.customResultMapper(X,t0);return X.map((Z)=>{return A6(this.fields,Array.prototype.slice.call(Z).map((Y)=>t0(Y)),this.joinsNotNullableMap)})}async get(X){let{fields:$,logger:Z,query:Y,tx:G,client:J,customResultMapper:_}=this;if(!$&&!_){let H=C1(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 S$(Z);if(!Z)return;if(this.customResultMapper)return this.customResultMapper(X,t0);return A6(this.fields,Array.prototype.slice.call(Z).map((Y)=>t0(Y)),this.joinsNotNullableMap)}async values(X){let $=C1(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 S$(X){return Object.keys(X).reduce(($,Z)=>{if(Object.prototype.propertyIsEnumerable.call(X,Z))$[Z]=X[Z];return $},{})}function t0(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 b$ extends d1{static[D]="LibSQLDatabase";async batch(X){return this.session.batch(X)}}function B1(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=r4($.schema,l4);G={fullSchema:$.schema,schema:W.tables,tableNamesMap:W.tableNamesMap}}let J=new l0(X,Z,G,{logger:Y,cache:$.cache},void 0),_=new b$("async",Z,J,G);if(_.$client=X,_.$cache=$.cache,_.$cache)_.$cache.invalidate=$.cache?.onMutate;return _}function s0(...X){if(typeof X[0]==="string"){let $=T1({url:X[0]});return B1($,X[1])}if(w4(X[0])){let{connection:$,client:Z,...Y}=X[0];if(Z)return B1(Z,Y);let G=typeof $==="string"?T1({url:$}):T1($);return B1(G,Y)}return B1(X[0],X[1])}((X)=>{function $(Z){return B1({},Z)}X.mock=$})(s0||(s0={}));import i7 from"node:crypto";import Y4 from"node:fs";function g$(X){let $=X.migrationsFolder,Z=[],Y=`${$}/meta/_journal.json`;if(!Y4.existsSync(Y))throw Error("Can't find meta/_journal.json file");let G=Y4.readFileSync(`${$}/meta/_journal.json`).toString(),J=JSON.parse(G);for(let _ of J.entries){let W=`${$}/${_.tag}.sql`;try{let H=Y4.readFileSync(`${$}/${_.tag}.sql`).toString(),O=H.split("--> statement-breakpoint").map((A)=>{return A});Z.push({sql:O,bps:_.breakpoints,folderMillis:_.when,hash:i7.createHash("sha256").update(H).digest("hex")})}catch{throw Error(`No file ${W} found in ${$} folder`)}}return Z}async function d$(X,$){let Z=g$($),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 o7,writeFile as YO,mkdir as GO}from"node:fs/promises";import{join as G4}from"node:path";import{homedir as r7}from"node:os";var m$=G4(r7(),".sylphx","sessions"),WO=G4(m$,".last-session");function t7(X){return G4(m$,`${X}.json`)}async function u$(X){try{let $=t7(X),Z=await o7($,"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 zO(X,$,Z){return{...X,messages:[...X.messages,{role:$,content:[{type:"text",content:Z}],timestamp:Date.now()}]}}var W4=a0(c$(),".sylphx","sessions"),z4=a0(c$(),".sylphx-flow"),e7=a0(z4,"memory.db"),J4=a0(z4,".session-migrated");async function XG(X){try{if((await X.all(z`SELECT name FROM sqlite_master WHERE type='table' AND name='sessions'`)).length===0)return!0;if(a7(J4))return!1;try{let Y=(await _4(W4)).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 $G(X){await l7(z4,{recursive:!0}),await d$(X,{migrationsFolder:"./drizzle"})}async function ZG(X,$){let Z=new z1(X),G=(await _4(W4)).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 u$(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 s7(J4,"utf8").catch(()=>k2("fs").writeFileSync(J4,new Date().toISOString())),{success:J,errors:_}}async function YG(X){let $=process.env.DATABASE_URL||`file:${e7}`,Z=T1({url:$}),Y=s0(Z);if(!await XG(Y))return Y;X?.({total:2,current:0,status:"Initializing database..."}),await $G(Y),X?.({total:2,current:1,status:"Database initialized"});try{let _=(await _4(W4)).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 ZG(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 n$(X){return YG(X)}var _G=GG(JG(),".sylphx-flow","memory.db"),kO=process.env.DATABASE_URL||`file:${_G}`,e0=null,X6=null,A0=null;async function WG(){if(e0)return e0;if(A0)return A0;return A0=n$((X)=>{if(process.env.DEBUG)console.log(`[DB] ${X.current}/${X.total}: ${X.status}`)}),e0=await A0,A0=null,e0}async function jO(){if(X6)return X6;let X=await WG();return X6=new z1(X),X6}
|
|
21
|
-
export{z as $,r as aa,S1 as ba,B4 as ca,N0 as da,G1 as ea,b as fa,J1 as ga,I as ha,e as ia,f as ja,N6 as ka,T1 as la,s0 as ma,zO as na,WG as oa,jO as pa};
|
|
22
|
-
|
|
23
|
-
//# debugId=76B6284BCAC2001B64756E2164756E21
|
package/dist/chunk-w2vbmr93.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{W as V}from"./chunk-5szm4n3x.js";import{X as U}from"./chunk-8z1sf25t.js";import{Mb as R}from"./chunk-sxy6vp20.js";var E=R((M,Q)=>{var{defineProperty:K,getOwnPropertyDescriptor:W,getOwnPropertyNames:X}=Object,Y=Object.prototype.hasOwnProperty,Z=(q,v)=>{for(var z in v)K(q,z,{get:v[z],enumerable:!0})},$=(q,v,z,F)=>{if(v&&typeof v==="object"||typeof v==="function"){for(let G of X(v))if(!Y.call(q,G)&&G!==z)K(q,G,{get:()=>v[G],enumerable:!(F=W(v,G))||F.enumerable})}return q},A=(q)=>$(K({},"__esModule",{value:!0}),q),L={};Z(L,{refreshToken:()=>D});Q.exports=A(L);var H=U(),B=V();async function D(){let{projectId:q,teamId:v}=(0,B.findProjectInfo)(),z=(0,B.loadToken)(q);if(!z||(0,B.isExpired)((0,B.getTokenPayload)(z.token))){let F=(0,B.getVercelCliToken)();if(!F)throw new H.VercelOidcTokenError("Failed to refresh OIDC token: login to vercel cli");if(!q)throw new H.VercelOidcTokenError("Failed to refresh OIDC token: project id not found");if(z=await(0,B.getVercelOidcToken)(F,q,v),!z)throw new H.VercelOidcTokenError("Failed to refresh OIDC token");(0,B.saveToken)(z,q)}process.env.VERCEL_OIDC_TOKEN=z.token;return}});export default E();
|
|
2
|
-
|
|
3
|
-
//# debugId=C2AB45DE24B1888864756E2164756E21
|
package/dist/chunk-wd9qbbe5.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{z as J}from"./chunk-bnxtqetr.js";import"./chunk-f06ma45b.js";import"./chunk-9c2nr2fz.js";import"./chunk-wrx1n6q6.js";import"./chunk-d4hj6d4t.js";import"./chunk-fs3f7acb.js";import"./chunk-cs1s5c3g.js";import"./chunk-vjf57v4h.js";import"./chunk-8z1sf25t.js";import"./chunk-jgsq3xax.js";import"./chunk-m9nt0bj3.js";import"./chunk-hxj4eapp.js";import"./chunk-cv1nhr27.js";import"./chunk-gyq335sw.js";import"./chunk-sxy6vp20.js";function K(b){if(!b||b.trim().length===0)return"New Chat";let z=b.trim().replace(/\n+/g," "),B=50;if(z.length<=B)return z;let q=z.substring(0,B),D=q.lastIndexOf(" ");if(D>30)return q.substring(0,D)+"...";return q+"..."}async function P(b,z,B,q,D){if(!b||b.trim().length===0)return"New Chat";try{let G=J(z,B,q,[{role:"user",content:`Generate a concise, descriptive title (max 50 characters) for a chat that starts with this message. Only respond with the title, nothing else:
|
|
2
|
-
|
|
3
|
-
${b}`}],[]),F="";for await(let H of G.textStream)F+=H,D(H);let E=F.trim().replace(/["\n]/g,"");return E.length>50?E.substring(0,50)+"...":E}catch(G){return K(b)}}function Q(b,z){let B=b||"New Chat",q=new Date(z),D=new Date;if(q.toDateString()===D.toDateString()){let E=q.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit"});return`${B} (${E})`}let F=q.toLocaleDateString("en-US",{month:"short",day:"numeric"});return`${B} (${F})`}export{P as generateSessionTitleWithStreaming,K as generateSessionTitle,Q as formatSessionDisplay};
|
|
4
|
-
|
|
5
|
-
//# debugId=400125EE223A9C9E64756E2164756E21
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/utils/session-title.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"/**\n * Session Title Generation Utility\n * Generate concise titles from user messages\n */\n\nimport { createAIStream } from '../core/ai-sdk.js';\nimport type { ProviderId } from '../types/config.types.js';\n\n/**\n * Generate a session title from the first user message\n * Takes the first 50 characters and adds ellipsis if truncated\n */\nexport function generateSessionTitle(firstMessage: string): string {\n if (!firstMessage || firstMessage.trim().length === 0) {\n return 'New Chat';\n }\n\n // Remove leading/trailing whitespace and newlines\n const cleaned = firstMessage.trim().replace(/\\n+/g, ' ');\n\n // Truncate to 50 characters\n const maxLength = 50;\n if (cleaned.length <= maxLength) {\n return cleaned;\n }\n\n // Find last space before maxLength to avoid cutting words\n const truncated = cleaned.substring(0, maxLength);\n const lastSpace = truncated.lastIndexOf(' ');\n\n if (lastSpace > 30) {\n // If there's a space in reasonable range, cut there\n return truncated.substring(0, lastSpace) + '...';\n }\n\n // Otherwise just truncate and add ellipsis\n return truncated + '...';\n}\n\n/**\n * Generate a session title using LLM with streaming\n */\nexport async function generateSessionTitleWithStreaming(\n firstMessage: string,\n provider: ProviderId,\n modelName: string,\n providerConfig: any,\n onChunk: (chunk: string) => void\n): Promise<string> {\n if (!firstMessage || firstMessage.trim().length === 0) {\n return 'New Chat';\n }\n\n try {\n const stream = createAIStream(\n provider,\n modelName,\n providerConfig,\n [\n {\n role: 'user',\n content: `Generate a concise, descriptive title (max 50 characters) for a chat that starts with this message. Only respond with the title, nothing else:\\n\\n${firstMessage}`,\n },\n ],\n [], // no tools for title generation\n );\n\n let fullTitle = '';\n\n for await (const chunk of stream.textStream) {\n fullTitle += chunk;\n onChunk(chunk);\n }\n\n // Clean up title\n const cleaned = fullTitle.trim().replace(/[\"\\n]/g, '');\n return cleaned.length > 50 ? cleaned.substring(0, 50) + '...' : cleaned;\n } catch (error) {\n // Fallback to simple title generation\n return generateSessionTitle(firstMessage);\n }\n}\n\n/**\n * Format session title for display with timestamp\n */\nexport function formatSessionDisplay(title: string | undefined, created: number): string {\n const displayTitle = title || 'New Chat';\n const date = new Date(created);\n const now = new Date();\n\n // Show time if today, otherwise show date\n const isToday = date.toDateString() === now.toDateString();\n\n if (isToday) {\n const timeStr = date.toLocaleTimeString('en-US', {\n hour: '2-digit',\n minute: '2-digit',\n });\n return `${displayTitle} (${timeStr})`;\n }\n\n const dateStr = date.toLocaleDateString('en-US', {\n month: 'short',\n day: 'numeric',\n });\n return `${displayTitle} (${dateStr})`;\n}\n"
|
|
6
|
-
],
|
|
7
|
-
"mappings": "ogBAYO,GAAS,LAAoB,LAAC,JAA8B,LACjE,HAAI,LAAC,HAAgB,JAAa,DAAK,JAAE,GAAW,JAClD,AAAO,WAIT,IAAM,EAAU,EAAa,KAAK,EAAE,QAAQ,OAAQ,GAAG,EAGjD,EAAY,GAClB,GAAI,EAAQ,QAAU,EACpB,OAAO,EAIT,IAAM,EAAY,EAAQ,UAAU,EAAG,CAAS,EAC1C,EAAY,EAAU,YAAY,GAAG,EAE3C,GAAI,EAAY,GAEd,OAAO,EAAU,UAAU,EAAG,CAAS,EAAI,MAI7C,OAAO,EAAY,MAMrB,eAAsB,CAAiC,CACrD,EACA,EACA,EACA,EACA,EACiB,CACjB,GAAI,CAAC,GAAgB,EAAa,KAAK,EAAE,SAAW,EAClD,MAAO,WAGT,GAAI,CACF,IAAM,EAAS,EACb,EACA,EACA,EACA,CACE,CACE,KAAM,OACN,QAAS;AAAA;AAAA,EAAqJ,GAChK,CACF,EACA,CAAC,CACH,EAEI,EAAY,GAEhB,cAAiB,KAAS,EAAO,WAC/B,GAAa,EACb,EAAQ,CAAK,EAIf,IAAM,EAAU,EAAU,KAAK,EAAE,QAAQ,SAAU,EAAE,EACrD,OAAO,EAAQ,OAAS,GAAK,EAAQ,UAAU,EAAG,EAAE,EAAI,MAAQ,EAChE,MAAO,EAAO,CAEd,OAAO,EAAqB,CAAY,GAOrC,SAAS,CAAoB,CAAC,EAA2B,EAAyB,CACvF,IAAM,EAAe,GAAS,WACxB,EAAO,IAAI,KAAK,CAAO,EACvB,EAAM,IAAI,KAKhB,GAFgB,EAAK,aAAa,IAAM,EAAI,aAAa,EAE5C,CACX,IAAM,EAAU,EAAK,mBAAmB,QAAS,CAC/C,KAAM,UACN,OAAQ,SACV,CAAC,EACD,MAAO,GAAG,MAAiB,KAG7B,IAAM,EAAU,EAAK,mBAAmB,QAAS,CAC/C,MAAO,QACP,IAAK,SACP,CAAC,EACD,MAAO,GAAG,MAAiB",
|
|
8
|
-
"debugId": "400125EE223A9C9E64756E2164756E21",
|
|
9
|
-
"names": []
|
|
10
|
-
}
|