UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

179 lines • 450 kB
import{At as e,Bt as t,Ct as n,D as r,G as i,H as a,Ht as o,It as s,K as c,Lt as l,M as u,Mt as d,Nt as f,Rt as p,S as m,Tt as h,U as g,V as ee,W as te,a as ne,bt as re,c as ie,d as ae,f as oe,i as se,n as ce,q as le,t as ue,ut as de,x as fe,y as pe,z as me}from"./session-transcript-reconcile.worker-subsystem-BUNaGCPF.mjs";import{$n as he,$t as ge,A as _e,An as ve,At as ye,B as be,Br as xe,Bt as Se,Cn as Ce,Ct as we,Dn as Te,Dt as Ee,En as v,Fn as De,Gr as Oe,Gt as ke,I as Ae,Jn as je,Jr as Me,K as Ne,Kt as Pe,L as Fe,Ln as Ie,Or as Le,Ot as Re,Pt as ze,Qt as Be,Rn as Ve,Sn as He,Tn as Ue,Tt as We,U as Ge,Un as Ke,Vr as qe,Wr as Je,X as Ye,Xn as Xe,Xt as Ze,Y as Qe,Yn as $e,Yt as et,Zt as tt,_ as nt,br as rt,bt as it,cn as at,ct as ot,dr as st,et as ct,fr as lt,hr as ut,i as dt,in as ft,jn as pt,kt as mt,lt as ht,mn as gt,mr as _t,nn as vt,nt as yt,pn as bt,pr as xt,qt as St,rn as Ct,st as wt,tn as Tt,tt as Et,un as Dt,ur as Ot,vr as kt,wn as At,xt as jt,yn as Mt,yr as Nt}from"./session-transcript-reconcile.worker-worker-task-pool-iygKQQAw.mjs";import{$ as Pt,A as Ft,An as It,At as Lt,B as Rt,Bt as zt,Cn as Bt,Ct as Vt,D as Ht,Dn as Ut,Dt as Wt,E as Gt,En as Kt,Ft as qt,H as Jt,I as Yt,J as Xt,L as Zt,M as Qt,Mn as $t,Mt as en,N as tn,O as nn,On as rn,P as an,Pt as on,Q as sn,R as cn,St as ln,X as un,Y as dn,Z as pn,_ as mn,_n as hn,an as y,b as gn,bn as _n,bt as vn,cn as yn,d as bn,et as xn,f as Sn,g as Cn,gn as wn,h as Tn,ht as En,it as Dn,j as On,jt as kn,k as An,kn as jn,kt as Mn,l as Nn,ln as Pn,pt as Fn,q as In,sn as Ln,t as Rn,tt as zn,u as Bn,v as Vn,vt as Hn,wn as Un,wt as Wn,x as Gn,xn as Kn,xt as qn,y as Jn,yn as Yn,yt as Xn,z as Zn,zt as Qn}from"./session-transcript-reconcile.worker-sqlite-snapshot-staging-owner-By9qNyNO.mjs";import{r as $n,t as er}from"./session-transcript-reconcile.worker-deferred-BtGQJMOQ.mjs";import{t as tr}from"./session-transcript-reconcile.worker-usingCtx-03vOGQ3v.mjs";import{a as nr,i as rr,o as ir}from"./session-transcript-reconcile.worker-cli-invocation-fIA_-Tg7.mjs";import{c as ar,d as or,h as sr,u as cr}from"./session-transcript-reconcile.worker-service-child-group-ownership-AVmJ78Uc.mjs";import{n as lr}from"./session-transcript-reconcile.worker-runtime-worker-url-BKeFM3b_.mjs";import{n as ur,r as dr}from"./session-transcript-reconcile.worker-path-existence-BSsZ8dW-.mjs";import{f as fr,o as pr,t as mr,u as hr}from"./session-transcript-reconcile.worker-gateway-process-argv-BLuCIIZP.mjs";import{o as gr}from"./session-transcript-reconcile.worker-openclaw-root-C8Ptm0sQ.mjs";import"node:module";import{MessageChannel as _r,isMainThread as vr,threadId as yr}from"node:worker_threads";import b,{chmodSync as br,existsSync as xr,realpathSync as Sr,statSync as Cr,unlinkSync as wr,writeFileSync as Tr}from"node:fs";import"node:fs/promises";import x from"node:path";import{AsyncLocalStorage as S}from"node:async_hooks";import{createHash as Er,hash as Dr,randomUUID as Or}from"node:crypto";import kr from"node:os";import"node:util";import{GCProfiler as Ar}from"node:v8";import{channel as jr}from"node:diagnostics_channel";import"node:perf_hooks";import{createDirectorySync as Mr}from"@openclaw/fs-safe/advanced";import{FsSafeError as Nr}from"@openclaw/fs-safe/errors";import{spawnSync as Pr}from"node:child_process";import"semver";import"node:buffer";import{setImmediate as Fr}from"node:timers/promises";import{acquireFileLockSync as Ir}from"@openclaw/fs-safe/file-lock";var Lr=Object.defineProperty,__exportAll=(e,t)=>{let n={};for(var r in e)Lr(n,r,{get:e[r],enumerable:!0});return t||Lr(n,Symbol.toStringTag,{value:`Module`}),n};const Rr={Scavenge:`scavenge`,MinorMarkSweep:`scavenge`,MarkSweepCompact:`mark_sweep_compact`,IncrementalMarking:`incremental`,ProcessWeakCallbacks:`weak_processing`},zr=/* @__PURE__ */ new Set;let Br,Vr,Hr;function getOldGenerationAfterGcBytes(){return Hr}function drain(e){let t=Br?.stop();e&&Br?.start();let n=[];for(let e of t?.statistics??[]){let t=Rr[e.gcType];if(!t)continue;let r=e.beforeGC.heapStatistics.usedHeapSize,i={kind:t,reason:`other`,durationMs:e.cost/1e3,heapUsedBeforeBytes:r,reclaimedBytes:Math.max(0,r-e.afterGC.heapStatistics.usedHeapSize)};if(t===`mark_sweep_compact`){i.heapUsedAfterMajorGcBytes=e.afterGC.heapStatistics.usedHeapSize,i.heapUsedAfterMajorGcTimestampSeconds=Date.now()/1e3,Hr=0;for(let t of e.afterGC.heapSpaceStatistics)(t.spaceName===`old_space`||t.spaceName===`large_object_space`)&&(Hr+=t.spaceUsedSize)}n.push(i)}if(n.length)for(let e of zr)e(n)}function flushGcSamples(){Br&&drain(!0)}function observeGcSamples(e){if(!process.versions.bun)return Br?drain(!0):(Br=new Ar,Br.start(),Vr=setInterval(()=>drain(!0),1e3).unref()),zr.add(e),()=>{if(!zr.has(e))return;let t=zr.size===1;drain(!t),zr.delete(e),t&&(clearInterval(Vr),Vr=void 0,Br=void 0,Hr=void 0)}}const Ur=s(Symbol.for(`openclaw.databaseProcessRole`),()=>({}));function getDatabaseProcessRole(){return Ur.role}let Wr=0;function withEngineStoreAdmission(e){Wr+=1;try{let t=e();if(ve(t))throw Error(`Database engine admission must remain synchronous`);return t}finally{--Wr}}function assertEngineStoreExecutionAllowed(){if(yr===0&&Wr===0&&Ur.role!==`cli-oneshot`)throw Error(`PostgreSQL connections must run in a worker; only synchronous admission, migrations, and CLI one-shots may run on the main thread`)}function isUndefined(e){return e===void 0||e===void 0}function isString(e){return typeof e==`string`}function isNumber(e){return typeof e==`number`}function isBoolean(e){return typeof e==`boolean`}function isNull(e){return e===null}function isDate(e){return e instanceof Date}function isBigInt(e){return typeof e==`bigint`}function isFunction(e){return typeof e==`function`}function isObject$1(e){return typeof e==`object`&&!!e}function freeze(e){return Object.freeze(e)}function asArray(e){return isReadonlyArray(e)?e:[e]}function isReadonlyArray(e){return Array.isArray(e)}function noop(e){return e}function getMessage(e){return e instanceof Error?e.message:String(e)}const C=freeze({is(e){return e.kind===`AlterTableNode`},create(e){return freeze({kind:`AlterTableNode`,table:e})},cloneWithTableProps(e,t){return freeze({...e,...t})},cloneWithColumnAlteration(e,t){return freeze({...e,columnAlterations:e.columnAlterations?[...e.columnAlterations,t]:[t]})}}),w=freeze({is(e){return e.kind===`IdentifierNode`},create(e){return freeze({kind:`IdentifierNode`,name:e})}}),Gr=freeze({is(e){return e.kind===`CreateIndexNode`},create(e){return freeze({kind:`CreateIndexNode`,name:w.create(e)})},cloneWith(e,t){return freeze({...e,...t})},cloneWithColumns(e,t){return freeze({...e,columns:[...e.columns||[],...t]})}}),Kr=freeze({is(e){return e.kind===`CreateSchemaNode`},create(e,t){return freeze({kind:`CreateSchemaNode`,schema:w.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),qr=[`preserve rows`,`delete rows`,`drop`],T=freeze({is(e){return e.kind===`CreateTableNode`},create(e){return freeze({kind:`CreateTableNode`,table:e,columns:freeze([])})},cloneWithColumn(e,t){return freeze({...e,columns:freeze([...e.columns,t])})},cloneWithConstraint(e,t){return freeze({...e,constraints:e.constraints?freeze([...e.constraints,t]):freeze([t])})},cloneWithIndex(e,t){return freeze({...e,indexes:e.indexes?freeze([...e.indexes,t]):freeze([t])})},cloneWithFrontModifier(e,t){return freeze({...e,frontModifiers:e.frontModifiers?freeze([...e.frontModifiers,t]):freeze([t])})},cloneWithEndModifier(e,t){return freeze({...e,endModifiers:e.endModifiers?freeze([...e.endModifiers,t]):freeze([t])})},cloneWith(e,t){return freeze({...e,...t})}}),Jr=freeze({is(e){return e.kind===`SchemableIdentifierNode`},create(e){return freeze({kind:`SchemableIdentifierNode`,identifier:w.create(e)})},createWithSchema(e,t){return freeze({kind:`SchemableIdentifierNode`,schema:w.create(e),identifier:w.create(t)})}}),Yr=freeze({is(e){return e.kind===`DropIndexNode`},create(e,t){return freeze({kind:`DropIndexNode`,name:Jr.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),Xr=freeze({is(e){return e.kind===`DropSchemaNode`},create(e,t){return freeze({kind:`DropSchemaNode`,schema:w.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),Zr=freeze({is(e){return e.kind===`DropTableNode`},create(e,t){return freeze({kind:`DropTableNode`,table:e,...t})},cloneWith(e,t){return freeze({...e,...t})}}),Qr=freeze({is(e){return e.kind===`AliasNode`},create(e,t){return freeze({kind:`AliasNode`,node:e,alias:t})}}),$r=freeze({is(e){return e.kind===`TableNode`},create(e){return freeze({kind:`TableNode`,table:Jr.create(e)})},createWithSchema(e,t){return freeze({kind:`TableNode`,table:Jr.createWithSchema(e,t)})}});function isOperationNodeSource(e){return isObject$1(e)&&isFunction(e.toOperationNode)}function isExpression(e){return isObject$1(e)&&`expressionType`in e&&isOperationNodeSource(e)}function isAliasedExpression(e){return isObject$1(e)&&`expression`in e&&isString(e.alias)&&isOperationNodeSource(e)}const ei=freeze({is(e){return e.kind===`SelectModifierNode`},create(e,t){return freeze({kind:`SelectModifierNode`,modifier:e,of:t})},createWithExpression(e){return freeze({kind:`SelectModifierNode`,rawModifier:e})}}),ti=freeze({is(e){return e.kind===`AndNode`},create(e,t){return freeze({kind:`AndNode`,left:e,right:t})}}),ni=freeze({is(e){return e.kind===`OrNode`},create(e,t){return freeze({kind:`OrNode`,left:e,right:t})}}),ri=freeze({is(e){return e.kind===`OnNode`},create(e){return freeze({kind:`OnNode`,on:e})},cloneWithOperation(e,t,n){return freeze({...e,on:t===`And`?ti.create(e.on,n):ni.create(e.on,n)})}}),ii=freeze({is(e){return e.kind===`JoinNode`},create(e,t){return freeze({kind:`JoinNode`,joinType:e,table:t,on:void 0})},createWithOn(e,t,n){return freeze({kind:`JoinNode`,joinType:e,table:t,on:ri.create(n)})},cloneWithOn(e,t){return freeze({...e,on:e.on?ri.cloneWithOperation(e.on,`And`,t):ri.create(t)})}}),ai=freeze({is(e){return e.kind===`BinaryOperationNode`},create(e,t,n){return freeze({kind:`BinaryOperationNode`,leftOperand:e,operator:t,rightOperand:n})}}),oi=freeze({"=":!0,"==":!0,"!=":!0,"<>":!0,">":!0,">=":!0,"<":!0,"<=":!0,in:!0,"not in":!0,is:!0,"is not":!0,like:!0,"not like":!0,match:!0,ilike:!0,"not ilike":!0,"@>":!0,"<@":!0,"^@":!0,"&&":!0,"?":!0,"?&":!0,"?|":!0,"!<":!0,"!>":!0,"<=>":!0,"!~":!0,"~":!0,"~*":!0,"!~*":!0,"@@":!0,"@@@":!0,"!!":!0,"<->":!0,regexp:!0,"is distinct from":!0,"is not distinct from":!0});Object.keys(oi);const si=freeze({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0});Object.keys(si);const ci=freeze({"->":!0,"->>":!0}),li=Object.keys(ci),ui=freeze({...oi,...si,"||":!0}),di=Object.keys(ui),fi=freeze({exists:!0,"not exists":!0});Object.keys(fi);const pi=freeze({...fi,"-":!0,not:!0}),mi=Object.keys(pi);[...di,...li,...mi];const hi=freeze({is(e){return e.kind===`OperatorNode`},create(e){return freeze({kind:`OperatorNode`,operator:e})}});function isBinaryOperator(e){return isString(e)&&ui[e]}function isJSONOperator(e){return isString(e)&&ci[e]}function isUnaryOperator(e){return isString(e)&&pi[e]}const E=freeze({is(e){return e.kind===`ColumnNode`},create(e){return freeze({kind:`ColumnNode`,column:w.create(e)})}}),gi=freeze({is(e){return e.kind===`SelectAllNode`},create(){return freeze({kind:`SelectAllNode`})}}),_i=freeze({is(e){return e.kind===`ReferenceNode`},create(e,t){return freeze({kind:`ReferenceNode`,table:t,column:e})},createSelectAll(e){return freeze({kind:`ReferenceNode`,table:e,column:gi.create()})}});var DynamicReferenceBuilder=class{#e;get dynamicReference(){return this.#e}get refType(){}constructor(e){this.#e=e}toOperationNode(){return parseSimpleReferenceExpression(this.#e)}};function isDynamicReferenceBuilder(e){return isObject$1(e)&&isOperationNodeSource(e)&&isString(e.dynamicReference)}const vi=freeze({is(e){return e.kind===`OrderByItemNode`},create(e,t){return freeze({kind:`OrderByItemNode`,orderBy:e,direction:t})},cloneWith(e,t){return freeze({...e,...t})}}),D=freeze({is(e){return e.kind===`RawNode`},create(e,t){return freeze({kind:`RawNode`,sqlFragments:freeze(e),parameters:freeze(t)})},createWithSql(e){return D.create([e],[])},createWithChild(e){return D.create([``,``],[e])},createWithChildren(e){return D.create(Array(e.length+1).fill(``),e)}}),yi=freeze({is(e){return e.kind===`CollateNode`},create(e){return freeze({kind:`CollateNode`,collation:w.create(e)})}});var bi=class OrderByItemBuilder{#e;constructor(e){this.#e=freeze(e)}desc(){return new OrderByItemBuilder({node:vi.cloneWith(this.#e.node,{direction:D.createWithSql(`desc`)})})}asc(){return new OrderByItemBuilder({node:vi.cloneWith(this.#e.node,{direction:D.createWithSql(`asc`)})})}nullsLast(){return new OrderByItemBuilder({node:vi.cloneWith(this.#e.node,{nulls:`last`})})}nullsFirst(){return new OrderByItemBuilder({node:vi.cloneWith(this.#e.node,{nulls:`first`})})}collate(e){return new OrderByItemBuilder({node:vi.cloneWith(this.#e.node,{collation:yi.create(e)})})}toOperationNode(){return this.#e.node}};const xi=/* @__PURE__ */ new Set;function logOnce(e){xi.has(e)||(xi.add(e),console.log(e))}function isOrderByDirection(e){return e===`asc`||e===`desc`}function parseOrderBy(e){if(e.length===2)return[parseOrderByItem(e[0],e[1])];if(e.length===1){let[t]=e;return Array.isArray(t)?(logOnce(`orderBy(array) is deprecated, use multiple orderBy calls instead.`),t.map(e=>parseOrderByItem(e))):[parseOrderByItem(t)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${e.length}`)}function parseOrderByItem(e,t){let n=parseOrderByExpression(e);if(vi.is(n)){if(t)throw Error(`Cannot specify direction twice!`);return n}return parseOrderByWithModifiers(n,t)}function parseOrderByExpression(e){if(isExpressionOrFactory(e))return parseExpression(e);if(isDynamicReferenceBuilder(e))return e.toOperationNode();let[t,n]=e.split(` `);return n?(logOnce("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),parseOrderByWithModifiers(parseStringReference(t),n)):parseStringReference(e)}function parseOrderByWithModifiers(e,t){if(typeof t==`string`){if(!isOrderByDirection(t))throw Error(`Invalid order by direction: ${t}`);return vi.create(e,D.createWithSql(t))}if(isExpression(t))return logOnce("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),vi.create(e,t.toOperationNode());let n=vi.create(e);return t?t(new bi({node:n})).toOperationNode():n}const Si=freeze({is(e){return e.kind===`JSONReferenceNode`},create(e,t){return freeze({kind:`JSONReferenceNode`,reference:e,traversal:t})},cloneWithTraversal(e,t){return freeze({...e,traversal:t})}}),Ci=freeze({is(e){return e.kind===`JSONOperatorChainNode`},create(e){return freeze({kind:`JSONOperatorChainNode`,operator:e,values:freeze([])})},cloneWithValue(e,t){return freeze({...e,values:freeze([...e.values,t])})}}),wi=freeze({is(e){return e.kind===`JSONPathNode`},create(e){return freeze({kind:`JSONPathNode`,inOperator:e,pathLegs:freeze([])})},cloneWithLeg(e,t){return freeze({...e,pathLegs:freeze([...e.pathLegs,t])})}});function parseSimpleReferenceExpression(e){return isString(e)?parseStringReference(e):e.toOperationNode()}function parseReferenceExpressionOrList(e){return isReadonlyArray(e)?e.map(e=>parseReferenceExpression(e)):[parseReferenceExpression(e)]}function parseReferenceExpression(e){return isExpressionOrFactory(e)?parseExpression(e):parseSimpleReferenceExpression(e)}function parseJSONReference(e,t){if(isJSONOperator(t))return Si.create(parseStringReference(e),Ci.create(hi.create(t)));if(t===`->$`||t===`->>$`)return Si.create(parseStringReference(e),wi.create(hi.create(t.slice(0,-1))));throw Error(`Invalid JSON operator: ${t}`)}function parseStringReference(e){if(!e.includes(`.`))return _i.create(E.create(e));let t=e.split(`.`).map(trim$2);if(t.length===3)return parseStringReferenceWithTableAndSchema(t);if(t.length===2)return parseStringReferenceWithTable(t);throw Error(`invalid column reference ${e}`)}function parseAliasedStringReference(e){let t=` as `;if(e.includes(t)){let[n,r]=e.split(t).map(trim$2);return Qr.create(parseStringReference(n),w.create(r))}return parseStringReference(e)}function parseColumnName(e){return E.create(e)}function parseOrderedColumnName(e){if(e.includes(` `)){let[t,n]=e.split(` `).map(trim$2);if(!isOrderByDirection(n))throw Error(`invalid order direction "${n}" next to "${t}"`);return parseOrderBy([t,n])[0]}return parseColumnName(e)}function parseStringReferenceWithTableAndSchema(e){let[t,n,r]=e;return _i.create(E.create(r),$r.createWithSchema(t,n))}function parseStringReferenceWithTable(e){let[t,n]=e;return _i.create(E.create(n),$r.create(t))}function trim$2(e){return e.trim()}const Ti=freeze({is(e){return e.kind===`PrimitiveValueListNode`},create(e){return freeze({kind:`PrimitiveValueListNode`,values:freeze([...e])})}}),Ei=freeze({is(e){return e.kind===`ValueListNode`},create(e){return freeze({kind:`ValueListNode`,values:freeze(e)})}}),O=freeze({is(e){return e.kind===`ValueNode`},create(e){return freeze({kind:`ValueNode`,value:e})},createImmediate(e){return freeze({kind:`ValueNode`,value:e,immediate:!0})}});function parseValueExpressionOrList(e){return isReadonlyArray(e)?parseValueExpressionList(e):parseValueExpression(e)}function parseValueExpression(e){return isExpressionOrFactory(e)?parseExpression(e):O.create(e)}function isSafeImmediateValue(e){return isNumber(e)||isBoolean(e)||isNull(e)}function parseSafeImmediateValue(e){if(!isSafeImmediateValue(e))throw Error(`unsafe immediate value ${JSON.stringify(e)}`);return O.createImmediate(e)}function parseValueExpressionList(e){return e.some(isExpressionOrFactory)?Ei.create(e.map(e=>parseValueExpression(e))):Ti.create(e)}const Di=freeze({is(e){return e.kind===`ParensNode`},create(e){return freeze({kind:`ParensNode`,node:e})}});function parseValueBinaryOperationOrExpression(e){if(e.length===3)return parseValueBinaryOperation(e[0],e[1],e[2]);if(e.length===1)return parseValueExpression(e[0]);throw Error(`invalid arguments: ${JSON.stringify(e)}`)}function parseValueBinaryOperation(e,t,n){return isIsOperator(t)&&needsIsOperator(n)?ai.create(parseReferenceExpression(e),parseBinaryOperator(t),O.createImmediate(n)):ai.create(parseReferenceExpression(e),parseBinaryOperator(t),parseValueExpressionOrList(n))}function parseReferentialBinaryOperation(e,t,n){return ai.create(parseReferenceExpression(e),parseBinaryOperator(t),parseReferenceExpression(n))}function parseFilterObject(e,t){return parseFilterList(Object.entries(e).filter(([,e])=>!isUndefined(e)).map(([e,t])=>parseValueBinaryOperation(e,needsIsOperator(t)?`is`:`=`,t)),t)}function parseFilterList(e,t,n=!0){let r=t===`and`?ti.create:ni.create;if(e.length===0)return ai.create(O.createImmediate(1),hi.create(`=`),O.createImmediate(+(t===`and`)));let i=toOperationNode(e[0]);for(let t=1;t<e.length;++t)i=r(i,toOperationNode(e[t]));return e.length>1&&n?Di.create(i):i}function isIsOperator(e){return e===`is`||e===`is not`}function needsIsOperator(e){return isNull(e)||isBoolean(e)}function parseBinaryOperator(e){if(isBinaryOperator(e))return hi.create(e);if(isOperationNodeSource(e))return e.toOperationNode();throw Error(`invalid operator ${JSON.stringify(e)}`)}function toOperationNode(e){return isOperationNodeSource(e)?e.toOperationNode():e}const Oi=freeze({is(e){return e.kind===`OrderByNode`},create(e){return freeze({kind:`OrderByNode`,items:freeze([...e])})},cloneWithItems(e,t){return freeze({...e,items:freeze([...e.items,...t])})}}),ki=freeze({is(e){return e.kind===`PartitionByNode`},create(e){return freeze({kind:`PartitionByNode`,items:freeze(e)})},cloneWithItems(e,t){return freeze({...e,items:freeze([...e.items,...t])})}}),Ai=freeze({is(e){return e.kind===`OverNode`},create(){return freeze({kind:`OverNode`})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?Oi.cloneWithItems(e.orderBy,t):Oi.create(t)})},cloneWithPartitionByItems(e,t){return freeze({...e,partitionBy:e.partitionBy?ki.cloneWithItems(e.partitionBy,t):ki.create(t)})}}),ji=freeze({is(e){return e.kind===`FromNode`},create(e){return freeze({kind:`FromNode`,froms:freeze(e)})},cloneWithFroms(e,t){return freeze({...e,froms:freeze([...e.froms,...t])})}}),Mi=freeze({is(e){return e.kind===`GroupByNode`},create(e){return freeze({kind:`GroupByNode`,items:freeze(e)})},cloneWithItems(e,t){return freeze({...e,items:freeze([...e.items,...t])})}}),Ni=freeze({is(e){return e.kind===`HavingNode`},create(e){return freeze({kind:`HavingNode`,having:e})},cloneWithOperation(e,t,n){return freeze({...e,having:t===`And`?ti.create(e.having,n):ni.create(e.having,n)})}}),k=freeze({is(e){return e.kind===`InsertQueryNode`},create(e,t,n){return freeze({kind:`InsertQueryNode`,into:e,...t&&{with:t},replace:n})},createWithoutInto(){return freeze({kind:`InsertQueryNode`})},cloneWith(e,t){return freeze({...e,...t})}}),Pi=freeze({is(e){return e.kind===`ListNode`},create(e){return freeze({kind:`ListNode`,items:freeze(e)})}}),Fi=freeze({is(e){return e.kind===`UpdateQueryNode`},create(e,t){return freeze({kind:`UpdateQueryNode`,table:e.length===1?e[0]:Pi.create(e),...t&&{with:t}})},createWithoutTable(){return freeze({kind:`UpdateQueryNode`})},cloneWithFromItems(e,t){return freeze({...e,from:e.from?ji.cloneWithFroms(e.from,t):ji.create(t)})},cloneWithUpdates(e,t){return freeze({...e,updates:e.updates?freeze([...e.updates,...t]):t})},cloneWithLimit(e,t){return freeze({...e,limit:t})}}),Ii=freeze({is(e){return e.kind===`UsingNode`},create(e){return freeze({kind:`UsingNode`,tables:freeze(e)})},cloneWithTables(e,t){return freeze({...e,tables:freeze([...e.tables,...t])})}}),Li=freeze({is(e){return e.kind===`DeleteQueryNode`},create(e,t){return freeze({kind:`DeleteQueryNode`,from:ji.create(e),...t&&{with:t}})},cloneWithOrderByItems:(e,t)=>j.cloneWithOrderByItems(e,t),cloneWithoutOrderBy:e=>j.cloneWithoutOrderBy(e),cloneWithLimit(e,t){return freeze({...e,limit:t})},cloneWithoutLimit(e){return freeze({...e,limit:void 0})},cloneWithUsing(e,t){return freeze({...e,using:e.using===void 0?Ii.create(t):Ii.cloneWithTables(e.using,t)})}}),A=freeze({is(e){return e.kind===`WhereNode`},create(e){return freeze({kind:`WhereNode`,where:e})},cloneWithOperation(e,t,n){return freeze({...e,where:t===`And`?ti.create(e.where,n):ni.create(e.where,n)})}}),Ri=freeze({is(e){return e.kind===`ReturningNode`},create(e){return freeze({kind:`ReturningNode`,selections:freeze(e)})},cloneWithSelections(e,t){return freeze({...e,selections:e.selections?freeze([...e.selections,...t]):freeze(t)})}}),zi=freeze({is(e){return e.kind===`ExplainNode`},create(e,t){return freeze({kind:`ExplainNode`,format:e,options:t})}}),Bi=freeze({is(e){return e.kind===`WhenNode`},create(e){return freeze({kind:`WhenNode`,condition:e})},cloneWithResult(e,t){return freeze({...e,result:t})}}),Vi=freeze({is(e){return e.kind===`MergeQueryNode`},create(e,t){return freeze({kind:`MergeQueryNode`,into:e,...t&&{with:t}})},cloneWithUsing(e,t){return freeze({...e,using:t})},cloneWithWhen(e,t){return freeze({...e,whens:e.whens?freeze([...e.whens,t]):freeze([t])})},cloneWithThen(e,t){return freeze({...e,whens:e.whens?freeze([...e.whens.slice(0,-1),Bi.cloneWithResult(e.whens[e.whens.length-1],t)]):void 0})}}),Hi=freeze({is(e){return e.kind===`OutputNode`},create(e){return freeze({kind:`OutputNode`,selections:freeze(e)})},cloneWithSelections(e,t){return freeze({...e,selections:e.selections?freeze([...e.selections,...t]):freeze(t)})}}),j=freeze({is(e){return M.is(e)||k.is(e)||Fi.is(e)||Li.is(e)||Vi.is(e)},cloneWithEndModifier(e,t){return freeze({...e,endModifiers:e.endModifiers?freeze([...e.endModifiers,t]):freeze([t])})},cloneWithWhere(e,t){return freeze({...e,where:e.where?A.cloneWithOperation(e.where,`And`,t):A.create(t)})},cloneWithJoin(e,t){return freeze({...e,joins:e.joins?freeze([...e.joins,t]):freeze([t])})},cloneWithReturning(e,t){return freeze({...e,returning:e.returning?Ri.cloneWithSelections(e.returning,t):Ri.create(t)})},cloneWithoutReturning(e){return freeze({...e,returning:void 0})},cloneWithoutWhere(e){return freeze({...e,where:void 0})},cloneWithExplain(e,t,n){return freeze({...e,explain:zi.create(t,n?.toOperationNode())})},cloneWithTop(e,t){return freeze({...e,top:t})},cloneWithOutput(e,t){return freeze({...e,output:e.output?Hi.cloneWithSelections(e.output,t):Hi.create(t)})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?Oi.cloneWithItems(e.orderBy,t):Oi.create(t)})},cloneWithoutOrderBy(e){return freeze({...e,orderBy:void 0})}}),M=freeze({is(e){return e.kind===`SelectQueryNode`},create(e){return freeze({kind:`SelectQueryNode`,...e&&{with:e}})},createFrom(e,t){return freeze({kind:`SelectQueryNode`,from:ji.create(e),...t&&{with:t}})},cloneWithSelections(e,t){return freeze({...e,selections:e.selections?freeze([...e.selections,...t]):freeze(t)})},cloneWithDistinctOn(e,t){return freeze({...e,distinctOn:e.distinctOn?freeze([...e.distinctOn,...t]):freeze(t)})},cloneWithFrontModifier(e,t){return freeze({...e,frontModifiers:e.frontModifiers?freeze([...e.frontModifiers,t]):freeze([t])})},cloneWithOrderByItems:(e,t)=>j.cloneWithOrderByItems(e,t),cloneWithGroupByItems(e,t){return freeze({...e,groupBy:e.groupBy?Mi.cloneWithItems(e.groupBy,t):Mi.create(t)})},cloneWithLimit(e,t){return freeze({...e,limit:t})},cloneWithOffset(e,t){return freeze({...e,offset:t})},cloneWithFetch(e,t){return freeze({...e,fetch:t})},cloneWithHaving(e,t){return freeze({...e,having:e.having?Ni.cloneWithOperation(e.having,`And`,t):Ni.create(t)})},cloneWithSetOperations(e,t){return freeze({...e,setOperations:e.setOperations?freeze([...e.setOperations,...t]):freeze([...t])})},cloneWithoutSelections(e){return freeze({...e,selections:[]})},cloneWithoutLimit(e){return freeze({...e,limit:void 0})},cloneWithoutOffset(e){return freeze({...e,offset:void 0})},cloneWithoutOrderBy:e=>j.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return freeze({...e,groupBy:void 0})}});var Ui=class JoinBuilder{#e;constructor(e){this.#e=freeze(e)}on(...e){return new JoinBuilder({...this.#e,joinNode:ii.cloneWithOn(this.#e.joinNode,parseValueBinaryOperationOrExpression(e))})}onRef(e,t,n){return new JoinBuilder({...this.#e,joinNode:ii.cloneWithOn(this.#e.joinNode,parseReferentialBinaryOperation(e,t,n))})}onTrue(){return new JoinBuilder({...this.#e,joinNode:ii.cloneWithOn(this.#e.joinNode,D.createWithSql(`true`))})}$call(e){return e(this)}toOperationNode(){return this.#e.joinNode}};const Wi=freeze({is(e){return e.kind===`PartitionByItemNode`},create(e){return freeze({kind:`PartitionByItemNode`,partitionBy:e})}});function parsePartitionBy(e){return parseReferenceExpressionOrList(e).map(Wi.create)}var Gi=class OverBuilder{#e;constructor(e){this.#e=freeze(e)}orderBy(...e){return new OverBuilder({overNode:Ai.cloneWithOrderByItems(this.#e.overNode,parseOrderBy(e))})}clearOrderBy(){return new OverBuilder({overNode:j.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(e){return new OverBuilder({overNode:Ai.cloneWithPartitionByItems(this.#e.overNode,parsePartitionBy(e))})}$call(e){return e(this)}toOperationNode(){return this.#e.overNode}};const Ki=freeze({is(e){return e.kind===`SelectionNode`},create(e){return freeze({kind:`SelectionNode`,selection:e})},createSelectAll(){return freeze({kind:`SelectionNode`,selection:gi.create()})},createSelectAllFromTable(e){return freeze({kind:`SelectionNode`,selection:_i.createSelectAll(e)})}});function parseSelectArg(e){return isFunction(e)?parseSelectArg(e(expressionBuilder())):isReadonlyArray(e)?e.map(e=>parseSelectExpression(e)):[parseSelectExpression(e)]}function parseSelectExpression(e){return isString(e)?Ki.create(parseAliasedStringReference(e)):isDynamicReferenceBuilder(e)?Ki.create(e.toOperationNode()):Ki.create(parseAliasedExpression(e))}function parseSelectAll(e){return e?Array.isArray(e)?e.map(parseSelectAllArg):[parseSelectAllArg(e)]:[Ki.createSelectAll()]}function parseSelectAllArg(e){if(isString(e))return Ki.createSelectAllFromTable(parseTable(e));throw Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}const qi=freeze({is(e){return e.kind===`ValuesNode`},create(e){return freeze({kind:`ValuesNode`,values:freeze(e)})}}),Ji=freeze({is(e){return e.kind===`DefaultInsertValueNode`},create(){return freeze({kind:`DefaultInsertValueNode`})}});function parseInsertExpression(e){let t=isFunction(e)?e(expressionBuilder()):e;return parseInsertColumnsAndValues(isReadonlyArray(t)?t:freeze([t]))}function parseInsertColumnsAndValues(e){let t=parseColumnNamesAndIndexes(e);return[freeze([...t.keys()].map(E.create)),qi.create(e.map(e=>parseRowValues(e,t)))]}function parseColumnNamesAndIndexes(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=Object.keys(n);for(let r of e)!t.has(r)&&n[r]!==void 0&&t.set(r,t.size)}return t}function parseRowValues(e,t){let n=Object.keys(e),r=Array.from({length:t.size}),i=!1,a=n.length;for(let o of n){let n=t.get(o);if(isUndefined(n)){a--;continue}let s=e[o];(isUndefined(s)||isExpressionOrFactory(s))&&(i=!0),r[n]=s}if(a<t.size||i){let e=Ji.create();return Ei.create(r.map(t=>isUndefined(t)?e:parseValueExpression(t)))}return Ti.create(r)}const Yi=freeze({is(e){return e.kind===`ColumnUpdateNode`},create(e,t){return freeze({kind:`ColumnUpdateNode`,column:e,value:t})}});function parseUpdate(...e){return e.length===2?[Yi.create(parseReferenceExpression(e[0]),parseValueExpression(e[1]))]:parseUpdateObjectExpression(e[0])}function parseUpdateObjectExpression(e){let t=isFunction(e)?e(expressionBuilder()):e;return Object.entries(t).filter(([e,t])=>t!==void 0).map(([e,t])=>Yi.create(E.create(e),parseValueExpression(t)))}const Xi=freeze({is(e){return e.kind===`OnDuplicateKeyNode`},create(e){return freeze({kind:`OnDuplicateKeyNode`,updates:e})}});var InsertResult=class{insertId;numInsertedOrUpdatedRows;constructor(e,t){this.insertId=e,this.numInsertedOrUpdatedRows=t}},NoResultError=class extends Error{node;constructor(e){super(`no result`),this.node=e}};function isNoResultErrorConstructor(e){return Object.prototype.hasOwnProperty.call(e,`prototype`)}const N=freeze({is(e){return e.kind===`OnConflictNode`},create(){return freeze({kind:`OnConflictNode`})},cloneWith(e,t){return freeze({...e,...t})},cloneWithIndexWhere(e,t){return freeze({...e,indexWhere:e.indexWhere?A.cloneWithOperation(e.indexWhere,`And`,t):A.create(t)})},cloneWithIndexOrWhere(e,t){return freeze({...e,indexWhere:e.indexWhere?A.cloneWithOperation(e.indexWhere,`Or`,t):A.create(t)})},cloneWithUpdateWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?A.cloneWithOperation(e.updateWhere,`And`,t):A.create(t)})},cloneWithUpdateOrWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?A.cloneWithOperation(e.updateWhere,`Or`,t):A.create(t)})},cloneWithoutIndexWhere(e){return freeze({...e,indexWhere:void 0})},cloneWithoutUpdateWhere(e){return freeze({...e,updateWhere:void 0})}});var Zi=class OnConflictBuilder{#e;constructor(e){this.#e=freeze(e)}column(e){let t=E.create(e);return new OnConflictBuilder({...this.#e,onConflictNode:N.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?freeze([...this.#e.onConflictNode.columns,t]):freeze([t])})})}columns(e){let t=e.map(E.create);return new OnConflictBuilder({...this.#e,onConflictNode:N.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?freeze([...this.#e.onConflictNode.columns,...t]):freeze(t)})})}constraint(e){return new OnConflictBuilder({...this.#e,onConflictNode:N.cloneWith(this.#e.onConflictNode,{constraint:w.create(e)})})}expression(e){return new OnConflictBuilder({...this.#e,onConflictNode:N.cloneWith(this.#e.onConflictNode,{indexExpression:e.toOperationNode()})})}where(...e){return new OnConflictBuilder({...this.#e,onConflictNode:N.cloneWithIndexWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictBuilder({...this.#e,onConflictNode:N.cloneWithIndexWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictBuilder({...this.#e,onConflictNode:N.cloneWithoutIndexWhere(this.#e.onConflictNode)})}doNothing(){return new OnConflictDoNothingBuilder({...this.#e,onConflictNode:N.cloneWith(this.#e.onConflictNode,{doNothing:!0})})}doUpdateSet(e){return new Qi({...this.#e,onConflictNode:N.cloneWith(this.#e.onConflictNode,{updates:parseUpdateObjectExpression(e)})})}$call(e){return e(this)}},OnConflictDoNothingBuilder=class{#e;constructor(e){this.#e=freeze(e)}toOperationNode(){return this.#e.onConflictNode}},Qi=class OnConflictUpdateBuilder{#e;constructor(e){this.#e=freeze(e)}where(...e){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:N.cloneWithUpdateWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:N.cloneWithUpdateWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:N.cloneWithoutUpdateWhere(this.#e.onConflictNode)})}$call(e){return e(this)}toOperationNode(){return this.#e.onConflictNode}};const $i=freeze({is(e){return e.kind===`TopNode`},create(e,t){return freeze({kind:`TopNode`,expression:e,modifiers:t})}});function parseTop(e,t){if(!isNumber(e)&&!isBigInt(e))throw Error(`Invalid top expression: ${e}`);if(!isUndefined(t)&&!isTopModifiers(t))throw Error(`Invalid top modifiers: ${t}`);return $i.create(e,t)}function isTopModifiers(e){return e===`percent`||e===`with ties`||e===`percent with ties`}const ea=freeze({is(e){return e.kind===`OrActionNode`},create(e){return freeze({kind:`OrActionNode`,action:e})}});var ta=class InsertQueryBuilder{#e;constructor(e){this.#e=freeze(e)}values(e){let[t,n]=parseInsertExpression(e);return new InsertQueryBuilder({...this.#e,queryNode:k.cloneWith(this.#e.queryNode,{columns:t,values:n})})}columns(e){return new InsertQueryBuilder({...this.#e,queryNode:k.cloneWith(this.#e.queryNode,{columns:freeze(e.map(E.create))})})}expression(e){return new InsertQueryBuilder({...this.#e,queryNode:k.cloneWith(this.#e.queryNode,{values:parseExpression(e)})})}defaultValues(){return new InsertQueryBuilder({...this.#e,queryNode:k.cloneWith(this.#e.queryNode,{defaultValues:!0})})}modifyEnd(e){return new InsertQueryBuilder({...this.#e,queryNode:j.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}ignore(){return new InsertQueryBuilder({...this.#e,queryNode:k.cloneWith(this.#e.queryNode,{orAction:ea.create(`ignore`)})})}orIgnore(){return new InsertQueryBuilder({...this.#e,queryNode:k.cloneWith(this.#e.queryNode,{orAction:ea.create(`ignore`)})})}orAbort(){return new InsertQueryBuilder({...this.#e,queryNode:k.cloneWith(this.#e.queryNode,{orAction:ea.create(`abort`)})})}orFail(){return new InsertQueryBuilder({...this.#e,queryNode:k.cloneWith(this.#e.queryNode,{orAction:ea.create(`fail`)})})}orReplace(){return new InsertQueryBuilder({...this.#e,queryNode:k.cloneWith(this.#e.queryNode,{orAction:ea.create(`replace`)})})}orRollback(){return new InsertQueryBuilder({...this.#e,queryNode:k.cloneWith(this.#e.queryNode,{orAction:ea.create(`rollback`)})})}top(e,t){return new InsertQueryBuilder({...this.#e,queryNode:j.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}onConflict(e){return new InsertQueryBuilder({...this.#e,queryNode:k.cloneWith(this.#e.queryNode,{onConflict:e(new Zi({onConflictNode:N.create()})).toOperationNode()})})}onDuplicateKeyUpdate(e){return new InsertQueryBuilder({...this.#e,queryNode:k.cloneWith(this.#e.queryNode,{onDuplicateKey:Xi.create(parseUpdateObjectExpression(e))})})}returning(e){return new InsertQueryBuilder({...this.#e,queryNode:j.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(){return new InsertQueryBuilder({...this.#e,queryNode:j.cloneWithReturning(this.#e.queryNode,parseSelectAll())})}output(e){return new InsertQueryBuilder({...this.#e,queryNode:j.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new InsertQueryBuilder({...this.#e,queryNode:j.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new InsertQueryBuilder({...this.#e,queryNode:j.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new InsertQueryBuilder({...this.#e})}$castTo(){return new InsertQueryBuilder(this.#e)}$narrowType(){return new InsertQueryBuilder(this.#e)}$assertType(){return new InsertQueryBuilder(this.#e)}withPlugin(e){return new InsertQueryBuilder({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new InsertResult(n.insertId,n.numAffectedRows??BigInt(0))]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new InsertQueryBuilder({...this.#e,queryNode:j.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}},DeleteResult=class{numDeletedRows;constructor(e){this.numDeletedRows=e}};const na=freeze({is(e){return e.kind===`LimitNode`},create(e){return freeze({kind:`LimitNode`,limit:e})}});var P,DeleteQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new P({...this.#e,queryNode:j.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new P({...this.#e,queryNode:j.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new P({...this.#e,queryNode:j.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new P({...this.#e,queryNode:j.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(e){return new P({...this.#e,queryNode:Li.cloneWithUsing(this.#e.queryNode,parseTableExpressionOrList(e))})}innerJoin(...e){return this.#t(`InnerJoin`,e)}leftJoin(...e){return this.#t(`LeftJoin`,e)}rightJoin(...e){return this.#t(`RightJoin`,e)}fullJoin(...e){return this.#t(`FullJoin`,e)}#t(e,t){return new P({...this.#e,queryNode:j.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}returning(e){return new P({...this.#e,queryNode:j.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new P({...this.#e,queryNode:j.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new P({...this.#e,queryNode:j.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new P({...this.#e,queryNode:j.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new P({...this.#e,queryNode:j.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new P({...this.#e,queryNode:Li.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...e){return new P({...this.#e,queryNode:j.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new P({...this.#e,queryNode:j.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new P({...this.#e,queryNode:Li.cloneWithLimit(this.#e.queryNode,na.create(parseValueExpression(e)))})}modifyEnd(e){return new P({...this.#e,queryNode:j.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}$call(e){return e(this)}$if(e,t){return e?t(this):new P({...this.#e})}$castTo(){return new P(this.#e)}$narrowType(){return new P(this.#e)}$assertType(){return new P(this.#e)}withPlugin(e){return new P({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new DeleteResult(n.numAffectedRows??BigInt(0))]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new P({...this.#e,queryNode:j.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};P=DeleteQueryBuilder;var UpdateResult=class{numUpdatedRows;numChangedRows;constructor(e,t){this.numUpdatedRows=e,this.numChangedRows=t}},F,UpdateQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new F({...this.#e,queryNode:j.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new F({...this.#e,queryNode:j.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new F({...this.#e,queryNode:j.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new F({...this.#e,queryNode:j.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}from(e){return new F({...this.#e,queryNode:Fi.cloneWithFromItems(this.#e.queryNode,parseTableExpressionOrList(e))})}innerJoin(...e){return this.#t(`InnerJoin`,e)}leftJoin(...e){return this.#t(`LeftJoin`,e)}rightJoin(...e){return this.#t(`RightJoin`,e)}fullJoin(...e){return this.#t(`FullJoin`,e)}#t(e,t){return new F({...this.#e,queryNode:j.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new F({...this.#e,queryNode:j.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new F({...this.#e,queryNode:j.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new F({...this.#e,queryNode:Fi.cloneWithLimit(this.#e.queryNode,na.create(parseValueExpression(e)))})}set(...e){return new F({...this.#e,queryNode:Fi.cloneWithUpdates(this.#e.queryNode,parseUpdate(...e))})}returning(e){return new F({...this.#e,queryNode:j.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new F({...this.#e,queryNode:j.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new F({...this.#e,queryNode:j.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new F({...this.#e,queryNode:j.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}modifyEnd(e){return new F({...this.#e,queryNode:j.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}clearReturning(){return new F({...this.#e,queryNode:j.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new F({...this.#e})}$castTo(){return new F(this.#e)}$narrowType(){return new F(this.#e)}$assertType(){return new F(this.#e)}withPlugin(e){return new F({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new UpdateResult(n.numAffectedRows??BigInt(0),n.numChangedRows)]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new F({...this.#e,queryNode:j.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};F=UpdateQueryBuilder;const ra=freeze({is(e){return e.kind===`CommonTableExpressionNameNode`},create(e,t){return freeze({kind:`CommonTableExpressionNameNode`,table:$r.create(e),columns:t?freeze(t.map(E.create)):void 0})}}),ia=freeze({is(e){return e.kind===`CommonTableExpressionNode`},create(e,t){return freeze({kind:`CommonTableExpressionNode`,name:e,expression:t})},cloneWith(e,t){return freeze({...e,...t})}});var aa=class CTEBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new CTEBuilder({...this.#e,node:ia.cloneWith(this.#e.node,{materialized:!0})})}notMaterialized(){return new CTEBuilder({...this.#e,node:ia.cloneWith(this.#e.node,{materialized:!1})})}toOperationNode(){return this.#e.node}};function parseCommonTableExpression(e,t){let n=isOperationNodeSource(t)?t.toOperationNode():t(createQueryCreator()).toOperationNode();return isFunction(e)?e(cteBuilderFactory(n)).toOperationNode():ia.create(parseCommonTableExpressionName(e),n)}function cteBuilderFactory(e){return t=>new aa({node:ia.create(parseCommonTableExpressionName(t),e)})}function parseCommonTableExpressionName(e){if(e.includes(`(`)){let t=e.split(/[\(\)]/),n=t[0],r=t[1].split(`,`).map(e=>e.trim());return ra.create(n,r)}return ra.create(e)}const oa=freeze({is(e){return e.kind===`WithNode`},create(e,t){return freeze({kind:`WithNode`,expressions:freeze([e]),...t})},cloneWithExpression(e,t){return freeze({...e,expressions:freeze([...e.expressions,t])})}}),sa=/* @__PURE__ */ `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.split(``);function randomString(e){let t=``;for(let n=0;n<e;++n)t+=randomChar();return t}function randomChar(){return sa[~~(Math.random()*sa.length)]}function createQueryId(){return new LazyQueryId}var LazyQueryId=class{#e;get queryId(){return this.#e===void 0&&(this.#e=randomString(8)),this.#e}},OperationNodeTransformer=class{nodeStack=[];#e=freeze({AliasNode:this.transformAlias.bind(this),ColumnNode:this.transformColumn.bind(this),IdentifierNode:this.transformIdentifier.bind(this),SchemableIdentifierNode:this.transformSchemableIdentifier.bind(this),RawNode:this.transformRaw.bind(this),ReferenceNode:this.transformReference.bind(this),SelectQueryNode:this.transformSelectQuery.bind(this),SelectionNode:this.transformSelection.bind(this),TableNode:this.transformTable.bind(this),FromNode:this.transformFrom.bind(this),SelectAllNode:this.transformSelectAll.bind(this),AndNode:this.transformAnd.bind(this),OrNode:this.transformOr.bind(this),ValueNode:this.transformValue.bind(this),ValueListNode:this.transformValueList.bind(this),PrimitiveValueListNode:this.transformPrimitiveValueList.bind(this),ParensNode:this.transformParens.bind(this),JoinNode:this.transformJoin.bind(this),OperatorNode:this.transformOperator.bind(this),WhereNode:this.transformWhere.bind(this),InsertQueryNode:this.transformInsertQuery.bind(this),DeleteQueryNode:this.transformDeleteQuery.bind(this),ReturningNode:this.transformReturning.bind(this),CreateTableNode:this.transformCreateTable.bind(this),AddColumnNode:this.transformAddColumn.bind(this),ColumnDefinitionNode:this.transformColumnDefinition.bind(this),DropTableNode:this.transformDropTable.bind(this),DataTypeNode:this.transformDataType.bind(this),OrderByNode:this.transformOrderBy.bind(this),OrderByItemNode:this.transformOrderByItem.bind(this),GroupByNode:this.transformGroupBy.bind(this),GroupByItemNode:this.transformGroupByItem.bind(this),UpdateQueryNode:this.transformUpdateQuery.bind(this),ColumnUpdateNode:this.transformColumnUpdate.bind(this),LimitNode:this.transformLimit.bind(this),OffsetNode:this.transformOffset.bind(this),OnConflictNode:this.transformOnConflict.bind(this),OnDuplicateKeyNode:this.transformOnDuplicateKey.bind(this),CreateIndexNode:this.transformCreateIndex.bind(this),DropIndexNode:this.transformDropIndex.bind(this),ListNode:this.transformList.bind(this),PrimaryKeyConstraintNode:this.transformPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.transformUniqueConstraint.bind(this),ReferencesNode:this.transformReferences.bind(this),CheckConstraintNode:this.transformCheckConstraint.bind(this),WithNode:this.transformWith.bind(this),CommonTableExpressionNode:this.transformCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.transformCommonTableExpressionName.bind(this),HavingNode:this.transformHaving.bind(this),CreateSchemaNode:this.transformCreateSchema.bind(this),DropSchemaNode:this.transformDropSchema.bind(this),AlterTableNode:this.transformAlterTable.bind(this),DropColumnNode:this.transformDropColumn.bind(this),RenameColumnNode:this.transformRenameColumn.bind(this),AlterColumnNode:this.transformAlterColumn.bind(this),ModifyColumnNode:this.transformModifyColumn.bind(this),AddConstraintNode:this.transformAddConstraint.bind(this),DropConstraintNode:this.transformDropConstraint.bind(this),RenameConstraintNode:this.transformRenameConstraint.bind(this),ForeignKeyConstraintNode:this.transformForeignKeyConstraint.bind(this),CreateViewNode:this.transformCreateView.bind(this),RefreshMaterializedViewNode:this.transformRefreshMaterializedView.bind(this),DropViewNode:this.transformDropView.bind(this),GeneratedNode:this.transformGenerated.bind(this),DefaultValueNode:this.transformDefaultValue.bind(this),OnNode:this.transformOn.bind(this),ValuesNode:this.transformValues.bind(this),SelectModifierNode:this.transformSelectModifier.bind(this),CreateTypeNode:this.transformCreateType.bind(this),DropTypeNode:this.transformDropType.bind(this),ExplainNode:this.transformExplain.bind(this),DefaultInsertValueNode:this.transformDefaultInsertValue.bind(this),AggregateFunctionNode:this.transformAggregateFunction.bind(this),OverNode:this.transformOver.bind(this),PartitionByNode:this.transformPartitionBy.bind(this),PartitionByItemNode:this.transformPartitionByItem.bind(this),SetOperationNode:this.transformSetOperation.bind(this),BinaryOperationNode:this.transformBinaryOperation.bind(this),UnaryOperationNode:this.transformUnaryOperation.bind(this),UsingNode:this.transformUsing.bind(this),FunctionNode:this.transformFunction.bind(this),CaseNode:this.transformCase.bind(this),WhenNode:this.transformWhen.bind(this),JSONReferenceNode:this.transformJSONReference.bind(this),JSONPathNode:this.transformJSONPath.bind(this),JSONPathLegNode:this.transformJSONPathLeg.bind(this),JSONOperatorChainNode:this.transformJSONOperatorChain.bind(this),TupleNode:this.transformTuple.bind(this),MergeQueryNode:this.transformMergeQuery.bind(this),MatchedNode:this.transformMatched.bind(this),AddIndexNode:this.transformAddIndex.bind(this),CastNode:this.transformCast.bind(this),FetchNode:this.transformFetch.bind(this),TopNode:this.transformTop.bind(this),OutputNode:this.transformOutput.bind(this),OrActionNode:this.transformOrAction.bind(this),CollateNode:this.transformCollate.bind(this),AlterTypeNode:this.transformAlterType.bind(this),AddValueNode:this.transformAddValue.bind(this),RenameValueNode:this.transformRenameValue.bind(this)});transformNode(e,t){if(!e)return e;this.nodeStack.push(e);let n=this.transformNodeImpl(e,t);return this.nodeStack.pop(),freeze(n)}transformNodeImpl(e,t){return this.#e[e.kind](e,t)}transformNodeList(e,t){return e&&freeze(e.map(e=>this.transformNode(e,t)))}transformSelectQuery(e,t){return{kind:`SelectQueryNode`,from:this.transformNode(e.from,t),selections:this.transformNodeList(e.selections,t),distinctOn:this.transformNodeList(e.distinctOn,t),joins:this.transformNodeList(e.joins,t),groupBy:this.transformNode(e.groupBy,t),orderBy:this.transformNode(e.orderBy,t),where:this.transformNode(e.where,t),frontModifiers:this.transformNodeList(e.frontModifiers,t),endModifiers:this.transformNodeList(e.endModifiers,t),limit:this.transformNode(e.limit,t),offset:this.transformNode(e.offset,t),with:this.transformNode(e.with,t),having:this.transformNode(e.having,t),explain:this.transformNode(e.explain,t),setOperations:this.transformNodeList(e.setOperations,t),fetch:this.transformNode(e.fetch,t),top:this.transformNode(e.top,t)}}transformSelection(e,t){return{kind:`SelectionNode`,selection:this.transformNode(e.selection,t)}}transformColumn(e,t){return{kind:`ColumnNode`,column:this.transformNode(e.column,t)}}transformAlias(e,t){return{kind:`AliasNode`,node:this.transformNode(e.node,t),alias:this.transformNode(e.alias,t)}}transformTable(e,t){return{kind:`TableNode`,table:this.transformNode(e.table,t)}}transformFrom(e,t){return{kind:`FromNode`,froms:this.transformNodeList(e.froms,t)}}transformReference(e,t){return{kind:`ReferenceNode`,column:this.transformNode(e.column,t),table:this.transformNode(e.table,t)}}transformAnd(e,t){return{kind:`AndNode`,left:this.transformNode(e.left,t),right:this.transformNode(e.right,t)}}transformOr(e,t){return{kind:`OrNode`,left:this.transformNode(e.left,t),right:this.transformNode(e.right,t)}}transformValueList(e,t){return{kind:`ValueListNode`,values:this.transformNodeList(e.values,t)}}transformParens(e,t){return{kind:`ParensNode`,node:this.transformNode(e.node,t)}}transformJoin(e,t){return{kind:`JoinNode`,joinType:e.joinType,table:this.transformNode(e.table,t),on:this.transformNode(e.on,t)}}transformRaw(e,t){return{kind:`RawNode`,sqlFragments:freeze([...e.sqlFragments]),parameters:this.transformNodeList(e.parameters,t)}}transformWhere(e,t){return{kind:`WhereNode`,where:this.transformNode(e.where,t)}}transformInsertQuery(e,t){return{kind:`InsertQueryNode`,into:this.transformNode(e.into,t),columns:this.transformNodeList(e.columns,t),values:this.transformNode(e.values,t),returning:this.transformNode(e.returning,t),onConflict:this.transformNode(e.onConflict,t),onDuplicateKey:this.transformNode(e.onDuplicateKey,t),endModifiers:this.transformNodeList(e.endModifiers,t),with:this.transformNode(e.with,t),orAction:this.transformNode(e.orAction,t),replace:e.replace,explain:this.transformNode(e.explain,t),defaultValues:e.defaultValues,top:this.transformNode(e.top,t),output:this.transformNode(e.output,t)}}transformValues(e,t){return{kind:`ValuesNode`,values:this.transformNodeList(e.values,t)}}transformDeleteQuery(e,t){return{kind:`DeleteQueryNode`,from:this.transformNode(e.from,t),using:this.transformNode(e.using,t),joins:this.transformNodeList(e.joins,t),where:this.transformNode(e.where,t),returning:this.transformNode(e.returning,t),endModifiers:this.transformNodeList(e.endModifiers,t),with:this.transformNode(e.with,t),orderBy:this.transformNode(e.orderBy,t),limit:this.transformNode(e.limit,t),explain:this.transformNode(e.explain,t),top:this.transformNode(e.top,t),output:this.transformNode(e.output,t)}}transformReturning(e,t){return{kind:`ReturningNode`,selections:this.transformNodeList(e.selections,t)}}transformCreateTable(e,t){return{kind:`CreateTableNode`,table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t),constraints:this.transformNodeList(e.constraints,t),indexes:this.transformNodeList(e.indexes,t),temporary:e.temporary,ifNotExists:e.ifNotExists,onCommit:e.onCommit,frontModifiers:this.transformNodeList(e.frontModifiers,t),endModifiers:this.transformNodeList(e.endModifiers,t),selectQuery:this.transformNode(e.selectQuery,t)}}transformColumnDefinition(e,t){return{kind:`ColumnDefinitionNode`,column:this.transformNode(e.column,t),dataType:this.transformNode(e.dataType,t),references:this.transformNode(e.references,t),primaryKey:e.primaryKey,autoIncrement:e.autoIncrement,unique:e.unique,notNull:e.notNull,unsigned:e.unsigned,defaultTo:this.transformNode(e.defaultTo,t),check:this.transformNode(e.check,t),generated:this.transformNode(e.generated,t),frontModifiers:this.transformNodeList(e.frontModifiers,t),endModifiers:this.transformNodeList(e.endModifiers,t),nullsNotDistinct:e.nullsNotDistinct,identity:e.identity,ifNotExists:e.ifNotExists}}transformAddColumn(e,t){return{kind:`AddColumnNode`,column:this.transformNode(e.column,t)}}transformDropTable(e,t){return{kind:`DropTableNode`,table:this.transformNode(e.table,t),ifExists:e.ifExists,cascade:e.cascade,temporary:e.temporary}}transformOrderBy(e,t){return{kind:`OrderByNode`,items:this.transformNodeList(e.items,t)}}transformOrderByItem(e,t){return{kind:`OrderByItemNode`,orderBy:this.transformNode(e.orderBy,t),direction:this.transformNode(e.direction,t),collation:this.transformNode(e.collation,t),nulls:e.nulls}}transformGroupBy(e,t){return{kind:`GroupByNode`,items:this.transformNodeList(e.items,t)}}transformGroupByItem(e,t){return{kind:`GroupByItemNode`,groupBy:this.transformNode(e.groupBy,t)}}transformUpdateQuery(e,t){return{kind:`UpdateQueryNode`,table:this.transformNode(e.table,t),from:this.transformNode(e.from,t),joins:this.transformNodeList(e.joins,t),where:this.transformNode(e.where,t),updates:this.transformNodeList(e.updates,t),returning:this.transformNode(e.returning,t),endModifiers:this.transformNodeList(e.endModifiers,t),with:this.transformNode(e.with,t),explain:this.transformNode(e.explain,t),limit:this.transformNode(e.limit,t),top:this.transformNode(e.top,t),output:this.transformNode(e.output,t),orderBy:this.transformNode(e.orderBy,t)}}transformColumnUpdate(e,t){return{kind:`ColumnUpdateNode`,column:this.transformNode(e.column,t),value:this.transformNode(e.value,t)}}transformLimit(e,t){return{kind:`LimitNode`,limit:this.transformNode(e.limit,t)}}transformOffset(e,t){return{kind:`OffsetNode`,offset:this.transformNode(e.offset,t)}}transformOnConflict(e,t){return{kind:`OnConflictNode`,columns:this.transformNodeList(e.columns,t),constraint:this.transformNode(e.constraint,t),indexExpression:this.transformNode(e.indexExpression,t),indexWhere:this.transformNode(e.indexWhere,t),updates:this.transformNodeList(e.updates,t),updateWhere:this.transformNode(e.updateWhere,t),doNothing:e.doNothing}}transformOnDuplicateKey(e,t){return{kind:`OnDuplicateKeyNode`,updates:this.transformNodeList(e.updates,t)}}transformCreateIndex(e,t){return{kind:`CreateIndexNode`,name:this.transformNode(e.name,t),table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t),unique:e.unique,using:this.transformNode(e.using,t),ifNotExists:e.ifNotExists,where:this.transformNode(e.where,t),nullsNotDistinct:e.nullsNotDistinct}}transformList(e,t){return{kind:`ListNode`,items:this.transformNodeList(e.items,t)}}transformDropIndex(e,t){return{kind:`DropIndexNode`,name:this.transformNode(e.name,t),table:this.transformNode(e.table,t),ifExists:e.ifExists,cascade:e.cascade}}transformPrimaryKeyConstraint(e,t){return{kind:`PrimaryKeyConstraintNode`,columns:this.transformNodeList(e.columns,t),name:this.transformNode(e.name,t),deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformUniqueConstraint(e,t){return{kind:`UniqueConstraintNode`,columns:this.transformNodeList(e.columns,t),name:this.transformNode(e.name,t),nullsNotDistinct:e.nullsNotDistinct,deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformForeignKeyConstraint(e,t){return{kind:`ForeignKeyConstraintNode`,columns:this.transformNodeList(e.columns,t),references:this.transformNode(e.references,t),name:this.transformNode(e.name,t),onDelete:e.onDelete,onUpdate:e.onUpdate,deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformSetOperation(e,t){return{kind:`SetOperationNode`,operator:e.operator,expression:this.transformNode(e.expression,t),all:e.all}}transformReferences(e,t){return{kind:`ReferencesNode`,table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t),onDelete:e.onDelete,onUpdate:e.onUpdate}}transformCheckConstraint(e,t){return{kind:`CheckConstraintNode`,expression:this.transformNode(e.expression,t),name:this.transformNode(e.name,t)}}transformWith(e,t){return{kind:`WithNode`,expressions:this.transformNodeList(e.expressions,t),recursive:e.recursive}}transformCommonTableExpression(e,t){return{kind:`CommonTableExpressionNode`,name:this.transformNode(e.name,t),materialized:e.materialized,expression:this.transformNode(e.expression,t)}}transformCommonTableExpressionName(e,t){return{kind:`CommonTableExpressionNameNode`,table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t)}}transformHaving(e,t){return{kind:`HavingNode`,having:this.transformNode(e.having,t)}}transformCreateSchema(e,t){return{kind:`CreateSchemaNode`,schema:this.transformNode(e.schema,t),ifNotExists:e.ifNotExists}}transformDropSchema(e,t){return{kind:`DropSchemaNode`,schema:this.transformNode(e.schema,t),ifExists:e.ifExists,cascade:e.cascade}}transformAlterTable(e,t){return{kind:`AlterTableNode`,table:this.transformNode(e.table,t),renameTo:this.transformNode(e.renameTo,t),setSchema:this.transformNode(e.setSchema,t),columnAlterations:this.transformNodeList(e.columnAlterations,t),addConstraint:this.transformNode(e.addConstraint,t),dropConstraint:this.transformNode(e.dropConstraint,t),renameConstraint:this.transformNode(e.renameConstraint,t),addIndex:this.transformNode(e.addIndex,t),dropIndex:this.transformNode(e.dropIndex,t)}}transformDropColumn(e,t){return{kind:`DropColumnNode`,column:this.transformNode(e.column,t),ifExists:e.ifExists}}transformRenameColumn(e,t){return{kind:`RenameColumnNode`,column:this.transformNode(e.column,t),renameTo:this.transformNode(e.renameTo,t)}}transformAlterColumn(e,t){return{kind:`AlterColumnNode`,column:this.transformNode(e.column,t),dataType:this.transformNode(e.dataType,t),dataTypeExpression:this.transformNode(e.dataTypeExpression,t),setDefault:this.transformNode(e.setDefault,t),dropDefault:e.dropDefault,setNotNull:e.setNotNull,dropNotNull:e.dropNotNull}}transformModifyColumn(e,t){return{kind:`ModifyColumnNode`,column:this.transformNode(e.column,t)}}transformAddConstraint(e,t){return{kind:`AddConstraintNode`,constraint:this.transformNode(e.constraint,t)}}transformDropConstraint(e,t){return{kind:`DropConstraintNode`,constraintName:this.transformNode(e.constraintName,t),ifExists:e.ifExists,modifier:e.modifier}}transformRenameConstraint(e,t){return{kind:`RenameConstraintNode`,oldName:this.transformNode(e.oldName,t),newName:this.transformNode(e.newName,t)}}transformCreateView(e,t){return{kind:`CreateViewNode`,name:this.transformNode(e.name,t),temporary:e.temporary,orReplace:e.orReplace,ifNotExists:e.ifNotExists,materialized:e.materialized,columns:this.transformNodeList(e.columns,t),as:this.transformNode(e.as,t)}}transformRefreshMaterializedView(e,t){return{kind:`RefreshMaterializedViewNode`,name:this.transformNode(e.name,t),concurrently:e.concurrently,withNoData:e.withNoData}}transformDropView(e,t){return{kind:`DropViewNode`,name:this.transformNode(e.name,t),ifExists:e.ifExists,materialized:e.materialized,cascade:e.cascade}}transformGenerated(e,t){return{kind:`GeneratedNode`,byDefault:e.byDefault,always:e.always,identity:e.identity,stored:e.stored,expression:this.transformNode(e.expression,t)}}transformDefaultValue(e,t){return{kind:`DefaultValueNode`,defaultValue:this.transformNode(e.defaultValue,t)}}transformOn(e,t){return{kind:`OnNode`,on:this.transformNode(e.on,t)}}transformSelectModifier(e,t){return{kind:`SelectModifierNode`,modifier:e.modifier,rawModifier:this.transformNode(e.rawModifier,t),of:this.transformNodeList(e.of,t)}}transformCreateType(e,t){return{kind:`CreateTypeNode`,name:this.transformNode(e.name,t),enum:this.transformNode(e.enum,t)}}transformDropType(e,t){return{kind:`DropTypeNode`,name:this.transformNode(e.name,t),additionalNames:this.transformNodeList(e.additionalNames,t),cascade:e.cascade,ifExists:e.ifExists}}transformExplain(e,t){return{kind:`ExplainNode`,format:e.format,options:this.transformNode(e.options,t)}}transformSchemableIdentifier(e,t){return{kind:`SchemableIdentifierNode`,schema:this.transformNode(e.schema,t),identifier:this.transformNode(e.identifier,t)}}transformAggregateFunction(e,t){return{kind:`AggregateFunctionNode`,func:e.func,aggregated:this.transformNodeList(e.aggregated,t),distinct:e.distinct,orderBy:this.transformNode(e.orderBy,t),withinGroup:this.transformNode(e.withinGroup,t),filter:this.transformNode(e.filter,t),over:this.transformNode(e.over,t)}}transformOver(e,t){return{kind:`OverNode`,orderBy:this.transformNode(e.orderBy,t),partitionBy:this.transformNode(e.partitionBy,t)}}transformPartitionBy(e,t){return{kind:`PartitionByNode`,items:this.transformNodeList(e.items,t)}}transformPartitionByItem(e,t){return{kind:`PartitionByItemNode`,partitionBy:this.transformNode(e.partitionBy,t)}}transformBinaryOperation(e,t){return{kind:`BinaryOperationNode`,leftOperand:this.transformNode(e.leftOperand,t),operator:this.transformNode(e.operator,t),rightOperand:this.transformNode(e.rightOperand,t)}}transformUnaryOperation(e,t){return{kind:`UnaryOperationNode`,operator:this.transformNode(e.operator,t),operand:this.transformNode(e.operand,t)}}transformUsing(e,t){return{kind:`UsingNode`,tables:this.transformNodeList(e.tables,t)}}transformFunction(e,t){return{kind:`FunctionNode`,func:e.func,arguments:this.transformNodeList(e.arguments,t)}}transformCase(e,t){return{kind:`CaseNode`,value:this.transformNode(e.value,t),when:this.transformNodeList(e.when,t),else:this.transformNode(e.else,t),isStatement:e.isStatement}}transformWhen(e,t){return{kind:`WhenNode`,condition:this.transformNode(e.condition,t),result:this.transformNode(e.result,t)}}transformJSONReference(e,t){return{kind:`JSONReferenceNode`,reference:this.transformNode(e.reference,t),traversal:this.transformNode(e.traversal,t)}}transformJSONPath(e,t){return{kind:`JSONPathNode`,inOperator:this.transformNode(e.inOperator,t),pathLegs:this.transformNodeList(e.pathLegs,t)}}transformJSONPathLeg(e,t){return{kind:`JSONPathLegNode`,type:e.type,value:e.value}}transformJSONOperatorChain(e,t){return{kind:`JSONOperatorChainNode`,operator:this.transformNode(e.operator,t),values:this.transformNodeList(e.values,t)}}transformTuple(e,t){return{kind:`TupleNode`,values:this.transformNodeList(e.values,t)}}transformMergeQuery(e,t){return{kind:`MergeQueryNode`,into:this.transformNode(e.into,t),using:this.transformNode(e.using,t),whens:this.transformNodeList(e.whens,t),with:this.transformNode(e.with,t),top:this.transformNode(e.top,t),endModifiers:this.transformNodeList(e.endModifiers,t),output:this.transformNode(e.output,t),returning:this.transformNode(e.returning,t)}}transformMatched(e,t){return{kind:`MatchedNode`,not:e.not,bySource:e.bySource}}transformAddIndex(e,t){return{kind:`AddIndexNode`,name:this.transformNode(e.name,t),columns:this.transformNodeList(e.columns,t),unique:e.unique,using:this.transformNode(e.using,t),ifNotExists:e.ifNotExists}}transformCast(e,t){return{kind:`CastNode`,expression:this.transformNode(e.expression,t),dataType:this.transformNode(e.dataType,t)}}transformFetch(e,t){return{kind:`FetchNode`,rowCount:this.transformNode(e.rowCount,t),modifier:e.modifier}}transformTop(e,t){return{kind:`TopNode`,expression:e.expression,modifiers:e.modifiers}}transformOutput(e,t){return{kind:`OutputNode`,selections:this.transformNodeList(e.selections,t)}}transformAlterType(e,t){return{kind:`AlterTypeNode`,name:this.transformNode(e.name,t),addValue:this.transformNode(e.addValue,t),renameTo:this.transformNode(e.renameTo,t),renameValue:this.transformNode(e.renameValue,t),setSchema:this.transformNode(e.setSchema,t)}}transformAddValue(e,t){return{kind:`AddValueNode`,value:this.transformNode(e.value,t),ifNotExists:e.ifNotExists,isBefore:e.isBefore,neighborValue:this.transformNode(e.neighborValue,t)}}transformRenameValue(e,t){return{kind:`RenameValueNode`,oldValue:this.transformNode(e.oldValue,t),newValue:this.transformNode(e.newValue,t)}}transformDataType(e,t){return e}transformSelectAll(e,t){return e}transformIdentifier(e,t){return e}transformValue(e,t){return e}transformPrimitiveValueList(e,t){return e}transformOperator(e,t){return e}transformDefaultInsertValue(e,t){return e}transformOrAction(e,t){return e}transformCollate(e,t){return e}};function isOperationNode(e){return isObject$1(e)&&isString(e.kind)}const ca={AlterTableNode:!0,AlterTypeNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,RefreshMaterializedViewNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0};function isRootOperationNode(e){return isOperationNode(e)&&ca[e.kind]===!0}const la=freeze({json_agg:!0,to_json:!0});var WithSchemaTransformer=class extends OperationNodeTransformer{#e;#t=/* @__PURE__ */ new Set;#n=/* @__PURE__ */ new Set;constructor(e){super(),this.#e=e}transformNodeImpl(e,t){if(!isRootOperationNode(e))return super.transformNodeImpl(e,t);let n=this.#a(e);for(let e of n)this.#n.add(e);let r=this.#i(e);for(let e of r)this.#t.add(e);let i=super.transformNodeImpl(e,t);for(let e of r)this.#t.delete(e);for(let e of n)this.#n.delete(e);return i}transformSchemableIdentifier(e,t){let n=super.transformSchemableIdentifier(e,t);return n.schema||!this.#t.has(e.identifier.name)?n:{...n,schema:w.create(this.#e)}}transformReferences(e,t){let n=super.transformReferences(e,t);return n.table.table.schema?n:{...n,table:$r.createWithSchema(this.#e,n.table.table.identifier.name)}}transformAggregateFunction(e,t){return{...super.transformAggregateFunction({...e,aggregated:[]},t),aggregated:this.#r(e,t,`aggregated`)}}transformFunction(e,t){return{...super.transformFunction({...e,arguments:[]},t),arguments:this.#r(e,t,`arguments`)}}transformSelectModifier(e,t){return{...super.transformSelectModifier({...e,of:void 0},t),of:e.of?.map(e=>$r.is(e)&&!e.table.schema?{...e,table:this.transformIdentifier(e.table.identifier,t)}:this.transformNode(e,t))}}#r(e,t,n){return la[e.func]?e[n].map(e=>!$r.is(e)||e.table.schema?this.transformNode(e,t):{...e,table:this.transformIdentifier(e.table.identifier,t)}):this.transformNodeList(e[n],t)}#i(e){let t=/* @__PURE__ */ new Set;if(`name`in e&&e.name&&Jr.is(e.name)&&this.#s(e.name,t),`from`in e&&e.from)for(let n of e.from.froms)this.#o(n,t);if(`into`in e&&e.into&&this.#o(e.into,t),`table`in e&&e.table&&this.#o(e.table,t),`joins`in e&&e.joins)for(let n of e.joins)this.#o(n.table,t);return`using`in e&&e.using&&(ii.is(e.using)?this.#o(e.using.table,t):this.#o(e.using,t)),t}#a(e){let t=/* @__PURE__ */ new Set;return`with`in e&&e.with&&this.#c(e.with,t),t}#o(e,t){if($r.is(e))return this.#s(e.table,t);if(Qr.is(e)&&$r.is(e.node))return this.#s(e.node.table,t);if(Pi.is(e))for(let n of e.items)this.#o(n,t);else if(Ii.is(e))for(let n of e.tables)this.#o(n,t)}#s(e,t){let n=e.identifier.name;!this.#t.has(n)&&!this.#n.has(n)&&t.add(n)}#c(e,t){for(let n of e.expressions){let e=n.name.table.table.identifier.name;this.#n.has(e)||t.add(e)}}},WithSchemaPlugin=class{#e;constructor(e){this.#e=new WithSchemaTransformer(e)}transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}async transformResult(e){return e.result}};const ua=freeze({is(e){return e.kind===`MatchedNode`},create(e,t=!1){return freeze({kind:`MatchedNode`,not:e,bySource:t})}});function parseMergeWhen(e,t,n){return Bi.create(parseFilterList([ua.create(!e.isMatched,e.bySource),...t&&t.length>0?[t.length===3&&n?parseReferentialBinaryOperation(t[0],t[1],t[2]):parseValueBinaryOperationOrExpression(t)]:[]],`and`,!1))}function parseMergeThen(e){return isString(e)?D.create([e],[]):isOperationNodeSource(e)?e.toOperationNode():e}var Deferred=class{#e;#t;#n;constructor(){this.#e=new Promise((e,t)=>{this.#n=t,this.#t=e})}get promise(){return this.#e}resolve=e=>{this.#t?.(e),this.#t=this.#n=void 0};reject=e=>{this.#n?.(e),this.#n=this.#t=void 0}};async function provideControlledConnection(e,t){let n=new Deferred,r=new Deferred;return e.provideConnection(async e=>(n.resolve(e),await r.promise),t).catch(e=>n.reject(e)),freeze({connection:await n.promise,release:r.resolve})}function getInflightQueryAbortHandler(e=`ignore query`,t,n){if(e!==`ignore query`){if(e===`cancel query`){let r=t.cancelQuery;return r||(n(),throwUnsupportedInflightQueryAbortStrategyError(e,t.killSession?`kill session`:void 0)),r.bind(t)}if(e===`kill session`){let r=t.killSession;return r||(n(),throwUnsupportedInflightQueryAbortStrategyError(e,t.cancelQuery?`cancel query`:void 0)),r.bind(t)}throw n(),Error(`Unexpected \`inflightQueryAbortStrategy\`: "${e}"`)}}function throwUnsupportedInflightQueryAbortStrategyError(e,t){throw Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${e}". Use "ignore query"${t?` or "${t}"`:``} instead.`)}function assertNotAborted(e,t,n){e?.aborted&&(n?.(),throwReasonWithTiming(e.reason,t))}function throwReasonWithTiming(e,t){throw decorateWithTiming(e,t),e}const I={};async function waitOrAbort(e,t,n,r){if(!t)return e;assertNotAborted(t,`before ${n}`,r);let{promise:i,resolve:a}=new Deferred,abortListener=()=>a(I);t.addEventListener(`abort`,abortListener);try{assertNotAborted(t,`before ${n}`,r);let a=await Promise.race([e,i]);if(a!==I)return a;r?.(),throwReasonWithTiming(t.reason,`during ${n}`)}finally{t.removeEventListener(`abort`,abortListener),a(I)}}function printBackgroundFail(e){return t=>console.error(`\`${e}\` failed in the background after abortion: ${getMessage(t)}`)}function decorateWithTiming(e,t){typeof e==`object`&&e&&!Object.isFrozen(e)&&Object.defineProperty(e,"__kysely_timing__",{configurable:!0,enumerable:!1,value:t,writable:!1})}const da=freeze([]);var QueryExecutorBase=class{#e;constructor(e=da){this.#e=e}get plugins(){return this.#e}transformQuery(e,t){for(let n of this.#e){let r=n.transformQuery({node:e,queryId:t});if(r.kind===e.kind)e=r;else throw Error([`KyselyPlugin.transformQuery must return a node`,`of the same kind that was given to it.`,`The plugin was given a ${e.kind}`,`but it returned a ${r.kind}`].join(` `))}return e}async executeQuery(e,t){let{inflightQueryAbortStrategy:n=`ignore query`,signal:r}=t||{};if(!r){let n=await this.provideConnection(async t=>await t.executeQuery(e),t);return await this.#t(n,e.queryId)}assertNotAborted(r,`before query execution`),t=freeze({signal:r});let{connection:i,release:a}=await provideControlledConnection(this,t),o=this.provideConnection.bind(this),{promise:s,resolve:c}=new Deferred,abortListener=()=>c(I);r.addEventListener(`abort`,abortListener,{once:!0});try{assertNotAborted(r,`before query execution`,a);let c=getInflightQueryAbortHandler(n,i,a);if(c&&i.collectSessionInfo){assertNotAborted(r,`before query execution`,a);let e=i.collectSessionInfo();await Promise.race([s,e]).catch(e=>{throw a(),e})===I&&(e.catch(printBackgroundFail(`collectSessionInfo`)).finally(a),throwReasonWithTiming(r.reason,`before query execution`))}let l=i.executeQuery(e,t),u=await Promise.race([s,l]).catch(e=>{throw a(),e});u===I?(Promise.allSettled([l.catch(printBackgroundFail(`query`)),c?.(o).catch(printBackgroundFail(`inflightQueryAbortHandler`))]).finally(a),throwReasonWithTiming(r.reason,`during query execution`)):a();let d=this.#t(u,e.queryId,t),f=await Promise.race([s,d]);return f===I&&(d.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),f}finally{c(I),r.removeEventListener(`abort`,abortListener)}}async*stream(e,t,n){let{signal:r}=n||{};if(!r){let{connection:r,release:i}=await provideControlledConnection(this);try{for await(let i of r.streamQuery(e,t))yield await this.#t(i,e.queryId,n)}finally{i()}return}n=freeze({signal:r}),assertNotAborted(r,`before connection acquisition`);let{connection:i,release:a}=await provideControlledConnection(this,n),{promise:o,resolve:s}=new Deferred,abortListener=()=>s(I);r.addEventListener(`abort`,abortListener,{once:!0});let c,l;assertNotAborted(r,`before query streaming`,a);let{queryId:u}=e;try{for(c=i.streamQuery(e,t,n);;){assertNotAborted(r,`during query streaming`);let e=c.next(),t=await Promise.race([o,e]);if(t===I&&(l=e.catch(printBackgroundFail(`iterator.next`)),throwReasonWithTiming(r.reason,`during query streaming`)),t.done)break;let i=this.#t(t.value,u,n),a=await Promise.race([o,i]);a===I&&(l=i.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),yield a}}finally{s(I),r.removeEventListener(`abort`,abortListener);let e=(c?.return?.()||Promise.resolve()).finally(()=>l).finally(a);l||await e}}async#t(e,t,n){let{signal:r}=n||{};for(let n of this.#e)e=await n.transformResult(freeze({queryId:t,result:e,signal:r}));return e}};const fa=new class NoopQueryExecutor extends QueryExecutorBase{get adapter(){throw Error(`this query cannot be compiled to SQL`)}compileQuery(){throw Error(`this query cannot be compiled to SQL`)}provideConnection(){throw Error(`this query cannot be executed`)}withConnectionProvider(){throw Error(`this query cannot have a connection provider`)}withPlugin(e){return new NoopQueryExecutor([...this.plugins,e])}withPlugins(e){return new NoopQueryExecutor([...this.plugins,...e])}withPluginAtFront(e){return new NoopQueryExecutor([e,...this.plugins])}withoutPlugins(){return new NoopQueryExecutor([])}};var MergeResult=class{numChangedRows;constructor(e){this.numChangedRows=e}},pa=class MergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new MergeQueryBuilder({...this.#e,queryNode:j.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new MergeQueryBuilder({...this.#e,queryNode:j.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(...e){return new ma({...this.#e,queryNode:Vi.cloneWithUsing(this.#e.queryNode,parseJoin(`Using`,e))})}returning(e){return new MergeQueryBuilder({...this.#e,queryNode:j.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new MergeQueryBuilder({...this.#e,queryNode:j.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new MergeQueryBuilder({...this.#e,queryNode:j.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new MergeQueryBuilder({...this.#e,queryNode:j.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}},ma=class WheneableMergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:j.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new WheneableMergeQueryBuilder({...this.#e,queryNode:j.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}whenMatched(){return this.#t([])}whenMatchedAnd(...e){return this.#t(e)}whenMatchedAndRef(e,t,n){return this.#t([e,t,n],!0)}#t(e,t){return new MatchedThenableMergeQueryBuilder({...this.#e,queryNode:Vi.cloneWithWhen(this.#e.queryNode,parseMergeWhen({isMatched:!0},e,t))})}whenNotMatched(){return this.#n([])}whenNotMatchedAnd(...e){return this.#n(e)}whenNotMatchedAndRef(e,t,n){return this.#n([e,t,n],!0)}whenNotMatchedBySource(){return this.#n([],!1,!0)}whenNotMatchedBySourceAnd(...e){return this.#n(e,!1,!0)}whenNotMatchedBySourceAndRef(e,t,n){return this.#n([e,t,n],!0,!0)}returning(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:j.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:j.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:j.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:j.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}#n(e,t=!1,n=!1){let r={...this.#e,queryNode:Vi.cloneWithWhen(this.#e.queryNode,parseMergeWhen({isMatched:!1,bySource:n},e,t))};return new(n?MatchedThenableMergeQueryBuilder:NotMatchedThenableMergeQueryBuilder)(r)}$call(e){return e(this)}$if(e,t){return e?t(this):new WheneableMergeQueryBuilder({...this.#e})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new MergeResult(n.numAffectedRows)]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}},MatchedThenableMergeQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}thenDelete(){return new ma({...this.#e,queryNode:Vi.cloneWithThen(this.#e.queryNode,parseMergeThen(`delete`))})}thenDoNothing(){return new ma({...this.#e,queryNode:Vi.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenUpdate(e){return new ma({...this.#e,queryNode:Vi.cloneWithThen(this.#e.queryNode,parseMergeThen(e(new UpdateQueryBuilder({queryId:this.#e.queryId,executor:fa,queryNode:Fi.createWithoutTable()}))))})}thenUpdateSet(...e){return this.thenUpdate(t=>t.set(...e))}},NotMatchedThenableMergeQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}thenDoNothing(){return new ma({...this.#e,queryNode:Vi.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenInsertValues(e){let[t,n]=parseInsertExpression(e);return new ma({...this.#e,queryNode:Vi.cloneWithThen(this.#e.queryNode,parseMergeThen(k.cloneWith(k.createWithoutInto(),{columns:t,values:n})))})}},ha=class QueryCreator{#e;constructor(e){this.#e=freeze(e)}selectFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:M.createFrom(parseTableExpressionOrList(e),this.#e.withNode)})}selectNoFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:M.cloneWithSelections(M.create(this.#e.withNode),parseSelectArg(e))})}insertInto(e){return new ta({queryId:createQueryId(),executor:this.#e.executor,queryNode:k.create(parseTable(e),this.#e.withNode)})}replaceInto(e){return new ta({queryId:createQueryId(),executor:this.#e.executor,queryNode:k.create(parseTable(e),this.#e.withNode,!0)})}deleteFrom(e){return new DeleteQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:Li.create(parseTableExpressionOrList(e),this.#e.withNode)})}updateTable(e){return new UpdateQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:Fi.create(parseTableExpressionOrList(e),this.#e.withNode)})}mergeInto(e){return new pa({queryId:createQueryId(),executor:this.#e.executor,queryNode:Vi.create(parseAliasedTable(e),this.#e.withNode)})}with(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?oa.cloneWithExpression(this.#e.withNode,n):oa.create(n)})}withRecursive(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?oa.cloneWithExpression(this.#e.withNode,n):oa.create(n,{recursive:!0})})}withPlugin(e){return new QueryCreator({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new QueryCreator({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new QueryCreator({...this.#e,executor:this.#e.executor.withPluginAtFront(new WithSchemaPlugin(e))})}};function createQueryCreator(){return new ha({executor:fa})}function createJoinBuilder(e,t){return new Ui({joinNode:ii.create(e,parseTableExpression(t))})}function createOverBuilder(){return new Gi({overNode:Ai.create()})}function parseJoin(e,t){if(t.length===3)return parseSingleOnJoin(e,t[0],t[1],t[2]);if(t.length===2)return parseCallbackJoin(e,t[0],t[1]);if(t.length===1)return parseOnlessJoin(e,t[0]);throw Error(`not implemented`)}function parseCallbackJoin(e,t,n){return n(createJoinBuilder(e,t)).toOperationNode()}function parseSingleOnJoin(e,t,n,r){return ii.createWithOn(e,parseTableExpression(t),parseReferentialBinaryOperation(n,`=`,r))}function parseOnlessJoin(e,t){return ii.create(e,parseTableExpression(t))}const ga=freeze({is(e){return e.kind===`OffsetNode`},create(e){return freeze({kind:`OffsetNode`,offset:e})}}),_a=freeze({is(e){return e.kind===`GroupByItemNode`},create(e){return freeze({kind:`GroupByItemNode`,groupBy:e})}});function parseGroupBy(e){return e=isFunction(e)?e(expressionBuilder()):e,parseReferenceExpressionOrList(e).map(_a.create)}const va=freeze({is(e){return e.kind===`SetOperationNode`},create(e,t,n){return freeze({kind:`SetOperationNode`,operator:e,expression:t,all:n})}});function parseSetOperations(e,t,n){return isFunction(t)&&(t=t(createExpressionBuilder())),isReadonlyArray(t)||(t=[t]),t.map(t=>va.create(e,parseExpression(t),n))}var L=class ExpressionWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new ya(ni.create(this.#e,parseValueBinaryOperationOrExpression(e)))}and(...e){return new ba(ti.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new ExpressionWrapper(this.#e)}$notNull(){return new ExpressionWrapper(this.#e)}toOperationNode(){return this.#e}},AliasedExpressionWrapper=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return Qr.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():w.create(this.#t))}},ya=class OrWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new OrWrapper(ni.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new OrWrapper(this.#e)}toOperationNode(){return Di.create(this.#e)}},ba=class AndWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}and(...e){return new AndWrapper(ti.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new AndWrapper(this.#e)}toOperationNode(){return Di.create(this.#e)}};const xa=freeze({is(e){return e.kind===`FetchNode`},create(e,t){return{kind:`FetchNode`,rowCount:O.create(e),modifier:t}}});function parseFetch(e,t){if(!isNumber(e)&&!isBigInt(e))throw Error(`Invalid fetch row count: ${e}`);if(!isFetchModifier(t))throw Error(`Invalid fetch modifier: ${t}`);return xa.create(e,t)}function isFetchModifier(e){return e===`only`||e===`with ties`}var R,SelectQueryBuilderImpl=class{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...e){return new R({...this.#e,queryNode:j.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new R({...this.#e,queryNode:j.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}having(...e){return new R({...this.#e,queryNode:M.cloneWithHaving(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}havingRef(e,t,n){return new R({...this.#e,queryNode:M.cloneWithHaving(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}select(e){return new R({...this.#e,queryNode:M.cloneWithSelections(this.#e.queryNode,parseSelectArg(e))})}distinctOn(e){return new R({...this.#e,queryNode:M.cloneWithDistinctOn(this.#e.queryNode,parseReferenceExpressionOrList(e))})}modifyFront(e){return new R({...this.#e,queryNode:M.cloneWithFrontModifier(this.#e.queryNode,ei.createWithExpression(e.toOperationNode()))})}modifyEnd(e){return new R({...this.#e,queryNode:j.cloneWithEndModifier(this.#e.queryNode,ei.createWithExpression(e.toOperationNode()))})}distinct(){return new R({...this.#e,queryNode:M.cloneWithFrontModifier(this.#e.queryNode,ei.create(`Distinct`))})}forUpdate(e){return new R({...this.#e,queryNode:j.cloneWithEndModifier(this.#e.queryNode,ei.create(`ForUpdate`,e?asArray(e).map(parseTable):void 0))})}forShare(e){return new R({...this.#e,queryNode:j.cloneWithEndModifier(this.#e.queryNode,ei.create(`ForShare`,e?asArray(e).map(parseTable):void 0))})}forKeyShare(e){return new R({...this.#e,queryNode:j.cloneWithEndModifier(this.#e.queryNode,ei.create(`ForKeyShare`,e?asArray(e).map(parseTable):void 0))})}forNoKeyUpdate(e){return new R({...this.#e,queryNode:j.cloneWithEndModifier(this.#e.queryNode,ei.create(`ForNoKeyUpdate`,e?asArray(e).map(parseTable):void 0))})}skipLocked(){return new R({...this.#e,queryNode:j.cloneWithEndModifier(this.#e.queryNode,ei.create(`SkipLocked`))})}noWait(){return new R({...this.#e,queryNode:j.cloneWithEndModifier(this.#e.queryNode,ei.create(`NoWait`))})}selectAll(e){return new R({...this.#e,queryNode:M.cloneWithSelections(this.#e.queryNode,parseSelectAll(e))})}innerJoin(...e){return this.#t(`InnerJoin`,e)}leftJoin(...e){return this.#t(`LeftJoin`,e)}rightJoin(...e){return this.#t(`RightJoin`,e)}fullJoin(...e){return this.#t(`FullJoin`,e)}crossJoin(...e){return this.#t(`CrossJoin`,e)}innerJoinLateral(...e){return this.#t(`LateralInnerJoin`,e)}leftJoinLateral(...e){return this.#t(`LateralLeftJoin`,e)}crossJoinLateral(...e){return this.#t(`LateralCrossJoin`,e)}crossApply(...e){return this.#t(`CrossApply`,e)}outerApply(...e){return this.#t(`OuterApply`,e)}#t(e,t){return new R({...this.#e,queryNode:j.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new R({...this.#e,queryNode:j.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}groupBy(e){return new R({...this.#e,queryNode:M.cloneWithGroupByItems(this.#e.queryNode,parseGroupBy(e))})}limit(e){return new R({...this.#e,queryNode:M.cloneWithLimit(this.#e.queryNode,na.create(parseValueExpression(e)))})}offset(e){return new R({...this.#e,queryNode:M.cloneWithOffset(this.#e.queryNode,ga.create(parseValueExpression(e)))})}fetch(e,t=`only`){return new R({...this.#e,queryNode:M.cloneWithFetch(this.#e.queryNode,parseFetch(e,t))})}top(e,t){return new R({...this.#e,queryNode:j.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}union(e){return new R({...this.#e,queryNode:M.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!1))})}unionAll(e){return new R({...this.#e,queryNode:M.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!0))})}intersect(e){return new R({...this.#e,queryNode:M.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!1))})}intersectAll(e){return new R({...this.#e,queryNode:M.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!0))})}except(e){return new R({...this.#e,queryNode:M.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!1))})}exceptAll(e){return new R({...this.#e,queryNode:M.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!0))})}as(e){return new AliasedSelectQueryBuilderImpl(this,e)}clearSelect(){return new R({...this.#e,queryNode:M.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new R({...this.#e,queryNode:j.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new R({...this.#e,queryNode:M.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new R({...this.#e,queryNode:M.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new R({...this.#e,queryNode:j.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new R({...this.#e,queryNode:M.cloneWithoutGroupBy(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new R({...this.#e})}$castTo(){return new R(this.#e)}$narrowType(){return new R(this.#e)}$assertType(){return new R(this.#e)}$asTuple(){return new L(this.toOperationNode())}$asScalar(){return new L(this.toOperationNode())}withPlugin(e){return new R({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile();return(await this.#e.executor.executeQuery(t,e)).rows}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new R({...this.#e,queryNode:j.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};R=SelectQueryBuilderImpl;function createSelectQueryBuilder(e){return new SelectQueryBuilderImpl(e)}var AliasedSelectQueryBuilderImpl=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return Qr.create(this.#e.toOperationNode(),w.create(this.#t))}};const Sa=freeze({is(e){return e.kind===`AggregateFunctionNode`},create(e,t=[]){return freeze({kind:`AggregateFunctionNode`,func:e,aggregated:t})},cloneWithDistinct(e){return freeze({...e,distinct:!0})},cloneWithOrderBy(e,t,n=!1){let r=n?`withinGroup`:`orderBy`;return freeze({...e,[r]:e[r]?Oi.cloneWithItems(e[r],t):Oi.create(t)})},cloneWithFilter(e,t){return freeze({...e,filter:e.filter?A.cloneWithOperation(e.filter,`And`,t):A.create(t)})},cloneWithOrFilter(e,t){return freeze({...e,filter:e.filter?A.cloneWithOperation(e.filter,`Or`,t):A.create(t)})},cloneWithOver(e,t){return freeze({...e,over:t})}}),Ca=freeze({is(e){return e.kind===`FunctionNode`},create(e,t){return freeze({kind:`FunctionNode`,func:e,arguments:t})}});var wa=class AggregateFunctionBuilder{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}as(e){return new AliasedAggregateFunctionBuilder(this,e)}distinct(){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Sa.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:j.cloneWithOrderByItems(this.#e.aggregateFunctionNode,parseOrderBy(e))})}clearOrderBy(){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:j.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Sa.cloneWithOrderBy(this.#e.aggregateFunctionNode,parseOrderBy(e),!0)})}filterWhere(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Sa.cloneWithFilter(this.#e.aggregateFunctionNode,parseValueBinaryOperationOrExpression(e))})}filterWhereRef(e,t,n){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Sa.cloneWithFilter(this.#e.aggregateFunctionNode,parseReferentialBinaryOperation(e,t,n))})}over(e){let t=createOverBuilder();return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Sa.cloneWithOver(this.#e.aggregateFunctionNode,(e?e(t):t).toOperationNode())})}$call(e){return e(this)}$castTo(){return new AggregateFunctionBuilder(this.#e)}$notNull(){return new AggregateFunctionBuilder(this.#e)}toOperationNode(){return this.#e.aggregateFunctionNode}},AliasedAggregateFunctionBuilder=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return Qr.create(this.#e.toOperationNode(),w.create(this.#t))}};function createFunctionModule(){let fn=(e,t)=>new L(Ca.create(e,parseReferenceExpressionOrList(t??[]))),agg=(e,t)=>new wa({aggregateFunctionNode:Sa.create(e,t?parseReferenceExpressionOrList(t):void 0)});return Object.assign(fn,{agg,avg(e){return agg(`avg`,[e])},coalesce(...e){return fn(`coalesce`,e)},count(e){return agg(`count`,[e])},countAll(e){return new wa({aggregateFunctionNode:Sa.create(`count`,parseSelectAll(e))})},max(e){return agg(`max`,[e])},min(e){return agg(`min`,[e])},sum(e){return agg(`sum`,[e])},any(e){return fn(`any`,[e])},jsonAgg(e){return new wa({aggregateFunctionNode:Sa.create(`json_agg`,[isString(e)?parseTable(e):e.toOperationNode()])})},toJson(e){return new L(Ca.create(`to_json`,[isString(e)?parseTable(e):e.toOperationNode()]))}})}const Ta=freeze({is(e){return e.kind===`UnaryOperationNode`},create(e,t){return freeze({kind:`UnaryOperationNode`,operator:e,operand:t})}});function parseUnaryOperation(e,t){if(isUnaryOperator(e))return Ta.create(hi.create(e),parseReferenceExpression(t));throw Error(`invalid unary operator ${JSON.stringify(e)}`)}const z=freeze({is(e){return e.kind===`CaseNode`},create(e){return freeze({kind:`CaseNode`,value:e})},cloneWithWhen(e,t){return freeze({...e,when:freeze(e.when?[...e.when,t]:[t])})},cloneWithThen(e,t){return freeze({...e,when:e.when?freeze([...e.when.slice(0,-1),Bi.cloneWithResult(e.when[e.when.length-1],t)]):void 0})},cloneWith(e,t){return freeze({...e,...t})}});var CaseBuilder=class{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:z.cloneWithWhen(this.#e.node,Bi.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:z.cloneWithWhen(this.#e.node,Bi.create(parseReferentialBinaryOperation(e,t,n)))})}},CaseThenBuilder=class{#e;constructor(e){this.#e=freeze(e)}then(e){return new CaseWhenBuilder({...this.#e,node:z.cloneWithThen(this.#e.node,isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e))})}thenRef(e){return new CaseWhenBuilder({...this.#e,node:z.cloneWithThen(this.#e.node,parseReferenceExpression(e))})}},CaseWhenBuilder=class{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:z.cloneWithWhen(this.#e.node,Bi.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:z.cloneWithWhen(this.#e.node,Bi.create(parseReferentialBinaryOperation(e,t,n)))})}else(e){return new CaseEndBuilder({...this.#e,node:z.cloneWith(this.#e.node,{else:isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e)})})}elseRef(e){return new CaseEndBuilder({...this.#e,node:z.cloneWith(this.#e.node,{else:parseReferenceExpression(e)})})}end(){return new L(z.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new L(z.cloneWith(this.#e.node,{isStatement:!0}))}},CaseEndBuilder=class{#e;constructor(e){this.#e=freeze(e)}end(){return new L(z.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new L(z.cloneWith(this.#e.node,{isStatement:!0}))}};const Ea=freeze({is(e){return e.kind===`JSONPathLegNode`},create(e,t){return freeze({kind:`JSONPathLegNode`,type:e,value:t})}}),Da=/^#-\d+$/;var JSONPathBuilder=class{#e;constructor(e){this.#e=e}at(e){if(typeof e!=`number`&&typeof e!=`string`||typeof e==`number`&&!Number.isInteger(e)||typeof e==`string`&&e!==`last`&&!Da.test(e))throw Error(`Unexpected index value in .at(...): ${e}`);return this.#t(`ArrayLocation`,e)}key(e){return this.#t(`Member`,e)}#t(e,t){return Si.is(this.#e)?new Oa(Si.cloneWithTraversal(this.#e,wi.is(this.#e.traversal)?wi.cloneWithLeg(this.#e.traversal,Ea.create(e,t)):Ci.cloneWithValue(this.#e.traversal,O.createImmediate(t)))):new Oa(wi.cloneWithLeg(this.#e,Ea.create(e,t)))}},Oa=class TraversedJSONPathBuilder extends JSONPathBuilder{#e;constructor(e){super(e),this.#e=e}get expressionType(){}as(e){return new AliasedJSONPathBuilder(this,e)}$castTo(){return new TraversedJSONPathBuilder(this.#e)}$notNull(){return new TraversedJSONPathBuilder(this.#e)}toOperationNode(){return this.#e}},AliasedJSONPathBuilder=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return Qr.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():w.create(this.#t))}};const ka=freeze({is(e){return e.kind===`TupleNode`},create(e){return freeze({kind:`TupleNode`,values:freeze(e)})}}),Aa=freeze({bigint:!0,bigserial:!0,binary:!0,blob:!0,boolean:!0,bytea:!0,char:!0,date:!0,datemultirange:!0,daterange:!0,datetime:!0,datetime2:!0,decimal:!0,"double precision":!0,float4:!0,float8:!0,int2:!0,int4:!0,int4multirange:!0,int4range:!0,int8:!0,int8multirange:!0,int8range:!0,integer:!0,json:!0,jsonb:!0,numeric:!0,nummultirange:!0,numrange:!0,real:!0,serial:!0,smallint:!0,text:!0,time:!0,timestamp:!0,timestamptz:!0,timetz:!0,tsmultirange:!0,tsrange:!0,tstzmultirange:!0,tstzrange:!0,uuid:!0,varbinary:!0,varchar:!0}),ja=freeze([/^varchar\(\d+\)$/,/^char\(\d+\)$/,/^decimal\(\d+, \d+\)$/,/^numeric\(\d+, \d+\)$/,/^binary\(\d+\)$/,/^datetime\(\d+\)$/,/^time\(\d+\)$/,/^timetz\(\d+\)$/,/^timestamp\(\d+\)$/,/^timestamptz\(\d+\)$/,/^datetime2\(\d+\)$/,/^varbinary\(\d+\)$/]),Ma=freeze({is(e){return e.kind===`DataTypeNode`},create(e){return freeze({kind:`DataTypeNode`,dataType:e})}});function isColumnDataType(e){return Aa[e]||ja.some(t=>t.test(e))}function parseDataTypeExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isColumnDataType(e))return Ma.create(e);throw Error(`invalid column data type ${JSON.stringify(e)}`)}const Na=freeze({is(e){return e.kind===`CastNode`},create(e,t){return freeze({kind:`CastNode`,expression:e,dataType:t})}});function createExpressionBuilder(e=fa){function binary(e,t,n){return new L(parseValueBinaryOperation(e,t,n))}function unary(e,t){return new L(parseUnaryOperation(e,t))}let t=Object.assign(binary,{fn:void 0,eb:void 0,selectFrom(t){return createSelectQueryBuilder({queryId:createQueryId(),executor:e,queryNode:M.createFrom(parseTableExpressionOrList(t))})},case(e){return new CaseBuilder({node:z.create(isUndefined(e)?void 0:parseReferenceExpression(e))})},ref(e,t){return isUndefined(t)?new L(parseStringReference(e)):new JSONPathBuilder(parseJSONReference(e,t))},jsonPath(){return new JSONPathBuilder(wi.create())},table(e){return new L(parseTable(e))},val(e){return new L(parseValueExpression(e))},refTuple(...e){return new L(ka.create(e.map(parseReferenceExpression)))},tuple(...e){return new L(ka.create(e.map(parseValueExpression)))},lit(e){return new L(parseSafeImmediateValue(e))},unary,not(e){return unary(`not`,e)},exists(e){return unary(`exists`,e)},neg(e){return unary(`-`,e)},between(e,t,n){return new L(ai.create(parseReferenceExpression(e),hi.create(`between`),ti.create(parseValueExpression(t),parseValueExpression(n))))},betweenSymmetric(e,t,n){return new L(ai.create(parseReferenceExpression(e),hi.create(`between symmetric`),ti.create(parseValueExpression(t),parseValueExpression(n))))},and(e){return isReadonlyArray(e)?new L(parseFilterList(e,`and`)):new L(parseFilterObject(e,`and`))},or(e){return isReadonlyArray(e)?new L(parseFilterList(e,`or`)):new L(parseFilterObject(e,`or`))},parens(...e){let t=parseValueBinaryOperationOrExpression(e);return Di.is(t)?new L(t):new L(Di.create(t))},cast(e,t){return new L(Na.create(parseReferenceExpression(e),parseDataTypeExpression(t)))}});return t.fn=createFunctionModule(),t.eb=t,t}function expressionBuilder(e){return createExpressionBuilder()}function parseExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isFunction(e))return e(expressionBuilder()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify(e)}`)}function parseAliasedExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isFunction(e))return e(expressionBuilder()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify(e)}`)}function isExpressionOrFactory(e){return isExpression(e)||isAliasedExpression(e)||isFunction(e)}var DynamicTableBuilder=class{#e;get table(){return this.#e}constructor(e){this.#e=e}as(e){return new AliasedDynamicTableBuilder(this.#e,e)}},AliasedDynamicTableBuilder=class{#e;#t;get table(){return this.#e}get alias(){return this.#t}constructor(e,t){this.#e=e,this.#t=t}toOperationNode(){return Qr.create(parseTable(this.#e),w.create(this.#t))}};function isAliasedDynamicTableBuilder(e){return isObject$1(e)&&isOperationNodeSource(e)&&isString(e.table)&&isString(e.alias)}function parseTableExpressionOrList(e){return isReadonlyArray(e)?e.map(e=>parseTableExpression(e)):[parseTableExpression(e)]}function parseTableExpression(e){return isString(e)?parseAliasedTable(e):isAliasedDynamicTableBuilder(e)?e.toOperationNode():parseAliasedExpression(e)}function parseAliasedTable(e){let t=` as `;if(e.includes(t)){let[n,r]=e.split(t).map(trim$1);return Qr.create(parseTable(n),w.create(r))}return parseTable(e)}function parseTable(e){if(e.includes(`.`)){let[t,n]=e.split(`.`).map(trim$1);return $r.createWithSchema(t,n)}return $r.create(e)}function trim$1(e){return e.trim()}const Pa=freeze({is(e){return e.kind===`AddColumnNode`},create(e){return freeze({kind:`AddColumnNode`,column:e})}}),B=freeze({is(e){return e.kind===`ColumnDefinitionNode`},create(e,t){return freeze({kind:`ColumnDefinitionNode`,column:E.create(e),dataType:t})},cloneWithFrontModifier(e,t){return freeze({...e,frontModifiers:e.frontModifiers?freeze([...e.frontModifiers,t]):[t]})},cloneWithEndModifier(e,t){return freeze({...e,endModifiers:e.endModifiers?freeze([...e.endModifiers,t]):[t]})},cloneWith(e,t){return freeze({...e,...t})}}),Fa=freeze({is(e){return e.kind===`DropColumnNode`},create(e){return freeze({kind:`DropColumnNode`,column:E.create(e)})},cloneWith(e,t){return freeze({...e,...t})}}),Ia=freeze({is(e){return e.kind===`RenameColumnNode`},create(e,t){return freeze({kind:`RenameColumnNode`,column:E.create(e),renameTo:E.create(t)})}}),La=freeze({is(e){return e.kind===`CheckConstraintNode`},create(e,t){return freeze({kind:`CheckConstraintNode`,expression:e,name:t?w.create(t):void 0})}}),Ra=freeze({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0});Object.keys(Ra);const za=freeze({is(e){return e.kind===`ReferencesNode`},create(e,t){return freeze({kind:`ReferencesNode`,table:e,columns:freeze([...t])})},cloneWithOnDelete(e,t){return freeze({...e,onDelete:t})},cloneWithOnUpdate(e,t){return freeze({...e,onUpdate:t})}});function isOnModifyForeignAction(e){return isString(e)&&Ra[e]}function parseDefaultValueExpression(e){return isOperationNodeSource(e)?e.toOperationNode():O.createImmediate(e)}const Ba=freeze({is(e){return e.kind===`GeneratedNode`},create(e){return freeze({kind:`GeneratedNode`,...e})},createWithExpression(e){return freeze({kind:`GeneratedNode`,always:!0,expression:e})},cloneWith(e,t){return freeze({...e,...t})}}),Va=freeze({is(e){return e.kind===`DefaultValueNode`},create(e){return freeze({kind:`DefaultValueNode`,defaultValue:e})}});function parseOnModifyForeignAction(e){if(isOnModifyForeignAction(e))return e;throw Error(`invalid OnModifyForeignAction ${e}`)}var Ha=class ColumnDefinitionBuilder{#e;constructor(e){this.#e=e}autoIncrement(){return new ColumnDefinitionBuilder(B.cloneWith(this.#e,{autoIncrement:!0}))}identity(){return new ColumnDefinitionBuilder(B.cloneWith(this.#e,{identity:!0}))}primaryKey(){return new ColumnDefinitionBuilder(B.cloneWith(this.#e,{primaryKey:!0}))}references(e){let t=parseStringReference(e);if(!t.table||gi.is(t.column))throw Error(`invalid call references('${e}'). The reference must have format table.column or schema.table.column`);return new ColumnDefinitionBuilder(B.cloneWith(this.#e,{references:za.create(t.table,[t.column])}))}onDelete(e){if(!this.#e.references)throw Error(`on delete constraint can only be added for foreign keys`);return new ColumnDefinitionBuilder(B.cloneWith(this.#e,{references:za.cloneWithOnDelete(this.#e.references,parseOnModifyForeignAction(e))}))}onUpdate(e){if(!this.#e.references)throw Error(`on update constraint can only be added for foreign keys`);return new ColumnDefinitionBuilder(B.cloneWith(this.#e,{references:za.cloneWithOnUpdate(this.#e.references,parseOnModifyForeignAction(e))}))}unique(){return new ColumnDefinitionBuilder(B.cloneWith(this.#e,{unique:!0}))}notNull(){return new ColumnDefinitionBuilder(B.cloneWith(this.#e,{notNull:!0}))}unsigned(){return new ColumnDefinitionBuilder(B.cloneWith(this.#e,{unsigned:!0}))}defaultTo(e){return new ColumnDefinitionBuilder(B.cloneWith(this.#e,{defaultTo:Va.create(parseDefaultValueExpression(e))}))}check(e){return new ColumnDefinitionBuilder(B.cloneWith(this.#e,{check:La.create(e.toOperationNode())}))}generatedAlwaysAs(e){return new ColumnDefinitionBuilder(B.cloneWith(this.#e,{generated:Ba.createWithExpression(e.toOperationNode())}))}generatedAlwaysAsIdentity(){return new ColumnDefinitionBuilder(B.cloneWith(this.#e,{generated:Ba.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new ColumnDefinitionBuilder(B.cloneWith(this.#e,{generated:Ba.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#e.generated)throw Error(`stored() can only be called after generatedAlwaysAs`);return new ColumnDefinitionBuilder(B.cloneWith(this.#e,{generated:Ba.cloneWith(this.#e.generated,{stored:!0})}))}modifyFront(e){return new ColumnDefinitionBuilder(B.cloneWithFrontModifier(this.#e,e.toOperationNode()))}nullsNotDistinct(){return new ColumnDefinitionBuilder(B.cloneWith(this.#e,{nullsNotDistinct:!0}))}ifNotExists(){return new ColumnDefinitionBuilder(B.cloneWith(this.#e,{ifNotExists:!0}))}modifyEnd(e){return new ColumnDefinitionBuilder(B.cloneWithEndModifier(this.#e,e.toOperationNode()))}$call(e){return e(this)}toOperationNode(){return this.#e}};const Ua=freeze({is(e){return e.kind===`ModifyColumnNode`},create(e){return freeze({kind:`ModifyColumnNode`,column:e})}}),Wa=freeze({is(e){return e.kind===`ForeignKeyConstraintNode`},create(e,t,n,r){return freeze({kind:`ForeignKeyConstraintNode`,columns:e,references:za.create(t,n),name:r?w.create(r):void 0})},cloneWith(e,t){return freeze({...e,...t})}});var Ga=class ForeignKeyConstraintBuilder{#e;constructor(e){this.#e=e}onDelete(e){return new ForeignKeyConstraintBuilder(Wa.cloneWith(this.#e,{onDelete:parseOnModifyForeignAction(e)}))}onUpdate(e){return new ForeignKeyConstraintBuilder(Wa.cloneWith(this.#e,{onUpdate:parseOnModifyForeignAction(e)}))}deferrable(){return new ForeignKeyConstraintBuilder(Wa.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new ForeignKeyConstraintBuilder(Wa.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new ForeignKeyConstraintBuilder(Wa.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new ForeignKeyConstraintBuilder(Wa.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}};const Ka=freeze({is(e){return e.kind===`AddConstraintNode`},create(e){return freeze({kind:`AddConstraintNode`,constraint:e})}}),qa=freeze({is(e){return e.kind===`UniqueConstraintNode`},create(e,t,n){return isString(e.at(0))&&(logOnce("`UniqueConstraintNode.create(columns: string[], ...)` is deprecated - pass `ColumnNode[]` instead."),e=e.map(E.create)),freeze({kind:`UniqueConstraintNode`,columns:freeze(e),name:t?w.create(t):void 0,nullsNotDistinct:n})},cloneWith(e,t){return freeze({...e,...t})}}),Ja=freeze({is(e){return e.kind===`DropConstraintNode`},create(e){return freeze({kind:`DropConstraintNode`,constraintName:w.create(e)})},cloneWith(e,t){return freeze({...e,...t})}}),Ya=freeze({is(e){return e.kind===`AlterColumnNode`},create(e,t,n){return freeze({kind:`AlterColumnNode`,column:E.create(e),[t]:n})}});var AlterColumnBuilder=class{#e;constructor(e){this.#e=e}setDataType(e){return new AlteredColumnBuilder(Ya.create(this.#e,`dataType`,parseDataTypeExpression(e)))}setDefault(e){return new AlteredColumnBuilder(Ya.create(this.#e,`setDefault`,parseDefaultValueExpression(e)))}dropDefault(){return new AlteredColumnBuilder(Ya.create(this.#e,`dropDefault`,!0))}setNotNull(){return new AlteredColumnBuilder(Ya.create(this.#e,`setNotNull`,!0))}dropNotNull(){return new AlteredColumnBuilder(Ya.create(this.#e,`dropNotNull`,!0))}$call(e){return e(this)}},AlteredColumnBuilder=class{#e;constructor(e){this.#e=e}toOperationNode(){return this.#e}},AlterTableExecutor=class{#e;constructor(e){this.#e=freeze(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},Xa=class AlterTableAddForeignKeyConstraintBuilder{#e;constructor(e){this.#e=freeze(e)}onDelete(e){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.onDelete(e)})}onUpdate(e){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.onUpdate(e)})}deferrable(){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.deferrable()})}notDeferrable(){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.initiallyImmediate()})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(C.cloneWithTableProps(this.#e.node,{addConstraint:Ka.create(this.#e.constraintBuilder.toOperationNode())}),this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},Za=class AlterTableDropConstraintBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new AlterTableDropConstraintBuilder({...this.#e,node:C.cloneWithTableProps(this.#e.node,{dropConstraint:Ja.cloneWith(this.#e.node.dropConstraint,{ifExists:!0})})})}cascade(){return new AlterTableDropConstraintBuilder({...this.#e,node:C.cloneWithTableProps(this.#e.node,{dropConstraint:Ja.cloneWith(this.#e.node.dropConstraint,{modifier:`cascade`})})})}restrict(){return new AlterTableDropConstraintBuilder({...this.#e,node:C.cloneWithTableProps(this.#e.node,{dropConstraint:Ja.cloneWith(this.#e.node.dropConstraint,{modifier:`restrict`})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const Qa=freeze({is(e){return e.kind===`PrimaryKeyConstraintNode`},create(e,t){return freeze({kind:`PrimaryKeyConstraintNode`,columns:freeze(e.map(E.create)),name:t?w.create(t):void 0})},cloneWith(e,t){return freeze({...e,...t})}}),$a=freeze({is(e){return e.kind===`AddIndexNode`},create(e){return freeze({kind:`AddIndexNode`,name:w.create(e)})},cloneWith(e,t){return freeze({...e,...t})},cloneWithColumns(e,t){return freeze({...e,columns:[...e.columns||[],...t]})}});var eo=class AlterTableAddIndexBuilder{#e;constructor(e){this.#e=freeze(e)}unique(){return new AlterTableAddIndexBuilder({...this.#e,node:C.cloneWithTableProps(this.#e.node,{addIndex:$a.cloneWith(this.#e.node.addIndex,{unique:!0})})})}column(e){return new AlterTableAddIndexBuilder({...this.#e,node:C.cloneWithTableProps(this.#e.node,{addIndex:$a.cloneWithColumns(this.#e.node.addIndex,[isString(e)?parseOrderedColumnName(e):e.toOperationNode()])})})}columns(e){return new AlterTableAddIndexBuilder({...this.#e,node:C.cloneWithTableProps(this.#e.node,{addIndex:$a.cloneWithColumns(this.#e.node.addIndex,e.map(e=>isString(e)?parseOrderedColumnName(e):e.toOperationNode()))})})}expression(e){return new AlterTableAddIndexBuilder({...this.#e,node:C.cloneWithTableProps(this.#e.node,{addIndex:$a.cloneWithColumns(this.#e.node.addIndex,[e.toOperationNode()])})})}using(e){return new AlterTableAddIndexBuilder({...this.#e,node:C.cloneWithTableProps(this.#e.node,{addIndex:$a.cloneWith(this.#e.node.addIndex,{using:D.createWithSql(e)})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},to=class UniqueConstraintNodeBuilder{#e;constructor(e){this.#e=e}nullsNotDistinct(){return new UniqueConstraintNodeBuilder(qa.cloneWith(this.#e,{nullsNotDistinct:!0}))}deferrable(){return new UniqueConstraintNodeBuilder(qa.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new UniqueConstraintNodeBuilder(qa.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new UniqueConstraintNodeBuilder(qa.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new UniqueConstraintNodeBuilder(qa.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}},no=class PrimaryKeyConstraintBuilder{#e;constructor(e){this.#e=e}deferrable(){return new PrimaryKeyConstraintBuilder(Qa.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new PrimaryKeyConstraintBuilder(Qa.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new PrimaryKeyConstraintBuilder(Qa.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new PrimaryKeyConstraintBuilder(Qa.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}},CheckConstraintBuilder=class{#e;constructor(e){this.#e=e}$call(e){return e(this)}toOperationNode(){return this.#e}};const ro=freeze({is(e){return e.kind===`RenameConstraintNode`},create(e,t){return freeze({kind:`RenameConstraintNode`,oldName:w.create(e),newName:w.create(t)})}});var io=class DropColumnBuilder{#e;constructor(e){this.#e=freeze({...e})}ifExists(){return new DropColumnBuilder({...this.#e,node:Fa.cloneWith(this.#e.node,{ifExists:!0})})}toOperationNode(){return this.#e.node}},AlterTableBuilder=class{#e;constructor(e){this.#e=freeze(e)}renameTo(e){return new AlterTableExecutor({...this.#e,node:C.cloneWithTableProps(this.#e.node,{renameTo:parseTable(e)})})}setSchema(e){return new AlterTableExecutor({...this.#e,node:C.cloneWithTableProps(this.#e.node,{setSchema:w.create(e)})})}alterColumn(e,t){let n=t(new AlterColumnBuilder(e));return new ao({...this.#e,node:C.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}dropColumn(e,t=noop){let n=t(new io({node:Fa.create(e)}));return new ao({...this.#e,node:C.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}renameColumn(e,t){return new ao({...this.#e,node:C.cloneWithColumnAlteration(this.#e.node,Ia.create(e,t))})}addColumn(e,t,n=noop){let r=n(new Ha(B.create(e,parseDataTypeExpression(t))));return new ao({...this.#e,node:C.cloneWithColumnAlteration(this.#e.node,Pa.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new Ha(B.create(e,parseDataTypeExpression(t))));return new ao({...this.#e,node:C.cloneWithColumnAlteration(this.#e.node,Ua.create(r.toOperationNode()))})}addUniqueConstraint(e,t,n=noop){let r=n(new to(qa.create(t.map(e=>isString(e)?E.create(e):parseExpression(e)),e)));return new AlterTableExecutor({...this.#e,node:C.cloneWithTableProps(this.#e.node,{addConstraint:Ka.create(r.toOperationNode())})})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(La.create(t.toOperationNode(),e)));return new AlterTableExecutor({...this.#e,node:C.cloneWithTableProps(this.#e.node,{addConstraint:Ka.create(r.toOperationNode())})})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new Ga(Wa.create(t.map(E.create),parseTable(n),r.map(E.create),e)));return new Xa({...this.#e,constraintBuilder:a})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new no(Qa.create(t,e)));return new AlterTableExecutor({...this.#e,node:C.cloneWithTableProps(this.#e.node,{addConstraint:Ka.create(r.toOperationNode())})})}dropConstraint(e){return new Za({...this.#e,node:C.cloneWithTableProps(this.#e.node,{dropConstraint:Ja.create(e)})})}renameConstraint(e,t){return new Za({...this.#e,node:C.cloneWithTableProps(this.#e.node,{renameConstraint:ro.create(e,t)})})}addIndex(e){return new eo({...this.#e,node:C.cloneWithTableProps(this.#e.node,{addIndex:$a.create(e)})})}dropIndex(e){return new AlterTableExecutor({...this.#e,node:C.cloneWithTableProps(this.#e.node,{dropIndex:Yr.create(e)})})}$call(e){return e(this)}},ao=class AlterTableColumnAlteringBuilder{#e;constructor(e){this.#e=freeze(e)}alterColumn(e,t){let n=t(new AlterColumnBuilder(e));return new AlterTableColumnAlteringBuilder({...this.#e,node:C.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}dropColumn(e,t=noop){let n=t(new io({node:Fa.create(e)}));return new AlterTableColumnAlteringBuilder({...this.#e,node:C.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}renameColumn(e,t){return new AlterTableColumnAlteringBuilder({...this.#e,node:C.cloneWithColumnAlteration(this.#e.node,Ia.create(e,t))})}addColumn(e,t,n=noop){let r=n(new Ha(B.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:C.cloneWithColumnAlteration(this.#e.node,Pa.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new Ha(B.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:C.cloneWithColumnAlteration(this.#e.node,Ua.create(r.toOperationNode()))})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},ImmediateValueTransformer=class extends OperationNodeTransformer{transformPrimitiveValueList(e){return Ei.create(e.values.map(O.createImmediate))}transformValue(e){return O.createImmediate(e.value)}},oo=class CreateIndexBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateIndexBuilder({...this.#e,node:Gr.cloneWith(this.#e.node,{ifNotExists:!0})})}unique(){return new CreateIndexBuilder({...this.#e,node:Gr.cloneWith(this.#e.node,{unique:!0})})}nullsNotDistinct(){return new CreateIndexBuilder({...this.#e,node:Gr.cloneWith(this.#e.node,{nullsNotDistinct:!0})})}on(e){return new CreateIndexBuilder({...this.#e,node:Gr.cloneWith(this.#e.node,{table:parseTable(e)})})}column(e){return new CreateIndexBuilder({...this.#e,node:Gr.cloneWithColumns(this.#e.node,[isString(e)?parseOrderedColumnName(e):e.toOperationNode()])})}columns(e){return new CreateIndexBuilder({...this.#e,node:Gr.cloneWithColumns(this.#e.node,e.map(e=>isString(e)?parseOrderedColumnName(e):e.toOperationNode()))})}expression(e){return new CreateIndexBuilder({...this.#e,node:Gr.cloneWithColumns(this.#e.node,[e.toOperationNode()])})}using(e){return new CreateIndexBuilder({...this.#e,node:Gr.cloneWith(this.#e.node,{using:D.createWithSql(e)})})}where(...e){let t=new ImmediateValueTransformer;return new CreateIndexBuilder({...this.#e,node:j.cloneWithWhere(this.#e.node,t.transformNode(parseValueBinaryOperationOrExpression(e),this.#e.queryId))})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},so=class CreateSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateSchemaBuilder({...this.#e,node:Kr.cloneWith(this.#e.node,{ifNotExists:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};function parseOnCommitAction(e){if(qr.includes(e))return e;throw Error(`invalid OnCommitAction ${e}`)}var co=class CreateTableAddIndexBuilder{#e;constructor(e){this.#e=e}using(e){return new CreateTableAddIndexBuilder($a.cloneWith(this.#e,{using:D.createWithSql(e)}))}$call(e){return e(this)}toOperationNode(){return this.#e}},lo=class CreateTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateTableBuilder({...this.#e,node:T.cloneWith(this.#e.node,{temporary:!0})})}onCommit(e){return new CreateTableBuilder({...this.#e,node:T.cloneWith(this.#e.node,{onCommit:parseOnCommitAction(e)})})}ifNotExists(){return new CreateTableBuilder({...this.#e,node:T.cloneWith(this.#e.node,{ifNotExists:!0})})}addColumn(e,t,n=noop){let r=n(new Ha(B.create(e,parseDataTypeExpression(t))));return new CreateTableBuilder({...this.#e,node:T.cloneWithColumn(this.#e.node,r.toOperationNode())})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new no(Qa.create(t,e)));return new CreateTableBuilder({...this.#e,node:T.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addUniqueConstraint(e,t,n=noop){let r=n(new to(qa.create(t.map(e=>isString(e)?E.create(e):parseExpression(e)),e)));return new CreateTableBuilder({...this.#e,node:T.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addIndex(e,t,n=noop){let r=n(new co($a.cloneWithColumns($a.create(e),t.map(e=>isString(e)?E.create(e):parseExpression(e)))));return new CreateTableBuilder({...this.#e,node:T.cloneWithIndex(this.#e.node,r.toOperationNode())})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(La.create(t.toOperationNode(),e)));return new CreateTableBuilder({...this.#e,node:T.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new Ga(Wa.create(t.map(E.create),parseTable(n),r.map(E.create),e)));return new CreateTableBuilder({...this.#e,node:T.cloneWithConstraint(this.#e.node,a.toOperationNode())})}modifyFront(e){return new CreateTableBuilder({...this.#e,node:T.cloneWithFrontModifier(this.#e.node,e.toOperationNode())})}modifyEnd(e){return new CreateTableBuilder({...this.#e,node:T.cloneWithEndModifier(this.#e.node,e.toOperationNode())})}as(e){return new CreateTableBuilder({...this.#e,node:T.cloneWith(this.#e.node,{selectQuery:parseExpression(e)})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},uo=class DropIndexBuilder{#e;constructor(e){this.#e=freeze(e)}on(e){return new DropIndexBuilder({...this.#e,node:Yr.cloneWith(this.#e.node,{table:parseTable(e)})})}ifExists(){return new DropIndexBuilder({...this.#e,node:Yr.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropIndexBuilder({...this.#e,node:Yr.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},fo=class DropSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropSchemaBuilder({...this.#e,node:Xr.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropSchemaBuilder({...this.#e,node:Xr.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},po=class DropTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new DropTableBuilder({...this.#e,node:Zr.cloneWith(this.#e.node,{temporary:!0})})}ifExists(){return new DropTableBuilder({...this.#e,node:Zr.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTableBuilder({...this.#e,node:Zr.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const mo=freeze({is(e){return e.kind===`CreateViewNode`},create(e){return freeze({kind:`CreateViewNode`,name:Jr.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var ImmediateValuePlugin=class{#e=new ImmediateValueTransformer;transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}transformResult(e){return Promise.resolve(e.result)}},ho=class CreateViewBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateViewBuilder({...this.#e,node:mo.cloneWith(this.#e.node,{temporary:!0})})}materialized(){return new CreateViewBuilder({...this.#e,node:mo.cloneWith(this.#e.node,{materialized:!0})})}ifNotExists(){return new CreateViewBuilder({...this.#e,node:mo.cloneWith(this.#e.node,{ifNotExists:!0})})}orReplace(){return new CreateViewBuilder({...this.#e,node:mo.cloneWith(this.#e.node,{orReplace:!0})})}columns(e){return new CreateViewBuilder({...this.#e,node:mo.cloneWith(this.#e.node,{columns:e.map(parseColumnName)})})}as(e){let t=e.withPlugin(new ImmediateValuePlugin).toOperationNode();return new CreateViewBuilder({...this.#e,node:mo.cloneWith(this.#e.node,{as:t})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const go=freeze({is(e){return e.kind===`DropViewNode`},create(e){return freeze({kind:`DropViewNode`,name:Jr.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var _o=class DropViewBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new DropViewBuilder({...this.#e,node:go.cloneWith(this.#e.node,{materialized:!0})})}ifExists(){return new DropViewBuilder({...this.#e,node:go.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropViewBuilder({...this.#e,node:go.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const vo=freeze({is(e){return e.kind===`CreateTypeNode`},create(e){return freeze({kind:`CreateTypeNode`,name:e})},cloneWithEnum(e,t){return freeze({...e,enum:Ei.create(t.map(O.createImmediate))})}});var yo=class CreateTypeBuilder{#e;constructor(e){this.#e=freeze(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}asEnum(e){return new CreateTypeBuilder({...this.#e,node:vo.cloneWithEnum(this.#e.node,e)})}$call(e){return e(this)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const bo=freeze({is(e){return e.kind===`DropTypeNode`},create(e){return Array.isArray(e)||(e=[e]),freeze({kind:`DropTypeNode`,name:e[0],additionalNames:e.slice(1)})},cloneWith(e,t){return freeze({...e,...t})}});var xo=class DropTypeBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropTypeBuilder({...this.#e,node:bo.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTypeBuilder({...this.#e,node:bo.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};function parseSchemableIdentifier(e){if(e.includes(`.`)){let t=e.split(`.`).map(trim);if(t.length===2)return Jr.createWithSchema(t[0],t[1]);throw Error(`invalid schemable identifier ${e}`)}return Jr.create(e)}function parseSchemableIdentifierArray(e){return Array.isArray(e)||(e=[e]),e.map(parseSchemableIdentifier)}function trim(e){return e.trim()}const So=freeze({is(e){return e.kind===`RefreshMaterializedViewNode`},create(e){return freeze({kind:`RefreshMaterializedViewNode`,name:Jr.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var Co=class RefreshMaterializedViewBuilder{#e;constructor(e){this.#e=freeze(e)}concurrently(){return new RefreshMaterializedViewBuilder({...this.#e,node:So.cloneWith(this.#e.node,{concurrently:!0,withNoData:!1})})}withData(){return new RefreshMaterializedViewBuilder({...this.#e,node:So.cloneWith(this.#e.node,{withNoData:!1})})}withNoData(){return new RefreshMaterializedViewBuilder({...this.#e,node:So.cloneWith(this.#e.node,{withNoData:!0,concurrently:!1})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const wo=freeze({is(e){return e.kind===`AlterTypeNode`},create(e){return freeze({kind:`AlterTypeNode`,name:e})},cloneWith(e,t){return freeze({...e,...t})}}),To=freeze({is(e){return e.kind===`AddValueNode`},create(e){return freeze({kind:`AddValueNode`,value:e})},cloneWith(e,t){return freeze({...e,...t})}});var QueryFinalizer=class{#e;constructor(e){this.#e=freeze(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){return await this.#e.executor.executeQuery(this.compile(),e)}},Eo,AlterTypeAddValueBuilder=class extends QueryFinalizer{#e;constructor(e){super(e),this.#e=e}ifNotExists(){return new Eo({...this.#e,node:wo.cloneWith(this.#e.node,{addValue:To.cloneWith(this.#e.node.addValue,{ifNotExists:!0})})})}before(e){return this.#t(e,!0)}after(e){return this.#t(e,!1)}#t(e,t){return new Eo({...this.#e,node:wo.cloneWith(this.#e.node,{addValue:To.cloneWith(this.#e.node.addValue,{isBefore:t,neighborValue:O.createImmediate(e)})})})}};Eo=AlterTypeAddValueBuilder;const Do=freeze({is(e){return e.kind===`RenameValueNode`},create(e,t){return freeze({kind:`RenameValueNode`,oldValue:e,newValue:t})}});var AlterTypeBuilder=class{#e;constructor(e){this.#e=freeze(e)}addValue(e){return new AlterTypeAddValueBuilder({...this.#e,node:wo.cloneWith(this.#e.node,{addValue:To.create(O.createImmediate(e))})})}renameTo(e){return new QueryFinalizer({...this.#e,node:wo.cloneWith(this.#e.node,{renameTo:w.create(e)})})}renameValue(e,t){return new QueryFinalizer({...this.#e,node:wo.cloneWith(this.#e.node,{renameValue:Do.create(O.createImmediate(e),O.createImmediate(t))})})}setSchema(e){return new QueryFinalizer({...this.#e,node:wo.cloneWith(this.#e.node,{setSchema:w.create(e)})})}},Oo=class SchemaModule{#e;constructor(e){this.#e=e}createTable(e){return new lo({queryId:createQueryId(),executor:this.#e,node:T.create(parseTable(e))})}dropTable(e){return new po({queryId:createQueryId(),executor:this.#e,node:Zr.create(parseTable(e))})}createIndex(e){return new oo({queryId:createQueryId(),executor:this.#e,node:Gr.create(e)})}dropIndex(e){return new uo({queryId:createQueryId(),executor:this.#e,node:Yr.create(e)})}createSchema(e){return new so({queryId:createQueryId(),executor:this.#e,node:Kr.create(e)})}dropSchema(e){return new fo({queryId:createQueryId(),executor:this.#e,node:Xr.create(e)})}alterTable(e){return new AlterTableBuilder({queryId:createQueryId(),executor:this.#e,node:C.create(parseTable(e))})}createView(e){return new ho({queryId:createQueryId(),executor:this.#e,node:mo.create(e)})}refreshMaterializedView(e){return new Co({queryId:createQueryId(),executor:this.#e,node:So.create(e)})}dropView(e){return new _o({queryId:createQueryId(),executor:this.#e,node:go.create(e)})}createType(e){return new yo({queryId:createQueryId(),executor:this.#e,node:vo.create(parseSchemableIdentifier(e))})}alterType(e){return new AlterTypeBuilder({executor:this.#e,node:wo.create(parseSchemableIdentifier(e)),queryId:createQueryId()})}dropType(e){return new xo({queryId:createQueryId(),executor:this.#e,node:bo.create(parseSchemableIdentifierArray(e))})}withPlugin(e){return new SchemaModule(this.#e.withPlugin(e))}withoutPlugins(){return new SchemaModule(this.#e.withoutPlugins())}withSchema(e){return new SchemaModule(this.#e.withPluginAtFront(new WithSchemaPlugin(e)))}},DynamicModule=class{ref(e){return new DynamicReferenceBuilder(e)}table(e){return new DynamicTableBuilder(e)}},DefaultConnectionProvider=class{#e;constructor(e){this.#e=e}async provideConnection(e,t){let n=await this.#e.acquireConnection(t);try{return await e(n)}finally{await this.#e.releaseConnection(n,t)}}},ko=class DefaultQueryExecutor extends QueryExecutorBase{#e;#t;#n;constructor(e,t,n,r=[]){super(r),this.#e=e,this.#t=t,this.#n=n}get adapter(){return this.#t}compileQuery(e,t){return this.#e.compileQuery(e,t)}provideConnection(e,t){return this.#n.provideConnection(e,t)}withPlugins(e){return new DefaultQueryExecutor(this.#e,this.#t,this.#n,[...this.plugins,...e])}withPlugin(e){return new DefaultQueryExecutor(this.#e,this.#t,this.#n,[...this.plugins,e])}withPluginAtFront(e){return new DefaultQueryExecutor(this.#e,this.#t,this.#n,[e,...this.plugins])}withConnectionProvider(e){return new DefaultQueryExecutor(this.#e,this.#t,e,[...this.plugins])}withoutPlugins(){return new DefaultQueryExecutor(this.#e,this.#t,this.#n,[])}};function performanceNow(){return typeof performance<`u`&&isFunction(performance.now)?performance.now():Date.now()}var ConnectionMutex=class{#e;#t;async obtainLock(){for(;this.#e;)await this.#e;this.#e=new Promise(e=>{this.#t=e})}releaseLock(){let e=this.#t;this.#e=void 0,this.#t=void 0,e?.()}},RuntimeDriver=class{#e;#t;#n;#r;#i;#a=/* @__PURE__ */ new WeakSet;#o;constructor(e,t,n){this.#e=e,this.#r=!1,this.#t=n,t.supportsMultipleConnections===!1&&(this.#o=new ConnectionMutex)}async init(e){if(this.#i)throw Error(`driver has already been destroyed`);this.#n??=this.#e.init(e).then(()=>{this.#r=!0}).catch(e=>{throw this.#n=void 0,e}),await waitOrAbort(this.#n,e?.signal,`init`)}async acquireConnection(e){if(this.#i)throw Error(`driver has already been destroyed`);if(this.#r||await this.init(e),this.#o){let t=this.#o.obtainLock();await waitOrAbort(t,e?.signal,`acquireConnection:mutex`,()=>t.then(()=>this.#o?.releaseLock()))}let t=this.#e.acquireConnection(e),n=await waitOrAbort(t,e?.signal,`acquireConnection:acquire`,()=>t?.then(e=>this.releaseConnection(e).catch(printBackgroundFail(`driver.releaseConnection`))).catch(printBackgroundFail(`driver.acquireConnection`)));return this.#a.has(n)||(this.#s()&&this.#c(n),this.#a.add(n)),n}async releaseConnection(e,t){await this.#e.releaseConnection(e,t),this.#o?.releaseLock()}async beginTransaction(e,t){return await this.#e.beginTransaction(e,t)}async commitTransaction(e){return await this.#e.commitTransaction(e)}async rollbackTransaction(e){return await this.#e.rollbackTransaction(e)}async savepoint(e,t,n){if(this.#e.savepoint)return await this.#e.savepoint(e,t,n);throw Error("The `savepoint` method is not supported by this driver")}async rollbackToSavepoint(e,t,n){if(this.#e.rollbackToSavepoint)return await this.#e.rollbackToSavepoint(e,t,n);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}async releaseSavepoint(e,t,n){if(this.#e.releaseSavepoint)return await this.#e.releaseSavepoint(e,t,n);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(e){this.#n&&(await waitOrAbort(this.#n,e?.signal,`destroy:initPromise`),this.#i??=this.#e.destroy(e).catch(e=>{throw this.#i=void 0,e}),await waitOrAbort(this.#i,e?.signal,`destroy`))}#s(){return this.#t.isLevelEnabled(`query`)||this.#t.isLevelEnabled(`error`)}#c(e){let t=e.executeQuery,n=e.streamQuery,r=this;e.executeQuery=async(n,i)=>{let a,o=performanceNow();try{return await t.call(e,n,i)}catch(e){throw a=e,await r.#l(e,n,o),e}finally{a||await r.#u(n,o)}},e.streamQuery=async function*(t,i,a){let o,s=performanceNow();try{for await(let r of n.call(e,t,i,a))yield r}catch(e){throw o=e,await r.#l(e,t,s),e}finally{o||await r.#u(t,s,!0)}}}async#l(e,t,n){await this.#t.error(()=>({level:`error`,error:e,query:t,queryDurationMillis:this.#d(n)}))}async#u(e,t,n=!1){await this.#t.query(()=>({level:`query`,isStream:n,query:e,queryDurationMillis:this.#d(t)}))}#d(e){return performanceNow()-e}};const ignoreError=()=>{};var SingleConnectionProvider=class{#e;#t;constructor(e){this.#e=e}async provideConnection(e){for(;this.#t;)await this.#t.catch(ignoreError);return this.#t=this.#n(e).finally(()=>{this.#t=void 0}),this.#t}async#n(e){return await e(this.#e)}};const Ao=[`read only`,`read write`],jo=[`read uncommitted`,`read committed`,`repeatable read`,`serializable`,`snapshot`];function validateTransactionSettings(e){if(e.accessMode&&!Ao.includes(e.accessMode))throw Error(`invalid transaction access mode ${e.accessMode}`);if(e.isolationLevel&&!jo.includes(e.isolationLevel))throw Error(`invalid transaction isolation level ${e.isolationLevel}`)}freeze([`query`,`error`]);var Log=class{#e;#t;constructor(e){isFunction(e)?(this.#t=e,this.#e=freeze({query:!0,error:!0})):(this.#t=defaultLogger,this.#e=freeze({query:e.includes(`query`),error:e.includes(`error`)}))}isLevelEnabled(e){return this.#e[e]}async query(e){this.#e.query&&await this.#t(e())}async error(e){this.#e.error&&await this.#t(e())}};function defaultLogger(e){if(e.level===`query`){let t=`kysely:query:${e.isStream?`stream:`:``}`;console.log(`${t} ${e.query.sql}`),console.log(`${t} duration: ${e.queryDurationMillis.toFixed(1)}ms`)}else e.level===`error`&&(e.error instanceof Error?console.error(`kysely:error: ${e.error.stack??e.error.message}`):console.error(`kysely:error: ${JSON.stringify({error:e.error,query:e.query.sql,queryDurationMillis:e.queryDurationMillis})}`))}function isCompilable(e){return isObject$1(e)&&isFunction(e.compile)}Symbol.asyncDispose??=Symbol(`Symbol.asyncDispose`);var Mo=class Kysely extends ha{#e;constructor(e){let t,n;if(isKyselyProps(e))t={executor:e.executor},n={...e};else{let r=e.dialect,i=r.createDriver(),a=r.createQueryCompiler(),o=r.createAdapter(),s=new RuntimeDriver(i,o,new Log(e.log??[])),c=new ko(a,o,new DefaultConnectionProvider(s),e.plugins??[]);t={executor:c},n={config:e,executor:c,dialect:r,driver:s}}super(t),this.#e=freeze(n)}get schema(){return new Oo(this.#e.executor)}get dynamic(){return new DynamicModule}get introspection(){return this.#e.dialect.createIntrospector(this.withoutPlugins())}case(e){return new CaseBuilder({node:z.create(isUndefined(e)?void 0:parseExpression(e))})}get fn(){return createFunctionModule()}transaction(){return new Po({...this.#e})}startTransaction(){return new Fo({...this.#e})}connection(){return new ConnectionBuilder({...this.#e})}withPlugin(e){return new Kysely({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new Kysely({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new Kysely({...this.#e,executor:this.#e.executor.withPluginAtFront(new WithSchemaPlugin(e))})}$extendTables(){return new Kysely({...this.#e})}$omitTables(){return new Kysely({...this.#e})}$pickTables(){return new Kysely({...this.#e})}withTables(){return this.$extendTables()}async destroy(){await this.#e.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#e.executor}async executeQuery(e,t){let n=isCompilable(e)?e.compile():e;return await this.#e.executor.executeQuery(n,t)}async[Symbol.asyncDispose](){await this.destroy()}},No=class Transaction extends Mo{#e;constructor(e){super(e),this.#e=e}get isTransaction(){return!0}transaction(){throw Error(`calling the transaction method for a Transaction is not supported`)}startTransaction(){throw Error(`calling the controlled transaction method for a Transaction is not supported`)}connection(){throw Error(`calling the connection method for a Transaction is not supported`)}destroy(){throw Error(`calling the destroy method for a Transaction is not supported`)}withPlugin(e){return new Transaction({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new Transaction({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new Transaction({...this.#e,executor:this.#e.executor.withPluginAtFront(new WithSchemaPlugin(e))})}withTables(){return new Transaction({...this.#e})}$extendTables(){return new Transaction({...this.#e})}$omitTables(){return new Transaction({...this.#e})}$pickTables(){return new Transaction({...this.#e})}};function isKyselyProps(e){return isObject$1(e)&&isObject$1(e.config)&&isObject$1(e.driver)&&isObject$1(e.executor)&&isObject$1(e.dialect)}var ConnectionBuilder=class{#e;constructor(e){this.#e=freeze(e)}async execute(e,t){return this.#e.executor.provideConnection(async t=>{let n=this.#e.executor.withConnectionProvider(new SingleConnectionProvider(t));return await e(new Mo({...this.#e,executor:n}))},freeze({signal:t?.signal}))}},Po=class TransactionBuilder{#e;constructor(e){this.#e=freeze(e)}setAccessMode(e){return new TransactionBuilder({...this.#e,accessMode:e})}setIsolationLevel(e){return new TransactionBuilder({...this.#e,isolationLevel:e})}async execute(e){let{isolationLevel:t,accessMode:n,...r}=this.#e,i={isolationLevel:t,accessMode:n};return validateTransactionSettings(i),this.#e.executor.provideConnection(async t=>{let n={isCommitted:!1,isRolledBack:!1},a=new Lo(this.#e.executor.withConnectionProvider(new SingleConnectionProvider(t)),n),o=new No({...r,executor:a}),s=!1;try{await this.#e.driver.beginTransaction(t,i),s=!0;let r=await e(o);return await this.#e.driver.commitTransaction(t),n.isCommitted=!0,r}catch(e){throw s&&(await this.#e.driver.rollbackTransaction(t),n.isRolledBack=!0),e}})}},Fo=class ControlledTransactionBuilder{#e;constructor(e){this.#e=freeze(e)}setAccessMode(e){return new ControlledTransactionBuilder({...this.#e,accessMode:e})}setIsolationLevel(e){return new ControlledTransactionBuilder({...this.#e,isolationLevel:e})}async execute(){let{isolationLevel:e,accessMode:t,...n}=this.#e,r={isolationLevel:e,accessMode:t};validateTransactionSettings(r);let i=await provideControlledConnection(this.#e.executor);try{await this.#e.driver.beginTransaction(i.connection,r)}catch(e){throw i.release(),e}return new Io({...n,connection:i,state:{isCommitted:!1,isRolledBack:!1},executor:this.#e.executor.withConnectionProvider(new SingleConnectionProvider(i.connection))})}},Io=class ControlledTransaction extends No{#e;#t;constructor(e){e={...e,executor:new Lo(e.executor,e.state)};let{connection:t,state:n,...r}=e;super(r),this.#e=freeze(e);let i=createQueryId();this.#t=t=>e.executor.compileQuery(t,i)}get isCommitted(){return this.#e.state.isCommitted}get isRolledBack(){return this.#e.state.isRolledBack}commit(){return new Command(async()=>{await this.#e.executor.provideConnection(async e=>{await this.#e.driver.commitTransaction(e),this.#e.state.isCommitted=!0,this.#e.connection.release()})})}rollback(){return new Command(async()=>{await this.#e.executor.provideConnection(async e=>{try{await this.#e.driver.rollbackTransaction(e)}finally{this.#e.state.isRolledBack=!0,this.#e.connection.release()}})})}savepoint(e){return new Command(async()=>(await this.#e.executor.provideConnection(async t=>{await this.#e.driver.savepoint?.(t,e,this.#t)}),new ControlledTransaction({...this.#e})))}rollbackToSavepoint(e){return new Command(async()=>(await this.#e.executor.provideConnection(async t=>{await this.#e.driver.rollbackToSavepoint?.(t,e,this.#t)}),new ControlledTransaction({...this.#e})))}releaseSavepoint(e){return new Command(async()=>(await this.#e.executor.provideConnection(async t=>{await this.#e.driver.releaseSavepoint?.(t,e,this.#t)}),new ControlledTransaction({...this.#e})))}withPlugin(e){return new ControlledTransaction({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new ControlledTransaction({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new ControlledTransaction({...this.#e,executor:this.#e.executor.withPluginAtFront(new WithSchemaPlugin(e))})}withTables(){return new ControlledTransaction({...this.#e})}$extendTables(){return new ControlledTransaction({...this.#e})}$omitTables(){return new ControlledTransaction({...this.#e})}$pickTables(){return new ControlledTransaction({...this.#e})}},Command=class{#e;constructor(e){this.#e=e}async execute(){return await this.#e()}};function assertNotCommittedOrRolledBack(e){if(e.isCommitted)throw Error(`Transaction is already committed`);if(e.isRolledBack)throw Error(`Transaction is already rolled back`)}var Lo=class NotCommittedOrRolledBackAssertingExecutor{#e;#t;constructor(e,t){this.#e=e instanceof NotCommittedOrRolledBackAssertingExecutor?e.#e:e,this.#t=t}get adapter(){return this.#e.adapter}get plugins(){return this.#e.plugins}transformQuery(e,t){return this.#e.transformQuery(e,t)}compileQuery(e,t){return this.#e.compileQuery(e,t)}provideConnection(e,t){return assertNotCommittedOrRolledBack(this.#t),this.#e.provideConnection(async t=>(assertNotCommittedOrRolledBack(this.#t),await e(t)),t)}executeQuery(e,t){return assertNotCommittedOrRolledBack(this.#t),this.#e.withConnectionProvider(this).executeQuery(e,t)}stream(e,t,n){return assertNotCommittedOrRolledBack(this.#t),this.#e.withConnectionProvider(this).stream(e,t,n)}withConnectionProvider(e){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withConnectionProvider(e),this.#t)}withPlugin(e){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withPlugin(e),this.#t)}withPlugins(e){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withPlugins(e),this.#t)}withPluginAtFront(e){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withPluginAtFront(e),this.#t)}withoutPlugins(){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withoutPlugins(),this.#t)}},Ro=class RawBuilderImpl{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}get isRawBuilder(){return!0}as(e){return new AliasedRawBuilderImpl(this,e)}$castTo(){return new RawBuilderImpl({...this.#e})}$notNull(){return new RawBuilderImpl(this.#e)}withPlugin(e){return new RawBuilderImpl({...this.#e,plugins:this.#e.plugins===void 0?freeze([e]):freeze([...this.#e.plugins,e])})}toOperationNode(){return this.#n(this.#t())}compile(e){return this.#r(this.#t(e))}async execute(e,t){let n=this.#t(e);return n.executeQuery(this.#r(n),t)}#t(e){let t=e===void 0?fa:e.getExecutor();return this.#e.plugins===void 0?t:t.withPlugins(this.#e.plugins)}#n(e){return e.transformQuery(this.#e.rawNode,this.#e.queryId)}#r(e){return e.compileQuery(this.#n(e),this.#e.queryId)}};function createRawBuilder(e){return new Ro(e)}var AliasedRawBuilderImpl=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}get rawBuilder(){return this.#e}toOperationNode(){return Qr.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():w.create(this.#t))}};const V=Object.assign((e,...t)=>createRawBuilder({queryId:createQueryId(),rawNode:D.create(e,t?.map(parseParameter)??[])}),{ref(e){return createRawBuilder({queryId:createQueryId(),rawNode:D.createWithChild(parseStringReference(e))})},val(e){return createRawBuilder({queryId:createQueryId(),rawNode:D.createWithChild(parseValueExpression(e))})},table(e){return createRawBuilder({queryId:createQueryId(),rawNode:D.createWithChild(parseTable(e))})},id(...e){let t=Array(e.length+1).fill(`.`);return t[0]=``,t[t.length-1]=``,createRawBuilder({queryId:createQueryId(),rawNode:D.create(t,e.map(w.create))})},lit(e){return createRawBuilder({queryId:createQueryId(),rawNode:D.createWithChild(O.createImmediate(e))})},raw(e){return createRawBuilder({queryId:createQueryId(),rawNode:D.createWithSql(e)})},join(e,t=V`, `){let n=Array(Math.max(2*e.length-1,0)),r=t.toOperationNode();for(let t=0;t<e.length;++t)n[2*t]=parseParameter(e[t]),t!==e.length-1&&(n[2*t+1]=r);return createRawBuilder({queryId:createQueryId(),rawNode:D.createWithChildren(n)})}});function parseParameter(e){return isOperationNodeSource(e)?e.toOperationNode():parseValueExpression(e)}var OperationNodeVisitor=class{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#e=freeze({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this),AlterTypeNode:this.visitAlterType.bind(this),AddValueNode:this.visitAddValue.bind(this),RenameValueNode:this.visitRenameValue.bind(this)});visitNode=e=>{this.nodeStack.push(e),this.#e[e.kind](e),this.nodeStack.pop()}};const zo=/'/g,Bo=/['"]/g;var DefaultQueryCompiler=class extends OperationNodeVisitor{#e=``;#t=[];get numParameters(){return this.#t.length}compileQuery(e,t){return this.#e=``,this.#t=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(e),freeze({query:e,queryId:t,sql:this.getSql(),parameters:[...this.#t]})}getSql(){return this.#e}visitSelectQuery(e){let t=this.parentNode!==void 0&&!Di.is(this.parentNode)&&!k.is(this.parentNode)&&!T.is(this.parentNode)&&!mo.is(this.parentNode)&&!va.is(this.parentNode);this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(` `)),t&&this.append(`(`),e.with&&(this.visitNode(e.with),this.append(` `)),this.append(`select`),e.distinctOn&&(this.append(` `),this.compileDistinctOn(e.distinctOn)),e.frontModifiers?.length&&(this.append(` `),this.compileList(e.frontModifiers,` `)),e.top&&(this.append(` `),this.visitNode(e.top)),e.selections&&(this.append(` `),this.compileList(e.selections)),e.from&&(this.append(` `),this.visitNode(e.from)),e.joins&&(this.append(` `),this.compileList(e.joins,` `)),e.where&&(this.append(` `),this.visitNode(e.where)),e.groupBy&&(this.append(` `),this.visitNode(e.groupBy)),e.having&&(this.append(` `),this.visitNode(e.having)),e.setOperations&&(this.append(` `),this.compileList(e.setOperations,` `)),e.orderBy&&(this.append(` `),this.visitNode(e.orderBy)),e.limit&&(this.append(` `),this.visitNode(e.limit)),e.offset&&(this.append(` `),this.visitNode(e.offset)),e.fetch&&(this.append(` `),this.visitNode(e.fetch)),e.endModifiers?.length&&(this.append(` `),this.compileList(this.sortSelectModifiers(e.endModifiers),` `)),t&&this.append(`)`)}visitFrom(e){this.append(`from `),this.compileList(e.froms)}visitSelection(e){this.visitNode(e.selection)}visitColumn(e){this.visitNode(e.column)}compileDistinctOn(e){this.append(`distinct on (`),this.compileList(e),this.append(`)`)}compileList(e,t=`, `){let n=e.length-1;for(let r=0;r<=n;r++)this.visitNode(e[r]),r<n&&this.append(t)}visitWhere(e){this.append(`where `),this.visitNode(e.where)}visitHaving(e){this.append(`having `),this.visitNode(e.having)}visitInsertQuery(e){let t=this.parentNode!==void 0&&!Di.is(this.parentNode)&&!D.is(this.parentNode)&&!Bi.is(this.parentNode);this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(` `)),t&&this.append(`(`),e.with&&(this.visitNode(e.with),this.append(` `)),this.append(e.replace?`replace`:`insert`),e.orAction&&(this.append(` `),this.visitNode(e.orAction)),e.top&&(this.append(` `),this.visitNode(e.top)),e.into&&(this.append(` into `),this.visitNode(e.into)),e.columns&&(this.append(` (`),this.compileList(e.columns),this.append(`)`)),e.output&&(this.append(` `),this.visitNode(e.output)),e.values&&(this.append(` `),this.visitNode(e.values)),e.defaultValues&&(this.append(` `),this.append(`default values`)),e.onConflict&&(this.append(` `),this.visitNode(e.onConflict)),e.onDuplicateKey&&(this.append(` `),this.visitNode(e.onDuplicateKey)),e.returning&&(this.append(` `),this.visitNode(e.returning)),t&&this.append(`)`),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `))}visitValues(e){this.append(`values `),this.compileList(e.values)}visitDeleteQuery(e){let t=this.parentNode!==void 0&&!Di.is(this.parentNode)&&!D.is(this.parentNode);this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(` `)),t&&this.append(`(`),e.with&&(this.visitNode(e.with),this.append(` `)),this.append(`delete `),e.top&&(this.visitNode(e.top),this.append(` `)),this.visitNode(e.from),e.output&&(this.append(` `),this.visitNode(e.output)),e.using&&(this.append(` `),this.visitNode(e.using)),e.joins&&(this.append(` `),this.compileList(e.joins,` `)),e.where&&(this.append(` `),this.visitNode(e.where)),e.returning&&(this.append(` `),this.visitNode(e.returning)),e.orderBy&&(this.append(` `),this.visitNode(e.orderBy)),e.limit&&(this.append(` `),this.visitNode(e.limit)),t&&this.append(`)`),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `))}visitReturning(e){this.append(`returning `),this.compileList(e.selections)}visitAlias(e){this.visitNode(e.node),this.append(` as `),this.visitNode(e.alias)}visitReference(e){e.table&&(this.visitNode(e.table),this.append(`.`)),this.visitNode(e.column)}visitSelectAll(e){this.append(`*`)}visitIdentifier(e){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier(e),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier(e){if(!isString(e.name))throw Error(`a non-string identifier was passed to compileUnwrappedIdentifier.`);this.append(this.sanitizeIdentifier(e.name))}visitAnd(e){this.visitNode(e.left),this.append(` and `),this.visitNode(e.right)}visitOr(e){this.visitNode(e.left),this.append(` or `),this.visitNode(e.right)}visitValue(e){e.immediate?this.appendImmediateValue(e.value):this.appendValue(e.value)}visitValueList(e){this.append(`(`),this.compileList(e.values),this.append(`)`)}visitTuple(e){this.append(`(`),this.compileList(e.values),this.append(`)`)}visitPrimitiveValueList(e){this.append(`(`);let{values:t}=e;for(let e=0;e<t.length;++e)this.appendValue(t[e]),e!==t.length-1&&this.append(`, `);this.append(`)`)}visitParens(e){this.append(`(`),this.visitNode(e.node),this.append(`)`)}visitJoin(e){this.append(Uo[e.joinType]),this.append(` `),this.visitNode(e.table),e.on&&(this.append(` `),this.visitNode(e.on))}visitOn(e){this.append(`on `),this.visitNode(e.on)}visitRaw(e){let{sqlFragments:t,parameters:n}=e;for(let e=0;e<t.length;++e)this.append(t[e]),n.length>e&&this.visitNode(n[e])}visitOperator(e){this.append(e.operator)}visitTable(e){this.visitNode(e.table)}visitSchemableIdentifier(e){e.schema&&(this.visitNode(e.schema),this.append(`.`)),this.visitNode(e.identifier)}visitCreateTable(e){this.append(`create `),e.frontModifiers?.length&&(this.compileList(e.frontModifiers,` `),this.append(` `)),e.temporary&&this.append(`temporary `),this.append(`table `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.table),e.selectQuery||(this.append(` (`),this.compileList([...e.columns,...e.constraints??[],...e.indexes??[]]),this.append(`)`)),e.onCommit&&(this.append(` on commit `),this.append(e.onCommit)),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `)),e.selectQuery&&(this.append(` as `),this.visitNode(e.selectQuery))}visitColumnDefinition(e){e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.column),this.append(` `),this.visitNode(e.dataType),e.unsigned&&this.append(` unsigned`),e.frontModifiers&&e.frontModifiers.length>0&&(this.append(` `),this.compileList(e.frontModifiers,` `)),e.generated&&(this.append(` `),this.visitNode(e.generated)),e.identity&&this.append(` identity`),e.defaultTo&&(this.append(` `),this.visitNode(e.defaultTo)),e.notNull&&this.append(` not null`),e.unique&&this.append(` unique`),e.nullsNotDistinct&&this.append(` nulls not distinct`),e.primaryKey&&this.append(` primary key`),e.autoIncrement&&(this.append(` `),this.append(this.getAutoIncrement())),e.references&&(this.append(` `),this.visitNode(e.references)),e.check&&(this.append(` `),this.visitNode(e.check)),e.endModifiers&&e.endModifiers.length>0&&(this.append(` `),this.compileList(e.endModifiers,` `))}getAutoIncrement(){return`auto_increment`}visitReferences(e){this.append(`references `),this.visitNode(e.table),this.append(` (`),this.compileList(e.columns),this.append(`)`),e.onDelete&&(this.append(` on delete `),this.append(e.onDelete)),e.onUpdate&&(this.append(` on update `),this.append(e.onUpdate))}visitDropTable(e){this.append(`drop `),e.temporary&&this.append(`temporary `),this.append(`table `),e.ifExists&&this.append(`if exists `),this.visitNode(e.table),e.cascade&&this.append(` cascade`)}visitDataType(e){this.append(e.dataType)}visitOrderBy(e){this.append(`order by `),this.compileList(e.items)}visitOrderByItem(e){this.visitNode(e.orderBy),e.collation&&(this.append(` `),this.visitNode(e.collation)),e.direction&&(this.append(` `),this.visitNode(e.direction)),e.nulls&&(this.append(` nulls `),this.append(e.nulls))}visitGroupBy(e){this.append(`group by `),this.compileList(e.items)}visitGroupByItem(e){this.visitNode(e.groupBy)}visitUpdateQuery(e){let t=this.parentNode!==void 0&&!Di.is(this.parentNode)&&!D.is(this.parentNode)&&!Bi.is(this.parentNode);if(this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(` `)),t&&this.append(`(`),e.with&&(this.visitNode(e.with),this.append(` `)),this.append(`update `),e.top&&(this.visitNode(e.top),this.append(` `)),e.table&&(this.visitNode(e.table),this.append(` `)),this.append(`set `),e.updates&&this.compileList(e.updates),e.output&&(this.append(` `),this.visitNode(e.output)),e.from&&(this.append(` `),this.visitNode(e.from)),e.joins){if(!e.from)throw Error(`Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins`);this.append(` `),this.compileList(e.joins,` `)}e.where&&(this.append(` `),this.visitNode(e.where)),e.returning&&(this.append(` `),this.visitNode(e.returning)),e.orderBy&&(this.append(` `),this.visitNode(e.orderBy)),e.limit&&(this.append(` `),this.visitNode(e.limit)),t&&this.append(`)`),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `))}visitColumnUpdate(e){this.visitNode(e.column),this.append(` = `),this.visitNode(e.value)}visitLimit(e){this.append(`limit `),this.visitNode(e.limit)}visitOffset(e){this.append(`offset `),this.visitNode(e.offset)}visitOnConflict(e){this.append(`on conflict`),e.columns?(this.append(` (`),this.compileList(e.columns),this.append(`)`)):e.constraint?(this.append(` on constraint `),this.visitNode(e.constraint)):e.indexExpression&&(this.append(` (`),this.visitNode(e.indexExpression),this.append(`)`)),e.indexWhere&&(this.append(` `),this.visitNode(e.indexWhere)),e.doNothing===!0?this.append(` do nothing`):e.updates&&(this.append(` do update set `),this.compileList(e.updates),e.updateWhere&&(this.append(` `),this.visitNode(e.updateWhere)))}visitOnDuplicateKey(e){this.append(`on duplicate key update `),this.compileList(e.updates)}visitCreateIndex(e){this.append(`create `),e.unique&&this.append(`unique `),this.append(`index `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.name),e.table&&(this.append(` on `),this.visitNode(e.table)),e.using&&(this.append(` using `),this.visitNode(e.using)),e.columns&&(this.append(` (`),this.compileList(e.columns),this.append(`)`)),e.nullsNotDistinct&&this.append(` nulls not distinct`),e.where&&(this.append(` `),this.visitNode(e.where))}visitDropIndex(e){this.append(`drop index `),e.ifExists&&this.append(`if exists `),this.visitNode(e.name),e.table&&(this.append(` on `),this.visitNode(e.table)),e.cascade&&this.append(` cascade`)}visitCreateSchema(e){this.append(`create schema `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.schema)}visitDropSchema(e){this.append(`drop schema `),e.ifExists&&this.append(`if exists `),this.visitNode(e.schema),e.cascade&&this.append(` cascade`)}visitPrimaryKeyConstraint(e){e.name&&(this.append(`constraint `),this.visitNode(e.name),this.append(` `)),this.append(`primary key (`),this.compileList(e.columns),this.append(`)`),this.buildDeferrable(e)}buildDeferrable(e){e.deferrable!==void 0&&(e.deferrable?this.append(` deferrable`):this.append(` not deferrable`)),e.initiallyDeferred!==void 0&&(e.initiallyDeferred?this.append(` initially deferred`):this.append(` initially immediate`))}visitUniqueConstraint(e){e.name&&(this.append(`constraint `),this.visitNode(e.name),this.append(` `)),this.append(`unique`),e.nullsNotDistinct&&this.append(` nulls not distinct`),this.append(` (`),this.compileList(e.columns),this.append(`)`),this.buildDeferrable(e)}visitCheckConstraint(e){e.name&&(this.append(`constraint `),this.visitNode(e.name),this.append(` `)),this.append(`check (`),this.visitNode(e.expression),this.append(`)`)}visitForeignKeyConstraint(e){e.name&&(this.append(`constraint `),this.visitNode(e.name),this.append(` `)),this.append(`foreign key (`),this.compileList(e.columns),this.append(`) `),this.visitNode(e.references),e.onDelete&&(this.append(` on delete `),this.append(e.onDelete)),e.onUpdate&&(this.append(` on update `),this.append(e.onUpdate)),this.buildDeferrable(e)}visitList(e){this.compileList(e.items)}visitWith(e){this.append(`with `),e.recursive&&this.append(`recursive `),this.compileList(e.expressions)}visitCommonTableExpression(e){this.visitNode(e.name),this.append(` as `),isBoolean(e.materialized)&&(e.materialized||this.append(`not `),this.append(`materialized `)),this.visitNode(e.expression)}visitCommonTableExpressionName(e){this.visitNode(e.table),e.columns&&(this.append(`(`),this.compileList(e.columns),this.append(`)`))}visitAlterTable(e){this.append(`alter table `),this.visitNode(e.table),this.append(` `),e.renameTo&&(this.append(`rename to `),this.visitNode(e.renameTo)),e.setSchema&&(this.append(`set schema `),this.visitNode(e.setSchema)),e.addConstraint&&this.visitNode(e.addConstraint),e.dropConstraint&&this.visitNode(e.dropConstraint),e.renameConstraint&&this.visitNode(e.renameConstraint),e.columnAlterations&&this.compileColumnAlterations(e.columnAlterations),e.addIndex&&this.visitNode(e.addIndex),e.dropIndex&&this.visitNode(e.dropIndex)}visitAddColumn(e){this.append(`add column `),this.visitNode(e.column)}visitRenameColumn(e){this.append(`rename column `),this.visitNode(e.column),this.append(` to `),this.visitNode(e.renameTo)}visitDropColumn(e){this.append(`drop column `),e.ifExists&&this.append(`if exists `),this.visitNode(e.column)}visitAlterColumn(e){this.append(`alter column `),this.visitNode(e.column),this.append(` `),e.dataType&&(this.announcesNewColumnDataType()&&this.append(`type `),this.visitNode(e.dataType),e.dataTypeExpression&&(this.append(`using `),this.visitNode(e.dataTypeExpression))),e.setDefault&&(this.append(`set default `),this.visitNode(e.setDefault)),e.dropDefault&&this.append(`drop default`),e.setNotNull&&this.append(`set not null`),e.dropNotNull&&this.append(`drop not null`)}visitModifyColumn(e){this.append(`modify column `),this.visitNode(e.column)}visitAddConstraint(e){this.append(`add `),this.visitNode(e.constraint)}visitDropConstraint(e){this.append(`drop constraint `),e.ifExists&&this.append(`if exists `),this.visitNode(e.constraintName),e.modifier===`cascade`?this.append(` cascade`):e.modifier===`restrict`&&this.append(` restrict`)}visitRenameConstraint(e){this.append(`rename constraint `),this.visitNode(e.oldName),this.append(` to `),this.visitNode(e.newName)}visitSetOperation(e){this.append(e.operator),this.append(` `),e.all&&this.append(`all `),this.visitNode(e.expression)}visitCreateView(e){this.append(`create `),e.orReplace&&this.append(`or replace `),e.materialized&&this.append(`materialized `),e.temporary&&this.append(`temporary `),this.append(`view `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.name),this.append(` `),e.columns&&(this.append(`(`),this.compileList(e.columns),this.append(`) `)),e.as&&(this.append(`as `),this.visitNode(e.as))}visitRefreshMaterializedView(e){this.append(`refresh materialized view `),e.concurrently&&this.append(`concurrently `),this.visitNode(e.name),e.withNoData?this.append(` with no data`):this.append(` with data`)}visitDropView(e){this.append(`drop `),e.materialized&&this.append(`materialized `),this.append(`view `),e.ifExists&&this.append(`if exists `),this.visitNode(e.name),e.cascade&&this.append(` cascade`)}visitGenerated(e){this.append(`generated `),e.always&&this.append(`always `),e.byDefault&&this.append(`by default `),this.append(`as `),e.identity&&this.append(`identity`),e.expression&&(this.append(`(`),this.visitNode(e.expression),this.append(`)`)),e.stored&&this.append(` stored`)}visitDefaultValue(e){this.append(`default `),this.visitNode(e.defaultValue)}visitSelectModifier(e){e.rawModifier?this.visitNode(e.rawModifier):this.append(Vo[e.modifier]),e.of&&(this.append(` of `),this.compileList(e.of,`, `))}visitCreateType(e){this.append(`create type `),this.visitNode(e.name),e.enum&&(this.append(` as enum `),this.visitNode(e.enum))}visitDropType(e){this.append(`drop type `),e.ifExists&&this.append(`if exists `),this.visitNode(e.name),e.additionalNames?.length&&(this.append(`, `),this.compileList(e.additionalNames)),e.cascade&&this.append(` cascade`)}visitAlterType(e){this.append(`alter type `),this.visitNode(e.name),this.append(` `),e.addValue?this.visitNode(e.addValue):e.renameTo?(this.append(`rename to `),this.visitNode(e.renameTo)):e.renameValue?this.visitNode(e.renameValue):e.setSchema&&(this.append(`set schema `),this.visitNode(e.setSchema))}visitAddValue(e){this.append(`add value `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.value),e.neighborValue&&(this.append(e.isBefore?` before `:` after `),this.visitNode(e.neighborValue))}visitRenameValue(e){this.append(`rename value `),this.visitNode(e.oldValue),this.append(` to `),this.visitNode(e.newValue)}visitExplain(e){this.append(`explain`),(e.options||e.format)&&(this.append(` `),this.append(this.getLeftExplainOptionsWrapper()),e.options&&(this.visitNode(e.options),e.format&&this.append(this.getExplainOptionsDelimiter())),e.format&&(this.append(`format`),this.append(this.getExplainOptionAssignment()),this.append(e.format)),this.append(this.getRightExplainOptionsWrapper()))}visitDefaultInsertValue(e){this.append(`default`)}visitAggregateFunction(e){this.append(e.func),this.append(`(`),e.distinct&&this.append(`distinct `),this.compileList(e.aggregated),e.orderBy&&(this.append(` `),this.visitNode(e.orderBy)),this.append(`)`),e.withinGroup&&(this.append(` within group (`),this.visitNode(e.withinGroup),this.append(`)`)),e.filter&&(this.append(` filter(`),this.visitNode(e.filter),this.append(`)`)),e.over&&(this.append(` `),this.visitNode(e.over))}visitOver(e){this.append(`over(`),e.partitionBy&&(this.visitNode(e.partitionBy),e.orderBy&&this.append(` `)),e.orderBy&&this.visitNode(e.orderBy),this.append(`)`)}visitPartitionBy(e){this.append(`partition by `),this.compileList(e.items)}visitPartitionByItem(e){this.visitNode(e.partitionBy)}visitBinaryOperation(e){this.visitNode(e.leftOperand),this.append(` `),this.visitNode(e.operator),this.append(` `),this.visitNode(e.rightOperand)}visitUnaryOperation(e){this.visitNode(e.operator),this.isMinusOperator(e.operator)||this.append(` `),this.visitNode(e.operand)}isMinusOperator(e){return hi.is(e)&&e.operator===`-`}visitUsing(e){this.append(`using `),this.compileList(e.tables)}visitFunction(e){this.append(e.func),this.append(`(`),this.compileList(e.arguments),this.append(`)`)}visitCase(e){this.append(`case`),e.value&&(this.append(` `),this.visitNode(e.value)),e.when&&(this.append(` `),this.compileList(e.when,` `)),e.else&&(this.append(` else `),this.visitNode(e.else)),this.append(` end`),e.isStatement&&this.append(` case`)}visitWhen(e){this.append(`when `),this.visitNode(e.condition),e.result&&(this.append(` then `),this.visitNode(e.result))}visitJSONReference(e){this.visitNode(e.reference),this.visitNode(e.traversal)}visitJSONPath(e){e.inOperator&&this.visitNode(e.inOperator),this.append(`'$`);for(let t of e.pathLegs)this.visitNode(t);this.append(`'`)}visitJSONPathLeg(e){let t=e.type===`ArrayLocation`,n=String(e.value);t?(this.append(`[`),this.append(this.sanitizeStringLiteral(n)),this.append(`]`)):(this.append(`."`),this.append(this.sanitizeJSONPathMemberValue(n)),this.append(`"`))}visitJSONOperatorChain(e){for(let t=0,n=e.values.length;t<n;t++)t===n-1?this.visitNode(e.operator):this.append(`->`),this.visitNode(e.values[t])}visitMergeQuery(e){e.with&&(this.visitNode(e.with),this.append(` `)),this.append(`merge `),e.top&&(this.visitNode(e.top),this.append(` `)),this.append(`into `),this.visitNode(e.into),e.using&&(this.append(` `),this.visitNode(e.using)),e.whens&&(this.append(` `),this.compileList(e.whens,` `)),e.returning&&(this.append(` `),this.visitNode(e.returning)),e.output&&(this.append(` `),this.visitNode(e.output)),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `))}visitMatched(e){e.not&&this.append(`not `),this.append(`matched`),e.bySource&&this.append(` by source`)}visitAddIndex(e){this.parentNode&&T.is(this.parentNode)||this.append(`add `),e.unique&&this.append(`unique `),this.append(`index `),this.visitNode(e.name),e.columns&&(this.append(` (`),this.compileList(e.columns),this.append(`)`)),e.using&&(this.append(` using `),this.visitNode(e.using))}visitCast(e){this.append(`cast(`),this.visitNode(e.expression),this.append(` as `),this.visitNode(e.dataType),this.append(`)`)}visitFetch(e){this.append(`fetch next `),this.visitNode(e.rowCount),this.append(` rows ${e.modifier}`)}visitOutput(e){this.append(`output `),this.compileList(e.selections)}visitTop(e){this.append(`top(${e.expression})`),e.modifiers&&this.append(` ${e.modifiers}`)}visitOrAction(e){this.append(e.action)}visitCollate(e){this.append(`collate `),this.visitNode(e.collation)}append(e){this.#e+=e}appendValue(e){this.addParameter(e),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return`"`}getRightIdentifierWrapper(){return`"`}getCurrentParameterPlaceholder(){return`$`+this.numParameters}getLeftExplainOptionsWrapper(){return`(`}getExplainOptionAssignment(){return` `}getExplainOptionsDelimiter(){return`, `}getRightExplainOptionsWrapper(){return`)`}sanitizeIdentifier(e){let t=this.getLeftIdentifierWrapper(),n=this.getRightIdentifierWrapper(),r=``;for(let i of e)r+=i,i===t?r+=t:i===n&&(r+=n);return r}sanitizeStringLiteral(e){return e.replace(zo,`''`)}sanitizeJSONPathMemberValue(e){return e.replace(Bo,e=>e===`'`?`''`:`\\"`)}addParameter(e){this.#t.push(e)}appendImmediateValue(e){if(isString(e))this.appendStringLiteral(e);else if(isNumber(e)||isBoolean(e)||isBigInt(e))this.append(e.toString());else if(isNull(e))this.append(`null`);else if(isDate(e))this.appendImmediateValue(e.toISOString());else throw Error(`invalid immediate value ${e}`)}appendStringLiteral(e){this.append(`'`),this.append(this.sanitizeStringLiteral(e)),this.append(`'`)}sortSelectModifiers(e){return freeze(e.toSorted((e,t)=>e.modifier&&t.modifier?Ho[e.modifier]-Ho[t.modifier]:1))}compileColumnAlterations(e){this.compileList(e)}announcesNewColumnDataType(){return!0}};const Vo=freeze({ForKeyShare:`for key share`,ForNoKeyUpdate:`for no key update`,ForUpdate:`for update`,ForShare:`for share`,NoWait:`nowait`,SkipLocked:`skip locked`,Distinct:`distinct`}),Ho=freeze({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),Uo=freeze({InnerJoin:`inner join`,LeftJoin:`left join`,RightJoin:`right join`,FullJoin:`full join`,CrossJoin:`cross join`,LateralInnerJoin:`inner join lateral`,LateralLeftJoin:`left join lateral`,LateralCrossJoin:`cross join lateral`,OuterApply:`outer apply`,CrossApply:`cross apply`,Using:`using`}),Wo=freeze({raw(e,t=[]){return freeze({sql:e,query:D.createWithSql(e),parameters:freeze(t),queryId:createQueryId()})}});var DialectAdapterBase=class{get supportsCreateIfNotExists(){return!0}get supportsMultipleConnections(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}};function parseSavepointCommand(e,t){return D.createWithChildren([D.createWithSql(`${e} `),w.create(t)])}var SqliteDriver=class{#e;#t;#n;constructor(e){this.#e=freeze({...e})}async init(e){this.#t=isFunction(this.#e.database)?await this.#e.database(e):this.#e.database,this.#n=new SqliteConnection(this.#t),this.#e.onCreateConnection&&await this.#e.onCreateConnection(this.#n,e)}async acquireConnection(){return this.#n}async beginTransaction(e){await e.executeQuery(Wo.raw(`begin`))}async commitTransaction(e){await e.executeQuery(Wo.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(Wo.raw(`rollback`))}async savepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`savepoint`,t),createQueryId()))}async rollbackToSavepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`rollback to`,t),createQueryId()))}async releaseSavepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`release`,t),createQueryId()))}async releaseConnection(){}async destroy(){this.#t?.close()}},SqliteConnection=class{#e;constructor(e){this.#e=e}async executeQuery(e){let{sql:t,parameters:n}=e,r=this.#e.prepare(t);if(r.reader)return{rows:r.all(n)};let{changes:i,lastInsertRowid:a}=r.run(n);return{insertId:a==null?void 0:BigInt(a),numAffectedRows:i==null?void 0:BigInt(i),rows:[]}}async*streamQuery(e,t){let{sql:n,parameters:r,query:i}=e,a=this.#e.prepare(n);if(!M.is(i))throw Error(`Sqlite driver only supports streaming of select queries`);let o=a.iterate(r);for(let e of o)yield{rows:[e]}}};const Go=/"/g,Ko=/[\\'"]/g;var SqliteQueryCompiler=class extends DefaultQueryCompiler{visitOrAction(e){this.append(`or `),this.append(e.action)}getCurrentParameterPlaceholder(){return`?`}getLeftExplainOptionsWrapper(){return``}getRightExplainOptionsWrapper(){return``}getLeftIdentifierWrapper(){return`"`}getRightIdentifierWrapper(){return`"`}getAutoIncrement(){return`autoincrement`}sanitizeIdentifier(e){return e.replace(Go,`""`)}sanitizeJSONPathMemberValue(e){return e.replace(Ko,e=>e===`\\`?`\\\\`:e===`'`?`''`:`\\"`)}visitDefaultInsertValue(e){this.append(`null`)}};const qo=`kysely_migration`,Jo=`kysely_migration_lock`;freeze({__noMigrations__:!0});var SqliteIntrospector=class{#e;constructor(e){this.#e=e}async getSchemas(){return[]}async getTables(e={withInternalKyselyTables:!1}){return await this.#n(e)}#t(e,t){let n=e.selectFrom(`sqlite_master`).where(`type`,`in`,[`table`,`view`]).where(`name`,`not like`,`sqlite_%`).select([`name`,`sql`,`type`]).orderBy(`name`);return t.withInternalKyselyTables||(n=n.where(`name`,`!=`,qo).where(`name`,`!=`,Jo)),n}async#n(e){let t=await this.#t(this.#e,e).execute(),n=await this.#e.with(`table_list`,t=>this.#t(t,e)).selectFrom([`table_list as tl`,V`pragma_table_info(tl.name)`.as(`p`)]).select([`tl.name as table`,`p.cid`,`p.name`,`p.type`,`p.notnull`,`p.dflt_value`,`p.pk`]).orderBy(`tl.name`).orderBy(`p.cid`).execute(),r={};for(let e of n)r[e.table]??=[],r[e.table].push(e);return t.map(({name:e,sql:t,type:n})=>{let i=t?.split(/[\(\),]/)?.find(e=>e.toLowerCase().includes(`autoincrement`))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,``),a=r[e]??[];if(!i){let e=a.filter(e=>e.pk>0);e.length===1&&e[0].type.toLowerCase()===`integer`&&(i=e[0].name)}return{name:e,isView:n===`view`,isForeign:!1,columns:a.map(e=>({name:e.name,dataType:e.type,isNullable:!e.notnull,isAutoIncrementing:e.name===i,hasDefaultValue:e.dflt_value!=null,comment:void 0}))}})}},SqliteAdapter=class extends DialectAdapterBase{get supportsMultipleConnections(){return!1}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(e,t){}async releaseMigrationLock(e,t){}},SqliteDialect=class{#e;constructor(e){this.#e=freeze({...e})}createDriver(){return new SqliteDriver(this.#e)}createQueryCompiler(){return new SqliteQueryCompiler}createAdapter(){return new SqliteAdapter}createIntrospector(e){return new SqliteIntrospector(e)}};function extendStackTrace(e,t){if(isStackHolder(e)&&t.stack){let n=t.stack.split(`
`).slice(1).join(`
`);return e.stack+=`\n${n}`,e}return e}function isStackHolder(e){return isObject$1(e)&&isString(e.stack)}const Yo=Symbol();var PostgresDriver=class{#e;#t=/* @__PURE__ */ new WeakMap;#n;constructor(e){this.#e=freeze({...e})}async init(e){this.#n=isFunction(this.#e.pool)?await this.#e.pool(e):this.#e.pool}async acquireConnection(e){let t=await this.#n.connect();if(!this.#n)throw t.release(),Error(`driver has already been destroyed`);let n=this.#t.get(t);return n||(n=new PostgresConnection(t,{controlClient:this.#e.controlClient||this.#n.Client,cursor:this.#e.cursor??null,poolOptions:this.#n.options}),this.#t.set(t,n),this.#e.onCreateConnection&&await this.#e.onCreateConnection(n,e)),this.#e.onReserveConnection&&await this.#e.onReserveConnection(n,e),n}async beginTransaction(e,t){let n=`begin`;(t.isolationLevel||t.accessMode)&&(n=`start transaction`,t.isolationLevel&&(n+=` isolation level ${t.isolationLevel}`),t.accessMode&&(n+=` ${t.accessMode}`)),await e.executeQuery(Wo.raw(n))}async commitTransaction(e){await e.executeQuery(Wo.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(Wo.raw(`rollback`))}async savepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`savepoint`,t),createQueryId()))}async rollbackToSavepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`rollback to`,t),createQueryId()))}async releaseSavepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`release`,t),createQueryId()))}async releaseConnection(e){e[Yo]()}async destroy(){if(this.#n){let e=this.#n;this.#n=void 0,await e.end()}}},PostgresConnection=class{#e;#t;#n;#r;constructor(e,t){this.#e=e,this.#t=t}async cancelQuery(e){return await this.#i(`select pg_cancel_backend(${this.#r})`,e)}async collectSessionInfo(){if(this.#r)return;let{processID:e}=this.#e;if(e)this.#r=e;else{let{rows:[{pid:e}]}=await this.#e.query(`select pg_backend_pid() as pid`,[]);this.#r=Number(e)}}async executeQuery(e){try{this.#n=e.queryId;let{command:t,rowCount:n,rows:r}=await this.#e.query(e.sql,e.parameters);return{numAffectedRows:t===`INSERT`||t===`UPDATE`||t===`DELETE`||t===`MERGE`?BigInt(n):void 0,rows:r??[]}}catch(e){throw extendStackTrace(e,/* @__PURE__ */ Error())}finally{this.#n=void 0}}async killSession(e){return await this.#i(`select pg_terminate_backend(${this.#r})`,e)}async*streamQuery(e,t){if(!this.#t.cursor)throw Error("`cursor` is not present in your postgres dialect config. It's required to make streaming work in postgres.");this.#n=e.queryId;let n=this.#e.query(new this.#t.cursor(e.sql,e.parameters.slice()));try{for(;;){let e=await n.read(t);if(e.length===0)break;yield{rows:e}}}finally{await n.close(),this.#n=void 0}}[Yo](){this.#e.release()}async#i(e,t){if(!this.#n)return;let{controlClient:n,poolOptions:r}=this.#t,i=this.#n;if(!n)return await t(async t=>{i.queryId===this.#n?.queryId&&await t.executeQuery(Wo.raw(e,[]))});let a=new n({...r,password:`password`in r?r.password:void 0});try{if(await a.connect(),i.queryId!==this.#n.queryId)return;await a.query(e,[])}finally{a.end()}}},PostgresIntrospector=class{#e;constructor(e){this.#e=e}async getSchemas(){return(await this.#e.selectFrom(`pg_catalog.pg_namespace`).select(`nspname`).$castTo().execute()).map(e=>({name:e.nspname}))}async getTables(e={withInternalKyselyTables:!1}){let t=this.#e.selectFrom(`pg_catalog.pg_attribute as a`).innerJoin(`pg_catalog.pg_class as c`,`a.attrelid`,`c.oid`).innerJoin(`pg_catalog.pg_namespace as ns`,`c.relnamespace`,`ns.oid`).innerJoin(`pg_catalog.pg_type as typ`,`a.atttypid`,`typ.oid`).innerJoin(`pg_catalog.pg_namespace as dtns`,`typ.typnamespace`,`dtns.oid`).select([`a.attname as column`,`a.attnotnull as not_null`,`a.atthasdef as has_default`,`c.relname as table`,`c.relkind as table_type`,`ns.nspname as schema`,`typ.typname as type`,`dtns.nspname as type_schema`,V`col_description(a.attrelid, a.attnum)`.as(`column_description`),V`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as(`auto_incrementing`)]).where(`c.relkind`,`in`,[`r`,`v`,`p`,`f`]).where(`ns.nspname`,`!~`,`^pg_`).where(`ns.nspname`,`!=`,`information_schema`).where(`ns.nspname`,`!=`,`crdb_internal`).where(V`has_schema_privilege(ns.nspname, 'USAGE')`).where(`a.attnum`,`>=`,0).where(`a.attisdropped`,`!=`,!0).orderBy(`ns.nspname`).orderBy(`c.relname`).orderBy(`a.attnum`).$castTo();e.withInternalKyselyTables||(t=t.where(`c.relname`,`!=`,qo).where(`c.relname`,`!=`,Jo));let n=await t.execute();return this.#t(n)}#t(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e){let e=n.get(r.schema);e||(e=/* @__PURE__ */ new Map,n.set(r.schema,e));let i=e.get(r.table);i||(i=freeze({columns:[],isForeign:r.table_type===`f`,isView:r.table_type===`v`,name:r.table,schema:r.schema}),e.set(r.table,i),t.push(i)),i.columns.push(freeze({comment:r.column_description??void 0,dataType:r.type,dataTypeSchema:r.type_schema,hasDefaultValue:r.has_default,isAutoIncrementing:r.auto_incrementing!==null,isNullable:!r.not_null,name:r.column}))}return t}};const Xo=/"/g;var PostgresQueryCompiler=class extends DefaultQueryCompiler{sanitizeIdentifier(e){return e.replace(Xo,`""`)}};const Zo=BigInt(`3853314791062309107`);var PostgresAdapter=class extends DialectAdapterBase{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(e,t){await V`
    with set_timeout as (
      select set_config('lock_timeout', '${V.lit(36e5)}', true) as config_val
    )
    select pg_advisory_lock(${V.lit(Zo)})
    from set_timeout`.execute(e)}async releaseMigrationLock(e,t){await V`select pg_advisory_unlock(${V.lit(Zo)})`.execute(e)}},PostgresDialect=class{#e;constructor(e){this.#e=e}createDriver(){return new PostgresDriver(this.#e)}createQueryCompiler(){return new PostgresQueryCompiler}createAdapter(){return new PostgresAdapter}createIntrospector(e){return new PostgresIntrospector(e)}};const Qo=/^v?((?:0|[1-9]\d*))\.((?:0|[1-9]\d*))\.((?:0|[1-9]\d*))(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u,$o=[{major:24,minor:16,patch:0},{major:26,minor:1,patch:0}],es=$o[$o.length-1];`${$o.map(({major:e,minor:t,patch:n},r)=>`>=${e}.${t}.${n}${r<$o.length-1?` <${e+1}`:``}`).join(` || `).replaceAll(` || `,`, `).replace(/, ([^,]+)$/,`, or $1`)}`;function parseNodeReleaseVersion(e){if(typeof e!=`string`)return null;let t=Qo.exec(e.trim());if(!t)return null;let n={major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3])};return Object.values(n).every(Number.isSafeInteger)&&(!t[4]||n.major>es.major)?n:null}function isNodeVersionAtLeast(e,t){return e?e.major===t.major?e.minor===t.minor?e.patch>=t.patch:e.minor>t.minor:e.major>t.major:!1}function renderProcessNodeVersionCheck(){return`((value) => {
  if (typeof value !== "string") return false;
  const match = new RegExp(${JSON.stringify(Qo.source)}, "u").exec(value.trim());
  if (!match) return false;
  const version = { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]) };
  if (!Object.values(version).every(Number.isSafeInteger)) return false;
  const floors = ${JSON.stringify($o)};
  if (match[4] && version.major <= floors[floors.length - 1].major) return false;
  const minimum = floors.find((floor) => floor.major === version.major);
  const atLeast = (floor) =>
    version.major > floor.major ||
    (version.major === floor.major &&
      (version.minor > floor.minor ||
        (version.minor === floor.minor && version.patch >= floor.patch)));
  return minimum ? atLeast(minimum) : version.major > floors[floors.length - 1].major;
})(process.versions.node)`}renderProcessNodeVersionCheck();const templateFragments=(e,t)=>e,ts=templateFragments`(SELECT value FROM json_each(${0}))`,ns=templateFragments`json_each(${0})`;function postgresStringArray(e){if(!D.is(e)||e.sqlFragments!==ts||e.parameters.length!==1)return;let t=e.parameters[0];for(;D.is(t)&&t.parameters.length===1&&t.sqlFragments.length===2&&t.sqlFragments.every(e=>e===``);)t=t.parameters[0];if(!O.is(t)||t.immediate||typeof t.value!=`string`)return;let n;try{n=JSON.parse(t.value)}catch{return}if(Array.isArray(n)&&n.every(e=>typeof e==`string`))return`{${n.map(e=>`"${e.replace(/["\\]/g,`\\$&`)}"`).join(`,`)}}`}var OpenClawPostgresQueryCompiler=class extends PostgresQueryCompiler{visitBinaryOperation(e){if(hi.is(e.operator)&&e.operator.operator===`in`){let t=postgresStringArray(e.rightOperand);if(t!==void 0){this.visitNode(e.leftOperand),this.append(` = ANY(`),this.appendValue(t),this.append(`::text[])`);return}}super.visitBinaryOperation(e)}visitRaw(e){let t=e.sqlFragments===ts;!t&&e.sqlFragments!==ns?super.visitRaw(e):(this.append(t?`(SELECT value FROM json_array_elements_text(`:`(SELECT ordinality - 1 AS key, value FROM json_array_elements_text(`),this.compileList(e.parameters),this.append(t?`::json) AS value)`:`::json) WITH ORDINALITY AS entries(value, ordinality))`))}},OpenClawPostgresDialect=class extends PostgresDialect{createQueryCompiler(){return new OpenClawPostgresQueryCompiler}};const rs=`ai.openclaw.node`,is=`OpenClaw Node`;function normalizeGatewayProfile(e){let t=e?.trim();return t&&de(t)!=="default"?t:null}function resolveGatewayProfileSuffix(e){let t=normalizeGatewayProfile(e);return t?`-${t}`:``}function resolveNodeLaunchAgentLabel(e){let t=normalizeGatewayProfile(e);return t?`${rs}.${t}`:rs}function resolveNodeSystemdServiceName(e){return`openclaw-node${resolveGatewayProfileSuffix(e)}`}function resolveNodeWindowsTaskName(e){let t=normalizeGatewayProfile(e);return t?`${is} (${t})`:is}function resolveNodeServiceIdentityEnvironment(e={}){let t=e.OPENCLAW_PROFILE;return{OPENCLAW_PROFILE:t,OPENCLAW_LAUNCHD_LABEL:resolveNodeLaunchAgentLabel(t),OPENCLAW_SYSTEMD_UNIT:resolveNodeSystemdServiceName(t),OPENCLAW_WINDOWS_TASK_NAME:resolveNodeWindowsTaskName(t),OPENCLAW_WINDOWS_TASK_HIDDEN_LAUNCHER:`1`,OPENCLAW_TASK_SCRIPT_NAME:`node.cmd`,OPENCLAW_LOG_PREFIX:`node${resolveGatewayProfileSuffix(t)}`,OPENCLAW_SERVICE_MARKER:`openclaw`,OPENCLAW_SERVICE_KIND:`node`}}const as=parseNodeReleaseVersion(process.versions.node),os=!process.versions.bun&&(as?.major===24&&isNodeVersionAtLeast(as,{major:24,minor:20,patch:0})||isNodeVersionAtLeast(as,{major:26,minor:6,patch:0})),ss=new SqliteDialect({database:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade; use executeSqliteQuerySync() to execute node:sqlite queries.`)}}),cs=/* @__PURE__ */ new WeakMap,ls=new OpenClawPostgresDialect({pool:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade.`)}});function getNodeSqliteKysely(e){if(v(e)){let t=cs.get(e);return t||(t=new Mo({dialect:ls}),cs.set(e,t)),t}let t=rn.get(e);if(t)return t;let n=new Mo({dialect:ss});return rn.set(e,n),n}function reportNodeSqliteKyselyQueryError(e,t){try{jn.get(e)?.(t)}catch{}}function releaseSqliteIterator(e,t,n,r){let i;try{e.return?.()}catch(e){i=e}if(t.release(),!n&&i!==void 0)throw h(i,r)}function executeCompiledSqliteQuerySync(e,t,n=!1,r=t.parameters){if(v(e)){let i=e.query(t.sql,r),a=n?i.rows.slice(0,1):i.rows;return i.columns.length>0?{rows:a}:{rows:[],numAffectedRows:BigInt(i.rowCount)}}try{let i=t.sql;return Ut(e),Kt(e,i,r,i=>{if(n&&M.is(t.query)){let e=i.get(...r);return{rows:e===void 0?[]:[e]}}if(M.is(t.query)||i.columns().length>0){if(os)return{rows:i.all(...r)};let t=i.iterate(...r),n=he(e,`kysely eager query`),a=!1,o,s=[];try{for(let e of t)n.progress(),s.push(e)}catch(e){a=!0,o=e}if(releaseSqliteIterator(t,n,a,`SQLite query cleanup failed`),a)throw h(o,`SQLite query failed`);return{rows:s}}i.setReadBigInts(!0);let a;try{a=i.run(...r)}finally{i.setReadBigInts(!1)}let{changes:o,lastInsertRowid:s}=a,c={numAffectedRows:BigInt(o),rows:[]};return k.is(t.query)&&o>0?{...c,insertId:BigInt(s)}:c})}catch(t){throw reportNodeSqliteKyselyQueryError(e,t),t}}function executeSqliteQuerySync(e,t){return executeCompiledSqliteQuerySync(e,t.compile())}function createSqliteQueryCache(e){let t=/* @__PURE__ */ new WeakMap;return n=>{let r=t.get(n);return r===void 0&&(r=e(n),t.set(n,r)),r}}function compileSqliteQueryBindings(e){let t=/* @__PURE__ */ new Map,n=e(e=>{let n=Symbol(`sqlite-query-parameter`);return t.set(n,e),V`${n}`}).compile(),r=n.parameters.map(e=>t.get(e)??(()=>e));return{compiled:n,bind:e=>r.map(t=>t(e))}}function prepareSqliteQuerySync(e,t){let{compiled:n,bind:r}=compileSqliteQueryBindings(t);return t=>executeCompiledSqliteQuerySync(e,n,!1,r(t))}function prepareSqliteQueryTakeFirstSync(e,t){let{compiled:n,bind:r}=compileSqliteQueryBindings(t);return t=>executeCompiledSqliteQuerySync(e,n,!0,r(t)).rows[0]}function iterateSqliteQuerySync(e,t){if(v(e))return(function*(){yield*executeCompiledSqliteQuerySync(e,t.compile()).rows})();let n=je();return(function*(){let r=t.compile(),i;try{if(i=e.prepare(r.sql),!M.is(r.query)&&i.columns().length===0)return;let t=r.parameters,a=i.iterate(...t),o=he(e,`kysely iterator`,n),s=!1;try{for(let e of a)o.progress(),yield e}catch(e){throw s=!0,h(e,`SQLite iterator failed`)}finally{releaseSqliteIterator(a,o,s,`SQLite iterator cleanup failed`)}}catch(t){throw reportNodeSqliteKyselyQueryError(e,t),t}finally{i&&Un(i)}})()}function executeSqliteQueryTakeFirstSync(e,t){return executeCompiledSqliteQuerySync(e,t.compile(),!0).rows[0]}function sha256Hex(e){return Dr(`sha256`,e,`hex`)}function sha256HexPrefixCore(e,t){return sha256Hex(e).slice(0,t)}const us=[``,`-wal`,`-shm`,`-journal`],ds=us.slice(1);Buffer.from([0,5,22,7]);const fs=ue(`state/sqlite`);var SqliteOrphanedSidecarsError=class extends Error{constructor(e,t,n){super(`SQLite database is missing at ${e}, and orphaned sidecars could not be copied: ${t.join(`, `)}. Refusing to open because SQLite could delete orphan WAL or journal state. Preserve the sidecar bytes, restore the main database, and pair it with the matching sidecar before retrying.`,{cause:n}),this.name=`SqliteOrphanedSidecarsError`}};function resolveSqliteDatabaseFilePaths(e){return us.map(t=>`${e}${t}`)}function findMatchingOrphanedSidecarCopy(e,t){let n=x.dirname(e),r=`${x.basename(e)}.orphaned-`,i=b.readdirSync(n,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.startsWith(r)).map(e=>x.join(n,e.name)).filter(e=>b.statSync(e).size===t);if(i.length===0)return;let a=fr(e);for(let e of i)if(fr(e)===a)return e}function copyOrphanedSidecar(e,t){let n=`${e}.orphaned-${t}`;for(let t=0;;t+=1){let r=t===0?n:`${n}-${t}`;try{return b.copyFileSync(e,r,b.constants.COPYFILE_EXCL),r}catch(e){if(e.code!==`EEXIST`)throw e}}}function quarantineOrphanedSqliteSidecars(e){if(b.existsSync(e))return;let t=[{path:`${e}-wal`,minimumBytes:32},{path:`${e}-journal`,minimumBytes:0}].flatMap(e=>{let t=b.statSync(e.path,{throwIfNoEntry:!1});return t?.isFile()===!0&&t.size>e.minimumBytes?[{path:e.path,size:t.size}]:[]});if(t.length===0)return;let n=Date.now(),r=[];try{for(let e of t){if(findMatchingOrphanedSidecarCopy(e.path,e.size))continue;let t=copyOrphanedSidecar(e.path,n);r.push({quarantinePath:t,sourcePath:e.path})}}catch(n){throw new SqliteOrphanedSidecarsError(e,t.map(e=>e.path),n)}if(r.length===0)return;let i=r.map(({sourcePath:e,quarantinePath:t})=>`${e} -> ${t}`);fs.warn(`SQLite database is missing at ${e}; copied orphaned sidecars: ${i.join(`, `)}. Committed frames could not be applied because the main database is missing. The bytes are preserved. Recovery requires restoring the main database and pairing it with the quarantined file.`,{databasePath:e,copiedSidecars:r})}var SqliteSchemaMismatchError=class extends Error{constructor(...e){super(...e),this.name=`SqliteSchemaMismatchError`}};function isSqliteSchemaMismatchError(e){return e instanceof Error&&e.name===`SqliteSchemaMismatchError`}const ps={"missing-table":`missing table`,"missing-column":`column definitions differ for`,"unexpected-column":`column definitions differ for`,"column-definition-drift":`column definitions differ for`,"table-constraint-drift":`table constraints differ for`,"table-definition-drift":`table definition differs for`,"missing-or-drifted-index":`missing or drifted index`,"unexpected-unique-index":`unexpected unique index`,"missing-or-drifted-trigger":`missing or drifted trigger`,"missing-or-drifted-view":`missing or drifted view`,"unexpected-trigger":`unexpected trigger`,"virtual-table-definition-drift":`virtual table definition differs for`,"table-options-drift":`table options differ for`};function isColumnIssue(e){return e===`column-definition-drift`||e===`missing-column`||e===`unexpected-column`}function defaultIssueMessage(e,t){let n=isColumnIssue(e)?t.split(`.`,1)[0]:t;return`${ps[e]} ${n}`}function createSqliteSchemaIssue(e,t,n){return{code:e,objectName:t,message:n??defaultIssueMessage(e,t)}}function legacySqliteSchemaIssueMessages(e){let t=new Set(e.filter(e=>isColumnIssue(e.code)).map(e=>e.objectName.split(`.`,1)[0]));return[...new Set(e.filter(e=>e.code!==`table-constraint-drift`||!t.has(e.objectName)).map(e=>e.message))]}function throwSqliteSchemaMismatches(e,t){let n=t.slice(0,8);throw t.length>n.length&&n.push(`${t.length-n.length} additional mismatch(es)`),new SqliteSchemaMismatchError(`SQLite schema is incomplete or noncanonical for ${e}: ${n.join(`; `)}; run openclaw doctor --fix to repair it.`)}const ms=/* @__PURE__ */ new WeakMap;function readCanonicalTableDefinition(e,t){if(!/^CREATE TABLE\b/iu.test(e)||tt(e,/\bAS\b/giu))return;let n=St(e,t);return[...n.columns.values()].every(e=>{let t=vt(e,0);return t?.keyword!==`CONSTRAINT`&&/^[a-z_][a-z0-9_]*$/u.test(t?.raw??``)})?n:void 0}function tableHasColumn(e,t,n){return readTableColumns(e,t).has(n)}function readTableColumns(e,t){if(v(e)){let n=Qn(e);if(!n){let n=e.prepare(`SELECT a.attname AS name FROM pg_catalog.pg_attribute a
        JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
        WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = ?
          AND a.attnum > 0 AND NOT a.attisdropped
        ORDER BY a.attnum`).all(t);return new Set(n.map(e=>String(e.name)))}return new Set(n.catalog.flatMap(e=>e.table===t&&e.kind===`column`&&e.value&&typeof e.value==`object`&&`name`in e.value&&typeof e.value.name==`string`?[e.value.name]:[]))}let n=Wt(e),r=n?.tableSql.get(t);if(n&&!r&&![...n.tables,...n.views].some(e=>e.toLowerCase()===t.toLowerCase()))return/* @__PURE__ */ new Set;if(n&&r){let e=ms.get(n),i=e?.get(t);if(i)return i;let a=readCanonicalTableDefinition(r,t);if(a){let r=new Set(a.columns.keys());return e||(e=/* @__PURE__ */ new Map,ms.set(n,e)),e.set(t,r),r}}let i=e.prepare(`PRAGMA table_info(${t})`).all();return new Set(i.flatMap(e=>typeof e.name==`string`?[e.name]:[]))}function classifySqliteTableReadError(e,t,n,r){if(v(e)||mt(r)!==1)return r;try{let i=readTableColumns(e,t);if(i.size>0&&n.some(e=>!i.has(e)))return new SqliteSchemaMismatchError(`SQLite table ${t} is missing required columns; run openclaw doctor --fix to repair it.`,{cause:r})}catch{}return r}function tablePrimaryKeyColumns(e,t){if(v(e)){let n=Qn(e);if(!n)return e.prepare(`SELECT a.attname AS name FROM pg_catalog.pg_index i
        JOIN pg_catalog.pg_class c ON c.oid = i.indrelid
        CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, position)
        JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid AND a.attnum = k.attnum
        WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = ? AND i.indisprimary
        ORDER BY k.position`).all(t).map(e=>String(e.name));let r=n.catalog.find(e=>e.table===t&&e.kind===`primaryKey`)?.value;return Array.isArray(r)?r.filter(e=>typeof e==`string`):[]}let n=Wt(e)?.tableSql.get(t),r=n&&readCanonicalTableDefinition(n,t);if(r){let e=r.constraints.find(e=>{let t=vt(e,0);return t&&Ct(e,t)===`PRIMARY`});if(!e)return[...r.columns].flatMap(([e,t])=>tt(t,/\bPRIMARY\s+KEY\b/giu)?[e]:[]);let t=et(e,`(`),n=ft(e.slice(t+1,Ze(e,t))).map(e=>ge(vt(e,0)?.raw??``));if(n.every(e=>r.columns.has(e)))return[...new Set(n)]}return e.prepare(`PRAGMA table_info(${t})`).all().filter(e=>Number(e.pk??0)>0&&typeof e.name==`string`).toSorted((e,t)=>Number(e.pk??0)-Number(t.pk??0)).map(e=>e.name)}function tableExists(e,t){if(v(e)){let n=Qn(e);return n?n.catalog.some(e=>e.table===t&&e.kind===`table`):e.prepare(`SELECT 1 AS present FROM pg_catalog.pg_class
      WHERE relnamespace = current_schema()::regnamespace AND relname = ? AND relkind IN ('r', 'p')`).get(t)?.present===1}let n=Wt(e);return n?n.tables.has(t):Kt(e,`SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?`,[t],e=>e.get(t))?.ok===1}function ensureColumn(e,t,n){let r=n.trim().split(/\s+/,1)[0];return!r||!tableExists(e,t)||tableHasColumn(e,t,r)?!1:(e.exec(`ALTER TABLE ${t} ADD COLUMN ${n};`),!0)}function readSqliteImageSizeBytes(e){return Number(e.prepare(`PRAGMA page_count;`).get()?.page_count)*Number(e.prepare(`PRAGMA page_size;`).get()?.page_size)}function createSqliteTableContractReader(e,t=[],n=[]){let r,i,a=/* @__PURE__ */ new Set,readCatalog=(o=[])=>{if(r)for(let t of o){if(!a.has(t))continue;let n=readSqliteColumnCatalog(e,t);r={...r,tables:r.tables.map(e=>e.name===t?{...e,columns:n}:e)},a.delete(t),i=void 0}else{let i=[...n,...o];r=readSqliteSchemaCatalog(e,{viewNames:t,virtualTableNames:i});for(let e of r.tables)e.sql&&/^CREATE VIRTUAL TABLE /iu.test(e.sql)&&!i.includes(e.name)&&a.add(e.name)}return r};return Object.assign(e=>{let t=readCatalog([e]);return(i??=sqliteSchemaContractFromCatalog(t)).get(e)},{readCatalog:(n,r)=>n.every(e=>t.includes(e))?readCatalog(r):readSqliteSchemaCatalog(e,{viewNames:n,virtualTableNames:r}),readView:n=>(t.includes(n)?readCatalog().views:readSqliteSchemaCatalog(e,{viewNames:[n],virtualTableNames:[]}).views).find(e=>e.name===n)})}function sqliteSchemaContractFromCatalog(e){return new Map(e.tables.map(e=>[e.name,Pe(e.name,e,{schema:`main`,name:e.name,strict:e.strict,wr:e.withoutRowid},e.indexes.map(e=>ke(e,e.sql,e.terms)).toSorted(compareJson),e.triggers,e.columns,e.foreignKeys)]))}function readSqliteSchemaCatalog(e,t={}){let n=e.prepare(`SELECT type, name, tbl_name, sql FROM main.sqlite_schema ORDER BY name`).all(),r=n.filter(e=>e.type===`table`&&!e.name.startsWith(`sqlite_`)),i=n.filter(e=>e.type===`view`&&(!t.viewNames||t.viewNames.includes(e.name)));if(r.length===0&&i.length===0)return{tables:[],views:[]};let a=e.prepare(`PRAGMA table_list`).all(),o=a.filter(e=>e.schema===`main`&&e.type===`virtual`&&t.virtualTableNames&&!t.virtualTableNames.includes(e.name)).map(e=>e.name),s=a.some(e=>[`pragma_index_list`,`pragma_index_xinfo`,`pragma_table_xinfo`,`pragma_foreign_key_list`].includes(e.name.toLowerCase())),c,l;if(!s){c=/* @__PURE__ */ new Map,l=/* @__PURE__ */ new Map;let t=e.prepare(`
        SELECT t.name AS table_name, i.seq AS index_seq,
          i.name AS index_name, i.origin, i.partial, i."unique",
          x.seqno, x.cid, x.name, x."desc", x.coll, x."key"
        FROM main.sqlite_schema AS t
        CROSS JOIN pragma_index_list(t.name, 'main') AS i
        LEFT JOIN pragma_index_xinfo(i.name, 'main') AS x ON 1 = 1
        WHERE t.type = 'table' AND substr(t.name, 1, 7) <> 'sqlite_'
        ORDER BY t.name, i.seq, x.seqno
      `).all();for(let e of t){let t=c.get(e.table_name)??[];if(t.at(-1)?.index_seq!==e.index_seq&&(t.push({table_name:e.table_name,index_seq:e.index_seq,name:e.index_name,origin:e.origin,partial:e.partial,unique:e.unique}),c.set(e.table_name,t)),e.seqno!==null){let t=l.get(e.table_name)??[];t.push({table_name:e.table_name,index_seq:e.index_seq,seqno:e.seqno,cid:e.cid,name:e.name,desc:e.desc,coll:e.coll,key:e.key}),l.set(e.table_name,t)}}}let u=t.viewNames?t.viewNames.length>0?`t.type = 'table' OR (t.type = 'view' AND t.name IN (${t.viewNames.map(()=>`?`).join(`, `)}))`:`t.type = 'table'`:`t.type IN ('table', 'view')`,d=o.length?`AND t.name NOT IN (${o.map(()=>`?`).join(`, `)})`:``,f=s?void 0:ie(e.prepare(`
          SELECT t.name AS table_name, x.cid, x.name, x.type, x."notnull", x.dflt_value, x.pk, x.hidden
          FROM main.sqlite_schema AS t
          CROSS JOIN pragma_table_xinfo(t.name, 'main') AS x
          WHERE (${u}) AND substr(t.name, 1, 7) <> 'sqlite_'
            ${d}
          ORDER BY t.name, x.cid
        `).all(...t.viewNames??[],...o),e=>e.table_name),p=s?void 0:ie(e.prepare(`
          SELECT t.name AS table_name, f.id, f.seq, f."table", f."from", f."to",
            f.on_update, f.on_delete, f."match"
          FROM main.sqlite_schema AS t
          CROSS JOIN pragma_foreign_key_list(t.name, 'main') AS f
          WHERE t.type = 'table' AND substr(t.name, 1, 7) <> 'sqlite_'
          ORDER BY t.name, f.id, f.seq
        `).all(),e=>e.table_name),m=ie(n.filter(e=>e.type===`trigger`),e=>e.tbl_name),h=new Map(n.filter(e=>e.type===`index`).map(e=>[e.name,e.sql])),normalizedRow=e=>({name:e.name,sql:Be(e.sql)}),readColumns=t=>o.includes(t)?[]:f?(f.get(t)??[]).map(({table_name:e,...t})=>t):readSqliteColumnCatalog(e,t),readTriggers=e=>(m.get(e)??[]).map(normalizedRow);return{tables:r.map(t=>{let n=a.find(e=>e.schema===`main`&&e.name===t.name);if(!n)throw Error(`Could not inspect SQLite table options for ${t.name}.`);let r=c?c.get(t.name)??[]:e.prepare(`PRAGMA main.index_list(${Tt(t.name)})`).all().map(({name:e,origin:t,partial:n,unique:r,seq:i})=>({name:e,origin:t,partial:n,unique:r,index_seq:i})),i=ie(l?.get(t.name)??[],e=>e.index_seq);return{name:t.name,sql:Be(t.sql),strict:n.strict,withoutRowid:n.wr,columns:readColumns(t.name),foreignKeys:p?(p.get(t.name)??[]).map(({table_name:e,...t})=>t):e.prepare(`PRAGMA main.foreign_key_list(${Tt(t.name)})`).all(),indexes:r.map(t=>({name:t.name,origin:t.origin,partial:t.partial,unique:t.unique,sql:Be(h.get(t.name)??null),terms:l?(i.get(t.index_seq)??[]).map(({table_name:e,index_seq:t,...n})=>n):e.prepare(`PRAGMA main.index_xinfo(${Tt(t.name)})`).all()})).toSorted((e,t)=>e.name.localeCompare(t.name)),triggers:readTriggers(t.name)}}),views:i.map(e=>({name:e.name,sql:Be(e.sql),columns:readColumns(e.name),triggers:readTriggers(e.name)}))}}function readSqliteColumnCatalog(e,t){return e.prepare(`PRAGMA main.table_xinfo(${Tt(t)})`).all()}function compareJson(e,t){return JSON.stringify(e).localeCompare(JSON.stringify(t))}const hs={statement:jr(`openclaw.database.statement`),request:jr(`openclaw.database.request`)},gs=/* @__PURE__ */ new WeakSet;let statementTiming;function attributesSqliteStatements(e){return e.startsWith(`session.transcript.`)||e.startsWith(`sessions.transcript-`)||e.startsWith(`session.metadata.`)||e.startsWith(`trajectory.`)||e.startsWith(`audit.writer.`)||e.startsWith(`knowledge.`)||e===`session.lifecycle.delete`||e===`session context snapshot read`}function startSqliteStatementTiming(e=!1){let t=statementTiming,n,r;if(e)try{r=observeGcSamples(e=>{for(let t of e)n=(n??0)+t.durationMs}),n=r?0:void 0}catch{}let i=/* @__PURE__ */ new Map,a=0,o=0,s=0,c;return statementTiming=(e,t,n)=>{a++,o+=t,(c===void 0||t>s)&&(c=e);let r=i.has(e)||i.size<32?e:``,l=i.get(r)??{count:0,totalMs:0,maxMs:0};i.set(r,l),s=Math.max(s,t),n!==void 0&&(l.rows=(l.rows??0)+n),l.count++,l.totalMs+=t,l.maxMs=Math.max(l.maxMs,t)},()=>{statementTiming=t;try{r?.()}catch{n=void 0}return{totalMs:o,callbackGcMs:n,summarize(){let identity=e=>{let t=normalizeSql(`sqlite`,e);return{id:e?Er(`sha256`).update(t).digest(`hex`).slice(0,16):`other`,operation:/^(SELECT|INSERT|UPDATE|DELETE|WITH|SAVEPOINT|RELEASE|ROLLBACK)\b/i.exec(t)?.[1]?.toUpperCase()??`OTHER`}};return{count:a,maxMs:s,slowest:c===void 0?void 0:{...identity(c),maxMs:s},statements:[...i].toSorted((e,t)=>t[1].totalMs-e[1].totalMs).slice(0,5).map(([e,t])=>Object.assign(identity(e),t,{totalMs:Math.round(t.totalMs*100)/100,maxMs:Math.round(t.maxMs*100)/100})),omittedGroups:Math.max(0,i.size-5)}}}}}function normalizeSql(e,t){let n=``;for(let r=0;r<t.length;){let i=t.slice(r);if(i.startsWith(`/*`)){let e=1;for(r+=2;r<t.length&&e;)t.startsWith(`/*`,r)?(e++,r+=2):t.startsWith(`*/`,r)?(e--,r+=2):r++;n+=` `;continue}let a=/^--[^\r\n]*/.exec(i)?.[0],o=(e===`postgres`?/^[eE]'(?:\\[\s\S]|''|[^'\\])*(?:'|$)/.exec(i)?.[0]:void 0)??/^(?:[uU]&)?'(?:''|[^'])*(?:'|$)/.exec(i)?.[0],s=/^\$(?:[A-Za-z_][\w]*)?\$/.exec(i)?.[0],c=/^(?:"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\])/.exec(i)?.[0],l=/[\w$]/.test(t[r-1]??``)?void 0:/^(?:0x[\da-f]+|\d+(?:\.\d*)?(?:e[+-]?\d+)?)(?!\w)/i.exec(i)?.[0];if(s){let e=t.indexOf(s,r+s.length);r=e<0?t.length:e+s.length,n+=`?`}else if(a||o||c||l){let e=a??o??c??l??``;r+=e.length,n+=a?` `:c?e:`?`}else n+=t[r++]}return n.replace(/\s+/g,` `).trim()}function observeDatabaseOperation(e,t,n,r,i){let a=hs[t],o=e===`sqlite`&&t===`statement`?statementTiming:void 0;if(!a.hasSubscribers&&!o)return r();let s=performance.now(),c=`error`,l;try{let e=r();return c=`ok`,l=i===`all`&&Array.isArray(e)?e.length:i===`get`?Number(e!==void 0):void 0,e}finally{let t=performance.now()-s;n!==void 0&&o?.(n,t,l),a.hasSubscribers&&a.publish({engine:e,sql:n===void 0?void 0:normalizeSql(e,n),threadId:yr,outcome:c,durationMs:t})}}function observeConnection(e){if(gs.has(e))return e;gs.add(e);let t=e.exec.bind(e),n=e.prepare.bind(e);return e.exec=e=>observeDatabaseOperation(`sqlite`,`statement`,e,()=>t(e)),e.prepare=e=>{let t=n(e);for(let n of[`get`,`all`,`run`]){let r=t[n].bind(t);Object.defineProperty(t,n,{configurable:!0,writable:!0,value:(...t)=>observeDatabaseOperation(`sqlite`,`statement`,e,()=>r(...t),n===`run`?void 0:n)})}let r=t.iterate.bind(t);return t.iterate=(...t)=>{let n=r(...t),i=statementTiming;if(!hs.statement.hasSubscribers&&!i)return n;let a=0,o=0,s=!1,c=!1,finish=t=>{c||(c=!0,s&&(i?.(e,a,o),hs.statement.hasSubscribers&&hs.statement.publish({engine:`sqlite`,sql:normalizeSql(`sqlite`,e),threadId:yr,outcome:t,durationMs:a})))},step=e=>{if(c)return e();let t=performance.now();try{let n=e();return a+=performance.now()-t,n.done?finish(`ok`):o++,n}catch(e){throw a+=performance.now()-t,finish(`error`),e}},l={next:(...e)=>(s=!0,step(()=>n.next(...e))),return:e=>step(()=>n.return?.(e)??{done:!0,value:e}),[Symbol.iterator](){return this}};return Object.setPrototypeOf(l,Object.getPrototypeOf(n)),l},t},e}const _s=1e3,vs=1e3,ys=Symbol.for(`openclaw.sqliteAbortedTransaction`);function assertTransactionUsable(e){if(v(e))return;let t=e[ys];if(t)throw t.error}const bs=ue(`sqlite/transaction`),xs=s(Symbol.for(`openclaw.sqliteWriteAdmissionServices`),()=>/* @__PURE__ */ new Map),Ss=/* @__PURE__ */ new WeakMap;function writeAdmissionLocation(e){let t=Ss.get(e);if(t!==void 0)return t;let n=e.location(),r=n===null?null:Je(n);return Ss.set(e,r),r}function retainSqliteWriteAdmissionService(e,t){let n=[...new Set(e.map(Je))].map(e=>{let n=xs.get(e)??/* @__PURE__ */ new Set,retained=()=>t();return n.add(retained),xs.set(e,n),{location:e,services:n,retained}});return()=>{for(let{location:e,services:t,retained:r}of n)t.delete(r),t.size===0&&xs.get(e)===t&&xs.delete(e)}}function execNativeBegin(e,t){let n=Date.now();t.nativeAttempts+=1;try{e.exec(`BEGIN IMMEDIATE`)}finally{t.nativeMs+=Date.now()-n}}function beginImmediateTransaction(e,t){let n=xs.size>0?writeAdmissionLocation(e):null,r=n===null?void 0:xs.get(n);if(!r){execNativeBegin(e,t);return}let i=performance.now()+vn(e);for(;;)try{qn(e,Math.min(25,Math.max(0,Math.ceil(i-performance.now()))),()=>execNativeBegin(e,t));return}catch(e){if(!jt(e)||performance.now()>=i)throw e;for(let e of r){let n=Date.now();t.serviceCalls+=1;try{e()}finally{t.serviceMs+=Date.now()-n}}if(performance.now()>=i)throw e}}function slowBusyWaitThresholdMs(e){return e?.busyTimeoutMs===void 0||e.busyTimeoutMs<=0?_s:Math.min(_s,e.busyTimeoutMs)}function transactionDiagnosticLabels(e,t){let n=t?.databaseLabel;if(!n)try{n=e?e.location()??`:memory:`:`unavailable`}catch{n=`unavailable`}return{database:n,operation:t?.operationLabel||je()?.operation||`unlabeled`,...t?.diagnosticContext?{context:{...t.diagnosticContext}}:{}}}function logTransactionStep(e,t){try{if(!t&&e.elapsedMs<slowBusyWaitThresholdMs(e.options))return;let n=t?Re(t.error):void 0,r=t?mt(t.error):void 0;(e.options?.logger??bs).warn(t?`SQLite transaction lock wait failed`:`slow SQLite transaction step`,{async:!1,...e.options?.busyTimeoutMs===void 0?{}:{busyTimeoutMs:e.options.busyTimeoutMs},...transactionDiagnosticLabels(e.db,e.options),...t?{code:Ee(t.error)}:{},elapsedMs:e.elapsedMs,...e.holderAtWaitStart?{holderAtWaitStart:e.holderAtWaitStart}:{},...t?{failureKind:`lock-contention`}:{},isMainThread:vr,pid:process.pid,...n===void 0?{}:{sqliteErrcode:n},...r===void 0?{}:{sqlitePrimaryCode:r},step:e.step,threadId:yr,...e.beginAdmission?{beginAdmission:{...e.beginAdmission}}:{}})}catch{}}function execTimedTransactionStep(e){let t=Date.now(),n=e.sql===`BEGIN IMMEDIATE`?{nativeAttempts:0,nativeMs:0,serviceCalls:0,serviceMs:0}:void 0,r=n?kt(e.db,t):void 0;try{n?beginImmediateTransaction(e.db,n):e.db.exec(e.sql);let i=Date.now()-t;return logTransactionStep({beginAdmission:n,db:e.db,elapsedMs:i,holderAtWaitStart:r,options:e.options,step:e.step}),i}catch(i){let a=Date.now()-t;throw jt(i)&&Vt(e.db)&&(e.step!==`begin`||e.options?.beginLockFailureReporting!==`suppress`)&&logTransactionStep({beginAdmission:n,db:e.db,elapsedMs:a,holderAtWaitStart:r,options:e.options,step:e.step},{error:i}),i}}function discardUnsafeConnection(e,t){let n={error:t};e[ys]??=n;try{at(e,t)}catch(t){throw e[ys]===n&&(n.error=t),t}finally{Bt(e);try{e.close()}catch{}}}function abortImmediateTransaction(e,t,n){if(!e[ys]){if(!n&&e.isOpen&&!e.isTransaction)at(e,t,`rolled-back`);else try{e.exec(`ROLLBACK`)}catch{discardUnsafeConnection(e,t)}}}function runSqliteTransactionSync(e,t,n,r){if(e.isTransaction){e.exec(`SAVEPOINT openclaw_tx_nested`);try{let n=en(e,t);return Ue(n),assertTransactionUsable(e),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`),n}catch(t){let n=e[ys];if(n)throw n.error;try{e.exec(`ROLLBACK TO SAVEPOINT openclaw_tx_nested`),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`)}catch{discardUnsafeConnection(e,t)}throw t}}let i=$e(),a=i?Date.now()-i.preparedAtMs:void 0,o=execTimedTransactionStep({db:e,options:r,sql:n===`immediate`?`BEGIN IMMEDIATE`:`BEGIN`,step:`begin`});return i&&(i.transactions.count+=1),settleSqliteTransactionSync(e,t,n,o,a,r)}function settleSqliteTransactionSync(e,t,n,r,i,a,o=!1){let s=$e(),c=Date.now(),l=n===`immediate`?rt(e):void 0;l&&Nt(l,a?.operationLabel||je()?.operation||`unlabeled`,c);let u=s?.hostAdmissionWaitMs??0,d=s?.databaseAdmissionWaitMs??0,f=0,commit=()=>{let t=Date.now(),n=s?.databaseAdmissionWaitMs??0;try{Dt(e),execTimedTransactionStep({db:e,options:a,sql:`COMMIT`,step:`commit`})}finally{f+=Date.now()-t-((s?.databaseAdmissionWaitMs??0)-n)}},p=!1,m=a?.operationLabel||je()?.operation,h=m?.startsWith(`sessions.transcript-hydration.`)===!0,g;try{let n=m&&attributesSqliteStatements(m)?startSqliteStatementTiming(h):void 0,r;try{r=o?t():en(e,t)}finally{g=n?.()}return Ue(r),assertTransactionUsable(e),p=!0,a?.withCommit?Ue(a.withCommit(commit)):commit(),r}catch(t){throw abortImmediateTransaction(e,t,p),assertTransactionUsable(e),t}finally{l&&Atomics.compareExchange(l,1,yr+1,0);try{s?.diskRead&&(s.diskRead.context=a?.diagnosticContext);let t=Date.now()-c,o=(s?.hostAdmissionWaitMs??0)-u,l=(s?.databaseAdmissionWaitMs??0)-d,p=Math.max(0,t-o-l-f);t<(a?.slowTransactionHoldMs??vs)||(a?.logger??bs).warn(`slow SQLite transaction hold`,{async:!1,callbackKind:`application-transaction`,isMainThread:vr,mode:n,pid:process.pid,threadId:yr,...transactionDiagnosticLabels(e,a),...s?.holdContext||h&&s?.hydrationActiveEvents!==void 0?{context:Xe(a?.diagnosticContext,h)}:{},elapsedMs:t,phases:{prepareMs:i,beginMs:r,sqlMs:p,...g?{statementExecutionMs:Math.round(g.totalMs*100)/100,callbackOtherMs:Math.round(Math.max(0,p-g.totalMs)*100)/100,callbackGcMs:g.callbackGcMs===void 0?void 0:Math.round(g.callbackGcMs*100)/100}:{},hostAdmissionWaitMs:o,databaseAdmissionWaitMs:l,commitMs:f},...g?{statementTiming:g.summarize()}:{},thresholdMs:a?.slowTransactionHoldMs??vs})}catch{}finally{s&&(s.preparedAtMs=Date.now(),s.hydrationActiveEvents!==void 0&&(s.hydrationActiveEvents=void 0))}}}function runSqliteDeferredTransactionSync(e,t,n){return v(e)?e.runTransaction(t,n):(assertTransactionUsable(e),gt(e,()=>runSqliteTransactionSync(e,t,`deferred`,n)))}function runSqliteReadSnapshotSync(e,t,n){if(v(e)){if(e.isTransaction){let e=t();return Ue(e),e}return e.runTransaction(t,n,!0)}if(assertTransactionUsable(e),!e.isTransaction)return runSqliteDeferredTransactionSync(e,t,n);let r=en(e,t);return Ue(r),assertTransactionUsable(e),r}function runSqliteImmediateTransactionSync(e,t,n){return v(e)?e.runTransaction(t,n):(assertTransactionUsable(e),gt(e,()=>runSqliteTransactionSync(e,t,`immediate`,n)))}function runSqliteSingleStatementSync(e,t){return v(e)?e.runTransaction(t):(assertTransactionUsable(e),gt(e,()=>{let n=xs.size>0?writeAdmissionLocation(e):null;if(e.isTransaction||n!==null&&xs.has(n))return runSqliteTransactionSync(e,t,`immediate`);let r=en(e,t);return Ue(r),r}))}const Cs=18e5;function getStateSchemaFacts(e){return v(e)?Qn(e):Wt(e)}const ws={name:`state.schema-version`,lifetime:`process`,schemaDependent:!0,read(e){if(typeof e==`object`&&e&&`userVersion`in e&&typeof e.userVersion==`number`&&`contentVersion`in e&&typeof e.contentVersion==`number`)return{userVersion:e.userVersion,contentVersion:e.contentVersion}}};function createStateSchemaAdmission(e,t,n){let r={name:e,lifetime:n,schemaDependent:!0,read(e){if(typeof e!=`object`||!e||!(`value`in e)||!(`admissionId`in e)||typeof e.admissionId!=`string`)return;let n=t(e.value);return n===void 0?void 0:{value:n,admissionId:e.admissionId}}};return{get(e){if(be(e))return;let t=Fe(e,r);if(!t)return;let n=getStateSchemaFacts(e);return t.admissionId===n?.admissionId?t.value:void 0},publish(e,t){!v(e)&&Mn(e)&&Wn(e);let n=getStateSchemaFacts(e);if(!n||!v(e)&&Fe(e,qt)?.admissionId!==n.admissionId)return;getStateSchemaVersionAdmission(e);let i={value:t,admissionId:n.admissionId};Ye(e,r,i)}}}const Ts=createStateSchemaAdmission(`state.runtime-schema`,e=>typeof e==`object`&&e&&`startupReady`in e&&typeof e.startupReady==`boolean`?{startupReady:e.startupReady}:void 0,`process`),Es=/* @__PURE__ */ new WeakMap;function rememberConnectionVersion(e,t){let n=Es.get(e),install=t=>{t?Es.set(e,t):Es.delete(e)};bt(e,{stage:()=>install(t),commit:()=>{},rollback:()=>install(n)})||install(t)}function schemaVersionKey(e){return{name:`state.schema-version:${e}`,read:ws.read}}function getStateSchemaVersionAdmission(e){let t=getStateSchemaFacts(e);if(!t)return;let n=Es.get(e);if(n?.schema===t)return n.facts;let r=Fe(e,schemaVersionKey(t.admissionId)),i=r?void 0:Fe(e,qt);if(!r&&!v(e)&&i?.admissionId!==t.admissionId)return;let a=r??Fe(e,ws);return a&&(rememberConnectionVersion(e,{schema:t,facts:a}),r||Ye(e,schemaVersionKey(t.admissionId),a)),a}function rememberStateSchemaVersionAdmission(e,t){let n=getStateSchemaFacts(e);if(!n)return;rememberConnectionVersion(e,{schema:n,facts:t});let r=Fe(e,qt);(v(e)||r?.admissionId===n.admissionId)&&(Ye(e,schemaVersionKey(n.admissionId),t),Ye(e,ws,t))}function publishStateSchemaVersionAdmission(e,t){Ye(e,ws,t);let n=getStateSchemaFacts(e);n?(rememberConnectionVersion(e,{schema:n,facts:t}),Ye(e,schemaVersionKey(n.admissionId),t)):rememberConnectionVersion(e)}function adoptPeerPublishedStateSchemaVersion(e,t){return t?.schema_version!==40||Dn(e)!==40?!1:(publishStateSchemaVersionAdmission(e,{userVersion:40,contentVersion:40}),!0)}function getStateRuntimeSchemaAdmission(e){return Ts.get(e)}function publishStateRuntimeSchemaAdmission(e,t){Ts.publish(e,{startupReady:t})}function readPublishedStateSchemaVersion(e){let t=getStateSchemaVersionAdmission(e);return t?t.userVersion:(v(e)&&zt(`postgres`,`repair`),Dn(e))}function getEnumValues(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function joinValues(e,t=`|`){return e.map(e=>stringifyPrimitive(e)).join(t)}function jsonStringifyReplacer(e,t){return typeof t==`bigint`?t.toString():t}var Cached=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function cached(e){return new Cached(e)}function nullish(e){return e==null}function cleanRegex(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function floatSafeRemainder(e,t){let n=e/t,r=Math.round(n),i=4*2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}function assignProp(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function rawShape(e){let t=Object.getOwnPropertyDescriptor(e,`shape`);return t?.get?t.get.raw:t?.value}function sourceShape(e){return rawShape(e._zod.def)??e._zod.def.shape}function deferProp(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return assignProp(this,t,e),e},enumerable:!0,configurable:!0})}function putProp(e,t,n){t in e?assignProp(e,t,n):e[t]=n}function mirrorShape(e,t,n,r){let i=sourceShape(t);for(let a of n){let n=Object.getOwnPropertyDescriptor(i,a);n.enumerable&&(n.get?deferProp(e,a,()=>{let e=t._zod.def.shape[a];return r?r(e,a):e}):putProp(e,a,r?r(n.value,a):n.value))}}function mirrorProps(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?deferProp(e,n,()=>t[n]):putProp(e,n,r.value))}}function mergeDefs(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function esc(e){return JSON.stringify(e)}function slugify(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const Ds=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function isObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Os=/* @__PURE__*/ cached(()=>{if(H.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function isPlainObject(e){if(isObject(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return isObject(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function shallowClone(e){return isPlainObject(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const ks=/* @__PURE__*/ new Set([`string`,`number`,`symbol`]);function escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function clone(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function normalizeParams(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function stringifyPrimitive(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function optionalKeys(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}const As={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},js={int64:[/* @__PURE__*/ BigInt(`-9223372036854775808`),/* @__PURE__*/ BigInt(`9223372036854775807`)],uint64:[/* @__PURE__*/ BigInt(0),/* @__PURE__*/ BigInt(`18446744073709551615`)]};function pick(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);let i={};return mirrorShape(i,e,maskedKeys(e,t)),clone(e,mergeDefs(n,{shape:i,checks:[]}))}function maskedKeys(e,t){let n=sourceShape(e),r=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&r.push(e)}return r}function omit(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);let i=new Set(maskedKeys(e,t)),a={};return mirrorShape(a,e,Reflect.ownKeys(sourceShape(e)).filter(e=>!i.has(e))),clone(e,mergeDefs(n,{shape:a,checks:[]}))}function extend(e,t){if(!isPlainObject(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=sourceShape(e);for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return clone(e,mergeDefs(e._zod.def,{shape:extended(e,t)}))}function extended(e,t){let n={};return mirrorShape(n,e,Reflect.ownKeys(sourceShape(e))),mirrorProps(n,t),n}function safeExtend(e,t){if(!isPlainObject(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return clone(e,mergeDefs(e._zod.def,{shape:extended(e,t)}))}function merge(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);let n={};return mirrorShape(n,e,Reflect.ownKeys(sourceShape(e))),mirrorShape(n,t,Reflect.ownKeys(sourceShape(t))),clone(e,mergeDefs(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function partial(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(maskedKeys(t,n)):void 0,o={};return mirrorShape(o,t,Reflect.ownKeys(sourceShape(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),clone(t,mergeDefs(t._zod.def,{shape:o,checks:[]}))}function required(e,t,n){let r=n?new Set(maskedKeys(t,n)):void 0,i={};return mirrorShape(i,t,Reflect.ownKeys(sourceShape(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),clone(t,mergeDefs(t._zod.def,{shape:i}))}function aborted(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function explicitlyAborted(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function prefixIssues(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function unwrapMessage(e){return typeof e==`string`?e:e?.message}function sizeCaps(e){let t=[];for(let n of e??[]){let e=n._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let r=e.maximum??e.length??e.size;r>=0&&t.push([r,n])}return t}function attachSchema(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function finalizeIssue(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:unwrapMessage(e.inst?._zod.def?.error?.(e))??unwrapMessage(a?.(e))??unwrapMessage(t?.error?.(e))??unwrapMessage(n.customError?.(e))??unwrapMessage(n.localeError?.(e))??`Invalid input`,s={};for(let t of Object.keys(e))t!==`inst`&&t!==`schema`&&t!==`continue`&&t!==`input`&&t!==`__proto__`&&(s[t]=e[t]);return s.path??=[],s.message=o,t?.reportInput&&(s.input=e.input),s}const Ms=/[\uD800-\uDBFF]/;function codePointLength(e){let t=e.length;if(!Ms.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function getLengthableOrigin(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function parsedType(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function issue(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function members(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):defineBound(e,n,r.value)}}function own(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function hide(e,t,n){return own(e,t,n,!1)}/* @__NO_SIDE_EFFECTS__ */
function derived(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return own(this,n,r(this))},set(e){own(this,n,e)}})}return t}function defineBound(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:own(this,t,n.bind(this))},set(e){own(this,t,e)}})}function claim(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}let Ns,Ps=!1;const Fs={configurable:!0,get(){Ps=!0}};function defineLazyInternal(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&Ns!==e._zod?Ns=void 0:(Ns=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Fs);let e=Ps;Ps=!1;try{let r=n(this);return Ps?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),Ps||=e,r}catch(n){throw delete this[t],Ps||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function installLazyProp(e,t,n,r){let i=claim(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}function constantCatch(e){let fn=()=>e;return fn[`~constantCatch`]=!0,fn}var Is;const Ls={value:void 0,enumerable:!1};let Rs=`captureStackTrace`in Error?Error:null;function newError(e){let t=Rs;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return Rs=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}/* @__NO_SIDE_EFFECTS__ */
function $constructor(e,t,n,r){let i={};function Internals(e){this.def=e,this.constr=_,this.traits=/* @__PURE__ */ new Set}Internals.prototype=i;let a=n,o=a&&/* @__PURE__ */ new WeakSet;function init(n,r){if(!n._zod){Ls.value=new Internals(r);try{Object.defineProperty(n,"_zod",Ls)}finally{Ls.value=void 0}}else if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),o){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;o.has(i)||(o.add(i),members(i,a))}let i=_.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let s=r?.Parent??Object;class Definition extends s{}Object.defineProperty(Definition,"name",{value:e});function _(e){let t=r?.Parent?newError(Definition):this;init(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(_,"init",{value:init}),Object.defineProperty(_,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(_,"name",{value:e}),_}var $ZodAsyncError=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},$ZodEncodeError=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Is=globalThis).__zod_globalConfig??(Is.__zod_globalConfig={});const H=globalThis.__zod_globalConfig;function config(e){return e&&Object.assign(H,e),H}function _getMessage(){let e=this._zod;return e.message??=JSON.stringify(e.def,jsonStringifyReplacer,2),e.message}function _setMessage(e){this._zod.message=e}const zs={get:_getMessage,set:_setMessage,enumerable:!0,configurable:!0},Bs={value:void 0,enumerable:!1},Vs=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]),Hs=/* @__PURE__ */ $constructor(`$ZodError`,(e,t)=>{e.name=`$ZodError`,Bs.value=t,Object.defineProperty(e,"issues",Bs),Bs.value=void 0,Object.defineProperty(e,"message",zs);let n=Object.getPrototypeOf(e);Vs.has(n)||(Vs.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let value=()=>this.message;return Object.defineProperty(this,"toString",{value,configurable:!0,writable:!0}),value},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))});function node(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function flattenError(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?node(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function formatError(e,t=e=>e.message){let n={_errors:[]},processError=(e,r=[])=>{for(let i of e.issues)if(i.code===`invalid_union`&&i.errors.length)i.errors.map(e=>processError({issues:e},[...r,...i.path]));else if(i.code===`invalid_key`)processError({issues:i.issues},[...r,...i.path]);else if(i.code===`invalid_element`)processError({issues:i.issues},[...r,...i.path]);else{let e=[...r,...i.path];if(e.length===0)n._errors.push(t(i));else{let r=n,a=0;for(;a<e.length;){let n=e[a],o=a===e.length-1;if(n===`_errors`){o&&r._errors.push(t(i)),a++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let s=r[n];o&&s._errors.push(t(i)),r=s,a++}}}};return processError(e),n}function finalizeParams(e,t){return{callee:t?.callee??e,Err:t?.Err}}const _parse=e=>{let fn=(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new $ZodAsyncError;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>finalizeIssue(e,a,config())));throw Ds(t,i?.callee??fn),t}return o.value};return fn},_parseAsync=e=>{let fn=async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>finalizeIssue(e,a,config())));throw Ds(t,i?.callee??fn),t}return o.value};return fn},_safeParse=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new $ZodAsyncError;return a.issues.length?failure(e,a.issues,i):{success:!0,data:a.value}};function failure(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>finalizeIssue(e,n,config()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}const _safeParseAsync=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?failure(e,a.issues,i):{success:!0,data:a.value}},Us=/* @__PURE__ */ Symbol.for(`zod.compile.invalid`),Ws=/* @__PURE__ */ Symbol.for(`zod.compile.fallback`),validate=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==Us)return!0;if(r.definite===!0&&n===void 0)return!1}return validateFallback(e,t,n)});function validateFallback(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[Ws]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new $ZodAsyncError;return a.issues.length===0}const validateAsync$1=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length===0},_encode=e=>{let t=_parse(e),fn=(e,n,r,i)=>{let a=r?{...r,direction:`backward`}:{direction:`backward`};return t(e,n,a,finalizeParams(fn,i))};return fn},_decode=e=>{let t=_parse(e),fn=(e,n,r,i)=>t(e,n,r,finalizeParams(fn,i));return fn},_encodeAsync=e=>{let t=_parseAsync(e),fn=async(e,n,r,i)=>{let a=r?{...r,direction:`backward`}:{direction:`backward`};return await t(e,n,a,finalizeParams(fn,i))};return fn},_decodeAsync=e=>{let t=_parseAsync(e),fn=async(e,n,r,i)=>await t(e,n,r,finalizeParams(fn,i));return fn},_safeEncode=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return _safeParse(e)(t,n,i)},_safeDecode=e=>(t,n,r)=>_safeParse(e)(t,n,r),_safeEncodeAsync=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return _safeParseAsync(e)(t,n,i)},_safeDecodeAsync=e=>async(t,n,r)=>_safeParseAsync(e)(t,n,r),Gs=/^[cC][0-9a-z]{6,}$/,Ks=/^[0-9a-z]+$/,qs=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Js=/^[0-9a-vA-V]{20}$/,Ys=/^[A-Za-z0-9]{27}$/,Xs=/^[a-zA-Z0-9_-]{21}$/;function nanoidOfLength(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}const Zs=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Qs=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,$s=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function emoji(){return/* @__PURE__ */ RegExp(`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`)}const ec=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,tc=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,nc=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,rc=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ic=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ac=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,oc=/^https?$/,sc=/^\+[1-9]\d{6,14}$/,cc=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;function anchor(e){return RegExp(`^${e}$`)}const lc=/*@__PURE__*/ anchor(cc);function timeSource(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time(e){return RegExp(`^${timeSource(e)}$`)}function datetime(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${timeSource({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${timeSource({precision:e.precision})}`:n;return RegExp(`^${cc}T(?:${r})$`)}const uc=/^[\s\S]{0,}$/,dc=/^-?\d+$/,fc=/^-?\d+(?:\.\d+)?$/,pc=/^(?:true|false)$/i,mc=/^null$/i,hc=/^[^A-Z]*$/,gc=/^[^a-z]*$/,U=/*@__PURE__*/ $constructor(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),_whenHasLength=e=>{let t=e.value;return!nullish(t)&&t.length!==void 0},_c={number:`number`,bigint:`bigint`,object:`date`},vc=/*@__PURE__*/ $constructor(`$ZodCheckLessThan`,(e,t)=>{U.init(e,t);let n=_c[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:_c[typeof r.value]??n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),yc=/*@__PURE__*/ $constructor(`$ZodCheckGreaterThan`,(e,t)=>{U.init(e,t);let n=_c[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:_c[typeof r.value]??n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),bc=/*@__PURE__*/ $constructor(`$ZodCheckMultipleOf`,(e,t)=>{U.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):floatSafeRemainder(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),xc=/*@__PURE__*/ $constructor(`$ZodCheckNumberFormat`,(e,t)=>{U.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=As[t.format];e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Sc=/*@__PURE__*/ $constructor(`$ZodCheckMaxLength`,(e,t)=>{var n;U.init(e,t),(n=e._zod.def).when??(n.when=_whenHasLength),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?codePointLength(r):i)<=t.maximum)return;let a=getLengthableOrigin(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Cc=/*@__PURE__*/ $constructor(`$ZodCheckMinLength`,(e,t)=>{var n;U.init(e,t),(n=e._zod.def).when??(n.when=_whenHasLength),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?codePointLength(r):i)>=t.minimum)return;let a=getLengthableOrigin(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),wc=/*@__PURE__*/ $constructor(`$ZodCheckLengthEquals`,(e,t)=>{var n;U.init(e,t),(n=e._zod.def).when??(n.when=_whenHasLength),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?codePointLength(r):i;if(a===t.length)return;let o=getLengthableOrigin(r),s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Tc=/*@__PURE__*/ $constructor(`$ZodCheckStringFormat`,(e,t)=>{var n,r;U.init(e,t),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Ec=/*@__PURE__*/ $constructor(`$ZodCheckRegex`,(e,t)=>{Tc.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Dc=/*@__PURE__*/ $constructor(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=hc,Tc.init(e,t)}),Oc=/*@__PURE__*/ $constructor(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=gc,Tc.init(e,t)}),kc=/*@__PURE__*/ $constructor(`$ZodCheckIncludes`,(e,t)=>{U.init(e,t);let n=escapeRegex(t.includes);t.pattern=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Ac=/*@__PURE__*/ $constructor(`$ZodCheckStartsWith`,(e,t)=>{U.init(e,t);let n=RegExp(`^${escapeRegex(t.prefix)}.*`);t.pattern??=n,e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),jc=/*@__PURE__*/ $constructor(`$ZodCheckEndsWith`,(e,t)=>{U.init(e,t);let n=RegExp(`.*${escapeRegex(t.suffix)}$`);t.pattern??=n,e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Mc=/*@__PURE__*/ $constructor(`$ZodCheckOverwrite`,(e,t)=>{U.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Doc=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{--this.indent}}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.content??[``];return new e(...Object.keys(this.closed),`return function (${this.args.join(`, `)}) {\n${t.join(`
`)}\n};`)(...Object.values(this.closed))}};const Nc={major:4,minor:6,patch:7},W=/*@__PURE__*/ $constructor(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Nc;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let runChecks=(t,n,r)=>{if(t.memo)return t;let i=aborted(t),a;for(let o of n){if(o._zod.def.when){if(explicitlyAborted(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new $ZodAsyncError;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(attachSchema(t.issues,n,e),i||=aborted(t,n))});else{if(t.issues.length===n)continue;attachSchema(t.issues,n,e),i||=aborted(t,n)}}return a?a.then(()=>t):t},handleCanaryResult=(t,n,r)=>{if(aborted(t))return t.aborted=!0,t;let a=runChecks(n,i,r);if(a instanceof Promise){if(r.async===!1)throw new $ZodAsyncError;return a.then(t=>e._zod.parse(t,r))}return e._zod.parse(a,r)};e._zod.run=(t,n)=>{if(n.skipChecks)return e._zod.parse(t,n);if(n.direction===`backward`){let r=e._zod.parse({value:t.value,issues:[]},{...n,skipChecks:!0});return r instanceof Promise?r.then(e=>handleCanaryResult(e,t,n)):handleCanaryResult(r,t,n)}let r=e._zod.parse(t,n);if(r instanceof Promise){if(n.async===!1)throw new $ZodAsyncError;return r.then(e=>runChecks(e,i,n))}return runChecks(r,i,n)}}},{get"~standard"(){return hide(this,`~standard`,standardProps(this))},set"~standard"(e){own(this,`~standard`,e)}}),toStandardResult=(e,t)=>e.issues.length?{issues:e.issues.map(e=>finalizeIssue(e,t,config()))}:{value:e.value};async function validateAsync(e,t){let n={async:!0};return toStandardResult(await e._zod.run({value:t,issues:[]},n),n)}function standardProps(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return toStandardResult(r,n)}catch{}return validateAsync(e,t)},vendor:`zod`,version:1}}const Pc=/*@__PURE__*/ $constructor(`$ZodString`,(e,t)=>{W.init(e,t),e._zod.pattern=t.pattern??uc,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),G=/*@__PURE__*/ $constructor(`$ZodStringFormat`,(e,t)=>{Tc.init(e,t),Pc.init(e,t)}),Fc=/*@__PURE__*/ $constructor(`$ZodGUID`,(e,t)=>{t.pattern??=Qs,G.init(e,t)}),Ic=/*@__PURE__*/ $constructor(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=uuid(e)}else t.pattern??=uuid();G.init(e,t)}),Lc=/*@__PURE__*/ $constructor(`$ZodEmail`,(e,t)=>{t.pattern??=$s,G.init(e,t)});function canParseURL(e){try{return typeof URL<`u`&&typeof URL.canParse==`function`?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function validateURL(e,t){return!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t)?canParseURL(e)||2:parseURLObject(e,t)}function parseURLObject(e,t){if(!t.normalize&&t.protocol?.source===oc.source&&!/^https?:\/\//i.test(e))return 1;try{if(typeof URL<`u`){let t=URL;if(typeof t.parse==`function`)return t.parse(e)??2}return new URL(e)}catch{return 2}}const Rc=/[\t\n\r]/g;function stripTabAndNewline(e){return e.replace(Rc,``)}function urlHostnameOk(e,t){return t.lastIndex=0,t.test(e.hostname)}function urlProtocolOk(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}const zc=/*@__PURE__*/ $constructor(`$ZodURL`,(e,t)=>{G.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=validateURL(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=stripTabAndNewline(r);return}t.hostname&&!urlHostnameOk(i,t.hostname)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!urlProtocolOk(i,t.protocol)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:stripTabAndNewline(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Bc=/*@__PURE__*/ $constructor(`$ZodEmoji`,(e,t)=>{t.pattern??=emoji(),G.init(e,t)}),Vc=/*@__PURE__*/ $constructor(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?Xs:nanoidOfLength(t.length),G.init(e,t)}),Hc=/*@__PURE__*/ $constructor(`$ZodCUID`,(e,t)=>{t.pattern??=Gs,G.init(e,t)}),Uc=/*@__PURE__*/ $constructor(`$ZodCUID2`,(e,t)=>{t.pattern??=Ks,G.init(e,t)}),Wc=/*@__PURE__*/ $constructor(`$ZodULID`,(e,t)=>{t.pattern??=qs,G.init(e,t)}),Gc=/*@__PURE__*/ $constructor(`$ZodXID`,(e,t)=>{t.pattern??=Js,G.init(e,t)}),Kc=/*@__PURE__*/ $constructor(`$ZodKSUID`,(e,t)=>{t.pattern??=Ys,G.init(e,t)}),qc=/*@__PURE__*/ $constructor(`$ZodISODateTime`,(e,t)=>{t.pattern??=datetime(t),G.init(e,t)}),Jc=/*@__PURE__*/ $constructor(`$ZodISODate`,(e,t)=>{t.pattern??=lc,G.init(e,t)}),Yc=/*@__PURE__*/ $constructor(`$ZodISOTime`,(e,t)=>{t.pattern??=time(t),G.init(e,t)}),Xc=/*@__PURE__*/ $constructor(`$ZodISODuration`,(e,t)=>{t.pattern??=Zs,G.init(e,t)}),Zc=/*@__PURE__*/ $constructor(`$ZodIPv4`,(e,t)=>{t.pattern??=ec,G.init(e,t)}),Qc=/^[0-9a-fA-F:.]+$/;function isValidIPv6(e){return Qc.test(e)?canParseURL(`http://[${e}]`):!1}const $c=/*@__PURE__*/ $constructor(`$ZodIPv6`,(e,t)=>{t.pattern??=tc,G.init(e,t),e._zod.check=n=>{isValidIPv6(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),el=/*@__PURE__*/ $constructor(`$ZodCIDRv4`,(e,t)=>{t.pattern??=nc,G.init(e,t)});function isValidCIDRv6(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:isValidIPv6(n)}const tl=/*@__PURE__*/ $constructor(`$ZodCIDRv6`,(e,t)=>{t.pattern??=rc,G.init(e,t),e._zod.check=n=>{isValidCIDRv6(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function isValidBase64(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const nl=/^[0-9a-zA-Z+/]*={0,2}$/,rl=/*@__PURE__*/ $constructor(`$ZodBase64`,(e,t)=>{t.pattern??=nl,G.init(e,t),e._zod.check=n=>{isValidBase64(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),il=/^[A-Za-z0-9_-]*$/;function isValidBase64URL(e){if(!il.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return isValidBase64(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const al=/*@__PURE__*/ $constructor(`$ZodBase64URL`,(e,t)=>{t.pattern??=il,G.init(e,t),e._zod.check=n=>{isValidBase64URL(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),ol=/*@__PURE__*/ $constructor(`$ZodE164`,(e,t)=>{t.pattern??=sc,G.init(e,t)});function isValidJWT(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}const sl=/*@__PURE__*/ $constructor(`$ZodJWT`,(e,t)=>{G.init(e,t),e._zod.check=n=>{isValidJWT(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),cl=/*@__PURE__*/ $constructor(`$ZodNumber`,(e,t)=>{W.init(e,t),e._zod.pattern=fc,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),ll=/*@__PURE__*/ $constructor(`$ZodNumberFormat`,(e,t)=>{xc.init(e,t),cl.init(e,t)}),ul=/*@__PURE__*/ $constructor(`$ZodBoolean`,(e,t)=>{W.init(e,t),e._zod.pattern=pc,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),dl=/*@__PURE__*/ $constructor(`$ZodNull`,(e,t)=>{W.init(e,t),e._zod.pattern=mc,e._zod.values=/* @__PURE__ */ new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),fl=/*@__PURE__*/ $constructor(`$ZodUnknown`,(e,t)=>{W.init(e,t),e._zod.parse=e=>e}),pl=/*@__PURE__*/ $constructor(`$ZodNever`,(e,t)=>{W.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function capSize(e,t){let n=sizeCaps(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map(e=>e[0])),i=e._zod.parse;e._zod.parse=(n,a)=>{let o=t(n.value);if(o>r&&!a?.skipChecks&&a?.direction!==`backward`){for(let[t,r]of sizeCaps(e._zod.def.checks))if(o>t&&r._zod.def.when(n)){let t=n.issues.length;return r._zod.check(n),n.issues[t].continue=!1,attachSchema(n.issues,t,e),n}}return i(n,a)}}const arraySize=e=>Array.isArray(e)?e.length:-1;function handleArrayResult(e,t,n){e.issues.length&&t.issues.push(...prefixIssues(n,e.issues)),t.value[n]=e.value}const ml=/*@__PURE__*/ $constructor(`$ZodArray`,(e,t)=>{W.init(e,t);let n=H.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[],s=i?.abortEarly;for(let e=0;e<a.length;e++){let n=a[e],c=t.element._zod.run({value:n,issues:[]},i);if(c instanceof Promise)o.push(c.then(t=>handleArrayResult(t,r,e)));else if(handleArrayResult(c,r,e),s&&c.issues.length!==0&&aborted(c))break}return o.length?Promise.all(o).then(()=>r):r},capSize(e,arraySize)});function handlePropertyResult(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...prefixIssues(n,e.issues))}!o&&i===void 0?e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]}):e.value===void 0?(o||i===`defaulted`&&!s)&&(t.value[n]=void 0):t.value[n]=e.value}}const hl=[];function normalizeDef(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:hl,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=optionalKeys(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function handleCatchall(e,t,n,r,i,a,o){let s=[],c=i.keySet,l=i.catchall._zod,u=l.def.type,d=l.optin,f=l.optout,p=0;for(let i in t){if(o&&n.issues.length!==p){if(aborted(n,p))break;p=n.issues.length}if(c.has(i))continue;if(i===`__proto__`){u===`never`&&s.push(i);continue}if(u===`never`){s.push(i);continue}let a=l.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>handlePropertyResult(e,n,i,t,d,f))):handlePropertyResult(a,n,i,t,d,f)}return s.length&&n.issues.push({code:`unrecognized_keys`,keys:s,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const gl=/*@__PURE__*/ $constructor(`$ZodObject`,(e,t)=>{W.init(e,t);let n=Object.getOwnPropertyDescriptor(t,`shape`),r=n?.get?n.get.raw:t.shape??{};if(r){let get=()=>{let e={...r};return Object.defineProperty(t,"shape",{value:e}),get.raw=e,e};get.raw=r,Object.defineProperty(t,"shape",{get})}let i=cached(()=>normalizeDef(t));defineLazyInternal(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||assignProp(n,e,/* @__PURE__ */ new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let a=isObject,o=t.catchall,s,c=H.memoizer;c?.attach(e),e._zod.parse=(t,n)=>{s??=i.value;let r=t.value;if(!a(r))return t.issues.push({expected:`object`,code:`invalid_type`,input:r,inst:e}),t;t.value=c?c.alloc(e,t,{},n):{};let l=[],u=s.shape,d=n?.abortEarly,f=t.issues.length;for(let e of s.allKeys){if(d&&t.issues.length!==f){if(aborted(t,f))break;f=t.issues.length}if(e===`__proto__`)continue;let i=u[e],a=i._zod.optin,o=i._zod.optout,s=i._zod.run({value:r[e],issues:[]},n);s instanceof Promise?l.push(s.then(n=>handlePropertyResult(n,t,e,r,a,o))):handlePropertyResult(s,t,e,r,a,o)}return o?handleCatchall(l,r,t,n,i.value,e,d===!0):l.length?Promise.all(l).then(()=>t):t}}),_l=/*@__PURE__*/ $constructor(`$ZodObjectJIT`,(e,t)=>{gl.init(e,t);let n=e._zod.parse,r=cached(()=>normalizeDef(t)),i=H.memoizer,generateFastpass=t=>{let n=r.value,a=n.symbolKeys,o=new Doc([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),parseStr=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,prefixStr=(e,t)=>`
          let ${e}_ab = false;
          for (let i = 0; i < ${e}.issues.length; i++) {
            const iss = ${e}.issues[i];
            iss.path = iss.path ? [${t}, ...iss.path] : [${t}];
            payload.issues.push(iss);
            if (iss.continue !== true) ${e}_ab = true;
          }
          if (${e}_ab && ctx && ctx.abortEarly) {
            payload.value = newResult;
            return payload;
          }`;o.write(`const input = payload.value;`);let s=Object.create(null),c=0;for(let e of n.allKeys)s[e]=`key_${c++}`;o.write(i?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(let e of n.allKeys){if(e===`__proto__`)continue;let n=s[e],r=typeof e==`symbol`?`syms[${a.indexOf(e)}]`:esc(e),i=`${r} in input`,c=t[e],l=c?._zod?.optin,u=l!==void 0,d=c?._zod?.optout===`optional`;if(o.write(`const ${n} = ${parseStr(r)};`),u&&d){let e=l===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;o.write(`
        const ${n}_present = ${i};
        if (!${n}.issues.length || ${n}_present) {
          if (${n}.issues.length) {${prefixStr(n,r)}
          }

          if (${e}) {
            newResult[${r}] = ${n}.value;
          }
        }

      `)}else u?(o.write(`
        if (${n}.issues.length) {${prefixStr(n,r)}
        }
      `),l===`defaulted`?o.write(`newResult[${r}] = ${n}.value;`):o.write(`
        if (${n}.value !== undefined || ${i}) {
          newResult[${r}] = ${n}.value;
        }
      `)):o.write(`
        const ${n}_present = ${i};
        if (${n}.issues.length) {${prefixStr(n,r)}
        }
        if (!${n}_present && !${n}.issues.length) {
          payload.issues.push({
            code: "invalid_type",
            expected: "nonoptional",
            input: undefined,
            path: [${r}]
          });
          if (ctx && ctx.abortEarly) {
            payload.value = newResult;
            return payload;
          }
        }

        if (${n}_present) {
          newResult[${r}] = ${n}.value;
        }

      `)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},a,o=isObject,s=!H.jitless,c=s&&Os.value,l=t.catchall,u;e._zod.parse=(i,d)=>{u??=r.value;let f=i.value;return o(f)?s&&c&&d?.async===!1&&d.jitless!==!0?(a||=generateFastpass(t.shape),i=a(i,d),l?handleCatchall([],f,i,d,u,e,d?.abortEarly===!0):i):n(i,d):(i.issues.push({expected:`object`,code:`invalid_type`,input:f,inst:e}),i)}});function handleUnionResults(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!aborted(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>finalizeIssue(e,r,config())))}),t)}const vl=/*@__PURE__*/ $constructor(`$ZodUnion`,(e,t)=>{W.init(e,t),defineLazyInternal(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),defineLazyInternal(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),defineLazyInternal(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),defineLazyInternal(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>cleanRegex(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>handleUnionResults(t,r,e,i)):handleUnionResults(o,r,e,i)}});function discriminatorMap(e){let t=/* @__PURE__ */ new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let e of r)if(t.has(e)){if(e!==void 0)throw Error(`Duplicate discriminator value "${String(e)}"`);t.set(e,null)}else t.set(e,n)}return t}const yl=/*@__PURE__*/ $constructor(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,vl.init(e,t);let n=e._zod.parse;defineLazyInternal(e,`propValues`,e=>{let t={},n=0;for(let r of e.def.options){let i=r._zod.propValues;if(!i||Object.keys(i).length===0)throw Error(`Invalid discriminated union option at index "${e.def.options.indexOf(r)}"`);i[e.def.discriminator]?.has(void 0)&&n++;for(let[e,n]of Object.entries(i)){Object.prototype.hasOwnProperty.call(t,e)||assignProp(t,e,/* @__PURE__ */ new Set);for(let r of n)t[e].add(r)}}return!e.def.unionFallback&&n>1&&t[e.def.discriminator]?.delete(void 0),t}),t.options.forEach((e,n)=>{let r=rawShape(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw Error(`Invalid discriminated union option at index "${n}"`)});let r=cached(()=>discriminatorMap(t));e._zod.parse=(i,a)=>{let o=i.value;if(!isObject(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=o?.[t.discriminator],c=r.value.get(s);return c&&(s!==void 0||a.direction!==`backward`)?c._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()).filter(e=>r.value.get(e)!==null),input:o,path:[t.discriminator],inst:e}),i)}}),bl=/*@__PURE__*/ $constructor(`$ZodIntersection`,(e,t)=>{W.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>handleIntersectionResults(e,t,n)):handleIntersectionResults(e,i,a)}});function mergeValues(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(isPlainObject(e)&&isPlainObject(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=mergeValues(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=mergeValues(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(e,t,n){let r=/* @__PURE__ */ new Map,i,a=/* @__PURE__ */ new Map,collect=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)collect(n,`l`)||e.issues.push(n);for(let t of n.issues)collect(t,`r`)||e.issues.push(t);let o=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(o.length){let t=i?o.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of o)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let s=mergeValues(t.value,n.value);if(!s.valid){if(aborted(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`)}return e.value=s.data,e}const xl=/*@__PURE__*/ $constructor(`$ZodRecord`,(e,t)=>{W.init(e,t);let n=H.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!isPlainObject(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=/* @__PURE__ */ new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>finalizeIssue(e,i,config())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...prefixIssues(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...prefixIssues(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&fc.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>finalizeIssue(e,i,config())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...prefixIssues(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...prefixIssues(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),Sl=/*@__PURE__*/ $constructor(`$ZodEnum`,(e,t)=>{W.init(e,t);let n=getEnumValues(t.entries),r=new Set(n);e._zod.values=r,defineLazyInternal(e,`pattern`,e=>{let t=getEnumValues(e.def.entries).filter(e=>ks.has(typeof e));return RegExp(t.length?`^(${t.map(e=>escapeRegex(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),Cl=/*@__PURE__*/ $constructor(`$ZodLiteral`,(e,t)=>{W.init(e,t);let n=new Set(t.values);e._zod.values=n,defineLazyInternal(e,`pattern`,e=>{let t=e.def.values;return RegExp(t.length?`^(${t.map(e=>typeof e==`string`?escapeRegex(e):e?escapeRegex(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),wl=/*@__PURE__*/ $constructor(`$ZodTransform`,(e,t)=>{W.init(e,t),e._zod.optin=`optional`,H.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $ZodEncodeError(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new $ZodAsyncError;return n.value=i,n}});function handleOptionalResult(e,t){return e.value=t.issues.length?void 0:t.value,e}const Tl=/*@__PURE__*/ $constructor(`$ZodOptional`,(e,t)=>{W.init(e,t),defineLazyInternal(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,defineLazyInternal(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?/* @__PURE__ */ new Set([...t,void 0]):void 0}),defineLazyInternal(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${cleanRegex(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>handleOptionalResult(e,t)):handleOptionalResult(e,r)}return t.innerType._zod.run(e,n)}}),El=/*@__PURE__*/ $constructor(`$ZodExactOptional`,(e,t)=>{Tl.init(e,t),defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),defineLazyInternal(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Dl=/*@__PURE__*/ $constructor(`$ZodNullable`,(e,t)=>{W.init(e,t),defineLazyInternal(e,`optin`,e=>e.def.innerType._zod.optin),defineLazyInternal(e,`optout`,e=>e.def.innerType._zod.optout),defineLazyInternal(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${cleanRegex(t.source)}|null)$`):void 0}),defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values?/* @__PURE__ */ new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Ol=/*@__PURE__*/ $constructor(`$ZodDefault`,(e,t)=>{W.init(e,t),e._zod.optin=`defaulted`,defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>handleDefaultResult(e,t)):handleDefaultResult(r,t)}});function handleDefaultResult(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const kl=/*@__PURE__*/ $constructor(`$ZodPrefault`,(e,t)=>{W.init(e,t),e._zod.optin=`defaulted`,defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Al=/*@__PURE__*/ $constructor(`$ZodNonOptional`,(e,t)=>{W.init(e,t),defineLazyInternal(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>handleNonOptionalResult(t,e)):handleNonOptionalResult(i,e)}});function handleNonOptionalResult(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function handleCatchResult(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>finalizeIssue(e,r,config()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}const jl=/*@__PURE__*/ $constructor(`$ZodCatch`,(e,t)=>{W.init(e,t),defineLazyInternal(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),defineLazyInternal(e,`optout`,e=>e.def.innerType._zod.optout),defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>handleCatchResult(e,r,t,n)):handleCatchResult(e,r,t,n)}}),Ml=/*@__PURE__*/ $constructor(`$ZodPipe`,(e,t)=>{W.init(e,t),defineLazyInternal(e,`values`,e=>e.def.in._zod.values),defineLazyInternal(e,`optin`,e=>e.def.in._zod.optin),defineLazyInternal(e,`optout`,e=>e.def.out._zod.optout),defineLazyInternal(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>handlePipeResult(e,t.in,n)):handlePipeResult(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>handlePipeResult(e,t.out,n)):handlePipeResult(r,t.out,n)}});function handlePipeResult(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Nl=/*@__PURE__*/ $constructor(`$ZodReadonly`,(e,t)=>{W.init(e,t),defineLazyInternal(e,`propValues`,e=>e.def.innerType._zod.propValues),defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),defineLazyInternal(e,`optin`,e=>e.def.innerType?._zod?.optin),defineLazyInternal(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(handleReadonlyResult):handleReadonlyResult(r)}});function handleReadonlyResult(e){return e.memo||(e.value=Object.freeze(e.value)),e}const Pl=/*@__PURE__*/ $constructor(`$ZodCustom`,(e,t)=>{U.init(e,t),W.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>handleRefineResult(t,n,r,e));handleRefineResult(i,n,r,e)}});function handleRefineResult(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(issue(e))}}var $ZodCyclicError=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}};const Fl=`~memo`,Il=[];function isRef(e){return typeof e==`object`&&!!e}function cloneIssues(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}const Ll=/*@__PURE__*/ new WeakMap;function isRecursive(e,t,n){let r=Ll.get(e);if(r!==void 0)return r?2:0;if(t.has(e))return 2;t.add(e);let i=0,check=e=>{if(i!==2&&e?._zod){let r=isRecursive(e,t,n);r>i&&(i=r)}},shape=(e,r)=>{let i=0;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?1:o.value?._zod?isRecursive(o.value,t,n):0;s>i&&(i=s)}return i},merge=e=>{e>i&&(i=e)},a=e._zod.def;switch(a.type){case`object`:{let e=rawShape(a);merge(e?shape(e,!0):1),check(a.catchall);break}case`array`:check(a.element);break;case`tuple`:for(let e of a.items)check(e);check(a.rest);break;case`record`:case`map`:check(a.keyType),check(a.valueType);break;case`set`:check(a.valueType);break;case`union`:for(let e of a.options)check(e);break;case`intersection`:check(a.left),check(a.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:check(a.innerType);break;case`pipe`:check(a.in),check(a.out);break;case`function`:check(a.input),check(a.output);break;case`lazy`:{let r=a._cachedInner??(n?e._zod.innerType:void 0);merge(r?isRecursive(r,t,!1):1);break}case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in a){let t=Object.getOwnPropertyDescriptor(a,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)check(n);else if(Array.isArray(n))for(let e of n)check(e)}}}return t.delete(e),settle(e,i)}function settle(e,t){return t!==1&&Ll.set(e,t===2),t}function bucketFor(e,t){let n=e.buckets.get(t);return n||(n=/* @__PURE__ */ new WeakMap,e.buckets.set(t,n)),n}let Rl;const zl=[],Bl={alloc(e,t,n){let r=Rl;if(!r)return n;Rl=void 0;let i={value:n,issues:null};return r.set(t.value,i),zl.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,wrapped=(e,n)=>{if(n.direction!==`backward`&&isBackEdge(n,e.value))throw new $ZodCyclicError;return t(e,n)};e._zod.parse=wrapped,e._zod.run===t&&(e._zod.run=wrapped)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,wrapped=(o,s)=>{if(n===void 0){let i=isRecursive(e,/* @__PURE__ */ new Set,!1);if(i===0)return e._zod.parse=t,e._zod.run===wrapped&&(e._zod.run=t),t(o,s);i===2||r?n=!0:r=!0}let c=o.value;if(!isRef(c))return t(o,s);let l=s[Fl];l||(l={buckets:/* @__PURE__ */ new WeakMap,backEdges:void 0},s[Fl]=l);let u;i===s?u=a:(u=bucketFor(l,e),i=s,a=u);let d=u.get(c);if(d)return o.value=d.value,d.issues?d.issues.length&&o.issues.push(...cloneIssues(d.issues)):(o.memo=!0,l.backEdges??(l.backEdges=/* @__PURE__ */ new WeakSet),l.backEdges.add(d.value)),o;Rl=u;let f=zl.length,p=t(o,s);Rl=void 0;let m=zl.length>f?zl.pop():void 0;return p instanceof Promise?p.then(e=>(m&&(m.issues=e.issues.length?cloneIssues(e.issues):Il),e)):(m&&(m.issues=p.issues.length?cloneIssues(p.issues):Il),p)};e._zod.parse=wrapped,e._zod.run===t&&(e._zod.run=wrapped)})}};function memoizer(){return Bl}function isBackEdge(e,t){let n=e[Fl]?.backEdges;return n!==void 0&&isRef(t)&&n.has(t)}const error=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function getSizing(t){return e[t]??null}let t={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,currency_code:`currency code`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},n={nan:`NaN`};function getTypeName(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):n[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${getTypeName(e.expected)}, received ${getTypeName(parsedType(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${stringifyPrimitive(e.values[0])}`:`Invalid option: expected one of ${joinValues(e.values,`|`)}`;case`too_big`:{let t=e.exact?`exactly `:e.inclusive?`<=`:`<`,n=getSizing(e.origin);return n?`Too big: expected ${e.origin??`value`} to have ${t}${e.maximum.toString()} ${n.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${t}${e.maximum.toString()}`}case`too_small`:{let t=e.exact?`exactly `:e.inclusive?`>=`:`>`,n=getSizing(e.origin);return n?`Too small: expected ${e.origin} to have ${t}${e.minimum.toString()} ${n.unit}`:`Too small: expected ${e.origin} to be ${t}${e.minimum.toString()}`}case`invalid_format`:{let n=e;return n.format===`starts_with`?`Invalid string: must start with "${n.prefix}"`:n.format===`ends_with`?`Invalid string: must end with "${n.suffix}"`:n.format===`includes`?`Invalid string: must include "${n.includes}"`:n.format===`regex`?`Invalid string: must match pattern ${n.pattern}`:`Invalid ${t[n.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${joinValues(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function en_default(){return{localeError:error()}}var Vl,$ZodRegistry=class{constructor(){this._map=/* @__PURE__ */ new WeakMap,this._idmap=/* @__PURE__ */ new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=/* @__PURE__ */ new WeakMap,this._idmap=/* @__PURE__ */ new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function registry(){return new $ZodRegistry}(Vl=globalThis).__zod_globalRegistry??(Vl.__zod_globalRegistry=registry());const Hl=globalThis.__zod_globalRegistry;function snapshotChecks(e){return e.checks&&=[...e.checks],e}// @__NO_SIDE_EFFECTS__
function _string(e,t){return new e(snapshotChecks({type:`string`,...normalizeParams(t)}))}// @__NO_SIDE_EFFECTS__
function _coercedString(e,t){return new e(snapshotChecks({type:`string`,coerce:!0,...normalizeParams(t)}))}// @__NO_SIDE_EFFECTS__
function _email(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _guid(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _uuid(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _uuidv4(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _uuidv6(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _uuidv7(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _url(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _emoji(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _nanoid(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _cuid(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _cuid2(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _ulid(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _xid(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _ksuid(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _ipv4(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _ipv6(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _cidrv4(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _cidrv6(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _base64(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _base64url(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _e164(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _jwt(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _isoDateTime(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _isoDate(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _isoTime(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _isoDuration(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _number(e,t){return new e(snapshotChecks({type:`number`,checks:[],...normalizeParams(t)}))}// @__NO_SIDE_EFFECTS__
function _int(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _boolean(e,t){return new e({type:`boolean`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _null$1(e,t){return new e({type:`null`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _unknown(e){return new e({type:`unknown`})}// @__NO_SIDE_EFFECTS__
function _never(e,t){return new e({type:`never`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _lt(e,t){return new vc({check:`less_than`,...normalizeParams(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
function _lte(e,t){return new vc({check:`less_than`,...normalizeParams(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
function _gt(e,t){return new yc({check:`greater_than`,...normalizeParams(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
function _gte(e,t){return new yc({check:`greater_than`,...normalizeParams(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
function _multipleOf(e,t){return new bc({check:`multiple_of`,...normalizeParams(t),value:e})}// @__NO_SIDE_EFFECTS__
function _maxLength(e,t){return new Sc({check:`max_length`,...normalizeParams(t),maximum:e})}// @__NO_SIDE_EFFECTS__
function _minLength(e,t){return new Cc({check:`min_length`,...normalizeParams(t),minimum:e})}// @__NO_SIDE_EFFECTS__
function _length(e,t){return new wc({check:`length_equals`,...normalizeParams(t),length:e})}// @__NO_SIDE_EFFECTS__
function _regex(e,t){return new Ec({check:`string_format`,format:`regex`,...normalizeParams(t),pattern:e})}// @__NO_SIDE_EFFECTS__
function _lowercase(e){return new Dc({check:`string_format`,format:`lowercase`,...normalizeParams(e)})}// @__NO_SIDE_EFFECTS__
function _uppercase(e){return new Oc({check:`string_format`,format:`uppercase`,...normalizeParams(e)})}// @__NO_SIDE_EFFECTS__
function _includes(e,t){return new kc({check:`string_format`,format:`includes`,...normalizeParams(t),includes:e})}// @__NO_SIDE_EFFECTS__
function _startsWith(e,t){return new Ac({check:`string_format`,format:`starts_with`,...normalizeParams(t),prefix:e})}// @__NO_SIDE_EFFECTS__
function _endsWith(e,t){return new jc({check:`string_format`,format:`ends_with`,...normalizeParams(t),suffix:e})}// @__NO_SIDE_EFFECTS__
function _overwrite(e){return new Mc({check:`overwrite`,tx:e})}// @__NO_SIDE_EFFECTS__
function _normalize(e){return/* @__PURE__ */ _overwrite(t=>t.normalize(e))}// @__NO_SIDE_EFFECTS__
function _trim(){return/* @__PURE__ */ _overwrite(e=>e.trim())}// @__NO_SIDE_EFFECTS__
function _toLowerCase(){return/* @__PURE__ */ _overwrite(e=>e.toLowerCase())}// @__NO_SIDE_EFFECTS__
function _toUpperCase(){return/* @__PURE__ */ _overwrite(e=>e.toUpperCase())}// @__NO_SIDE_EFFECTS__
function _slugify(){return/* @__PURE__ */ _overwrite(e=>slugify(e))}// @__NO_SIDE_EFFECTS__
function _array(e,t,n){return new e({type:`array`,element:t,...normalizeParams(n)})}// @__NO_SIDE_EFFECTS__
function _custom(e,t,n){let r=normalizeParams(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}// @__NO_SIDE_EFFECTS__
function _refine(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...normalizeParams(n)})}// @__NO_SIDE_EFFECTS__
function _superRefine(e,t){let n=/* @__PURE__ */ _check(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(issue(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(issue(r))}},e(t.value,t)),t);return n}// @__NO_SIDE_EFFECTS__
function _check(e,t){let n=new U({check:`custom`,...normalizeParams(t)});return n._zod.check=e,n}function assignProps(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&assignProp(e,t,n[t]);return e}function initializeContext(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Hl,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:/* @__PURE__ */ new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function handleUnrepresentable(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function processSchema(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,processSchema(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&assignProps(o.schema,c),t.io===`input`&&isTransforming(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function encodeJSONPointerSegment(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function extractDefs(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=/* @__PURE__ */ new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let makeURI=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${encodeJSONPointerSegment(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+encodeJSONPointerSegment(a)}},extractToDef=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=makeURI(e);t.def={...t.schema},r&&(t.defId=r);let i=t.schema;for(let e in i)delete i[e];i.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>

Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])extractToDef(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){extractToDef(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&extractToDef(n)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function compactTypeUnion(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;compactTypeUnion(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}const Ul=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]),Wl=[`oneOf`,`anyOf`];function undeclaredConstraint(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function foldObjects(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!Ul.has(e))return null;t.push(n)}let n={},r=/* @__PURE__ */ new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??undeclaredConstraint(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}assignProp(n,r,e.length===1?e[0]:foldObjects(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=undeclaredConstraint(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function foldIntersection(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of Ul)if(t in e)return;let n=t.filter(e=>Wl.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=foldObjects(t);else{let e=n[0],i=Wl.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>foldObjects([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,assignProps(e,r))}function finalize(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let flattenRef=t=>{let n=e.seen.get(t);if(n.ref===null)return;let r=n.def??n.schema,i={...r},a=n.ref;if(n.ref=null,a){flattenRef(a);let n=e.seen.get(a),o=n.schema;if(o.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(r.allOf=r.allOf??[],r.allOf.push(o)):assignProps(r,o),assignProps(r,i),t._zod.parent===a)for(let e in r)e!==`$ref`&&e!==`allOf`&&(e in i||delete r[e]);if(o.$ref&&n.def)for(let e in r)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(r[e])===JSON.stringify(n.def[e])&&delete r[e]}let o=t._zod.parent;if(o&&o!==a){flattenRef(o);let t=e.seen.get(o);if(t?.schema.$ref&&(r.$ref=t.schema.$ref,t.def))for(let e in r)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(r[e])===JSON.stringify(t.def[e])&&delete r[e]}e.override({zodSchema:t,jsonSchema:r,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())flattenRef(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())compactTypeUnion(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])foldIntersection(e)}}let r={};if(e.target===`draft-2020-12`?r.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?r.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?r.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");r.$id=e.external.uri(n)}assignProps(r,n.defId?n.schema:n.def??n.schema);let i=e.metadataRegistry.get(t)?.id;i!==void 0&&r.id===i&&delete r.id;let a=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,assignProp(a,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(a).length>0&&(e.target===`draft-2020-12`?r.$defs=a:r.definitions=a);try{let n=JSON.parse(JSON.stringify(r));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:createStandardJSONSchemaMethod(t,`input`,e.processors),output:createStandardJSONSchemaMethod(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function isTransforming(e,t){let n=t??{seen:/* @__PURE__ */ new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return isTransforming(r.element,n);if(r.type===`set`)return isTransforming(r.valueType,n);if(r.type===`lazy`)return isTransforming(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return isTransforming(r.innerType,n);if(r.type===`intersection`)return isTransforming(r.left,n)||isTransforming(r.right,n);if(r.type===`record`||r.type===`map`)return isTransforming(r.keyType,n)||isTransforming(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:isTransforming(r.in,n)||isTransforming(r.out,n);if(r.type===`object`){for(let e in r.shape)if(isTransforming(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(isTransforming(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(isTransforming(e,n))return!0;return!!(r.rest&&isTransforming(r.rest,n))}return!1}const createToJSONSchemaMethod=(e,t={})=>n=>{let r=initializeContext({...n,processors:t});return processSchema(e,r),extractDefs(r,e),finalize(r,e)},createStandardJSONSchemaMethod=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=initializeContext({...i??{},target:a,io:t,processors:n});return processSchema(e,o),extractDefs(o,e),finalize(o,e)},narrowMin=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},narrowMax=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},narrowBoth=(e,t)=>{narrowMin(e,`minimum`,t),narrowMax(e,`maximum`,t)},addDivisor=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},addPattern=(e,t)=>{e.patterns??=/* @__PURE__ */ new Set,e.patterns.add(t)},intersectMime=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},setFormat=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},minContributor=(e,t)=>narrowMin(e,`minimum`,t.minimum),maxContributor=(e,t)=>narrowMax(e,`maximum`,t.maximum),formatContributor=e=>(t,n)=>{setFormat(t,n.format);let[r,i]=e[n.format];narrowMin(t,`minimum`,r),narrowMax(t,`maximum`,i)},Gl={greater_than:(e,t)=>narrowMin(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>narrowMax(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>addDivisor(e,t.value),number_format:formatContributor(As),bigint_format:formatContributor(js),min_length:minContributor,max_length:maxContributor,length_equals:(e,t)=>narrowBoth(e,t.length),min_size:minContributor,max_size:maxContributor,size_equals:(e,t)=>narrowBoth(e,t.size),string_format:(e,t)=>{setFormat(e,t.format),t.pattern&&addPattern(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>intersectMime(e,t.mime)};function aggregateChecks(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)Gl[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&narrowMin(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&narrowMin(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&narrowMax(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&narrowMax(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&addDivisor(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&intersectMime(t,i.mime);for(let e of i.patterns??[])addPattern(t,e);return t}const Kl={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},ql=/* @__PURE__ */ new Map([[nl,ic],[il,ac]]),exactPattern=e=>ql.get(e)??e,stringProcessor=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=aggregateChecks(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Kl[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(exactPattern);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},numberProcessor=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=aggregateChecks(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=/* @__PURE__ */ new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):handleUnrepresentable(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},booleanProcessor=(e,t,n,r)=>{n.type=`boolean`},nullProcessor=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},neverProcessor=(e,t,n,r)=>{n.not={}},enumProcessor=(e,t,n,r)=>{let i=e._zod.def,a=getEnumValues(i.entries);a.length===0?n.not={}:(a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a)},literalProcessor=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(handleUnrepresentable(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(handleUnrepresentable(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},customProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},transformProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},arrayProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=aggregateChecks(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=processSchema(a.element,t,{...r,path:[...r.path,`items`]})};function inputOptin(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?inputOptin(t.out):t.type===`catch`?inputOptin(t.innerType):e._zod.optin}const objectProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&handleUnrepresentable(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)assignProp(i.properties,e,processSchema(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?inputOptin(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=processSchema(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},unionProcessor=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>processSchema(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},intersectionProcessor=(e,t,n,r)=>{let i=e._zod.def,a=processSchema(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=processSchema(i.right,t,{...r,path:[...r.path,`allOf`,1]}),isSimpleIntersection=e=>`allOf`in e&&Object.keys(e).length===1,s=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(o)?o.allOf:[o]];n.allOf=s,t.intersections.push(s)};function stringifyKeyNames(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=stringifyKeyNames(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>stringifyKeyNames(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i&&(p.type=`string`,a||(p.pattern=(r.includes(`number`)?fc:dc).source)),p}const Jl=/* @__PURE__ */ new WeakMap;function rewriteKeyNames(e){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=/* @__PURE__ */ new Map;for(let r of Jl.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=stringifyKeyNames(t,a,/* @__PURE__ */ new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}const recordProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=aggregateChecks(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=processSchema(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)assignProp(i.patternProperties,exactPattern(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=processSchema(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=Jl.get(t);n||(n=[],Jl.set(t,n),t.deferred.push(()=>rewriteKeyNames(t))),n.push(e)}i.additionalProperties=processSchema(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&inputOptin(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},nullableProcessor=(e,t,n,r)=>{let i=e._zod.def,a=processSchema(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},nonoptionalProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Yl=Symbol();function serializeDefaultValue(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(handleUnrepresentable(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Yl):JSON.parse(o)}const defaultProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=serializeDefaultValue(i.defaultValue,e,t,n,r);o!==Yl&&(n.default=o)},prefaultProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=serializeDefaultValue(i.defaultValue,e,t,n,r);o!==Yl&&(n._prefault=o)},catchProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{handleUnrepresentable(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},pipeProcessor=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;processSchema(o,t,r);let s=t.seen.get(e);s.ref=o},readonlyProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},optionalProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Xl=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}const K=/*@__PURE__*/ $constructor(`ZodError`,(e,t)=>{Hs.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);Xl.has(n)||(Xl.add(n),_lazyMethod(n,`format`,e=>t=>formatError(e,t)),_lazyMethod(n,`flatten`,e=>t=>flattenError(e,t)),_lazyMethod(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}),_lazyMethod(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),Zl=/* @__PURE__ */ _parse(K),Ql=/* @__PURE__ */ _parseAsync(K),$l=/* @__PURE__ */ _safeParse(K),eu=/* @__PURE__ */ _safeParseAsync(K),tu=/* @__PURE__ */ _encode(K),nu=/* @__PURE__ */ _decode(K),ru=/* @__PURE__ */ _encodeAsync(K),iu=/* @__PURE__ */ _decodeAsync(K),au=/* @__PURE__ */ _safeEncode(K),ou=/* @__PURE__ */ _safeDecode(K),su=/* @__PURE__ */ _safeEncodeAsync(K),cu=/* @__PURE__ */ _safeDecodeAsync(K);function _ensureDefaultLocale(){H.localeError||config(en_default())}function _ensureDefaultMemoizer(){H.memoizer||config({memoizer:memoizer()})}const q=/*@__PURE__*/ $constructor(`ZodType`,(e,t)=>(_ensureDefaultLocale(),W.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(mergeDefs(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return clone(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(refine(e,t))},superRefine(e,t){return this.check(superRefine(e,t))},overwrite(e){return this.check(/* @__PURE__ */ _overwrite(e))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(e){return nonoptional(this,e)},array(){return array(this)},or(e){return union([this,e])},and(e){return intersection(this,e)},transform(e){return pipe(this,transform(e))},default(e){return _default(this,e)},prefault(e){return prefault(this,e)},catch(e){return _catch(this,e)},pipe(e){return pipe(this,e)},readonly(){return readonly(this)},describe(e){let t=this.clone();return Hl.add(t,{description:e}),t},meta(...e){if(e.length===0)return Hl.get(this);let t=this.clone();return Hl.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return hide(this,`~standard`,{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,`input`),output:createStandardJSONSchemaMethod(this,`output`)}})},set"~standard"(e){own(this,`~standard`,e)},parse:function _parse(e,t){return Zl(this,e,t,{callee:_parse})},parseAsync:async function _parseAsync(e,t){return await Ql(this,e,t,{callee:_parseAsync})},safeParse(e,t){return $l(this,e,t)},async safeParseAsync(e,t){return eu(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){own(this,`spa`,e)},validate(e,t){return validate(this,e,t)},validateAsync(e,t){return validateAsync$1(this,e,t)},encode:function _encode(e,t){return tu(this,e,t,{callee:_encode})},decode:function _decode(e,t){return nu(this,e,t,{callee:_decode})},encodeAsync:async function _encodeAsync(e,t){return await ru(this,e,t,{callee:_encodeAsync})},decodeAsync:async function _decodeAsync(e,t){return await iu(this,e,t,{callee:_decodeAsync})},safeEncode(e,t){return au(this,e,t)},safeDecode(e,t){return ou(this,e,t)},async safeEncodeAsync(e,t){return su(this,e,t)},async safeDecodeAsync(e,t){return cu(this,e,t)},toJSONSchema(e){return createToJSONSchemaMethod(this,{})(e)},get description(){return Hl.get(this)?.description},get _def(){return this._zod.def}}),lu=/*@__PURE__*/ $constructor(`_ZodString`,(e,t)=>{Pc.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>stringProcessor(e,t,n,r)},/*@__PURE__*/ derived({format:e=>aggregateChecks(e).format??null,minLength:e=>aggregateChecks(e).minimum??null,maxLength:e=>aggregateChecks(e).maximum??null},{regex(...e){return this.check(/* @__PURE__ */ _regex(...e))},includes(...e){return this.check(/* @__PURE__ */ _includes(...e))},startsWith(...e){return this.check(/* @__PURE__ */ _startsWith(...e))},endsWith(...e){return this.check(/* @__PURE__ */ _endsWith(...e))},min(...e){return this.check(/* @__PURE__ */ _minLength(...e))},max(...e){return this.check(/* @__PURE__ */ _maxLength(...e))},length(...e){return this.check(/* @__PURE__ */ _length(...e))},nonempty(...e){return this.check(/* @__PURE__ */ _minLength(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ _lowercase(e))},uppercase(e){return this.check(/* @__PURE__ */ _uppercase(e))},trim(){return this.check(/* @__PURE__ */ _trim())},normalize(...e){return this.check(/* @__PURE__ */ _normalize(...e))},toLowerCase(){return this.check(/* @__PURE__ */ _toLowerCase())},toUpperCase(){return this.check(/* @__PURE__ */ _toUpperCase())},slugify(){return this.check(/* @__PURE__ */ _slugify())}})),uu=/*@__PURE__*/ $constructor(`ZodString`,(e,t)=>{Pc.init(e,t),lu.init(e,t)},{email(e){return this.check(/* @__PURE__ */ _email(hu,e))},url(e){return this.check(/* @__PURE__ */ _url(vu,e))},jwt(e){return this.check(/* @__PURE__ */ _jwt(Nu,e))},emoji(e){return this.check(/* @__PURE__ */ _emoji(yu,e))},guid(e){return this.check(/* @__PURE__ */ _guid(gu,e))},uuid(e){return this.check(/* @__PURE__ */ _uuid(_u,e))},uuidv4(e){return this.check(/* @__PURE__ */ _uuidv4(_u,e))},uuidv6(e){return this.check(/* @__PURE__ */ _uuidv6(_u,e))},uuidv7(e){return this.check(/* @__PURE__ */ _uuidv7(_u,e))},nanoid(e){return this.check(/* @__PURE__ */ _nanoid(bu,e))},cuid(e){return this.check(/* @__PURE__ */ _cuid(xu,e))},cuid2(e){return this.check(/* @__PURE__ */ _cuid2(Su,e))},ulid(e){return this.check(/* @__PURE__ */ _ulid(Cu,e))},base64(e){return this.check(/* @__PURE__ */ _base64(Au,e))},base64url(e){return this.check(/* @__PURE__ */ _base64url(ju,e))},xid(e){return this.check(/* @__PURE__ */ _xid(wu,e))},ksuid(e){return this.check(/* @__PURE__ */ _ksuid(Tu,e))},ipv4(e){return this.check(/* @__PURE__ */ _ipv4(Eu,e))},ipv6(e){return this.check(/* @__PURE__ */ _ipv6(Du,e))},cidrv4(e){return this.check(/* @__PURE__ */ _cidrv4(Ou,e))},cidrv6(e){return this.check(/* @__PURE__ */ _cidrv6(ku,e))},e164(e){return this.check(/* @__PURE__ */ _e164(Mu,e))},datetime(e){return this.check(/* @__PURE__ */ _isoDateTime(du,e))},date(e){return this.check(/* @__PURE__ */ _isoDate(fu,e))},time(e){return this.check(/* @__PURE__ */ _isoTime(pu,e))},duration(e){return this.check(/* @__PURE__ */ _isoDuration(mu,e))}});function string(e){return/* @__PURE__ */ _string(uu,e)}const J=/*@__PURE__*/ $constructor(`ZodStringFormat`,(e,t)=>{G.init(e,t),lu.init(e,t)}),du=/*@__PURE__*/ $constructor(`ZodISODateTime`,(e,t)=>{qc.init(e,t),J.init(e,t)}),fu=/*@__PURE__*/ $constructor(`ZodISODate`,(e,t)=>{Jc.init(e,t),J.init(e,t)}),pu=/*@__PURE__*/ $constructor(`ZodISOTime`,(e,t)=>{Yc.init(e,t),J.init(e,t)}),mu=/*@__PURE__*/ $constructor(`ZodISODuration`,(e,t)=>{Xc.init(e,t),J.init(e,t)}),hu=/*@__PURE__*/ $constructor(`ZodEmail`,(e,t)=>{Lc.init(e,t),J.init(e,t)}),gu=/*@__PURE__*/ $constructor(`ZodGUID`,(e,t)=>{Fc.init(e,t),J.init(e,t)}),_u=/*@__PURE__*/ $constructor(`ZodUUID`,(e,t)=>{Ic.init(e,t),J.init(e,t)}),vu=/*@__PURE__*/ $constructor(`ZodURL`,(e,t)=>{zc.init(e,t),J.init(e,t)}),yu=/*@__PURE__*/ $constructor(`ZodEmoji`,(e,t)=>{Bc.init(e,t),J.init(e,t)}),bu=/*@__PURE__*/ $constructor(`ZodNanoID`,(e,t)=>{Vc.init(e,t),J.init(e,t)}),xu=/*@__PURE__*/ $constructor(`ZodCUID`,(e,t)=>{Hc.init(e,t),J.init(e,t)}),Su=/*@__PURE__*/ $constructor(`ZodCUID2`,(e,t)=>{Uc.init(e,t),J.init(e,t)}),Cu=/*@__PURE__*/ $constructor(`ZodULID`,(e,t)=>{Wc.init(e,t),J.init(e,t)}),wu=/*@__PURE__*/ $constructor(`ZodXID`,(e,t)=>{Gc.init(e,t),J.init(e,t)}),Tu=/*@__PURE__*/ $constructor(`ZodKSUID`,(e,t)=>{Kc.init(e,t),J.init(e,t)}),Eu=/*@__PURE__*/ $constructor(`ZodIPv4`,(e,t)=>{Zc.init(e,t),J.init(e,t)}),Du=/*@__PURE__*/ $constructor(`ZodIPv6`,(e,t)=>{$c.init(e,t),J.init(e,t)}),Ou=/*@__PURE__*/ $constructor(`ZodCIDRv4`,(e,t)=>{el.init(e,t),J.init(e,t)}),ku=/*@__PURE__*/ $constructor(`ZodCIDRv6`,(e,t)=>{tl.init(e,t),J.init(e,t)}),Au=/*@__PURE__*/ $constructor(`ZodBase64`,(e,t)=>{rl.init(e,t),J.init(e,t)}),ju=/*@__PURE__*/ $constructor(`ZodBase64URL`,(e,t)=>{al.init(e,t),J.init(e,t)}),Mu=/*@__PURE__*/ $constructor(`ZodE164`,(e,t)=>{ol.init(e,t),J.init(e,t)}),Nu=/*@__PURE__*/ $constructor(`ZodJWT`,(e,t)=>{sl.init(e,t),J.init(e,t)}),Pu=/*@__PURE__*/ $constructor(`ZodNumber`,(e,t)=>{cl.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>numberProcessor(e,t,n,r),e.isFinite=!0},/*@__PURE__*/ derived({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=aggregateChecks(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=aggregateChecks(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=aggregateChecks(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>aggregateChecks(e).format??null},{gt(e,t){return this.check(/* @__PURE__ */ _gt(e,t))},gte(e,t){return this.check(/* @__PURE__ */ _gte(e,t))},min(e,t){return this.check(/* @__PURE__ */ _gte(e,t))},lt(e,t){return this.check(/* @__PURE__ */ _lt(e,t))},lte(e,t){return this.check(/* @__PURE__ */ _lte(e,t))},max(e,t){return this.check(/* @__PURE__ */ _lte(e,t))},int(e){return this.check(int(e))},safe(e){return this.check(int(e))},positive(e){return this.check(/* @__PURE__ */ _gt(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ _gte(0,e))},negative(e){return this.check(/* @__PURE__ */ _lt(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ _lte(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ _multipleOf(e,t))},step(e,t){return this.check(/* @__PURE__ */ _multipleOf(e,t))},finite(){return this}}));function number(e){return/* @__PURE__ */ _number(Pu,e)}const Fu=/*@__PURE__*/ $constructor(`ZodNumberFormat`,(e,t)=>{ll.init(e,t),Pu.init(e,t)});function int(e){return/* @__PURE__ */ _int(Fu,e)}const Iu=/*@__PURE__*/ $constructor(`ZodBoolean`,(e,t)=>{ul.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>booleanProcessor(e,t,n,r)});function boolean(e){return/* @__PURE__ */ _boolean(Iu,e)}const Lu=/*@__PURE__*/ $constructor(`ZodNull`,(e,t)=>{dl.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nullProcessor(e,t,n,r)});function _null(e){return/* @__PURE__ */ _null$1(Lu,e)}const Ru=/*@__PURE__*/ $constructor(`ZodUnknown`,(e,t)=>{fl.init(e,t),q.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function unknown(){return/* @__PURE__ */ _unknown(Ru)}const zu=/*@__PURE__*/ $constructor(`ZodNever`,(e,t)=>{pl.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>neverProcessor(e,t,n,r)});function never(e){return/* @__PURE__ */ _never(zu,e)}const Bu=/*@__PURE__*/ $constructor(`ZodArray`,(e,t)=>{_ensureDefaultMemoizer(),ml.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>arrayProcessor(e,t,n,r),e.element=t.element},{min(e,t){return this.check(/* @__PURE__ */ _minLength(e,t))},nonempty(e){return this.check(/* @__PURE__ */ _minLength(1,e))},max(e,t){return this.check(/* @__PURE__ */ _maxLength(e,t))},length(e,t){return this.check(/* @__PURE__ */ _length(e,t))},unwrap(){return this.element}});function array(e,t){return/* @__PURE__ */ _array(Bu,e,t)}const Vu=/*@__PURE__*/ $constructor(`ZodObject`,(e,t)=>{_ensureDefaultMemoizer(),_l.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>objectProcessor(e,t,n,r),installLazyProp(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return _enum(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown()}))},loose(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown()}))},strict(){return this.clone(mergeDefs(this._zod.def,{catchall:never()}))},strip(){return this.clone(mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return extend(this,e)},safeExtend(e){return safeExtend(this,e)},merge(e){return merge(this,e)},pick(e){return pick(this,e)},omit(e){return omit(this,e)},partial(...e){return partial(Yu,this,e[0])},exactPartial(...e){return partial(Xu,this,e[0],`exactPartial`)},required(...e){return required(ed,this,e[0])}});function object(e,t){let n={type:`object`,shape:e??{},...normalizeParams(t)};return new Vu(n)}function strictObject(e,t){return new Vu({type:`object`,shape:e,catchall:never(),...normalizeParams(t)})}function looseObject(e,t){return new Vu({type:`object`,shape:e,catchall:unknown(),...normalizeParams(t)})}const Hu=/*@__PURE__*/ $constructor(`ZodUnion`,(e,t)=>{vl.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>unionProcessor(e,t,n,r),e.options=t.options});function union(e,t){return new Hu({type:`union`,options:e,...normalizeParams(t)})}const Uu=/*@__PURE__*/ $constructor(`ZodDiscriminatedUnion`,(e,t)=>{Hu.init(e,t),yl.init(e,t)});function discriminatedUnion(e,t,n){return new Uu({type:`union`,options:t,discriminator:e,...normalizeParams(n)})}const Wu=/*@__PURE__*/ $constructor(`ZodIntersection`,(e,t)=>{bl.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>intersectionProcessor(e,t,n,r)});function intersection(e,t){return new Wu({type:`intersection`,left:e,right:t})}const Gu=/*@__PURE__*/ $constructor(`ZodRecord`,(e,t)=>{_ensureDefaultMemoizer(),xl.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>recordProcessor(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function record(e,t,n){return!t||!t._zod?new Gu({type:`record`,keyType:string(),valueType:e,...normalizeParams(t)}):new Gu({type:`record`,keyType:e,valueType:t,...normalizeParams(n)})}const Ku=/*@__PURE__*/ $constructor(`ZodEnum`,(e,t)=>{Sl.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>enumProcessor(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Ku({...t,checks:[],...normalizeParams(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Ku({...t,checks:[],...normalizeParams(r),entries:i})}});function _enum(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new Ku({type:`enum`,entries:n,...normalizeParams(t)})}const qu=/*@__PURE__*/ $constructor(`ZodLiteral`,(e,t)=>{Cl.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>literalProcessor(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function literal(e,t){return new qu({type:`literal`,values:Array.isArray(e)?e:[e],...normalizeParams(t)})}const Ju=/*@__PURE__*/ $constructor(`ZodTransform`,(e,t)=>{_ensureDefaultMemoizer(),wl.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>transformProcessor(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $ZodEncodeError(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(issue(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(issue(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function transform(e){return new Ju({type:`transform`,transform:e})}const Yu=/*@__PURE__*/ $constructor(`ZodOptional`,(e,t)=>{Tl.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>optionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function optional(e){return new Yu({type:`optional`,innerType:e})}const Xu=/*@__PURE__*/ $constructor(`ZodExactOptional`,(e,t)=>{El.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>optionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function exactOptional(e){return new Xu({type:`optional`,innerType:e})}const Zu=/*@__PURE__*/ $constructor(`ZodNullable`,(e,t)=>{Dl.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nullableProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function nullable(e){return new Zu({type:`nullable`,innerType:e})}const Qu=/*@__PURE__*/ $constructor(`ZodDefault`,(e,t)=>{Ol.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>defaultProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _default(e,t){return new Qu({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}const $u=/*@__PURE__*/ $constructor(`ZodPrefault`,(e,t)=>{kl.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>prefaultProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function prefault(e,t){return new $u({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}const ed=/*@__PURE__*/ $constructor(`ZodNonOptional`,(e,t)=>{Al.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nonoptionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function nonoptional(e,t){return new ed({type:`nonoptional`,innerType:e,...normalizeParams(t)})}const td=/*@__PURE__*/ $constructor(`ZodCatch`,(e,t)=>{jl.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>catchProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _catch(e,t){return new td({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:constantCatch(t)})}const nd=/*@__PURE__*/ $constructor(`ZodPipe`,(e,t)=>{Ml.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pipeProcessor(e,t,n,r),e.in=t.in,e.out=t.out});function pipe(e,t){return new nd({type:`pipe`,in:e,out:t})}const rd=/*@__PURE__*/ $constructor(`ZodReadonly`,(e,t)=>{Nl.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>readonlyProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function readonly(e){return new rd({type:`readonly`,innerType:e})}const id=/*@__PURE__*/ $constructor(`ZodCustom`,(e,t)=>{Pl.init(e,t),q.init(e,t),e._zod.processJSONSchema=(t,n,r)=>customProcessor(e,t,n,r)});function custom(e,t){return/* @__PURE__ */ _custom(id,e??(()=>!0),t)}function refine(e,t={}){return/* @__PURE__ */ _refine(id,e,t)}function superRefine(e,t){return/* @__PURE__ */ _superRefine(e,t)}function safeParseWithSchema(e,t){let n=e.safeParse(t);return n.success?n.data:null}function safeParseJsonWithSchema(e,t){try{return safeParseWithSchema(e,JSON.parse(t))}catch{return null}}function readLockFileOwnerPayload(e){return e?{pid:typeof e.pid==`number`&&Number.isInteger(e.pid)&&e.pid>0?e.pid:void 0,createdAt:typeof e.createdAt==`string`?e.createdAt:void 0,starttime:typeof e.starttime==`number`&&Number.isInteger(e.starttime)&&e.starttime>=0?e.starttime:void 0}:null}function inspectStaleLockOwner(e){let t=readLockFileOwnerPayload(e.payload);if(!t?.pid)return null;if((e.isPidDefinitelyDead??or)(t.pid))return{reason:`owner-process-exited`,pid:t.pid,recordedStarttime:t.starttime??null,observedStarttime:null};let n=t.starttime===void 0?null:(e.getProcessStartTime??ar)(t.pid),r={pid:t.pid,recordedStarttime:t.starttime??null,observedStarttime:n},i=process.platform===`darwin`&&t.starttime!==void 0&&t.starttime>1e10?Math.floor(t.starttime/1e6):t.starttime;return n!==null&&n!==i?{reason:`owner-starttime-changed`,...r}:null}function isLockOwnerDefinitelyStale(e){return inspectStaleLockOwner(e)!==null}const ad=string().min(1).max(4096),od={pid:number().int().positive(),startIdentity:ad.max(128)},sd=strictObject({...od,startIdentitySource:literal(`argv-sha256`).nullable().optional()}).refine(({startIdentity:e,startIdentitySource:t})=>t===`argv-sha256`?/^win32-argv-sha256:[a-f0-9]{64}$/.test(e):!e.startsWith(`win32-argv-sha256:`)),cd=union([strictObject({platform:_enum([`linux`,`darwin`]),identity:string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i)}),strictObject({platform:literal(`win32`),identity:string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{7}Z$/)}),strictObject({platform:literal(`freebsd`),identity:string().regex(/^[a-f0-9]{32}$/)})]),ld=strictObject({kind:literal(`native`),unit:ad,scope:ad,placement:discriminatedUnion(`kind`,[strictObject({kind:literal(`pending`)}),strictObject({kind:literal(`attached`),invocation:string().regex(/^[a-f0-9]{32}$/i)})])}),ud=literal(`original-cancellation-v1`),dd=strictObject({kind:literal(`update`),mutationProtocol:ud}).extend({mutationProtocol:ud.optional(),custody:_enum([`reserved`,`bound`]).optional()}),fd=discriminatedUnion(`kind`,[dd,strictObject({kind:literal(`triage`),phase:_enum([`reserved`,`running`,`closing`,`closed`,`uncertain`]),lifetime:discriminatedUnion(`kind`,[strictObject({kind:literal(`foreground`),boot:cd}),ld])}).refine(e=>e.phase!==`running`||e.lifetime.kind!==`native`||e.lifetime.placement.kind===`attached`)]),pd=ad.refine(x.isAbsolute,`Native source path must be absolute`),md=string().regex(/^[a-f0-9]{64}$/),hd=strictObject({runId:ad,transactionId:ad,claimId:ad,revision:number().int().nonnegative(),recordSha256:md,serviceKey:pd,configPaths:array(pd).min(1).max(512),lifetimeId:ad}),gd=strictObject({id:string().uuid(),phase:_enum([`reserved`,`admitted`]),source:hd}),_d={executor:sd,helper:sd,action:fd},vd=strictObject({version:literal(2),executor:sd,helper:sd,action:dd}),yd=strictObject({key:ad,owner:ad,payload:string().min(1),updatedAt:number().int().nonnegative()});discriminatedUnion(`version`,[strictObject({version:literal(4),executor:sd,helper:sd,action:dd,cancellation:yd}).refine(e=>{let t=safeParseJsonWithSchema(vd,e.cancellation.payload);return t!==null&&JSON.stringify(t.helper)===JSON.stringify(e.helper)&&JSON.stringify(t.executor)===JSON.stringify(e.executor)&&JSON.stringify(t.action)===JSON.stringify(e.action)&&(JSON.stringify(e.helper)===JSON.stringify(e.executor)||t.action.mutationProtocol===`original-cancellation-v1`)}),strictObject({version:literal(2),..._d,mutationOriginal:yd.optional()}).refine(e=>{if(!e.mutationOriginal)return!0;let t=safeParseJsonWithSchema(vd,e.mutationOriginal.payload);return t!==null&&!e.mutationOriginal.key.includes(`/.openclaw-update-child-`)&&t.action.mutationProtocol===`original-cancellation-v1`}),strictObject({version:literal(3),..._d,action:strictObject({kind:literal(`update`)}),nativeBorrower:gd})]),strictObject({version:literal(1),...od});const bd=[`-NoProfile`,`-NonInteractive`,`-Command`,`(Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime.ToUniversalTime().ToString('o')`];function predatesCurrentBoot(e,t){return e<(t?.platform===`win32`?Date.parse(t.identity):NaN)-3e5}function createManagedHandoffBootIdentityReader(e){return function(){let t,n=process.platform===`android`?`linux`:process.platform;if(n===`linux`)t=b.readFileSync(`/proc/sys/kernel/random/boot_id`,`utf8`).trim();else if([`freebsd`,`darwin`,`win32`].includes(process.platform)){let n=process.platform===`freebsd`,r=process.platform===`win32`,i=Pr(r?`powershell.exe`:n?`/sbin/sysctl`:`/usr/sbin/sysctl`,r?bd:n?[`-b`,`kern.boot_id`]:[`-n`,`kern.bootsessionuuid`],{env:e,...n?{maxBuffer:16}:{encoding:`utf8`,windowsHide:!0},timeout:r?5e3:1e3,killSignal:`SIGKILL`,stdio:[`ignore`,`pipe`,`ignore`]});!i.error&&i.status===0&&(t=n?Buffer.isBuffer(i.stdout)&&i.stdout.length===16?i.stdout.toString(`hex`):void 0:i.stdout.toString().trim())}let r={platform:n,identity:n===`win32`?t:t?.toLowerCase()},i=cd.safeParse(r);if(!i.success)throw Error(`OS boot identity unavailable; run openclaw triage manually`);return i.data}}const[xd,Sd,Cd]=cd.options,wd=string().min(1),Td=string().regex(/^[a-f0-9]{64}$/u),Ed=discriminatedUnion(`platform`,[xd.extend({host:wd,platform:literal(`linux`),pidNsInode:string().min(1)}),xd.extend({host:wd,platform:literal(`darwin`)}),Sd.extend({host:wd,identity:Sd.shape.identity.optional()}),Cd.extend({host:wd})]);let Dd;function readGatewayLockProcessNamespace(){if(Dd?.platform===process.platform&&(Dd.value!==null||process.platform!==`linux`&&process.platform!==`android`))return Dd.value;try{let e=process.platform===`win32`?{platform:`win32`}:createManagedHandoffBootIdentityReader(process.env)(),t=Ed.parse({host:kr.hostname(),...e,...e.platform===`linux`?{pidNsInode:b.readlinkSync(`/proc/self/ns/pid`).match(/^pid:\[(\d+)\]$/u)?.[1]}:{}});return Dd={platform:process.platform,value:t},t}catch{return Dd={platform:process.platform,value:null},null}}function isLegacyGatewayLeaseLock(e){return process.platform===`linux`&&e.processNamespace===void 0&&e.role===`gateway`&&typeof e.ownerId==`string`&&e.ownerId.length>0&&typeof e.createdAt==`string`}function readLockHeartbeat(e){try{return b.statSync(e).mtimeMs}catch{return}}function isForeignLinuxNamespace(e,t){return e?.platform===`linux`&&t?.platform===`linux`&&(e.host!==t.host||e.pidNsInode!==t.pidNsInode)}function describeGatewayLockHolder(e,t,n){let r=Ed.safeParse(e.processNamespace).data,i=(t?readLockHeartbeat(t):void 0)??e.heartbeatAt,a=i===void 0?void 0:Date.now()-i,o=`${r?.host??e.host??`unknown host`}${r?.platform===`linux`?`/pid-ns ${r.pidNsInode}`:``}`,s=n===`live`?`The holder ${e.pid} is alive on this host, stop it first`:n===`unknown`?`Stop the holder before retrying`:`Run this command inside the Gateway container or with a shared PID namespace`;return`holder ${e.pid??`unknown`} at ${o}, last renewed ${a===void 0?`at an unknown time`:`${Math.max(0,Math.floor(a/1e3))} s ago`}. ${s}.`}var GatewayLockNamespaceError=class extends Error{constructor(e,t){let n=process.platform===`linux`&&e.processNamespace===void 0;super(`cannot verify Gateway ownership from this process${t?` at ${t}`:``}. ${n?`Legacy holder ${e.pid??`unknown`} has no PID namespace evidence. It may already have stopped. Independently verify that no Gateway using this state is running on this host or in any sharing container. With a current OpenClaw CLI using the same state and profile, run \`openclaw gateway recover-lock --json\`, then \`openclaw gateway recover-lock --confirm <confirmation> --json\` with the returned confirmation. Retry Doctor afterward.`:describeGatewayLockHolder(e,t)}`),this.name=`GatewayLockNamespaceError`,this.legacyLock=n,this.legacyLease=isLegacyGatewayLeaseLock(e)||n&&typeof e.expiresAt==`number`;let r=Ed.safeParse(e.processNamespace).data;if(isForeignLinuxNamespace(r,readGatewayLockProcessNamespace())){let n=t?readLockHeartbeat(t):e.heartbeatAt;n!==void 0&&(this.heartbeatAgeMs=Math.max(0,Date.now()-n))}}};function classifyGatewayOwnerProcessNamespace(e,t={}){let n=Ed.safeParse(e).data;if(!n||t.ownerHost!==void 0&&t.ownerHost!==n.host)return`unknown`;let r=readGatewayLockProcessNamespace();if(!r||n.platform!==r.platform)return`unknown`;if(t.readGatewayHeartbeat&&isForeignLinuxNamespace(n,r)){if(n.host===r.host&&/^[a-f0-9]{12}$/u.test(r.host)&&hr())return`dead`;let e=t.readGatewayHeartbeat();if(e!==void 0&&Date.now()-e>9e4)return`dead`}if(n.platform===`darwin`&&t.machineIdentity!==void 0){let e=Td.safeParse(t.machineIdentity).data,i=Se();if(e&&i){if(e!==i)return`unknown`;if(n.identity!==r.identity)return`dead`}}let i=n.platform===`darwin`&&r.platform===`darwin`&&n.identity===r.identity;return n.host!==r.host&&!i?`unknown`:n.platform===`win32`?`same`:n.identity===r.identity?n.platform!==`linux`||r.platform===`linux`&&n.pidNsInode===r.pidNsInode?`same`:`unknown`:`dead`}const Od=object({pid:number(),ownerId:string().min(1).optional(),stateOwnerKind:literal(`schema`).optional(),cronOwnerProjection:literal(`dynamic-default-v1`).optional(),createdAt:string(),startupPhase:literal(`starting`).optional(),configPath:string(),port:number().int().min(1).max(65535).optional(),role:_enum([`gateway`,`agent-embedded`,`skill-workshop-apply`,`sqlite-maintenance`]).optional(),stateDir:string().optional(),startTime:number().optional(),parentPid:number().int().positive().optional(),parentStartTime:number().optional(),processNamespace:Ed.nullable().optional(),machineIdentity:Td.nullable().optional()});function parseGatewayLockPayload(e){return safeParseJsonWithSchema(Od,e)}function createColdAdmissionBudget(e){let t=Xn(e.busyTimeoutMs,`busyTimeoutMs`),n=performance.now()+t,r=dr(e.databasePath);return{remainingBusyTimeoutMs:()=>Math.max(0,Math.ceil(n-performance.now())),retryDelay:t=>{if(!(t instanceof lt)||dr(t.databasePath)!==r||e.canRetry?.()===!1)throw t;let i=n-performance.now();if(i<=0)throw t;return Math.min(10,i)}}}const kd=/* @__PURE__ */ new Set([`ENOTSUP`,`EOPNOTSUPP`,`EINVAL`]);function hasRestrictivePermissions(e){try{return!(Cr(e).mode&63)}catch{return!1}}function filesystemRejectsChmod(e){let t;try{let n=Cr(e).isDirectory()?e:x.dirname(e);t=x.join(n,`.openclaw-chmod-probe-${Or()}`),Tr(t,``,{flag:`wx`,mode:384})}catch{return!1}try{return br(t,384),!1}catch(e){return o(e)&&e.code===`EPERM`}finally{try{wr(t)}catch{}}}function canIgnorePrivateChmodError(e,t,n){return t&&kd.has(t)?!0:t!==`EROFS`&&t!==`EPERM`?!1:n||t===`EPERM`&&filesystemRejectsChmod(e)}function applyPrivateModeSync(e,t){if((Cr(e).mode&4095)===t)return{applied:!0};try{return br(e,t),{applied:!0}}catch(t){if(!canIgnorePrivateChmodError(e,o(t)?t.code:void 0,hasRestrictivePermissions(e)))throw t;return{applied:!1,error:t}}}const Ad=`Run OpenClaw as the user that owns its state directory, and keep that directory on a local filesystem that supports file ownership and permissions`;function ensureOwnerDirectory(e,t){let n=b.mkdirSync(e,{recursive:!0,mode:448});if(n&&t){let r=x.toNamespacedPath(n),i=[];for(let t=e;;){let{dev:e,ino:n}=b.lstatSync(t,{bigint:!0});if(i.push({path:t,dev:e,ino:n}),x.toNamespacedPath(t)===r)break;let a=x.dirname(t);if(a===t)throw Error(`Created state ownership directory is outside its expected ancestry`);t=a}for(let e of i){let n=t.findIndex(t=>t.path===e.path);n<0?t.push(e):t[n]=e}}let r=b.lstatSync(e),i=process.getuid?.();if(!r.isDirectory())throw Error(`State ownership directory must be a user-owned real directory`);if(i!==void 0&&r.uid!==i)throw Error(`State ownership directory ${e} is owned by uid ${r.uid}, not this user (uid ${i}). ${Ad}`);if(process.platform!==`win32`&&(r.mode&4095)!=448&&(applyPrivateModeSync(e,448),b.lstatSync(e).mode&63))throw Error(`State ownership directory ${e} permissions could not be set to 0700. ${Ad}`)}function removeCreatedProjectionDirectories(e){let t=e[0];for(;t;){try{let e=b.lstatSync(t.path,{bigint:!0});e.isDirectory()&&e.dev===t.dev&&e.ino===t.ino&&b.rmdirSync(t.path)}catch(e){let t=n(e);if(t!==`ENOENT`&&t!==`ENOTEMPTY`&&t!==`EEXIST`)throw e}e.shift(),t=e[0]}}function resolveStateOwnerIdentity(e){let t=dr(e);return stateOwnerIdentity(t,dr(stateOwnerDirectory(t)))}async function resolveStateOwnerIdentityAsync(e){let t=await ur(e);return stateOwnerIdentity(t,await ur(stateOwnerDirectory(t)))}function stateOwnerIdentity(e,t){return{canonicalPath:e,ownerPath:x.join(t,`state.${sha256HexPrefixCore(e,16)}.lock`),key:process.platform===`win32`?p(e):e}}function stateOwnerDirectory(e){let t=process.getuid?.();return process.platform===`win32`?x.join(kr.homedir(),`AppData`,`Local`,`OpenClaw`,`locks`,t===void 0?`openclaw-state-owners`:`openclaw-state-owners-${t}`):oe(Ln(e))}function isGatewayStateOwnerLockSnapshotCurrent(e,t,n,r){return t.isFile()&&e.nlink!==0n&&e.dev===t.dev&&e.ino===t.ino&&r===n}const jd=Date.now.bind(Date);function captureLock(e){let t=b.readFileSync(e.lockPath,`utf8`);if(!e.verifyStillHeld())throw Error(`OpenClaw state ownership is no longer current`);return t}function startGatewayStateOwnerHeartbeat(e,n){let r={};for(let t of e)r[t.lockPath]=captureLock(t);let i=Object.keys(r)[0];if(!i)throw Error(`Gateway state ownership requires a held lock`);let a=b.statSync(i,{bigint:!0}),{moduleUrl:o,runtimeGeneration:s}=nt(_e(`gatewayStateOwnerHeartbeat`));return d(()=>{let c=new BigInt64Array(new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT));Atomics.store(c,0,BigInt(jd()));let{port1:l,port2:u}=new _r,d=pt(o,{workerData:{clock:`epoch`,locks:r,intervalMs:15e3,failureMs:6e4,lastBeat:c.buffer,events:u},transferList:[u],execArgv:lr(o)}),f=er();d.on(`message`,e=>{e===`closed`&&f.resolve()}),d.unref();let p=0,m=/* @__PURE__ */ new Map,rejectPending=e=>{for(let t of m.values())t.reject(e);m.clear(),l.unref()};l.on(`message`,e=>{if(Ke(`lifecycle`,`from_worker`),e===`parent-lost`)nr();else if(e&&typeof e==`object`&&e.type===`lost`)n(/* @__PURE__ */ Error(`${e.error}; restart the Gateway.`),e.lockPath);else if(e&&typeof e==`object`&&e.type===`verified`){let t=m.get(e.id);m.delete(e.id),m.size===0&&l.unref(),e.error?t?.reject(Error(e.error)):t?.resolve(e.current)}}),l.unref(),d.on(`error`,e=>{let t=/* @__PURE__ */ Error(`${re(e)}; restart Gateway.`);rejectPending(t),n(t)}),d.once(`exit`,()=>{f.resolve(),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership verification worker stopped`))});let g,remainingUntilInspection=()=>{let e=Atomics.load(c,0),t=jd()-Number(e);return t<0?0:6e4-t},inspect=()=>{let e=remainingUntilInspection();if(e<=0)throw Error(`Gateway state ownership renewal is overdue at ${i}; retry after storage recovers.`);return e},renewAsync=async()=>{let n=jd(),o=new Date(n);for(let n of e)try{let t=r[n.lockPath];if(t===void 0)throw Error(`owner acquisition bytes were not registered`);let s=await b.promises.open(n.lockPath,`r+`);try{let r=await s.stat({bigint:!0}),c=await b.promises.lstat(n.lockPath,{bigint:!0}),l=Buffer.alloc(Buffer.byteLength(t)+1),{bytesRead:u}=await s.read(l,0,l.length,0),d=await b.promises.lstat(n.lockPath,{bigint:!0});if(g||!e.has(n))continue;if(!isGatewayStateOwnerLockSnapshotCurrent(r,c,t,l.subarray(0,u).toString(`utf8`))||!d.isFile()||d.dev!==r.dev||d.ino!==r.ino||n.lockPath===i&&(r.dev!==a.dev||r.ino!==a.ino)){if(n.lockPath!==i)continue;throw Error(`owner lock was removed or replaced`)}await s.utimes(o,o)}finally{await s.close()}}catch(e){if(n.lockPath!==i&&t(e,`ENOENT`))continue;throw e}!g&&e.size>0&&Atomics.store(c,0,BigInt(n))},ee,te,watch=()=>{let e=remainingUntilInspection();e>0?(ee=setTimeout(watch,e),ee.unref()):te??=renewAsync().then(()=>{te=void 0,g||watch()},e=>{te=void 0,g||n(/* @__PURE__ */ Error(`Gateway state ownership is no longer current at ${i}: ${re(e)}; restart the Gateway.`))})};watch();let stop=()=>(g||=(clearTimeout(ee),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership is no longer current`)),l.close(),d.ref(),d.postMessage(`stop`,[]),(async()=>(await gr(f.promise,1e3)||process.emitWarning(`Gateway state-owner heartbeat did not close within ${ir}ms; forcing termination. Lock file descriptors may remain open until process exit.`,{code:`GATEWAY_STATE_HEARTBEAT_CLOSE_TIMEOUT`}),d.terminate()))()),Promise.all([g,te]).then(()=>void 0));s?.retain(d,async()=>async()=>{await stop()});let assertActive=()=>{if(g||d.threadId===-1)throw Error(`Gateway state ownership verification worker stopped`)},ne=new Set(Object.keys(r));return{worker:d,paths:ne,register(e){let t=captureLock(e);r[e.lockPath]=t,d.postMessage([e.lockPath,t],[]),ne.add(e.lockPath)},inspect,assertActive,verify(e){assertActive();let t=++p;return new Promise((n,r)=>{m.set(t,{resolve:n,reject:r}),l.ref();try{d.postMessage({type:`verify`,id:t,paths:e},[])}catch(e){m.delete(t),m.size===0&&l.unref(),r(h(e,`Gateway state ownership verification failed`))}})},stop}})}function hasPhysicalOwnership(e){try{return verifyOwnerLock(e,e.locks.values().next().value)}catch(t){if(e.lost.signal.aborted)return!1;throw t}}function verifyOwnerLock(e,t){if(e.lost.signal.throwIfAborted(),e.heartbeat?.inspect(),!t)return!1;let n=e.getProjection?.();n&&e.heartbeat&&!e.heartbeat.paths.has(n.lockPath)&&e.heartbeat.register(n);let r=e.payload.role??`gateway`;return e.kind===`process`&&e.accepting&&(r===`gateway`||r===`agent-embedded`)&&e.heartbeat?(e.heartbeat.assertActive(),!0):t.verifyStillHeld()?!0:(loseOwner(e,/* @__PURE__ */ Error(`${t.lockPath}: no longer current; lock removed/replaced; restart the Gateway.`)),!1)}const Md=ue(`gateway/state`);function loseOwner(e,t){e.lost.signal.aborted||(e.accepting=!1,Y.clear(),e.heartbeat?.stop(),Md.error(t.message),e.lost.abort(t))}function observeOwnerLoss(e,t,n){let r=[...e.locks,e.getProjection?.()];(!n||r.some(e=>e?.lockPath===n))&&loseOwner(e,t)}const Y=s(Symbol.for(`openclaw.gatewayStateReadOwnerPaths`),()=>/* @__PURE__ */ new Map),X=s(Symbol.for(`openclaw.gatewayStateOwners`),()=>/* @__PURE__ */ new Map),Nd=/* @__PURE__ */ new Set([`--port`,`--bind`,`--token`,`--token-file`,`--auth`,`--password`,`--password-file`,`--tailscale`,`--ws-log`,`--raw-stream-path`]),Pd=/* @__PURE__ */ new Set([`--tailscale-reset-on-exit`,`--allow-unconfigured`,`--dev`,`--ambient-channels`,`--dev-ambient-channels`,`--reset`,`--update-canary`,`--force`,`--verbose`,`--cli-backend-logs`,`--claude-cli-logs`,`--compact`,`--raw-stream`]);function isForegroundGatewayRunArgv(e){let t=pr(e,{commandPath:[`gateway`],booleanFlags:[...Pd,`--task-supervisor`],valueFlags:[...Nd,`--task-supervisor-child`],mode:`command-path`});return t?t.length===0||t.length===1&&t[0]===`run`:!1}function classifyGatewayLockProcessNamespace(e,t,n){if(e&&n&&isLegacyGatewayLeaseLock(e)){let t=Date.now(),r=Date.parse(e.createdAt);if(!Number.isFinite(r)||t-r<=3e5)return`unknown`;try{let r=Xt(pn(n),{readOnly:!0});try{let n=getNodeSqliteKysely(r),{rows:i}=executeSqliteQuerySync(r,{compile:()=>V`SELECT expires_at AS expiresAt
              FROM ${V`state_leases NOT INDEXED`}
              WHERE scope = ${`gateway-owner`} AND owner = ${e.ownerId}`.compile(n)});return i.every(e=>typeof e.expiresAt==`number`&&e.expiresAt<=t)?`dead`:`unknown`}finally{r.close()}}catch{return`unknown`}}if((process.platform===`win32`||process.platform===`darwin`)&&e&&e.processNamespace===void 0&&t){try{if(Date.now()-b.statSync(t).mtimeMs>9e4&&isLockOwnerDefinitelyStale({payload:{pid:e.pid,starttime:e.startTime}}))return`dead`}catch{}return`unknown`}return classifyGatewayOwnerProcessNamespace(e?.processNamespace,{machineIdentity:e?.machineIdentity,readGatewayHeartbeat:t?()=>readLockHeartbeat(t):void 0})}function finiteNonNegativeNumber(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function findExistingDiskSpacePath(e){let t=x.resolve(e);for(;;)try{return b.statSync(t).isDirectory()?t:x.dirname(t)}catch{let e=x.dirname(t);if(e===t)return null;t=e}}function tryReadDiskSpace(e){let t=findExistingDiskSpacePath(e);if(!t)return null;try{let n=b.statfsSync(t),r=finiteNonNegativeNumber(n.bsize),i=finiteNonNegativeNumber(n.bavail);if(r===null||i===null)return null;let a=finiteNonNegativeNumber(n.blocks);return{targetPath:e,checkedPath:t,availableBytes:r*i,totalBytes:a===null?null:r*a}}catch{return null}}function formatDiskSpaceBytes(e){let t=e/1048576,n=Math.max(0,Math.round(t));if(n<1024)return`${n} MiB`;let r=t/1024;return`${r.toFixed(+(r<10))} GiB`}const Fd=new S;function comparableStateOwnerStaleReason(e,t){return t===`dead`?`owner-process-exited`:t===`same`?inspectStaleLockOwner({payload:{pid:e.pid,starttime:e.startTime}})?.reason:void 0}function isGatewayStateOwnerDefinitelyStale(t,n,r){let i=e(t)?t:null;if(!i)return!1;let a=classifyGatewayLockProcessNamespace(i,n,r);if(a===`unknown`)throw new GatewayLockNamespaceError(i,n);return comparableStateOwnerStaleReason(i,a)!==void 0}function assertPersistedStateDatabaseAccessAllowed(e){let{databasePath:t,ownerPath:r,assertMaintenance:i}=e,a=`OpenClaw state ownership at ${t} could not be verified from ${r}; restart the Gateway.`,o;try{o=b.readFileSync(r,`utf8`)}catch(e){if(n(e)===`ENOENT`)return;throw new st(a,{cause:e})}let s=Fd.getStore();if(s?.deadOwner?.path===r&&s.deadOwner.raw===o)return;let c=parseGatewayLockPayload(o);if(!c)throw new lt(t,a);if(!Number.isSafeInteger(c.pid)||c.pid<=0)throw new st(a);let l=classifyGatewayLockProcessNamespace(c,r,t),u=comparableStateOwnerStaleReason(c,l);if(u){s&&u===`owner-process-exited`&&(s.deadOwner={path:r,raw:o});return}if(l===`same`&&c.pid===process.pid&&!vr)return;if(l===`same`&&!cr(c.pid))throw new lt(t,a);let d=c.role??`gateway`;if(d===`gateway`||d===`agent-embedded`)return;if(l===`same`&&c.pid===process.pid){i();return}let f=`OpenClaw state at ${t} is undergoing offline maintenance by ${d} process ${c.pid}, started ${c.createdAt}; retry when it finishes. For update progress, run \`openclaw update status --json\`. ${describeGatewayLockHolder(c,r,l===`same`?`live`:`unknown`)}`;throw c.stateOwnerKind===`schema`&&c.role===`sqlite-maintenance`?new lt(t,f):new _t(t,f)}function defaultPayload(e){let t=Ln(e),n=ar(process.pid),r=rr(),i=r===void 0?null:ar(r);return{pid:process.pid,ownerId:Or(),createdAt:(/* @__PURE__ */ new Date()).toISOString(),stateDir:t,configPath:x.join(t,`openclaw.json`),role:`sqlite-maintenance`,processNamespace:readGatewayLockProcessNamespace(),machineIdentity:process.platform===`darwin`?Se():void 0,...r===void 0?{}:{parentPid:r},...i===null?{}:{parentStartTime:i},...n===null?{}:{startTime:n}}}function assertGatewayRestorationPriority(e,t,r){if(r.role===`gateway`)return;let i;try{i=b.readFileSync(t,`utf8`)}catch(e){if(n(e)===`ENOENT`)return;throw e}let a=parseGatewayLockPayload(i);if(!(isGatewayStateOwnerDefinitelyStale(a)||a?.pid===r.pid)&&!(r.pid===process.pid&&isForegroundGatewayRunArgv(process.argv)&&mr(process.argv,{command:`gateway`}).kind===`openclaw`))throw new lt(e,`Gateway restoration has priority for OpenClaw state at ${e}; retry when it finishes.`)}function acquireGatewayStateOwnerFile(e,t,r,i=0,a){let o=performance.now()+i,s=`${resolveStateOwnerIdentity(e).ownerPath}.gateway-restoration`;assertGatewayRestorationPriority(e,s,r),ensureOwnerDirectory(x.dirname(t),a);let c={holder:null},stale=({payload:n})=>(c.holder=Od.safeParse(n).data??null,isGatewayStateOwnerDefinitelyStale(c.holder,t,e));if(i>0)try{let n=c.holder=parseGatewayLockPayload(b.readFileSync(t,`utf8`));if(n&&!isGatewayStateOwnerDefinitelyStale(n,t,e)&&(n.pid===process.pid||(n.role??`gateway`)===`gateway`&&cr(n.pid)))throw new Ot(e)}catch(e){if(n(e)!==`ENOENT`)throw e}for(let l=!1;;)try{return Ir(t,{lockPath:t,retry:i>0?{factor:1.25,minTimeout:10,maxTimeout:25,randomize:!1}:{retries:0},timeoutMs:Math.max(0,Math.ceil(o-performance.now())),staleMs:1/0,staleRecovery:`remove-if-unchanged`,reentrantOwner:r.ownerId,payload:()=>(assertGatewayRestorationPriority(e,s,r),r),shouldReclaim:stale,shouldRemoveStaleLock:stale})}catch(r){let i=n(r);if(i===`ENOENT`&&!l){l=!0,ensureOwnerDirectory(x.dirname(t),a);continue}if(i===`file_lock_timeout`||i===`file_lock_stale`){let{holder:n}=c,i=describeGatewayLockHolder(n??{},t,n&&cr(n.pid)?`live`:`unknown`);throw new Ot(e,r,i,n?{pid:n.pid,role:n.role}:void 0)}throw r}}const Id=s(Symbol.for(`openclaw.stateDatabaseSchemaOwners`),()=>new S);function getStateDatabaseSchemaLease(e){let t=Id.getStore()?.get(resolveStateOwnerIdentity(e).key);if(t&&!t.active)throw Error(`State schema maintenance scope is no longer current`);return t?.lease.assertCurrent(),t?.lease}function withStateDatabaseColdAdmission(e,t){let{remainingBusyTimeoutMs:n,retryDelay:r}=createColdAdmissionBudget(e),i=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));for(;;)try{return assertStateDatabaseAccessAllowed(e.databasePath),t(n)}catch(e){Atomics.wait(i,0,0,r(e))}}function resolveGatewayStateOwnerPath(e){return resolveStateOwnerIdentity(e).ownerPath}function leaseForFile(e,t,n,r){let i=!1,holdsPhysicalLease=()=>verifyOwnerLock(n,t)&&(!r||r.verifyStillHeld());function run(e){a.assertCurrent(),Y.clear();let t=new Map(Id.getStore()),r={lease:a,active:!0};t.set(n.key,r);let leave=()=>{r.active=!1,Y.clear()};try{let n=Id.run(t,e);return ve(n)?Promise.resolve(n).finally(leave):(leave(),n)}catch(e){throw leave(),e}}let a={path:e,assertCurrent(){if(i||!holdsPhysicalLease())throw Error(`OpenClaw state ownership is no longer current`)},assertDatabaseAccess(e){if(i||X.get(n.key)!==n||resolveStateOwnerIdentity(e).key!==n.key||!holdsPhysicalLease())throw Error(`OpenClaw state maintenance does not own this database`)},run,release(){Y.clear(),i||(r?.release(),t.release(),i=!0,n.locks.delete(t),r&&n.locks.delete(r),n.locks.size===0&&X.get(n.key)===n&&(n.heartbeat?.stop(),n.accepting=!1,X.delete(n.key),n.onReleased?.())),n.locks.size===0&&removeCreatedProjectionDirectories(n.projectionDirectories)}};return a}function acquireStateDatabaseSchemaLease(e,t={}){Y.clear();let n=resolveStateOwnerIdentity(e),r=X.get(n.key),i=r?.path??n.ownerPath;if(r&&(!r.accepting||!hasPhysicalOwnership(r)))throw new Ot(e,r.lost.signal.reason);r&&assertStateDatabaseAccessAllowed(e);let a=r?.payload??{...defaultPayload(e),stateOwnerKind:`schema`},o,s=[];try{o=acquireGatewayStateOwnerFile(e,i,a,r?0:t.busyTimeoutMs??5e3,s)}catch(t){if(t instanceof Ot)try{assertStateDatabaseAccessAllowed(e)}catch(e){if(e instanceof lt)throw e}throw t}let c=r?.projectionPath??x.join(ae(Ln(dr(e))),`gateway.state.lock`),l;try{l=r?.getProjection?.()?.retain()??acquireGatewayStateOwnerFile(e,c,{...a,role:a.role===`gateway`?`gateway`:`agent-embedded`},0,s)}catch(e){return Ce({release(){o.release(),removeCreatedProjectionDirectories(s)}},`state schema projection admission`,()=>{throw e})}r?(r.locks.add(o),r.locks.add(l),r.projectionDirectories.push(...s)):(r={key:n.key,path:i,kind:`schema`,payload:a,projectionPath:c,locks:/* @__PURE__ */ new Set([o,l]),projectionDirectories:s,lost:new AbortController,accepting:!0},X.set(r.key,r));let u=leaseForFile(i,o,r,l);try{let e=r.heartbeat??=startGatewayStateOwnerHeartbeat(r.locks,(e,t)=>observeOwnerLoss(r,e,t));return u.assertCurrent(),e.register(l),u}catch(e){return Ce(u,`state schema ownership verification`,()=>{throw e})}}function prepareStateDatabaseReadAccess(e){return captureAdmittedGatewayStateOwner(e,!1)}async function captureAdmittedGatewayStateOwner(e,t){e.assertCurrent();let n=e.identity.canonicalPath,r=process.platform===`win32`?p(n):n,i=X.get(r);if(!i||i.kind!==`process`)return;let a={canonicalPath:n,key:r,ownerPath:i.path},assertRegistered=()=>{if(e.assertCurrent(),i.lost.signal.throwIfAborted(),X.get(r)!==i)throw ut()},assertCurrent=()=>{if(assertRegistered(),!i.accepting)throw ut();assertStateDatabaseAccessAtOwnerPath(n,a,void 0)},o=createStateDatabaseAccess(a,i),assertReadAllowed=e=>{assertRegistered(),o.assertReadAllowed(e)},s=x.resolve(e.databasePath),c=t?assertCurrent:assertRegistered;if(c(),t||Y.get(s)!==i){let t=await ur(s);if(c(),(process.platform===`win32`?p(t):t)!==r)throw new Ot(e.databasePath)}return t||(assertReadAllowed(),Y.get(x.resolve(n))===i&&Y.set(s,i)),{ownerId:i.payload.ownerId,role:i.payload.role??`gateway`,signal:i.lost.signal,assertCurrent,assertReadAllowed,prepareAccess:o.prepareAccess}}function assertStateDatabaseReadAllowed(e,t){assertStateDatabaseReadAtOwnerPath(e,t)}function assertStateDatabaseReadAtOwnerPath(e,t,n){if(X.size===0){assertStateDatabaseAccessAtOwnerPath(e,n??resolveStateOwnerIdentity(e),t);return}let r=x.resolve(e);if(Y.get(r)?.accepting)return;let i=n??resolveStateOwnerIdentity(e),a=X.get(i.key),o=a?.payload.role??`gateway`;if(!a||a.kind!==`process`||!a.accepting||o!==`gateway`&&o!==`agent-embedded`)assertStateDatabaseAccessAtOwnerPath(e,i,t);else{if(!hasPhysicalOwnership(a))throw a.lost.signal.throwIfAborted(),Error(`OpenClaw state ownership at ${e} was lost: owner lock was removed or replaced; restart the Gateway.`);Y.set(r,a)}}function assertStateDatabaseAccessAllowed(e,t){assertStateDatabaseAccessAtOwnerPath(e,resolveStateOwnerIdentity(e),t)}async function captureStateDatabaseAccess(e){return createStateDatabaseAccess(await resolveStateOwnerIdentityAsync(e))}function createStateDatabaseAccess(e,t){let{canonicalPath:n}=e,r=X.get(e.key);return{canonicalPath:n,processOwner:r?.kind===`process`?{role:r.payload.role??`gateway`,signal:r.lost.signal,assertCurrent(){if(r.lost.signal.throwIfAborted(),!r.accepting||X.get(e.key)!==r)throw ut()}}:void 0,prepareAccess:async r=>{let i=t??X.get(e.key),a=i?.payload.role??`gateway`;if(!i||i.kind!==`process`||!i.accepting||a!==`gateway`&&a!==`agent-embedded`)return assertStateDatabaseAccessAtOwnerPath(n,e,r),(t=r)=>{if(i&&X.get(e.key)!==i)throw ut();assertStateDatabaseReadAtOwnerPath(n,t,e)};let o=i.heartbeat,s=i.locks.values().next().value,c=i.getProjection?.();if(!o||!s)throw ut();let assertCurrent=(t=r)=>{if(i.lost.signal.throwIfAborted(),o.assertActive(),X.get(e.key)!==i||i.heartbeat!==o)throw ut();if(!i.accepting)assertStateDatabaseAccessAtOwnerPath(n,e,t);else if(!i.locks.has(s)||i.getProjection?.()!==c)throw ut()};assertCurrent();let l=[s.lockPath];c&&l.push(c.lockPath);let u=await o.verify(l).catch(e=>{throw i.lost.signal.throwIfAborted(),e});if(assertCurrent(),!u){let e=/* @__PURE__ */ Error(`${s.lockPath}: no longer current; lock removed/replaced; restart the Gateway.`);throw loseOwner(i,e),e}return Y.set(x.resolve(n),i),assertCurrent},assertReadAllowed(t){assertStateDatabaseReadAtOwnerPath(n,t,e)}}}function assertStateDatabaseAccessAtOwnerPath(e,t,n){let assertMaintenance=()=>{let t=n?n.schemaLease:getStateDatabaseSchemaLease(e);if(t){t.assertDatabaseAccess(e);return}let r=n?n.maintenanceScope:hn();if(!r)throw new xt(e);r.assertDatabaseAccess(e)},r=X.get(t.key);if(r){if(!hasPhysicalOwnership(r))throw r.lost.signal.throwIfAborted(),Error(`OpenClaw state ownership at ${e} was lost: owner lock was removed or replaced; restart the Gateway.`);let t=r.payload.role??`gateway`;(!r.accepting||t!==`gateway`&&t!==`agent-embedded`)&&assertMaintenance()}else assertPersistedStateDatabaseAccessAllowed({databasePath:e,ownerPath:t.ownerPath,assertMaintenance})}function createSqliteTerminalOpenLatch(e){let t=/* @__PURE__ */ new Map;return{peek:e=>t.get(x.resolve(e)),get:e=>t.get(x.resolve(e)),record:(n,r)=>{let i=x.resolve(n);$n(r),t.set(i,r),e.closeByPath(i,r)},clear:e=>{t.delete(x.resolve(e))},clearAll:e=>{for(let n of t.keys())(e===void 0||l(e,n))&&t.delete(n)}}}function sameFileFingerprint(e,t){return e.dev===t.dev&&e.ino===t.ino&&Jt(e,t)&&e.sha256===t.sha256}function sameOptionalFileFingerprint(e,t){return e===void 0?t===void 0:t!==void 0&&sameFileFingerprint(e,t)}function sameSqliteFileGeneration(e,t){return sameFileFingerprint(e.database,t.database)&&sameOptionalFileFingerprint(e.journal,t.journal)&&sameOptionalFileFingerprint(e.wal?.size===0n?void 0:e.wal,t.wal?.size===0n?void 0:t.wal)}function parseFileFingerprint(t){if(!e(t))throw Error(`SQLite file fingerprint must be an object`);for(let e of[`birthtimeNs`,`ctimeNs`,`dev`,`ino`,`mtimeNs`,`size`])if(typeof t[e]!=`string`||!/^-?\d+$/u.test(t[e]))throw Error(`SQLite file fingerprint ${e} is invalid`);if(typeof t.sha256!=`string`||!/^[a-f0-9]{64}$/u.test(t.sha256))throw Error(`SQLite file fingerprint sha256 is invalid`);return{birthtimeNs:BigInt(t.birthtimeNs),ctimeNs:BigInt(t.ctimeNs),dev:BigInt(t.dev),ino:BigInt(t.ino),mtimeNs:BigInt(t.mtimeNs),sha256:t.sha256,size:BigInt(t.size)}}function parseSqliteFileGeneration(t){let n=JSON.parse(t);if(!e(n))throw Error(`SQLite file generation must be an object`);return{database:parseFileFingerprint(n.database),...n.journal===void 0?{}:{journal:parseFileFingerprint(n.journal)},...n.wal===void 0?{}:{wal:parseFileFingerprint(n.wal)}}}function readSqliteFileGenerationSync(e){return parseSqliteFileGeneration(mn(e,void 0,`file-generation`))}async function backupNodeSqliteDatabase(e,t,n){let r=setInterval(()=>{},100);try{let r=await ze().backup(e,sn(t),{progress:n});return n?.({totalPages:r,remainingPages:0}),r}finally{clearInterval(r)}}function createPrivateWindowsDirectory(e){let t=!1;try{Mr(x.resolve(e),{private:!0,assertBeforeMutation(){t=!0}})}catch(e){throw!t||e instanceof Nr&&e.code===`already-exists`?Gn(e):e}}function resolvePrivateSqliteSnapshotStagingRoot(e=process.env){try{return resolveSnapshotStagingRoot(e)}catch(e){throw e instanceof Error&&Jn(e)?new Vn(`SQLite snapshot staging root is unavailable: ${e.message}; free disk space/quota`,{cause:e}):e}}function resolveSnapshotStagingRoot(e){let t=e.OPENCLAW_UPDATE_IN_PROGRESS===`1`?e.TMPDIR?.trim():void 0;if(t&&x.isAbsolute(t))return ne({preferredDir:x.join(t,`openclaw`),tmpdir:()=>t});let n=process.platform===`win32`?e.LOCALAPPDATA?.trim():void 0,i=process.platform===`win32`?`AppData/Local`:`.cache`,a=process.platform===`darwin`?`Library/Caches`:i,o=[e.XDG_CACHE_HOME?.trim(),n].find(e=>e&&x.isAbsolute(e))??x.join(r(e),a),s=m(e),c=Er(`sha256`).update(s).digest(`hex`).slice(0,24);b.mkdirSync(o,{recursive:!0,mode:448});let l=ne({preferredDir:x.join(o,`openclaw`),tmpdir:()=>o}),[u=``,...d]=x.relative(l,s).split(x.sep),f=d.length>0&&/^sqlite-[a-f0-9]{24}$/u.test(u)?u:`sqlite-${c}`,p=x.join(l,f);b.mkdirSync(p,{recursive:!0,mode:448});let h=b.lstatSync(p);if(!h.isDirectory()||process.getuid&&h.uid!==process.getuid()||process.platform!==`win32`&&h.mode&63)throw Error(`SQLite snapshot namespace must be a private user-owned directory`);return p}function createPrivateSqliteTempDirectorySync(e,t){if(process.platform!==`win32`)try{return b.mkdtempSync(x.join(e,t))}catch(e){throw Gn(e)}let n=x.join(e,`${t}${Or()}`);return createPrivateWindowsDirectory(n),n}function sqliteSnapshotSourceFileSize(e){try{let t=b.statSync(e);return t.isFile()?t.size:0}catch(e){if(t(e,`ENOENT`))return 0;throw e}}function assertSqliteSnapshotSpace(e,t){let n=typeof e==`string`?[``,`-wal`,`-journal`].reduce((t,n)=>t+sqliteSnapshotSourceFileSize(e+n),0):readSqliteImageSizeBytes(e),r=tryReadDiskSpace(t);if(r&&r.availableBytes<n)throw Object.assign(/* @__PURE__ */ Error(`SQLite read-only snapshot needs ${formatDiskSpaceBytes(n)} (${n} bytes) near ${t}, but only ${formatDiskSpaceBytes(r.availableBytes)} (${r.availableBytes} bytes) is available. Free disk space before retrying.`),{code:`ENOSPC`})}function acquireSqliteSnapshotReadToken(e){return Zt(e,`read`)}function sqliteSnapshotStagingError(e,t,n=!1,r){we(t,`snapshot`);let i=n,a=!1,o=!1,s;for(let n=0,r=t;n<8&&r instanceof Error;n+=1){o||=r instanceof AggregateError||r instanceof Mt;let{errcode:t,path:n}=r;a||=Jn(r),(a||typeof t==`number`&&[13,778,1034,1290].includes(t)||`${n??``}${x.sep}`.startsWith(`${e}${x.sep}`))&&(i=!0,typeof t==`number`&&(s=t)),r=r.cause}if(!i)return t;let c=a?`free disk space/quota`:`check filesystem health and write permissions`,l=``;if(a&&r)try{let t=sqliteSnapshotSourceFileSize(r)+sqliteSnapshotSourceFileSize(`${r}-wal`)+sqliteSnapshotSourceFileSize(`${r}-journal`),n=tryReadDiskSpace(e)?.availableBytes,i=b.existsSync(`${r}-wal`)&&b.existsSync(`${r}-shm`);l=`; estimated ${t} bytes needed; ${n===void 0?`available bytes unknown`:`${n} bytes available`}; source ${i?`has live WAL sidecars`:`has no live WAL sidecars`}`}catch{}let u=process.env.OPENCLAW_UPDATE_IN_PROGRESS===`1`?`TMPDIR`:`XDG_CACHE_HOME`,d=`${t instanceof Error?t.message:String(t)}${s===void 0?``:` (SQLite errcode=${s})`}; snapshot staging root ${n?e:x.dirname(e)}${l}: ${c} or set ${u} to a writable filesystem`,f=a&&!o&&We(t)!==`source`?new Vn(d,{cause:t}):Error(d,{cause:t});return gn(t)?Gn(f):f}async function createSqliteSnapshotStagingDirectory(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1,n,r=!1){n?.throwIfAborted();try{return await allocateSqliteSnapshotStagingDirectory(e,t,n,r)}catch(e){throw e instanceof Mt||r&&e instanceof AggregateError||(n?.throwIfAborted(),we(e,`snapshot`)),e}}async function allocateSqliteSnapshotStagingDirectory(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1,n,r=!1){if(n?.throwIfAborted(),r){let r=new AbortController;return an((async()=>{let{allocateWorkerOwnedSqliteSnapshotDirectory:i}=await import(`./session-transcript-reconcile.worker-sqlite-snapshot-staging-allocation-Dpqrk2dj.mjs`);n?.throwIfAborted(),r.signal.throwIfAborted();let a=await i(e,t,n?AbortSignal.any([n,r.signal]):r.signal);if(Ft(a.directory),n?.aborted||r.signal.aborted){if(!await Qt(a.directory))throw new Mt(`SQLite snapshot cleanup failed: ${a.directory}`);n?.throwIfAborted(),r.signal.throwIfAborted()}return a.directory})(),()=>r.abort(/* @__PURE__ */ Error(`SQLite snapshot allocation stopped`)))}return createSqliteSnapshotStagingDirectorySync(e,t)}function createSqliteSnapshotStagingDirectorySync(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1){let n=createSqliteSnapshotStagingTokenSync(e,t);return Ft(n.directory,n.release),n.directory}function createSqliteSnapshotStagingTokenSync(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1){let n;try{try{n=createPrivateSqliteTempDirectorySync(e,t?`openclaw-sqlite-readonly-${process.pid}-`:Yt)}catch(t){throw sqliteSnapshotStagingError(e,t,!0)}return{directory:n,release:Zt(n,`create`)}}catch(e){throw n&&On(n),e}}Buffer.from([217,213,5,249,32,161,99,215]);async function prepareSqliteReadOnlyLocationFromOwnedDatabase(e,t,n,r){let assertReady=()=>{if(n?.throwIfAborted(),t(),!e.isOpen||e.isTransaction)throw Error(`SQLite inspection requires an open owner outside a transaction`)};assertReady();let i=await createSqliteSnapshotStagingDirectory(void 0,!1,n,r===`async`);try{assertReady(),assertSqliteSnapshotSpace(e,i);let r=x.join(i,`database.sqlite.partial`);return await an(backupNodeSqliteDatabase(e,r)),n?.throwIfAborted(),t(),nn(i)}catch(e){let t=[e];throw!await Qt(i,e=>t.push(e))&&r===`async`?Ht(t,`Owned SQLite snapshot preparation`):e}}const Ld=s(Symbol.for(`openclaw.sqliteSnapshotFlights`),()=>({unscoped:/* @__PURE__ */ new Map,scoped:/* @__PURE__ */ new WeakMap}));function completed$1(e){let t=De(()=>{});return t.resolve(e),t.operation}function serviceWhenSettled(e,t){e.result.then(t,t)}function createFlight(e,t,n){let r,i=!1,a=!1,o,s,c,l=De(()=>{if(!(a||l.operation.read().status!==`pending`)){a=!0;try{i||(i=!0,r=n(d.controller.signal,e=>c=e),serviceWhenSettled(r.operation,serviceFlight)),r.operation.service();let e=r.operation.read();e.status===`fulfilled`?l.resolve(e.value):e.status===`rejected`&&l.reject(e.error)}catch(e){l.reject(e)}finally{a=!1}}}),u=De(()=>{l.operation.service();let n=l.operation.read();if(n.status!==`pending`&&u.operation.read().status===`pending`){if(e.get(t)===d&&e.delete(t),n.status===`rejected`)u.reject(c??n.error);else if(d.references>0)u.resolve(n.value);else{o||(o=releaseSnapshot(d,n.value),serviceWhenSettled(o,()=>u.operation.service())),o.service();let e=o.read();e.status===`fulfilled`?e.value?u.resolve(n.value):u.reject(new Mt(`SQLite orphan snapshot cleanup did not complete`)):e.status===`rejected`&&u.reject(e.error)}}});function serviceFlight(){l.operation.service();for(let e of d.listeners)e();u.operation.service()}let d={controller:new AbortController,references:0,listeners:/* @__PURE__ */ new Set,production:l.operation,settled:u.operation,closeProducer(){return s??=r?.startClose?.()??completed$1(void 0),s}};return an(u.operation.result,()=>{d.controller.abort(/* @__PURE__ */ Error(`SQLite snapshot owner stopped`)),serviceFlight()}),d}function releaseSnapshot(e,t){return Ie(t.startCleanup(),t=>t?Ve(e.closeProducer(),()=>!0):completed$1(!1))}function leaseFlight(e,t){let n=!1,r,releaseReference=()=>(n||(n=!0,e.references--),e.references===0),startCleanup=()=>(r??=!n&&releaseReference()?releaseSnapshot(e,t):completed$1(!0),r);return{location:t.location,cleanupRoot:t.cleanupRoot,privateFamily:t.privateFamily,cleanup(){if(n){let e=r?.read();return!e||e.status===`fulfilled`&&e.value}if(e.references>1)return releaseReference(),!0;let i=t.cleanup();return i&&releaseReference(),i},cleanupAsync:()=>startCleanup().result,startCleanup}}function startSnapshotFlight(e,t,n,r,i){r?.throwIfAborted();let a=`${Me(e).key}:${t}`,o=Ld.unscoped;if(i?.scope){let e=Ld.scoped.get(i.scope);e||(e=/* @__PURE__ */ new Map,Ld.scoped.set(i.scope,e)),o=e}let s=o.get(a);s||(s=createFlight(o,a,n),o.set(a,s));let c=s;c.references++;let l=!1,u=!1,d,f=De(()=>{if(f.operation.read().status===`pending`){if(l||r?.aborted){if(u||(u=!0,c.references--),c.references===0&&(c.controller.abort(r?.reason),o.get(a)===c&&o.delete(a),c.settled.service(),c.settled.read().status===`pending`))return;f.reject(r?.reason??/* @__PURE__ */ Error(`SQLite snapshot preparation closed`))}else{c.production.service();let e=c.production.read();if(e.status===`pending`)return;e.status===`fulfilled`?f.resolve(leaseFlight(c,e.value)):(c.references--,f.reject(e.error))}r?.removeEventListener(`abort`,service),c.listeners.delete(service),c.settled.service()}}),service=()=>f.operation.service();return serviceWhenSettled(c.settled,service),c.listeners.add(service),r?.addEventListener(`abort`,service,{once:!0}),queueMicrotask(service),{...f.operation,startClose(){l=!0,f.operation.service();let e=f.operation.read();return d??=e.status===`fulfilled`?Ve(e.value.startCleanup(),e=>{if(!e)throw new Mt(`SQLite snapshot lease cleanup did not complete`)}):c.references===0?c.closeProducer():completed$1(void 0),d}}}function startAwaitedSnapshotWork(e){let t=De(()=>{});return Promise.resolve().then(e).then(t.resolve,t.reject),t.operation}async function prepareSingleFlightSqliteSnapshot(e,t,n,r,i){return startSnapshotFlight(e,t,(e,t)=>({operation:startAwaitedSnapshotWork(async()=>{let r=await n(e,t);return{...r,startCleanup:()=>startAwaitedSnapshotWork(()=>r.cleanupAsync())}})}),r,i).result}function startSingleFlightSqliteSnapshot(e,t,n,r,i){return startSnapshotFlight(e,t,(e,t)=>{let r=n(e,t);return{operation:r,startClose:()=>r.startClose()}},r,i)}const Rd=s(Symbol.for(`openclaw.sqliteLiveSnapshotOwners`),()=>/* @__PURE__ */ new Map);function registerLiveSqliteSnapshotOwner(e){let t=Me(e.databasePath),n={assertCurrent:e.assertCurrent,database:e.database};return Rd.set(t.key,n),()=>{Rd.get(t.key)===n&&Rd.delete(t.key)}}function prepareSqliteSnapshotFromLiveOwner(e,t){t?.throwIfAborted();let n=Me(e),r=Rd.get(n.key);if(r)return r.assertCurrent(),prepareSingleFlightSqliteSnapshot(n.canonicalPath,`live-owner:openclaw-state`,e=>prepareSqliteReadOnlyLocationFromOwnedDatabase(r.database,r.assertCurrent,e),t)}function fingerprint(e){return[e.dev,e.ino,e.birthtimeNs,e.ctimeNs,e.mtimeNs,e.size].join(`:`)}function walFingerprint(e){return[e.dev,e.ino,e.mtimeNs,e.size].join(`:`)}function readFile$1(e){let t=b.lstatSync(e,{bigint:!0,throwIfNoEntry:!1});if(t){if(!t.isFile()||t.nlink!==1n)throw Error(`Private SQLite snapshot must be an independent regular file: ${e}`);return t}}function captureSqlitePrivateSnapshotFamily(e,t){if(b.lstatSync(`${e}-journal`,{throwIfNoEntry:!1}))return;let n=readFile$1(e),r=readFile$1(`${e}-wal`);return n?{root:t,main:fingerprint(n),wal:r&&r.size>32n?walFingerprint(r):null}:void 0}const zd=s(Symbol.for(`openclaw.sqliteReusableSnapshots`),()=>/* @__PURE__ */ new Map),Bd=s(Symbol.for(`openclaw.sqliteReusableSnapshotScopes`),()=>({depth:0,retiring:/* @__PURE__ */ new Set}));function isSqliteSnapshotReuseActive(){return Bd.depth>0}function completed(e){let t=De(()=>{});return t.resolve(e),t.operation}function readSource(e){try{let t=b.statSync(e,{bigint:!0,throwIfNoEntry:!1});if(!t?.isFile()||b.statSync(`${e}-journal`,{throwIfNoEntry:!1}))return;let n=b.statSync(`${e}-wal`,{bigint:!0,throwIfNoEntry:!1}),r=n&&n.size>0n?n:void 0;return{fingerprint:[`${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}:${t.ctimeNs}`,r?`${r.dev}:${r.ino}:${r.size}:${r.mtimeNs}`:`none`].join(`|`),main:t,newestMs:Math.max(Number(t.mtimeMs),Number(r?.mtimeMs??0)),quiescentMs:[t,r].some(e=>e&&e.mtimeNs%1000000000n==0n)?2e3:50}}catch{return}}function canonicalKey(e){try{return b.realpathSync.native(e)}catch{return}}function retire(e,t){zd.get(e)===t&&zd.delete(e),t.retired=!0,t.leases===0&&settleRetirement(t.retire)}function settleRetirement(e){let t=new Promise(t=>{t(e())}).catch(reportRetirementFailure).finally(()=>Bd.retiring.delete(t));Bd.retiring.add(t)}function reportRetirementFailure(e){ce({subsystem:`infra/sqlite-snapshot`}).warn({error:String(e)},`Retiring a reusable SQLite snapshot failed.`)}function lend(e,t){t.leases+=1;let n=!1,release=()=>(n||(n=!0,--t.leases,t.leases===0&&t.retired&&retire(e,t)),!0);return{location:t.location,cleanupRoot:t.cleanupRoot,privateFamily:t.privateFamily,cleanup:release,cleanupAsync:async()=>release(),startCleanup:()=>completed(release())}}function leaseReusableSqliteSnapshot(e,t,n={}){let r=canonicalKey(e),i=r?zd.get(r):void 0;if(r&&i){if(readSource(r)?.fingerprint!==i.fingerprint||!b.existsSync(i.location))retire(r,i);else if(!i.logicalOnly||n.logicalReader){if(t)try{xe(i.main,t)}catch{return}return lend(r,i)}}}function captureReusableSqliteSource(e){let t=Bd.depth>0?canonicalKey(e):void 0,n=t?readSource(t):void 0;return n&&Date.now()-n.newestMs>=n.quiescentMs?n:void 0}function captureFamily(e){try{return captureSqlitePrivateSnapshotFamily(e.location,e.cleanupRoot??x.dirname(e.location))}catch{return}}const Vd=s(Symbol.for(`openclaw.sqliteReusableSnapshotSources`),()=>/* @__PURE__ */ new Map);function bindReusableSqliteSource(e,t){t&&Vd.set(e,t)}function publishBoundReusableSqliteSnapshot(e,t,n){let r=canonicalKey(e)??x.resolve(e),i=zd.get(r),a=Vd.get(t.location)??(i?.location===t.location?i:void 0);return Vd.delete(t.location),a?publishReusableSqliteSnapshot(e,a,t,n):t}function publishReusableSqliteSnapshot(e,t,n,r,i={}){let a=canonicalKey(e)??x.resolve(e),o=zd.get(a);if(o?.location===n.location&&o.fingerprint===t.fingerprint)return settleRetirement(r),lend(a,o);o&&retire(a,o);let s={...t,logicalOnly:i.logicalOnly===!0,location:n.location,cleanupRoot:n.cleanupRoot,privateFamily:n.privateFamily??captureFamily(n),leases:0,retired:!1,retire:r};return zd.set(a,s),lend(a,s)}function createLeasedSqliteSnapshotPreparation(e){return{...completed(e),startClose:()=>Ve(e.startCleanup(),()=>void 0)}}function buildUpdateRehearsalPathEnv(e){return{HOME:e,USERPROFILE:e,TMPDIR:e,TMP:e,TEMP:e,XDG_CONFIG_HOME:x.join(e,`config`),XDG_CACHE_HOME:x.join(e,`cache`),XDG_DATA_HOME:x.join(e,`data`),XDG_STATE_HOME:x.join(e,`state`),OPENCLAW_HOME:e,OPENCLAW_STATE_DIR:e,OPENCLAW_CONFIG_PATH:x.join(e,`openclaw.json`),OPENCLAW_WORKSPACE_DIR:x.join(e,`workspace`),OPENCLAW_SKIP_CHANNELS:`1`,OPENCLAW_SKIP_PROVIDERS:`1`,OPENCLAW_SKIP_CRON:`1`,OPENCLAW_SKIP_GMAIL_WATCHER:`1`,OPENCLAW_SKIP_CANVAS_HOST:`1`,OPENCLAW_SKIP_BROWSER_CONTROL_SERVER:`1`,OPENCLAW_SKIP_STARTUP_MODEL_PREWARM:`1`,OPENCLAW_NO_AUTO_UPDATE:`1`,NODE_DISABLE_COMPILE_CACHE:`1`}}function projectUpdateRehearsalDatabaseConfig(t,n){if(!e(t)||!e(t.database)||!resolveUpdateRehearsalRoot(n))return t;let{engine:r,families:i}=t.database;return r===`postgres`||e(i)&&Object.values(i).some(t=>e(t)&&t.engine===`postgres`)?{...t,database:{engine:`sqlite`}}:t}function resolveUpdateRehearsalRoot(e){let t=e.OPENCLAW_STATE_DIR;if(t&&x.isAbsolute(t)&&[`0`,`1`].includes(e.OPENCLAW_UPDATE_IN_PROGRESS??``)&&!Object.entries(buildUpdateRehearsalPathEnv(t)).some(([t,n])=>e[t]!==n)&&e.OPENCLAW_SERVICE_REPAIR_POLICY===`external`&&e.OPENCLAW_UPDATE_PARENT_ALLOWS_GATEWAY_SERVICE_REPAIR===`0`&&e.OPENCLAW_UPDATE_PARENT_ALLOWS_GATEWAY_ACTIVATION===`0`&&!e.OPENCLAW_COMPATIBILITY_HOST_VERSION)return x.resolve(t)}function isUpdateRehearsalReadOnlyPath(e,t){let n=resolveUpdateRehearsalRoot(t);if(!n)return!1;let r=x.resolve(e);return!l(n,r)||!l(dr(n),dr(r))}function isUpdateRehearsalPrivateDatabase(e,t){return resolveUpdateRehearsalRoot(t)!==void 0&&resolveSqliteDatabaseFilePaths(e).every(e=>!isUpdateRehearsalReadOnlyPath(e,t))}function findArtifactSnapshot(e,t){let n=e.snapshots.get(t.canonicalPath);if(n&&(n.sourceIdentity.key!==t.key||n.sourceIdentity.birthtime!==t.birthtime))throw Error(`SQLite database file identity changed during inspection`);return n}function retainArtifactSnapshot(e,t,n){let r=tn(t.cleanupRoot??x.dirname(t.location));e.privateRoots.add(t.cleanupRoot??x.dirname(t.location));let i={...t,sourceIdentity:n,cleanup:()=>(r(),t.cleanup()),cleanupAsync:()=>(r(),t.cleanupAsync())};return e.snapshots.set(n.canonicalPath,i),i}function assertCustodiedSourceUnchanged(e,t){let n=b.statSync(e,{bigint:!0,throwIfNoEntry:!1});if(!n||n.ino!==t.ino||n.size!==t.size||n.mtimeNs!==t.mtimeNs||Kn(e)===void 0)throw Error(`SQLite source changed during in-place inspection: ${e}`)}function openSqliteReadOnlyDatabase(e,t={}){let n=cn.getStore();if(!n||!Zn(`agent`,e))return Xt(e,{...t,readOnly:!0});let r=Me(e),i=findArtifactSnapshot(n,r),a=i?void 0:Kn(r.canonicalPath);i||a||isUpdateRehearsalPrivateDatabase(e,process.env)||(i=retainArtifactSnapshot(n,prepareSqliteReadOnlyLocationSync(e),r));let o=i?tn(i.cleanupRoot??x.dirname(i.location)):void 0,s={},close=()=>{s.close?.(),o?.(),n.readers.delete(close)};n.readers.add(close);let c=i?.location??(a?un(r.canonicalPath):e),l=Xt(c,{...t,readOnly:!0}),u=l.close.bind(l);return s.close=()=>{l.isOpen&&(u(),a&&assertCustodiedSourceUnchanged(r.canonicalPath,a))},l.close=close,l}async function prepareSqliteReadOnlyLocation(e,t={}){let n=Hn(t.signal),r=t.preserveSourceArtifacts===!0||Zn(`agent`,e);try{if(n?.throwIfAborted(),!r&&t.allowLiveOwner!==!1){let t=prepareSqliteSnapshotFromLiveOwner(e,n);if(t)return await t}n?.throwIfAborted();let i=t.reuse===!0&&r,a=i?leaseReusableSqliteSnapshot(e,t.expectedSourceIdentity):void 0;if(a)return a;let o=t.requireCleanup??t.signal!==void 0,s=prepareSingleFlightSqliteSnapshot(e,`${r?`worker-sync`:`worker-async`}:${o?`strict`:`best-effort`}:sync-token${t.expectedSourceIdentity?`:${JSON.stringify(t.expectedSourceIdentity)}`:``}`,async(n,a)=>{let s,c=i?captureReusableSqliteSource(e):void 0;try{n.throwIfAborted(),s=await createSqliteSnapshotStagingDirectory(void 0,!1,n),n.throwIfAborted();let a=await Tn(e,{mode:r?`sync`:`async`,signal:n,stagingRoot:s,expectedSourceIdentity:t.expectedSourceIdentity});n.throwIfAborted(),bindReusableSqliteSource(a,c);let l=Gt(a,s,o);return i&&(l.privateFamily=captureFamily(l)),l}catch(e){if(s&&!await Qt(s)){let t=new Mt(`${re(e)}; SQLite snapshot cleanup failed: ${s}`,{cause:e});throw a?.(t),t}throw e instanceof Mt?(a(e),e):(n.throwIfAborted(),e)}},n,t.shared===!1?{scope:{}}:void 0);return i?s.then(t=>publishBoundReusableSqliteSnapshot(e,t,()=>t.cleanup())):s}catch(e){throw n?.throwIfAborted(),e}}function startSqliteReadOnlyLocationAsync(e,t={}){let n=Hn(t.signal);n?.throwIfAborted();let r=x.resolve(e),i=t.preserveSourceArtifacts===!0||Zn(`agent`,r),a=t.expectedSourceIdentity===void 0?void 0:Oe(t.expectedSourceIdentity);if(a&&!i)throw Error(`SQLite source identity requires artifact-preserving preparation`);let o=t.reuse&&i?leaseReusableSqliteSnapshot(r,a):void 0;if(o)return createLeasedSqliteSnapshotPreparation(o);let s=t.signal!==void 0,{env:c,cwd:l}=Bn(),u=resolvePrivateSqliteSnapshotStagingRoot(),d=Sn(),f=Rn(),p=S.snapshot();return startSingleFlightSqliteSnapshot(r,`${i?`worker-sync`:`worker-async`}:${s?`strict`:`best-effort`}:async-token${a?`:${JSON.stringify(a)}`:``}`,e=>p(()=>{let t=f.start({type:`prepare`,root:u,pathname:r,allowLegacyWorker:!1,preserveSourceArtifacts:i,expectedSourceIdentity:a,deadlineOwnedByCaller:d,launch:{env:c,cwd:l,transport:{kind:`native`}}},e);return{...Ve(t,e=>{if(e.type!==`prepared`)throw Error(`SQLite snapshot producer returned an allocation without its prepared location`);let t=Gt(e.location,e.directory,s);return t.privateFamily=i?captureSqlitePrivateSnapshotFamily(e.location,e.directory):void 0,t}),startClose:()=>t.startClose()}}),n,{scope:f})}async function prepareSqliteReadOnlyLocationAwaited(e,t){let n=Hn(t.signal),r=x.resolve(e),i=Oe(t.expectedSourceIdentity);return(t.reuse?leaseReusableSqliteSnapshot(r,i):void 0)||(t.reuse&&!t.allowLiveOwner&&isSqliteSnapshotReuseActive()?prepareSqliteReadOnlyLocation(r,{preserveSourceArtifacts:!0,signal:n,requireCleanup:!0,reuse:!0,expectedSourceIdentity:i}):prepareSingleFlightSqliteSnapshot(r,`worker-${t.allowLiveOwner?`metadata`:`sync`}:strict:awaited-token:${JSON.stringify(i)}`,async(e,n)=>{let a=t.allowLiveOwner;return useAwaitedSnapshotWorker(e,n,async(t,n)=>{let o={mode:a?`metadata`:`sync`,stagingRoot:n,expectedSourceIdentity:i,signal:e},s=a?await Cn(r,o):await t.run(r,o);if(typeof s!=`string`)throw Error(`SQLite snapshot preparation returned an invalid location`);return e.throwIfAborted(),Gt(s,n,!0)})},n))}async function useAwaitedSnapshotWorker(e,t,n){e.throwIfAborted();let r=Bn(),i=bn({...r,retainOnOperationError:!0}),a,o,retire=()=>{if(o&&o.read().status!==`rejected`)return o;let e=De(()=>{});return o=e.operation,(async()=>{if(a){let e=i.isRetired();e&&(await i.close(),i=bn(r)),await i.run(a,{mode:e?`staging-reconcile`:`staging-retire`})}await i.close(),await i.closed,a&&await b.promises.rm(a,{recursive:!0,force:!0,maxRetries:3,retryDelay:20})})().then(e.resolve,e.reject),o};try{let t=await i.run(resolvePrivateSqliteSnapshotStagingRoot(),{mode:`staging-create`,signal:e});if(typeof t!=`string`)throw Error(`SQLite snapshot allocation returned an invalid directory`);a=t,An(a,retire),e.throwIfAborted();let r=await n(i,a);return e.throwIfAborted(),r}catch(e){try{if(a){if(!await Qt(a))throw new Mt(`SQLite snapshot cleanup failed: ${a}`)}else await i.close(),await i.closed}catch(n){let r=AggregateError([e,n],`SQLite snapshot preparation and cleanup failed`);throw t?.(r),r}throw e}}function prepareSqliteReadOnlyLocationSync(e,t,n={}){let r=n.reuse?leaseReusableSqliteSnapshot(e,t):void 0;if(r)return r;let i=n.reuse?captureReusableSqliteSource(e):void 0,a=createSqliteSnapshotStagingDirectorySync();try{let n=Gt(mn(e,a,`sync`,t),a);return i?publishReusableSqliteSnapshot(e,i,n,()=>n.cleanup()):n}catch(e){throw On(a)?e:new Mt(`${re(e)}; SQLite snapshot cleanup failed: ${a}`,{cause:e})}}const Hd={name:`openclaw.quarantine.schema`,lifetime:`process`,schemaDependent:!0,read(e){if(typeof e==`object`&&e&&`version`in e&&typeof e.version==`number`)return{version:e.version}}};function quarantineDecisionAdmission(e){return{name:`openclaw.quarantine.decision:${x.resolve(e)}`,lifetime:`process`,read:e=>e===null||isQuarantineDecision(e)?e:void 0}}function isQuarantineDecision(t){return e(t)&&(t.kind===`agent`||t.kind===`state`)&&typeof t.reason==`string`&&typeof t.quarantinedAt==`number`&&(t.verifiedGenerationJson===null||typeof t.verifiedGenerationJson==`string`)}function readQuarantineSchemaVersion(e,t,n=!1){let r=n?void 0:Fe(e,Hd);if(r)return r.version;let i=e.prepare(`PRAGMA user_version`).get()?.user_version;if(typeof i!=`number`||!Number.isInteger(i))throw Error(`OpenClaw quarantine store ${t} has an invalid schema version.`);if(i>2)throw Error(`OpenClaw quarantine store ${t} uses newer schema version ${i}.`);return i!==0&&Ye(e,Hd,{version:i}),i}function readOpenClawDatabaseQuarantine(e,t={}){let n=Pn(t.env??process.env);t.refreshIdentity&&Ne(n);let load=()=>readPersistedQuarantineDecision(e,n,t.fresh)??null,r=t.fresh?load():Ae(n,quarantineDecisionAdmission(e),load);return r?resolveQuarantineDecision(r,e,n):void 0}function readPersistedQuarantineDecision(e,t,n=!1){if(!xr(t))return;let r=openSqliteReadOnlyDatabase(t,{timeout:5e3}),i;try{i={value:readQuarantineDecision(r,e,t,n)}}catch(e){i={error:e}}try{r.close()}catch(n){let r,a=`error`in i?i.error:void 0;if(`value`in i&&i.value)try{r=resolveQuarantineDecision(i.value,e,t)}catch(e){a=e}throw new In(a===void 0?[n]:[a,n],r)}if(`error`in i)throw i.error;return i.value}function readQuarantineDecision(e,t,n,r=!1){let i=readQuarantineSchemaVersion(e,n,r);if(i===0)return;let a=i>=2?`, verified_generation`:``,o=e.prepare(`SELECT kind, reason, quarantined_at${a} FROM quarantined_databases WHERE path = ? LIMIT 1`).get(x.resolve(t));if(!o)return;let s=i>=2?o.verified_generation:void 0;if(o.kind!==`agent`&&o.kind!==`state`||typeof o.reason!=`string`||typeof o.quarantined_at!=`number`||!Number.isInteger(o.quarantined_at)||s!=null&&typeof s!=`string`)throw Error(`OpenClaw quarantine store ${n} contains an invalid row.`);return{kind:o.kind,quarantinedAt:o.quarantined_at,reason:o.reason,verifiedGenerationJson:typeof s==`string`?s:null}}function resolveQuarantineDecision(e,t,n){if(e.verifiedGenerationJson!==null){let r;try{r=parseSqliteFileGeneration(e.verifiedGenerationJson)}catch{throw Error(`OpenClaw quarantine store ${n} contains an invalid row.`)}try{let e=readSqliteFileGenerationSync(x.resolve(t));if(!sameSqliteFileGeneration(r,e))return}catch{return}}return{kind:e.kind,quarantinedAt:e.quarantinedAt,reason:e.reason}}function readOpenClawDatabaseQuarantineFailure(e,t,n={}){let r,i;try{r=readOpenClawDatabaseQuarantine(t,n)}catch(e){if(!(e instanceof In))return;if(!e.quarantine)throw e;r=e.quarantine,i=e}if(!r)return;let a=/* @__PURE__ */ Error(`OpenClaw ${e} database ${t} is quarantined after integrity verification failed: ${r.reason??`unknown integrity error`}. Restore the database from a backup or repair it, then run openclaw doctor --fix to clear the quarantine. See ${Fn}.`);return a.name=`SqliteIntegrityError`,i&&(a.cause=i),a}const Ud=new S;function getProcessCleanupBudget(){return Ud.getStore()}function createStateDatabaseRetainer(e,t){let admit=(e,n,r)=>{let i=hn();return n===`cached-read`?i?.assertReadAdmission():i?.assertAdmission(),t.assertOpen(e,n,r),i},retain=(n,r,i=!1)=>{if(t.capture(n.path).assertCurrent(),e.cachedDatabases.get(n.path)!==n||!n.db.isOpen)throw Error(`OpenClaw state database borrow requires its current canonical handle`);let a=e.borrowers.get(n.db)??{references:/* @__PURE__ */ new Set,retiring:!1,cleanupComplete:!1};if(a.retiring)throw Error(`OpenClaw state database native owner is retiring`);i||_n(n.db),e.borrowers.set(n.db,a);let isCurrent=()=>!r||Yn(n.db,r),o=i?void 0:{ordinary:r===void 0,isCurrent,retire:()=>{isCurrent()?t.retire(n,r===void 0):a.retiring=!1}};function createAsyncStateDatabaseRetirement(){let e={},r,i,finish=r=>{a.references.delete(e),a.releaseJoin?a.releaseJoin.resolve():r?.isCurrent()?r.retire():a.retiring=!1,a.retirement=void 0,a.asyncRetirement=void 0,i?.(),i=void 0,a.releaseJoin||t.touch(n)},run=()=>r||(a.cleanupComplete||a.references.size>+!!a.references.has(e)?Promise.resolve():a.retirement?.isCurrent()?(a.retiring=!0,a.references.add(e),i??=t.ownRetirement(n,close),r=Promise.resolve().then(async()=>{await n.walMaintenance.stop(),finish(a.retirement)}).catch(r=>{throw a.references.add(e),t.retainFailed(n),a.releaseJoin?.reject(r),a.releaseJoin=void 0,r}),r.catch(()=>{}),r):(finish(),Promise.resolve()));function close(){let e=run();return e.catch(t=>{throw r===e&&(r=void 0),t})}return{start:()=>void run(),close}}let s={};a.references.add(s);let c=!1,release=()=>{if(c||a.cleanupComplete)c=!0;else if(c=!0,a.references.delete(s),a.releaseJoin)a.references.size===0&&a.releaseJoin.resolve();else if(a.retirement&&!a.retirement.isCurrent()&&(a.retirement=void 0,a.asyncRetirement=void 0,a.retiring=!1),o?.isCurrent()&&!a.retirement?.ordinary&&(a.retirement=o),!(a.references.size>0)){if(!a.retirement)t.touch(n);else if(a.retiring=!0,a.asyncRetirement)a.asyncRetirement.start();else{try{a.retirement.retire()}catch(e){throw c=!1,t.retainFailed(n),e}a.retirement=void 0,t.touch(n)}}},l={release,async releaseAsync(){a.cleanupComplete||(a.releaseJoin?release():((o?.isCurrent()&&!a.retirement?.ordinary?o:a.retirement)?.isCurrent()&&(a.asyncRetirement??=createAsyncStateDatabaseRetirement()),release(),await a.asyncRetirement?.close()))}};return r?.own(l,`shared-references`,()=>l.releaseAsync()),l},findReadDatabase=(t,n,r)=>{let i=y({path:t}),a=e.cachedDatabases.get(i);return a?.db.isOpen?{database:a,scope:admit(i,n,r)}:{database:void 0,scope:void 0}},retainReadReference=(t,n)=>{let r=retain(t,n,!0),assertCurrent=()=>{if(e.cachedDatabases.get(t.path)!==t||!t.db.isOpen)throw Error(`Shared-state read lost its original native owner`)};return{assertCurrent,observe(){assertCurrent(),_n(t.db)},release:()=>r.release()}};return{retain:e=>retain(e,admit(e.path)),retainForIndependentRead(e,t,n){let{database:r,scope:i}=findReadDatabase(e,t,n);return r?retainReadReference(r,i):void 0},borrowForRead(e,t,n){let{database:r,scope:i}=findReadDatabase(e,t,n);if(r){if(r.db.isTransaction)throw Error(`Asynchronous shared-state reads cannot run inside a native transaction`);return{database:r,...retainReadReference(r,i)}}}}}async function joinStateDatabaseBorrowersReleased(e,t){e&&!e.cleanupComplete&&(e.retiring=!0,e.references.size!==0&&(e.releaseJoin||(e.releaseJoin=er(),getProcessCleanupBudget()?.warn(`Waiting for ${e.references.size} active native borrower(s) before retiring OpenClaw state database: ${t}`)),await e.releaseJoin.promise))}function assertStateDatabaseBorrowersReleased(e,t){if(e?.references.size)throw Error(`OpenClaw state database still has active native borrowers (${e.references.size}): ${t}`)}function createStateDatabaseCacheAdmission(e){return{closeTerminalFailure(t,n){Nn(n,t),ht(t),e.invalidate(t);let r=e.cachedDatabases.get(t),i=[];try{r&&e.evict(r)}catch(e){i.push(e)}try{e.notifyTerminalFailure(t,n)}catch(e){i.push(e)}At(i,`Terminal shared-state failure cleanup failed`)},read(t,n){if(!t.db.isOpen)return n(t);let r=!1;try{return en(t.db,()=>(r=!0,n(t)))}catch(n){if(r)throw n;let i=n instanceof Error?n:Error(String(n));if(it(i)){e.evict(t);return}throw i}}}}const Wd=ue(`state/db`);function createStateDatabaseIdleRetirement({cachedDatabases:e,retainedDatabaseHandles:t,idleTimers:n,idleReferences:r,borrowers:i},a){let touch=o=>{if(!(e.get(o.path)===o&&o.db.isOpen)&&t.get(o.db)!==o)return;let s=n.get(o.db);if(s){s.refresh();return}let c=d(()=>setTimeout(()=>{n.delete(o.db);try{o.db.isOpen&&o.db.isTransaction?touch(o):!i.get(o.db)?.references.size&&!r.get(o.db)?.size&&a(o,!1,{busyTimeoutMs:0,checkpointMode:`PASSIVE`})}catch(e){Wd.warn(`Idle shared-state database cleanup failed`,{path:o.path,error:e}),touch(o)}},Cs));c.unref(),n.set(o.db,c)};return{touch,retain(t){if(e.get(t.path)!==t||!t.db.isOpen||i.get(t.db)?.retiring)throw Error(`OpenClaw state database idle retention requires its current canonical handle`);let n=r.get(t.db)??/* @__PURE__ */ new Set,a={};return n.add(a),r.set(t.db,n),()=>{n.delete(a)&&e.get(t.path)===t&&t.db.isOpen&&touch(t)}}}}const Gd=s(Symbol.for(`openclaw.sqliteWalWriteAdmissions`),()=>/* @__PURE__ */ new WeakMap);function registerSqliteWalWorkerMaintenance(e,t,n){e.exec(`PRAGMA wal_autocheckpoint = 0;`);let r=Gd.get(e)?.stopCheckpointTick;Gd.set(e,{execute:t,cancel:n}),r?.()}function isSqliteWalWorkerMaintained(e){return Gd.get(e)?.execute!==void 0}function cancelSqliteWalWriteAdmission(e){return Gd.get(e)?.cancel?.()}function createSqliteWalMaintenanceScheduler(e,t,n,r,i,a,o){let s=Gd.get(e);Gd.set(e,{...s,stopCheckpointTick:o});let c;return()=>(c||=(async()=>{let i=a(),o=!1;for(;;){let a=n(i);if(!a||i===0&&Gd.get(e)?.execute)return;a.continuation=o;let s,admitted=()=>{n(i)&&(s=t(a))},c=Gd.get(e);c?.execute?(s=await c.execute(a),s?.checkpoint&&r(s.checkpoint)):c?.admit?await c.admit(admitted):admitted();let l=s?.reclaimedPages??0;if(i-=l,l<=0||i<=0)return;o=!0,await Fr()}})().catch(i).finally(()=>{c=void 0}),c)}var Kd={blockedEverywhereKeys:/* @__PURE__ */ `NODE_OPTIONS.NODE_PATH.NODE_REDIRECT_WARNINGS.NODE_REPL_EXTERNAL_MODULE.NODE_REPL_HISTORY.NODE_V8_COVERAGE.PYTHONHOME.PYTHONPATH.PERL5LIB.PERL5OPT.PERL5SHELL.PERLLIB.RUBYLIB.RUBYOPT.BASHOPTS.BASH_ENV.ENV.KSH_ENV.BROWSER.GIT_ALLOW_PROTOCOL.GIT_EDITOR.GIT_EXTERNAL_DIFF.GIT_DIR.GIT_WORK_TREE.GIT_COMMON_DIR.GIT_EXEC_PATH.GIT_INDEX_FILE.GIT_OBJECT_DIRECTORY.GIT_ALTERNATE_OBJECT_DIRECTORIES.GIT_NAMESPACE.GIT_PROTOCOL_FROM_USER.GIT_SEQUENCE_EDITOR.GIT_TEMPLATE_DIR.GIT_SSL_NO_VERIFY.GIT_SSL_CAINFO.GIT_SSL_CAPATH.CC.CPP.CXX.CXXCPP.CARGO_BUILD_RUSTC.CARGO_BUILD_RUSTC_WRAPPER.CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER.CARGO_BUILD_RUSTDOC.RUSTC.RUSTC_WRAPPER.RUSTC_WORKSPACE_WRAPPER.RUSTDOC.CMAKE_C_COMPILER.CMAKE_CXX_COMPILER.SHELL.SHELLOPTS.PS4.GCONV_PATH.IFS.SSLKEYLOGFILE.JAVA_OPTS.JAVA_TOOL_OPTIONS._JAVA_OPTIONS.JDK_JAVA_OPTIONS.PYTHONBREAKPOINT.DOTNET_STARTUP_HOOKS.DOTNET_ADDITIONAL_DEPS.FPATH.GLIBC_TUNABLES.MAVEN_OPTS.MAKE.MAKEFLAGS.MFLAGS.SBT_OPTS.GRADLE_OPTS.ANT_OPTS.HGRCPATH.HGEDITOR.HGMERGE.EXINIT.VIMINIT.MYVIMRC.GVIMINIT.LUA_INIT.LUA_INIT_5_1.LUA_INIT_5_2.LUA_INIT_5_3.LUA_INIT_5_4.EMACSLOADPATH.RUBYSHELL.GIT_HOOK_PATH.SVN_EDITOR.SVN_SSH.BZR_EDITOR.BZR_SSH.BZR_PLUGIN_PATH.SUDO_ASKPASS.JULIA_EDITOR.CONFIG_SITE.CONFIG_SHELL.CMAKE_TOOLCHAIN_FILE.CATALINA_OPTS.CORECLR_PROFILER.HELM_PLUGINS.PACKER_PLUGIN_PATH.VAGRANT_VAGRANTFILE.ERL_AFLAGS.ERL_FLAGS.ERL_ZFLAGS.ELIXIR_ERL_OPTIONS.R_ENVIRON.R_PROFILE.R_ENVIRON_USER.R_PROFILE_USER.TCLLIBPATH.HOSTALIASES`.split(`.`),blockedOverrideOnlyKeys:/* @__PURE__ */ `HOME.GRADLE_USER_HOME.ZDOTDIR.GIT_DIR.GIT_WORK_TREE.GIT_COMMON_DIR.GIT_INDEX_FILE.GIT_OBJECT_DIRECTORY.GIT_ALTERNATE_OBJECT_DIRECTORIES.GIT_NAMESPACE.GIT_SSH_COMMAND.GIT_SSH.GIT_PROXY_COMMAND.GIT_ASKPASS.GIT_SSL_NO_VERIFY.GIT_SSL_CAINFO.GIT_SSL_CAPATH.SSH_ASKPASS.LESSOPEN.LESSCLOSE.PAGER.MANPAGER.GIT_PAGER.EDITOR.VISUAL.FCEDIT.SUDO_EDITOR.PROMPT_COMMAND.HISTFILE.PERL5DB.PERL5DBCMD.OPENSSL_CONF.OPENSSL_ENGINES.PYTHONSTARTUP.WGETRC.CURL_HOME.CLASSPATH.CFLAGS.CGO_CFLAGS.CGO_LDFLAGS.GOFLAGS.MAKEFLAGS.MFLAGS.CORECLR_PROFILER_PATH.PHPRC.PHP_INI_SCAN_DIR.DENO_DIR.BUN_CONFIG_REGISTRY.YARN_RC_FILENAME.HTTP_PROXY.HTTPS_PROXY.ALL_PROXY.NO_PROXY.NODE_TLS_REJECT_UNAUTHORIZED.NODE_EXTRA_CA_CERTS.SSL_CERT_FILE.SSL_CERT_DIR.REQUESTS_CA_BUNDLE.CURL_CA_BUNDLE.DOCKER_HOST.DOCKER_TLS_VERIFY.DOCKER_CERT_PATH.PIP_INDEX_URL.PIP_PYPI_URL.PIP_EXTRA_INDEX_URL.PIP_CONFIG_FILE.PIP_FIND_LINKS.PIP_TRUSTED_HOST.UV_INDEX.UV_INDEX_URL.UV_PYTHON.UV_EXTRA_INDEX_URL.UV_DEFAULT_INDEX.DOCKER_CONTEXT.LIBRARY_PATH.LDFLAGS.CPATH.C_INCLUDE_PATH.CPLUS_INCLUDE_PATH.OBJC_INCLUDE_PATH.GOPROXY.GONOSUMCHECK.GONOSUMDB.GONOPROXY.GOPRIVATE.GOENV.GOPATH.HGRCPATH.PYTHONUSERBASE.RUSTC_WRAPPER.RUSTFLAGS.RUSTUP_DIST_ROOT.RUSTUP_DIST_SERVER.RUSTUP_HOME.RUSTUP_TOOLCHAIN.RUSTUP_UPDATE_ROOT.CARGO_HOME.VIRTUAL_ENV.LUA_PATH.LUA_CPATH.GEM_HOME.GEM_PATH.BUNDLE_GEMFILE.COMPOSER_HOME.CONDA_DEFAULT_ENV.CONDA_PREFIX.CARGO_BUILD_RUSTC_WRAPPER.XDG_CACHE_HOME.XDG_CONFIG_DIRS.XDG_CONFIG_HOME.XDG_DATA_DIRS.XDG_DATA_HOME.XDG_RUNTIME_DIR.XDG_STATE_HOME.AWS_CONFIG_FILE.KUBECONFIG.GOOGLE_APPLICATION_CREDENTIALS.AWS_SHARED_CREDENTIALS_FILE.AWS_WEB_IDENTITY_TOKEN_FILE.AZURE_AUTH_LOCATION.HELM_HOME.ANSIBLE_CONFIG.ANSIBLE_LIBRARY.ANSIBLE_CALLBACK_PLUGINS.ANSIBLE_COLLECTIONS_PATH.ANSIBLE_CONNECTION_PLUGINS.ANSIBLE_FILTER_PLUGINS.ANSIBLE_INVENTORY_PLUGINS.ANSIBLE_LOOKUP_PLUGINS.ANSIBLE_MODULE_UTILS.ANSIBLE_REMOTE_TEMP.ANSIBLE_ROLES_PATH.ANSIBLE_STRATEGY_PLUGINS.R_LIBS_USER.TF_CLI_CONFIG_FILE.TF_PLUGIN_CACHE_DIR.AMQP_URL.AWS_ACCESS_KEY_ID.AWS_CONTAINER_CREDENTIALS_FULL_URI.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.AWS_SECRET_ACCESS_KEY.AWS_SECURITY_TOKEN.AWS_SESSION_TOKEN.AZURE_CLIENT_ID.AZURE_CLIENT_SECRET.DATABASE_URL.GH_TOKEN.GITHUB_TOKEN.GITLAB_TOKEN.MONGODB_URI.NODE_AUTH_TOKEN.NPM_TOKEN.REDIS_URL.SSH_AUTH_SOCK.SYSTEMROOT.WINDIR`.split(`.`),allowedInheritedOverrideOnlyKeys:/* @__PURE__ */ `ALL_PROXY.AWS_CONFIG_FILE.AWS_SHARED_CREDENTIALS_FILE.AWS_WEB_IDENTITY_TOKEN_FILE.AZURE_AUTH_LOCATION.CURL_CA_BUNDLE.DOCKER_CERT_PATH.DOCKER_CONTEXT.DOCKER_HOST.DOCKER_TLS_VERIFY.GIT_PAGER.GOOGLE_APPLICATION_CREDENTIALS.GRADLE_USER_HOME.HISTFILE.HOME.HTTPS_PROXY.HTTP_PROXY.KUBECONFIG.MANPAGER.NODE_EXTRA_CA_CERTS.NODE_TLS_REJECT_UNAUTHORIZED.NO_PROXY.PAGER.REQUESTS_CA_BUNDLE.RUSTUP_DIST_ROOT.RUSTUP_DIST_SERVER.RUSTUP_HOME.RUSTUP_TOOLCHAIN.RUSTUP_UPDATE_ROOT.SSH_AUTH_SOCK.SSL_CERT_DIR.SSL_CERT_FILE.SYSTEMROOT.WINDIR.XDG_CACHE_HOME.XDG_CONFIG_DIRS.XDG_CONFIG_HOME.XDG_DATA_DIRS.XDG_DATA_HOME.XDG_RUNTIME_DIR.XDG_STATE_HOME.ZDOTDIR`.split(`.`),blockedOverridePrefixes:[`GIT_CONFIG_`,`NPM_CONFIG_`,`CARGO_REGISTRIES_`,`TF_VAR_`],blockedPrefixes:[`DYLD_`,`LD_`,`BASH_FUNC_`]};function sortUniqueUppercase(e){return Object.freeze(Array.from(new Set(e.map(e=>e.toUpperCase()))).toSorted((e,t)=>e<t?-1:+(e>t)))}function derivePolicyArrays(e){let t=e.blockedEverywhereKeys??[],n=e.blockedOverrideOnlyKeys??[],r=e.allowedInheritedOverrideOnlyKeys??[],i=new Set(r.map(e=>e.toUpperCase())),a=e.blockedPrefixes??[],o=e.blockedOverridePrefixes??[],s=e.blockedInheritedPrefixes??a;return{blockedInheritedKeys:sortUniqueUppercase([...t,...n.filter(e=>!i.has(e.toUpperCase()))]),blockedInheritedPrefixes:sortUniqueUppercase(s),blockedKeys:sortUniqueUppercase(t),blockedOverrideKeys:sortUniqueUppercase(n),blockedPrefixes:sortUniqueUppercase(a),blockedOverridePrefixes:sortUniqueUppercase(o)}}function loadHostEnvSecurityPolicy(e=Kd){let t=derivePolicyArrays(e);return Object.freeze({blockedEverywhereKeys:Object.freeze(e.blockedEverywhereKeys??[]),blockedOverrideOnlyKeys:Object.freeze(e.blockedOverrideOnlyKeys??[]),allowedInheritedOverrideOnlyKeys:Object.freeze(e.allowedInheritedOverrideOnlyKeys??[]),blockedInheritedKeys:t.blockedInheritedKeys,blockedInheritedPrefixes:t.blockedInheritedPrefixes,blockedPrefixes:t.blockedPrefixes,blockedOverridePrefixes:t.blockedOverridePrefixes,blockedKeys:t.blockedKeys,blockedOverrideKeys:t.blockedOverrideKeys})}const qd=loadHostEnvSecurityPolicy(),Jd=/^[A-Za-z_][A-Za-z0-9_]*$/,Yd=new Set(qd.blockedKeys);new Set(qd.blockedInheritedKeys);const Xd=new Set(qd.blockedOverrideKeys);(/* @__PURE__ */ new Set([...Object.keys(resolveNodeServiceIdentityEnvironment()),`OPENCLAW_GATEWAY_SERVICE_PID`])).delete(`OPENCLAW_PROFILE`);const Zd=/^CARGO_TARGET_[A-Z0-9_]+_(?:LINKER|RUNNER)$/;new S;function normalizeEnvVarKey(e,t){let n=e.trim();return!n||t?.portable&&!Jd.test(n)?null:n}function isDangerousHostEnvVarName(e){let t=normalizeEnvVarKey(e)?.toUpperCase();return t!==void 0&&(Yd.has(t)||qd.blockedPrefixes.some(e=>t.startsWith(e)))}function isDangerousHostEnvOverrideVarName(e){let t=normalizeEnvVarKey(e)?.toUpperCase();return t!==void 0&&(Xd.has(t)||Zd.test(t)||qd.blockedOverridePrefixes.some(e=>t.startsWith(e)))}function isConfigRuntimeEnvVarAllowed(e,t){let n=e.toUpperCase();return!!t.trim()&&n!==`OPENCLAW_ALLOW_OLDER_BINARY_DESTRUCTIVE_ACTIONS`&&n!==`OPENCLAW_INCLUDE_ROOTS`&&n!==`OPENCLAW_CONFIG_READONLY`&&n!==`OPENCLAW_CONFIG_READONLY_NOTICE`&&n!==`OPENCLAW_DISABLE_GATEWAY_LOCAL_TERMINALS`&&n!==`OPENCLAW_DISABLE_CRON_HOST_EXECUTION`&&n!==`OPENCLAW_DEV_RELOAD_BUNDLED_PLUGINS`&&!isDangerousHostEnvVarName(e)&&!isDangerousHostEnvOverrideVarName(e)&&!u(t)}function collectConfigRuntimeEnvVars(e){let t=e?.env;if(!t)return{};let n={},r=[...Object.entries(t.vars??{}),...Object.entries(t).filter(([e])=>e!==`shellEnv`&&e!==`vars`)];for(let[e,t]of r){if(typeof t!=`string`)continue;let r=normalizeEnvVarKey(e,{portable:!0});r&&isConfigRuntimeEnvVarAllowed(r,t)&&(n[r]=t)}return n}function findCaseInsensitiveEnvKey(e,t){if(Object.hasOwn(e,t))return t;let n=t.toUpperCase();return Object.keys(e).find(e=>e.toUpperCase()===n)}function envSnapshotKey(e){return process.platform===`win32`?e.toUpperCase():e}function indexConfigRuntimeEnvValues(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of Object.entries(e))for(let e of a(n)){let n=t.get(e)??/* @__PURE__ */ new Set;n.add(r),t.set(e,n)}return t}const Qd=/* @__PURE__ */ new WeakMap;function resolveAppliedConfigEnvOwnership(e){return{...Qd.get(le(e)),...e===process.env?$d.ownedEnv:{}}}new S;function cloneEnvWithPlatformSemantics(e){let t={...te(e)};return process.platform===`win32`&&(t=new Proxy(t,{deleteProperty(e,t){if(typeof t!=`string`)return Reflect.deleteProperty(e,t);let n=findCaseInsensitiveEnvKey(e,t);return!n||Reflect.deleteProperty(e,n)},get(e,t,n){if(typeof t!=`string`)return Reflect.get(e,t,n);let r=findCaseInsensitiveEnvKey(e,t);return r?e[r]:Reflect.get(e,t,n)},getOwnPropertyDescriptor(e,t){if(typeof t!=`string`)return Reflect.getOwnPropertyDescriptor(e,t);let n=findCaseInsensitiveEnvKey(e,t);if(n)return{configurable:!0,enumerable:!0,value:e[n],writable:!0}},has(e,t){return typeof t==`string`?findCaseInsensitiveEnvKey(e,t)!==void 0:Reflect.has(e,t)},set(e,t,n){return typeof t==`string`?(e[findCaseInsensitiveEnvKey(e,t)??t]=n,!0):Reflect.set(e,t,n)}})),Qd.set(c(t),resolveAppliedConfigEnvOwnership(e)),i(t),t}let $d={ownedEnv:{},sourceConfig:null};function collectConfigRuntimeEnvOwnership(e,t,n,r={}){let i=te(t),o=te(n),s={},c=new Set((r.replacedLowerPrecedenceKeys??[]).map(envSnapshotKey));for(let[t,n]of Object.entries(collectConfigRuntimeEnvVars(e)))for(let e of a(t)){let t=findCaseInsensitiveEnvKey(o,e);if(!t||o[t]!==n)continue;let r=findCaseInsensitiveEnvKey(i,e);(!r||i[r]!==n||c.has(envSnapshotKey(t)))&&(s[t]=n)}return s}function filterConfigRuntimeEnvOwnership(e,t,n){let r=te(t),i=indexConfigRuntimeEnvValues(collectConfigRuntimeEnvVars(e)),o={};for(let[e,t]of Object.entries(n)){let n=a(e)[0]??e,s=findCaseInsensitiveEnvKey(r,e);s&&r[s]===t&&i.get(n)?.has(t)&&(o[s]=t)}return o}function applyConfigEnvVars(e,t=process.env,n={}){g(t);let r={...t},o=resolveAppliedConfigEnvOwnership(t),s=collectConfigRuntimeEnvVars(e),l=Object.entries(n.lowerPrecedenceEnv??{}),u=new Map(l.map(([e,t])=>[envSnapshotKey(e),t])),d=me(Object.keys(s)),f=indexConfigRuntimeEnvValues(s),p=/* @__PURE__ */ new Map;for(let e of Object.keys(s)){let n=a(e),r=n.map(e=>[e,t[e]]).find(([e,t])=>t?.trim()&&u.get(e)!==t&&!f.get(e)?.has(t))?.[1];if(r!==void 0)for(let e of n)p.set(e,r)}let m=[];for(let[e,n]of l)d.has(envSnapshotKey(e))&&t[e]===n&&(delete t[e],m.push(e));m.length>0&&n.onLowerPrecedenceKeysReplaced?.(m);for(let[e,n]of Object.entries(s)){let r=p.get(envSnapshotKey(e));if(r!==void 0){t[e]=r;continue}let i=t[e];i?.trim()&&u.get(envSnapshotKey(e))!==i||(t[e]=n)}ee(t),Qd.set(c(t),{...filterConfigRuntimeEnvOwnership(e,t,o),...collectConfigRuntimeEnvOwnership(e,r,t,{replacedLowerPrecedenceKeys:m})}),i(t)}const ef=s(Symbol.for(`openclaw.gatewayServiceInstallation`),()=>new S);function getGatewayServiceInstallation(){return ef.getStore()?.installation}function isGatewayExternallySupervised(e=process.env){return e.OPENCLAW_SUPERVISOR_MODE?.trim().toLowerCase()===`external`}function jsonArrayValue(e,t){return V`${V.raw(v(e)?`json_build_array`:`json_array`)}(${V.join(t)})`}function jsonObjectValue(e,t){return V`${V.raw(v(e)?`json_build_object`:`json_object`)}(${V.join(Object.entries(t).flatMap(([e,t])=>[V.lit(e),t]))})`}function objectPath(e){return V`string_to_array(substr(${e}, 3), '.')`}function jsonPathValue(e,t,n,r=`text`){if(!v(e))return V`json_extract(${t}, ${n})`;let i=V`(${t}::jsonb ${V.raw(r===`json`?`#>`:`#>>`)} ${objectPath(n)})`;return V`${i}${V.raw(r===`number`?`::double precision`:r===`json`?`::text`:``)}`}function jsonValid(e,t){return v(e)?V`pg_input_is_valid(${t}, 'json')`:V`json_valid(${t})`}function jsonType(e,t,n){let r=n?v(e)?V`(${t}::jsonb #> ${objectPath(n)})`:V`${t}, ${n}`:t;return v(e)?V`jsonb_typeof(${r}::jsonb)`:V`json_type(${r})`}function jsonRemovePaths(e,t,n){if(!v(e))return V`json_remove(${t}, ${V.join(n)})`;let r=V`${t}::jsonb`;for(let e of n)r=V`(${r} #- ${objectPath(e)})`;return V`${r}::text`}function jsonSetPath(e,t,n,r,i=!1){if(!v(e))return V`json_set(${t}, ${n}, ${r})`;let a=i?V`${r}::jsonb`:V`to_jsonb(${r}::text)`;return V`jsonb_set(${t}::jsonb, ${objectPath(n)}, coalesce(${a}, 'null'::jsonb))::text`}function jsonPickObject(e,t,n){return v(e)?V`(SELECT coalesce(jsonb_object_agg(key, value), '{}'::jsonb)::text
        FROM jsonb_each(CASE WHEN jsonb_typeof(${t}::jsonb) = 'object' THEN ${t}::jsonb ELSE '{}'::jsonb END)
        WHERE key IN (${V.join(n)}))`:V`(SELECT json_group_object(key, CASE type
    WHEN 'object' THEN json(value) WHEN 'array' THEN json(value)
    WHEN 'true' THEN json('true') WHEN 'false' THEN json('false')
    ELSE value END) FROM json_each(${t}) WHERE key IN (${V.join(n)}))`}function jsonNativeFieldsValid(e,t){return v(e)?V`coalesce(pg_input_is_valid(${t}, 'jsonb'), false)`:V`coalesce(json_valid(${t}), 0)`}const tf=s(Symbol.for(`openclaw.stateDatabaseSchemaPolicies`),()=>({scopes:new S,existingDatabases:/* @__PURE__ */ new WeakMap,hasAdmittedExistingDatabase:!1}));function canonicalPath(e){let n=y({path:e});try{return Je(Sr.native(n))}catch(e){if(t(e,`ENOENT`))return n;throw e}}function assertSchemaScopeActive(e){if(e&&!e.active)throw Error(`Existing shared-state schema admission has ended.`)}function getExistingOpenClawStateSchemaPath(){let e=tf.scopes.getStore();return assertSchemaScopeActive(e),e?.path}function captureOpenClawStateSchemaReadAdmission(e){let t=tf.scopes.getStore();if(t)return isExistingOpenClawStateSchema(e),{path:t.path,assertCurrent:()=>assertSchemaScopeActive(t)}}function isExistingOpenClawStateSchema(e,t){let n=getExistingOpenClawStateSchemaPath(),r=tf.scopes.getStore(),i=t&&tf.existingDatabases.get(t);if(!r&&!i)return!1;let a=y({path:e}),o=n!==void 0&&(n===a||r?.canonicalPath===a||r?.canonicalPath===canonicalPath(a));if(n&&!o)throw Error(`Existing shared-state schema admission is bound to ${n}, not ${e}.`);if(i&&(!o||i!==r?.canonicalPath))throw Error(`Shared-state database ${e} was admitted without schema repair; close its existing handle before ordinary admission.`);return o}function recordExistingOpenClawStateSchemaDatabase(e,t){let n=tf.scopes.getStore();if(!n||!isExistingOpenClawStateSchema(t,e))throw Error(`Existing shared-state schema admission requires its active path scope.`);tf.existingDatabases.set(e,n.canonicalPath),tf.hasAdmittedExistingDatabase=!0}function assertExistingOpenClawStateSchemaCacheAdmission(e,t){let n=getExistingOpenClawStateSchemaPath();if(!tf.hasAdmittedExistingDatabase)return;let r=tf.scopes.getStore(),i=r?y({path:e}):void 0,a=r&&(n===i||r.canonicalPath===i)?r.canonicalPath:void 0;for(let n of[t.cachedDatabases,t.retainedDatabaseHandles])for(let{db:t}of n.values()){let n=tf.existingDatabases.get(t);n&&t.isOpen&&(a??=canonicalPath(e),n===a&&isExistingOpenClawStateSchema(e,t))}}function assertOpenClawStateSchemaRepairAllowed(e){if(isExistingOpenClawStateSchema(e))throw Error(`Shared-state schema repair is owned by the existing installation at ${e}; run openclaw doctor --fix with that installation. The managed node retries automatically.`)}function captureSqliteWorkerStateContext(e){return{databaseEngineSelection:e.databaseEngineSelection??Le(),environment:{...e.environment},initializationCronDefaultStoreKey:e.initializationCronDefaultStoreKey,...e.initializationEnvironment?{initializationEnvironment:{...e.initializationEnvironment}}:{},...e.initializationAgentPaths?{initializationAgentPaths:[...e.initializationAgentPaths]}:{},existingSchemaPath:e.existingSchemaPath,gatewayServiceInstallation:e.gatewayServiceInstallation,...e.stateIntegrity?{stateIntegrity:e.stateIntegrity}:{},artifactPreservingReads:e.artifactPreservingReads,liveStateReads:e.liveStateReads,...e.scheduledMaintenanceSuspension?{scheduledMaintenanceSuspension:e.scheduledMaintenanceSuspension}:{}}}function sqliteWorkerRequestBytes(e,t,n){let r=t?.initializationAgentPaths?.reduce((e,t)=>e+Buffer.byteLength(t,`utf8`),0)??0;return[t?.environment,t?.initializationEnvironment].reduce((e,t)=>Object.entries(t??{}).reduce((e,[t,n])=>e+Buffer.byteLength(t,`utf8`)+Buffer.byteLength(n??``,`utf8`),e),e.byteLength+Buffer.byteLength(JSON.stringify(t?.databaseEngineSelection)??``,`utf8`)+Buffer.byteLength(JSON.stringify(t?.gatewayServiceInstallation)??``,`utf8`)+(n?.byteLength??0)+r+Buffer.byteLength(t?.initializationCronDefaultStoreKey??``,`utf8`)+(t?.scheduledMaintenanceSuspension?.byteLength??0))}const nf=s(Symbol.for(`openclaw.sqliteWorkerStateContext`),()=>new S);function captureSqliteWorkerWalMaintenanceSuspension(){let e=nf.getStore()?.scheduledMaintenanceSuspension;if(!e)return;let t=new Int32Array(e);return()=>Atomics.load(t,0)>0}function getSqliteWorkerCronDefaultStoreKey(){return nf.getStore()?.initializationCronDefaultStoreKey}function getSqliteWorkerExistingDatabaseIdentity(e){let t=nf.getStore()?.existingDatabase;return t?.databasePath===e?t.identity:void 0}function getSqliteWorkerStateIntegrityAdmission(){return nf.getStore()?.stateIntegrity}const rf=`cron.defaultStoreKey`;function resolveLegacyCronDefaultStoreKey(e){return x.resolve(fe(e),`cron`,`jobs.json`)}function resolveCronIdentityMigrationDefaultStoreKey(e){return getSqliteWorkerCronDefaultStoreKey()??resolveLegacyCronDefaultStoreKey(e)}function readBindingRow(e,t){if(t?.has(`config_machine_state`)??tableExists(e,`config_machine_state`))return executeSqliteQueryTakeFirstSync(e,getNodeSqliteKysely(e).selectFrom(`config_machine_state`).select(`value_json`).where(`state_key`,`=`,rf))}function resolveUnboundCronDefaultStoreKey(e,t){return e.length===0||e.some(e=>e.storeKey===t)?t:void 0}const af=[[`cron_jobs`,`jobs`],[`cron_job_scratch`,`scratch`],[`cron_run_receipts`,`receipts`]];function readCronStorePartitionInventoryInDatabase(t,n){let r=/* @__PURE__ */ new Map,add=(e,t,n)=>{if(typeof e!=`string`||e.length===0)return;let i=r.get(e);i||(i={storeKey:e,jobs:0,scratch:0,receipts:0,history:0,quarantine:0,proactiveReceipts:0},r.set(e,i)),i[t]+=n};for(let[e,r]of af)if(n?.has(e)??tableExists(t,e)){let n=getNodeSqliteKysely(t).selectFrom(e).select(`store_key`).select(e=>e.fn.countAll().as(`count`)).groupBy(`store_key`);for(let e of executeSqliteQuerySync(t,n).rows)add(e.store_key,r,Number(e.count))}if(n?.has(`cron_run_logs`)??tableExists(t,`cron_run_logs`)){let e=getNodeSqliteKysely(t).selectFrom(`cron_run_logs`).select(`store_key`).select(e=>e.fn.countAll().as(`count`)).groupBy(`store_key`);for(let n of executeSqliteQuerySync(t,e).rows)add(n.store_key,`history`,Number(n.count))}if(n?.has(`task_runs`)??tableExists(t,`task_runs`)){let n=getNodeSqliteKysely(t).selectFrom(`task_runs`).select(e=>[V`CASE WHEN ${jsonValid(t,e.ref(`detail_json`))}
          THEN ${jsonPickObject(t,e.ref(`detail_json`),[`storeKey`])} END`.as(`detail_json`)]).where(`runtime`,`=`,`cron`);for(let r of executeSqliteQuerySync(t,n).rows)if(typeof r.detail_json==`string`)try{let t=JSON.parse(r.detail_json);e(t)&&add(t.storeKey,`history`,1)}catch{}}if(n?.has(`diagnostic_events`)??tableExists(t,`diagnostic_events`)){let e=getNodeSqliteKysely(t).selectFrom(`diagnostic_events`).select(`scope`).select(e=>e.fn.countAll().as(`count`)).where(`scope`,`like`,`cron.quarantine:%`).groupBy(`scope`);for(let n of executeSqliteQuerySync(t,e).rows)typeof n.scope==`string`&&add(n.scope.slice(16),`quarantine`,Number(n.count))}if(n?.has(`config_machine_state`)??tableExists(t,`config_machine_state`)){let e=getNodeSqliteKysely(t).selectFrom(`config_machine_state`).select(`state_key`).where(`state_key`,`like`,`automation-default:%`);for(let n of executeSqliteQuerySync(t,e).rows)add(n.state_key.slice(19,n.state_key.lastIndexOf(`:`)),`proactiveReceipts`,1)}return[...r.values()].toSorted((e,t)=>e.storeKey<t.storeKey?-1:+(e.storeKey>t.storeKey))}const of={version:34,tables:[`config_machine_state`],columns:[],migrate:(e,t,n)=>migrateCronDefaultStoreIdentity(e,{previousVersion:t,legacyDefaultStoreKey:n.legacyCronDefaultStoreKey??resolveCronIdentityMigrationDefaultStoreKey(n.env)}),applied:`Introduced durable default cron partition selection (v34)`};function migrateCronDefaultStoreIdentity(e,t){if(t.previousVersion>=34||readBindingRow(e,t.sourceTables))return!1;let n=t.fresh?t.legacyDefaultStoreKey:void 0;if(!t.fresh){if(af.some(([n])=>(t.sourceTables?.has(n)??tableExists(e,n))&&executeSqliteQueryTakeFirstSync(e,getNodeSqliteKysely(e).selectFrom(n).select(`store_key`).where(`store_key`,`=`,t.legacyDefaultStoreKey).limit(1))))n=t.legacyDefaultStoreKey;else{let r=readCronStorePartitionInventoryInDatabase(e,t.sourceTables);n=resolveUnboundCronDefaultStoreKey(r,t.legacyDefaultStoreKey)??(r.length===1?r[0]?.storeKey:void 0)}}return n!==void 0&&(executeSqliteQuerySync(e,getNodeSqliteKysely(e).insertInto(`config_machine_state`).values({state_key:rf,value_json:JSON.stringify(n),updated_at_ms:t.nowMs??Date.now()})),!0)}function captureOpenClawStateReadContextWithAdmission(e,t,n,r){let i=captureOpenClawStateSchemaReadAdmission(e),a=t(e,r),o=getGatewayServiceInstallation(),s=a.captureIntegrity?.(),c=a.assertCurrent,l=a,runInCapturedSchemaScope;if(i){let e=S.snapshot();l={databasePath:a.databasePath,coordinationKey:a.coordinationKey,get identity(){return a.identity},captureIntegrity:a.captureIntegrity,assertCurrent(){a.assertCurrent(),i.assertCurrent()}},runInCapturedSchemaScope=t=>e(()=>(l.assertCurrent(),t()))}return{databaseEngineSelection:Le(),maintenanceScope:hn(),admission:l,assertPublicationCurrent:c,existingSchemaPath:i?.path,gatewayServiceInstallation:o&&n(o.databasePath)?.key===a.identity.key?o:void 0,stateIntegrity:s,runInCapturedSchemaScope,artifactPreservingReads:Zn(`agent`,e)||void 0,liveStateReads:Rt()||void 0}}function captureOpenClawStateReadWorkerContextWithAdmission(e,t,n){let r=e.env??process.env,i=process.platform===`win32`?cloneEnvWithPlatformSemantics(r):r,a={OPENCLAW_STATE_DIR:m(i),...isGatewayExternallySupervised(i)?{OPENCLAW_SUPERVISOR_MODE:`external`}:{}};return{...captureOpenClawStateReadContextWithAdmission(e.path??yn(a),t,n),environment:a}}function captureOpenClawStateWorkerContextWithAdmission(e,t,n){let r=captureOpenClawStateReadWorkerContextWithAdmission(e,t,n);return{...r,initializationCronDefaultStoreKey:resolveLegacyCronDefaultStoreKey(e.env??process.env),initializationEnvironment:sr([e.env??process.env,{OPENCLAW_STATE_DIR:void 0,OPENCLAW_SUPERVISOR_MODE:void 0},r.environment]),...e.initializationAgentPaths?{initializationAgentPaths:e.initializationAgentPaths.map(e=>x.resolve(e))}:{}}}function createStateDatabaseWalOwner({cachedDatabases:e,retainedDatabaseHandles:t,databaseIdentities:n,asyncResources:r},i,a){return{ownRetirement(e,t){let n={admission:{identity:a(e)},close:t},i=r.register(n);return wn(e.db)?.own(n,`shared-references`,()=>n.close()),i},async stop(r,i){let a=/* @__PURE__ */ new Set([...t.values(),...e.values()]);await Promise.all([...a].filter(e=>r===void 0||e.path===r||i!==void 0&&n.get(e.db)?.key===i.key).flatMap(({walMaintenance:e})=>e?[e.stop()]:[]))},register(t,n,a,o){if(!vr||v(t.db))return;let s=captureOpenClawStateWorkerContextWithAdmission({path:t.path,env:o},()=>a,r.knownIdentity),c=new AbortController,l,cancel=()=>{if(c.abort(),!l)d();else return l.then(()=>void 0,()=>void 0)},u={admission:{identity:n},async close(){cancel(),await t.walMaintenance.stop(),d()}},d=r.register(u),run=async r=>{let a=wn(t.db),o={...s,maintenanceScope:a},assertCurrent=()=>{if(c.signal.throwIfAborted(),o.admission.assertCurrent(),a?.assertAdmission(),wn(t.db)!==a||e.get(t.path)!==t||!t.db.isOpen)throw new Pt(`Shared-state WAL maintenance owner changed`)},l,u=!1;try{assertCurrent(),l=i(t);let{runOpenClawStateWorkerOperation:e}=await import(`./session-transcript-reconcile.worker-openclaw-state-worker-store-yB8Jm_pu.mjs`);return assertCurrent(),await e(o,e=>e.execute({type:`database.walMaintenance`,input:r},{signal:c.signal}),{existingOnly:!0,assertCurrent,createAdmission:()=>({nativeLocations:[t.path,n.canonicalPath],databaseIdentity:{databasePath:t.path,key:n.key,birthtime:n.birthtime},admission:dt((e,t)=>{if(assertCurrent(),!t())throw new Pt(`Shared-state WAL maintenance authority expired`);u=!0})})})}catch(e){if(!u&&(zn(e)||c.signal.aborted&&pe(e)))return;throw e}finally{l?.()}};registerSqliteWalWorkerMaintenance(t.db,e=>{if(c.signal.aborted)return Promise.resolve(void 0);let t=run(e);return l=t,t.finally(()=>{l===t&&(l=void 0),c.signal.aborted&&d()})},cancel)},readHealth(){let t=e.get(x.resolve(yn()));return t?.db.isOpen?t.walMaintenance.health:void 0}}}const sf=s(Symbol.for(`openclaw.stateNativeIdentities`),()=>/* @__PURE__ */ new WeakMap);function readTrackedStateDatabaseIdentity(e){return sf.get(Te(e))}function openTrackedStateDatabase(e,t){let n=openTrackedStateDatabaseResult(e,t);if(n.status===`unavailable`)throw n.error;return n.database}function openTrackedStateDatabaseResult(e,t){assertStateDatabaseAccessAllowed(e);try{t?.expectedIdentity!==void 0&&qe(e,t.expectedIdentity);let n=t?.existingOnly||t?.expectedIdentity!==void 0?dn(e):e,r=t?.readOnly?{readOnly:!0,timeout:t.timeout}:{enableForeignKeyConstraints:t?.enableForeignKeyConstraints},i=Me(e),a=ye(()=>Xt(n,r));try{assertStateDatabaseAccessAllowed(e),i.key.startsWith(`file:`)&&qe(e,i.key,i.birthtime);let t=i.key.startsWith(`file:`)?i:Me(e);if(t.key.startsWith(`file:`)){sf.set(a,t);let e=It(a,()=>{sf.delete(a),e()})}}catch(e){throw a.close(),e}return{status:`available`,database:a}}catch(e){return{status:`unavailable`,error:e}}}function closeTrackedStateDatabase(e){e.isOpen&&e.close()}function closeStateDatabaseHandle(e,t){try{var n=tr();let r=[];if(v(e.db)){for(let t of[e.db,e.db.anchor]){if(t===e.db.anchor&&e.db.isOpen)break;try{t.isOpen&&t.close()}catch(e){r.push(e)}}let t=e.db.isOpen||e.db.anchor.isOpen;if(!t)try{e.afterClose?.()}catch(e){r.push(e),t=!0}return{errors:r,cleanupPending:t}}let i=n.u(Qe(e.db)),a=isSqliteWalWorkerMaintained(e.db),o=e.walMaintenance?.health?.state===`error`,s=!1;try{e.db.isOpen&&!a&&ln(e.db,0),s=e.walMaintenance?.close(t)===!0&&t?.checkpointMode!==`PASSIVE`}catch(e){r.push(e)}try{Bt(e.db)}catch(e){r.push(e)}try{closeTrackedStateDatabase(e.db)}catch(e){r.push(e)}let c=!1;if(!e.db.isOpen)try{e.afterClose?.()}catch(e){r.push(e),c=!0}return r.length===0&&!c&&t?.checkpointMode!==`PASSIVE`&&(s||a&&!o)&&i.publish(),{errors:r,cleanupPending:c}}catch(e){n.e=e}finally{n.d()}}const cf=/* @__PURE__ */ new WeakMap;function getMaintenanceSqliteTableChecks(e){let t=hn();if(!t?.ownsSchemaMaintenance||t.sqliteIntegrityCheck!==`quick`)return;let n=Lt(e),r=e.location();if(n===void 0||!r||ct(e)===void 0)return;let i=Et(r);if(i===void 0)return;let a=cf.get(t);if(a||(a={committed:/* @__PURE__ */ new Map,transactions:/* @__PURE__ */ new WeakMap},cf.set(t,a)),!e.isTransaction){let e=a.committed.get(i);return e||(e=/* @__PURE__ */ new Set,a.committed.set(i,e)),e}let o=`${i}:${n}`,s=a.transactions.get(e);if(s)s.token!==o&&(s.token=o,s.tables.clear());else{let n=/* @__PURE__ */ new Set;s={token:o,tables:n},a.transactions.set(e,s),t.own(s,`shared-resources`,kn(e,()=>n.clear()))}return s.tables}var SqliteRepairableForeignKeyError=class extends Error{constructor(e,t){super(`SQLite foreign_key_check failed for ${e}: repairable task_delivery_state.task_id references task_runs.task_id cascade-owned orphans (${t} rows). Run openclaw doctor --fix to migrate this legacy state before retrying.`),this.name=`SqliteRepairableForeignKeyError`,this.repair={kind:`task-delivery-orphans`,relation:`task_delivery_state.task_id`,parentTable:`task_runs`,orphanCount:t}}};function isTerminalSqliteIntegrityError(e){return e.name===`SqliteIntegrityError`?!e.cause||it(e.cause):!1}function assertSqliteIntegrity(e,t,n={}){if(n.check===`quick`&&n.schemaOnly)return runSqliteCheck(e,t,`quick_check`,`schema_meta`),{integrityCheck:`ok`};let r=n.check===`quick`?`quick_check`:`integrity_check`,i=!1;try{runSqliteCheck(e,t,r,void 0,n.allFindings||n.ftsSchemas!==void 0)}catch(a){if(!n.ftsSchemas||!(a instanceof SqliteIntegrityError)||!a.findings||!classifySqliteFtsIntegrityFindings(e,a.findings,n.ftsSchemas))throw a;if(r===`quick_check`)return assertSqliteIntegrity(e,t,{check:`full`,ftsSchemas:n.ftsSchemas});i=!0}if(r===`quick_check`&&n.tables?.length){let r=new Set(on(e).filter(e=>e.type===`table`).map(e=>e.name));for(let i of n.tables)r.has(i)&&assertSqliteTableIntegrity(e,t,i)}return runSqliteForeignKeyCheck(e,t),r===`integrity_check`&&!i&&yt(e),i?{integrityCheck:`ok`,staleFts:!0}:{integrityCheck:`ok`}}function classifySqliteFtsIntegrityFindings(e,t,n){let r=/* @__PURE__ */ new Set;for(let e of t){if(e===`ok`)continue;let t=typeof e==`string`?/^malformed inverted index for FTS5 table main\.([A-Za-z_][A-Za-z0-9_]*)$/u.exec(e):null;if(!t?.[1])return;r.add(t[1])}if(r.size===0)return;let i=/* @__PURE__ */ new Map;for(let e of n)for(let t of e.matchAll(/CREATE VIRTUAL TABLE (?:IF NOT EXISTS )?([A-Za-z_][A-Za-z0-9_]*) USING fts5\s*\(/gu)){let n=t[1],r=Ze(e,t.index+t[0].length-1),a=i.get(n)??/* @__PURE__ */ new Set;a.add(Be(e.slice(t.index,r+1))),i.set(n,a)}let a=on(e).filter(e=>e.type===`table`);for(let e of r){let t=a.find(t=>t.name===e)?.sql;if(typeof t!=`string`||!i.get(e)?.has(Be(t)))return}return[...r].toSorted()}function assertSqliteTableIntegrity(e,t,n){let r=getMaintenanceSqliteTableChecks(e);r?.has(n)||(runSqliteCheck(e,`${t} table ${n}`,`integrity_check`,n),r?.add(n))}function readSqliteCheckFindings(e,t,n,r=!1){let i=n?`('${n.replaceAll(`'`,`''`)}')`:r?`(2147483647)`:``;return e.prepare(`PRAGMA ${t}${i};`).all().map(e=>e[t]??Object.values(e)[0])}function runSqliteCheck(e,t,n,r,i=!1){let a;try{a=readSqliteCheckFindings(e,n,r,i)}catch(e){throw new SqliteIntegrityError(`SQLite ${n} failed for ${t}: ${e instanceof Error?e.message:String(e)}`,e)}if(a.length===1&&a[0]===`ok`)return`ok`;throw new SqliteIntegrityError(`SQLite ${n} failed for ${t}: ${a.map(e=>String(e)).join(`; `)||`no result`}`,void 0,a)}function runSqliteForeignKeyCheck(e,t){let n=0,r=!0,i,a=[];try{let t=e.prepare(`PRAGMA foreign_key_check;`);t.setReadBigInts(!0);for(let o of t.iterate())n+=1,retainSortedForeignKeyViolation(a,o),r&&(o.table===`task_delivery_state`&&o.parent===`task_runs`?(i??=readTaskDeliveryCascadeForeignKeyId(e),r=o.fkid===i):r=!1)}catch(e){throw new SqliteIntegrityError(`SQLite foreign_key_check failed for ${t}: ${e instanceof Error?e.message:String(e)}`,e)}if(a.length===0)return;if(r)throw new SqliteRepairableForeignKeyError(t,n);let o=a.map(formatSqliteForeignKeyViolation);throw n>5&&o.push(`additional violations omitted`),new SqliteIntegrityError(`SQLite foreign_key_check failed for ${t}: ${o.join(`; `)}`)}function readTaskDeliveryCascadeForeignKeyId(e){let t=e.prepare(`PRAGMA foreign_key_list(task_delivery_state);`);t.setReadBigInts(!0);let n=t.all(),r=n.find(e=>e.table===`task_runs`&&e.from===`task_id`&&e.to===`task_id`&&e.on_delete===`CASCADE`);return r&&typeof r.id==`bigint`&&n.filter(e=>e.id===r.id).length===1?r.id:void 0}var SqliteIntegrityError=class extends Error{constructor(e,t,n){super(t===void 0?`${e}. Stop the Gateway, run "openclaw doctor --fix" to inspect and repair this database, and restart. Only if Doctor still cannot repair the offline database, preserve the database and WAL and restore a verified backup.`:e,t===void 0?void 0:{cause:t}),this.findings=n,this.name=`SqliteIntegrityError`}};function retainSortedForeignKeyViolation(e,t){e.push(t),e.sort(compareSqliteForeignKeyViolations),e.length>5&&e.pop()}function compareSqliteForeignKeyViolations(e,t){let n=Buffer.compare(Buffer.from(e.table),Buffer.from(t.table));if(n!==0)return n;if(e.rowid===null||t.rowid===null){if(e.rowid!==t.rowid)return e.rowid===null?-1:1}else if(e.rowid!==t.rowid)return e.rowid<t.rowid?-1:1;let r=Buffer.compare(Buffer.from(e.parent),Buffer.from(t.parent));return r===0?e.fkid===t.fkid?0:e.fkid<t.fkid?-1:1:r}function formatSqliteForeignKeyViolation(e){let t=e.rowid===null?`row without rowid`:`row ${e.rowid.toString()}`;return`${e.table} ${t} references ${e.parent} (foreign key ${e.fkid.toString()})`}const lf=s(Symbol.for(`openclaw.stateIntegrityBindings`),()=>/* @__PURE__ */ new WeakMap),uf={name:`state.integrity`,lifetime:`process`,read:e=>e===!0||void 0};function hasStateDatabaseIntegrityAdmission(e){return!!(getStateRuntimeSchemaAdmission(e)||Fe(e,uf))}function assertStateDatabaseIntegrityOnce(e,t){hasStateDatabaseIntegrityAdmission(e)||(assertSqliteIntegrity(e,t),Ye(e,uf,!0))}function invalidate(e){let t=Atomics.load(e,0);for(;t>=0n;){let n=Atomics.compareExchange(e,0,t,t+1n);if(n===t)return;t=n}}function invalidateOpenClawStateRuntimeIntegrity(e){ot(e);let t=lf.get(e);t&&(invalidate(new BigInt64Array(t.revision)),invalidate(new BigInt64Array(t.lifetimeRevision)))}function bind(e,t){if(lf.get(e)?.revision===t.revision)return;lf.get(e)?.release();let n=new BigInt64Array(t.revision),r=kn(e,()=>invalidate(n)),release=()=>{r(),i()},i=It(e,e=>{e===`replace`&&(invalidate(n),invalidate(new BigInt64Array(t.lifetime.revision))),release()});lf.set(e,{revision:t.revision,lifetimeRevision:t.lifetime.revision,release})}function assertOpenClawStateRuntimeIntegrity(e,t,n,r,i=`verify`){let a=r&&readTrackedStateDatabaseIdentity(e);if(!r||!a||!a.key.startsWith(`file:`)||a.key!==r.identity.key||a.birthtime!==r.identity.birthtime){if(i===`require-proof`)throw Error(`Shared-state reader requires current worker integrity proof`);assertStateDatabaseIntegrityOnce(e,t);return}bind(e,r);let o=new BigInt64Array(r.revision),s=new BigInt64Array(r.proof),c=BigInt.asIntN(64,BigInt(n.userVersion>>>0)<<32n|BigInt(n.schemaVersion>>>0)),l=Atomics.load(s,0);if(Atomics.load(o,0)===r.epoch&&l!==-1n){if(l===c&&Atomics.load(o,0)===r.epoch&&hasStateDatabaseIntegrityAdmission(e))return;invalidate(o)}if(i===`require-proof`)throw Error(`Shared-state reader requires current worker integrity proof`);assertStateDatabaseIntegrityOnce(e,t);let publish=()=>{Atomics.load(o,0)===r.epoch&&Atomics.store(s,0,c)};return()=>{e.isTransaction?bt(e,{commit:publish}):publish()}}function retainSqliteDatabaseRemovalExclusion(e,t){if(!xr(e))return;let n=Xt(dn(e)),close=()=>{if(!n.isOpen)return;let e=[];try{n.isTransaction&&n.exec(`ROLLBACK`)}catch(t){e.push(t)}try{n.close()}catch(t){e.push(t)}At(e,`SQLite state removal exclusion cleanup failed.`)};try{t.own(n,`shared-handles`,close),n.exec(`PRAGMA busy_timeout = 0; PRAGMA locking_mode = EXCLUSIVE; BEGIN EXCLUSIVE;`)}catch(e){try{close()}catch(t){throw He([e,t],`SQLite state removal admission and cleanup both failed.`,e)}if(jt(e))throw Error(`Cannot remove OpenClaw state directory while another SQLite connection is active`,{cause:e});let t=mt(e);if(t!==11&&t!==26)throw e;return}process.platform===`win32`&&close()}function createOpenClawStateSnapshotOwnerRegistry(){let e=/* @__PURE__ */ new WeakMap;return{register(t,n){v(t.db)||e.set(t.db,registerLiveSqliteSnapshotOwner({database:t.db,databasePath:t.path,assertCurrent:()=>{if(n()!==t||!t.db.isOpen)throw Error(`OpenClaw state snapshot owner is no longer current`)}}))},release(t){v(t)||(e.get(t)?.(),e.delete(t))}}}const df=s(Symbol.for(`openclaw.stateSnapshotOwners`),createOpenClawStateSnapshotOwnerRegistry);var ff=/* @__PURE__ */ __exportAll({assertPublishedOpenClawStateDatabaseLifecycle:()=>assertPublishedOpenClawStateDatabaseLifecycle,borrowOpenClawStateDatabaseForAsyncRead:()=>Of,captureOpenClawStateDatabaseReadAdmission:()=>jf,captureOpenClawStateIntegrityAdmission:()=>Mf,clearOpenClawStateDatabaseOpenFailure:()=>clearOpenClawStateDatabaseOpenFailure,closeOpenClawStateDatabase:()=>closeOpenClawStateDatabase,closeOpenClawStateDatabaseAsync:()=>closeOpenClawStateDatabaseAsync,closeOpenClawStateDatabaseByPath:()=>closeOpenClawStateDatabaseByPath,closeOpenClawStateDatabaseByPathAsync:()=>closeOpenClawStateDatabaseByPathAsync,closeOpenClawStateDatabaseForTest:()=>closeOpenClawStateDatabaseForTest,closeOpenClawStateDatabaseWorkersByPathAsync:()=>closeOpenClawStateDatabaseWorkersByPathAsync,getOpenClawStateDatabaseTerminalFailureAsync:()=>getOpenClawStateDatabaseTerminalFailureAsync,isOpenClawStateDatabaseOpen:()=>isOpenClawStateDatabaseOpen,joinOpenClawStateDatabaseBorrowers:()=>joinOpenClawStateDatabaseBorrowers,openClawStateDatabaseCache:()=>Nf,prepareOpenClawStateCachedRead:()=>prepareOpenClawStateCachedRead,prepareOpenClawStateDatabaseRemoval:()=>prepareOpenClawStateDatabaseRemoval,publishOpenClawStateDatabaseWorkerAdmission:()=>publishOpenClawStateDatabaseWorkerAdmission,readOpenClawStateWalHealth:()=>Cf,recordOpenClawStateDatabaseOpenFailure:()=>recordOpenClawStateDatabaseOpenFailure,registerOpenClawStateDatabaseAsyncResource:()=>Af,registerOpenClawStateDatabaseLifecycleListener:()=>registerOpenClawStateDatabaseLifecycleListener,registerOpenClawStatePathAsyncResource:()=>registerOpenClawStatePathAsyncResource,registerOpenClawStatePathCacheInvalidation:()=>registerOpenClawStatePathCacheInvalidation,releaseOpenClawStateDatabaseCustody:()=>releaseOpenClawStateDatabaseCustody,requireOpenClawStateDatabaseIdentity:()=>requireOpenClawStateDatabaseIdentity,retainOpenClawStateDatabase:()=>Df,retainOpenClawStateDatabaseForIdle:()=>xf,retainOpenClawStateDatabaseForIndependentRead:()=>kf});const pf=s(En,()=>({cachedDatabases:/* @__PURE__ */ new Map,retainedDatabaseHandles:/* @__PURE__ */ new Map,idleTimers:/* @__PURE__ */ new WeakMap,idleReferences:/* @__PURE__ */ new WeakMap,unregisterRetainedExitClose:void 0,databaseIdentities:/* @__PURE__ */ new WeakMap,borrowers:/* @__PURE__ */ new WeakMap,databaseLifecycleListeners:/* @__PURE__ */ new Set,terminalOpenLatch:createSqliteTerminalOpenLatch({closeByPath:(e,t)=>Ef.closeTerminalFailure(e,t)}),asyncResources:xn()}),()=>closeOpenClawStateDatabaseAsync(),`shared-state`),{cachedDatabases:Z,retainedDatabaseHandles:mf,idleTimers:hf,idleReferences:gf,databaseIdentities:_f,borrowers:Q,databaseLifecycleListeners:vf,terminalOpenLatch:yf,asyncResources:$}=pf,{touch:bf,retain:xf}=createStateDatabaseIdleRetirement(pf,retireOpenClawStateDatabaseHandle),{register:Sf,readHealth:Cf,ownRetirement:wf,stop:Tf}=createStateDatabaseWalOwner(pf,xf,requireOpenClawStateDatabaseIdentity);function notifyOpenClawStateDatabaseLifecycle(e){let t=e.kind===`open-error`?{...e,identity:e.identity??$.knownIdentity(e.path)}:e;for(let e of vf)e(t)}function notifyOpenClawStateDatabaseClosed(e){notifyOpenClawStateDatabaseLifecycle({kind:`closed`,path:e.path,identity:requireOpenClawStateDatabaseIdentity(e)})}function requireOpenClawStateDatabaseIdentity(e){let t=_f.get(e.db);if(!t)throw Error(`Published shared-state owner has no recorded database identity`);return t}const Ef=createStateDatabaseCacheAdmission({cachedDatabases:Z,evict:evictCachedOpenClawStateDatabase,invalidate:e=>$.invalidate(e),notifyTerminalFailure:(e,t)=>notifyOpenClawStateDatabaseLifecycle({kind:`terminal-failure`,path:e,error:t,identity:$.knownIdentity(e)})});function registerOpenClawStateDatabaseLifecycleListener(e){vf.add(e);for(let t of Z.values())t.db.isOpen&&e({kind:`opened`,database:t,identity:requireOpenClawStateDatabaseIdentity(t)});return()=>vf.delete(e)}function registerOpenClawStatePathCacheInvalidation(e){return registerOpenClawStateDatabaseLifecycleListener(t=>{if(t.kind!==`opened`)for(let[n,r]of e)r.path===(t.identity?.canonicalPath??t.path)&&e.delete(n)})}function retainStateDatabaseClose(e){mf.set(e.db,e),pf.unregisterRetainedExitClose??=se(closeOpenClawStateDatabase)}function ownMaintenanceStateDatabaseHandle(e){hn()?.own(e.db,`shared-handles`,async()=>{let t=hn();t&&Yn(e.db,t)&&(Z.get(e.path)===e||mf.get(e.db)===e)&&(await e.walMaintenance?.stop(),Yn(e.db,t)&&(Z.get(e.path)===e||mf.get(e.db)===e)&&retireOpenClawStateDatabaseHandle(e,!1))})}function closeUnpublishedOpenClawStateDatabaseHandle(e){let t=closeOpenClawStateDatabaseHandle(e);return mf.get(e.db)===e&&ownMaintenanceStateDatabaseHandle(e),t}const{retain:Df,borrowForRead:Of,retainForIndependentRead:kf}=createStateDatabaseRetainer(pf,{assertOpen(e,t,n){assertOpenClawStateDatabaseOpenAllowed(e,t,n),assertExistingOpenClawStateSchemaCacheAdmission(e,pf)},capture:e=>$.capture(e),retire:retireOpenClawStateDatabaseHandle,retainFailed:retainStateDatabaseClose,ownRetirement:wf,touch:bf});function closeOpenClawStateDatabaseHandle(e,t){clearTimeout(hf.get(e.db)),hf.delete(e.db);try{assertStateDatabaseBorrowersReleased(Q.get(e.db),e.path)}catch(n){let r=Q.get(e.db);return r&&(r.retiring=!0,r.retirement={ordinary:!0,isCurrent:()=>!0,retire:()=>{At(closeOpenClawStateDatabaseHandle(e,t),`OpenClaw state database cleanup failed for ${e.path}.`),r.cleanupComplete=!0,Q.delete(e.db)}}),retainStateDatabaseClose(e),[n]}gf.delete(e.db),df.release(e.db);let{errors:n,cleanupPending:r}=closeStateDatabaseHandle(e,t);return e.db.isOpen||r?retainStateDatabaseClose(e):mf.delete(e.db),Z.get(e.path)?.db===e.db&&Z.delete(e.path),mf.size===0&&(pf.unregisterRetainedExitClose?.(),pf.unregisterRetainedExitClose=void 0),n}function evictCachedOpenClawStateDatabase(e){return v(e.db)||invalidateOpenClawStateRuntimeIntegrity(e.db),Z.get(e.path)===e&&($.invalidate(e.path),Z.delete(e.path),notifyOpenClawStateDatabaseClosed(e),closeOpenClawStateDatabaseHandle(e,{checkpointMode:`PASSIVE`}),!0)}function evictOpenClawStateDatabaseAfterCorruption(e,t){return it(t)&&evictCachedOpenClawStateDatabase(e)}function publishOpenClawStateDatabase(e,t){let{db:n,path:r}=e,{identity:i,admission:a}=$.publish(r);return _f.set(n,readTrackedStateDatabaseIdentity(n)??i),Z.set(r,e),Sf(e,i,a,t),bf(e),df.register(e,()=>Z.get(r)),ownMaintenanceStateDatabaseHandle(e),notifyOpenClawStateDatabaseLifecycle({kind:`opened`,database:e,identity:i}),v(n)||$t(n,t=>{!n.isTransaction&&it(t)&&evictCachedOpenClawStateDatabase(e)}),yf.clear(r),e}function getCachedOpenClawStateDatabase(e,t){let n=y({path:e}),r=yf.get(n);if(r)throw r;let i=readCachedOpenClawStateDatabase(n,t?.readOnly===!0);return i&&bf(i),i}function readCachedOpenClawStateDatabase(e,t){let n=hn();t?n?.assertReadAdmission():n?.assertAdmission(),assertExistingOpenClawStateSchemaCacheAdmission(e,pf);let r=Z.get(e);if(r&&Q.get(r.db)?.retiring)throw Error(`OpenClaw state database native borrower cleanup is pending: ${e}`);return r}function prepareOpenClawStateCachedRead(e){let t=y({path:e});getCachedOpenClawStateDatabase(t,{readOnly:!0});let n=$.capture(t);return()=>(n.assertCurrent(),readCachedOpenClawStateDatabase(t,!0))}function withCachedOpenClawStateDatabase(e,t,n){let r=getCachedOpenClawStateDatabase(e,t);return r&&Ef.read(r,n)}function getOpenClawStateDatabaseIfOpenAtPath(e){let t=getCachedOpenClawStateDatabase(e);return _n(t?.db.isOpen?t.db:void 0),t?.db.isOpen?t:void 0}function closeStaleCachedOpenClawStateDatabase(e){if(Z.get(e.path)!==e)return;$.invalidate(e.path);let t=closeOpenClawStateDatabaseHandle(e);notifyOpenClawStateDatabaseClosed(e),At(t,`Stale OpenClaw state database cleanup failed for ${e.path}.`)}function recordOpenClawStateDatabaseOpenFailure(e,t){yf.record(y({path:e}),t)}function clearOpenClawStateDatabaseOpenFailure(e){let t=y({path:e});yf.clear(t),$.invalidate(t),notifyOpenClawStateDatabaseLifecycle({kind:`failure-cleared`,path:t,identity:$.knownIdentity(t)})}async function getOpenClawStateDatabaseTerminalFailureAsync(e,t){return e.admission.assertCurrent(),t?.throwIfAborted(),yf.get(e.admission.databasePath)}function assertOpenClawStateDatabaseOpenAllowed(e,t,n){let r=y({path:e});t===`cached-read`&&n?n.assertReadAllowed():(t===`cached-read`?assertStateDatabaseReadAllowed:assertStateDatabaseAccessAllowed)(e);let{identity:i}=$.capture(r),a=yf.get(r);if(a)throw a;for(let t of mf.values())if(Q.get(t.db)?.retiring&&(t.path===r||_f.get(t.db)?.key===i.key))throw Error(`OpenClaw state database native borrower cleanup is pending: ${e}`)}function recordOpenClawStateDatabaseLifecycleOpenError(e,t){notifyOpenClawStateDatabaseLifecycle({kind:`open-error`,path:y({path:e}),error:t})}function assertOpenClawStateDatabaseFreshOpenAllowedAtPath(e,t,n,r){assertOpenClawStateDatabaseOpenAllowed(e);let i;try{i=readOpenClawDatabaseQuarantineFailure(`state`,e,{env:t,refreshIdentity:r})}catch(e){if(!(e instanceof In))throw e;n?.(e)}if(i?.cause instanceof In&&n?.(i.cause),i)throw Ef.closeTerminalFailure(e,i),i}function retireOpenClawStateDatabaseHandle(e,t=!0,n){assertStateDatabaseBorrowersReleased(Q.get(e.db),e.path);let r=Q.get(e.db);try{let r=Z.get(e.path)?.db===e.db;t&&$.invalidate(e.path);let i=closeOpenClawStateDatabaseHandle(e,n);if(r&&t)try{notifyOpenClawStateDatabaseClosed(e)}catch(e){i.push(e)}At(i,`OpenClaw state database cleanup failed for ${e.path}.`)}catch(t){throw r&&retainStateDatabaseClose(e),t}r&&(r.cleanupComplete=!0,Q.delete(e.db))}function stateDatabaseHandlesAt(e,t){return[.../* @__PURE__ */ new Set([...mf.values(),...Z.values()])].filter(n=>e===void 0||n.path===e||t!==void 0&&_f.get(n.db)?.key===t.key)}function retireOpenClawStateDatabaseHandles(e,t,n){let r=stateDatabaseHandlesAt(e,n),i=[];for(let e of r)try{retireOpenClawStateDatabaseHandle(e,!0,t)}catch(e){i.push(e)}return At(i,`OpenClaw state database cleanup failed.`),r.length>0}function closeOpenClawStateDatabaseByPath(e,t){return retireOpenClawStateDatabaseHandles(y({path:e}),t,$.identity(e))}function sealOpenClawStateDatabaseByPath(e){let t=y({path:e}),n=$.identity(e);return!stateDatabaseHandlesAt(t,n).some(e=>Q.get(e.db)?.references.size)&&retireOpenClawStateDatabaseHandles(t,void 0,n)}function closeOpenClawStateDatabase(e){retireOpenClawStateDatabaseHandles(void 0,e)}const Af=$.register;function registerOpenClawStatePathAsyncResource(e,t){return Af({close(n){return!n||n.key===e.identity.key||n.canonicalPath===e.identity.canonicalPath?t():Promise.resolve()}})}const jf=$.capture,Mf=$.integrity;function publishOpenClawStateDatabaseWorkerAdmission(e,t){t&&e.assertCurrent(),$.publish(e.databasePath,t),e.assertCurrent(),Ge(e.databasePath,e.identity)}function closeOpenClawStateDatabaseByPathAsync(e,t){let n=y({path:e});return $.close(n,async e=>(await Tf(n,e),retireOpenClawStateDatabaseHandles(n,t,e)))}function closeOpenClawStateDatabaseWorkersByPathAsync(e){return $.close(y({path:e}),()=>!1)}async function closeOpenClawStateDatabaseAsync(e){await $.close(void 0,async()=>(await Tf(),retireOpenClawStateDatabaseHandles(void 0,e)))}async function joinOpenClawStateDatabaseBorrowers(){await Promise.all(stateDatabaseHandlesAt().map(e=>joinStateDatabaseBorrowersReleased(Q.get(e.db),e.path)))}async function releaseOpenClawStateDatabaseCustody(){await closeOpenClawStateDatabaseAsync(),wt()}function isOpenClawStateDatabaseOpen(e){return e===void 0?Array.from(Z.values()).some(e=>e.db.isOpen):Z.get(y({path:e}))?.db.isOpen===!0}function closeOpenClawStateDatabaseForTest(){closeOpenClawStateDatabase(),yf.clearAll()}function assertPublishedOpenClawStateDatabaseLifecycle(){if(f(En)!==pf)throw Error(`OpenClaw state database lifecycle is retired; its owners cannot serve the published lifecycle`)}const Nf={assertOpenClawStateDatabaseFreshOpenAllowedAtPath,assertOpenClawStateDatabaseOpenAllowed,clearOpenClawStateDatabaseOpenFailure,closeOpenClawStateDatabase,closeOpenClawStateDatabaseByPath,sealOpenClawStateDatabaseByPath,closeOpenClawStateDatabaseForTest,closeOpenClawStateDatabaseHandle,closeUnpublishedOpenClawStateDatabaseHandle,closeStaleCachedOpenClawStateDatabase,evictCachedOpenClawStateDatabase,evictOpenClawStateDatabaseAfterCorruption,getCachedOpenClawStateDatabase,peekOpenClawStateDatabaseConnection:e=>Z.get(y({path:e}))?.db,withCachedOpenClawStateDatabase,getOpenClawStateDatabaseRecordedFailure:yf.peek,getOpenClawStateDatabaseIfOpenAtPath,getKnownOpenClawStateDatabaseIdentity:$.knownIdentity,isOpenClawStateDatabaseOpen,isOpenClawStateDatabaseSchemaReady:e=>Z.get(e.path)===e&&e.db.isOpen,publishOpenClawStateDatabase,recordOpenClawStateDatabaseOpenFailure,recordOpenClawStateDatabaseLifecycleOpenError,async reconcileFailedWorkerAdmission(e){await $.retireChangedAdmission(e),e.assertCurrent()},touchStateDatabase:bf};async function prepareOpenClawStateDatabaseRemoval(e,t){let n=y({path:e}),r=hn();if(!r?.ownsSchemaMaintenance)throw Error(`State removal requires the installation's maintenance owner`);r.assertAdmission();let i=$.holdExclusion(n);try{await closeOpenClawStateDatabaseByPathAsync(n),r.assertOwnerCurrent(),retainSqliteDatabaseRemovalExclusion(n,r),r.assertOwnerCurrent()}catch(e){throw i(),e}let a=!0;return{assertCurrent(){if(!a)throw Error(`State removal admission has been released`);t()},release(){a&&(a=!1,i())}}}export{cancelSqliteWalWriteAdmission as $,getStateSchemaVersionAdmission as $t,of as A,createSqliteQueryCache as An,parseGatewayLockPayload as At,jsonArrayValue as B,expressionBuilder as Bn,literal as Bt,closeTrackedStateDatabase as C,isSqliteSchemaMismatchError as Cn,classifyGatewayLockProcessNamespace as Ct,captureOpenClawStateReadWorkerContextWithAdmission as D,quarantineOrphanedSqliteSidecars as Dn,Ed as Dt,readTrackedStateDatabaseIdentity as E,ds as En,GatewayLockNamespaceError as Et,sqliteWorkerRequestBytes as F,prepareSqliteQuerySync as Fn,_null as Ft,jsonRemovePaths as G,getOldGenerationAfterGcBytes as Gn,record as Gt,jsonObjectValue as H,getDatabaseProcessRole as Hn,never as Ht,assertOpenClawStateSchemaRepairAllowed as I,prepareSqliteQueryTakeFirstSync as In,array as It,jsonValid as J,unknown as Jt,jsonSetPath as K,observeGcSamples as Kn,string as Kt,getExistingOpenClawStateSchemaPath as L,parseNodeReleaseVersion as Ln,boolean as Lt,captureSqliteWorkerWalMaintenanceSuspension as M,executeSqliteQueryTakeFirstSync as Mn,predatesCurrentBoot as Mt,getSqliteWorkerExistingDatabaseIdentity as N,getNodeSqliteKysely as Nn,uu as Nt,migrateCronDefaultStoreIdentity as O,resolveSqliteDatabaseFilePaths as On,Td as Ot,getSqliteWorkerStateIntegrityAdmission as P,iterateSqliteQuerySync as Pn,_enum as Pt,cloneEnvWithPlatformSemantics as Q,getStateRuntimeSchemaAdmission as Qt,isExistingOpenClawStateSchema as R,SqliteQueryCompiler as Rn,custom as Rt,isTerminalSqliteIntegrityError as S,createSqliteSchemaIssue as Sn,withStateDatabaseColdAdmission as St,openTrackedStateDatabaseResult as T,throwSqliteSchemaMismatches as Tn,applyPrivateModeSync as Tt,jsonPathValue as U,withEngineStoreAdmission as Un,number as Ut,jsonNativeFieldsValid as V,assertEngineStoreExecutionAllowed as Vn,looseObject as Vt,jsonPickObject as W,flushGcSamples as Wn,object as Wt,getGatewayServiceInstallation as X,adoptPeerPublishedStateSchemaVersion as Xt,isGatewayExternallySupervised as Y,_coercedString as Yt,applyConfigEnvVars as Z,createStateSchemaAdmission as Zt,assertStateDatabaseIntegrityOnce as _,readTableColumns as _n,assertStateDatabaseAccessAllowed as _t,closeOpenClawStateDatabase as a,assertTransactionUsable as an,prepareSqliteReadOnlyLocationSync as at,assertSqliteIntegrity as b,tablePrimaryKeyColumns as bn,prepareStateDatabaseReadAccess as bt,ff as c,runSqliteImmediateTransactionSync as cn,projectUpdateRehearsalDatabaseConfig as ct,Af as d,observeConnection as dn,leaseReusableSqliteSnapshot as dt,publishStateRuntimeSchemaAdmission as en,createSqliteWalMaintenanceScheduler as et,registerOpenClawStateDatabaseLifecycleListener as f,observeDatabaseOperation as fn,publishReusableSqliteSnapshot as ft,assertOpenClawStateRuntimeIntegrity as g,ensureColumn as gn,acquireStateDatabaseSchemaLease as gt,kf as h,classifySqliteTableReadError as hn,createPrivateSqliteTempDirectorySync as ht,Mf as i,Cs as in,prepareSqliteReadOnlyLocationAwaited as it,captureSqliteWorkerStateContext as j,executeSqliteQuerySync as jn,createManagedHandoffBootIdentityReader as jt,resolveCronIdentityMigrationDefaultStoreKey as k,sha256Hex as kn,classifyGatewayOwnerProcessNamespace as kt,publishOpenClawStateDatabaseWorkerAdmission as l,runSqliteReadSnapshotSync as ln,captureReusableSqliteSource as lt,requireOpenClawStateDatabaseIdentity as m,sqliteSchemaContractFromCatalog as mn,acquireSqliteSnapshotReadToken as mt,Of as n,readPublishedStateSchemaVersion as nn,readOpenClawDatabaseQuarantineFailure as nt,getOpenClawStateDatabaseTerminalFailureAsync as o,retainSqliteWriteAdmissionService as on,startSqliteReadOnlyLocationAsync as ot,registerOpenClawStatePathAsyncResource as p,createSqliteTableContractReader as pn,prepareSqliteReadOnlyLocationFromOwnedDatabase as pt,jsonType as q,union as qt,jf as r,rememberStateSchemaVersionAdmission as rn,openSqliteReadOnlyDatabase as rt,Nf as s,runSqliteDeferredTransactionSync as sn,isUpdateRehearsalPrivateDatabase as st,assertPublishedOpenClawStateDatabaseLifecycle as t,publishStateSchemaVersionAdmission as tn,isSqliteWalWorkerMaintained as tt,recordOpenClawStateDatabaseOpenFailure as u,runSqliteSingleStatementSync as un,isSqliteSnapshotReuseActive as ut,invalidateOpenClawStateRuntimeIntegrity as v,tableExists as vn,captureStateDatabaseAccess as vt,openTrackedStateDatabase as w,legacySqliteSchemaIssueMessages as wn,Y as wt,assertSqliteTableIntegrity as x,SqliteSchemaMismatchError as xn,resolveGatewayStateOwnerPath as xt,SqliteRepairableForeignKeyError as y,tableHasColumn as yn,getStateDatabaseSchemaLease as yt,recordExistingOpenClawStateSchemaDatabase as z,V as zn,discriminatedUnion as zt};