harperdb 4.7.8 → 4.7.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,7 +15,7 @@
15
15
  `)}}});var aq,Fl,cq,uc,Hp,wd,Eae,fS,kN=se(()=>{aq=b(us()),Fl=b(st());G();cq=b(sr());Rd();dS();uc=(0,cq.loggerWithTag)("componentStatus.crossThread"),Hp=class{static{a(this,"CrossThreadStatusCollector")}awaitingResponses=new Map;responseCheckers=new Map;nextRequestId=1;listenerAttached=!1;timeout;cleanupTimer=null;constructor(t=5e3){this.timeout=t}attachListener(){this.listenerAttached||((0,Fl.onMessageByType)(T_.COMPONENT_STATUS_RESPONSE,({message:t})=>{let r=t.isMainThread?"main":`worker-${t.workerIndex}`;uc.trace?.("Received component status response from %s, with requestId: %d",r,t.requestId);let n=this.awaitingResponses.get(t.requestId);if(n){n.push({workerIndex:t.workerIndex,isMainThread:t.isMainThread||!1,statuses:t.statuses||[]});let s=this.responseCheckers.get(t.requestId);s&&s()}}),this.listenerAttached=!0)}scheduleCleanup(){this.cleanupTimer&&clearTimeout(this.cleanupTimer),this.awaitingResponses.size>0&&(this.cleanupTimer=setTimeout(()=>{this.awaitingResponses.size>0&&(uc.debug?.(`Cleaning up ${this.awaitingResponses.size} stale pending requests`),this.awaitingResponses.clear()),this.cleanupTimer=null},3e4))}async collect(t){try{this.attachListener(),this.scheduleCleanup();let r=this.nextRequestId++,n=[];this.awaitingResponses.set(r,n);let o=((0,Fl.getWorkerCount)()||1)+1-1,l=await new Promise((p,h)=>{let E=!1,_=a(()=>{let y=this.awaitingResponses.get(r);y&&y.length>=o&&!E&&(E=!0,S(),uc.trace?.(`Collected all ${y.length} expected responses for request ${r}`),p(y))},"checkComplete"),R=setTimeout(()=>{if(!E){E=!0;let y=this.awaitingResponses.get(r)||[];this.awaitingResponses.delete(r),uc.debug?.(`Collection timeout for request ${r}: collected ${y.length}/${o} responses`),p(y)}},this.timeout),S=a(()=>{this.awaitingResponses.delete(r),clearTimeout(R)},"cleanup");this.responseCheckers.set(r,_),(0,aq.sendItcEvent)({type:T_.COMPONENT_STATUS_REQUEST,message:{requestId:r}}).then(()=>{_()}).catch(y=>{E=!0,S(),this.responseCheckers.delete(r),h(new Ad("sendItcEvent",y))})});this.responseCheckers.delete(r);let u=new Map,d=t.getAllStatuses(),f=(0,Fl.getWorkerIndex)(),m=f===void 0?"main":`worker-${f}`;for(let[p,h]of d)u.set(`${p}@${m}`,{...h,workerIndex:f});for(let p of l)for(let[h,E]of p.statuses){let _=p.isMainThread?"main":`worker-${p.workerIndex}`;u.set(`${h}@${_}`,{...E,workerIndex:p.workerIndex})}return uc.debug?.(`Collected component status from ${l.length+1} threads (including local)`),u}catch(r){return r instanceof Ad?uc.error?.(`ITC failure during component status collection: ${r.message}`):uc.warn?.("Failed to collect component status from all threads:",r),uc.debug?.(`Collection failed for request. Error: ${r instanceof Error?r.message:"Unknown error"}`),this.getLocalStatusOnly(t)}}getLocalStatusOnly(t){let r=t.getAllStatuses(),n=new Map,s=(0,Fl.getWorkerIndex)(),i=s===void 0?"main":`worker-${s}`;for(let[o,c]of r)n.set(`${o}@${i}`,{...c,workerIndex:s});return n}cleanup(){this.awaitingResponses.clear(),this.responseCheckers.clear(),this.cleanupTimer&&(clearTimeout(this.cleanupTimer),this.cleanupTimer=null)}},wd=class{static{a(this,"StatusAggregator")}static aggregate(t){let r=new Map,n=new Map;for(let[s,i]of t){let o=s.indexOf("@"),c=o!==-1?s.substring(0,o):s,l=n.get(c);l||(l=[],n.set(c,l)),l.push([s,i])}for(let[s,i]of n){let o=this.aggregateComponentGroup(s,i);r.set(s,o)}return r}static aggregateComponentGroup(t,r){let n={workers:{}},s=0,i,o,c=new Map,l=new Map;for(let[m,p]of r){let h=m.lastIndexOf("@"),E=h!==-1?m.substring(h+1):"",_=p.lastChecked instanceof Date?p.lastChecked.getTime():new Date(p.lastChecked).getTime();if(E==="main")n.main=_;else if(E&&E.startsWith("worker-")){let R=parseInt(E.substring(7));isNaN(R)||(n.workers[R]=_)}c.set(p.status,(c.get(p.status)||0)+1),p.status!==Pe.HEALTHY&&p.message&&(!i||_>s)&&(s=_,i=p.message),p.error&&!o&&(o=p.error)}let u=this.determineOverallStatus(c);if(Array.from(c.keys()).length>1)for(let[m,p]of r)p.status!==u&&l.set(m,{workerIndex:p.workerIndex!==void 0?p.workerIndex:-1,status:p.status,message:p.message,error:p.error});let f={componentName:t,status:u,lastChecked:n,latestMessage:i,error:o};return l.size>0&&(f.abnormalities=l),f}static determineOverallStatus(t){let r=[Pe.ERROR,Pe.WARNING,Pe.LOADING,Pe.UNKNOWN,Pe.HEALTHY];for(let n of r)if(t.has(n)&&t.get(n)>0)return n;return Pe.UNKNOWN}},Eae=parseInt(process.env.COMPONENT_STATUS_TIMEOUT||"5000"),fS=new Hp(Eae)});var dc,mS=se(()=>{UN();Rd();kN();dS();dc=class e{static{a(this,"ComponentStatusRegistry")}statusMap=new Map;reset(){this.statusMap=new Map}setStatus(t,r,n,s){if(!t||typeof t!="string")throw new Id(String(t),"setStatus","Component name must be a non-empty string");if(!Object.values(Pe).includes(r))throw new Id(t,"setStatus",`Invalid status level: ${r}. Must be one of: ${Object.values(Pe).join(", ")}`);this.statusMap.set(t,new bd(r,n,s))}getStatus(t){return this.statusMap.get(t)}getAllStatuses(){return this.statusMap}reportHealthy(t,r){this.setStatus(t,Pe.HEALTHY,r)}reportError(t,r,n){this.setStatus(t,Pe.ERROR,n,r)}reportWarning(t,r){this.setStatus(t,Pe.WARNING,r)}initializeLoading(t,r){this.setStatus(t,Pe.LOADING,r||"Component is loading")}markLoaded(t,r){this.setStatus(t,Pe.HEALTHY,r||"Component loaded successfully")}markFailed(t,r,n){this.setStatus(t,Pe.ERROR,n,r)}getComponentsByStatus(t){let r=[];for(let[n,s]of this.statusMap)s.status===t&&r.push({name:n,status:s});return r}getStatusSummary(){let t={[Pe.HEALTHY]:0,[Pe.ERROR]:0,[Pe.WARNING]:0,[Pe.LOADING]:0,[Pe.UNKNOWN]:0};for(let r of this.statusMap.values())t[r.status]++;return t}static async getAggregatedFromAllThreads(t){let r=await fS.collect(t);return wd.aggregate(r)}async getAggregatedStatusFor(t,r){r||(r=await e.getAggregatedFromAllThreads(this));let n=[],s=t+".",i=r.get(t);i&&n.push({key:t,...i});for(let[f,m]of r)f.startsWith(s)&&n.push({key:f,...m});if(n.length===0)return{status:Pe.UNKNOWN,message:"The component has not been loaded yet (may need a restart)",lastChecked:{workers:{}}};let o=n.some(f=>f.status===Pe.ERROR),c=n.some(f=>f.status===Pe.LOADING),l=o?Pe.ERROR:c?Pe.LOADING:Pe.HEALTHY,u="All components loaded successfully",d={};if(o||c){u=n.filter(m=>m.status===Pe.ERROR||m.status===Pe.LOADING).map(m=>`${m.key}: ${m.latestMessage||m.status}`).join("; ");for(let m of n)m.status!==Pe.HEALTHY&&(d[m.key]={status:m.status,message:m.latestMessage})}return{status:l,message:u,...Object.keys(d).length>0&&{details:d},lastChecked:n[0]?.lastChecked||{workers:{}}}}}});var hr,pS=se(()=>{mS();hr=new dc});function uq(e){let t=lq.get(e);return t||(t=new HN(e),lq.set(e,t)),t}function dq(){hr.reset()}var HN,lq,ao,fq,mq=se(()=>{pS();Rd();HN=class{static{a(this,"ComponentStatusBuilder")}componentName;constructor(t){this.componentName=t}healthy(t){return hr.setStatus(this.componentName,Pe.HEALTHY,t),this}warning(t){return hr.setStatus(this.componentName,Pe.WARNING,t),this}error(t,r){return hr.setStatus(this.componentName,Pe.ERROR,t,r),this}loading(t){return hr.setStatus(this.componentName,Pe.LOADING,t||"Loading..."),this}unknown(t){return hr.setStatus(this.componentName,Pe.UNKNOWN,t),this}get(){return hr.getStatus(this.componentName)}},lq=new Map;a(uq,"statusForComponent");ao={loading(e,t){hr.initializeLoading(e,t)},loaded(e,t){hr.markLoaded(e,t)},failed(e,t,r){hr.markFailed(e,t,r)}};a(dq,"reset");fq=Pe});var Gp={};ye(Gp,{AggregationError:()=>BN,COMPONENT_STATUS_LEVELS:()=>Pe,ComponentStatus:()=>bd,ComponentStatusError:()=>lc,ComponentStatusOperationError:()=>Id,ComponentStatusRegistry:()=>dc,CrossThreadCollectionError:()=>FN,CrossThreadStatusCollector:()=>Hp,CrossThreadTimeoutError:()=>xN,ITCError:()=>Ad,StatusAggregator:()=>wd,componentStatusRegistry:()=>hr,crossThreadCollector:()=>fS,query:()=>_ae});var _ae,pq=se(()=>{pS();mS();UN();mS();kN();pS();dS();Rd();_ae={get(e){return hr.getStatus(e)},all(){return hr.getAllStatuses()},byStatus(e){return hr.getComponentsByStatus(e)},summary(){return hr.getStatusSummary()},async allThreads(){return dc.getAggregatedFromAllThreads(hr)}}});var GN={};ye(GN,{STATUS:()=>fq,internal:()=>Gp,lifecycle:()=>ao,reset:()=>dq,statusForComponent:()=>uq});var qp=se(()=>{mq();pq()});var Vp=M((QMe,_q)=>{"use strict";var Es=Q(),Tn=(G(),D(j)),gae=ZB(),Sae=(hs(),D(oo)),{validateEvent:qN}=us(),$p=ms(),Tae=require("process"),{resetDatabases:yae}=(Oe(),D(pt)),Rae={[Tn.ITC_EVENT_TYPES.SCHEMA]:bae,[Tn.ITC_EVENT_TYPES.USER]:Eq,[Tn.ITC_EVENT_TYPES.COMPONENT_STATUS_REQUEST]:Iae};async function bae(e){let t=qN(e);if(t){Es.error(t);return}Es.trace("ITC schemaHandler received schema event:",e),await gae(e.message),await Aae(e.message)}a(bae,"schemaHandler");async function Aae(e){try{$p.resetReadTxn(Tn.SYSTEM_SCHEMA_NAME,Tn.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),$p.resetReadTxn(Tn.SYSTEM_SCHEMA_NAME,Tn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),$p.resetReadTxn(Tn.SYSTEM_SCHEMA_NAME,Tn.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=yae();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Es.error(t)}}a(Aae,"syncSchemaMetadata");var hq=[];async function Eq(e){try{try{$p.resetReadTxn(Tn.SYSTEM_SCHEMA_NAME,Tn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),$p.resetReadTxn(Tn.SYSTEM_SCHEMA_NAME,Tn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Es.warn(r)}let t=qN(e);if(t){Es.error(t);return}Es.trace(`ITC userHandler ${Tn.HDB_ITC_CLIENT_PREFIX}${Tae.pid} received user event:`,e),await Sae.setUsersWithRolesCache();for(let r of hq)r()}catch(t){Es.error(t)}}a(Eq,"userHandler");Eq.addListener=function(e){hq.push(e)};async function Iae(e){try{let t=qN(e);if(t){Es.error(t);return}Es.trace("ITC componentStatusRequestHandler received request:",e);let{internal:r}=(qp(),D(GN)),{getWorkerIndex:n}=st(),{sendItcEvent:s}=us(),i=r.componentStatusRegistry.getAllStatuses(),o=Array.from(i.entries()),c=n(),l=c===void 0,u=e.message.originator,d={type:Tn.ITC_EVENT_TYPES.COMPONENT_STATUS_RESPONSE,message:{requestId:e.message.requestId,statuses:o,workerIndex:c,isMainThread:l}};u!==void 0&&threads.sendToThread(u,d)?Es.trace(`Sent component status response directly to thread ${u}`):(u===void 0?Es.debug("No originator threadId, falling back to broadcast"):Es.warn(`Failed to send direct response to thread ${u}, falling back to broadcast`),await s(d))}catch(t){Es.error("Error handling component status request:",t)}}a(Iae,"componentStatusRequestHandler");_q.exports=Rae});var us=M((nUe,Sq)=>{"use strict";var ZMe=Q(),$N=ae(),wae=(G(),D(j)),{ITC_ERRORS:Kp}=Jr(),{parentPort:eUe,threadId:Nae,isMainThread:Cae,workerData:tUe}=require("worker_threads"),{onMessageFromWorkers:Oae,broadcast:rUe,broadcastWithAcknowledgement:Pae}=st();Sq.exports={sendItcEvent:Lae,validateEvent:gq,SchemaEventMsg:Dae,UserEventMsg:vae};var hS;Oae(async(e,t)=>{hS=hS||Vp(),gq(e),hS[e.type]&&await hS[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function Lae(e){return!Cae&&e.message&&(e.message.originator=Nae),Pae(e)}a(Lae,"sendItcEvent");function gq(e){if(typeof e!="object")return Kp.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||$N.isEmpty(e.type))return Kp.MISSING_TYPE;if(!e.hasOwnProperty("message")||$N.isEmpty(e.message))return Kp.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||$N.isEmpty(e.message.originator))return Kp.MISSING_ORIGIN;if(wae.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Kp.INVALID_EVENT(e.type)}a(gq,"validateEvent");function Dae(e,t,r,n=void 0,s=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=n,this.attribute=s}a(Dae,"SchemaEventMsg");function vae(e){this.originator=e}a(vae,"UserEventMsg")});var Xo=M((oUe,bq)=>{"use strict";var Tq=(G(),D(j)),iUe=ae(),ES=Q(),yq=UB(),Nd,{sendItcEvent:Rq}=us();function Mae(e){try{ES.debug("signalSchemaChange called with message:",e),Nd=Nd||Vp();let t=new yq(Tq.ITC_EVENT_TYPES.SCHEMA,e);return Nd.schema(t),Rq(t)}catch(t){ES.error(t)}}a(Mae,"signalSchemaChange");function Uae(e){try{ES.trace("signalUserChange called with message:",e),Nd=Nd||Vp();let t=new yq(Tq.ITC_EVENT_TYPES.USER,e);return Nd.user(t),Rq(t)}catch(t){ES.error(t)}}a(Uae,"signalUserChange");bq.exports={signalSchemaChange:Mae,signalUserChange:Uae}});function Yp(e,t,r,n){if(e.append)e.append(t,r,n);else if(e.set){let s=e.get(t);if(s)if(n)r=(typeof s=="string"?s:s.join(", "))+", "+r;else if(typeof s=="string")r=[s,r];else{s.push(r);return}return e.set(t,r)}else e[t]=(e[t]?e[t]+", ":"")+r}function Aq(e,t){(typeof e.set!="function"||typeof e.has!="function")&&(e=new Hs(e));for(let[r,n]of t)e.has(r)?r.toLowerCase()==="set-cookie"&&e.append?.(r,n,!0):e.set(r,n);return e}var Hs,Wp=se(()=>{Hs=class extends Map{static{a(this,"Headers")}constructor(t){if(t)if(t[Symbol.iterator])super(t);else{super();for(let r in t)this.set(r,t[r])}else super()}set(t,r){return typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r),super.set(t.toLowerCase(),[t,r])}get(t){return typeof t!="string"&&(t=""+t),super.get(t.toLowerCase())?.[1]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase();if(!super.has(n))return super.set(n,[t,r])}append(t,r,n){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase(),i=super.get(s);if(i){let o=i[1];if(n)r=(typeof o=="string"?o:o.join(", "))+", "+r;else if(typeof o=="string")r=[o,r];else{o.push(r);return}}return super.set(s,[t,r])}*[Symbol.iterator](){for(let[t,r]of super.values()){if(Array.isArray(r)&&t.toLowerCase()==="set-cookie"){for(let n of r)yield[t,n];continue}yield[t,r]}}};a(Yp,"appendHeader");a(Aq,"mergeHeaders")});function _S(e,t,r=Bae){let n;return function(...i){return n?n.length*VN>r?t(...i):new Promise((o,c)=>{n.push({args:i,fn(){try{let l=e(...i);o(l)}catch(l){c(l)}}})}):(n=[],s(performance.now(),i),e(...i))};function s(i,o){setImmediate(()=>{let c=performance.now();VN=(VN*4+c-i)/5;let l=n.shift();if(l){let{args:u,fn:d}=l;d(),s(c,u)}else n=null})}}var Nq,xae,Bae,Iq,Fae,KN,wq,VN,YN=se(()=>{Nq=b(sr()),xae=3e3,Bae=2e4,Iq=0,Fae=3e4,KN=3e3,wq=performance.now()+KN,VN=0;a(_S,"throttle");setInterval(()=>{let e=performance.now();e-wq-KN>xae&&Iq+Fae<e&&(Nq.default.warn?.("JavaScript execution has taken too long and is not allowing proper event queue cycling, consider using 'await new Promise(setImmediate)' in code that will execute for a long duration"),Iq=e),wq=e},KN).unref()});var Fq={};ye(Fq,{EVICTED:()=>Sl,INVALIDATED:()=>kn,coerceType:()=>SS,makeTable:()=>TS});function TS(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:l,schemaDefined:u,dbisDB:d,sealed:f,splitSegments:m,replicate:p}=e,{expirationMS:h,evictionMS:E,audit:_,trackDeletes:R}=e;E??=0;let{attributes:S}=e;S||(S=[]);let y=II(i,n,l),w,I,H={},X=Promise.resolve(),q,k,z;for(let K of S)(K.assignCreatedTime||K.name==="__createdtime__")&&(q=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(k=K),K.expiresAt&&(z=K),K.isPrimaryKey&&(H=K);let Y,ce=[],de=[],te=1,Se=2,Ne={},Ke={},$e=864e5,Ir=0,nr,zr,xr,Pu=!1,zc,Ft,Ps,Ha=Hl.get(x.REPLICATION_DATABASES);if(Array.isArray(Ha)){for(let K of Ha)if(K.name===c&&K.replicateTo>=0){Ps=K.replicateTo;break}}let o_=i.getRange({start:!1,end:!1}).constructor,cm=10,a_=6;_&&mm(),jm(i.env.path,K=>{if(I)return qa(K)});class lm extends Ol{static{a(this,"Updatable")}getUpdatedTime(){return ec.get(this.getRecord())?.version}getExpiresAt(){return ec.get(this.getRecord())?.expiresAt}addTo(g,T){if(typeof T=="number"||typeof T=="bigint")this.set(g,new Cp(T));else throw new Error("Can not add or subtract a non-numeric value")}subtractFrom(g,T){return this.addTo(g,-T)}}class ve extends Xt{#e;#t;#n;#r;#s;#i;static name=s;static primaryStore=i;static auditStore=l;static primaryKey=t;static tableName=s;static tableId=n;static indices=r;static audit=_;static databasePath=o;static databaseName=c;static attributes=S;static replicate=p;static sealed=f;static splitSegments=m??!0;static createdTimeProperty=q;static updatedTimeProperty=k;static propertyResolvers;static userResolvers={};static sources=[];static getResidencyById;static get expirationMS(){return h}static dbisDB=d;static schemaDefined=u;static sourcedFrom(g,T){if(T&&(this.sourceOptions=T,(T.expiration||T.eviction||T.scanInterval)&&this.setTTLExpiration(T)),T?.intermediateSource)g.intermediateSource=!0,this.sources.unshift(g);else{if(this.sources.some(v=>!v.intermediateSource)){if(this.sources.some(v=>v.name===g.name))return;throw new Error("Can not have multiple canonical (non-intermediate) sources")}this.sources.push(g)}I=I||g.get&&(!g.get.reliesOnPrototype||g.prototype.get),w=w||g.load;let C=a(v=>{let A=this.sources;if(A=A.filter(U=>U.intermediateSource&&U[v]&&(!U[v].reliesOnPrototype||U.prototype[v])),A.length>0)if(A.length===1){let U=A[0];return(N,L,$)=>{if(N?.source!==U)return U[v](L,$,N)}}else return(U,N,L)=>{let $=[];for(let W of A){if(U?.source===W)break;$.push(W[v](N,L,U))}return Promise.all($)}},"getApplyToIntermediateSource"),P=this.sources[this.sources.length-1];P.intermediateSource&&(P={});let O=a(v=>{if(P[v]&&(!P[v].reliesOnPrototype||P.prototype[v]))return(A,U,N)=>{if(!A?.source)return P[v](U,N,A)}},"getApplyToCanonicalSource");Ne={put:O("put"),patch:O("patch"),delete:O("delete"),publish:O("publish")},Ke={put:C("put"),patch:C("patch"),delete:C("delete"),publish:C("publish"),invalidate:C("invalidate")};let B=P.shouldRevalidateEvents;return(async()=>{let v=!1,A,U=a(async(N,L)=>{let $=N.value,W=N.table?Me[c][N.table]:ve;if(c===_m&&(N.table===xu.ROLE_TABLE_NAME||N.table===xu.USER_TABLE_NAME)&&(v=!0),N.id===void 0&&(N.id=$[W.primaryKey],N.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(N));N.source=g;let J={residencyId:Jc(N.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:N.nodeId,async:!0},F=N.id,he=await W.getResource(F,L,J);switch(N.finished&&await N.finished,N.type){case"put":return B?he._writeInvalidate(F,$,J):he._writeUpdate(F,$,!0,J);case"patch":return B?he._writeInvalidate(F,$,J):he._writeUpdate(F,$,!1,J);case"delete":return he._writeDelete(F,J);case"publish":case"message":return he._writePublish(F,$,J);case"invalidate":return he._writeInvalidate(F,$,J);case"relocate":return he._writeRelocate(F,J);default:Fe.default.error?.("Unknown operation",N.type,N.id)}},"writeUpdate");try{let N=g.subscribe;N&&R==null&&(R=!0);let L={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},$=g.subscribeOnThisThread?g.subscribeOnThisThread((0,kl.getWorkerIndex)(),L):(0,kl.getWorkerIndex)()===0,W=N&&$&&await g.subscribe?.(L);if(W){let J;for await(let F of W)try{if(!(F.type==="transaction"?F.writes[0]:F)){Fe.default.error?.("Bad subscription event",F);continue}if(F.source=g,F.type==="end_txn"){J?.resolve();let _e;if(F.localTime&&A!==F.localTime&&F.remoteNodeIds?.length>0&&(_e=a(()=>{let re=[Symbol.for("seq"),F.remoteNodeIds[0]],oe=d.get(re),ge=oe?.nodes;ge||(ge=[]);for(let ie of F.remoteNodeIds.slice(1)){let Ce=ge.find(Be=>Be.id===ie);ge=ge.filter(Be=>Be.id!==ie||Be===Ce),Ce||(Ce={id:ie,seqId:0},ge.push(Ce)),Ce.seqId=Math.max(oe?.seqId??1,F.localTime),ie===J?.nodeId&&(Ce.lastTxnTime=F.timestamp)}let me=Math.max(oe?.seqId??1,F.localTime);Fe.default.trace?.("Received txn",c,me,new Date(me),F.localTime,new Date(F.localTime),F.remoteNodeIds),d.put(re,{seqId:me,nodes:ge})},"updateRecordedSequenceId"),A=F.localTime),F.onCommit){let re=J?J.committed.then(F.onCommit):F.onCommit();_e&&(re?.then?re.then(_e):_e())}else _e&&_e();continue}if(J)if(F.beginTxn)J.resolve();else{J.writePromises.push(U(F,J));continue}!F.timestamp&&F.version&&(F.timestamp=F.version);let ue=At(F,()=>{if(F.type==="transaction"){let _e=[];for(let re of F.writes)try{_e.push(U(re,F))}catch(oe){throw oe.message+=" writing "+JSON.stringify(re)+" of event "+JSON.stringify(F),oe}return Promise.all(_e)}else if(F.type==="define_schema"){let _e=this.attributes.slice(0),re=!1;for(let oe of F.attributes)_e.find(ge=>ge.name===oe.name)||(_e.push(oe),re=!0);re&&(ze({table:s,database:c,attributes:_e,origin:"cluster"}),zp.signalSchemaChange(new Jp.SchemaEventMsg(process.pid,V.CREATE_TABLE,c,s)))}else return F.beginTxn?(J=F,J.writePromises=[U(F,F)],new Promise(_e=>{J.resolve=()=>_e(Promise.all(J.writePromises))})):U(F,F)});J&&(J.committed=ue),v&&ue&&!ue?.waitingForUserChange&&(ue.then(()=>zp.signalUserChange(new Jp.UserEventMsg(process.pid))),ue.waitingForUserChange=!0),F.onCommit&&(ue?ue.then(F.onCommit):F.onCommit())}catch(he){Fe.default.error?.("error in subscription handler",he)}}}catch(N){Fe.default.error?.(N)}})(),this}static get isCaching(){return I}static get shouldRevalidateEvents(){return this.prototype.get!==ve.prototype.get}static getResource(g,T,C){let P=super.getResource(g,T,C);if(this.loadAsInstance===!1&&(T._freezeRecords=!0),g!=null&&this.loadAsInstance!==!1){ki(g);try{if(P.getRecord?.())return P;if(typeof g=="object"&&g&&!Array.isArray(g))throw new Error(`Invalid id ${JSON.stringify(g)}`);let O=!C?.async||i.cache?.get?.(g),B=Br(T),v=B.getReadTxn();if(v?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return xo(g,T,{transaction:v,ensureLoaded:C?.ensureLoaded},O,A=>{if(A?ve._updateResource(P,A):P.#e=null,T.onlyIfCached){if(!P.doesExist())throw new dt.ServerError("Entry is not cached",504)}else if(C?.ensureLoaded){let U=pn(g,A,T,P);if(U)return B?.disregardReadTxn(),P.#i=!0,T.loadedFromSource=!0,Gs(U,N=>(ve._updateResource(P,N),P))}return P})}catch(O){throw O.message.includes("Unable to serialize object")&&(O.message+=": "+JSON.stringify(g)),O}}return P}static _updateResource(g,T){g.#r=T,g.#e=T?.value??null,g.#n=T?.version}ensureLoaded(){let g=pn(this.getId(),this.#r,this.getContext());if(g)return this.#i=!0,this.getContext().loadedFromSource=!0,Gs(g,T=>{this.#r=T,this.#e=T.value,this.#n=T.version})}static getNewId(){let g=H?.type;if(g==="String"||g==="ID")return super.getNewId();if(!Ft){let O=i.getEntry(Symbol.for("id_allocation")),B=O?.value,v;if(B&&B.nodeName===server.hostname&&(!Jae(i)||B.pid===process.pid)){let A=B.start,U=B.end;v=A;for(let N of i.getKeys({start:U,end:A,limit:1,reverse:!0}))v=N}else B=P(O?.version??null),v=B.start;Ft=new BigInt64Array([BigInt(v)+1n]),Ft=new BigInt64Array(i.getUserSharedBuffer("id",Ft.buffer)),Ft.maxSafeId=B.end}let T=Number(Atomics.add(Ft,0,1n)),C=g==="Int"?512:1048576;if(T+C>=Ft.maxSafeId){let O=a(B=>{Ft.maxSafeId=T+(g==="Int"?1023:4194303);let v=(g==="Int"?Math.pow(2,31):Math.pow(2,49))-1,A=B?void 0:i.useReadTransaction(),U=Number(Ft[0]);for(let $ of i.getKeys({start:U+1,end:v,limit:1,transaction:A}))v=$;A?.done();let{value:N,version:L}=i.getEntry(Symbol.for("id_allocation"));if(Ft.maxSafeId<v){if(N.end>Ft.maxSafeId-100)return;Fe.default.info?.("New id allocation",T,Ft.maxSafeId,L),i.put(Symbol.for("id_allocation"),{start:N.start,end:Ft.maxSafeId,nodeName:server.hostname,pid:process.pid},Date.now(),L)}else{Fe.default.warn?.(`Id conflict detected, starting new id allocation range, attempting to allocate to ${Ft.maxSafeId}, but id of ${v} detected`);let $=P(L);$.alreadyUpdated||Atomics.store(Ft,0,BigInt($.start+1)),Ft.maxSafeId=$.end}},"updateEnd");T+C===Ft.maxSafeId?setImmediate(O):T+100>=Ft.maxSafeId&&(Fe.default.warn?.(`Synchronous id allocation required on table ${s}${g=="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`),i.transactionSync(()=>O(!0)))}return T;function P(O){let B=(g==="Int"?Math.pow(2,31):Math.pow(2,49))-1,v=B/4,A,U,N=!1,L,$;do{L=Math.floor(Math.random()*B),$={start:L,end:L+(g==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},A=0;for(let W of i.getKeys({start:L,limit:1,reverse:!0}))A=W;U=B;for(let W of i.getKeys({start:L+1,end:B,limit:1}))U=W;v*=.875,v<1e3&&!N&&(N=!0,Fe.default.error?.(`Id allocation in table ${s} is very dense, limited safe range of numbers to allocate ids in${g==="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`,L,A,U,v))}while(!(v<U-L&&(v<L-A||A===0)));return i.transactionSync(()=>{let W=i.getEntry(Symbol.for("id_allocation"));return(W?.version??null)==O?(Fe.default.info?.("Allocated new id range",$),i.put(Symbol.for("id_allocation"),$,Date.now()),$):(Fe.default.debug?.("Looks like ids were already allocated"),{alreadyUpdated:!0,...W.value})})}}static setTTLExpiration(g){if(typeof g=="number")h=g*1e3,E||(E=0);else if(g&&typeof g=="object")h=g.expiration*1e3,E=(g.eviction||0)*1e3,$e=g.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(h<0)throw new Error("Expiration can not be negative");$e=$e||(h+E)/4,qa()}static getResidencyRecord(g){return d.get([Symbol.for("residency_by_id"),g])}static setResidency(g){ve.getResidency=g&&((T,C)=>{try{return g(T,C)}catch(P){throw P.message+=` in residency function for table ${s}`,P}})}static setResidencyById(g){ve.getResidencyById=g&&(T=>{try{return g(T)}catch(C){throw C.message+=` in residency function for table ${s}`,C}})}static getResidency(g,T){if(ve.getResidencyById)return ve.getResidencyById(g[t]);let C=Ps;if(T.replicateTo!=null){if(Array.isArray(T.replicateTo))return T.replicateTo.includes(server.hostname)?T.replicateTo:[server.hostname,...T.replicateTo];T.replicateTo>=0&&(C=T.replicateTo)}if(C>=0&&server.nodes){let P=[server.hostname];if(T.previousResidency)P.push(...T.previousResidency.slice(0,C));else{let O=server.nodes.map(A=>A.name),B=Math.floor(O.length*Math.random());P.push(...O.slice(B,B+C));let v=B+C-O.length;v>0&&P.push(...O.slice(0,v))}return P}}static enableAuditing(){_||(_=!0,mm(),ve.audit=!0)}static coerceId(g){return g===""?null:SS(g,H)}static async dropTable(){delete Me[c][s];for(let g of i.getRange({versions:!0,snapshot:!1,lazy:!0}))g.metadataFlags&Zr&&g.value&&Qa(g.value);if(c===o){for(let g of S)d.remove(ve.tableName+"/"+g.name),r[g.name]?.drop();d.remove(ve.tableName+"/"),i.drop(),await d.committed}else console.log("legacy dropTable"),await i.close(),jN.default.unlinkSync(i.env.path);zp.signalSchemaChange(new Jp.SchemaEventMsg(process.pid,V.DROP_TABLE,c,s))}get(g){let T=this.constructor;if(typeof g=="string"&&T.loadAsInstance!==!1)return this.getProperty(g);if(um(g))return this.search(g);if(g&&g.id===void 0&&!g.toString()){let C={records:"./",name:s,database:c,auditSize:l?.getStats().entryCount,attributes:S,recordCount:void 0,estimatedRecordRange:void 0};return this.getContext()?.includeExpensiveRecordCountEstimates?ve.getRecordCount().then(P=>(C.recordCount=P.recordCount,C.estimatedRecordRange=P.estimatedRange,C)):C}if(g!==void 0&&T.loadAsInstance===!1){let C=this.getContext(),P=Br(C),O=P.getReadTxn();if(O?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");let B=Ls(g);ki(B);let v=!0;return g.checkPermission&&(v=this.allowRead(C.user,g)),Gs(Gs(v,A=>{if(!A)throw new dt.AccessViolation(C.user);let U=!0;return xo(B,C,{transaction:O,ensureLoaded:U},!1,N=>{if(C.onlyIfCached){if(!N?.value)throw new dt.ServerError("Entry is not cached",504)}else if(U){let L=pn(B,N,C);if(L)return P?.disregardReadTxn(),C.loadedFromSource=!0,L.then($=>$?.value)}return N?.value})}),A=>{let U=g?.select;return U&&A!=null?id(U,this.constructor)(A):A})}if(g?.property)return this.getProperty(g.property);if(this.doesExist()||g?.ensureLoaded===!1||this.getContext()?.returnNonexistent)return this}allowRead(g,T){let C=Dn(g,T);if(C?.read){if(C.isSuperUser)return!0;let P=C.attribute_permissions,O=T?.select;if(P?.length>0||Pu&&O){if(T||(T={}),O){let B=Array.isArray(O)?O:[O],v=P?.length>0&&WN(P,"read");T.select=B.map(A=>{let U=A.name||A;if(!v||v[U]){let N=xr[U]?.definition?.tableClass;if(N){if(A.name||(A={name:A}),!A.checkPermission&&T.checkPermission&&(A.checkPermission=T.checkPermission),!N.prototype.allowRead.call(null,g,A))return!1;if(!A.select)return A.name}return A}}).filter(Boolean)}else T.select=P.filter(B=>B.read&&!xr[B.attribute_name]).map(B=>B.attribute_name);return T}else return!0}}allowUpdate(g,T,C){let P=Dn(g,C);if(P?.update){let O=P.attribute_permissions;if(O?.length>0){let B=WN(O,"update");for(let v in T)if(!B[v])return!1;for(let v of O){let A=v.attribute_name;!v.update&&!(A in T)&&(T[A]=this.getProperty(A))}}return Ga(this.getContext())}}allowCreate(g,T,C){if(this.isCollection){let P=Dn(g,C);if(P?.insert){let O=P.attribute_permissions;if(O?.length>0){let B=WN(O,"insert");for(let v in T)if(!B[v])return!1;return Ga(this.getContext())}else return Ga(this.getContext())}}else return this.allowUpdate(g,{})}allowDelete(g,T){return Dn(g,T)?.delete&&Ga(this.getContext())}update(g,T){let C,P=typeof T=="boolean"||T===void 0&&(g==null||typeof g=="object"&&!(g instanceof URLSearchParams)),O=!1;P?(O=T,T=g,C=this.getId()):C=Ls(g);let B=this.getContext();if(!Br(B))throw new Error("Can not update a table resource outside of a transaction");if(T===!1)return this;if(typeof T=="object"&&T)if(O)Object.isFrozen(T)&&(T={...T}),this.#e={},this.#t=T;else if(P){let A=this.#t;A&&(T=Object.assign(A,T)),this.#t=T}else{let A=!0;if(g==null)throw new TypeError("Can not put a record without a target");return g.checkPermission&&(A=this.allowUpdate(B.user,T,g)),Gs(A,U=>{if(!U)throw new dt.AccessViolation(B.user);return Gs(i.get(Ls(g)),N=>{let L=new lm(N);return L._setChanges(T),this._writeUpdate(C,L.getChanges(),!1),L})})}return this._writeUpdate(C,this.#t,O),this}addTo(g,T){if(typeof T=="number"||typeof T=="bigint")this.#s===Oq?this.set(g,(+this.getProperty(g)||0)+T):(this.#s||this.update(),this.set(g,new Cp(T)));else throw new Error("Can not add a non-numeric value")}subtractFrom(g,T){if(typeof T=="number")return this.addTo(g,-T);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this.#r}getRecord(){return this.#e}getChanges(){return this.#t}_setChanges(g){this.#t=g}setRecord(g){this.#e=g}invalidate(g){let T=!0,C=this.getContext();return g?.checkPermission&&(T=this.allowDelete(C.user,g,C)),Gs(T,P=>{if(!P)throw new dt.AccessViolation(C.user);this._writeInvalidate(g?Ls(g):this.getId())})}_writeInvalidate(g,T,C){let P=this.getContext();ki(g),Br(this.getContext()).addWrite({key:g,store:i,invalidated:!0,entry:this.#r,before:Ne.invalidate?.bind(this,P,g),beforeIntermediate:Mu(T,Ke.invalidate?.bind(this,P,g)),commit:a((B,v)=>{if(!(Fr(B,v,C?.nodeId)<=0)){T??=null;for(let A in r)T||(T={}),T[A]===void 0&&(T[A]=this.getProperty(A));Fe.default.trace?.(`Invalidating entry in ${s} id: ${g}, timestamp: ${new Date(B).toISOString()}`),y(g,T,v,B,kn,_,{user:P?.user,residencyId:C?.residencyId,nodeId:C?.nodeId,tableToTrack:s},"invalidate")}},"commit")})}_writeRelocate(g,T){let C=this.getContext();ki(g),Br(this.getContext()).addWrite({key:g,store:i,invalidated:!0,entry:this.#r,before:Ne.relocate?.bind(this,C,g),beforeIntermediate:Ke.relocate?.bind(this,C,g),commit:a((O,B)=>{if(Fr(O,B,T?.nodeId)<=0)return;let v=ve.getResidencyRecord(T.residencyId),A=0,U=null,N=B?.value;if(v&&!v.includes(server.hostname)){for(let L in r)U||(U={}),U[L]=N[L];A=kn}else U=N;Fe.default.trace?.(`Relocating entry id: ${g}, timestamp: ${new Date(O).toISOString()}`),y(g,U,B,O,A,_,{user:C.user,residencyId:T.residencyId,nodeId:T.nodeId,expiresAt:T.expiresAt},"relocate",!1,null)},"commit")})}static _recordRelocate(g,T){if(this.getResidencyById)return!1;let C={previousResidency:this.getResidencyRecord(g.residencyId),isRelocation:!0},P=$a(this.getResidency(T.value,C)),O;if(P){if(!P.includes(server.hostname))return!1;O=Jc(P)}let B=0;Fe.default.debug?.("Performing a relocate of an entry",g.key,T.value,P);let v=y(g.key,T.value,g,g.version,B,!0,{residencyId:O,expiresAt:T.expiresAt},"relocate",!1,null);return!0}static evict(g,T,C){let P=this.Source,O;if(!((I||_)&&(!T||(O=i.getEntry(g),!O||!T)||O.version!==C))){if(I){if(i.hasLock(g,O.version))return;let B;for(let v in r)B||(B={}),B[v]=T[v];if(B)return y(g,B,O,C,Sl,null,null,null,!0)}return i.ifVersion(g,C,()=>{Lu(g,T,null)}),gl(i,O??i.getEntry(g),C)}}lock(){throw new Error("Not yet implemented")}static operation(g,T){return g.table||=s,g.schema||=c,global.operation(g,T)}put(g,T){if(T===void 0||T instanceof URLSearchParams)this.update(g,!0);else{let C=!0;if(g==null)throw new TypeError("Can not put a record without a target");let P=this.getContext();return g.checkPermission&&(C=this.allowUpdate(P.user,T,g)),Gs(C,O=>{if(!O)throw new dt.AccessViolation(P.user);if(Array.isArray(T))for(let B of T){let v=B[t];this._writeUpdate(v,B,!0)}else{let B=Ls(g);this._writeUpdate(B,T,!0)}})}}create(g,T){let C=!0,P=this.getContext();if(!T&&!(g instanceof URLSearchParams)&&(T=g,g=void 0),!T||typeof T!="object"||Array.isArray(T))throw new TypeError("Can not create a record without an object");return g?.checkPermission&&(C=this.allowCreate(P.user,T,g)),Gs(C,O=>{if(!O)throw new dt.AccessViolation(P.user);let B=Ls(g)??T[t];if(B===void 0)B=this.constructor.getNewId(),T[t]=B;else if(i.get(B))throw new dt.ClientError("Record already exists",409);return this._writeUpdate(B,T,!0),T})}patch(g,T){if(T===void 0||T instanceof URLSearchParams)this.update(g,!1);else{let C=this.update(g,T);if(C?.then)return C.then(()=>{})}}_writeUpdate(g,T,C,P){let O=this.getContext(),B=Br(O);ki(g);let v=this.#r??i.getEntry(g);this.#s=C?Oq:Yae;let A=a(N=>C?N.put?()=>N.put(O,g,T):null:N.patch?()=>N.patch(O,g,T):N.put?()=>N.put(O,g,Pl(this)):null,"writeToSources"),U={key:g,store:i,entry:v,nodeName:O?.nodeName,validate:a(N=>{T||(T=this.#t),C||T&&Jg(this.#t===T?this:T)?O?.source||(B.checkOverloaded(),this.validate(T,!C),k&&(T[k.name]=k.type==="Date"?new Date(N):k.type==="String"?new Date(N).toISOString():N),C&&(t&&T[t]!==g&&(T[t]=g),q&&(v?.value?T[q.name]=v?.value[q.name]:T[q.name]=q.type==="Date"?new Date(N):q.type==="String"?new Date(N).toISOString():N),T=Pl(T))):B.removeWrite(U)},"validate"),before:A(Ne),beforeIntermediate:Mu(T,A(Ke)),commit:a((N,L,$)=>{if($){if(O&&L?.version>(O.lastModified||0)&&(O.lastModified=L.version),this.#r=L,L?.value&&L.value.getRecord)throw new Error("Can not assign a record to a record, check for circular references");C||(this.#e=L?.value??null)}this.#t=void 0,this.#n=N;let W=L?.value,J;this.#s=0;let F=!1,he=Fr(N,L,P?.nodeId),ue,_e=C?"put":"patch",re;P?.residencyId!=null&&(re=P.residencyId);let oe=O?.expiresAt??(h?h+Date.now():-1);if(he<=0){if(_){let ie=L.localTime,Ce=L.version;Fe.default.trace?.("Applying CRDT update to record with id: ",g,"txn time",new Date(N),"applying later update from:",new Date(Ce),"local recorded time",new Date(ie));let Be=[];for(;ie>N||Ce>=N&&ie>0;){let He=l.get(ie);if(!He)break;let Te=It(He);if(Ce=Te.version,Ce>=N){if(Ce===N){if(he=Fr(N,{version:Ce,localTime:ie},P?.nodeId),he===0)return me(!1);if(he>0){ie=Te.previousLocalTime;continue}}if(Te.type==="patch")Be.push(Te),ue=T;else if(Te.type==="put"||Te.type==="delete")return me(!1)}ie=Te.previousLocalTime}ie||Fe.default.debug?.("No further audit history, applying incremental updates based on available history",g,"existing version preserved",L),Be.sort((He,Te)=>He.version-Te.version);for(let He of Be){let Te=He.getValue(i);if(Fe.default.debug?.("Rebuilding update with future patch:",new Date(He.version),Te,He),J=K_(J??T,Te,C),!J)return me(!1)}}else{if(C)return me(!1);J=K_(J??T,W,C),Fe.default.debug?.("Rebuilding update without audit:",J)}Fe.default.trace?.("Rebuilt record to save:",J," is full update:",C)}let ge;if(C&&!J?ge=T:this.constructor.loadAsInstance===!1?ge=Pl(W,J??T):(this.#e=W,ge=Pl(this,J??T)),this.#e=ge,ge&&ge.getRecord)throw new Error("Can not assign a record to a record, check for circular references");if(re==null){v?.residencyId&&(O.previousResidency=ve.getResidencyRecord(v.residencyId));let ie=$a(ve.getResidency(ge,O));if(ie&&!ie.includes(server.hostname))if(ue??=ge,F=!0,ve.getResidencyById)ge=void 0;else{ge=null;for(let Ce in r)ge||(ge={}),ge[Ce]=ue[Ce]}re=Jc(ie)}C||(ue=T),Fe.default.trace?.(`Saving record with id: ${g}, timestamp: ${new Date(N).toISOString()}${oe?", expires at: "+new Date(oe).toISOString():""}${L?", replaces entry from: "+new Date(L.version).toISOString():", new entry"}`,(()=>{try{return JSON.stringify(ge).slice(0,100)}catch{return""}})()),Lu(g,W,ge),me(!0),O.expiresAt&&qa();function me(ie){y(g,ie?ge:void 0,ie?L:{...L,value:void 0},N,F?kn:0,_,{omitLocalRecord:F,user:O?.user,residencyId:re,expiresAt:oe,nodeId:P?.nodeId,originatingOperation:O?.originatingOperation,tableToTrack:c==="system"?null:s},_e,!1,ie?ue:ue??T)}a(me,"writeCommit")},"commit")};B.addWrite(U)}async delete(g){if(um(g)){g.select=["$id"];for await(let T of this.search(g))this._writeDelete(T.$id);return!0}if(g){let T=!0,C=this.getContext();return g.checkPermission&&(T=this.allowDelete(C.user,g,C)),Gs(T,P=>{if(!P)throw new dt.AccessViolation(C.user);let O=Ls(g);return this._writeDelete(O),!0})}return this._writeDelete(this.getId()),!!this.#e}_writeDelete(g,T){let C=Br(this.getContext());ki(g);let P=this.getContext();return C.addWrite({key:g,store:i,entry:this.#r,nodeName:P?.nodeName,before:Ne.delete?.bind(this,P,g),beforeIntermediate:Ke.delete?.bind(this,P,g),commit:a((O,B,v)=>{let A=B?.value;v&&(P&&B?.version>(P.lastModified||0)&&(P.lastModified=B.version),ve._updateResource(this,B)),!(Fr(O,B,T?.nodeId)<=0)&&(Lu(this.getId(),A),Fe.default.trace?.(`Deleting record with id: ${g}, txn timestamp: ${new Date(O).toISOString()}`),_||R?(y(g,null,B,O,0,_,{user:P?.user,nodeId:T?.nodeId,tableToTrack:s},"delete"),_||qa()):gl(i,B))},"commit")}),!0}search(g){let T=this.getContext(),C=Br(T);if(!g)throw new Error("No query provided");if(g.parseError)throw g.parseError;if(g.checkPermission&&!this.allowRead(T.user,g))throw new dt.AccessViolation(T.user);T&&(T.lastModified=qae);let P=g.conditions;P?P.length===void 0&&(P=P[Symbol.iterator]?Array.from(P):[P]):P=Array.isArray(g)?g:g[Symbol.iterator]?Array.from(g):[];let O=g.id??this.getId();O&&(P=[{attribute:null,comparator:Array.isArray(O)?"prefix":"starts_with",value:O}].concat(P));let B,v={};function A(oe,ge){let me;switch(ge){case"and":case void 0:if(oe.length<1)throw new Error('An "and" operator requires at least one condition');me=!0;break;case"or":if(oe.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+ge)}for(let ie of oe){if(ie.conditions){ie.conditions=A(ie.conditions,ie.operator);continue}let Ce=ie[0]??ie.attribute,Be=Ce==null?H:Wi(S,Ce);if(Be)(Be.type||NI[ie.comparator])&&(ie[1]===void 0?ie.value=N(ie.value,Be):ie[1]=N(ie[1],Be));else if(Ce!=null&&!g.allowConditionsOnDynamicAttributes)throw(0,dt.handleHDBError)(new Error,`${Ce} is not a defined attribute`,404);if(ie.chainedConditions)if(ie.chainedConditions.length===1&&(!ie.operator||ie.operator=="and")){let He=ie.chainedConditions[0],Te,ht;if(He.comparator==="gt"||He.comparator==="greater_than"||He.comparator==="ge"||He.comparator==="greater_than_equal"?(Te=ie,ht=He):(Te=He,ht=ie),Te.comparator!=="lt"&&Te.comparator!=="less_than"&&Te.comparator!=="le"&&Te.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let Ct=ht.comparator==="ge"||ht.comparator==="greater_than_equal",Ot=Te.comparator==="le"||Te.comparator==="less_than_equal";ie.comparator=(Ct?"ge":"gt")+(Ot?"le":"lt"),ie.value=[ht.value,Te.value]}else throw new Error("Multiple chained conditions are not currently supported")}return oe}a(A,"prepareConditions");function U(oe,ge){if(g.enforceExecutionOrder)return oe;for(let me of oe)me.conditions&&(me.conditions=U(me.conditions,me.operator));return oe.length>1&&ge!=="or"?kae(oe,Ig(ve)):oe}a(U,"orderConditions");function N(oe,ge){return Array.isArray(oe)?oe.map(me=>SS(me,ge)):SS(oe,ge)}a(N,"coerceTypedValues");let L=g.operator;(P.length>0||L)&&(P=A(P,L));let $=typeof g.sort=="object"&&g.sort,W;if($&&L!=="or"){let oe=$.attribute;if(oe==null)throw new dt.ClientError("Sort requires an attribute");if(B=P.find(ge=>rd(ge.attribute)===rd(oe)),!B){let ge=Wi(S,oe);if(!ge)throw(0,dt.handleHDBError)(new Error,`${Array.isArray(oe)?oe.join("."):oe} is not a defined attribute`,404);if(ge.indexed)B={...$,comparator:"sort"},P.push(B);else if(P.length===0&&!g.allowFullScan)throw(0,dt.handleHDBError)(new Error,`${Array.isArray(oe)?oe.join("."):oe} is not indexed and not combined with any other conditions`,404)}B&&(B.descending=!!$.descending)}P=U(P,L),$&&(B&&P[0]===B?$.next&&(W={dbOrderedAttribute:$.attribute,attribute:$.next.attribute,descending:$.next.descending,next:$.next.next}):(B&&P.splice(P.indexOf(B),1),W=$));let J=g.select;if(P.length===0&&(P=[{attribute:t,comparator:"greater_than",value:!0}]),g.explain)return{conditions:P,operator:L,postOrdering:W,selectApplied:!!J};let F=C.useReadTxn(),he=CI(P,L,ve,F,g,T,(oe,ge)=>fm(oe,J,T,F,ge),v),ue=g.ensureLoaded!==!1,_e=ve.transformEntryForSelect(J,T,F,v,ue,!0),re=ve.transformToOrderedSelect(he,J,W,T,F,_e);return(g.offset||g.limit!==void 0)&&(re=re.slice(g.offset,g.limit!==void 0?(g.offset||0)+g.limit:void 0)),re.onDone=()=>{re.onDone=null,C.doneReadTxn()},re.selectApplied=!0,re.getColumns=()=>{if(J){let oe=[];for(let ge of J)ge==="*"?oe.push(...S.map(me=>me.name)):oe.push(ge.name||ge);return oe}return S.filter(oe=>!oe.computed&&!oe.relationship).map(oe=>oe.name)},re}static transformToOrderedSelect(g,T,C,P,O,B){let v=new o_;if(C){g=fm(g,T,P,O,null);let A;v.iterate=function(){let N,L=g[Symbol.asyncIterator]?g[Symbol.asyncIterator]():g[Symbol.iterator](),$,W=C.dbOrderedAttribute,J,F,he=!0;function ue(re){let oe=re.next&&ue(re.next),ge=re.descending;return P.sort=re,(me,ie)=>{let Ce=Du(me,re.attribute,P),Be=Du(ie,re.attribute,P),He=ge?(0,Gl.compareKeys)(Be,Ce):(0,Gl.compareKeys)(Ce,Be);return He===0?oe?.(me,ie)||0:He}}a(ue,"createComparator");let _e=ue(C);return{async next(){let re;if(N)if(re=N.next(),re.done){if($)return v.onDone&&v.onDone(),re}else return{value:await B.call(this,re.value)};A=[],J&&A.push(J);do if(re=await L.next(),re.done){if($=!0,A.length)break;return v.onDone&&v.onDone(),re}else{let oe=re.value;if(oe?.then&&(oe=await oe),W){let ge=Du(oe,W,P);if(he)he=!1,F=ge;else if(ge!==F){F=ge,J=oe;break}}A.push(oe)}while(!0);return C.isGrouped,A.sort(_e),N=A[Symbol.iterator](),re=N.next(),re.done?(v.onDone&&v.onDone(),re):{value:await B.call(this,re.value)}},return(){return v.onDone&&v.onDone(),L.return()},throw(){return v.onDone&&v.onDone(),L.throw()}}};let U=a(N=>{if(typeof T=="object"&&Array.isArray(N.attribute))for(let L=0;L<T.length;L++){let $=T[L],W;if($.name===N.attribute[0]){for(W=$.sort||($.sort={});W.next;)W=W.next;W.attribute=N.attribute.slice(1),W.descending=N.descending}else $===N.attribute[0]&&(T[L]=W={name:$,sort:{attribute:N.attribute.slice(1),descending:N.descending}})}N.next&&U(N.next)},"applySortingOnSelect");U(C)}else v.iterate=(g[Symbol.asyncIterator]||g[Symbol.iterator]).bind(g),v=v.map(function(A){try{let U=B.call(this,A);return typeof U?.catch=="function"?U.catch(N=>{throw N.partialObject={[t]:A.key},N}):U}catch(U){throw U.partialObject={[t]:A.key},U}});return v}static transformEntryForSelect(g,T,C,P,O,B){let v;O&&I&&!(typeof g=="string"?[g]:g)?.every(N=>{let L;return typeof N=="object"?L=N.name:L=N,r[L]||L===t})&&(v=!0);let A,U=a(function(N){let L;if(T?.transaction?.stale&&(T.transaction.stale=!1),N!=null){if(L=N.deref?N.deref():N.value,!L&&(N.key===void 0||N.deref)||N.metadataFlags&kn){if(N.metadataFlags&kn&&T.replicateFrom===!1&&B&&N.residencyId)return mc.SKIP;if(N=xo(N.key??N,T,{transaction:C,lazy:g?.length<4,ensureLoaded:O},this?.isSync,$=>$),N?.then)return N.then(U.bind(this));L=N?.value}if(v&&N?.metadataFlags&(kn|Sl)||N?.expiresAt!=null&&N?.expiresAt<Date.now()){if(T.onlyIfCached)return{[t]:N.key,message:"This entry has expired"};let $=pn(N.key??N,N,T);if($?.then)return $.then(U)}}if(L==null)return B?mc.SKIP:L;if(g&&!(g[0]==="*"&&g.length===1)){let $,W=a((F,he)=>{let ue;typeof F=="object"?ue=F.name:ue=F;let _e=xr?.[ue],re;if(_e){let oe=P?.[ue];if(oe)if(oe.hasMappings){let me=_e.from?L[_e.from]:rd(N.key);re=oe.get(me),re||(re=[])}else re=oe.fromRecord?.(L);else re=_e(L,T,N,!0);let ge=a(me=>{if(_e.directReturn)return he(me,ue);if(me&&typeof me=="object"){let ie=_e.definition?.tableClass||ve;A||(A={});let Ce=A[ue]||(A[ue]=ie.transformEntryForSelect(ue===F?null:F.select||(Array.isArray(F)?F:null),T,C,oe,O));if(Array.isArray(me)){let Be=[],He=ie.transformToOrderedSelect(me,F.select,typeof F.sort=="object"&&F.sort,T,C,Ce)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),Te=a(Ct=>{for(;!Ct.done;){if(Ct?.then)return Ct.then(Te);Be.push(Ct.value),Ct=He.next()}he(Be,ue)},"nextValue"),ht=Te(He.next());ht&&($||($=[]),$.push(ht));return}else if(me=Ce.call(this,me),me?.then){$||($=[]),$.push(me.then(Be=>he(Be,ue)));return}}he(me,ue)},"handleResolvedValue");re?.then?($||($=[]),$.push(re.then(ge))):ge(re);return}else re=L[ue],re&&typeof re=="object"&&ue!==F&&(re=ve.transformEntryForSelect(F.select||F,T,C,null)({value:re}));he(re,ue)},"selectAttribute"),J;if(typeof g=="string")W(g,F=>{J=F});else if(Array.isArray(g))if(g.asArray)J=[],g.forEach((F,he)=>{F==="*"?g[he]=L:W(F,ue=>J[he]=ue)});else{J={};let F=g.forceNulls;for(let he of g)if(he==="*")for(let ue in L)J[ue]=L[ue];else W(he,(ue,_e)=>{ue===void 0&&F&&(ue=null),J[_e]=ue})}else throw new dt.ClientError("Invalid select"+g);return $?Promise.all($).then(()=>J):J}return L},"transform");return U}async subscribe(g){if(!l)throw new Error("Can not subscribe to a table without an audit log");_||ze({table:s,database:c,schemaDefined:u,attributes:S,audit:!0}),g||(g={});let T=!g.rawEvents,C=[],P=UI(ve,this.getId()??null,function(v,A,U,N){try{let L=A.getValue?.(i,T),$=A.type;if(!L&&$==="patch"&&T){let J=i.getEntry(v);J?.version===A.version?L=J.value:L=A.getValue?.(i,!0,U),$="put"}let W={id:v,localTime:U,value:L,version:A.version,type:$,beginTxn:N};C?C.push(W):(c!=="system"&&We(A.size??1,"db-message",s,null),this.send(W))}catch(L){Fe.default.error?.(L)}},g.startTime||0,g),O=(async()=>{this.isCollection&&(P.includeDescendants=!0,g.onlyChildren&&(P.onlyChildren=!0)),g.supportsTransactions&&(P.supportsTransactions=!0);let v=this.getId(),A=g.previousCount;A>1e3&&(A=1e3);let U=g.startTime;if(this.isCollection){if(U){if(A)throw new dt.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:L}of l.getRange({start:U,exclusiveStart:!0,snapshot:!1})){let $=It(L);if($.tableId!==n)continue;let W=$.recordId;if(v==null||vq(v,W)){let J=$.getValue(i,T,N);if(B({id:W,localTime:N,value:J,version:$.version,type:$.type,size:$.size}),P.queue?.length>Lq&&await P.waitForDrain()===!1)return}P.startTime=N}}else if(A){let N=[];for(let{key:L,value:$}of l.getRange({start:"z",end:!1,reverse:!0}))try{let W=It($);if(W.tableId!==n)continue;let J=W.recordId;if(v==null||vq(v,J)){let F=W.getValue(i,T,L);if(N.push({id:J,localTime:L,value:F,version:W.version,type:W.type}),--A<=0)break}}catch(W){Fe.default.error("Error getting history entry",L,W)}for(let L=N.length;L>0;)B(N[--L]);N[0]&&(P.startTime=N[0].localTime)}else if(!g.omitCurrent){for(let{key:N,value:L,version:$,localTime:W,size:J}of i.getRange({start:v??!1,end:v==null?void 0:[v,Gl.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(L&&(B({id:N,localTime:W,value:L,version:$,type:"put",size:J}),P.queue?.length>Lq&&await P.waitForDrain()===!1))return}}else{A&&!U&&(U=0);let N=this.#r?.localTime;if(N===AI&&(i.cache?.delete(v),this.#r=i.getEntry(v),Fe.default.trace?.("re-retrieved record",N,this.#r?.localTime),N=this.#r?.localTime),Fe.default.trace?.("Subscription from",U,"from",v,N),U<N){let L=[],$=N;do{let W=l.get($);if(W){g.omitCurrent=!0;let J=It(W),F=J.getValue(i,T,$);T&&(J.type="put"),L.push({id:v,value:F,localTime:$,...J}),$=J.previousLocalTime}else break;A&&A--}while($>U&&A!==0);for(let W=L.length;W>0;)B(L[--W]);P.startTime=N}!g.omitCurrent&&this.doesExist()&&B({id:v,localTime:N,value:this.#e,version:this.#n,type:"put"})}for(let N of C)B(N);C=null})();function B(v){c!=="system"&&We(v.size??1,"db-message",s,null),P.send(v)}return a(B,"send"),g.listener&&P.on("data",g.listener),P}static subscribeOnThisThread(g,T){return g===0||T?.crossThreads===!1}doesExist(){return!!(this.#e||this.#s)}publish(g,T,C){if(T===void 0||T instanceof URLSearchParams)this._writePublish(this.getId(),g,T);else{let P=!0,O=this.getContext();return g.checkPermission&&(P=this.allowCreate(O.user,g,O)),Gs(P,B=>{if(!B)throw new dt.AccessViolation(O.user);let v=Ls(g);this._writePublish(v,T,C)})}}_writePublish(g,T,C){let P=Br(this.getContext());g??=null,g!==null&&ki(g);let O=this.getContext();P.addWrite({key:g,store:i,entry:this.#r,nodeName:O?.nodeName,validate:a(()=>{O?.source||(P.checkOverloaded(),this.validate(T))},"validate"),before:Ne.publish?.bind(this,O,g,T),beforeIntermediate:Mu(T,Ke.publish?.bind(this,O,g,T)),commit:a((B,v,A)=>{v===void 0&&R&&!_&&qa(),Fe.default.trace?.(`Publishing message to id: ${g}, timestamp: ${new Date(B).toISOString()}`),y(g,v?.value??null,v,v?.version||B,0,!0,{user:O?.user,residencyId:C?.residencyId,expiresAt:O?.expiresAt,nodeId:C?.nodeId,tableToTrack:s},"message",!1,T)},"commit")})}validate(g,T){let C,P=a((O,B,v)=>{if(B.type&&O!=null)if(T&&O.__op__&&(O=O.value),B.properties){typeof O!="object"&&(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be an object${B.type?" ("+B.type+")":""}`);let A=B.properties;for(let U=0,N=A.length;U<N;U++){let L=A[U];if(L.relationship||L.computed){g.hasOwnProperty(L.name)&&(C||(C=[])).push(`Computed property ${v}.${L.name} may not be directly assigned a value`);continue}let $=P(O[L.name],L,v+"."+L.name);$&&(O[L.name]=$)}if(B.sealed&&O!=null&&typeof O=="object")for(let U in O)A.find(N=>N.name===U)||(C||(C=[])).push(`Property ${U} is not allowed within object in property ${v}`)}else switch(B.type){case"Int":(typeof O!="number"||O>>0!==O)&&(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof O!="number"||!(Math.floor(O)===O&&Math.abs(O)<=9007199254740992))&&(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof O!="number"&&(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be a number`);break;case"ID":typeof O=="string"||O?.length>0&&O.every?.(A=>typeof A=="string")||(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be a string, or an array of strings`);break;case"String":typeof O!="string"&&(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be a string`);break;case"Boolean":typeof O!="boolean"&&(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be a boolean`);break;case"Date":if(!(O instanceof Date)){if(typeof O=="string"||typeof O=="number")return new Date(O);(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be a Date`)}break;case"BigInt":if(typeof O!="bigint"){if(typeof O=="string"||typeof O=="number")return BigInt(O);(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be a bigint`)}break;case"Bytes":if(!(O instanceof Uint8Array)){if(typeof O=="string")return Buffer.from(O);(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be a Buffer or Uint8Array`)}break;case"Blob":if(!(O instanceof vs)){if(typeof O=="string"&&(O=Buffer.from(O)),O instanceof Buffer)return createBlob(O,{type:"text/plain"});(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be a Blob`)}break;case"array":if(Array.isArray(O)){if(B.elements)for(let A=0,U=O.length;A<U;A++){let N=O[A],L=P(N,B.elements,v+"[*]");L&&(O[A]=L)}}else(C||(C=[])).push(`Value ${qs(O)} in property ${v} must be an Array`);break}B.nullable===!1&&O==null&&(C||(C=[])).push(`Property ${v} is required (and not does not allow null values)`)},"validateValue");for(let O=0,B=S.length;O<B;O++){let v=S[O];if(v.relationship||v.computed){Object.hasOwn(g,v.name)&&(C||(C=[])).push(`Computed property ${v.name} may not be directly assigned a value`);continue}if(!T||v.name in g){let A=P(g[v.name],v,v.name);A!==void 0&&(g[v.name]=A)}}if(f)for(let O in g)S.find(B=>B.name===O)||(C||(C=[])).push(`Property ${O} is not allowed`);if(C)throw new dt.ClientError(C.join(". "))}getUpdatedTime(){return this.#n}wasLoadedFromSource(){return I?!!this.#i:void 0}static async addAttributes(g){let T=S.slice(0);for(let C of g){if(!C.name)throw new dt.ClientError("Attribute name is required");if(C.name.match(/[`/]/))throw new dt.ClientError("Attribute names cannot include backticks or forward slashes");Hae(C.name),T.push(C)}return ze({table:s,database:c,schemaDefined:u,attributes:T}),ve.indexingOperation}static async removeAttributes(g){let T=S.filter(C=>!g.includes(C.name));return ze({table:s,database:c,schemaDefined:u,attributes:T}),ve.indexingOperation}static getSize(){let g=i.getStats();return(g.treeBranchPageCount+g.treeLeafPageCount+g.overflowPages)*g.pageSize}static getAuditSize(){let g=l?.getStats();return g&&(g.treeBranchPageCount+g.treeLeafPageCount+g.overflowPages)*g.pageSize}static getStorageStats(){let g=i.env.path,T=jN.default.statfsSync?.(g)??{};return{available:T.bavail*T.bsize,free:T.bfree*T.bsize,size:T.blocks*T.bsize}}static async getRecordCount(g){let T=i.getStats().entryCount,C=1e3/2,P=performance.now(),O=Math.floor(T/2),B=g?.exactCount,v=0,A=0,U;for(let{value:N}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(N!=null&&v++,A++,await fc(),!B&&A<O&&performance.now()-P>C){U=A;break}if(U){let N=v;v=0;for(let{value:re}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:U,snapshot:!1}))re!=null&&v++,await fc();let L=U*2,$=(v+N)/L,W=Math.pow((v-N+1)/U/2,2)+$*(1-$)/L,J=Math.max(Math.sqrt(W)*T,1),F=Math.round($*T),he=Math.max(F-1.96*J,v+N),ue=Math.min(F+1.96*J,T),_e=Math.pow(10,Math.round(Math.log10(J)));return _e>F&&(_e=_e/10),v=Math.round(F/_e)*_e,{recordCount:v,estimatedRange:[Math.round(he),Math.round(ue)]}}return{recordCount:v}}static updatedAttributes(){xr=this.propertyResolvers={$id:a((g,T,C)=>({value:C.key}),"$id"),$updatedtime:a((g,T,C)=>C.version,"$updatedtime"),$updatedTime:a((g,T,C)=>C.version,"$updatedTime"),$expiresAt:a((g,T,C)=>C.expiresAt,"$expiresAt"),$record:a((g,T,C)=>C?{value:g}:g,"$record"),$distance:a((g,T,C)=>C&&(C.distance??T?.vectorDistances?.get(C)),"$distance")};for(let g of this.attributes){g.isPrimaryKey&&(H=g),g.resolve=null;let T=g.relationship,C=g.computed;if(T)if(g.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),C&&console.error("A relationship property is already computed and can not be combined with a computed function (the relationship will be given precedence)"),Pu=!0,T.to)g.elements?.definition?(xr[g.name]=g.resolve=(P,O,B,v)=>{let A=P[T.from?T.from:t],U=g.elements.definition.tableClass;return v?td({attribute:T.to,value:A},Br(O).getReadTxn(),!1,U,!1).map(N=>N&&N.key!==void 0?N:U.primaryStore.getEntry(N,{transaction:Br(O).getReadTxn()})).asArray:U.search([{attribute:T.to,value:A}],O).asArray},g.set=()=>{},g.resolve.definition=g.elements.definition,g.resolve.to=T.to,T.from&&(g.resolve.from=T.from)):console.error(`The one-to-many/many-to-many relationship property "${g.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(T.from){let P=g.definition||g.elements?.definition;P?(xr[g.name]=g.resolve=(O,B,v,A)=>{let U=O[T.from];if(U===void 0)return;if(g.elements){let L,$=U?.map(W=>{let J=P.tableClass.primaryStore[A?"getEntry":"get"](W,{transaction:Br(B).getReadTxn()});return J?.then&&(L=!0),ve.loadAsInstance===!1&&Object.freeze(A?J?.value:J),J});return T.filterMissing?L?Promise.all($).then(W=>W.filter(Mq)):$.filter(Mq):L?Promise.all($):$}let N=P.tableClass.primaryStore[A?"getEntry":"get"](U,{transaction:Br(B).getReadTxn()});return ve.loadAsInstance===!1&&Object.freeze(A?N?.value:N),N},g.set=(O,B)=>{if(Array.isArray(B)){let v=B.map(A=>A.getId?.()||A[P.tableClass.primaryKey]);O[T.from]=v}else{let v=B.getId?.()||B[P.tableClass.primaryKey];O[T.from]=v}},g.resolve.definition=g.definition||g.elements?.definition,g.resolve.from=T.from):console.error(`The relationship property "${g.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${g.name}" in table "${s}" must use either "from" or "to" arguments`);else if(C)typeof C.from=="function"&&this.setComputedAttribute(g.name,C.from),xr[g.name]=g.resolve=(P,O,B)=>{let v=typeof C.from=="string"?P[C.from]:P,A=this.userResolvers[g.name];if(A)return A(v,O,B);Fe.default.warn(`Computed attribute "${g.name}" does not have a function assigned to it. Please use setComputedAttribute('${g.name}', resolver) to assign a resolver function.`),this.userResolvers[g.name]=()=>{}},g.resolve.directReturn=!0;else if(r[g.name]?.customIndex?.propertyResolver){let P=r[g.name].customIndex;xr[g.name]=(O,B,v)=>{let A=O[g.name];return P.propertyResolver(A,B,v)},xr[g.name].directReturn=!0}}Op(this,this),Op(lm,this,!0);for(let g of S){let T=g.name;g.resolve&&(Object.defineProperty(i.encoder.structPrototype,T,{get(){return g.resolve(this,sd.getStore())},set(C){return g.set(this,C)},configurable:!0,enumerable:g.enumerable}),g.enumerable&&!i.encoder.structPrototype.toJSON&&Object.defineProperty(i.encoder.structPrototype,"toJSON",{configurable:!0,value(){let C={};for(let P in this)C[P]=this[P];return C}}))}}static setComputedAttribute(g,T){let C=Wi(S,g);if(!C){console.error(`The attribute "${g}" does not exist in the table "${s}"`);return}if(!C.computed){console.error(`The attribute "${g}" is not defined as computed in the table "${s}"`);return}this.userResolvers[g]=T}static async deleteHistory(g=0,T=!1){let C;for(let{key:P,value:O}of l.getRange({start:0,end:g}))await fc(),It(O).tableId===n&&(C=ug(l,P,O));if(T)for(let P of i.getRange({start:0,versions:!0})){let{key:O,value:B,localTime:v}=P;await fc(),B===null&&v<g&&(C=gl(i,P))}await C}static async*getHistory(g=0,T=1/0){for(let{key:C,value:P}of l.getRange({start:g||1,end:T})){await fc();let O=It(P);O.tableId===n&&(yield{id:O.recordId,localTime:C,version:O.version,type:O.type,value:O.getValue(i,!0,C),user:O.user,operation:O.originatingOperation})}}static async getHistoryOfRecord(g){let T=[];if(g==null)throw new Error("An id is required");let C=i.getEntry(g);if(!C)return T;let P=C.localTime;if(!P)throw new Error("The entry does not have a local audit time");let O=0;do{await fc();let B=l.get(P);if(B){let v=It(B);T.push({id:v.recordId,localTime:P,version:v.version,type:v.type,value:v.getValue(i,!0,P),user:v.user}),P=v.previousLocalTime}else break}while(O<1e3&&P);return T.reverse()}static cleanup(){Y?.remove()}}let c_=_S(async(K,g,T)=>{for(let C of ve.sources)if(C.get&&(!C.get.reliesOnPrototype||C.prototype.get)){if(C.available?.(T)===!1)continue;g.source=C;let P=await C.get(K,g);if(P)return P}},()=>{throw new dt.ServerError("Service unavailable, exceeded request queue limit for resolving cache record",503)});ve.updatedAttributes();let Yb=ve.prototype;return h&&ve.setTTLExpiration(h/1e3),z&&l_(),ve;function Lu(K,g,T){let C;for(let P in r){let O=r[P],B=O.isIndexing,v=xr[P],A=T&&(v?v(T):T[P]),U=g&&(v?v(g):g[P]);if(A===U&&!B)continue;if(O.customIndex){O.customIndex.index(K,A,U);continue}C=!0;let N=O.indexNulls,L=(0,jp.getIndexedValues)(A,N),$=(0,jp.getIndexedValues)(U,N);if($?.length>0){let W=new Set($);if(L=L?L.filter(J=>{if(W.has(J))W.delete(J);else return!0}):[],$=Array.from(W),($.length>0||L.length>0)&&Cq){let J=$.concat(L).map(F=>({key:F,value:K}));O.prefetch(J,Dq)}for(let J=0,F=$.length;J<F;J++)O.remove($[J],K)}else L?.length>0&&Cq&&O.prefetch(L.map(W=>({key:W,value:K})),Dq);if(L)for(let W=0,J=L.length;W<J;W++)O.put(L[W],K)}return C}a(Lu,"updateIndices");function ki(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>Pq)throw new Error("Primary key size is too large: "+K.length);break;case"object":if(K===null)throw new Error("Invalid primary key of null");break;case"bigint":if(K<2n**64n&&K>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof K)}if((0,Gl.writeKey)(K,Wae,0)>Pq)throw new Error("Primary key size is too large: "+K.length);return!0}a(ki,"checkValidId");function Ls(K){return typeof K=="object"&&K?K.id:K}a(Ls,"requestTargetToId");function um(K){return typeof K=="object"&&K&&K.isCollection}a(um,"isSearchTarget");function dm(K){}a(dm,"isRequestTarget");function xo(K,g,T,C,P){if(ve.getResidencyById&&T.ensureLoaded&&g?.replicateFrom!==!1){let B=$a(ve.getResidencyById(K));if(B&&!B.includes(server.hostname)&&w)return w({key:K,residency:B}).then(P)}let O=a(()=>{if(g?.transaction?.stale&&(g.transaction.stale=!1),T.transaction?.isDone)return P(null,K);let B=i.getEntry(K,T);return(c!=="system"||s==="hdb_analytics")&&(Bq.default.trace?.("Recording db-read action for",`${c}.${s}`),We(B?.size??1,"db-read",s,null)),g?._freezeRecords&&Object.freeze(B?.value),B?.residencyId&&B.metadataFlags&kn&&w&&T.ensureLoaded&&g?.replicateFrom!==!1?w(B).then(v=>P(v,K),v=>(Fe.default.error?.("Error loading remote record",K,B,T,v),P(null,K))):(B&&g&&(B?.version>(g.lastModified||0)&&(g.lastModified=B.version),B?.localTime&&!g.lastRefreshed&&(g.lastRefreshed=B.localTime)),P(B,K))},"whenPrefetched");return C?O():te>0?(te--,O()):new Promise((B,v)=>{te===0?(te--,i.prefetch([K],()=>{A(),U()})):(ce.push(K),de.push(U),ce.length>a_&&(te--,A()));function A(){if(ce.length>0){let N=de;i.prefetch(ce,()=>{te===-1?A():te++;for(let L of N)L()}),ce=[],de=[],Se>2&&Se--}else te=Se,Se<cm&&Se++}a(A,"prefetch");function U(){try{B(O())}catch(N){v(N)}}a(U,"load")})}a(xo,"loadLocalRecord");function Dn(K,g){let T=g?.checkPermission;if(typeof T!="object"){if(!K?.role)return;T=K.role.permission}if(T.super_user)return jae;let C=T[c],P,O=C?.tables;if(O)return O[s];if(c==="data"&&(P=T[s])&&!P.tables)return P}a(Dn,"getTablePermissions");function pn(K,g,T,C){if(I){let P=!1;if(T.noCache?P=!0:(g?(!g.value||g.metadataFlags&(kn|Sl)||g.expiresAt!=null&&g.expiresAt<Date.now())&&(P=!0):P=!0,tn(!P,"cache-hit",s)),P){let O=vu(K,g,T).then(B=>(B?.value&&B?.value.getRecord?.()&&Fe.default.error?.("Can not assign a record that is already a resource"),T&&(B?.version>(T.lastModified||0)&&(T.lastModified=B.version),T.lastRefreshed=Date.now()),B));if(T?.onlyIfCached||g?.value&&C?.allowStaleWhileRevalidate?.(g,K)){if(O.catch(B=>Fe.default.warn?.(B)),T?.onlyIfCached&&!C.doesExist())throw new dt.ServerError("Entry is not cached",504);return}else return O}}else if(g?.value&&g.expiresAt!=null&&g.expiresAt<Date.now())return ve.evict(g.key,g.value,g.version),g.value=null,{then(P){return P(g)}}}a(pn,"ensureLoadedFromSource");function Br(K){let g=K?.transaction;if(g){if(!g.lmdbDb)return g.lmdbDb=i,g;do{if(g.lmdbDb?.path===i.path)return g;let T=g.next;if(!T)return g=g.next=new ko,g.lmdbDb=i,g;g=T}while(!0)}else return new q_}a(Br,"txnForContext");function Du(K,g,T){if(!K)return;let C=(K.deref?K.deref():K.value)??i.getEntry(K.key)?.value;if(typeof g=="object"){let O=xr,B=C;for(let v=0,A=g.length;v<A;v++){let U=g[v],N=O?.[U];B=N&&B?N(B,T,K):B?.[U],K=null,O=N?.definition?.tableClass?.propertyResolvers}return B}let P=xr[g];return P?P(C,T,K):C[g]}a(Du,"getAttributeValue");function fm(K,g,T,C,P){let O=P?.length,B={transaction:C,lazy:O>0||typeof g=="string"||g?.length<4,alwaysPrefetch:!0},v;function A(U,N){let L=U?.value;if(!L)return mc.SKIP;for(let $=0;$<O;$++)if(!v?.includes($)&&!P[$](L,U))return mc.SKIP;return N!==void 0&&(U.key=N),U}if(a(A,"processEntry"),O>0||!K.hasEntries){let U=K.map(N=>{if(v=null,typeof N=="object"&&N?.key!==void 0)return O>0?A(N):N;if(N==null)return mc.SKIP;for(let L=0;L<O;L++){let W=P[L].idFilter;if(W){if(!W(N))return mc.SKIP;v||(v=[]),v.push(L)}}return xo(N,T,B,!1,A)});return Array.isArray(K)&&(U=U.filter(N=>N!==mc.SKIP)),U.hasEntries=!0,U}return K}a(fm,"transformToEntries");function Fr(K,g,T=server.replication?.getThisNodeId(l)){if(K<=g?.version){if(g?.version===K&&T!==void 0){let C=server.replication?.exportIdMapping(l),P=g.localTime,O=P&&l.get(P);if(O){let B,v,A=It(O);for(let U in C)C[U]===T&&(B=U),C[U]===A.nodeId&&(v=U);if(B>v)return 1;if(B===v)return 0}}return-1}return 1}a(Fr,"precedesExistingVersion");async function vu(K,g,T){let C=g?.metadataFlags,P=g?.version,O,B;if(!i.attemptLock(K,P,()=>{clearTimeout(B);let N=i.getEntry(K);!N||!N.value||N.metadataFlags&(kn|Sl)?O(vu(K,i.getEntry(K),T)):O(N)}))return new Promise(N=>{O=N,B=setTimeout(()=>{i.unlock(K,P)},Kae)});let v=g?.value,A={requestContext:T,replacingRecord:v,replacingEntry:g,replacingVersion:P,noCacheStore:!1,source:null,resourceCache:T?.resourceCache,transaction:void 0,expiresAt:void 0,lastModified:void 0},U=T?.responseHeaders;return new Promise((N,L)=>{let $;Gs(At(A,async W=>{let J=performance.now(),F,he,ue;try{F=await c_(K,A,g),ue=C&kn;let re=A.lastModified||ue&&P;re||(re=(0,jp.getNextMonotonicTime)()),he=ue||re>P||!v;let oe=performance.now()-J;if(We(oe,"cache-resolution",s,null,"success"),U&&Yp(U,"Server-Timing",`cache-resolve;dur=${oe.toFixed(2)}`,!0),W.timestamp=re,h&&A.expiresAt==null&&(A.expiresAt=Date.now()+h),F){if(typeof F!="object")throw new Error("Only objects can be cached and stored in tables");if(F.status>0&&F.headers)if(F.status>=300)if(F.status===304)F=v,re=P;else throw new dt.ServerError(F.body||"Error from source",F.status);else F=F.body;typeof F.toJSON=="function"&&(F=F.toJSON()),t&&F[t]!==K&&(F[t]=K)}$=!0,N({key:K,version:re,value:F})}catch(re){re.message+=` while resolving record ${K} for ${s}`,v&&((re.code==="ECONNRESET"||re.code==="ECONNREFUSED"||re.code==="EAI_AGAIN")&&!T?.mustRevalidate||T?.staleIfError&&(re.statusCode===500||re.statusCode===502||re.statusCode===503||re.statusCode===504))?(N({key:K,version:P,value:v}),Fe.default.trace?.(re.message,"(returned stale record)")):L(re);let oe=performance.now()-J;We(oe,"cache-resolution",s,null,"fail"),U&&Yp(U,"Server-Timing",`cache-resolve;dur=${oe.toFixed(2)}`,!0),A.transaction.abort();return}if(T?.noCacheStore||A.noCacheStore){A.transaction.abort();return}Br(A).addWrite({key:K,store:i,entry:g,nodeName:"source",before:Mu(F),commit:a((re,oe)=>{if(oe?.version!==P)return;let ge=Lu(K,v,F);if(F){Ke.put?.(A,K,F),oe&&(T.previousResidency=ve.getResidencyRecord(oe.residencyId));let me,ie=!1,Ce,Be=$a(ve.getResidency(F,T));if(Be){if(!Be.includes(server.hostname))if(me=F,ie=!0,ve.getResidencyById)F=void 0;else{F=null;for(let He in r)F||(F={}),F[He]=me[He]}Ce=Jc(Be)}Fe.default.trace?.(`Writing resolved record from source with id: ${K}, timestamp: ${new Date(re).toISOString()}`),y(K,F,oe,re,ie?kn:0,_&&(he||ie)||null,{user:A?.user,expiresAt:A.expiresAt,residencyId:Ce,tableToTrack:s},"put",!!ue,me)}else oe&&(Ke.delete?.(A,K),Fe.default.trace?.(`Deleting resolved record from source with id: ${K}, timestamp: ${new Date(re).toISOString()}`),_||R?y(K,null,oe,re,0,_&&he||null,{user:A?.user,tableToTrack:s},"delete",!!ue):gl(i,oe,P))},"commit")})}),()=>{i.unlock(K,P)},W=>{i.unlock(K,P),$&&Fe.default.error?.("Error committing cache update",W)})})}a(vu,"getFromSource");function Ga(K){if(!K||K.user?.role?.permission?.super_user)return!0;if(K.replicateTo)throw new dt.ClientError("Can not specify replication parameters without super user permissions",403);if(K.replicatedConfirmation)throw new dt.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}a(Ga,"checkContextPermissions");function qa(K){let g=!1;if(K&&(K-Ir>1&&(g=!0),Ir=K),!($e===nr&&!g)&&(nr=$e,(0,kl.getWorkerIndex)()===(0,kl.getWorkerCount)()-1))return zr&&clearTimeout(zr),$e?new Promise(T=>{let C=new Date;C.setMonth(0),C.setDate(1),C.setHours(0),C.setMinutes(0),C.setSeconds(0);let P=$e/(1+Ir),O=g?Date.now():Math.ceil((Date.now()-C.getTime())/P)*P+C.getTime(),B=a(v=>{Fe.default.trace?.(`Scheduled next cleanup scan at ${new Date(v)}`),zr=setTimeout(()=>X=X.then(async()=>{if(B(Math.max(v+$e,Date.now())),i.rootStore.status!=="open"){clearTimeout(zr);return}let A=50,U=new Array(A),N=0,L=Math.pow(Ir,8)*(Hl.get(x.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),$=E/Math.pow(Math.max(Ir,1),4);Fe.default.debug?.(`Starting cleanup scan for ${s}, evict threshold ${L}, adjusted eviction ${$}ms`);function W(J,F,he,ue){let _e=J+$-Date.now();if(_e<0)return!0;if(Ir){let re=i.lastSize;return he&Zr&&al(ue,oe=>{oe.size&&(re+=oe.size)}),Fe.default.trace?.(`shouldEvict adjusted ${_e} ${re}, ${_e*(J-F)/re} < ${L}`),_e*(J-F)/re<L}return!1}a(W,"shouldEvict");try{let J=0;for(let F of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:he,value:ue,version:_e,expiresAt:re,metadataFlags:oe}=F,ge;ue===null&&!_&&_e+Vae<Date.now()?ge=gl(i,F,_e):re!=null&&W(re,_e,oe,ue)&&(ge=ve.evict(he,ue,_e),J++),ge&&(await U[N],U[N]=ge.catch(me=>{Fe.default.error?.("Cleanup error",me)}),++N>=A&&(N=0)),await fc()}Fe.default.debug?.(`Finished cleanup scan for ${s}, evicted ${J} entries`)}catch(J){Fe.default.warn?.(`Error in cleanup scan for ${s}:`,J)}T(void 0),Ir=0}),Math.min(v-Date.now(),2147483647)).unref()},"startNextTimer");B(O)}):void 0}a(qa,"scheduleCleanup");function mm(){Y=l?.addDeleteRemovalCallback(n,i,(K,g)=>{i.remove(K,g)})}a(mm,"addDeleteRemoval");function l_(){(0,kl.getWorkerIndex)()===0&&setInterval(async()=>{if(!zc){zc=!0;try{let K=z.name,g=r[K];if(!g)throw new Error(`expiresAt attribute ${z} must be indexed`);for(let T of g.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let C of g.getValues(T)){let P=i.getEntry(C);P?.value?P.value[K]<Date.now()&&ve.evict(C,P.value,P.version):i.ifVersion(C,P?.version,()=>g.remove(T,C))}await fc()}}catch(K){Fe.default.error?.("Error in evicting old records",K)}finally{zc=!1}}},$ae).unref()}a(l_,"runRecordExpirationEviction");function $a(K){if(K!=null){if(Array.isArray(K))return K;if(typeof K=="number"){if(K>=65536)throw new Error(`Shard id ${K} must be below 65536`);let g=server.shards?.get?.(K);if(g)return Fe.default.trace?.(`Shard ${K} mapped to ${g.map(T=>T.name).join(", ")}`),g.map(T=>T.name);throw new Error(`Shard ${K} is not defined`)}throw new Error(`Shard or residency list ${K} is not a valid type, must be a shard number or residency list of node hostnames`)}}a($a,"residencyFromFunction");function Jc(K){if(K){let g=K.join(","),T=d.get([Symbol.for("residency_by_set"),g]);return T||(d.put([Symbol.for("residency_by_set"),g],T=Math.floor(Math.random()*2147418112)+65535),d.put([Symbol.for("residency_by_id"),T],K),T)}}a(Jc,"getResidencyId");function Mu(K,g){let T=jA(K,i.rootStore);if(T){let C=g;return C?async()=>{await C(),await T}:()=>T}return g}a(Mu,"preCommitBlobsForRecordBefore")}function WN(e,t){let r=e.attr_object||(e.attr_object={}),n=r[t];if(n)return n;n=r[t]=Object.create(null);for(let s of e)n[s.attribute_name]=s[t];return n}function Dq(){}function SS(e,t){let r=t?.type;if(e===null)return e;if(e===""&&r&&r!=="String"&&r!=="Any")return null;try{switch(r){case"Int":case"Long":if(e[0]==="$")return gS(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return gS(+e);case"Float":return e==="null"?null:gS(+e);case"BigInt":return e==="null"?null:BigInt(e);case"Boolean":return(0,Cd.autoCastBooleanStrict)(e);case"Date":if(isNaN(e)){if(e==="null")return null;zae.test(e)||(e+="Z");let n=new Date(e);return gS(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,Cd.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function gS(e){if(isNaN(e))throw new SyntaxError;return e}function vq(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t||t.startsWith?.(e);if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let n=0;n<r;n++)if(t[n]!==e[n])return!1;return!0}return!1}else if(t[0]===e)return!0}function Gs(e,t,r){return e?.then?e.then(t,r):t(e)}function Mq(e){return e!=null}function qs(e){try{return JSON.stringify(e)}catch{return e}}function Jae(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var mc,jp,Uq,xq,Hl,dt,zp,Jp,Fe,Gl,kl,Cd,jN,Bq,kae,Hae,Gae,qae,$ae,Vae,Cq,Kae,Oq,Yae,kn,Sl,Wae,Pq,Lq,jae,CUe,zae,fc,Cg=se(()=>{G();mc=require("lmdb"),jp=b(xn()),Uq=b(require("lodash")),xq=b(Um());ji();Bm();Hl=b(fe());xI();dt=b(Ee()),zp=b(Xo()),Jp=b(us());Oe();Ng();Fe=b(sr());Vw();za();Gl=require("ordered-binary"),kl=b(st());qi();Cd=b(ae());pl();os();Y_();Wp();jN=b(require("node:fs"));is();og();Bq=b(Q());YN();({sortBy:kae}=Uq.default),{validateAttribute:Hae}=xq.default,Gae=new Uint8Array(9);Gae[8]=192;qae=1/0,$ae=6e4,Vae=864e5;Hl.initSync();Cq=Hl.get(x.STORAGE_PREFETCHWRITES),Kae=1e4,Oq=1,Yae=2,kn=1,Sl=8,Wae=Buffer.allocUnsafeSlow(8192),Pq=1978,Lq=100,jae={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},CUe=(0,Cd.convertToMS)(Hl.get(x.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(TS,"makeTable");a(WN,"attributesAsObject");a(Dq,"noop");zae=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(SS,"coerceType");a(gS,"rejectNaN");a(vq,"isDescendantId");fc=a(()=>new Promise(setImmediate),"rest");a(Gs,"when");a(Mq,"exists");a(qs,"stringify");a(Jae,"hasOtherProcesses")});function yS(e,t){if(!Array.isArray(e)||!Array.isArray(t))throw new Error("Euclidean distance comparison requires an array");let r=0,n=Math.max(e.length,t.length);for(let s=0;s<n;s++){let i=e[s]||0,o=t[s]||0,c=i-o;r+=c*c}return r}function RS(e,t){if(!Array.isArray(e)||!Array.isArray(t))throw new Error("Cosine distance comparison requires an array");let r=0,n=0,s=0,i=Math.max(e.length,t.length);for(let o=0;o<i;o++){let c=e[o]||0,l=t[o]||0;r+=c*l,n+=c*c,s+=l*l}return n=Math.sqrt(n),s=Math.sqrt(s),1-r/(n*s||1)}var kq=se(()=>{a(yS,"euclideanDistance");a(RS,"cosineDistance")});var Hq,Gq,Pd,co,Od,Qae,Xae,bS,qq=se(()=>{kq();Hq=require("msgpackr"),Gq=b(sr()),Pd=b(Ee()),co=(0,Gq.loggerWithTag)("HNSW"),Od=Symbol.for("entryPoint"),Qae=Symbol.for("key"),Xae=10,bS=class{static{a(this,"HierarchicalNavigableSmallWorld")}static useObjectStore=!0;indexStore;M=16;efConstruction=100;efConstructionSearch=50;mL=1/Math.log(this.M);optimizeRouting=.5;nodesVisitedCount=0;idIncrementer;distance;constructor(t,r){this.indexStore=t,t&&(this.indexStore.encoder.useFloat32=Hq.FLOAT32_OPTIONS.ALWAYS),this.distance=r?.distance==="euclidean"?yS:RS,r&&(r.M!==void 0&&(this.M=r.M,this.mL=1/Math.log(this.M)),r.efConstruction!==void 0&&(this.efConstruction=this.efConstructionSearch=r.efConstruction),r.efConstructionSearch!==void 0&&(this.efConstructionSearch=r.efConstructionSearch),r.mL!==void 0&&(this.mL=r.mL),r.optimizeRouting!==void 0&&(this.optimizeRouting=r.optimizeRouting))}index(t,r,n){let s=typeof t=="number"?[Qae,t]:t,i=this.indexStore.get(s);if(!i){if(!r)return;if(!this.idIncrementer){let f=0;for(let m of this.indexStore.getKeys({reverse:!0,limit:1,start:1/0,end:0}))typeof m=="number"&&(f=m);this.idIncrementer=new BigInt64Array([BigInt(f)+1n]),this.idIncrementer=new BigInt64Array(this.indexStore.getUserSharedBuffer("next-id",this.idIncrementer.buffer))}i=Number(Atomics.add(this.idIncrementer,0,1n)),this.indexStore.put(s,i)}let o=new Map,c,l=this.indexStore.get(Od);if(n?c={...this.indexStore.get(i)}:c={},r){let f=l&&this.indexStore.get(l);if(f==null){let E=Math.floor(-Math.log(Math.random())*this.mL),_={vector:r,level:E,primaryKey:t};for(let R=0;R<=E;R++)_[R]=[];if(this.indexStore.put(i,_),typeof i!="number")throw new Error("Invalid nodeId: "+i);co.debug?.("setting entry point to",i),this.indexStore.put(Od,i);return}let m=c.level??Math.min(Math.floor(-Math.log(Math.random())*this.mL),Xae),p=f.level;if(m>=p){if(typeof i!="number")throw new Error("Invalid nodeId: "+i);co.debug?.("setting entry point to",i),this.indexStore.put(Od,i)}for(;p>m;){let E=this.searchLayer(r,l,f,this.efConstruction,p);E.length>0&&(l=E[0].id,f=E[0].node),p--}let h=new Array(m+1);for(let E=0;E<=m;E++)h[E]=[];for(let E=Math.min(m,p);E>=0;E--){let _=this.searchLayer(r,l,f,this.efConstruction,E);_=_.slice(0,this.M<<1),_.length===0&&E===0&&co.info?.("should not have zero connections for",l);let R=h[E];for(let S=0;S<_.length;S++){let{id:y,distance:w,node:I}=_[S];if(y===i)continue;let H=[];if(this.optimizeRouting){let k=!1,z=I[E],Y=1+this.optimizeRouting*(1+.5*S/this.M);for(let ce=0;ce<z?.length;ce++){let{id:de,distance:te}=z[ce],Se=1+this.optimizeRouting*(1+.5*ce/this.M);for(let Ne=0;Ne<R.length;Ne++){let{id:Ke,distance:$e}=R[Ne];if(Ke===de){w*Y>$e+te?k=!0:te*Se>w+$e&&(H.push({fromId:Ke,toId:y}),H.push({fromId:y,toId:Ke}));break}}if(k)break}if(k)continue}else if(S>=(E>0?this.M:this.M<<1))continue;R.push({id:y,distance:w});for(let{fromId:k,toId:z}of H){let Y=d(k);Y||(Y=d(k,this.indexStore.get(k)));for(let ce=0;ce<Y[E].length;ce++)if(Y[E][ce].id===z){Object.isFrozen(Y[E])&&(Y[E]=Y[E].slice()),Y[E].splice(ce,1);break}}let X=c[E],q=X?.find(({id:k})=>k===y);if(q){let k=X?.indexOf(q);X.copied||(X=[...X],X.copied=!0,c[E]=X),X.splice(k,1)}else this.addConnection(y,d(y,I),i,E,w,d)}}this.indexStore.put(i,{vector:r,level:m,primaryKey:t,...h})}else{if(l===i){let f=c.level??0;for(let m=f;m>=0&&(l=c[m]?.[0]?.id,l===void 0);m--);if(l===void 0){let m=-1;for(let{key:p,value:h}of this.indexStore.getRange({start:0,end:1/0}))if(h.level>m){if(l=p,h.level===f)break;m=h.level}}if(l===void 0)this.indexStore.remove(Od);else{if(typeof l!="number")throw new Error("Invalid nodeId: "+l);co.debug?.("setting entry point to",l),this.indexStore.put(Od,l)}}this.indexStore.remove(i)}let u=new Map;if(c.level!==void 0)for(let f=0;f<=c.level;f++){let m=c[f];for(let{id:p}of m){let h=d(p,this.indexStore.get(p));if(h)for(let E=0;E<=f;E++)h[E]=h[E]?.filter(({id:_})=>_!==i),h[E]?.length===0&&(co.info?.("node was left orphaned, will reindex",p),u.set(h.primaryKey,h.vector))}}function d(f,m){let p=o.get(f);return!p&&m&&(p={...m},o.set(f,p)),p}a(d,"updateNode");for(let[f,m]of o)this.indexStore.put(f,m);for(let[f,m]of u)this.index(f,m,m);this.checkSymmetry(i,this.indexStore.get(i))}getEntryPoint(){let t=this.indexStore.get(Od);if(t===void 0)return;let r=this.indexStore.get(t);return{id:t,...r}}searchLayer(t,r,n,s,i,o=this.distance){let c=new Set([r]),l=[{id:r,distance:this.distance(t,n.vector),node:n}],u=[...l];for(;l.length>0;){l.sort((p,h)=>p.distance-h.distance);let d=l.shift(),f=u[u.length-1].distance;if(d.distance>f)break;let m=d.node;for(let{id:p}of m[i]||[]){if(c.has(p)||p===void 0)continue;c.add(p);let h=this.indexStore.get(p);if(!h)continue;this.nodesVisitedCount++;let E=o(t,h.vector);if(E<f||u.length<s){let _={id:p,distance:E,node:h};l.push(_),u.push(_)}}u.sort((p,h)=>p.distance-h.distance),u.length>s&&u.splice(s,u.length-s)}return u.visited=c.size,u}search({target:t,value:r,descending:n,distance:s,comparator:i}){let o=0;switch(i){case"lt":case"le":o=r;case"sort":break;default:throw new Pd.ClientError(`Can not use "${i}" comparator with HNSW`)}if(n)throw new Pd.ClientError("Can not use descending sort order with HNSW");let c;if(s==="cosine")c=RS;else if(s==="euclidean")c=yS;else{if(s)throw new Pd.ClientError("Unknown distance function");c=this.distance}if(!t)throw new Pd.ClientError("A target vector must be provided for an HNSW query");if(!Array.isArray(t))throw new Pd.ClientError("The target vector must be an array");let l=this.getEntryPoint();if(!l)return[];let u=l.id,d=[];for(let f=l.level;f>=0;f--)if(d=this.searchLayer(t,u,l,this.efConstructionSearch,f,c),d.length>0){let m=d[0];l=m.node,u=m.id}return o&&(d=d.filter(f=>f.distance<o)),d.map(f=>({key:f.node.primaryKey,distance:f.distance}))}checkSymmetry(t,r){if(!r)return;let n=0,s;for(;(s=r[n])&&s.length!==0;){for(let{id:i}of s){let o=this.indexStore.get(i);if(!o){co.info?.("could not find neighbor node",o);continue}o[n]?.find(({id:l})=>l==t)||co.info?.("asymmetry detected",o[n])}n++}}addConnection(t,r,n,s,i,o){r[s]||(r[s]=[]);let c=s===0?this.M<<1:this.M;if(this.optimizeRouting&&(c<<=2),r[s].length>=c+(c>>2)){co.debug?.("maxConnections reached, removing some connections",c);let l=[...r[s]];l.sort((f,m)=>f.distance-m.distance);let u=l.slice(0,c),d=l.slice(c);r[s]=u;for(let f of d){let m=o(f.id)??this.indexStore.get(f.id);m&&m[s]&&(m=o(f.id,m),m[s]=m[s].filter(({id:p})=>p!==t),s===0&&m[s].length===0&&co.info?.("should not remove last connection",t,n))}}r[s].find(({id:l})=>l===n)?co.debug?.("already connected",t,n):r[s]=[...r[s],{id:n,distance:i}]}validateConnectivity(t=0){let r=this.getEntryPoint(),n=new Set,s=[r.id];n.add(r.id);let i=0;for(;s.length>0;){let o=s.shift(),c=this.indexStore.get(o);for(let l=t;l<=c.level;l++)for(let{id:u}of c[l]||[])i++,n.has(u)||(n.add(u),s.push(u))}return n.size!==this.totalNodes&&console.log("visited",n.size,"total",this.totalNodes),{isFullyConnected:n.size===this.totalNodes,averageConnections:i/n.size}}get totalNodes(){return Array.from(this.indexStore.getKeys({start:0,end:1/0})).length}estimateCountAsSort(){return Math.sqrt(this.indexStore.getStats().entryCount*this.efConstructionSearch)}propertyResolver(t,r,n){let s=r?.sort;if(s){let i=s.vectorDistances;if(i){let l=i.get(n);if(l)return l}else i=r.vectorDistances=s.vectorDistances=new Map;let o=this.distance;s.type&&(o=s.distance==="euclidean"?yS:RS);let c=o(s.target,t);return i.set(n,c),c}return t}}});var zN,$q=se(()=>{qq();zN={HNSW:bS}});var pt={};ye(pt,{NON_REPLICATING_SYSTEM_TABLES:()=>AS,database:()=>Ed,databaseEnvs:()=>na,databases:()=>Me,dropDatabase:()=>zw,dropTableMeta:()=>sce,getDatabases:()=>lt,getDefaultCompression:()=>LS,getTables:()=>ece,onRemovedDB:()=>nh,onUpdatedTable:()=>ql,readMetaDb:()=>Qp,resetDatabases:()=>Ud,table:()=>ze,tables:()=>yn});function rh(e,t){let r=OS.OpenDBIObject??OS.default.OpenDBIObject;return new r(e,t)}function ece(){return CS||lt(),yn||{}}function lt(){if(CS)return Me;CS=!0,vd=new Map;let e=(0,Zt.getHdbBasePath)()&&(0,Ht.join)((0,Zt.getHdbBasePath)(),Zc),t=(0,Zt.get)(x.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Zt.get)(x.STORAGE_PATH)||e&&((0,_s.existsSync)(e)?e:(0,Ht.join)((0,Zt.getHdbBasePath)(),__)),!!e){if((0,_s.existsSync)(e))for(let r of(0,_s.readdirSync)(e,{withFileTypes:!0})){let n=(0,Ht.basename)(r.name,".mdb");r.isFile()&&(0,Ht.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&Qp((0,Ht.join)(e,r.name),null,n)}if((0,_s.existsSync)((0,Dd.getBaseSchemaPath)())){for(let r of(0,_s.readdirSync)((0,Dd.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,Ht.join)((0,Dd.getBaseSchemaPath)(),r.name),s=(0,Ht.join)((0,Dd.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,_s.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,Ht.extname)(i.name).toLowerCase()===".mdb"){let o=(0,Ht.join)(s,i.name);Qp((0,Ht.join)(n,i.name),(0,Ht.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,_s.existsSync)(s))for(let o of(0,_s.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,Ht.extname)(o.name).toLowerCase()===".mdb"&&Qp((0,Ht.join)(s,o.name),(0,Ht.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],l=(0,Ht.join)(c.path,(0,Ht.basename)(o+".mdb"));(0,_s.existsSync)(l)&&Qp(l,o,r,null,!0)}}for(let r in Me){let n=vd.get(r);if(n){let s=Me[r];r.includes("delete")&&Cr.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(Cr.trace(`delete table class ${i}`),delete s[i])}else if(delete Me[r],r==="data"){for(let s in yn)delete yn[s];delete yn[PS]}}if((0,Zt.get)(x.ANALYTICS_REPLICATE)===!1?AS.includes("hdb_analytics")||AS.push("hdb_analytics"):(Me.system?.hdb_analytics?.enableAuditing(),Me.system?.hdb_analytics_hostname?.enableAuditing()),Me.system)for(let r of AS)Me.system[r]&&(Me.system[r].replicate=!1);return vd=null,Me}}function Ud(){CS=!1;for(let[,e]of na)e.needsDeletion=!0;lt();for(let[e,t]of na)if(t.needsDeletion&&!e.endsWith("system.mdb")){t.close(),na.delete(e);let r=Me[t.databaseName];for(let n in r)if(r[n].primaryStore.path===e){delete Me[t.databaseName],Zp.forEach(i=>i(t.databaseName));break}}return Me}function Qp(e,t,r=XN,n,s){let i=new JN.default(e,!1);try{let o=na.get(e);o?o.needsDeletion=!1:(o=(0,Md.open)(i),na.set(e,o));let c=new rh(!1),l=o.dbisDb||(o.dbisDb=o.openDB(IS.INTERNAL_DBIS_NAME,c)),u=o.auditStore;u||(n?(0,_s.existsSync)(n)&&(i.path=n,u=(0,Md.open)(i),u.isLegacy=!0):u=lg(o));let d=jq(r),f=d[PS],m=new Map;for(let{key:p,value:h}of l.getRange({start:!1})){let[E,_]=p.toString().split("/");_===""?_=h.name:_||(_=E,E=t,h.name||(h.name=_,h.indexed=!h.is_hash_attribute)),f?.add(E);let R=m.get(E);R||m.set(E,R={attributes:[]}),(_==null||h.is_hash_attribute)&&(R.primary=h),_!=null&&R.attributes.push(h),Object.defineProperty(h,"key",{value:p,configurable:!0})}for(let[p,h]of m){let{attributes:E,primary:_}=h;if(!_){for(let te of E)if(te.is_hash_attribute||te.isPrimaryKey){_=te;break}if(!_){Cr.warn(`Unable to find a primary key attribute on table ${p}, with attributes: ${JSON.stringify(E)}`);continue}}let R=d[p],S={},y=[],w,I,H=typeof _.audit=="boolean"?_.audit:(0,Zt.get)(x.LOGGING_AUDITLOG),X=_.trackDeletes,q=_.expiration,k=_.eviction,z=_.sealed,Y=_.splitSegments,ce=_.replicate;if(R)S=R.indices,y=R.attributes,R.schemaVersion++;else{w=_.tableId,w?w>=(l.get(Ld)||0)&&(l.putSync(Ld,w+1),Cr.info(`Updating next table id (it was out of sync) to ${w+1} for ${p}`)):(_.tableId=w=l.get(Ld),w||(w=1),Cr.debug("Table {tableName} missing an id, assigning {tableId}"),l.putSync(Ld,w+1),l.putSync(_.key,_));let te=new rh(!_.is_hash_attribute,_.is_hash_attribute);if(te.compression=_.compression,te.compression){let Se=(0,Zt.get)(x.STORAGE_COMPRESSION_THRESHOLD)||Wq;te.compression.threshold=Se}I=bg(o.openDB(_.key,te),o),o.databaseName=r,I.tableId=w}let de;for(let te of E){te.attribute=te.name;try{if(!te.is_hash_attribute&&(te.indexed||te.attribute&&!te.name)){if(!S[te.name]){let Ne=Jq(te.key,o,te);S[te.name]=Ne,S[te.name].indexNulls=te.indexNulls}let Se=y.find(Ne=>Ne.name===te.name);Se?y.splice(y.indexOf(Se),1,te):y.push(te),de=!0}}catch(Se){Cr.error("Error trying to update attribute",te,y,S,Se)}}for(let te of y)if(!E.find(Ne=>Ne.name===te.name)){if(te.is_hash_attribute){Cr.error("Unable to remove existing primary key attribute",te);continue}te.indexed&&(y.splice(y.indexOf(te),1),de=!0)}if(R)de&&(R.schemaVersion++,R.updatedAttributes());else{R=zq(d,p,TS({primaryStore:I,auditStore:u,audit:H,sealed:z,splitSegments:Y,replicate:ce,expirationMS:q&&q*1e3,evictionMS:k&&k*1e3,trackDeletes:X,tableName:p,tableId:w,primaryKey:_.name,databasePath:s?r+"/"+p:r,databaseName:r,indices:S,attributes:E,schemaDefined:_.schemaDefined,dbisDB:l})),R.schemaVersion=1;for(let te of Xp)te(R)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function jq(e){let t=Me[e];if(t||(e==="data"?t=Me[e]=yn:e==="system"?Object.defineProperty(Me,"system",{value:t=Object.create(null),configurable:!0}):t=Me[e]=Object.create(null)),vd&&!vd.has(e)){let r=new Set;t[PS]=r,vd.set(e,r)}return t}function zq(e,t,r){return e[t]=r,r}function Ed({database:e,table:t}){e||(e=XN),lt();let r=jq(e),n=(0,Ht.join)((0,Zt.getHdbBasePath)(),Zc),s=(0,Zt.get)(x.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,Zt.get)(x.STORAGE_PATH)||((0,_s.existsSync)(n)?n:(0,Ht.join)((0,Zt.getHdbBasePath)(),__));let o=(0,Ht.join)(n,(i?t:e)+".mdb"),c=na.get(o);if(!c||c.status==="closed"){let l=new JN.default(o,!1);c=(0,Md.open)(l),na.set(o,c)}return c.auditStore||(c.auditStore=lg(c)),c}async function zw(e){if(!Me[e])throw new Error("Schema does not exist");let t=Me[e],r;for(let n in t)r=t[n].primaryStore.rootStore,na.delete(r.path),r.status==="open"&&(await r.close(),await eh.remove(r.path));if(r||(r=Ed({database:e,table:null}),r.status==="open"&&(await r.close(),await eh.remove(r.path))),e==="data"){for(let n in yn)delete yn[n];delete yn[PS]}delete Me[e],Zp.forEach(n=>n(e)),await WA(r)}function Jq(e,t,r){let n=r.is_hash_attribute||r.indexed.type&&zN[r.indexed.type]?.useObjectStore,s=new rh(!n,n),i=t.openDB(e,s);if(r.indexed.type){let o=zN[r.indexed.type];o?i.customIndex=new o(i,r.indexed):Cr.error(`The indexing type '${r.indexed.type}' is unknown`)}return i}function ze(e){let{table:t,database:r,expiration:n,eviction:s,scanInterval:i,attributes:o,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,schemaDefined:m,origin:p}=e;r||(r=XN);let h=Ed({database:r,table:t}),E=Me[r];Cr.trace(`Defining ${t} in ${r}`);let _=E?.[t];if(h.status==="closed")throw new Error(`Can not use a closed data store for ${t}`);let R,S,y;m==null&&(m=!0);let w=new rh(!1);for(let Y of o)Y.attribute&&!Y.name?(Y.name=Y.attribute,Y.indexed=!0):Y.attribute=Y.name,Y.expiresAt&&(Y.indexed=!0);let I,H;if(_){if(R=_.primaryKey,_.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${t} class`);u==null&&(u=_.splitSegments),_.attributes.splice(0,_.attributes.length,...o)}else{let Y=h.auditStore;S=o.find(Se=>Se.isPrimaryKey)||{},R=S.name,S.is_hash_attribute=S.isPrimaryKey=!0,S.schemaDefined=m,S.compression=LS(),f&&(S.trackDeletes=!0),c=S.audit=typeof c=="boolean"?c:(0,Zt.get)(x.LOGGING_AUDITLOG),n&&(S.expiration=n),s&&(S.eviction=s),u??=!1,S.splitSegments=u,typeof l=="boolean"&&(S.sealed=l),typeof d=="boolean"&&(S.replicate=d),p&&(S.origins?S.origins.includes(p)||S.origins.push(p):S.origins=[p]),Cr.trace(`${t} table loading, opening primary store`);let ce=new rh(!1,!0);ce.compression=S.compression;let de=t+"/";if(y=h.dbisDb=h.openDB(IS.INTERNAL_DBIS_NAME,w),z(),y.get(de))return H&&H(),Ud(),ze(e);let te=bg(h.openDB(de,ce),h);h.databaseName=r,te.tableId=y.get(Ld),Cr.trace(`Assigning new table id ${te.tableId} for ${t}`),te.tableId||(te.tableId=1),y.put(Ld,te.tableId+1),S.tableId=te.tableId,_=zq(E,t,TS({primaryStore:te,auditStore:Y,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:R,tableName:t,tableId:te.tableId,databasePath:r,databaseName:r,indices:{},attributes:o,schemaDefined:m,dbisDB:y})),_.schemaVersion=1,I=!0,y.put(de,S)}let X=_.indices;y=y||(h.dbisDb=h.openDB(IS.INTERNAL_DBIS_NAME,w)),_.dbisDB=y;let q=[];for(let{key:Y,value:ce}of y.getRange({start:!0})){let[de,te]=Y.toString().split("/");if(te===""&&(te=ce.name),te){if(de!==t)continue}else continue;let Se=o.find(Ke=>Ke.name===te),Ne=!Se?.indexed&&ce.indexed&&!ce.isPrimaryKey;if((!Se||Ne)&&(z(),I=!0,Se||y.remove(Y),Ne)){let Ke=_.indices[de];Ke&&q.push(Ke)}}let k=[];try{for(let Y of o||[]){if((Y.relationship||Y.computed)&&(I=!0,Y.relationship))continue;let ce=t+"/"+(Y.name||"");Object.defineProperty(Y,"key",{value:ce,configurable:!0});let de=y.get(ce);if(Y.isPrimaryKey){if(de=de||y.get(ce=t+"/")||{},c!==void 0&&c!==_.audit||l!==void 0&&l!==_.sealed||d!==void 0&&d!==_.replicate||(+n||void 0)!==(+de.expiration||void 0)||(+s||void 0)!==(+de.eviction||void 0)||Y.type!==de.type){let Se={...de};typeof c=="boolean"&&(c&&_.enableAuditing(c),Se.audit=c),n&&(Se.expiration=+n),s&&(Se.eviction=+s),l!==void 0&&(Se.sealed=l),d!==void 0&&(Se.replicate=d),Y.type&&(Se.type=Y.type),I=!0,z(),y.put(ce,Se)}continue}de?.attribute&&!de.name&&(de.indexed=!0);let te=!de||de.type!==Y.type||JSON.stringify(de.indexed)!==JSON.stringify(Y.indexed)||de.nullable!==Y.nullable||de.version!==Y.version||de.enumerable!==Y.enumerable||JSON.stringify(de.properties)!==JSON.stringify(Y.properties)||JSON.stringify(de.elements)!==JSON.stringify(Y.elements);if(Y.indexed){let Se=Jq(ce,h,Y);(te||de.indexingPID&&de.indexingPID!==process.pid||de.restartNumber<th.workerData?.restartNumber)&&(I=!0,z(),de=y.get(ce),(te||de.indexingPID&&de.indexingPID!==process.pid||de.restartNumber<th.workerData?.restartNumber)&&(I=!0,Y.indexNulls===void 0&&(Y.indexNulls=!0),_.primaryStore.getStats().entryCount>0&&(Y.lastIndexedKey=de?.lastIndexedKey??void 0,Y.indexingPID=process.pid,Se.isIndexing=!0,Object.defineProperty(Y,"dbi",{value:Se}),k.push(Y))),y.put(ce,Y)),de?.indexNulls&&Y.indexNulls===void 0&&(Y.indexNulls=!0),Se.indexNulls=Y.indexNulls,X[Y.name]=Se}else te&&(I=!0,z(),y.put(ce,Y))}}finally{H&&H()}if(I&&(_.schemaVersion++,_.updatedAttributes()),Cr.trace(`${t} table loading, running index`),k.length>0||q.length>0?_.indexingOperation=nce(_,k,q):I&&wS.signalSchemaChange(new NS.SchemaEventMsg(process.pid,"schema-change",_.databaseName,_.tableName)),_.origin=p,I)for(let Y of Xp)Y(_,p!=="cluster");return(n||s||i)&&_.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Cr.trace(`${t} table loaded`),_;function z(){H||h.transactionSync(()=>({then(Y){H=Y}}))}a(z,"startTxn")}async function nce(e,t,r){try{Cr.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await wS.signalSchemaChange(new NS.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o={},c=0,l=t.length;if(await new Promise(u=>setImmediate(u)),l>0){let u;for(let f of t)(0,Md.compareKeys)(f.lastIndexedKey,u)<0&&(u=f.lastIndexedKey),f.lastIndexedKey==null&&f.dbi.clearAsync();let d=0;for(let{key:f,value:m,version:p}of e.primaryStore.getRange({start:u,lazy:l<4,versions:!0,snapshot:!1}))if(m){if(d++,s=e.primaryStore.ifVersion(f,p,()=>{for(let h=0;h<l;h++){let E=t[h],_=E.name,R=E.dbi;try{let S=E.resolve,y=m&&(S?S(m):m[_]);if(R.customIndex){R.customIndex.index(f,y);continue}let w=(0,Vq.getIndexedValues)(y,R.indexNulls);if(w)for(let I=0,H=w.length;I<H;I++)R.put(w[I],f)}catch(S){o[_]||(o[_]=!0,Cr.error(`Error indexing attribute ${_}`,S))}}}),s.then(()=>d--,h=>{d--,Cr.error(h)}),th.workerData&&th.workerData.restartNumber!==Yq.restartNumber&&(i=!0),++c%100===0||i){for(let h of t)h.lastIndexedKey=f,e.dbisDB.put(h.key,h);if(i)return}d>tce?await s:d>rce&&await new Promise(h=>setImmediate(h))}for(let f of t)delete f.lastIndexedKey,delete f.indexingPID,f.dbi.isIndexing=!1,s=e.dbisDB.put(f.key,f)}await s,await wS.signalSchemaChange(new NS.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Cr.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Cr.error("Error in indexing",n)}}function sce({table:e,database:t}){let r=Ed({database:t,table:e}),n=[],s=r.dbisDb;for(let i of s.getKeys({start:e+"/",end:e+"0"}))n.push(s.remove(i));return Promise.all(n)}function ql(e){return Xp.push(e),{remove(){let t=Xp.indexOf(e);t>-1&&Xp.splice(t,1)}}}function nh(e){return Zp.push(e),{remove(){let t=Zp.indexOf(e);t>-1&&Zp.splice(t,1)}}}function LS(){let e=(0,Zt.get)(x.STORAGE_COMPRESSION),t=(0,Zt.get)(x.STORAGE_COMPRESSION_DICTIONARY),r=(0,Zt.get)(x.STORAGE_COMPRESSION_THRESHOLD)||Wq,n={startingOffset:32};return t&&(n.dictionary=eh.readFileSync(t)),r&&(n.threshold=r),e&&n}var Zt,IS,Md,Ht,_s,Dd,JN,eh,QN,Vq,wS,NS,th,Kq,Yq,OS,Zae,Cr,XN,PS,Wq,AS,yn,Me,Ld,Xp,Zp,CS,na,vd,tce,rce,Oe=se(()=>{Zt=b(fe()),IS=b(Jt()),Md=require("lmdb"),Ht=require("path"),_s=require("fs"),Dd=b(bt());Cg();JN=b(dp());G();eh=b(require("fs-extra")),QN=b(oi()),Vq=b(xn()),wS=b(Xo()),NS=b(us()),th=require("worker_threads"),Kq=b(Q()),Yq=b(st());qi();pl();is();$q();OS=b(up()),{forComponent:Zae}=Kq.default;a(rh,"OpenDBIObject");Cr=Zae("storage"),XN="data",PS=Symbol("defined-tables"),Wq=((0,Zt.get)(x.STORAGE_PAGESIZE)||4096)-60;(0,Zt.initSync)();AS=["hdb_temp","hdb_certificate","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_info"],yn=Object.create(null),Me=Object.create(null);(0,QN._assignPackageExport)("databases",Me);(0,QN._assignPackageExport)("tables",yn);Ld=Symbol.for("next-table-id"),Xp=[],Zp=[],na=new Map;a(ece,"getTables");a(lt,"getDatabases");a(Ud,"resetDatabases");a(Qp,"readMetaDb");a(jq,"ensureDB");a(zq,"setTable");a(Ed,"database");a(zw,"dropDatabase");a(Jq,"openIndex");a(ze,"table");tce=1e3,rce=10;a(nce,"runIndexing");a(sce,"dropTableMeta");a(ql,"onUpdatedTable");a(nh,"onRemovedDB");a(LS,"getDefaultCompression")});var tC={};ye(tC,{loadGQLSchema:()=>ace,start:()=>eC,startOnMainThread:()=>oce});function eC({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:l,NamedTypeNode:u,StringValueNode:d}=await import("graphql"),f=o(new c(r.toString(),s)),m=new Map,p=[],h;for(let R of f.definitions)switch(R.kind){case l.OBJECT_TYPE_DEFINITION:let H=function(q){if(q.kind==="NonNullType"){let Y=H(q.type);return Y.nullable=!1,Y}if(q.kind==="ListType")return{type:"array",elements:H(q.type)};let z={type:q.name?.value};return Object.defineProperty(z,"location",{value:q.loc.startToken}),z};a(H,"getProperty");let S=R.name.value,y=[],w={table:null,database:null,properties:y};m.set(S,w),i.allTypes.set(S,w);for(let q of R.directives){if(q.name.value==="table"){for(let z of q.arguments)w[z.name.value]=z.value.value;w.schema&&(w.database=w.schema),w.table||(w.table=S),w.audit&&(w.audit=w.audit!=="false"),w.attributes=w.properties,p.push(w)}if(q.name.value==="sealed"&&(w.sealed=!0),q.name.value==="splitSegments"&&(w.splitSegments=!0),q.name.value==="replicate"&&(w.replicate=!0),q.name.value==="export"){w.export=!0;for(let z of q.arguments)typeof w.export!="object"&&(w.export={}),w.export[z.name.value]=z.value.value}}let I=!1,X={};for(let q of R.fields){let k=H(q.type);k.name=q.name.value,y.push(k),X[k.name]=void 0;for(let z of q.directives){let Y=z.name.value;if(Y==="primaryKey")I?console.warn("Can not define two attributes as a primary key at",z.loc):(k.isPrimaryKey=!0,I=!0);else if(Y==="indexed"){let ce={};for(let de of z.arguments||[])ce[de.name.value]=de.value.value;k.indexed=ce}else if(Y==="computed"){for(let ce of z.arguments||[])if(ce.name.value==="from"){let de=ce.value.value;k.computed={from:_(de,ce,X)},k.version==null&&(k.version=de)}else ce.name.value==="version"&&(k.version=ce.value.value);k.computed=k.computed||!0}else if(Y==="relationship"){let ce={};for(let de of z.arguments)ce[de.name.value]=de.value.value;k.relationship=ce}else if(Y==="createdTime")k.assignCreatedTime=!0;else if(Y==="updatedTime")k.assignUpdatedTime=!0;else if(Y==="expiresAt")k.expiresAt=!0;else if(Y==="enumerable")k.enumerable=!0;else if(Y==="allow"){let ce=k.authorizedRoles=[];for(let de of z.arguments)de.name.value==="role"&&ce.push(de.value.value)}else server.knownGraphQLDirectives.includes(Y)&&console.warn(`@${Y} is an unknown directive, at`,z.loc)}}w.type=S,S==="Query"&&(h=w)}function E(R){let S=m.get(R.type);S?(Object.defineProperty(R,"properties",{value:S.properties}),Object.defineProperty(R,"definition",{value:S})):R.type==="array"?E(R.elements):ice.includes(R.type)||(0,Xq.getWorkerIndex)()===0&&console.error(`The type ${R.type} is unknown at line ${R.location.line}, column ${R.location.column}, in ${s}`)}a(E,"connectPropertyType");for(let R of m.values())for(let S of R.properties)E(S);for(let R of p)R.tableClass=e(R),R.export&&(R.export.name===""?i.set((0,ZN.dirname)(n),R.tableClass):i.set((0,ZN.dirname)(n)+"/"+(R.export.name||R.type),R.tableClass,R.export));function _(R,S,y){return new Qq.Script(`function computed(attributes) { return function(record) { with(attributes) { with (record) { return ${R}; } } } } computed;`,{filename:s,lineOffset:S.loc.startToken.line-1,columnOffset:S.loc.startToken.column}).runInThisContext()(y)}a(_,"createComputedFrom")}}var ZN,Qq,Xq,ice,oce,ace,Zq=se(()=>{ZN=require("path"),Qq=require("node:vm");Oe();Xq=b(st());rc();ice=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt","Blob"];server.knownGraphQLDirectives||(server.knownGraphQLDirectives=[]);server.knownGraphQLDirectives.push("table","sealed","export","primaryKey","indexed","computed","relationship","createdTime","updatedTime","expiresAt","allow","enumerable");a(eC,"start");oce=eC,ace=a(e=>eC({ensureTable:ze}).handleFile(e,null,null,new od),"loadGQLSchema")});var nC={};ye(nC,{start:()=>Ece});function cce(e){if(e.kind!==qe.Kind.OPERATION_DEFINITION&&e.kind!==qe.Kind.FRAGMENT_DEFINITION)throw new Vr(`Unexpected non-executable definition type ${e.kind}.`)}function e$(e){if(typeof e!="object"||e===null)throw new lo("Request body must be an object.");if(!("query"in e))throw new lo("Request body must contain a `query` field.");if(typeof e.query!="string")throw new lo("Request body `query` field must be a string.");if("variables"in e&&(typeof e.variables!="object"||e.variables===null))throw new lo("Request body `variables` field must be an object.");if("operationName"in e&&typeof e.operationName!="string")throw new lo("Request body `operationName` field must be a string.")}function rC(e){return parseInt(e.value,10)}function r$(e){return parseFloat(e.value)}function n$(e,t,r){let n=r.get(e.name.value);return s$(n)?i$(n,t):{attribute:t,value:n}}function s$(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}function i$(e,t){return t=typeof t=="string"?[t]:t,Object.entries(e).flatMap(([r,n])=>(t=[...t,r],s$(n)?i$(n,t):{attribute:t,value:n}))}function lce(e,t,r){switch(t=[...t,e.name.value],e.value.kind){case qe.Kind.NULL:return{attribute:t,value:null};case qe.Kind.INT:return{attribute:t,value:rC(e.value)};case qe.Kind.FLOAT:return{attribute:t,value:r$(e.value)};case qe.Kind.BOOLEAN:case qe.Kind.STRING:return{attribute:t,value:e.value.value};case qe.Kind.VARIABLE:return n$(e.value,t,r);case qe.Kind.OBJECT:return o$(e.value,t,r);case qe.Kind.LIST:case qe.Kind.ENUM:default:throw new Vr(`Value type, ${e.value.kind}, is not supported.`)}}function o$(e,t,r){return e.fields.flatMap(n=>lce(n,t,r))}function uce(e,t){switch(e.value.kind){case qe.Kind.NULL:return{attribute:e.name.value,value:null};case qe.Kind.INT:return{attribute:e.name.value,value:rC(e.value)};case qe.Kind.FLOAT:return{attribute:e.name.value,value:r$(e.value)};case qe.Kind.BOOLEAN:case qe.Kind.STRING:return{attribute:e.name.value,value:e.value.value};case qe.Kind.VARIABLE:return n$(e.value,e.name.value,t);case qe.Kind.OBJECT:return o$(e.value,[e.name.value],t);case qe.Kind.LIST:case qe.Kind.ENUM:default:throw new Vr(`Argument type, ${e.value.kind}, is not supported.`)}}function dce(e,t){return e.flatMap(r=>uce(r,t))}function DS(e,t){return e.selections.flatMap(r=>{switch(r.kind){case qe.Kind.FIELD:return r;case qe.Kind.FRAGMENT_SPREAD:{let n=r.name.value,s=t.get(n);if(s==null)throw new Vr(`Fragment \`${n}\` not found.`);return DS(s.selectionSet,t)}case qe.Kind.INLINE_FRAGMENT:return DS(r.selectionSet,t)}})}function a$(e,t){return DS(e,t).map(r=>r.selectionSet?.selections.length>0?{name:r.name.value,select:a$(r.selectionSet,t)}:r.name.value)}async function fce(e,t,r,n){let s=Bs.getMatch(e.name.value,"graphql");if(s===void 0)throw new Vr(`Resource \`${e.name.value}\` not found.`);let i=s.Resource,o={select:a$(e.selectionSet,r),conditions:dce(e.arguments,t)},c=[];n.authorize=!0;for await(let l of i.search(o,n))c.push(l);return[e.name.value,c]}function c$(e){switch(e.kind){case qe.Kind.NULL:return null;case qe.Kind.INT:return rC(e);case qe.Kind.FLOAT:return parseFloat(e.value);case qe.Kind.STRING:case qe.Kind.BOOLEAN:return e.value;case qe.Kind.OBJECT:return e.fields.reduce((t,r)=>({[r.name.value]:c$(r.value),...t}),{});case qe.Kind.LIST:case qe.Kind.ENUM:default:throw new Vr(`Value type, ${e.kind}, is not supported.`)}}function mce(e,t){let r=new Map;for(let n of e){let s=n.variable.name.value,i=t?.[s];if(i===void 0&&n.defaultValue!==void 0&&(i=c$(n.defaultValue)),n.type.kind===qe.Kind.NON_NULL_TYPE&&!(s in t)&&i===void 0)throw new Vr(`Variable $${s} is required, but not provided.`);r.set(n.variable.name.value,i??null)}return r}async function pce(e,t,r,n){if(e.operation===qe.OperationTypeNode.SUBSCRIPTION)throw new Vr("Subscriptions are not supported.");if(e.operation===qe.OperationTypeNode.MUTATION)throw new Vr("Mutations are not supported yet.");let s=mce(e.variableDefinitions,t),i=await Promise.all(DS(e.selectionSet,r).map(c=>fce(c,s,r,n))),o={data:{}};for(let[c,l]of i)o.data[c]=l;return o}async function t$({query:e,variables:t={},operationName:r},n){let s=qe.parse(e),i=new Map,o=new Map;for(let u of s.definitions)if(cce(u),u.kind===qe.Kind.FRAGMENT_DEFINITION)o.set(u.name.value,u);else{if(u.name===void 0&&s.definitions.length>1)throw new Vr("Unnamed operations are only allowed when there is a single operation in the document.");let d=u.name?.value??"Unnamed Query";if(i.has(d))throw new Vr(`Duplicate operation definition: ${d}`);i.set(d,u)}let c;if(r==null)if(i.size===1)c=i.entries().next().value[1];else throw new Vr("Operation name is required when there are multiple operations in the document.");else if(c=i.get(r),c==null)throw new Vr(`Operation \`${r}\` not found.`);let l=await pce(c,t,o,n);return{status:200,headers:{"Content-Type":"application/graphql-response+json; charset=utf-8"},body:JSON.stringify(l)}}async function hce(e){switch(e.method){case"GET":{let t=new URLSearchParams(e.url.split("?")[1]),r={};for(let[n,s]of t)r[n]=n==="variables"||n==="extensions"?JSON.parse(s):s;return e$(r),t$(r,e)}case"POST":{let r=await $o(e.headers.get("content-type"),!0)(e._nodeRequest);return e$(r),t$(r,e)}default:throw new lo("Method Not Allowed",405,{Allow:"GET, POST"})}}function Ece(e){e.server.http(async(t,r)=>{if(!t.url.startsWith("/graphql"))return r(t);try{return await hce(t)}catch(n){logger.error(n);let s=t.headers.get("accept")??"application/graphql-response+json";switch(s){case"application/json":{if(n instanceof lo)return{status:n.statusCode,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/json",...n.headers}};if(n instanceof qe.GraphQLError)return{status:200,body:JSON.stringify({errors:[n]}),headers:{"Content-Type":"application/json"}};if(n instanceof Vr)return{status:200,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/json"}};if(n instanceof Error)return{status:500,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/json"}};break}default:logger.info(`Unsupported accept header, ${s}, defaulting to application/graphql-response+json`);case"application/graphql-response+json":{if(n instanceof lo)return{status:n.statusCode,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/graphql-response+json",...n.headers}};if(n instanceof qe.GraphQLError)return{status:400,body:JSON.stringify({errors:[n]}),headers:{"Content-Type":"application/graphql-response+json"}};if(n instanceof Vr)return{status:400,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/graphql-response+json"}};if(n instanceof Error)return{status:500,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/graphql-response+json"}};break}}throw n}},{port:e.port,securePort:e.securePort})}var qe,Vr,lo,l$=se(()=>{qe=b(require("graphql"));Vo();rc();a(cce,"assertExecutableDefinitionNode");a(e$,"assertRequestParams");a(rC,"processIntValueNode");a(r$,"processFloatValueNode");a(n$,"processVariableNode");a(s$,"isObject");a(i$,"transformObjectIntoQueryCondition");a(lce,"processObjectFieldNode");a(o$,"processObjectValueNode");a(uce,"processArgumentNode");a(dce,"buildConditionsQuery");a(DS,"fillInFragments");a(a$,"buildSelectQuery");a(fce,"processFieldNode");a(c$,"processConstValueNode");a(mce,"resolveVariables");a(pce,"executeOperation");a(t$,"resolver");Vr=class extends Error{static{a(this,"GraphQLQueryingError")}},lo=class extends Error{static{a(this,"HTTPError")}statusCode;headers;constructor(t,r=400,n={}){super(t),this.statusCode=r,this.headers=n}};a(hce,"graphqlQueryingHandler");a(Ece,"start")});var h$=M((JUe,p$)=>{var xd=require("validate.js"),d$=mt(),Bd=(G(),D(j)),{handleHDBError:_ce,hdbErrors:gce}=Ee(),{HDB_ERROR_MSGS:ar,HTTP_STATUS_CODES:Sce}=gce,sC=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),Tce={STRUCTURE_USER:"structure_user"},u$=Object.values(Bd.ROLE_TYPES_ENUM),yce="attribute_permissions",Rce="attribute_name",{PERMS_CRUD_ENUM:Fd}=Bd,bce=[yce,...Object.values(Fd)],f$=[Fd.READ,Fd.INSERT,Fd.UPDATE],Ace=[Rce,...f$];function Ice(e){let t=sC();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,m$(e,t)}a(Ice,"addRoleValidation");function wce(e){let t=sC();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,m$(e,t)}a(wce,"alterRoleValidation");function Nce(e){let t=sC();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,d$.validateObject(e,t)}a(Nce,"dropRoleValidation");var Cce=["operation","role","id","permission","hdb_user","access"];function m$(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)Cce.includes(n[o])||s.push(n[o]);s.length>0&&Er(ar.INVALID_ROLE_JSON_KEYS(s),r);let i=d$.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{Er(o,r)}),e.permission){let o=Oce(e);o&&Er(o,r),u$.forEach(c=>{e.permission[c]&&!xd.isBoolean(e.permission[c])&&Er(ar.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(u$.indexOf(o)<0){if(o===Tce.STRUCTURE_USER){let l=e.permission[o];if(typeof l=="boolean")continue;if(Array.isArray(l)){for(let u=0,d=l.length;u<d;u++){let f=l[u];global.hdb_schema[f]||Er(ar.SCHEMA_NOT_FOUND(f),r)}continue}Er(ar.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){Er(ar.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let l in c.tables){let u=c.tables[l];if(!l||!global.hdb_schema[o][l]){Er(ar.TABLE_NOT_FOUND(o,l),r);continue}if(Object.keys(u).forEach(d=>{bce.includes(d)||Er(ar.INVALID_PERM_KEY(d),r,o,l)}),Object.values(Fd).forEach(d=>{xd.isDefined(u[d])?xd.isBoolean(u[d])||Er(ar.TABLE_PERM_NOT_BOOLEAN(d),r,o,l):Er(ar.TABLE_PERM_MISSING(d),r,o,l)}),u.attribute_permissions===void 0){Er(ar.ATTR_PERMS_ARRAY_MISSING,r,o,l);continue}else if(!(Array.isArray(u.attribute_permissions)||u.attribute_permissions===null)){Er(ar.ATTR_PERMS_NOT_ARRAY,r,o,l);continue}if(u.attribute_permissions){let d=global.hdb_schema[o][l].attributes.map(({attribute:m})=>m),f={read:!1,insert:!1,update:!1};for(let m in u.attribute_permissions){let p=u.attribute_permissions[m];if(Object.keys(p).forEach(E=>{!Ace.includes(E)&&E!==Fd.DELETE&&Er(ar.INVALID_ATTR_PERM_KEY(E),r,o,l)}),!xd.isDefined(p.attribute_name)){Er(ar.ATTR_PERM_MISSING_NAME,r,o,l);continue}let h=p.attribute_name;if(!d.includes(h)){Er(ar.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,l);continue}f$.forEach(E=>{xd.isDefined(p[E])?xd.isBoolean(p[E])||Er(ar.ATTR_PERM_NOT_BOOLEAN(E,h),r,o,l):Er(ar.ATTR_PERM_MISSING(E,h),r,o,l)}),!f.read&&p.read===!0&&(f.read=!0),!f.insert&&p.insert===!0&&(f.insert=!0),!f.update&&p.update===!0&&(f.update=!0)}if(u.read===!1&&f.read===!0||u.insert===!1&&f.insert===!0||u.update===!1&&f.update===!0){let m=`${o}.${l}`;Er(ar.MISMATCHED_TABLE_ATTR_PERMS(m),r,o,l)}}}}return Pce(r)}a(m$,"customValidate");p$.exports={addRoleValidation:Ice,alterRoleValidation:wce,dropRoleValidation:Nce};function Oce(e){let{operation:t,permission:r}=e;if(t===Bd.OPERATIONS_ENUM.ADD_ROLE||t===Bd.OPERATIONS_ENUM.ALTER_ROLE){let n=r.super_user===!0,s=r.cluster_user===!0;if(Object.keys(r).length>1&&(n||s)){if(s&&n)return ar.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?Bd.ROLE_TYPES_ENUM.SUPER_USER:Bd.ROLE_TYPES_ENUM.CLUSTER_USER;return ar.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(Oce,"validateNoSUPerms");function Pce(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:ar.ROLE_PERMS_ERROR,...e};return _ce(new Error,n,Sce.BAD_REQUEST)}else return null}a(Pce,"generateRolePermResponse");function Er(e,t,r,n){if(!r)t.main_permissions.push(e);else{let s=n?r+"_"+n:r;t.schema_permissions[s]?t.schema_permissions[s].push(e):t.schema_permissions[s]=[e]}}a(Er,"addPermError")});var ih=M((ZUe,S$)=>{"use strict";var E$=Vn(),_$=Sn(),Lce=Ul(),oC=h$(),aC=Xo(),XUe=require("uuid").v4,Dce=require("util"),vS=(G(),D(j)),vce=ae(),cC=_$.searchByValue,Mce=_$.searchByHash,Uce=Dce.promisify(Lce.delete),xce=di(),Bce=pd(),{hdbErrors:Fce,handleHDBError:$l}=Ee(),{HDB_ERROR_MSGS:g$,HTTP_STATUS_CODES:sh}=Fce,{UserEventMsg:lC}=us();S$.exports={addRole:kce,alterRole:Hce,dropRole:Gce,listRoles:qce};function iC(e){try{e.hdb_auth_header&&delete e.hdb_auth_header,e.HDB_INTERNAL_PATH&&delete e.HDB_INTERNAL_PATH,e.operation&&delete e.operation,e.hdb_user&&delete e.hdb_user}catch{}return e}a(iC,"scrubRoleDetails");async function kce(e){let t=oC.addRoleValidation(e);if(t)throw t;e=iC(e);let r={schema:"system",table:"hdb_role",attribute:"role",value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await cC(r)||[])}catch(i){throw $l(i)}if(n&&n.length>0)throw $l(new Error,g$.ROLE_ALREADY_EXISTS(e.role),sh.CONFLICT,void 0,void 0,!0);e.id||(e.id=e.role);let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await E$.insert(s),aC.signalUserChange(new lC(process.pid)),e=iC(e),e}a(kce,"addRole");async function Hce(e){let t=oC.alterRoleValidation(e);if(t)throw t;e=iC(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await E$.update(r)}catch(s){throw $l(s)}if(n&&n?.message==="updated 0 of 1 records")throw $l(new Error,"Invalid role id",sh.BAD_REQUEST,void 0,void 0,!0);return await aC.signalUserChange(new lC(process.pid)),e}a(Hce,"alterRole");async function Gce(e){let t=oC.dropRoleValidation(e);if(t)throw $l(new Error,t,sh.BAD_REQUEST,void 0,void 0,!0);let r=new Bce(vS.SYSTEM_SCHEMA_NAME,vS.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await Mce(r));if(n.length===0)throw $l(new Error,g$.ROLE_NOT_FOUND,sh.NOT_FOUND,void 0,void 0,!0);let s=new xce(vS.SYSTEM_SCHEMA_NAME,vS.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await cC(s)),o=!1;if(vce.isEmptyOrZeroLength(i)===!1){for(let l=0;l<i.length;l++)if(i[l].active===!0){o=!0;break}}if(o===!0)throw $l(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,sh.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await Uce(c),aC.signalUserChange(new lC(process.pid)),`${n[0].role} successfully deleted`}a(Gce,"dropRole");async function qce(){return cC({table:"hdb_role",schema:"system",hash_attribute:"id",attribute:"id",value:"*",get_attributes:["*"]})}a(qce,"listRoles")});var uC={};ye(uC,{start:()=>R$,startOnMainThread:()=>Kce});function R$({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r){let n=(0,T$.parseDocument)(r.toString(),{simpleKeys:!0}).toJSON();for(let s in n){let i=n[s];i.permission||(i={permission:i},i.permission.access&&(i.access=i.permission.access,delete i.permission.access));for(let o in i.permission){if($ce.includes(o))continue;let c=i.permission[o];c.tables||(i.permission[o]=c={tables:c});for(let l in c.tables){let u=c.tables[l];if(u.read=!!u.read,u.insert=!!u.insert,u.update=!!u.update,u.delete=!!u.delete,u.attributes){let d=[];for(let f in u.attributes){let m=u.attributes[f];m.attribute_name=f,d.push(m)}u.attribute_permissions=d,delete u.attributes}if(u.attribute_permissions){if(!Array.isArray(u.attribute_permissions))throw new Error("attribute_permissions must be an array if defined");for(let d of u.attribute_permissions)d.read=!!d.read,d.insert=!!d.insert,d.update=!!d.update}else u.attribute_permissions=null}}i.role=i.id=s,await Vce(i)}}}async function Vce(e){let t=lt().system.hdb_role;for await(let r of t.search([{attribute:"role",value:e.role}])){let{__createdtime__:n,__updatedtime__:s,...i}=r;return(0,y$.isEqual)(i,e)?void 0:(e.id=r.id,(0,MS.alterRole)(e))}return(0,MS.addRole)(e)}var MS,T$,y$,$ce,Kce,b$=se(()=>{Oe();MS=b(ih()),T$=require("yaml"),y$=require("lodash"),$ce=["super_user","cluster_user","structure_user"];a(R$,"start");a(Vce,"ensureRole");Kce=R$});async function US(e){let t=(0,w$.pathToFileURL)(e).toString();if(Yce)return oh||(oh=Wce(zce)),(await(await oh).import(t)).namespace;try{return await import(t)}catch(r){try{(await import("internal/util")).default.decorateErrorStack(r)}catch{}throw r}}async function Wce(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),oh=new Compartment({console,Math,Date,fetch:jce,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,I$.extname)(r)||(r+=".js"),r)},importHook:a(async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){s.Resource=Xt,s.tables=yn,s.databases=Me}};let n=await(0,A$.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)},"importHook")}),oh}function jce(e,t){let r=typeof e=="string"||e.url;if(new URL(r).protocol!="https")throw new Error("Only https is allowed in fetch");return fetch(e,t)}function zce(){return{Resource:Xt,tables:yn}}var A$,I$,w$,Yce,oh,dC=se(()=>{ji();Oe();A$=require("fs/promises"),I$=require("path"),w$=require("url"),Yce=!1;a(US,"secureImport");a(Wce,"getCompartment");a(jce,"secureOnlyFetch");a(zce,"getGlobalVars")});var fC={};ye(fC,{ResourceLoadError:()=>xS,handleApplication:()=>Jce,suppressHandleApplicationWarning:()=>Qce});function C$(e){return typeof e=="function"&&("get"in e||"put"in e||"post"in e||"delete"in e)}async function Jce(e){e.handleEntry(a(async function(r){if(r.entryType!=="file"){e.logger.warn(`jsResource plugin cannot handle entry type ${r.entryType}. Modify the 'files' option in ${e.configFilePath} to only include files.`);return}if(r.eventType!=="add"){e.requestRestart();return}try{let n=await US(r.absolutePath),s=(0,N$.dirname)(r.urlPath).replace(/\\/g,"/").replace(/^\/$/,"");C$(n.default)&&(e.resources.set(s,n.default),e.logger.debug(`Registered root resource: ${s}`)),O$(e,n,s)}catch(n){throw new xS(r.absolutePath,n)}},"handleResourceEntry"))}function O$(e,t,r){for(let n in t){let s=t[n],i=`${r}/${n}`;C$(s)?(e.resources.set(i,s),e.logger.debug(`Registered resource: ${i}`)):typeof s=="object"&&O$(e,s,i)}}var N$,xS,Qce,P$=se(()=>{dC();N$=require("path");a(C$,"isResource");xS=class extends Error{static{a(this,"ResourceLoadError")}filePath;cause;constructor(t,r){super(`Failed to load resource module ${t}${r?`: ${r.message}`:""}`),this.name="ResourceLoadError",this.filePath=t,this.cause=r}};a(Jce,"handleApplication");a(O$,"recurseForResources");Qce=!0});var pC={};ye(pC,{start:()=>Xce});function Xce({resources:e}){e.set("login",mC),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var mC,L$=se(()=>{ji();a(Xce,"start");mC=class extends Xt{static{a(this,"Login")}static async get(t,r,n){}static async post(t,r,n){let{username:s,password:i,redirect:o}=r;return{data:await n.login(s,i)}}}});function FS(e,t){let r={openapi:Zce,info:{title:"HarperDB HTTP REST interface",version:B$.packageJson.version},servers:[{description:"REST API",url:t}],paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},n=[{basicAuth:[],bearerAuth:[]}],s=a(i=>{if(i.type&&!r.components.schemas[i.type]){r.components.schemas[i.type]={};let o={},c=[];for(let l of i.properties)BS[l.type]?o[l.name]=new EC(BS[l.type],l.type):l.properties?(o[l.name]=new k$(l.type),s(l)):l.elements?.properties&&(o[l.name]=new nle(l.elements.type),s(l.elements)),l.nullable===!1&&c.push(l.name);r.components.schemas[i.type]=new x$(o,!i.sealed,c)}},"includeDefinitionInSchema");for(let[,i]of e){if(!i.path||i.Resource.isError)continue;let{path:o}=i,c=o.split("/").pop(),{attributes:l,sealed:u}=i.Resource,{prototype:d,primaryKey:f="id"}=i.Resource;if(!l&&e.allTypes.has(i.path)){let k=e.allTypes.get(i.path);u=k.sealed,l=k.properties}if(!f)continue;let m={},p=[],h=[];if(l)for(let{type:k,name:z,elements:Y,relationship:ce,definition:de,nullable:te}of l){let Se=de??Y?.definition;Se&&s(Se),te===!1&&h.push(z),ce?k==="array"?m[z]={type:"array",items:{$ref:$s+Y.type}}:m[z]={$ref:$s+k}:Se?k==="array"?m[z]={type:"array",items:{$ref:$s+Se.type}}:m[z]={$ref:$s+Se.type}:k==="array"?Y.type==="Any"?m[z]={type:"array",items:{format:Y.type}}:m[z]={type:"array",items:new EC(BS[Y.type],Y.type)}:k==="Any"?m[z]={format:k}:m[z]=new EC(BS[k],k),p.push(new _C(z,"query",m[z]))}let E=Object.keys(m),_=new _C(f,"path",{type:"string",format:"ID"});_.required=!0,_.description="primary key of record";let R=new _C("property","path",{enum:E});R.required=!0,r.components.schemas[c]=new x$(m,!u,h);let S=d.post!==Resource.prototype.post||d.update,y=typeof d.put=="function",w=typeof d.get=="function",I=typeof d.delete=="function",H=typeof d.patch=="function",X=`/${o}/`;r.paths[X]||(r.paths[X]={}),S&&(r.paths[X].post=new ele(c,n,{200:new kd({$ref:$s+c},{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}})},"create a new record auto-assigning a primary key")),r.paths[X].options=new D$(p,n,{200:new v$},"retrieve information about the communication options available for a target resource or the server as a whole, without performing any resource action"),w&&(r.paths[X].get=new hC(p,n,{200:new kd({type:"array",items:{$ref:$s+c}})},"search for records by the specified property name and value pairs")),I&&(r.paths[X].delete=new U$(p,n,"delete all the records that match the provided query",{204:new M$}));let q="/"+o+"/{"+f+"}";if(r.paths[q]||(r.paths[q]={}),r.paths[q].options=new D$(p,n,{200:new v$},"retrieve information about the communication options available for a target resource or the server as a whole, without performing any resource action"),w&&(r.paths[q].get=new hC([_],n,{200:new kd({$ref:$s+c})},"retrieve a record by its primary key")),y&&(r.paths[q].put=new tle([_],n,c,{200:new kd({$ref:$s+c})},"create or update the record with the URL path that maps to the record's primary key")),H&&(r.paths[q].patch=new rle([_],n,c,{200:new kd({$ref:$s+c})},"patch the record with the URL path that maps to the record's primary key")),I&&(r.paths[q].delete=new U$([_],n,"delete a record with the given primary key",{204:new M$})),w&&R.schema.enum.length>0){let k=`/${o}/{${f}}.{property}`;r.paths[k]||(r.paths[k]={}),r.paths[k].get=new hC([_,R],n,{200:new kd({enum:E})},"used to retrieve the specified property of the specified record")}}for(let[,i]of e.allTypes)s(i),i.sealed&&r.components.schemas[i.type].additionalProperties&&(r.components.schemas[i.type].additionalProperties=!1);return r}function ele(e,t,r,n){this.description=n,this.requestBody={content:{"application/json":{schema:{$ref:$s+e}}}},this.security=t,this.responses=r}function hC(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function D$(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function v$(){this.description=F$,this.headers={},this.content={}}function kd(e,t){this.description=F$,this.content={"application/json":{schema:e}},this.headers=t}function M$(){this.description="successfully processed request, no content returned to client"}function tle(e,t,r,n,s){this.description=s,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:$s+r}}}},this.responses=n}function rle(e,t,r,n,s){this.description=s,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:$s+r}}}},this.responses=n}function U$(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function x$(e,t,r){this.type="object",this.properties=e,this.additionalProperties=t,this.required=r}function EC(e,t){this.type=e,(e==="string"||e==="number"||e==="integer")&&t!=="String"&&(this.format=t)}function k$(e){this.$ref=`#/components/schemas/${e}`}function nle(e){this.type="array",this.items=new k$(e)}function _C(e,t,r){this.name=e,this.in=t,this.schema=r}var B$,Zce,BS,$s,F$,gC=se(()=>{B$=b(Rt()),Zce="3.0.3",BS={Int:"integer",Float:"number",Long:"integer",ID:"string",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer"},$s="#/components/schemas/",F$="successful operation";a(FS,"generateJsonApi");a(ele,"Post");a(hC,"Get");a(D$,"Options");a(v$,"ResponseOptions200");a(kd,"Response200");a(M$,"Response204");a(tle,"Put");a(rle,"Patch");a(U$,"Delete");a(x$,"ResourceSchema");a(EC,"Type");a(k$,"Ref");a(nle,"ArrayRef");a(_C,"Parameter")});var G$={};ye(G$,{Request:()=>pc,createReuseportFd:()=>kS});var H$,pc,SC,TC,kS,ah=se(()=>{H$=require("os"),pc=class{static{a(this,"Request")}#e;#t;_nodeRequest;_nodeResponse;method;url;headers;isWebSocket;user;constructor(t,r){this.method=t.method;let n=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=n,this.headers=new TC(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get authorized(){return this._nodeRequest.socket.authorized}get peerCertificate(){return this.#t===void 0&&(this.#t=this._nodeRequest.socket.getPeerCertificate?.(!0)||null),this.#t}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new SC(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get hostname(){return this._nodeRequest.headers.host}get httpVersion(){return this._nodeRequest.httpVersion}get isAborted(){return!1}get nodeRequest(){return this._nodeRequest}sendEarlyHints(t,r={}){r.link=t,this._nodeResponse.writeEarlyHints(r)}},SC=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}pipe(t,r){return this.#e.pipe(t,r)}},TC=class{static{a(this,"Headers")}asObject;constructor(t){this.asObject=t}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return Object.prototype.hasOwnProperty.call(this.asObject,t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}delete(t){delete this.asObject[t.toLowerCase()]}forEach(t){for(let[r,n]of this)t(n,r,this)}};(0,H$.platform)()!="win32"&&(kS=require("node-unix-socket").createReuseportFd)});var GS={};ye(GS,{parseHeaderValue:()=>RC,start:()=>ole});async function ile(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream",s=n?"CONNECT":e.method;e.search&&wg(e);let i=new Hs;try{e.responseHeaders=i;let o=e.url.slice(1),c,l;if(o!==q$){let _=HS.getMatch(o,n?"sse":"rest");if(!_)return t(e);e.handlerPath=_.path,c=new xs(_.relativeURL),c.async=!0,l=_.Resource}if(l?.isCaching){let _=r["cache-control"];if(_){let R=RC(_);for(let S of R)switch(S.name){case"max-age":e.expiresAt=S.value*1e3+Date.now();break;case"only-if-cached":e.onlyIfCached=!0;break;case"no-cache":e.noCache=!0;break;case"no-store":e.noCacheStore=!0;break;case"stale-if-error":e.staleIfError=!0;break;case"must-revalidate":e.mustRevalidate=!0;break}}}let u=r["x-replicate-to"];if(u){let _=RC(u).map(R=>(R.next?.name==="confirm"&&R.next.value>=0&&(e.replicatedConfirmation=+R.next.value),R.name));e.replicateTo=_.length===1&&+_[0]>=0?+_[0]:_[0]==="*"?void 0:_}r["x-replicate-from"]==="none"&&(e.replicateFrom=!1);let f=await At(e,()=>{if(r["content-length"]||r["transfer-encoding"])try{e.data=$o(r["content-type"],!0)(e.body,e.headers)}catch(_){throw new Hd.ClientError(_,400)}if(e.authorize=!0,o===q$&&s==="GET"){if(e?.user?.role?.permission?.super_user)return FS(HS,`${e.protocol}://${e.hostname}`);throw new Hd.ServerError("Forbidden",403)}switch(c.checkPermission=e.user?.role?.permission??{},s){case"GET":case"HEAD":return l.get(c,e);case"POST":return l.post(c,e.data,e);case"PUT":return l.put(c,e.data,e);case"DELETE":return l.delete(c,e);case"PATCH":return l.patch(c,e.data,e);case"OPTIONS":i.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return l.connect(c,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return l.query(c,e.data,e);case"COPY":return l.copy(c,r.destination,e);case"MOVE":return l.move(c,r.destination,e);case"BREW":throw new Hd.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Hd.ServerError(`Method ${s} is not recognized`,501)}}),m=200,p=e.lastModified;if(f==null)m=s==="GET"||s==="HEAD"?404:204,yC.lastModified&&isFinite(p)&&i.setIfNone("Last-Modified",new Date(p).toUTCString());else if(f.status>0&&f.headers){let _=Aq(f.headers,i);return f.headers!==_&&(f.headers=_),f.data!==void 0&&(f.body=$m(f.data,e,f)),f}else if(isFinite(p)){sle[0]=p;let _=String.fromCharCode(34,(sn[0]&63)+62,(sn[0]>>6)+(sn[1]<<2&63)+62,(sn[1]>>4)+(sn[2]<<4&63)+62,(sn[2]>>2)+62,(sn[3]&63)+62,(sn[3]>>6)+(sn[4]<<2&63)+62,(sn[4]>>4)+(sn[5]<<4&63)+62,(sn[5]>>2)+62,(sn[6]&63)+62,(sn[6]>>6)+(sn[7]<<2&63)+62,34),R=r["if-none-match"];R&&_==R?(f?.onDone&&f.onDone(),m=304,f=void 0):i.setIfNone("ETag",_),yC.lastModified&&i.setIfNone("Last-Modified",new Date(p).toUTCString())}e.createdResource&&(m=201),e.newLocation&&i.setIfNone("Location",e.newLocation);let h={status:m,headers:i,body:void 0},E=e.loadedFromSource??f?.wasLoadedFromSource?.();return E!==void 0&&(h.wasCacheMiss=E,!E&&isFinite(p)&&i.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||p))/1e3))),f!==void 0&&(h.body=$m(f,e,h),s==="HEAD"&&(h.body=void 0)),h}catch(o){o.statusCode?o.statusCode===500?Ei.warn(o):Ei.info(o):Ei.error(o),o.statusCode===405&&(o.method&&(o.message+=` to handle HTTP method ${o.method.toUpperCase()||""}`),o.allow&&(o.allow.push("trace","head","options"),i.setIfNone("Allow",o.allow.map(l=>l.toUpperCase()).join(", "))));let c={status:o.statusCode||500,headers:i,body:void 0};return c.body=$m(o instanceof Error?K$(o):o,e,c),c}}function ole(e){yC=e,e.includeExpensiveRecordCountEstimates&&(pc.prototype.includeExpensiveRecordCountEstimates=!0),!$$&&($$=!0,HS=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return ile(t,r)},e),e.webSocket!==!1&&e.server.ws(async(t,r,n)=>{ch++;let s=new ss;V$||(V$=!0,ip(l=>{ch>0&&l.push({metric:"ws-connections",connections:ch,byThread:!0})}));let i;t.on("error",l=>{i=!0,Ei.warn(l)});let o;t.on("message",a(function(u){o||(o=$o(r.requestedContentType??r.headers.asObject["content-type"],!1));let d=o(u);We(u.length,"bytes-received",r.handlerPath,"message","ws"),s.push(d)},"message"));let c;t.on("close",()=>{ch--,tn(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()});try{await n;let l=r.url.slice(1),u=HS.getMatch(l,"ws");if(tn(!!u,"connection","ws","connect"),u){r.handlerPath=u.path,We(h=>({count:h.count,total:ch}),"connections",r.handlerPath,"connect","ws"),r.authorize=!0;let d=new xs(u.relativeURL);d.checkPermission=r.user?.role?.permission??{};let f=u.Resource;c=(await At(r,()=>f.connect(d,s,r)))[Symbol.asyncIterator]();let p;for(;!(p=await c.next()).done;){let h=await qo(p.value,r);t.send(h),We(h.length,"bytes-sent",r.handlerPath,"message","ws"),t._socket.writableNeedDrain&&await new Promise(E=>t._socket.once("drain",E))}}else return t.close(1011,`No resource was found to handle ${r.pathname}`)}catch(l){l.statusCode?l.statusCode===500?Ei.warn(l):Ei.info(l):Ei.error(l),t.close(ale[l.statusCode]||1011,K$(l))}t.close()},e))}function RC(e){return e.trim().split(",").map(t=>{let r,n=t.trim().split(";"),s;for(;s=n.pop();)if(s.includes("=")){let[i,o]=s.trim().split("=");i=i.trim(),o&&(o=o.trim()),r={name:i.toLowerCase(),value:o,next:r}}else r={name:s.toLowerCase(),next:r};return r})}var Ei,Hd,K$,sn,sle,yC,q$,$$,HS,V$,ch,ale,Y$=se(()=>{Vo();os();Ei=b(Q()),Hd=b(Ee());Ng();qu();za();Wp();gC();ah();Og();({errorToString:K$}=Ei),sn=new Uint8Array(8),sle=new Float64Array(sn.buffer,0,1),yC={},q$="openapi";a(ile,"http");ch=0;a(ole,"start");ale={401:3e3,403:3003};a(RC,"parseHeaderValue")});var bC=M((Ixe,j$)=>{var{recordAction:qS,recordActionBinary:W$}=(os(),D(_g)),cle=require("fastify-plugin"),lle=200;j$.exports=cle(function(e,t,r){e.addHook("onResponse",async(n,s)=>{let i=s.elapsedTime}),e.addHook("onSend",async(n,s,i)=>{let o=s.elapsedTime,c=performance.now(),l=s.request.routeOptions,u,d,f;l.config?.isOperation?(u=n.body?.operation,d="operation"):(u=l.url,d="fastify-route",f=l.method),qS(o,"duration",u,f,d),W$(s.raw.statusCode<400,"success",u,f,d),W$(1,"response_"+s.raw.statusCode,u,f,d);let m=lle;i?.pipe?(i.on("data",_=>{m+=_.length}),i.on("end",()=>{qS(performance.now()-c,"transfer",u,f,d),qS(m,"bytes-sent",u,f,d)})):(m+=i?.length||0,qS(m,"bytes-sent",u,f,d));let p=o.toFixed(3),h=s.getHeader("Server-Timing"),E=`db;dur=${p}`;s.header("Server-Timing",h?`${h}, ${E}`:E)}),r()},{name:"hdb-request-time"})});var J$=M((wxe,z$)=>{var ule=mt(),dle={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};z$.exports=function(e){return ule.validateObject(e,dle)}});var $S=M((Nxe,Q$)=>{"use strict";var fle=(G(),D(j)).OPERATIONS_ENUM,AC=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=fle.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};Q$.exports=AC});var dh={};ye(dh,{createTokens:()=>wC,getJWTRSAKeys:()=>jS,refreshOperationToken:()=>NC,validateOperationToken:()=>CC,validateRefreshToken:()=>zS});async function jS(){if(VS)return VS;try{let e=lh.default.join(uh.default.getHdbBasePath(),rA),t=await KS.default.readFile(lh.default.join(e,Sm.JWT_PASSPHRASE_NAME),"utf8"),r=await KS.default.readFile(lh.default.join(e,Sm.JWT_PRIVATE_KEY_NAME),"utf8");return VS={publicKey:await KS.default.readFile(lh.default.join(e,Sm.JWT_PUBLIC_KEY_NAME),"utf8"),privateKey:r,passphrase:t},VS}catch(e){throw WS.default.error(e),new _i.ClientError(qd.NO_ENCRYPTION_KEYS,Gd.INTERNAL_SERVER_ERROR)}}async function wC(e){let t=(0,IC.validateBySchema)(e,uo.default.object({username:uo.default.string().optional(),password:uo.default.string().optional(),role:uo.default.string().optional(),expires_in:uo.default.alternatives(uo.default.string(),uo.default.number()).optional()}));if(t)throw new _i.ClientError(t.message);let r;try{let f=e.bypass_auth!==!0;!e.username&&!e.password&&(e.username=e.hdb_user?.username,f=!1),r=await yd(e.username,e.password,f)}catch(f){throw WS.default.error(f),new _i.ClientError(qd.INVALID_CREDENTIALS,Gd.UNAUTHORIZED)}if(!r)throw new _i.ClientError(qd.INVALID_CREDENTIALS,Gd.UNAUTHORIZED);let n=!1,s=!1;r.role?.permission&&(n=r.role.permission.super_user===!0,s=r.role.permission.cluster_user===!0);let i={username:e.username,super_user:n,cluster_user:s};e.role&&(i.role=e.role);let o=await jS(),c=await $d.default.sign(i,{key:o.privateKey,passphrase:o.passphrase},{expiresIn:e.expires_in??rV,algorithm:YS,subject:Vd.OPERATION}),l=await $d.default.sign(i,{key:o.privateKey,passphrase:o.passphrase},{expiresIn:mle,algorithm:YS,subject:Vd.REFRESH}),u=aN(l,$r.SHA256);if((await(0,X$.update)(new Z$.default(_m,xu.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]))).skipped_hashes.length>0)throw new _i.ClientError(qd.REFRESH_TOKEN_SAVE_FAILED,Gd.INTERNAL_SERVER_ERROR);return eV.default.signalUserChange(new tV.UserEventMsg(process.pid)),{operation_token:c,refresh_token:l}}async function NC(e){let t=(0,IC.validateBySchema)(e,uo.default.object({refresh_token:uo.default.string().required()}).required());if(t)throw new _i.ClientError(t.message);let{refresh_token:r}=e;await zS(r);let n=await jS(),s=await $d.default.decode(r);return{operation_token:await $d.default.sign({username:s.username,super_user:s.super_user,cluster_user:s.cluster_user},{key:n.privateKey,passphrase:n.passphrase},{expiresIn:rV,algorithm:YS,subject:Vd.OPERATION})}}async function CC(e){return nV(e,Vd.OPERATION)}async function zS(e){return nV(e,Vd.REFRESH)}async function nV(e,t){try{let r=await jS(),n=await $d.default.verify(e,r.publicKey,{algorithms:YS,subject:t});if(n.role)throw new Error("Invalid token");let s=await yd(n.username,void 0,!1);if(t===Vd.REFRESH&&!cN(s.refresh_token,e))throw new Error("Invalid token");return s}catch(r){throw WS.default.warn(r),r?.name==="TokenExpiredError"?new _i.ClientError(qd.TOKEN_EXPIRED,Gd.FORBIDDEN):new _i.ClientError(qd.INVALID_TOKEN,Gd.UNAUTHORIZED)}}var $d,KS,lh,uo,IC,_i,WS,X$,Z$,eV,tV,uh,Gd,qd,rV,mle,YS,Vd,VS,Kd=se(()=>{$d=b(require("jsonwebtoken")),KS=b(require("fs-extra")),lh=b(require("node:path")),uo=b(require("joi")),IC=b(mt());G();_i=b(Ee()),WS=b(Q());uN();hs();X$=b(Vn()),Z$=b($S()),eV=b(Xo()),tV=b(us()),uh=b(fe()),{HTTP_STATUS_CODES:Gd,AUTHENTICATION_ERROR_MSGS:qd}=_i.hdbErrors;uh.default.initSync();rV=uh.default.get(x.AUTHENTICATION_OPERATIONTOKENTIMEOUT)||"1d",mle=uh.default.get(x.AUTHENTICATION_REFRESHTOKENTIMEOUT)||"30d",YS="RS256",Vd={OPERATION:"operation",REFRESH:"refresh"};a(jS,"getJWTRSAKeys");a(wC,"createTokens");a(NC,"refreshOperationToken");a(CC,"validateOperationToken");a(zS,"validateRefreshToken");a(nV,"validateToken")});var OC=M((vxe,oV)=>{"use strict";var ple=J$(),Yd=require("passport"),hle=require("passport-local").Strategy,Ele=require("passport-http").BasicStrategy,_le=require("util"),gle=(hs(),D(oo)),iV=_le.callbackify(gle.findAndValidateUser),Dxe=Jr(),Sle=(G(),D(j)),sV=(Kd(),D(dh)),{AccessViolation:Tle}=Ee();Yd.use(new hle(function(e,t,r){iV(e,t,r)}));Yd.use(new Ele(function(e,t,r){iV(e,t,r)}));Yd.serializeUser(function(e,t){t(null,e)});Yd.deserializeUser(function(e,t){t(null,e)});function yle(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let n,s;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");n=o[0],s=o[1]}function i(o,c){return o?r(o):c?r(null,c):r(new Tle)}switch(a(i,"handleResponse"),n){case"Basic":Yd.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===Sle.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?sV.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):sV.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Yd.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(yle,"authorize");function Rle(e,t){let r=ple(e);if(r){t(r);return}let n={authorized:!0,messages:[]},s=e.user.role;if(!s?.permission)return t("Invalid role");let i=JSON.parse(s.permission);if(i.super_user)return t(null,n);if(!i[e.schema])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.schema} schema`),t(null,n);if(!i[e.schema].tables[e.table])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.table} table`),t(null,n);if(!i[e.schema].tables[e.table][e.operation])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return n.authorized=!1,n.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(n.authorized=!1,n.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,n)}a(Rle,"checkPermissions");oV.exports={authorize:yle,checkPermissions:Rle}});var UC=M((Bxe,uV)=>{var ZS=require("clone"),eT=mt(),ble=ae(),QS=(G(),D(j)),Uxe=Q(),PC=require("fs"),DC=require("joi"),{string:XS}=DC.types(),{hdbErrors:Ale,handleHDBError:JS}=Ee(),{HDB_ERROR_MSGS:xxe,HTTP_STATUS_CODES:LC}=Ale,{commonValidators:Wd}=Ji(),aV=" is required",Ile=["insert","update","upsert"],vC={database:{presence:!1,format:Wd.schema_format,length:Wd.schema_length},schema:{presence:!1,format:Wd.schema_format,length:Wd.schema_length},table:{presence:!0,format:Wd.schema_format,length:Wd.schema_length},action:{inclusion:{within:Ile,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},wle={schema:XS.required(),table:XS.required(),action:XS.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Nle,AWS_SECRET:Cle,AWS_BUCKET:Ole,AWS_FILE_KEY:Ple,REGION:Lle}=QS.S3_BUCKET_AUTH_KEYS,Dle={s3:{presence:!0},[`s3.${Nle}`]:{presence:!0,type:"String"},[`s3.${Cle}`]:{presence:!0,type:"String"},[`s3.${Ole}`]:{presence:!0,type:"String"},[`s3.${Ple}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Lle}`]:{presence:!0,type:"String"}},cV=ZS(vC);cV.data.presence={message:aV};var lV=ZS(vC);lV.file_path.presence={message:aV};var vle=Object.assign(ZS(vC),Dle),MC=ZS(wle);MC.csv_url=XS.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();MC.passthrough_headers=DC.object();function Mle(e){let t=eT.validateObject(e,cV);return tT(e,t)}a(Mle,"dataObject");function Ule(e){let t=eT.validateBySchema(e,DC.object(MC));return tT(e,t)}a(Ule,"urlObject");function xle(e){let t=eT.validateObject(e,lV);return tT(e,t)}a(xle,"fileObject");function Ble(e){let t=eT.validateObject(e,vle);return tT(e,t)}a(Ble,"s3FileObject");function tT(e,t){if(!t){let r=ble.checkGlobalSchemaTable(e.schema,e.table);if(r)return JS(new Error,r,LC.BAD_REQUEST);if(e.operation===QS.OPERATIONS_ENUM.CSV_FILE_LOAD)try{PC.accessSync(e.file_path,PC.constants.R_OK|PC.constants.F_OK)}catch(n){return n.code===QS.NODE_ERROR_CODES.ENOENT?JS(n,`No such file or directory ${n.path}`,LC.BAD_REQUEST):n.code===QS.NODE_ERROR_CODES.EACCES?JS(n,`Permission denied ${n.path}`,LC.BAD_REQUEST):JS(n)}}return t}a(tT,"postValidateChecks");uV.exports={dataObject:Mle,urlObject:Ule,fileObject:xle,s3FileObject:Ble}});var xC=M((kxe,dV)=>{"use strict";var fh=Q(),rT=(G(),D(j));async function Fle(e,t,r,n=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let s;try{return s=await e(t),r&&await r(t,s,n),t.operation===rT.OPERATIONS_ENUM.INSERT||t.operation===rT.OPERATIONS_ENUM.UPDATE||t.operation===rT.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===rT.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(fh.info(i.message),i):i.http_resp_msg?(fh.error(`Error calling operation: ${e.name}`),fh.error(i.http_resp_msg),i):(fh.error(`Error calling operation: ${e.name}`),fh.error(i),i)}}a(Fle,"callOperationFunctionAsAwait");dV.exports={callOperationFunctionAsAwait:Fle}});var BC=M((Gxe,mV)=>{"use strict";var{S3:kle,GetObjectCommand:Hle}=require("@aws-sdk/client-s3");mV.exports={getFileStreamFromS3:Gle,getS3AuthObj:fV};async function Gle(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await fV(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new Hle(r))).Body}a(Gle,"getFileStreamFromS3");function fV(e,t,r){return new kle({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(fV,"getS3AuthObj")});var hV=M(($xe,pV)=>{"use strict";var FC=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,n,s,i,o,c=null){this.op=t,this.action=r,this.schema=n,this.table=s,this.file_path=i,this.file_type=o,this.role_perms=c}},kC=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};pV.exports={BulkLoadFileObject:FC,BulkLoadDataObject:kC}});var _V=M((Kxe,EV)=>{"use strict";var HC=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,n=[],s=[]){this.schema=t,this.table=r,this.required_table_permissions=n,this.required_attribute_permissions=s}};EV.exports=HC});var SV=M((Wxe,gV)=>{"use strict";var GC=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};gV.exports=GC});var $C=M((zxe,yV)=>{"use strict";var TV=_V(),qle=SV(),{HDB_ERROR_MSGS:$le}=Jr(),qC=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=$le.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,n){if(r&&n){let s=`${r}_${n}`;if(this.unauthorized_access[s])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,n){let s=new TV(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let l=new qle(c,s[c]);i.push(l)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new TV(r,n,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};yV.exports=qC});var Vl=M((Xxe,IV)=>{"use strict";var Qxe=Sn(),mh=Q(),{validateBySchema:RV}=mt(),sa=require("joi"),Vle=no(),nT=ae(),{handleHDBError:sT,hdbErrors:Kle,ClientError:bV}=Ee(),{HDB_ERROR_MSGS:iT,HTTP_STATUS_CODES:VC}=Kle,AV=fe();AV.initSync();var{getDatabases:KC}=(Oe(),D(pt)),Yle=require("fs-extra"),Wle=(G(),D(j));IV.exports={describeAll:jle,describeTable:oT,describeSchema:zle};async function jle(e={}){try{let t=nT.isEmptyOrZeroLength(e),r=!!e.bypass_auth,n,s;!t&&!r&&(n=e.hdb_user?.role?.permission,s=n?.super_user||n?.cluster_user);let i=KC(),o={},c={},l=[],u=e?.exact_count,d=e?.include_computed;for(let m in i){o[m]=!0,!t&&!s&&!r&&(c[m]=e.hdb_user?.role?.permission[m]?.describe);let p=i[m];for(let h in p)try{let E;if(t||s||r)E=await oT({schema:m,table:h,exact_count:u,include_computed:d});else if(n&&n[m].describe&&n[m].tables[h].describe){let _=n[m].tables[h].attribute_permissions;E=await oT({schema:m,table:h,exact_count:u,include_computed:d},_)}E&&l.push(E)}catch(E){mh.error(E)}}let f={};for(let m in l)t||s||r?(f[l[m].schema]==null&&(f[l[m].schema]={}),f[l[m].schema][l[m].name]=l[m],o[l[m].schema]&&delete o[l[m].schema]):c[l[m].schema]&&(f[l[m].schema]==null&&(f[l[m].schema]={}),f[l[m].schema][l[m].name]=l[m],o[l[m].schema]&&delete o[l[m].schema]);for(let m in o)t||s||r?f[m]={}:c[m]&&(f[m]={});return f}catch(t){return mh.error("Got an error in describeAll"),mh.error(t),sT(new Error,iT.DESCRIBE_ALL_ERR)}}a(jle,"describeAll");async function oT(e,t){nT.transformReq(e);let{schema:r,table:n}=e;r=r?.toString(),n=n?.toString();let s=t;e.hdb_user&&!e.hdb_user?.role?.permission?.super_user&&(s=e.hdb_user?.role?.permission[r]?.tables[n]?.attribute_permissions);let i=RV(e,sa.object({database:sa.string(),table:sa.string().required(),exact_count:sa.boolean().strict(),include_computed:sa.boolean().strict()}));if(i)throw new bV(i.message);let c=KC()[r];if(!c)throw sT(new Error,iT.SCHEMA_NOT_FOUND(e.schema),VC.NOT_FOUND);let l=c[n];if(!l)throw sT(new Error,iT.TABLE_NOT_FOUND(e.schema,e.table),VC.NOT_FOUND);function u(p){(!p.computed||e.include_computed)&&d.push({attribute:p.attribute,type:p.type,elements:p.elements?.type,indexed:p.indexed,is_primary_key:p.isPrimaryKey,assigned_created_time:p.assignCreatedTime,assigned_updated_time:p.assignUpdatedTime,nullable:p.nullable,computed:p.computed?!0:void 0,properties:p.properties?p.properties.map(h=>({type:h.type,name:h.name})):void 0})}a(u,"pushAtt");let d=[];if(s){let p={};s.forEach(h=>{h.describe&&(p[h.attribute_name]=!0)}),l.attributes.forEach(h=>{p[h.name]&&u(h)})}else l.attributes?.forEach(p=>u(p));let f;try{f=(await Yle.stat(l.primaryStore.env.path)).size}catch(p){mh.warn("unable to get database size",p)}let m={schema:r,name:l.tableName,hash_attribute:l.attributes.find(p=>p.isPrimaryKey||p.is_hash_attribute)?.name,audit:l.audit,schema_defined:l.schemaDefined,attributes:d,db_size:f};l.replicate!==void 0&&(m.replicate=l.replicate),l.expirationMS!==void 0&&(m.expiration=l.expirationMS/1e3+"s"),l.sealed!==void 0&&(m.sealed=l.sealed),l.sources?.length>0&&(m.sources=l.sources.map(p=>p.name).filter(p=>p&&p!=="NATSReplicator"&&p!=="Replicator")),AV.get(Wle.CONFIG_PARAMS.CLUSTERING_ENABLED)&&(m.clustering_stream_name=Vle.createNatsTableStreamName(m.schema,m.name));try{let p=await l.getRecordCount({exactCount:!!e.exact_count});m.record_count=p.recordCount,m.table_size=l.getSize(),m.db_audit_size=l.getAuditSize(),m.estimated_record_range=p.estimatedRange;let h=l.auditStore;if(h)for(let E of h.getKeys({reverse:!0,limit:1}))m.last_updated_record=E[0];if(!m.last_updated_record&&l.indices.__updatedtime__)for(let E of l.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))m.last_updated_record=E}catch(p){mh.warn(`unable to stat table dbi due to ${p}`)}return m}a(oT,"descTable");async function zle(e){nT.transformReq(e);let t=RV(e,sa.object({database:sa.string(),exact_count:sa.boolean().strict(),include_computed:sa.boolean().strict()}));if(t)throw new bV(t.message);let r;e.hdb_user&&!e.hdb_user?.role?.permission?.super_user&&(r=e.hdb_user?.role?.permission[e.schema]);let n=e.schema.toString(),i=KC()[n];if(!i)throw sT(new Error,iT.SCHEMA_NOT_FOUND(e.schema),VC.NOT_FOUND);let o={};for(let c in i){let l;if(r&&r.tables[c]&&(l=r.tables[c]),nT.isEmpty(l)||l.describe){let u=await oT({schema:e.schema,table:c,exact_count:e.exact_count,include_computed:e.include_computed},l?l.attribute_permissions:null);u&&(o[u.name]=u)}}return o}a(zle,"describeSchema")});var PV=M((e0e,OV)=>{"use strict";var Jle=Vl(),{hdbErrors:wV}=Ee(),{getDatabases:NV}=(Oe(),D(pt));OV.exports={checkSchemaExists:CV,checkSchemaTableExists:Qle,schemaDescribe:Jle};async function CV(e){if(!NV()[e])return wV.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(CV,"checkSchemaExists");async function Qle(e,t){let r=await CV(e);if(r)return r;if(!NV()[e][t])return wV.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Qle,"checkSchemaTableExists")});var aT=M((r0e,LV)=>{"use strict";var Xle=ms();LV.exports={writeTransaction:Zle};function Zle(e,t,r){return Xle.writeTransaction(e,t,r)}a(Zle,"writeTransaction")});var JC=M((a0e,$V)=>{"use strict";var{decode:eue}=require("msgpackr"),{isMainThread:s0e,parentPort:i0e,threadId:o0e}=require("worker_threads"),uT=_r(),jd=vt(),jC=(G(),D(j)),Rn=Q(),WC=fe(),tue=(G(),D(j)),{onMessageByType:rue}=st(),UV=no(),{recordAction:DV,recordActionBinary:nue}=(os(),D(_g)),{publishToStream:sue}=uT,{ConsumerEvents:vV}=require("nats"),iue=Sn(),{promisify:oue}=require("util"),{decodeBlobsWithWrites:aue}=(is(),D(rg)),xV=oue(setTimeout),dT=1e4,fT,lT,cue,lue,BV,ph=new Map,zd=new Map;$V.exports={initialize:FV,ingestConsumer:zC,setSubscription:uue,setIgnoreOrigin:mue,getDatabaseSubscriptions:fue,updateConsumer:kV};async function FV(){rue(jC.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,async n=>{await kV(n)}),BV=!0,Rn.notify("Initializing clustering ingest service.");let{connection:e,jsm:t,js:r}=await uT.getNATSReferences();fT=e,lT=e.info.server_name,cue=t,lue=r}a(FV,"initialize");async function kV(e){if(e.status==="start"){let{js:t,jsm:r}=await HV(e.node_domain_name);zC(e.stream_name,t,r,e.node_domain_name)}else if(e.status==="stop"){let t=ph.get(e.stream_name+e.node_domain_name);t&&(Rn.notify("Closing ingest consumer for node:",e.node_domain_name,"stream:",e.stream_name),await t.close?.(),ph.set(e.stream_name+e.node_domain_name,"close")),zd.get(e.node_domain_name)==="failed"&&zd.set(e.node_domain_name,"close")}}a(kV,"updateConsumer");var mT=new Map;function uue(e,t,r){let n=mT.get(e);n||mT.set(e,n=new Map),n.set(t,r),BV||FV().then(due)}a(uue,"setSubscription");async function due(){let e=await iue.searchByValue({database:"system",table:"hdb_nodes",attribute:"name",value:"*"});for await(let t of e){let r=t.name+jd.SERVER_SUFFIX.LEAF,n,s;for(let i of t.subscriptions||[])if(i.subscribe===!0){if(!n&&({js:n,jsm:s}=await HV(r),!n))break;let{schema:o,table:c}=i,l=UV.createNatsTableStreamName(o,c);zC(l,n,s,r)}}}a(due,"accessConsumers");async function HV(e){let t,r,n=1;for(;!r;)try{t=await fT.jetstream({domain:e}),r=await fT.jetstreamManager({domain:e,checkAPI:!1})}catch(s){if(zd.get(e)==="close")break;zd.set(e,"failed"),n%10===1&&Rn.warn("Nats ingest attempting to connect to:",e,"Nats error:",s.message);let i=n++*100<dT?n++*100:dT;await xV(i)}return{js:t,jsm:r}}a(HV,"connectToRemoteJS");function fue(){return mT}a(fue,"getDatabaseSubscriptions");var GV;function mue(e){GV=e}a(mue,"setIgnoreOrigin");var qV=100,MV=new Array(qV),cT=0;async function zC(e,t,r,n){let{connection:s}=await uT.getNATSReferences();fT=s,lT=s.info.server_name;let i,o=1;for(;!i;)try{i=await t.consumers.get(e,lT),Rn.notify("Initializing ingest consumer for node:",n,"stream:",e)}catch(u){if(zd.get(n)==="close")break;o%10===1&&Rn.warn("Nats ingest error getting consumer:",n,"stream:",e,"Nats error:",u.message),u.code==="404"&&(Rn.notify("Nats ingest creating consumer for node:",n,"stream:",e),i=await uT.createConsumer(r,e,lT,new Date(Date.now()).toISOString()));let d=o++*100<dT?o++*100:dT;await xV(d)}let c=!1,l;for(;!c;){if(ph.get(e+n)==="close"||zd.get(n)==="close"){ph.delete(e+n),c=!0;continue}l=await i.consume({max_messages:WC.get(jC.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS)??100,bind:!0}),ph.set(e+n,l);let u=!1;(async()=>{for await(let d of await l.status())if(d.type===vV.ConsumerDeleted&&(await l.close(),c=!0),d.type===vV.HeartbeatsMissed){let f=d.data;Rn.trace(`${f} clustering ingest consumer heartbeats missed, node: ${n} stream: ${l.consumer.stream}`),f===100&&(Rn.warn(`Restarting clustering ingest consumer due to missed heartbeat threshold being met, node: ${n} stream: ${l.consumer.stream}`),l.stop(),u=!0)}})();try{for await(let d of l)await MV[cT],MV[cT]=pue(d).catch(f=>{Rn.error(f)}),++cT>=qV&&(cT=0)}catch(d){d.message==="consumer deleted"?(Rn.notify("Nats consumer deleted, closing messages for node:",n,"stream:",l.consumer.stream),await l.close(),c=!0):Rn.error("Error consuming clustering ingest, restarting consumer",d)}}}a(zC,"ingestConsumer");async function pue(e){let t;await aue(()=>{t=eue(e.data)}),DV(e.data.length,"bytes-received",e.subject,t.operation,"ingest"),Rn.trace("Nats message processor message size:",e?.msg?._msg?.size,"bytes");let r=e.headers,n=!1,s=WC.get(jC.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(jd.MSG_HEADERS.TRANSACTED_NODES)&&r.values(jd.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(jd.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!GV),nue(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(jd.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:l,table:u,records:d,hash_values:f,__origin:m,expiresAt:p}=t;Rn.trace("processing message:",o,c,u,(d?"records: "+d.map(I=>I?.id):"")+(f?"ids: "+f:""),"with sequence:",e.seq),Rn.trace(`messageProcessor nats msg id: ${e.headers.get(jd.MSG_HEADERS.NATS_MSG_ID)}`);let h;d||(d=f);let E=new Promise(I=>h=I),{timestamp:_,user:R,node_name:S}=m||{},y=mT.get(c)?.get(u);if(!y)throw new Error(`Missing table for replication message: ${u}`);if(o==="define_schema")t.type=o,t.onCommit=h,y.send(t);else if(d.length===1&&!l)y.send({type:YC(o),value:d[0],id:f?.[0],expiresAt:p,timestamp:_,table:u,onCommit:h,user:R,nodeName:S});else{let I=d.map((H,X)=>({type:YC(o),value:H,expiresAt:p,id:f?.[X],table:u}));for(;l;)I.push({type:YC(l.operation),value:l.record,expiresAt:l.expiresAt,id:l.id,table:l.table}),l=l.next;y.send({type:"transaction",writes:I,table:u,timestamp:_,onCommit:h,user:R,nodeName:S})}WC.get(tue.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&sue(e.subject.split(".").slice(0,-1).join("."),UV.createNatsTableStreamName(c,u),e.headers,e.data),await E;let w=Date.now()-_;_&&DV(w,"replication-latency",e.subject,o,"ingest")}catch(o){Rn.error(o)}e.ack()}a(pue,"messageProcessor");function YC(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(YC,"convertOperation")});var _r=M((p0e,o1)=>{"use strict";var Kr=fe();Kr.initSync();var hue=require("fs-extra"),Eue=require("semver"),_h=require("path"),{monotonicFactory:_ue}=require("ulidx"),KV=_ue(),gue=require("util"),YV=require("child_process"),Sue=gue.promisify(YV.exec),Tue=YV.spawn,on=vt(),rt=(G(),D(j)),{packageJson:yue,PACKAGE_ROOT:Rue}=Rt(),pT=ae(),gi=Q(),hT=no(),bue=aT(),hh=_t(),{broadcast:Aue,onMessageByType:Iue,getWorkerIndex:wue}=st(),{isMainThread:WV}=require("worker_threads"),{Encoder:Nue,decode:eO}=require("msgpackr"),jV=new Nue,{isEmpty:jl}=pT,zV=(hs(),D(oo)),l0e=48*36e11;WV&&Iue(rt.ITC_EVENT_TYPES.RESTART,()=>{bn=void 0,Wl=void 0});var{connect:Cue,StorageType:Oue,RetentionPolicy:Pue,AckPolicy:tO,DeliverPolicy:rO,DiscardPolicy:Lue,NatsConnection:u0e,JetStreamManager:d0e,JetStreamClient:f0e,StringCodec:m0e,JSONCodec:Due,createInbox:nO,headers:vue,ErrorCode:VV}=require("nats"),{recordAction:Mue}=(os(),D(_g)),{encodeBlobsAsBuffers:Uue}=(is(),D(rg)),JV=Due(),xue="clustering",Bue=yue.engines[on.NATS_SERVER_NAME],Fue=_h.join(Rue,"dependencies"),ZC=_h.join(Fue,`${process.platform}-${process.arch}`,on.NATS_BINARY_NAME),QC,XC,Eh,Kl,Yl;o1.exports={runCommand:QV,checkNATSServerInstalled:kue,createConnection:sO,getConnection:gh,getJetStreamManager:Sh,getJetStream:ZV,getNATSReferences:fo,getServerList:Gue,createLocalStream:iO,listStreams:e1,deleteLocalStream:que,getServerConfig:Jd,listRemoteStreams:$ue,viewStream:Vue,viewStreamIterator:Kue,publishToStream:Yue,request:zue,reloadNATS:oO,reloadNATSHub:Jue,reloadNATSLeaf:Que,extractServerName:jue,requestErrorHandler:Xue,createLocalTableStream:s1,createTableStreams:tde,purgeTableStream:i1,purgeSchemaTableStreams:rde,getStreamInfo:nde,updateLocalStreams:ide,closeConnection:Hue,getJsmServerName:ET,addNatsMsgHeader:t1,clearClientCache:XV,updateRemoteConsumer:Zue,createConsumer:r1,updateConsumerIterator:ede};async function QV(e,t=void 0){let{stdout:r,stderr:n}=await Sue(e,{cwd:t});if(n)throw new Error(n.replace(`
16
16
  `,""));return r.replace(`
17
17
  `,"")}a(QV,"runCommand");async function kue(){try{await hue.access(ZC)}catch{return!1}let e=await QV(`${ZC} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return Eue.eq(t,Bue)}a(kue,"checkNATSServerInstalled");async function sO(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await zV.getClusterUser();if(jl(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}gi.trace("create nats connection called");let i=await Cue({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:Kr.get(rt.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Kr.get(rt.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Kr.get(rt.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),gi.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&gi.error("Error with Nats client connection, connection closed",o),i===bn&&XV()}),i}a(sO,"createConnection");function XV(){bn=void 0,Kl=void 0,Yl=void 0,Wl=void 0}a(XV,"clearClientCache");async function Hue(){bn&&(await bn.drain(),bn=void 0,Kl=void 0,Yl=void 0,Wl=void 0)}a(Hue,"closeConnection");var bn,Wl;async function gh(){return Wl||(Wl=sO(Kr.get(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),bn=await Wl),bn||Wl}a(gh,"getConnection");async function Sh(){if(Kl)return Kl;jl(bn)&&await gh();let{domain:e}=Jd(rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(jl(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Kl=await bn.jetstreamManager({domain:e,timeout:6e4}),Kl}a(Sh,"getJetStreamManager");async function ZV(){if(Yl)return Yl;jl(bn)&&await gh();let{domain:e}=Jd(rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(jl(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Yl=bn.jetstream({domain:e,timeout:6e4}),Yl}a(ZV,"getJetStream");async function fo(){let e=bn||await gh(),t=Kl||await Sh(),r=Yl||await ZV();return{connection:e,jsm:t,js:r}}a(fo,"getNATSReferences");async function Gue(e){let t=Kr.get(rt.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await zV.getClusterUser(),s=await sO(t,r,n),i=nO(),o=s.subscribe(i),c=[],l,u=(async()=>{for await(let d of o){let f=JV.decode(d.data);f.response_time=Date.now()-l,c.push(f)}})();return l=Date.now(),await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await s.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await s.flush(),await pT.asyncSetTimeout(e),await o.drain(),await s.close(),await u,c}a(Gue,"getServerList");async function iO(e,t){let{jsm:r}=await fo(),n=Kr.get(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Kr.get(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=Kr.get(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:Oue.File,retention:Pue.Limits,subjects:t,discard:Lue.Old,maxMsgs:s,maxBytes:i,maxAge:n})}a(iO,"createLocalStream");async function e1(){let{jsm:e}=await fo(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(e1,"listStreams");async function que(e){let{jsm:t}=await fo();await t.streams.delete(e)}a(que,"deleteLocalStream");async function $ue(e){let{connection:t}=await fo(),r=[],n=nO(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(JV.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:n}),await t.flush(),await s.drain(),await i,r}a($ue,"listRemoteStreams");async function Vue(e,t=void 0,r=void 0){let{jsm:n,js:s}=await fo(),i=KV(),o={durable_name:i,ack_policy:tO.Explicit};t&&(o.deliver_policy=rO.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),l=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let u=[];for await(let d of l){let f=eO(d.data),m={nats_timestamp:d.info.timestampNanos,nats_sequence:d.info.streamSequence,entry:f};if(d.headers&&(m.origin=d.headers.get(on.MSG_HEADERS.ORIGIN)),u.push(m),d.ack(),d.info.pending===0)break}return await c.delete(),u}a(Vue,"viewStream");async function*Kue(e,t=void 0,r=void 0){let{jsm:n,js:s}=await fo(),i=KV(),o={durable_name:i,ack_policy:tO.Explicit};t&&(o.deliver_policy=rO.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),l=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let u of l){let d=eO(u.data);d[0]||(d=[d]);for(let f of d){let m={nats_timestamp:u.info.timestampNanos,nats_sequence:u.info.streamSequence,entry:f};u.headers&&(m.origin=u.headers.get(on.MSG_HEADERS.ORIGIN)),yield m}if(u.ack(),u.info.pending===0)break}await c.delete()}a(Kue,"viewStreamIterator");async function Yue(e,t,r,n){gi.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=t1(n,r);let{js:s}=await fo(),i=await ET(),o=`${e}.${i}`,c=await Uue(()=>n instanceof Uint8Array?n:jV.encode(n));try{gi.trace(`publishToStream publishing to subject: ${o}`),Mue(c.length,"bytes-sent",e,n.operation,"replication"),await s.publish(o,c,{headers:r})}catch(l){if(l.code&&l.code.toString()==="503")return n1(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(l.code&&l.code.toString()==="503"){gi.trace(`publishToStream creating stream: ${t}`);let d=o.split(".");d[2]="*",await iO(t,[o]),await s.publish(o,c,{headers:r})}else throw l}});throw l}}a(Yue,"publishToStream");function t1(e,t){t===void 0&&(t=vue());let r=Kr.get(rt.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(on.MSG_HEADERS.ORIGIN)&&r&&t.append(on.MSG_HEADERS.ORIGIN,r),t}a(t1,"addNatsMsgHeader");function Jd(e){e=e.toLowerCase();let t=_h.join(Kr.get(rt.CONFIG_PARAMS.ROOTPATH),xue);if(e===rt.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return jl(XC)&&(XC={port:hh.getConfigFromFile(rt.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:hh.getConfigFromFile(rt.CONFIG_PARAMS.CLUSTERING_NODENAME)+on.SERVER_SUFFIX.HUB,config_file:on.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:_h.join(t,on.PID_FILES.HUB),hdbNatsPath:t}),XC;if(e===rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return jl(QC)&&(QC={port:hh.getConfigFromFile(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:hh.getConfigFromFile(rt.CONFIG_PARAMS.CLUSTERING_NODENAME)+on.SERVER_SUFFIX.LEAF,config_file:on.NATS_CONFIG_FILES.LEAF_SERVER,domain:hh.getConfigFromFile(rt.CONFIG_PARAMS.CLUSTERING_NODENAME)+on.SERVER_SUFFIX.LEAF,pid_file_path:_h.join(t,on.PID_FILES.LEAF),hdbNatsPath:t}),QC;gi.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(Jd,"getServerConfig");async function r1(e,t,r,n){try{await e.consumers.add(t,{ack_policy:tO.Explicit,durable_name:r,deliver_policy:rO.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(r1,"createConsumer");async function Wue(e,t,r){await e.consumers.delete(t,r)}a(Wue,"removeConsumer");function jue(e){return e.split(".")[1]}a(jue,"extractServerName");async function zue(e,t,r=6e4,n=nO()){if(!pT.isObject(t))throw new Error("data param must be an object");let s=jV.encode(t),{connection:i}=await fo(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return eO(c.data)}a(zue,"request");function oO(e){return new Promise(async(t,r)=>{let n=Tue(ZC,["--signal",`reload=${e}`],{cwd:__dirname}),s,i;n.on("error",o=>{r(o)}),n.stdout.on("data",o=>{i+=o.toString()}),n.stderr.on("data",o=>{s+=o.toString()}),n.stderr.on("close",o=>{s&&r(s),t(i)})})}a(oO,"reloadNATS");async function Jue(){let{pid_file_path:e}=Jd(rt.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await oO(e)}a(Jue,"reloadNATSHub");async function Que(){let{pid_file_path:e}=Jd(rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await oO(e)}a(Que,"reloadNATSLeaf");function Xue(e,t,r){let n;switch(e.code){case VV.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case VV.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(Xue,"requestErrorHandler");async function Zue(e,t){let r=t+on.SERVER_SUFFIX.LEAF,{connection:n}=await fo(),{jsm:s}=await ade(r),{schema:i,table:o}=e,c=hT.createNatsTableStreamName(i,o),l=e.start_time?e.start_time:new Date(Date.now()).toISOString();await n1(async()=>{if(e.subscribe===!0)await r1(s,c,n.info.server_name,l);else try{await Wue(s,c,n.info.server_name)}catch(u){gi.trace(u)}})}a(Zue,"updateRemoteConsumer");async function ede(e,t,r,n){let s=hT.createNatsTableStreamName(e,t),i=r+on.SERVER_SUFFIX.LEAF,o={type:rt.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:n,stream_name:s,node_domain_name:i};if(!WV&&wue()<Kr.get(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=JC();await c(o)}await Aue(o),n==="stop"&&await pT.asyncSetTimeout(1e3)}a(ede,"updateConsumerIterator");function n1(e){return bue.writeTransaction(rt.SYSTEM_SCHEMA_NAME,rt.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(n1,"exclusiveLock");async function s1(e,t){let r=hT.createNatsTableStreamName(e,t),n=await ET(),s=sde(e,t,n);await iO(r,[s])}a(s1,"createLocalTableStream");async function tde(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await s1(n,s)}}a(tde,"createTableStreams");async function i1(e,t,r=void 0){if(Kr.get(rt.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=hT.createNatsTableStreamName(e,t),{domain:s}=Jd(rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await(await(await gh()).jetstreamManager({domain:s,timeout:24e4})).streams.purge(n,r)}catch(n){if(n.message==="stream not found")gi.warn(n);else throw n}}a(i1,"purgeTableStream");async function rde(e,t){if(Kr.get(rt.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await i1(e,t[r])}a(rde,"purgeSchemaTableStreams");async function nde(e){return(await Sh()).streams.info(e)}a(nde,"getStreamInfo");function sde(e,t,r){return`${on.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(sde,"createSubjectName");async function ET(){if(Eh)return Eh;if(Eh=(await Sh())?.nc?.info?.server_name,Eh===void 0)throw new Error("Unable to get jetstream manager server name");return Eh}a(ET,"getJsmServerName");async function ide(){let e=await Sh(),t=await ET(),r=await e1();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=ode(n),c=i.split(".");if(c[c.length-1]===t&&!o||s.name==="__HARPERDB_WORK_QUEUE__")continue;let u=i.split(".");u[u.length-1]=t;let d=u.join(".");gi.trace(`Updating stream subject name from: ${i} to: ${d}`),s.subjects[0]=d,await e.streams.update(s.name,s)}}a(ide,"updateLocalStreams");function ode(e){let{config:t}=e,r=!1,n=Kr.get(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Kr.get(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=Kr.get(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,n!==t.max_age&&(t.max_age=n,r=!0),s!==t.max_bytes&&(t.max_bytes=s,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(ode,"updateStreamLimits");async function ade(e){let t,r;try{t=await bn.jetstream({domain:e}),r=await bn.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw gi.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a(ade,"connectToRemoteJS")});function aO(e){let t=e.get(_T),r=t?(0,Qd.unpack)(t):null;r||(r={remoteNameToId:{}});let n=nt(),s=!1;r.nodeName=nt();let i=r.remoteNameToId;if(i[n]!==0){let o=0,c;for(let l in i){let u=i[l];u===0?c=l:u>o&&(o=u)}if(c){o++,i[c]=o;let l=[Symbol.for("seq"),o];e.rootStore.dbisDb.transactionSync(()=>{e.rootStore.dbisDb.get(l)||e.rootStore.dbisDb.putSync(l,{seqId:yh(e)??1,nodes:[]})})}i[n]=0,e.putSync(_T,(0,Qd.pack)(r))}return r}function Th(e){return aO(e).remoteNameToId}function c1(e,t){let r=aO(t),n=r.remoteNameToId,s=new Map,i=!1;for(let o in e){let c=e[o],l=n[o];if(l==null){let u=0;for(let d in n){let f=n[d];f>u&&(u=f)}l=u+1,n[o]=l,i=!0}s.set(c,l)}return i&&t.putSync(_T,(0,Qd.pack)(r)),s}function gT(e,t){let r=aO(t),n=r.remoteNameToId,s=n[e];if(s==null){let i=0;for(let o in n){let c=n[o];c>i&&(i=c)}s=i+1,n[e]=s,t.putSync(_T,(0,Qd.pack)(r))}return a1.trace?.("The remote node name map",e,n,s),s}var a1,Qd,_T,cO=se(()=>{a1=b(sr());gs();Qd=require("msgpackr"),_T=Symbol.for("remote-ids");a(aO,"getIdMappingRecord");a(Th,"exportIdMapping");a(c1,"remoteToLocalNodeId");a(gT,"getIdOfRemoteNode")});var p1={};ye(p1,{commitsAwaitingReplication:()=>Xd,getHDBNodeTable:()=>Gt,getReplicationSharedStatus:()=>Zd,iterateRoutes:()=>bh,shouldReplicateToNode:()=>Rh,subscribeToNodeUpdates:()=>ef});function Gt(){return l1||(l1=ze({table:"hdb_nodes",database:"system",attributes:[{name:"name",isPrimaryKey:!0},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"url"},{attribute:"routes"},{attribute:"ca"},{attribute:"ca_info"},{attribute:"replicates"},{attribute:"revoked_certificates"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]}))}function Zd(e,t,r,n){return new Float64Array(e.getUserSharedBuffer(["replicated",t,r],new ArrayBuffer(64),n&&{callback:n}))}function ef(e){Gt().subscribe({}).then(async t=>{for await(let r of t){let n=r?.value?.name;m1.debug?.("adding node",n,"on node",nt()," on process",process.pid),server.nodes=server.nodes.filter(i=>i.name!==n),r.type==="put"&&n!==nt()&&(r.value?server.nodes.push(r.value):console.error("Invalid node update event",r));let s=new Map;for await(let i of Gt().search({}))if(i.shard!=null){let o=s.get(i.shard);o||s.set(i.shard,o=[]),o.push(i)}server.shards=s,(r.type==="put"||r.type==="delete")&&e(r.value,r.id)}})}function Rh(e,t){let r=hc.default.get(x.REPLICATION_DATABASES);return(e.replicates===!0||e.replicates?.sends)&&databases[t]&&(r==="*"||r?.find?.(n=>(typeof n=="string"?n:n.name)===t&&(!n.sharded||e.shard===hc.default.get(x.REPLICATION_SHARD))))&&Gt().primaryStore.get(nt())?.replicates||e.subscriptions?.some(n=>(n.database||n.schema)===t&&n.subscribe)}function cde(){ef(e=>{Ec({},(t,r)=>{let n=e.name,s=u1.get(n);if(s||u1.set(n,s=new Map),s.has(r))return;let i;for(let o in t)if(i=t[o].auditStore,i)break;if(i){let o=Zd(i,r,n,()=>{let c=o[0],l=o.lastTime;for(let{txnTime:u,onConfirm:d}of Xd.get(r)||[])u>l&&u<=c&&d();o.lastTime=c});o.lastTime=0,s.set(r,o)}})})}function*bh(e){for(let t of e.routes||[]){let r=t.url,n;if(typeof t=="string"?t.includes("://")?r=t:n=t:n=t.hostname??t.host,n&&!r){let s=hc.default.get(x.REPLICATION_SECUREPORT)??(!hc.default.get(x.REPLICATION_PORT)&&hc.default.get(x.OPERATIONSAPI_NETWORK_SECUREPORT)),i;(i=n.match(/:(\d+)$/)?.[1])?n=n.slice(0,-i[0].length-1):t.port?i=t.port:i=s||hc.default.get(x.REPLICATION_PORT)||hc.default.get(x.OPERATIONSAPI_NETWORK_PORT);let o=i?.lastIndexOf?.(":");o>0&&(i=+i.slice(o+1).replace(/[\[\]]/g,"")),r=(s?"wss://":"ws://")+n+":"+i}if(!r){d1.isMainThread&&console.error("Invalid route, must specify a url or host (with port)");continue}yield{replicates:!t.subscriptions,url:r,subscription:t.subscriptions,routes:t.routes,startTime:t.startTime,revoked_certificates:t.revokedCertificates}}}var d1,f1,hc,m1,l1,u1,Xd,tf=se(()=>{Oe();gs();Bm();d1=require("worker_threads"),f1=b(Ee()),hc=b(fe());G();m1=b(sr());server.nodes=[];a(Gt,"getHDBNodeTable");a(Zd,"getReplicationSharedStatus");a(ef,"subscribeToNodeUpdates");a(Rh,"shouldReplicateToNode");u1=new Map;Ux((e,t,r)=>{if(r>server.nodes.length)throw new f1.ClientError(`Cannot confirm replication to more nodes (${r}) than are in the network (${server.nodes.length})`);Xd||(Xd=new Map,cde());let n=Xd.get(e);return n||(n=[],Xd.set(e,n)),new Promise(s=>{let i=0;n.push({txnTime:t,onConfirm:a(()=>{++i===r&&s()},"onConfirm")})})});a(cde,"startSubscriptionToReplications");a(bh,"iterateRoutes")});var y1={};ye(y1,{connectedToNode:()=>zl,disconnectedFromNode:()=>nf,ensureNode:()=>ia,requestClusterStatus:()=>T1,startOnMainThread:()=>lO});async function lO(e){let t=0,r=lt();for(let o of Object.getOwnPropertyNames(r)){let c=r[o];for(let l in c){let u=c[l];if(u.auditStore){ST.set(o,yh(u.auditStore));break}}}Si.whenThreadsStarted.then(async()=>{let o=[];for await(let u of r.system.hdb_nodes?.search([])||[])o.push(u);let c=nt();function l(){let u=Gt().primaryStore.get(c);if(u!==null){let d=e.url??_c();if(u===void 0||u.url!==d||u.shard!==e.shard)return ia(c,{name:c,url:d,shard:e.shard,replicates:!0})}}a(l,"ensureThisNode"),Gt().primaryStore.get(c)&&l();for(let u of bh(e))try{let d=!u.subscriptions;if(d&&await l(),d&&u.replicates==null&&(u.replicates=!0),h1.push(u),o.find(f=>f.url===u.url))continue;s(u)}catch(d){console.error(d)}ef(s)});let n;function s(o,c=o?.name){let l=nt()&&c===nt()||_c()&&o?.url===_c();if(l){let m=!!o?.replicates;if(n!==void 0&&n!==m)for(let p of Gt().search([]))p.replicates&&p.name!==c&&s(p,p.name);n=m}if(ot.trace("Setting up node replication for",o),!o){for(let[m,p]of mo){let h;for(let[E,{worker:_,nodes:R}]of p){let S=R[0];if(S&&S.name==c){h=!0;for(let[y,{worker:w}]of p)p.delete(y),ot.warn("Node was deleted, unsubscribing from node",c,y,m),w?.postMessage({type:"unsubscribe-from-node",node:c,nodes:R,database:y,url:m});break}}if(h){mo.get(m).iterator.remove(),mo.delete(m);return}}return}if(l)return;if(!o.url){ot.info(`Node ${o.name} is missing url`);return}let u=mo.get(o.url);if(u&&u.iterator.remove(),!(o.replicates===!0||o.replicates?.sends)&&!o.subscriptions?.length&&!u)return;if(ot.info(`Added node ${o.name} at ${o.url} for process ${nt()}`),o.replicates&&o.subscriptions&&(o={...o,subscriptions:null}),o.name){for(let[m,p]of rf)if(o.url===p.url){rf.delete(m);break}rf.set(o.name,o)}let d=lt();if(u||(u=new Map,mo.set(o.url,u)),u.iterator=Ec(e,(m,p,h)=>{h?f(p,!0):f(p,!1)}),o.subscriptions)for(let m of o.subscriptions){let p=m.database||m.schema;d[p]||(ot.warn(`Database ${p} not found for node ${o.name}, making a subscription anyway`),f(p,!1))}function f(m,p){ot.trace("Setting up replication for database",m,"on node",o.name);let h=u.get(m),E,_=[{replicateByDefault:p,...o}];ST.has(m)&&Ah.default.get(x.REPLICATION_FAILOVER)&&(_.push({replicateByDefault:p,name:nt(),startTime:ST.get(m),endTime:Date.now(),replicates:!0}),ST.delete(m));let R=Rh(o,m),S=Si.workers.filter(y=>y.name==="http");if(h){if(E=h.worker,h.nodes=_,R)return}else R&&(t=t%S.length,E=S[t++],E||ot.warn("No http workers available to subscribe to node",o.name,o.url),u.set(m,{worker:E,nodes:_,url:o.url}),E?.on("exit",()=>{u.get(m)?.worker===E&&(u.delete(m),f(m,p))}));if(R){let y=lde.HDB_LEADER_URL??process.env.HDB_LEADER_URL??h1[0]?.url,w=y?new URL(y).hostname:Array.from(Gt().primaryStore.getKeys({}).filter(H=>H!==nt()))[0],I=_[0].name??(_[0].url&&new URL(_[0].url).hostname);ot.warn(`Setting up subscription with leader ${w} for node ${I}`),_[0].isLeader=!w||I===w,setTimeout(()=>{let H={..._[0],type:"subscribe-to-node",database:m,nodes:_};E?E.postMessage(H):Ih(H)},ude)}else{ot.info("Node no longer should be used, unsubscribing from node",{replicates:o.replicates,databaseName:m,node:o,subscriptions:o.subscriptions,hasDatabase:!!d[m],thisReplicates:Gt().primaryStore.get(nt())?.replicates}),Gt().primaryStore.get(nt())?.replicates||(n=!1,ot.info("Disabling replication, this node name",nt(),Gt().primaryStore.get(nt()),m));let y={type:"unsubscribe-from-node",database:m,url:o.url,name:o.name,nodes:_};E?E.postMessage(y):yT(y)}}a(f,"onDatabase")}a(s,"onNodeUpdate"),nf=a(function(o){try{ot.info("Disconnected from node",o.name,o.url,"finished",!!o.finished);let c=Array.from(rf.keys()),l=c.sort(),u=l.indexOf(o.name||Ti(o.url));if(u===-1){ot.warn("Disconnected node not found in node map",o.name,c);return}let d=mo.get(o.url),f=d?.get(o.database);if(!f){ot.warn("Disconnected node not found in replication map",o.database,d);return}if(f.connected=!1,o.finished||!Ah.default.get(x.REPLICATION_FAILOVER))return;let m=f.nodes[0];if(!(m.replicates===!0||m.replicates?.sends||m.subscriptions?.length))return;let p=m.shard,h=(u+1)%l.length;for(;u!==h;){let E=l[h],_=rf.get(E);d=mo.get(_.url);let R=d?.get(o.database);if(!R||R.connected===!1||R.nodes[0].shard!==p){h=(h+1)%l.length;continue}let{nodes:S}=R,y=!1;for(let w of f.nodes){if(S.some(I=>I.name===w.name)){ot.info(`Disconnected node is already failing over to ${E} for ${o.database}`);continue}w.endTime<Date.now()||(S.push(w),ot.info(`Failing over ${o.database} from ${o.name} to ${E}`),i(w,o.database,R.nodes[0]),y=!0)}f.nodes=[f.nodes[0]],y||ot.info(`Disconnected node ${o.name} has no nodes to fail over to ${E}`);return}ot.warn("Unable to find any other node to fail over to",o.name,o.url)}catch(c){ot.error("Error failing over node",c)}},"disconnectedFromNode"),zl=a(function(o){let c=mo.get(o.url),l=c?.get(o.database);if(!l){ot.warn("Connected node not found in replication map, this may be because the node is being removed",o.database,c);return}l.connected=!0,l.latency=o.latency;let u=l.nodes[0];if(!u){ot.warn("Newly connected node has no node subscriptions",o.database,l);return}if(!u.name){ot.debug("Connected node is not named yet",o.database,l);return}if(!Ah.default.get(x.REPLICATION_FAILOVER))return;l.nodes=[u];let d=!1;for(let f of mo.values()){let m=f.get(o.database);if(!m||m==l)continue;let{worker:p,nodes:h,connected:E}=m;if(h)if(E===!1&&h[0].shard===u.shard&&node.url===u.url)for(let _ of h)i(_,o.database);else{let _=h.filter(R=>{if(R)return R.name===u.name&&R.worker?(R.worker.postMessage({type:"unsubscribe-to-node",database:o.database,url:o.url,nodes:[R]}),!1):!0});_.length<h.length&&(m.nodes=_)}}},"connectedToNode");function i(o,c,l=o){let u=Si.workers.filter(f=>f.name==="http");t=t%u.length;let d=u[t++];Object.defineProperty(o,"worker",{value:d,configurable:!0}),d?d.postMessage({url:l.url,name:l.name,type:"subscribe-to-node",database:c,nodes:[o]}):Ih({url:l.url,name:l.name,database:c,nodes:[o]})}a(i,"connectToNextWorker"),(0,Si.onMessageByType)("disconnected-from-node",nf),(0,Si.onMessageByType)("connected-to-node",zl),(0,Si.onMessageByType)("request-cluster-status",T1)}function T1(e,t){let r=[];for(let[n,s]of rf)try{let i=mo.get(s.url);ot.info("Getting cluster status for",n,s.url,"has dbs",i?.size);let o=[];if(i){for(let[l,{worker:u,connected:d,nodes:f,latency:m}]of i)o.push({database:l,connected:d,latency:m,threadId:u?.threadId,nodes:f.filter(p=>!(p.endTime<Date.now())).map(p=>p.name)});let c=_1(s);c.database_sockets=o,delete c.ca,delete c.node_name,delete c.__updatedtime__,delete c.__createdtime__,r.push(c)}}catch(i){ot.warn("Error getting cluster status for",s?.url,i)}return t?.postMessage({type:"cluster-status",connections:r}),{connections:r}}async function ia(e,t){let r=Gt();e=e??Ti(t.url),t.name=e;try{if(t.ca){let s=new g1.X509Certificate(t.ca);t.ca_info={issuer:s.issuer.replace(/\n/g," "),subject:s.subject.replace(/\n/g," "),subjectAltName:s.subjectAltName,serialNumber:s.serialNumber,validFrom:s.validFrom,validTo:s.validTo}}}catch(s){ot.error("Error parsing replication CA info for hdb_nodes table",s.message)}let n=r.primaryStore.get(e);if(ot.debug(`Ensuring node ${e} at ${t.url}, existing record:`,n,"new record:",t),!n)await r.patch(t);else{t.replicates&&!Ah.default.get(x.CLUSTERING_ENABLED)&&(t.subscriptions=null);for(let s in t)if(n[s]!==t[s]&&s==="subscriptions"&&t[s]&&n[s]){let i=[],o=_1(n[s]);for(let c of t[s]){let l=!1;for(let u of o)if((c.database??c.schema)===(u.database??u.schema)&&c.table===u.table){u.publish=c.publish,u.subscribe=c.subscribe,l=!0;break}l||i.push(c)}t.subscriptions=[...o,...i];break}if(Array.isArray(t.revoked_certificates)){let s=n.revoked_certificates||[];t.revoked_certificates=[...new Set([...s,...t.revoked_certificates])]}ot.info(`Updating node ${e} at ${t.url}`),await r.patch(t)}}var Si,TT,ot,E1,Ah,g1,S1,_1,lde,ude,mo,nf,zl,rf,ST,h1,wh=se(()=>{Oe();Si=b(st());gs();TT=require("worker_threads");tf();ot=b(Q()),E1=b(require("lodash")),Ah=b(fe());G();g1=require("crypto"),S1=b(require("minimist")),{cloneDeep:_1}=E1.default,lde=(0,S1.default)(process.argv),ude=200,mo=new Map,rf=new Map,ST=new Map,h1=[];a(lO,"startOnMainThread");a(T1,"requestClusterStatus");TT.parentPort&&(nf=a(e=>{TT.parentPort.postMessage({type:"disconnected-from-node",...e})},"disconnectedFromNode"),zl=a(e=>{TT.parentPort.postMessage({type:"connected-to-node",...e})},"connectedToNode"),(0,Si.onMessageByType)("subscribe-to-node",e=>{Ih(e)}),(0,Si.onMessageByType)("unsubscribe-from-node",e=>{yT(e)}));a(ia,"ensureNode")});var Ts=M(qt=>{"use strict";var gr=require("path"),{watch:dde}=require("chokidar"),Yn=require("fs-extra"),sf=require("node-forge"),N1=require("net"),{generateKeyPair:uO,X509Certificate:oa,createPrivateKey:C1,randomBytes:fde}=require("node:crypto"),mde=require("util");uO=mde.promisify(uO);var Mt=sf.pki,yi=require("joi"),{v4:O1}=require("uuid"),{validateBySchema:pO}=mt(),{forComponent:pde}=Q(),Ss=fe(),Vs=(G(),D(j)),{CONFIG_PARAMS:Ql}=Vs,Ri=cA(),{ClientError:gc}=Ee(),bT=require("node:tls"),{relative:P1,join:hde}=require("node:path"),{CERTIFICATE_VALUES:R1}=Ri,Ede=el(),dO=_t(),{table:_de,getDatabases:gde,databases:RT}=(Oe(),D(pt)),{getJWTRSAKeys:b1}=(Kd(),D(dh)),Xe=pde("tls").conditional;qt.generateKeys=_O;qt.updateConfigCert=F1;qt.createCsr=Ide;qt.signCertificate=wde;qt.setCertTable=of;qt.loadCertificates=U1;qt.reviewSelfSignedCert=SO;qt.createTLSSelector=H1;qt.listCertificates=q1;qt.addCertificate=Dde;qt.removeCertificate=Mde;qt.createNatsCerts=Ode;qt.generateCertsKeys=Cde;qt.getReplicationCert=Ch;qt.getReplicationCertAuth=Ade;qt.renewSelfSigned=Pde;qt.hostnamesFromCert=yO;qt.getKey=Ude;qt.getHostnamesFromCertificate=xde;qt.getPrimaryHostName=TO;qt.generateSerialNumber=wT;var{urlToNodeName:L1,getThisNodeUrl:Sde,getThisNodeName:IT,clearThisNodeName:Tde}=(gs(),D(aa)),{readFileSync:yde,statSync:D1}=require("node:fs"),O0e=fe(),{getTicketKeys:Rde,onMessageFromWorkers:bde}=st(),{isMainThread:v1}=require("worker_threads"),{TLSSocket:M1,createSecureContext:P0e}=require("node:tls"),hO=3650,Nh=["127.0.0.1","localhost","::1"],EO=[{name:"countryName",value:"USA"},{name:"stateOrProvinceName",value:"Colorado"},{name:"localityName",value:"Denver"},{name:"organizationName",value:"HarperDB, Inc."}];function wT(){let e=fde(8);return e[0]=e[0]&127|1,e.toString("hex")}a(wT,"generateSerialNumber");bde(async e=>{e.type===Vs.ITC_EVENT_TYPES.RESTART&&(Ss.initSync(!0),await SO())});var an;function Tc(){return an||(an=gde().system.hdb_certificate,an||(an=_de({table:"hdb_certificate",database:"system",attributes:[{name:"name",isPrimaryKey:!0},{attribute:"uses"},{attribute:"certificate"},{attribute:"is_authority"},{attribute:"private_key_name"},{attribute:"details"},{attribute:"is_self_signed"},{attribute:"__updatedtime__"}]}))),an}a(Tc,"getCertTable");async function Ch(){let e=H1("operations-api"),t={secureContexts:null,setSecureContext:a(s=>{},"setSecureContext")};await e.initialize(t);let r=t.secureContexts.get(IT());if(!r)return;let n=new oa(r.options.cert);return r.cert_parsed=n,r.issuer=n.issuer,r}a(Ch,"getReplicationCert");async function Ade(){Tc();let e=(await Ch()).options.cert,r=new oa(e).issuer.match(/CN=(.*)/)?.[1];return an.get(r)}a(Ade,"getReplicationCertAuth");var A1,Sc=new Map;function U1(){if(A1)return;A1=!0;let e=[{configKey:Ql.TLS},{configKey:Ql.OPERATIONSAPI_TLS}];Tc();let t=gr.dirname(dO.getConfigFilePath()),r;for(let{configKey:n}of e){let s=dO.getConfigFromFile(n);if(s){Array.isArray(s)||(s=[s]);for(let i of s){let o=i.privateKey,c=o&&P1(hde(t,"keys"),o);c&&I1(o,l=>{Sc.set(c,l)},"private key");for(let l of[!1,!0]){let u=i[l?"certificateAuthority":"certificate"];if(u&&v1){let d;I1(u,f=>{if(R1.cert===f)return;let m=i.hostname??i.hostnames??i.host??i.hosts;m&&!Array.isArray(m)&&(m=[m]);let p=k1(u),h=new oa(p),E;try{E=TO(h)}catch(y){Xe.error?.("error extracting host name from certificate",y);return}if(E==null){Xe.error?.("No host name found on certificate");return}if(h.checkIssued(new oa(R1.cert)))return;let _=an.primaryStore.get(E),R=D1(u).mtimeMs,S=!_||_.is_self_signed?1:_.file_timestamp??_.__updatedtime__;if(_&&R<=S){R<S&&Xe.info?.(`Certificate ${E} at ${u} is older (${new Date(R)}) than the certificate in the database (${S>1?new Date(S):"only self signed certificate available"})`);return}r=an.put({name:E,uses:["https",...n.includes("operations")?["operations"]:[]],ciphers:i.ciphers,certificate:p,private_key_name:c,is_authority:l,hostnames:m,fileTimestamp:R,details:{issuer:h.issuer.replace(/\n/g," "),subject:h.subject?.replace(/\n/g," "),subject_alt_name:h.subjectAltName,serial_number:h.serialNumber,valid_from:h.validFrom,valid_to:h.validTo}})},l?"certificate authority":"certificate")}}}}}return r}a(U1,"loadCertificates");function I1(e,t,r){let n,s=a((i,o)=>{try{let c=o.mtimeMs;c&&c!==n&&(n&&v1&&Xe.warn?.(`Reloading ${r}:`,i),n=c,t(k1(i)))}catch(c){Xe.error?.(`Error loading ${r}:`,i,c)}},"loadFile");Yn.existsSync(e)?s(e,D1(e)):Xe.error?.(`${r} file not found:`,e),dde(e,{persistent:!1}).on("change",s)}a(I1,"loadAndWatch");function fO(){let e=Sde();if(e==null){let t=Nh[0];return Xe.info?.("replication url is missing from harperdb-config.yaml, using default host"+t),t}return L1(e)}a(fO,"getHost");function AT(){let e=IT();if(e==null){let t=Nh[0];return Xe.info?.("replication url is missing from harperdb-config.yaml, using default host"+t),t}return e}a(AT,"getCommonName");async function Ide(){let e=await Ch(),t=Mt.certificateFromPem(e.options.cert),r=Mt.privateKeyFromPem(e.options.key);Xe.info?.("Creating CSR with cert named:",e.name);let n=Mt.createCertificationRequest();n.publicKey=t.publicKey;let s=[{name:"commonName",value:AT()},...EO];Xe.info?.("Creating CSR with subject",s),n.setSubject(s);let i=[{name:"unstructuredName",value:"HarperDB, Inc."},{name:"extensionRequest",extensions:x1()}];return Xe.info?.("Creating CSR with attributes",i),n.setAttributes(i),n.sign(r),sf.pki.certificationRequestToPem(n)}a(Ide,"createCsr");function x1(){let e=Nh.includes(AT())?Nh:[...Nh,AT()];return e.includes(fO())||e.push(fO()),[{name:"basicConstraints",cA:!1,critical:!0},{name:"keyUsage",digitalSignature:!0,keyEncipherment:!0,critical:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"nsCertType",client:!0,server:!0},{name:"subjectAltName",altNames:e.map(t=>N1.isIP(t)?{type:7,ip:t}:{type:2,value:t})}]}a(x1,"certExtensions");async function wde(e){let t={},r=gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME);if(e.csr){let n,s;Tc();for await(let d of an.search([]))if(d.is_authority&&!d.details.issuer.includes("HarperDB-Certificate-Authority")){if(Sc.has(d.private_key_name)){n=Sc.get(d.private_key_name),s=d;break}else if(d.private_key_name&&await Yn.exists(gr.join(r,d.private_key_name))){n=Yn.readFile(gr.join(r,d.private_key_name)),s=d;break}}if(!n){let d=await mO();s=d.ca,n=d.private_key}n=Mt.privateKeyFromPem(n),t.signingCA=s.certificate;let i=Mt.certificateFromPem(s.certificate);Xe.info?.("Signing CSR with cert named",s.name);let o=Mt.certificationRequestFromPem(e.csr);try{o.verify()}catch(d){return Xe.error?.(d),new Error("Error verifying CSR: "+d.message)}let c=sf.pki.createCertificate();c.serialNumber=wT(),c.validity.notBefore=new Date;let l=new Date;c.validity.notAfter=l,c.validity.notAfter.setDate(l.getDate()+hO),Xe.info?.("sign cert setting validity:",c.validity),Xe.info?.("sign cert setting subject from CSR:",o.subject.attributes),c.setSubject(o.subject.attributes),Xe.info?.("sign cert setting issuer:",i.subject.attributes),c.setIssuer(i.subject.attributes);let u=o.getAttribute({name:"extensionRequest"}).extensions;Xe.info?.("sign cert adding extensions from CSR:",u),c.setExtensions(u),c.publicKey=o.publicKey,c.sign(n,sf.md.sha256.create()),t.certificate=Mt.certificateToPem(c)}else Xe.info?.("Sign cert did not receive a CSR from:",e.url,"only the CA will be returned");return t}a(wde,"signCertificate");async function Nde(e,t){await of({name:IT(),uses:["https","wss"],certificate:e,private_key_name:"privateKey.pem",is_authority:!1,is_self_signed:!0}),await of({name:t.subject.getField("CN").value,uses:["https","wss"],certificate:Mt.certificateToPem(t),private_key_name:"privateKey.pem",is_authority:!0,is_self_signed:!0})}a(Nde,"createCertificateTable");async function of(e){let t;try{t=new oa(e.certificate)}catch(r){Xe.error?.(`Failed to parse certificate for ${e.name}:`,r.message),Xe.debug?.("Certificate record details:",JSON.stringify(e,null,2));let n=new Error(`Invalid certificate format for ${e.name}: ${r.message}. This may be due to corrupted certificate data during transfer or encoding issues.`);throw n.code="INVALID_CERTIFICATE_FORMAT",n.cause=r,n}e.details={issuer:t.issuer.replace(/\n/g," "),subject:t.subject?.replace(/\n/g," "),subject_alt_name:t.subjectAltName,serial_number:t.serialNumber,valid_from:t.validFrom,valid_to:t.validTo},Tc(),await an.patch(e)}a(of,"setCertTable");async function _O(){let e=await uO("rsa",{modulusLength:4096,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKey:Mt.publicKeyFromPem(e.publicKey),privateKey:Mt.privateKeyFromPem(e.privateKey)}}a(_O,"generateKeys");async function gO(e,t,r){let n=Mt.createCertificate();if(!t){let o=await Ch();t=Mt.certificateFromPem(o.options.cert).publicKey}n.publicKey=t,n.serialNumber=wT(),n.validity.notBefore=new Date;let s=new Date;n.validity.notAfter=s,n.validity.notAfter.setDate(s.getDate()+hO);let i=[{name:"commonName",value:AT()},...EO];return n.setSubject(i),n.setIssuer(r.subject.attributes),n.setExtensions(x1()),n.sign(e,sf.md.sha256.create()),Mt.certificateToPem(n)}a(gO,"generateCertificates");async function mO(){let e=await q1(),t;for(let r of e){if(!r.is_authority)continue;let n=await G1(r.private_key_name);if(r.private_key_name&&n&&new oa(r.certificate).checkPrivateKey(C1(n))){Xe.trace?.(`CA named: ${r.name} found with matching private key`),t={ca:r,private_key:n};break}}if(t)return t;Xe.trace?.("No CA found with matching private key")}a(mO,"getCertAuthority");async function B1(e,t,r=!0){let n=Mt.createCertificate();n.publicKey=t,n.serialNumber=wT(),n.validity.notBefore=new Date;let s=new Date;n.validity.notAfter=s,n.validity.notAfter.setDate(s.getDate()+hO);let i=[{name:"commonName",value:`HarperDB-Certificate-Authority-${Ss.get(Ql.REPLICATION_HOSTNAME)??L1(Ss.get(Ql.REPLICATION_URL))??O1().split("-")[0]}`},...EO];n.setSubject(i),n.setIssuer(i),n.setExtensions([{name:"basicConstraints",cA:!0,critical:!0},{name:"keyUsage",keyCertSign:!0,critical:!0},{name:"subjectKeyIdentifier"}]),n.sign(e,sf.md.sha256.create());let o=gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME),c=gr.join(o,Ri.PRIVATEKEY_PEM_NAME);return r&&await Yn.writeFile(c,Mt.privateKeyToPem(e)),n}a(B1,"generateCertAuthority");async function Cde(){let{privateKey:e,publicKey:t}=await _O(),r=await B1(e,t),n=await gO(e,t,r);await Nde(n,r),F1()}a(Cde,"generateCertsKeys");async function Ode(){let e=await gO(Mt.privateKeyFromPem(Ri.CERTIFICATE_VALUES.key),void 0,Mt.certificateFromPem(Ri.CERTIFICATE_VALUES.cert)),t=gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME),r=gr.join(t,Ri.NATS_CERTIFICATE_PEM_NAME);await Yn.exists(r)||await Yn.writeFile(r,e);let n=gr.join(t,Ri.NATS_CA_PEM_NAME);await Yn.exists(n)||await Yn.writeFile(n,Ri.CERTIFICATE_VALUES.cert)}a(Ode,"createNatsCerts");async function Pde(){Tc();for await(let e of an.search([{attribute:"is_self_signed",value:!0}]))await an.delete(e.name);await SO()}a(Pde,"renewSelfSigned");async function SO(){Tde(),await U1(),Tc();let e=await mO();if(!e){Xe.notify?.("A matching Certificate Authority and key was not found. A new CA will be created in advance, so it's available if needed.");let r=a(u=>{try{return{key:Mt.privateKeyFromPem(Yn.readFileSync(u)),keyPath:u}}catch(d){return Xe.warn?.(`Failed to parse private key from ${u}:`,d.message),{key:null,keyPath:u}}},"tryToParseKey"),n=Ss.get(Ql.TLS),s,i;if(Array.isArray(n)){for(let u of n)if(u.privateKey){let d=r(u.privateKey);if(s=d.key,i=d.keyPath,d.key)break}}else{let u=Ss.get(Ql.TLS_PRIVATEKEY),d=r(u);s=d.key,i=d.keyPath}let o=gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME),c=P1(o,i);s||(Xe.warn?.("Unable to parse the TLS key",i,"A new key will be generated and used to create Certificate Authority"),{privateKey:s}=await _O(),Yn.existsSync(gr.join(o,Ri.PRIVATEKEY_PEM_NAME))&&(c=`privateKey${O1().split("-")[0]}.pem`),await Yn.writeFile(gr.join(o,c),Mt.privateKeyToPem(s)));let l=await B1(s,Mt.setRsaPublicKey(s.n,s.e),!1);await of({name:l.subject.getField("CN").value,uses:["https"],certificate:Mt.certificateToPem(l),private_key_name:c,is_authority:!0,is_self_signed:!0})}if(!await Ch()){let r=IT();Xe.notify?.(`A suitable replication certificate was not found, creating new self singed cert named: ${r}`),e=e??await mO();let n=Mt.certificateFromPem(e.ca.certificate),s=n.publicKey,i=await gO(Mt.privateKeyFromPem(e.private_key),s,n);await of({name:r,uses:["https","operations","wss"],certificate:i,is_authority:!1,private_key_name:e.ca.private_key_name,is_self_signed:!0})}}a(SO,"reviewSelfSignedCert");function F1(){let e=Ede(Object.keys(Vs.CONFIG_PARAM_MAP),!0),t=gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME),r=gr.join(t,Ri.PRIVATEKEY_PEM_NAME),n=gr.join(t,Ri.NATS_CERTIFICATE_PEM_NAME),s=gr.join(t,Ri.NATS_CA_PEM_NAME),i=Vs.CONFIG_PARAMS,o={[i.TLS_PRIVATEKEY]:e[i.TLS_PRIVATEKEY.toLowerCase()]?e[i.TLS_PRIVATEKEY.toLowerCase()]:r};e[i.TLS_CERTIFICATE.toLowerCase()]&&(o[i.TLS_CERTIFICATE]=e[i.TLS_CERTIFICATE.toLowerCase()]),e[i.TLS_CERTIFICATEAUTHORITY.toLowerCase()]&&(o[i.TLS_CERTIFICATEAUTHORITY]=e[i.TLS_CERTIFICATEAUTHORITY.toLowerCase()]),e[i.OPERATIONSAPI_TLS_CERTIFICATE.toLowerCase()]&&(o[i.OPERATIONSAPI_TLS_CERTIFICATE]=e[i.OPERATIONSAPI_TLS_CERTIFICATE.toLowerCase()]),e[i.OPERATIONSAPI_TLS_PRIVATEKEY.toLowerCase()]&&(o[i.OPERATIONSAPI_TLS_PRIVATEKEY]=e[i.OPERATIONSAPI_TLS_PRIVATEKEY.toLowerCase()]),e[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY.toLowerCase()]&&(o[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY]=e[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY.toLowerCase()]),(e[i.CLUSTERING_ENABLED.toLowerCase()]||e.clustering)&&(o[i.CLUSTERING_TLS_CERTIFICATE]=e[i.CLUSTERING_TLS_CERTIFICATE.toLowerCase()]??n,o[i.CLUSTERING_TLS_CERT_AUTH]=e[i.CLUSTERING_TLS_CERT_AUTH.toLowerCase()]??s,o[i.CLUSTERING_TLS_PRIVATEKEY]=e[i.CLUSTERING_TLS_PRIVATEKEY.toLowerCase()]??r),dO.updateConfigValue(void 0,void 0,o,!1,!0)}a(F1,"updateConfigCert");function k1(e){return e.startsWith("-----BEGIN")?e:yde(e,"utf8")}a(k1,"readPEM");var w1=bT.createSecureContext;bT.createSecureContext=function(e){if(!e.cert||!e.key)return w1(e);let t={...e};delete t.key,delete t.cert;let r=w1(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};var Lde=M1.prototype._init;M1.prototype._init=function(e,t){Lde.call(this,e,t);let r=this;this._handle.oncertcb=function(n){let s=n.servername;r._SNICallback(s,(i,o)=>{this.sni_context=o?.context||o,this.certCbDone()})}};var Jl=new Map;function H1(e,t){let r=new Map,n,s=!1;return i.initialize=o=>i.ready?i.ready:(o&&(o.secureContexts=r,o.secureContextsListeners=[]),i.ready=new Promise((c,l)=>{async function u(){try{r.clear(),Jl.clear();let d=0;if(RT===void 0){c();return}for await(let f of RT.system.hdb_certificate.search([])){let m=f.certificate,p=new oa(m);f.is_authority&&(p.asString=m,Jl.set(p.subject,m))}for await(let f of RT.system.hdb_certificate.search([]))try{if(f.is_authority)continue;let m=e==="operations-api",p=f.is_self_signed?1:3;m&&f.uses?.includes?.("operations")&&(p+=1);let h=await G1(f.private_key_name),E=f.certificate,_=new oa(E);if(Jl.has(_.issuer)&&(E+=`
18
- `+Jl.get(_.issuer)),!h||!E)throw new Error("Missing private key or certificate for secure server");let R={ciphers:f.ciphers,ticketKeys:Rde(),availableCAs:Jl,ca:t&&Array.from(Jl.values()),cert:E,key:h,key_file:f.private_key_name,is_self_signed:f.is_self_signed};o&&(R.sessionIdContext=o.sessionIdContext);let S=f.hostnames??yO(_);Array.isArray(S)||(S=[S]);for(let I of S)I===fO()&&(p+=1);let y=bT.createSecureContext(R);y.name=f.name,y.options=R,y.quality=p,y.certificateAuthorities=Array.from(Jl),y.certStart=E.toString().slice(0,100);let w;for(let I of S)if(I){I[0]==="*"&&(s=!0,I=I.slice(1)),N1.isIP(I)&&(w=!0);let H=r.get(I)?.quality??0;Xe.trace?.("Assigning TLS for hostname",I,"if",p,">",H),p>H&&r.set(I,y)}else Xe.error?.("No hostname found for certificate at",bT.certificate);Xe.trace?.("Adding TLS",y.name,"for",o.ports||"client","cert named",f.name,"hostnames",S,"quality",p,"best quality",d),p>d&&(i.defaultContext=n=y,d=p,o&&(o.defaultContext=y))}catch(m){Xe.error?.("Error applying TLS for",f.name,m)}o?.secureContextsListeners.forEach(f=>f()),c(n)}catch(d){l(d)}}a(u,"updateTLS"),RT?.system.hdb_certificate.subscribe({listener:a(()=>setTimeout(()=>u(),1500).unref(),"listener"),omitCurrent:!0}),u()})),i;function i(o,c){Xe.info?.("TLS requested for",o||"(no SNI)");let l=o;for(;;){let d=r.get(l);if(d)return Xe.debug?.("Found certificate for",o,d.certStart),d.updatedContext&&(d=d.updatedContext),c(null,d);if(s&&l){let f=l.indexOf(".",1);f<0?l="":l=l.slice(f)}else break}o?Xe.debug?.("No certificate found to match",o,"using the default certificate"):Xe.debug?.("No SNI, using the default certificate",n?.name);let u=n;u?u.updatedContext&&(u=u.updatedContext):Xe.info?.("No default certificate found"),c(null,u)}a(i,"SNICallback")}a(H1,"createTLSSelector");async function G1(e){let t=Sc.get(e);return!t&&e?await Yn.readFile(gr.join(Ss.get(Ql.ROOTPATH),Vs.LICENSE_KEY_DIR_NAME,e),"utf8"):t}a(G1,"getPrivateKeyByName");async function q1(){Tc();let e=[];for await(let t of an.search([]))e.push(t);return e}a(q1,"listCertificates");async function Dde(e){let t=pO(e,yi.object({name:yi.string().required(),certificate:yi.string().required(),is_authority:yi.boolean().required(),private_key:yi.string(),hosts:yi.array(),uses:yi.array()}));if(t)throw new gc(t.message);let{name:r,certificate:n,private_key:s,is_authority:i}=e,o=new oa(n),c=!1,l=!1,u;for(let[p,h]of Sc)!s&&!c&&o.checkPrivateKey(C1(h))&&(c=!0,u=p),s&&s===h&&(l=!0,u=p);if(!i&&!s&&!c)throw new gc("A suitable private key was not found for this certificate");let d;if(!r){try{d=TO(o)}catch(p){Xe.error?.(p)}if(d==null)throw new gc("Error extracting certificate host name, please provide a name parameter")}let f=vde(r??d);s&&!c&&!l&&(await Yn.writeFile(gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,f+".pem"),s),Sc.set(f,s));let m={name:r??d,certificate:n,is_authority:i,hosts:e.hosts,uses:e.uses};return(!i||i&&u||i&&s)&&(m.private_key_name=u??f+".pem"),e.ciphers&&(m.ciphers=e.ciphers),await of(m),"Successfully added certificate: "+f}a(Dde,"addCertificate");function vde(e){return e.replace(/[^a-z0-9\.]/gi,"-")}a(vde,"sanitizeName");async function Mde(e){let t=pO(e,yi.object({name:yi.string().required()}));if(t)throw new gc(t.message);let{name:r}=e;Tc();let n=await an.get(r);if(!n)throw new gc(r+" not found");let{private_key_name:s}=n;if(s){let i=Array.from(await an.search([{attribute:"private_key_name",value:s}]));i.length===1&&i[0].name===r&&(Xe.info?.("Removing private key named",s),await Yn.remove(gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,s)))}return await an.delete(r),"Successfully removed "+r}a(Mde,"removeCertificate");function TO(e){let t=e.subject?.match(/CN=(.*)/)?.[1];return t||yO(e)[0]}a(TO,"getPrimaryHostName");function yO(e){if(e.subjectAltName)return e.subjectAltName.split(",").map(r=>{let n=r.indexOf(":");if(r=r.slice(n+1),r=r.trim(),r[0]==='"')try{r=JSON.parse(r)}catch{}return r.indexOf("=")>-1?r.match(/CN=([^,]*)/)?.[1]:r}).filter(r=>r);let t=e.subject?.match(/CN=(.*)/)?.[1];return t?[t]:[]}a(yO,"hostnamesFromCert");async function Ude(e){if(e.bypass_auth!==!0)throw new gc("Unauthorized","401");let t=pO(e,yi.object({name:yi.string().required()}));if(t)throw new gc(t.message);let{name:r}=e;if(r===".jwtPrivate")return(await b1()).privateKey;if(r===".jwtPublic")return(await b1()).publicKey;if(Sc.get(r))return Sc.get(e.name);throw new gc("Key not found")}a(Ude,"getKey");function xde(e){return[e.subject?.CN,...e.subjectaltname.split(",").filter(t=>t.trim().startsWith("DNS:")).map(t=>t.trim().substring(4))]}a(xde,"getHostnamesFromCertificate")});var dK={};ye(dK,{BACK_PRESSURE_RATIO_POSITION:()=>lK,CONFIRMATION_STATUS_POSITION:()=>cK,LATENCY_POSITION:()=>MT,NodeReplicationConnection:()=>cf,OPERATION_REQUEST:()=>wO,RECEIVED_TIME_POSITION:()=>DT,RECEIVED_VERSION_POSITION:()=>LT,RECEIVING_STATUS_POSITION:()=>vT,RECEIVING_STATUS_RECEIVING:()=>uK,RECEIVING_STATUS_WAITING:()=>NO,SENDING_TIME_POSITION:()=>Ph,createWebSocket:()=>UT,databaseSubscriptions:()=>Rc,replicateOverWS:()=>Lh,tableUpdateListeners:()=>PO});async function UT(e,t){let{authorization:r,rejectUnauthorized:n}=t||{},s=nt(),i;if(e==null)throw new TypeError(`Invalid URL: Expected a string URL for node "${s}" but received ${e}`);if(e.includes("wss://")){if(!AO){let l=(0,sK.createTLSSelector)("operations-api"),u={secureContexts:null};await l.initialize(u),AO=u.secureContexts}if(i=AO.get(s),i&&le.debug?.("Creating web socket for URL",e,"with certificate named:",i.name),!i&&n!==!1)throw new Error("Unable to find a valid certificate to use for replication to connect to "+e)}let o={};r&&(o.Authorization=r);let c={headers:o,localAddress:s?.startsWith("127.0")?s:void 0,servername:(0,oK.isIP)(t?.serverName)?void 0:t?.serverName,noDelay:!0,highWaterMark:128*1024,rejectUnauthorized:n!==!1,secureContext:void 0};return i&&((af?.caCount!==ca.size||af?.derivedFromContext!==i)&&(af=iK.createSecureContext({...i.options,ca:[...ca,...i.options.availableCAs.values()]}),af.caCount=ca.size,af.derivedFromContext=i),c.secureContext=af),new tK.WebSocket(e,"harperdb-replication-v1",c)}function Lh(e,t,r){let n=t.port||t.securePort,s=OO.pid%1e3+"-"+rK.threadId+(n?"s:"+n:"c:"+t.url?.slice(-4))+" "+Math.random().toString().slice(2,3);le.debug?.(s,"Initializing replication connection",r);let i=0,o=Buffer.allocUnsafeSlow(1024),c=0,l=new DataView(o.buffer,0,1024),u=t.database,d=t.databaseSubscriptions||Rc,f,m,p=!1,h=t.subscription;h?.then&&h.then(A=>{h=A,h.auditStore&&(f=h.auditStore)});let E=t.tables||u&&lt()[u],_,R=new Map,S=[];_=r.name,_&&t.connection&&(t.connection.nodeName=_);let y,w,I,H,X,q,k,z=6e4,Y,ce=0,de=0,te=0,Se=eK.default.get(x.REPLICATION_BLOBTIMEOUT)??12e4,Ne=new Map,Ke=[],$e=0,Ir;if(t.url){let A=a(()=>{X&&de===e._socket?.bytesRead&&te===e._socket?.bytesWritten?e.terminate():(X=performance.now(),e.ping(),de=e._socket?.bytesRead,te=e._socket?.bytesWritten)},"sendPing");I=setInterval(A,X1).unref(),A()}else nr();e._socket?.setMaxListeners(200);function nr(){clearTimeout(H),de=e._socket?.bytesRead,te=e._socket?.bytesWritten,H=setTimeout(()=>{de===e._socket?.bytesRead&&te===e._socket?.bytesWritten&&(le.warn?.(`Timeout waiting for ping from ${_}, terminating connection and reconnecting`),e.terminate())},X1*2).unref()}a(nr,"resetPingTimer");let zr=0,xr=0,Pu=!1,zc=3e4;function Ft(){if(pn?.length>0){let A=performance.now(),U=A-xr;zr=(zr*zc+(Pu?U:0))/(zc+U),m&&(m[lK]=zr),xr=A}}a(Ft,"updateBackPressureRatio"),setInterval(Ft,zc).unref();function Ps(){if(!(!_||!u))return m||(m=Zd(f,u,_)),m}a(Ps,"getSharedStatus"),u&&Jc(u);let Ha,o_,cm=[],a_=[],lm,ve=[],c_=[],Yb=[],Lu=150,ki=25,Ls=0,um=0,dm=!1,xo,Dn,pn,Br;e.on("message",Du);async function Du(A){if(r=await r,!r){le.error?.(s,"No authorization provided"),Fr(1008,"Unauthorized");return}fm(A),e.off("message",Du),e.on("message",fm)}a(Du,"onWSMessageWhenAuthorized");function fm(A){ce=performance.now();try{let U=A.dataView=new ul(A.buffer,A.byteOffset,A.byteLength);if(A[0]>127){let W=(0,at.decode)(A),[J,F,he]=W;switch(J){case V1:{if(F){if(_){if(_!==F){le.error?.(s,`Node name mismatch, expecting to connect to ${_}, but peer reported name as ${F}, disconnecting`),e.send((0,at.encode)([Oh])),Fr(1008,"Node name mismatch");return}}else if(_=F,t.connection?.tentativeNode){let me=t.connection.tentativeNode;me.name=_,t.connection.tentativeNode=null,ia(_,me)}if(t.connection&&(t.connection.nodeName=_),le.debug?.(s,"received node name:",_,"db:",u??W[2]),!u)try{Jc(u=W[2]),u==="system"&&(Ha=Ec(t,(me,ie)=>{$a(ie)&&K(ie)}),e.on("close",()=>{Ha?.remove()}))}catch(me){le.warn?.(s,"Error setting database",me),e.send((0,at.encode)([Oh])),Fr(1008,me.message);return}mm()}break}case J1:{le.debug?.(s,"Received table definitions for",F.map(me=>me.table));for(let me of F){let ie=W[2];me.database=ie;let Ce;if($a(ie)){if(u==="system")Me[ie]?.[me.table]||(Ce=v(me,Me[ie]?.[me.table]));else{if(ie!=="data"&&!Me[ie]){le.warn?.("Database not found",ie);return}Ce=v(me,Me[ie]?.[me.table])}f||(f=Ce?.auditStore),E||(E=lt()?.[ie])}}break}case Oh:Fr();break;case wO:try{let me=r?.replicates||r?.subscribers||r?.name;le.debug?.("Received operation request",F,"from",_),server.operation(F,{user:r},!me).then(ie=>{le.debug?.("Requested request from finished",_,ie),Array.isArray(ie)&&(ie={results:ie}),ie.requestId=F.requestId,e.send((0,at.encode)([CT,ie]))},ie=>{le.debug?.("Failed requested operation from",_,ie),e.send((0,at.encode)([CT,{requestId:F.requestId,error:RO(ie)}]))})}catch(me){e.send((0,at.encode)([CT,{requestId:F.requestId,error:RO(me)}]))}break;case CT:let{resolve:ue,reject:_e}=R.get(F.requestId);le.debug?.("Received completed operation request",_,F),F.error?_e(new Error(F.error)):ue(F),R.delete(F.requestId);break;case bO:let re=W[3];if(!E){u?le.error?.(s,"No database found for",u):le.error?.(s,"Database name never received"),Fr();return}let oe=E[re];oe=v({table:re,database:u,attributes:F.attributes,schemaDefined:F.schemaDefined},oe),cm[he]={name:re,decoder:new at.Packr({useBigIntExtension:!0,randomAccessStructure:!0,freezeData:!0,typedStructs:F.typedStructs,structures:F.structures}),getEntry(me){return oe.primaryStore.getEntry(me)},rootStore:oe.primaryStore.rootStore};break;case K1:Br=f?c1(F,f):new Map,lm=W[2],le.debug?.(s,`Acknowledged subscription request, receiving messages for nodes: ${lm}`);break;case Y1:let ge=he;Yb[ge]=F;break;case z1:Ps()[cK]=F,le.trace?.(s,"received and broadcasting committed update",F),Ps().buffer.notify();break;case j1:y=F,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),Ps(),replication_shared_status[LT]=last_sequence_id_received,replication_shared_status[DT]=Date.now(),replication_shared_status[vT]=NO;break;case OT:{let me=W[1],{fileId:ie,size:Ce,finished:Be,error:He}=me,Te=Ne.get(ie);le.debug?.("Received blob",ie,"has stream",!!Te,"connectedToBlob",!!Te?.connectedToBlob,"length",W[2].length,"finished",Be),Te||(Te=new IO.PassThrough,Te.expectedSize=Ce,Ne.set(ie,Te)),Te.lastChunk=Date.now();let ht=W[2];We(ht.byteLength,"bytes-received",`${_}.${u}`,"replication","blob");try{Be?(He?(Te.on("error",()=>{}),Te.destroy(new Error("Blob error: "+He+" for record "+(Te.recordId??"unknown")+" from "+_))):Te.end(ht),Te.connectedToBlob&&Ne.delete(ie)):Te.write(ht)}catch(Ct){le.error?.(`Error receiving blob for ${Te.recordId} from ${_} and streaming to storage`,Ct),Ne.delete(ie)}break}case W1:{let me=F,ie;try{let Ce=W[3],Be=a_[he]||(a_[he]=E[W[4]]);if(!Be)return le.warn?.("Unknown table id trying to handle record request",he);let He=Be.primaryStore.getBinaryFast(Symbol.for("structures")),Te=He?.length??0;if(Te>0&&Te!==um){um=Te;let Ct=(0,at.decode)(He);e.send((0,at.encode)([bO,{typedStructs:Ct.typed,structures:Ct.named},he,Be.tableName]))}let ht=Be.primaryStore.getBinaryFast(Ce);if(ht){let Ct=Be.primaryStore.decoder.decode(ht,{valueAsBuffer:!0}),Ot=ut||{};Ot.version=(0,aK.getLastVersion)(),ut&&ut[Qu]&Zr&&(Ct=Buffer.from(Ct),Wm(()=>Be.primaryStore.decoder.decode(ht),u_=>Ga(u_,Ce),Be.primaryStore.rootStore)),ie=(0,at.encode)([NT,me,{value:Ct,expiresAt:Ot.expiresAt,version:Ot.version,residencyId:Ot.residencyId,nodeId:Ot.nodeId,user:Ot.user}])}else ie=(0,at.encode)([NT,me])}catch(Ce){ie=(0,at.encode)([NT,me,{error:Ce.message}])}e.send(ie);break}case NT:{let{resolve:me,reject:ie,tableId:Ce,key:Be}=R.get(W[1]),He=W[2];if(He?.error)ie(new Error(He.error));else if(He){let Te;tg(()=>{let ht=cm[Ce].decoder.decode(He.value);He.value=ht,He.key=Be,me(He)||Te&&setTimeout(()=>Te.forEach(X_),6e4).unref()},f?.rootStore,ht=>{let Ct=qa(ht,Be);return Te||(Te=[]),Te.push(Ct),Ct})}else me();R.delete(W[1]);break}case $1:{pn=F;let me,ie,Ce=!1;if(h){if(u!==h.databaseName&&!h.then){le.error?.("Subscription request for wrong database",u,h.databaseName);return}}else h=d.get(u);if(le.debug?.(s,"received subscription request for",u,"at",pn),!h){let De;h=new Promise(ft=>{le.debug?.("Waiting for subscription to database "+u),De=ft}),h.ready=De,Rc.set(u,h)}if(r.name)ie=Gt().subscribe(r.name),ie.then(async De=>{me=De;for await(let ft of me){let kr=ft.value;if(!(kr?.replicates===!0||kr?.replicates?.receives||kr?.subscriptions?.some(fr=>(fr.database||fr.schema)===u&&fr.publish!==!1))){Ce=!0,Fr(1008,`Unauthorized database subscription to ${u}`);return}}},De=>{le.error?.(s,"Error subscribing to HDB nodes",De)});else if(!(r?.role?.permission?.super_user||r.replicates)){e.send((0,at.encode)([Oh])),Fr(1008,`Unauthorized database subscription to ${u}`);return}if(Dn&&(le.debug?.(s,"stopping previous subscription",u),Dn.emit("close")),pn.length===0)return;let Be=pn[0],He=a(De=>{if(De&&(Be.replicateByDefault?!Be.tables.includes(De.tableName):Be.tables.includes(De.tableName)))return{table:De}},"tableToTableEntry"),Te={txnTime:0},ht,Ct,Ot=1/0,u_,d_=a((De,ft)=>{if(De.type==="end_txn"){Te.txnTime&&(o[i]!==66&&le.error?.("Invalid encoding of message"),C(9),C(fg),O(u_=ft),sU()),i=c,Te.txnTime=0;return}let kr=De.nodeId,fr=De.tableId,zt=Ct[fr];if(!zt&&(zt=Ct[fr]=He(h.tableById[fr]),!zt))return le.debug?.("Not subscribed to table",fr);let yt=zt.table,Uu=yt.primaryStore,si=Uu.encoder;(De.extendedType&Rg||!si.typedStructs)&&(si._mergeStructures(si.getStructures()),si.typedStructs&&(si.lastTypedStructuresLength=si.typedStructs.length));let f_=ht[kr];if(!(f_&&f_.startTime<ft&&(!f_.endTime||f_.endTime>ft)))return PT&&le.trace?.(s,"skipping replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",ht),iU();PT&&le.trace?.(s,"sending replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",ht);let Wb=De.version,Qc=De.residencyId,jb=l_(Qc,yt),m_;if(jb&&!jb.includes(_)){let Hi=l_(De.previousResidencyId,yt);if(Hi&&!Hi.includes(_)&&(De.type==="put"||De.type==="patch")||yt.getResidencyById)return iU();let Xc=De.recordId;le.trace?.(s,"sending invalidation",Xc,_,"from",kr);let pm=0;Qc&&(pm|=dl),De.previousResidencyId&&(pm|=fl);let Qb,p_=null;for(let oU in yt.indices){if(!p_){if(Qb=De.getValue(Uu,!0),!Qb)break;p_={}}p_[oU]=Qb[oU]}m_=ml(De.version,fr,Xc,null,kr,De.user,De.type==="put"||De.type==="patch"?"invalidate":De.type,si.encode(p_),pm,Qc,De.previousResidencyId,De.expiresAt)}function iU(){return le.trace?.(s,"skipping audit record",De.recordId),q||(q=setTimeout(()=>{q=null,(u_||0)+Q1/2<Ot&&(PT&&le.trace?.(s,"sending skipped sequence update",Ot),e.send((0,at.encode)([j1,Ot])))},Q1).unref()),new Promise(setImmediate)}a(iU,"skipAuditRecord");let zb=si.typedStructs,Jb=si.structures;if((zb?.length!=zt.typed_length||Jb?.length!=zt.structure_length)&&(zt.typed_length=zb?.length,zt.structure_length=Jb.length,le.debug?.(s,"send table struct",zt.typed_length,zt.structure_length),zt.sentName||(zt.sentName=!0),e.send((0,at.encode)([bO,{typedStructs:zb,structures:Jb,attributes:yt.attributes,schemaDefined:yt.schemaDefined},fr,zt.table.tableName]))),Qc&&!c_[Qc]&&(e.send((0,at.encode)([Y1,jb,Qc])),c_[Qc]=!0),Te.txnTime!==Wb&&(Te.txnTime&&(PT&&le.trace?.(s,"new txn time, sending queued txn",Te.txnTime),o[i]!==66&&le.error?.("Invalid encoding of message"),sU()),Te.txnTime=Wb,i=c,O(Wb)),m_)C(m_.length),P(m_);else{let Hi=De.encoded;De.extendedType&Zr&&Wm(()=>De.getValue(Uu),pm=>Ga(pm,De.recordId),Uu.rootStore);let Xc=Hi[0]===66?8:0;C(Hi.length-Xc),P(Hi,Xc),le.trace?.("wrote record",De.recordId,"length:",Hi.length)}if(e._socket.writableNeedDrain){let Hi=performance.now();return Pu=!0,Ft(),new Promise(Xc=>{le.debug?.(`Waiting for remote node ${_} to allow more commits ${e._socket.writableNeedDrain?"due to network backlog":"due to requested flow directive"}`),e._socket.once("drain",()=>{Xc(),Pu=!1,Ft()})})}else return $e>ki?new Promise(Hi=>{Ir=Hi}):new Promise(setImmediate)},"sendAuditRecord"),sU=a(()=>{c-i>8?(e.send(o.subarray(i,c)),le.debug?.(s,"Sent message, size:",c-i),u!=="system"&&We(c-i,"bytes-sent",`${_}.${u}`,"replication","egress")):le.debug?.(s,"skipping empty transaction")},"sendQueuedData");Dn=new CO.EventEmitter,Dn.once("close",()=>{Ce=!0,me?.end()});for(let{startTime:De}of pn)De<Ot&&(Ot=De);(ie||Promise.resolve()).then(async()=>{h=await h,f=h.auditStore,Ct=h.tableById.map(He),ht=[];for(let{name:ft,startTime:kr,endTime:fr}of pn){let zt=gT(ft,f);le.debug?.("subscription to",ft,"using local id",zt,"starting",kr),ht[zt]={startTime:kr,endTime:fr}}K(u),Ha||(Ha=ql(ft=>{ft.databaseName===u&&K(u)}),o_=nh(ft=>{ft===u&&(e.send((0,at.encode)([Oh])),Fr())}),e.on("close",()=>{Ha?.remove(),o_?.remove()})),e.send((0,at.encode)([K1,Th(h.auditStore),pn.map(({name:ft})=>ft)]));let De=!0;do{if(isFinite(Ot)||(le.warn?.("Invalid sequence id "+Ot),Fr(1008,"Invalid sequence id"+Ot)),De&&!Ce&&(De=!1,Ot===0)){le.info?.("Replicating all tables to",_);let ft=Date.now(),kr=xT(f);for(let fr in E){if(!He(fr))continue;let zt=E[fr];for(let yt of zt.primaryStore.getRange({snapshot:!1,versions:!0})){if(Ce)return;le.trace?.(s,"Copying record from",u,fr,yt.key,yt.localTime),ft=Math.max(yt.localTime??1,ft),Ps()[Ph]=1;let Uu=ml(yt.version,zt.tableId,yt.key,null,kr,null,"put",Wm(()=>zt.primaryStore.encoder.encode(yt.value),si=>Ga(si,yt.key)),yt.metadataFlags&-256,yt.residencyId,null,yt.expiresAt);await d_({recordId:yt.key,tableId:zt.tableId,type:"put",getValue(){return yt.value},encoded:Uu,version:yt.version,residencyId:yt.residencyId,nodeId:kr,extendedType:yt.metadataFlags},yt.localTime)}}Te.txnTime||(Te.txnTime=ft,O(ft)),c-i>8&&d_({type:"end_txn"},Ot),Ps()[Ph]=0,Ot=ft}for(let{key:ft,value:kr}of f.getRange({start:Ot||1,exclusiveStart:!0,snapshot:!1})){if(Ce)return;let fr=It(kr);le.debug?.("sending audit record",ft,fr.recordId),Ps()[Ph]=ft,Ot=ft,await d_(fr,ft),Dn.startTime=ft}c-i>8&&d_({type:"end_txn"},Ot),Ps()[Ph]=0,await vB(f)}while(!Ce)}).catch(De=>{le.error?.(s,"Error handling subscription to node",De),Fr(1008,"Error handling subscription to node")});break}}return}U.position=8;let N=!0,L,$;do{Ps();let W=U.readInt();if(W===9&&U.getUint8(U.position)==fg){U.position++,y=$=U.readFloat64(),m[LT]=y,m[DT]=Date.now(),m[vT]=NO,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),le.trace?.("received remote sequence update",y,u);break}let J=U.position,F=It(A,J,J+W),he=cm[F.tableId];he||le.error?.(`No table found with an id of ${F.tableId}`);let ue;F.residencyId&&(ue=Yb[F.residencyId],le.trace?.(s,"received residency list",ue,F.type,F.recordId));let _e=F.recordId;try{tg(()=>{L={table:he.name,id:F.recordId,type:F.type,nodeId:Br.get(F.nodeId),residencyList:ue,timestamp:F.version,value:F.getValue(he),user:F.user,beginTxn:N,expiresAt:F.expiresAt}},f?.rootStore,re=>qa(re,_e))}catch(re){throw re.message+=" record id: "+_e,re.message+=" typed structures for current decoder"+JSON.stringify(he.decoder.typedStructs),re.message+=" structures for current decoder"+JSON.stringify(he.decoder.structures),re}N=!1,le.debug?.(s,"received replication message",F.type,"id",L.id,"version",new Date(F.version),"nodeId",L.nodeId),m[LT]=F.version,m[DT]=Date.now(),m[vT]=uK,h.send(L),U.position=J+W}while(U.position<A.byteLength);Ls++,u!=="system"&&We(A.byteLength,"bytes-received",`${_}.${u}.${L?.table||"unknown_table"}`,"replication","ingest"),Ls>Lu&&!dm&&(dm=!0,e.pause(),le.debug?.(`Commit backlog causing replication back-pressure, requesting that ${_} pause replication`)),h.send({type:"end_txn",localTime:y,remoteNodeIds:S,async onCommit(){if(L){let W=Date.now()-L.timestamp;u!=="system"&&We(W,"replication-latency",_+"."+u+"."+L.table,L.type,"ingest")}Ls--,dm&&(dm=!1,e.resume(),le.debug?.(`Replication resuming ${_}`)),Ke.length>0&&await Promise.all(Ke),le.trace?.("All blobs finished"),!w&&$&&(le.trace?.(s,"queuing confirmation of a commit at",$),setTimeout(()=>{e.send((0,at.encode)([z1,w])),le.trace?.(s,"sent confirmation of a commit at",w),w=null},Fde)),w=$,le.debug?.("last sequence committed",new Date($),u)}})}catch(U){le.error?.(s,"Error handling incoming replication message",U)}}a(fm,"onWSMessage"),e.on("ping",nr),e.on("pong",()=>{if(t.connection){let A=performance.now()-X;t.connection.latency=A,Ps()&&(m[MT]=A),t.isSubscriptionConnection&&zl({name:_,database:u,url:t.url,latency:A})}X=null}),e.on("close",(A,U)=>{clearInterval(I),clearTimeout(H),clearInterval(k),Dn&&Dn.emit("close"),xo&&xo.end();for(let[N,{reject:L}]of R)L(new Error(`Connection closed ${U?.toString()} ${A}`));le.debug?.(s,"closed",A,U?.toString())});function Fr(A,U){try{e.isFinished=!0,le.debug?.(s,"closing",_,u,A,U),e.close(A,U),t.connection?.emit("finished")}catch(N){le.error?.(s,"Error closing connection",N)}}a(Fr,"close");let vu=new Set;async function Ga(A,U){let N=Z_(A);if(vu.has(N)){le.debug?.("Blob already being sent",N);return}vu.add(N);try{let L;$e++;for await(let $ of A.stream())L&&(le.debug?.("Sending blob chunk",N,"length",L.length),e.send((0,at.encode)([OT,{fileId:N,size:A.size},L]))),L=$,e._socket.writableNeedDrain&&(le.debug?.("draining",N),await new Promise(W=>e._socket.once("drain",W)),le.debug?.("drained",N)),We($.length,"bytes-sent",`${_}.${u}`,"replication","blob");le.debug?.("Sending final blob chunk",N,"length",L.length),e.send((0,at.encode)([OT,{fileId:N,size:A.size,finished:!0},L]))}catch(L){le.warn?.("Error sending blob",L,"blob id",N,"for record",U),e.send((0,at.encode)([OT,{fileId:N,finished:!0,error:RO(L)},Buffer.alloc(0)]))}finally{vu.delete(N),$e--,$e<ki&&Ir?.()}}a(Ga,"sendBlobs");function qa(A,U){let N=Z_(A),L=Ne.get(N);le.debug?.("Received transaction with blob",N,"has stream",!!L,"ended",!!L?.writableEnded),L?L.writableEnded&&Ne.delete(N):(L=new IO.PassThrough,Ne.set(N,L)),L.connectedToBlob=!0,L.lastChunk=Date.now(),L.recordId=U,A.size===void 0&&L.expectedSize&&(A.size=L.expectedSize);let $=L.blob??createBlob(L,A);L.blob=$;let W=Yo(()=>Ym($).saving,h.auditStore?.rootStore);return W&&(W.blobId=N,Ke.push(W),W.finally(()=>{le.debug?.(`Finished receiving blob stream ${N}`),Ke.splice(Ke.indexOf(W),1)})),$}a(qa,"receiveBlobs");function mm(){if(p||(p=!0,t.connection?.on("subscriptions-updated",mm)),!f&&h&&(f=h.auditStore),t.connection?.isFinished)throw new Error("Can not make a subscription request on a connection that is already closed");let A=new Map;f||(f=h?.auditStore);try{for(let L of h?.dbisDB?.getRange({start:Symbol.for("seq"),end:[Symbol.for("seq"),Buffer.from([255])]})||[])for(let $ of L.value.nodes||[])$.lastTxnTime>(A.get($.id)??0)&&A.set($.id,$.lastTxnTime)}catch(L){if(!L.message.includes("Can not re"))throw L}let U=t.connection?.nodeSubscriptions?.[0];S=[];let N=t.connection?.nodeSubscriptions.map((L,$)=>{let W=[],{replicateByDefault:J}=L;if(L.subscriptions){for(let _e of L.subscriptions)if(_e.subscribe&&(_e.schema||_e.database)===u){let re=_e.table;E?.[re]?.replicate!==!1&&W.push(re)}J=!1}else for(let _e in E)(J?E[_e].replicate===!1:E[_e].replicate)&&W.push(_e);let F=f&&gT(L.name,f),he=h?.dbisDB?.get([Symbol.for("seq"),F])??1,ue=Math.max(he?.seqId??1,(typeof L.startTime=="string"?new Date(L.startTime).getTime():L.startTime)??1);if(le.debug?.("Starting time recorded in db",L.name,F,u,he?.seqId,"start time:",ue,new Date(ue)),U!==L){let _e=f&&gT(U.name,f),re=h?.dbisDB?.get([Symbol.for("seq"),_e])??1;for(let oe of re?.nodes||[])oe.name===L.name&&(ue=oe.seqId,le.debug?.("Using sequence id from proxy node",U.name,ue))}return F===void 0?le.warn("Starting subscription request from node",L,"but no node id found"):S.push(F),A.get(F)>ue&&(ue=A.get(F),le.debug?.("Updating start time from more recent txn recorded",U.name,ue)),ue===1&&(L.isLeader?(le.warn?.(`Requesting full copy of database ${u} from ${L.url}`),ue=0):ue=Date.now()-6e4),le.trace?.(s,"defining subscription request",L.name,u,new Date(ue)),{name:L.name,replicateByDefault:J,tables:W,startTime:ue,isLeader:L.isLeader,endTime:L.endTime}});if(N)if(le.debug?.(s,"sending subscription request",N,h?.dbisDB?.path),clearTimeout(Y),N.length>0)e.send((0,at.encode)([$1,N]));else{let L=a(()=>{let $=performance.now();Y=setTimeout(()=>{ce<=$?Fr(1008,"Connection has no subscriptions and is no longer used"):L()},z).unref()},"scheduleClose");L()}}a(mm,"sendSubscriptionRequestUpdate");function l_(A,U){if(!A)return;let N=ve[A];return N||(N=U.getResidencyRecord(A),ve[A]=N),N}a(l_,"getResidence");function $a(A){return!(yc&&yc!="*"&&!yc[A]&&!yc.includes?.(A)&&!yc.some?.(U=>U.name===A))}a($a,"checkDatabaseAccess");function Jc(A){if(h=h||d.get(A),!$a(A))throw new Error(`Access to database "${A}" is not permitted`);h||le.warn?.(`No database named "${A}" was declared and registered`),f=h?.auditStore,E||(E=lt()?.[A]);let U=nt();if(U===_)throw U?new Error("Should not connect to self",U):new Error("Node name not defined");return Mu(U,A),!0}a(Jc,"setDatabase");function Mu(A,U){let N=lt()?.[U],L=[];for(let $ in N){let W=N[$];L.push({table:$,schemaDefined:W.schemaDefined,attributes:W.attributes.map(J=>({name:J.name,type:J.type,isPrimaryKey:J.isPrimaryKey}))})}le.trace?.("Sending database info for node",A,"database name",U),e.send((0,at.encode)([V1,A,U,L]))}a(Mu,"sendNodeDBName");function K(A){let U=lt()?.[A],N=[];for(let L in U){if(pn&&!pn.some(W=>W.replicateByDefault?!W.tables.includes(L):W.tables.includes(L)))continue;let $=U[L];N.push({table:L,schemaDefined:$.schemaDefined,attributes:$.attributes.map(W=>({name:W.name,type:W.type,isPrimaryKey:W.isPrimaryKey}))})}e.send((0,at.encode)([J1,N,A]))}a(K,"sendDBSchema"),k=setInterval(()=>{for(let[A,U]of Ne)U.lastChunk+Se<Date.now()&&(le.warn?.(`Timeout waiting for blob stream to finish ${A} for record ${U.recordId??"unknown"} from ${_}`),Ne.delete(A),U.end())},Se).unref();let g=1,T=[];return{end(){xo&&xo.end(),Dn&&Dn.emit("close")},getRecord(A){let U=g++;return new Promise((N,L)=>{let $=[W1,U,A.table.tableId,A.id];T[A.table.tableId]||($.push(A.table.tableName),T[A.table.tableId]=!0),e.send((0,at.encode)($)),ce=performance.now(),R.set(U,{tableId:A.table.tableId,key:A.id,resolve(W){let{table:J,entry:F}=A;if(N(W),W)return J._recordRelocate(F,W)},reject:L})})},sendOperation(A){let U=g++;return A.requestId=U,e.send((0,at.encode)([wO,A])),new Promise((N,L)=>{R.set(U,{resolve:N,reject:L})})}};function C(A){B(5),A<128?o[c++]=A:A<16384?(l.setUint16(c,A|32768),c+=2):A<1056964608?(l.setUint32(c,A|3221225472),c+=4):(o[c]=255,l.setUint32(c+1,A),c+=5)}function P(A,U=0,N=A.length){let L=N-U;B(L),A.copy(o,c,U,N),c+=L}function O(A){B(8),l.setFloat64(c,A),c+=8}function B(A){if(A+16>o.length-c){let U=Buffer.allocUnsafeSlow(c+A-i+65536>>10<<11);o.copy(U,0,i,c),c=c-i,i=0,o=U,l=new DataView(o.buffer,0,o.length)}}function v(A,U){let N=A.database??"data";U||(U={});let L=U.schemaDefined,$=!1,W=A.schemaDefined,J=U.attributes||[];for(let F=0;F<A.attributes?.length;F++){let he=A.attributes[F],ue=J.find(_e=>_e.name===he.name);(!ue||ue.type!==he.type)&&(L?le.error?.(`Schema for '${u}.${A.table}' is defined locally, but attribute '${he.name}: ${he.type}' from '${_}' does not match local attribute ${ue?"'"+ue.name+": "+ue.type+"'":"which does not exist"}`):($=!0,W||(he.indexed=!0),ue?J[J.indexOf(ue)]=he:J.push(he)))}return $?(le.debug?.("(Re)creating",A),ze({table:A.table,database:A.database,schemaDefined:A.schemaDefined,attributes:J,...U})):U}}var eK,at,tK,rK,nK,CO,sK,iK,OO,oK,IO,aK,Bde,RO,le,$1,V1,K1,Oh,Y1,bO,W1,NT,wO,CT,j1,z1,J1,OT,cK,LT,DT,Ph,MT,vT,lK,NO,uK,PO,Rc,PT,Q1,Fde,X1,AO,af,Z1,cf,LO=se(()=>{Oe();qi();cO();xI();gs();eK=b(fe());G();pl();at=require("msgpackr"),tK=require("ws"),rK=require("worker_threads"),nK=b(Q());wh();CO=require("events"),sK=b(Ts()),iK=b(require("node:tls"));tf();OO=b(require("node:process")),oK=require("node:net");os();is();IO=require("node:stream"),aK=require("lmdb"),{forComponent:Bde,errorToString:RO}=nK.default,le=Bde("replication").conditional,$1=129,V1=140,K1=141,Oh=142,Y1=130,bO=132,W1=133,NT=134,wO=136,CT=137,j1=143,z1=144,J1=145,OT=146,cK=0,LT=1,DT=2,Ph=3,MT=4,vT=5,lK=6,NO=0,uK=1,PO=new Map,Rc=new Map,PT=!0,Q1=300,Fde=2,X1=3e4;a(UT,"createWebSocket");Z1=500,cf=class extends CO.EventEmitter{static{a(this,"NodeReplicationConnection")}socket;startTime;retryTime=Z1;retries=0;isConnected=!0;isFinished=!1;nodeSubscriptions;latency=0;replicateTablesByDefault;session;sessionResolve;sessionReject;url;subscription;databaseName;nodeName;authorization;constructor(t,r,n,s,i){super(),this.url=t,this.subscription=r,this.databaseName=n,this.authorization=i,this.nodeName=this.nodeName??Ti(t)}async connect(){this.session||this.resetSession();let t=[];this.socket=await UT(this.url,{serverName:this.nodeName,authorization:this.authorization});let r;le.debug?.(`Connecting to ${this.url}, db: ${this.databaseName}, process ${OO.pid}`),this.socket.on("open",()=>{this.socket._socket.unref(),le[this.isConnected?"info":"warn"]?.(`Connected to ${this.url}, db: ${this.databaseName}`),this.retries=0,this.retryTime=Z1,this.nodeSubscriptions&&zl({name:this.nodeName,database:this.databaseName,url:this.url}),this.isConnected=!0,r=Lh(this.socket,{database:this.databaseName,subscription:this.subscription,url:this.url,connection:this,isSubscriptionConnection:this.nodeSubscriptions!==void 0},{replicates:!0}),this.sessionResolve(r)}),this.socket.on("error",n=>{n.code==="SELF_SIGNED_CERT_IN_CHAIN"?(le.warn?.(`Can not connect to ${this.url}, this server does not have a certificate authority for the certificate provided by ${this.url}`),n.isHandled=!0):n.code!=="ECONNREFUSED"&&(n.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"?le.error?.(`Can not connect to ${this.url}, the certificate provided by ${this.url} is not trusted, this node needs to be added to the cluster, or a certificate authority needs to be added`):le.error?.(`Error in connection to ${this.url} due to ${n.message}`)),this.sessionReject(n)}),this.socket.on("close",(n,s)=>{if(this.isConnected&&(this.nodeSubscriptions&&nf({name:this.nodeName,database:this.databaseName,url:this.url,finished:this.socket.isFinished}),this.isConnected=!1),this.removeAllListeners("subscriptions-updated"),this.socket.isFinished){this.isFinished=!0,r?.end(),this.emit("finished");return}if(++this.retries%20===1){let i=s?.toString();le.warn?.(`${r?"Disconnected from":"Failed to connect to"} ${this.url} (db: "${this.databaseName}"), due to ${i?'"'+i+'" ':""}(code: ${n})`)}r=null,this.resetSession(),setTimeout(()=>{this.connect()},this.retryTime).unref(),this.retryTime+=this.retryTime>>8})}resetSession(){this.session=new Promise((t,r)=>{this.sessionResolve=t,this.sessionReject=r})}subscribe(t,r){this.nodeSubscriptions=t,this.replicateTablesByDefault=r,this.emit("subscriptions-updated",t)}unsubscribe(){this.socket.isFinished=!0,this.socket.close(1008,"No longer subscribed")}getRecord(t){return this.session.then(r=>r.getRecord(t))}};a(Lh,"replicateOverWS")});function bc(e,t){let r=e.toString("base64"),n=[`-----BEGIN ${t}-----`];for(let s=0;s<r.length;s+=64)n.push(r.substring(s,s+64));return n.push(`-----END ${t}-----`),n.join(`
18
+ `+Jl.get(_.issuer)),!h||!E)throw new Error("Missing private key or certificate for secure server");let R={ciphers:f.ciphers,ticketKeys:Rde(),availableCAs:Jl,ca:t&&Array.from(Jl.values()),cert:E,key:h,key_file:f.private_key_name,is_self_signed:f.is_self_signed};o&&(R.sessionIdContext=o.sessionIdContext);let S=f.hostnames??yO(_);Array.isArray(S)||(S=[S]);for(let I of S)I===fO()&&(p+=1);let y=bT.createSecureContext(R);y.name=f.name,y.options=R,y.quality=p,y.certificateAuthorities=Array.from(Jl),y.certStart=E.toString().slice(0,100);let w;for(let I of S)if(I){I[0]==="*"&&(s=!0,I=I.slice(1)),N1.isIP(I)&&(w=!0);let H=r.get(I)?.quality??0;Xe.trace?.("Assigning TLS for hostname",I,"if",p,">",H),p>H&&r.set(I,y)}else Xe.error?.("No hostname found for certificate at",bT.certificate);Xe.trace?.("Adding TLS",y.name,"for",o.ports||"client","cert named",f.name,"hostnames",S,"quality",p,"best quality",d),p>d&&(i.defaultContext=n=y,d=p,o&&(o.defaultContext=y))}catch(m){Xe.error?.("Error applying TLS for",f.name,m)}o?.secureContextsListeners.forEach(f=>f()),c(n)}catch(d){l(d)}}a(u,"updateTLS"),RT?.system.hdb_certificate.subscribe({listener:a(()=>setTimeout(()=>u(),1500).unref(),"listener"),omitCurrent:!0}),u()})),i;function i(o,c){Xe.info?.("TLS requested for",o||"(no SNI)");let l=o;for(;;){let d=r.get(l);if(d)return Xe.debug?.("Found certificate for",o,d.certStart),d.updatedContext&&(d=d.updatedContext),c(null,d);if(s&&l){let f=l.indexOf(".",1);f<0?l="":l=l.slice(f)}else break}o?Xe.debug?.("No certificate found to match",o,"using the default certificate"):Xe.debug?.("No SNI, using the default certificate",n?.name);let u=n;u?u.updatedContext&&(u=u.updatedContext):Xe.info?.("No default certificate found"),c(null,u)}a(i,"SNICallback")}a(H1,"createTLSSelector");async function G1(e){let t=Sc.get(e);return!t&&e?await Yn.readFile(gr.join(Ss.get(Ql.ROOTPATH),Vs.LICENSE_KEY_DIR_NAME,e),"utf8"):t}a(G1,"getPrivateKeyByName");async function q1(){Tc();let e=[];for await(let t of an.search([]))e.push(t);return e}a(q1,"listCertificates");async function Dde(e){let t=pO(e,yi.object({name:yi.string().required(),certificate:yi.string().required(),is_authority:yi.boolean().required(),private_key:yi.string(),hosts:yi.array(),uses:yi.array()}));if(t)throw new gc(t.message);let{name:r,certificate:n,private_key:s,is_authority:i}=e,o=new oa(n),c=!1,l=!1,u;for(let[p,h]of Sc)!s&&!c&&o.checkPrivateKey(C1(h))&&(c=!0,u=p),s&&s===h&&(l=!0,u=p);if(!i&&!s&&!c)throw new gc("A suitable private key was not found for this certificate");let d;if(!r){try{d=TO(o)}catch(p){Xe.error?.(p)}if(d==null)throw new gc("Error extracting certificate host name, please provide a name parameter")}let f=vde(r??d);s&&!c&&!l&&(await Yn.writeFile(gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,f+".pem"),s),Sc.set(f,s));let m={name:r??d,certificate:n,is_authority:i,hosts:e.hosts,uses:e.uses};return(!i||i&&u||i&&s)&&(m.private_key_name=u??f+".pem"),e.ciphers&&(m.ciphers=e.ciphers),await of(m),"Successfully added certificate: "+f}a(Dde,"addCertificate");function vde(e){return e.replace(/[^a-z0-9\.]/gi,"-")}a(vde,"sanitizeName");async function Mde(e){let t=pO(e,yi.object({name:yi.string().required()}));if(t)throw new gc(t.message);let{name:r}=e;Tc();let n=await an.get(r);if(!n)throw new gc(r+" not found");let{private_key_name:s}=n;if(s){let i=Array.from(await an.search([{attribute:"private_key_name",value:s}]));i.length===1&&i[0].name===r&&(Xe.info?.("Removing private key named",s),await Yn.remove(gr.join(Ss.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,s)))}return await an.delete(r),"Successfully removed "+r}a(Mde,"removeCertificate");function TO(e){let t=e.subject?.match(/CN=(.*)/)?.[1];return t||yO(e)[0]}a(TO,"getPrimaryHostName");function yO(e){if(e.subjectAltName)return e.subjectAltName.split(",").map(r=>{let n=r.indexOf(":");if(r=r.slice(n+1),r=r.trim(),r[0]==='"')try{r=JSON.parse(r)}catch{}return r.indexOf("=")>-1?r.match(/CN=([^,]*)/)?.[1]:r}).filter(r=>r);let t=e.subject?.match(/CN=(.*)/)?.[1];return t?[t]:[]}a(yO,"hostnamesFromCert");async function Ude(e){if(e.bypass_auth!==!0)throw new gc("Unauthorized","401");let t=pO(e,yi.object({name:yi.string().required()}));if(t)throw new gc(t.message);let{name:r}=e;if(r===".jwtPrivate")return(await b1()).privateKey;if(r===".jwtPublic")return(await b1()).publicKey;if(Sc.get(r))return Sc.get(e.name);throw new gc("Key not found")}a(Ude,"getKey");function xde(e){return[e.subject?.CN,...e.subjectaltname.split(",").filter(t=>t.trim().startsWith("DNS:")).map(t=>t.trim().substring(4))]}a(xde,"getHostnamesFromCertificate")});var dK={};ye(dK,{BACK_PRESSURE_RATIO_POSITION:()=>lK,CONFIRMATION_STATUS_POSITION:()=>cK,LATENCY_POSITION:()=>MT,NodeReplicationConnection:()=>cf,OPERATION_REQUEST:()=>wO,RECEIVED_TIME_POSITION:()=>DT,RECEIVED_VERSION_POSITION:()=>LT,RECEIVING_STATUS_POSITION:()=>vT,RECEIVING_STATUS_RECEIVING:()=>uK,RECEIVING_STATUS_WAITING:()=>NO,SENDING_TIME_POSITION:()=>Ph,createWebSocket:()=>UT,databaseSubscriptions:()=>Rc,replicateOverWS:()=>Lh,tableUpdateListeners:()=>PO});async function UT(e,t){let{authorization:r,rejectUnauthorized:n}=t||{},s=nt(),i;if(e==null)throw new TypeError(`Invalid URL: Expected a string URL for node "${s}" but received ${e}`);if(e.includes("wss://")){if(!AO){let l=(0,sK.createTLSSelector)("operations-api"),u={secureContexts:null};await l.initialize(u),AO=u.secureContexts}if(i=AO.get(s),i&&le.debug?.("Creating web socket for URL",e,"with certificate named:",i.name),!i&&n!==!1)throw new Error("Unable to find a valid certificate to use for replication to connect to "+e)}let o={};r&&(o.Authorization=r);let c={headers:o,localAddress:s?.startsWith("127.0")?s:void 0,servername:(0,oK.isIP)(t?.serverName)?void 0:t?.serverName,noDelay:!0,highWaterMark:128*1024,rejectUnauthorized:n!==!1,secureContext:void 0};return i&&((af?.caCount!==ca.size||af?.derivedFromContext!==i)&&(af=iK.createSecureContext({...i.options,ca:[...ca,...i.options.availableCAs.values()]}),af.caCount=ca.size,af.derivedFromContext=i),c.secureContext=af),new tK.WebSocket(e,"harperdb-replication-v1",c)}function Lh(e,t,r){let n=t.port||t.securePort,s=OO.pid%1e3+"-"+rK.threadId+(n?"s:"+n:"c:"+t.url?.slice(-4))+" "+Math.random().toString().slice(2,3);le.debug?.(s,"Initializing replication connection",r);let i=0,o=Buffer.allocUnsafeSlow(1024),c=0,l=new DataView(o.buffer,0,1024),u=t.database,d=t.databaseSubscriptions||Rc,f,m,p=!1,h=t.subscription;h?.then&&h.then(A=>{h=A,h.auditStore&&(f=h.auditStore)});let E=t.tables||u&&lt()[u],_,R=new Map,S=[];_=r.name,_&&t.connection&&(t.connection.nodeName=_);let y,w,I,H,X,q,k,z=6e4,Y,ce=0,de=0,te=0,Se=eK.default.get(x.REPLICATION_BLOBTIMEOUT)??12e4,Ne=new Map,Ke=[],$e=0,Ir;if(t.url){let A=a(()=>{X&&de===e._socket?.bytesRead&&te===e._socket?.bytesWritten?e.terminate():(X=performance.now(),e.ping(),de=e._socket?.bytesRead,te=e._socket?.bytesWritten)},"sendPing");I=setInterval(A,X1).unref(),A()}else nr();e._socket?.setMaxListeners(200);function nr(){clearTimeout(H),de=e._socket?.bytesRead,te=e._socket?.bytesWritten,H=setTimeout(()=>{de===e._socket?.bytesRead&&te===e._socket?.bytesWritten&&(le.warn?.(`Timeout waiting for ping from ${_}, terminating connection and reconnecting`),e.terminate())},X1*2).unref()}a(nr,"resetPingTimer");let zr=0,xr=0,Pu=!1,zc=3e4;function Ft(){if(pn?.length>0){let A=performance.now(),U=A-xr;zr=(zr*zc+(Pu?U:0))/(zc+U),m&&(m[lK]=zr),xr=A}}a(Ft,"updateBackPressureRatio"),setInterval(Ft,zc).unref();function Ps(){if(!(!_||!u))return m||(m=Zd(f,u,_)),m}a(Ps,"getSharedStatus"),u&&Jc(u);let Ha,o_,cm=[],a_=[],lm,ve=[],c_=[],Yb=[],Lu=150,ki=25,Ls=0,um=0,dm=!1,xo,Dn,pn,Br;e.on("message",Du);async function Du(A){if(r=await r,!r){le.error?.(s,"No authorization provided"),Fr(1008,"Unauthorized");return}fm(A),e.off("message",Du),e.on("message",fm)}a(Du,"onWSMessageWhenAuthorized");function fm(A){ce=performance.now();try{let U=A.dataView=new ul(A.buffer,A.byteOffset,A.byteLength);if(A[0]>127){let W=(0,at.decode)(A),[J,F,he]=W;switch(J){case V1:{if(F){if(_){if(_!==F){le.error?.(s,`Node name mismatch, expecting to connect to ${_}, but peer reported name as ${F}, disconnecting`),e.send((0,at.encode)([Oh])),Fr(1008,"Node name mismatch");return}}else if(_=F,t.connection?.tentativeNode){let me=t.connection.tentativeNode;me.name=_,t.connection.tentativeNode=null,ia(_,me)}if(t.connection&&(t.connection.nodeName=_),le.debug?.(s,"received node name:",_,"db:",u??W[2]),!u)try{Jc(u=W[2]),u==="system"&&(Ha=Ec(t,(me,ie)=>{$a(ie)&&K(ie)}),e.on("close",()=>{Ha?.remove()}))}catch(me){le.warn?.(s,"Error setting database",me),e.send((0,at.encode)([Oh])),Fr(1008,me.message);return}mm()}break}case J1:{le.debug?.(s,"Received table definitions for",F.map(me=>me.table));for(let me of F){let ie=W[2];me.database=ie;let Ce;if($a(ie)){if(u==="system")Me[ie]?.[me.table]||(Ce=v(me,Me[ie]?.[me.table]));else{if(ie!=="data"&&!Me[ie]){le.warn?.("Database not found",ie);return}Ce=v(me,Me[ie]?.[me.table])}f||(f=Ce?.auditStore),E||(E=lt()?.[ie])}}break}case Oh:Fr();break;case wO:try{let me=r?.replicates||r?.subscribers||r?.name;le.debug?.("Received operation request",F,"from",_),server.operation(F,{user:r},!me).then(ie=>{le.debug?.("Requested request from finished",_,ie),Array.isArray(ie)&&(ie={results:ie}),ie.requestId=F.requestId,e.send((0,at.encode)([CT,ie]))},ie=>{le.debug?.("Failed requested operation from",_,ie),e.send((0,at.encode)([CT,{requestId:F.requestId,error:RO(ie)}]))})}catch(me){e.send((0,at.encode)([CT,{requestId:F.requestId,error:RO(me)}]))}break;case CT:let{resolve:ue,reject:_e}=R.get(F.requestId);le.debug?.("Received completed operation request",_,F),F.error?_e(new Error(F.error)):ue(F),R.delete(F.requestId);break;case bO:let re=W[3];if(!E){u?le.error?.(s,"No database found for",u):le.error?.(s,"Database name never received"),Fr();return}let oe=E[re];oe=v({table:re,database:u,attributes:F.attributes,schemaDefined:F.schemaDefined},oe),cm[he]={name:re,decoder:new at.Packr({useBigIntExtension:!0,randomAccessStructure:!0,freezeData:!0,typedStructs:F.typedStructs,structures:F.structures}),getEntry(me){return oe.primaryStore.getEntry(me)},rootStore:oe.primaryStore.rootStore};break;case K1:Br=f?c1(F,f):new Map,lm=W[2],le.debug?.(s,`Acknowledged subscription request, receiving messages for nodes: ${lm}`);break;case Y1:let ge=he;Yb[ge]=F;break;case z1:Ps()[cK]=F,le.trace?.(s,"received and broadcasting committed update",F),Ps().buffer.notify();break;case j1:y=F,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),Ps(),m[LT]=last_sequence_id_received,m[DT]=Date.now(),m[vT]=NO;break;case OT:{let me=W[1],{fileId:ie,size:Ce,finished:Be,error:He}=me,Te=Ne.get(ie);le.debug?.("Received blob",ie,"has stream",!!Te,"connectedToBlob",!!Te?.connectedToBlob,"length",W[2].length,"finished",Be),Te||(Te=new IO.PassThrough,Te.expectedSize=Ce,Ne.set(ie,Te)),Te.lastChunk=Date.now();let ht=W[2];We(ht.byteLength,"bytes-received",`${_}.${u}`,"replication","blob");try{Be?(He?(Te.on("error",()=>{}),Te.destroy(new Error("Blob error: "+He+" for record "+(Te.recordId??"unknown")+" from "+_))):Te.end(ht),Te.connectedToBlob&&Ne.delete(ie)):Te.write(ht)}catch(Ct){le.error?.(`Error receiving blob for ${Te.recordId} from ${_} and streaming to storage`,Ct),Ne.delete(ie)}break}case W1:{let me=F,ie;try{let Ce=W[3],Be=a_[he]||(a_[he]=E[W[4]]);if(!Be)return le.warn?.("Unknown table id trying to handle record request",he);let He=Be.primaryStore.getBinaryFast(Symbol.for("structures")),Te=He?.length??0;if(Te>0&&Te!==um){um=Te;let Ct=(0,at.decode)(He);e.send((0,at.encode)([bO,{typedStructs:Ct.typed,structures:Ct.named},he,Be.tableName]))}let ht=Be.primaryStore.getBinaryFast(Ce);if(ht){let Ct=Be.primaryStore.decoder.decode(ht,{valueAsBuffer:!0}),Ot=ut||{};Ot.version=(0,aK.getLastVersion)(),ut&&ut[Qu]&Zr&&(Ct=Buffer.from(Ct),Wm(()=>Be.primaryStore.decoder.decode(ht),u_=>Ga(u_,Ce),Be.primaryStore.rootStore)),ie=(0,at.encode)([NT,me,{value:Ct,expiresAt:Ot.expiresAt,version:Ot.version,residencyId:Ot.residencyId,nodeId:Ot.nodeId,user:Ot.user}])}else ie=(0,at.encode)([NT,me])}catch(Ce){ie=(0,at.encode)([NT,me,{error:Ce.message}])}e.send(ie);break}case NT:{let{resolve:me,reject:ie,tableId:Ce,key:Be}=R.get(W[1]),He=W[2];if(He?.error)ie(new Error(He.error));else if(He){let Te;tg(()=>{let ht=cm[Ce].decoder.decode(He.value);He.value=ht,He.key=Be,me(He)||Te&&setTimeout(()=>Te.forEach(X_),6e4).unref()},f?.rootStore,ht=>{let Ct=qa(ht,Be);return Te||(Te=[]),Te.push(Ct),Ct})}else me();R.delete(W[1]);break}case $1:{pn=F;let me,ie,Ce=!1;if(h){if(u!==h.databaseName&&!h.then){le.error?.("Subscription request for wrong database",u,h.databaseName);return}}else h=d.get(u);if(le.debug?.(s,"received subscription request for",u,"at",pn),!h){let De;h=new Promise(ft=>{le.debug?.("Waiting for subscription to database "+u),De=ft}),h.ready=De,Rc.set(u,h)}if(r.name)ie=Gt().subscribe(r.name),ie.then(async De=>{me=De;for await(let ft of me){let kr=ft.value;if(!(kr?.replicates===!0||kr?.replicates?.receives||kr?.subscriptions?.some(fr=>(fr.database||fr.schema)===u&&fr.publish!==!1))){Ce=!0,Fr(1008,`Unauthorized database subscription to ${u}`);return}}},De=>{le.error?.(s,"Error subscribing to HDB nodes",De)});else if(!(r?.role?.permission?.super_user||r.replicates)){e.send((0,at.encode)([Oh])),Fr(1008,`Unauthorized database subscription to ${u}`);return}if(Dn&&(le.debug?.(s,"stopping previous subscription",u),Dn.emit("close")),pn.length===0)return;let Be=pn[0],He=a(De=>{if(De&&(Be.replicateByDefault?!Be.tables.includes(De.tableName):Be.tables.includes(De.tableName)))return{table:De}},"tableToTableEntry"),Te={txnTime:0},ht,Ct,Ot=1/0,u_,d_=a((De,ft)=>{if(De.type==="end_txn"){Te.txnTime&&(o[i]!==66&&le.error?.("Invalid encoding of message"),C(9),C(fg),O(u_=ft),sU()),i=c,Te.txnTime=0;return}let kr=De.nodeId,fr=De.tableId,zt=Ct[fr];if(!zt&&(zt=Ct[fr]=He(h.tableById[fr]),!zt))return le.debug?.("Not subscribed to table",fr);let yt=zt.table,Uu=yt.primaryStore,si=Uu.encoder;(De.extendedType&Rg||!si.typedStructs)&&(si._mergeStructures(si.getStructures()),si.typedStructs&&(si.lastTypedStructuresLength=si.typedStructs.length));let f_=ht[kr];if(!(f_&&f_.startTime<ft&&(!f_.endTime||f_.endTime>ft)))return PT&&le.trace?.(s,"skipping replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",ht),iU();PT&&le.trace?.(s,"sending replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",ht);let Wb=De.version,Qc=De.residencyId,jb=l_(Qc,yt),m_;if(jb&&!jb.includes(_)){let Hi=l_(De.previousResidencyId,yt);if(Hi&&!Hi.includes(_)&&(De.type==="put"||De.type==="patch")||yt.getResidencyById)return iU();let Xc=De.recordId;le.trace?.(s,"sending invalidation",Xc,_,"from",kr);let pm=0;Qc&&(pm|=dl),De.previousResidencyId&&(pm|=fl);let Qb,p_=null;for(let oU in yt.indices){if(!p_){if(Qb=De.getValue(Uu,!0),!Qb)break;p_={}}p_[oU]=Qb[oU]}m_=ml(De.version,fr,Xc,null,kr,De.user,De.type==="put"||De.type==="patch"?"invalidate":De.type,si.encode(p_),pm,Qc,De.previousResidencyId,De.expiresAt)}function iU(){return le.trace?.(s,"skipping audit record",De.recordId),q||(q=setTimeout(()=>{q=null,(u_||0)+Q1/2<Ot&&(PT&&le.trace?.(s,"sending skipped sequence update",Ot),e.send((0,at.encode)([j1,Ot])))},Q1).unref()),new Promise(setImmediate)}a(iU,"skipAuditRecord");let zb=si.typedStructs,Jb=si.structures;if((zb?.length!=zt.typed_length||Jb?.length!=zt.structure_length)&&(zt.typed_length=zb?.length,zt.structure_length=Jb.length,le.debug?.(s,"send table struct",zt.typed_length,zt.structure_length),zt.sentName||(zt.sentName=!0),e.send((0,at.encode)([bO,{typedStructs:zb,structures:Jb,attributes:yt.attributes,schemaDefined:yt.schemaDefined},fr,zt.table.tableName]))),Qc&&!c_[Qc]&&(e.send((0,at.encode)([Y1,jb,Qc])),c_[Qc]=!0),Te.txnTime!==Wb&&(Te.txnTime&&(PT&&le.trace?.(s,"new txn time, sending queued txn",Te.txnTime),o[i]!==66&&le.error?.("Invalid encoding of message"),sU()),Te.txnTime=Wb,i=c,O(Wb)),m_)C(m_.length),P(m_);else{let Hi=De.encoded;De.extendedType&Zr&&Wm(()=>De.getValue(Uu),pm=>Ga(pm,De.recordId),Uu.rootStore);let Xc=Hi[0]===66?8:0;C(Hi.length-Xc),P(Hi,Xc),le.trace?.("wrote record",De.recordId,"length:",Hi.length)}if(e._socket.writableNeedDrain){let Hi=performance.now();return Pu=!0,Ft(),new Promise(Xc=>{le.debug?.(`Waiting for remote node ${_} to allow more commits ${e._socket.writableNeedDrain?"due to network backlog":"due to requested flow directive"}`),e._socket.once("drain",()=>{Xc(),Pu=!1,Ft()})})}else return $e>ki?new Promise(Hi=>{Ir=Hi}):new Promise(setImmediate)},"sendAuditRecord"),sU=a(()=>{c-i>8?(e.send(o.subarray(i,c)),le.debug?.(s,"Sent message, size:",c-i),u!=="system"&&We(c-i,"bytes-sent",`${_}.${u}`,"replication","egress")):le.debug?.(s,"skipping empty transaction")},"sendQueuedData");Dn=new CO.EventEmitter,Dn.once("close",()=>{Ce=!0,me?.end()});for(let{startTime:De}of pn)De<Ot&&(Ot=De);(ie||Promise.resolve()).then(async()=>{h=await h,f=h.auditStore,Ct=h.tableById.map(He),ht=[];for(let{name:ft,startTime:kr,endTime:fr}of pn){let zt=gT(ft,f);le.debug?.("subscription to",ft,"using local id",zt,"starting",kr),ht[zt]={startTime:kr,endTime:fr}}K(u),Ha||(Ha=ql(ft=>{ft.databaseName===u&&K(u)}),o_=nh(ft=>{ft===u&&(e.send((0,at.encode)([Oh])),Fr())}),e.on("close",()=>{Ha?.remove(),o_?.remove()})),e.send((0,at.encode)([K1,Th(h.auditStore),pn.map(({name:ft})=>ft)]));let De=!0;do{if(isFinite(Ot)||(le.warn?.("Invalid sequence id "+Ot),Fr(1008,"Invalid sequence id"+Ot)),De&&!Ce&&(De=!1,Ot===0)){le.info?.("Replicating all tables to",_);let ft=Date.now(),kr=xT(f);for(let fr in E){if(!He(fr))continue;let zt=E[fr];for(let yt of zt.primaryStore.getRange({snapshot:!1,versions:!0})){if(Ce)return;le.trace?.(s,"Copying record from",u,fr,yt.key,yt.localTime),ft=Math.max(yt.localTime??1,ft),Ps()[Ph]=1;let Uu=ml(yt.version,zt.tableId,yt.key,null,kr,null,"put",Wm(()=>zt.primaryStore.encoder.encode(yt.value),si=>Ga(si,yt.key)),yt.metadataFlags&-256,yt.residencyId,null,yt.expiresAt);await d_({recordId:yt.key,tableId:zt.tableId,type:"put",getValue(){return yt.value},encoded:Uu,version:yt.version,residencyId:yt.residencyId,nodeId:kr,extendedType:yt.metadataFlags},yt.localTime)}}Te.txnTime||(Te.txnTime=ft,O(ft)),c-i>8&&d_({type:"end_txn"},Ot),Ps()[Ph]=0,Ot=ft}for(let{key:ft,value:kr}of f.getRange({start:Ot||1,exclusiveStart:!0,snapshot:!1})){if(Ce)return;let fr=It(kr);le.debug?.("sending audit record",ft,fr.recordId),Ps()[Ph]=ft,Ot=ft,await d_(fr,ft),Dn.startTime=ft}c-i>8&&d_({type:"end_txn"},Ot),Ps()[Ph]=0,await vB(f)}while(!Ce)}).catch(De=>{le.error?.(s,"Error handling subscription to node",De),Fr(1008,"Error handling subscription to node")});break}}return}U.position=8;let N=!0,L,$;do{Ps();let W=U.readInt();if(W===9&&U.getUint8(U.position)==fg){U.position++,y=$=U.readFloat64(),m[LT]=y,m[DT]=Date.now(),m[vT]=NO,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),le.trace?.("received remote sequence update",y,u);break}let J=U.position,F=It(A,J,J+W),he=cm[F.tableId];he||le.error?.(`No table found with an id of ${F.tableId}`);let ue;F.residencyId&&(ue=Yb[F.residencyId],le.trace?.(s,"received residency list",ue,F.type,F.recordId));let _e=F.recordId;try{tg(()=>{L={table:he.name,id:F.recordId,type:F.type,nodeId:Br.get(F.nodeId),residencyList:ue,timestamp:F.version,value:F.getValue(he),user:F.user,beginTxn:N,expiresAt:F.expiresAt}},f?.rootStore,re=>qa(re,_e))}catch(re){throw re.message+=" record id: "+_e,re.message+=" typed structures for current decoder"+JSON.stringify(he.decoder.typedStructs),re.message+=" structures for current decoder"+JSON.stringify(he.decoder.structures),re}N=!1,le.debug?.(s,"received replication message",F.type,"id",L.id,"version",new Date(F.version),"nodeId",L.nodeId),m[LT]=F.version,m[DT]=Date.now(),m[vT]=uK,h.send(L),U.position=J+W}while(U.position<A.byteLength);Ls++,u!=="system"&&We(A.byteLength,"bytes-received",`${_}.${u}.${L?.table||"unknown_table"}`,"replication","ingest"),Ls>Lu&&!dm&&(dm=!0,e.pause(),le.debug?.(`Commit backlog causing replication back-pressure, requesting that ${_} pause replication`)),h.send({type:"end_txn",localTime:y,remoteNodeIds:S,async onCommit(){if(L){let W=Date.now()-L.timestamp;u!=="system"&&We(W,"replication-latency",_+"."+u+"."+L.table,L.type,"ingest")}Ls--,dm&&(dm=!1,e.resume(),le.debug?.(`Replication resuming ${_}`)),Ke.length>0&&await Promise.all(Ke),le.trace?.("All blobs finished"),!w&&$&&(le.trace?.(s,"queuing confirmation of a commit at",$),setTimeout(()=>{e.send((0,at.encode)([z1,w])),le.trace?.(s,"sent confirmation of a commit at",w),w=null},Fde)),w=$,le.debug?.("last sequence committed",new Date($),u)}})}catch(U){le.error?.(s,"Error handling incoming replication message",U)}}a(fm,"onWSMessage"),e.on("ping",nr),e.on("pong",()=>{if(t.connection){let A=performance.now()-X;t.connection.latency=A,Ps()&&(m[MT]=A),t.isSubscriptionConnection&&zl({name:_,database:u,url:t.url,latency:A})}X=null}),e.on("close",(A,U)=>{clearInterval(I),clearTimeout(H),clearInterval(k),Dn&&Dn.emit("close"),xo&&xo.end();for(let[N,{reject:L}]of R)L(new Error(`Connection closed ${U?.toString()} ${A}`));le.debug?.(s,"closed",A,U?.toString())});function Fr(A,U){try{e.isFinished=!0,le.debug?.(s,"closing",_,u,A,U),e.close(A,U),t.connection?.emit("finished")}catch(N){le.error?.(s,"Error closing connection",N)}}a(Fr,"close");let vu=new Set;async function Ga(A,U){let N=Z_(A);if(vu.has(N)){le.debug?.("Blob already being sent",N);return}vu.add(N);try{let L;$e++;for await(let $ of A.stream())L&&(le.debug?.("Sending blob chunk",N,"length",L.length),e.send((0,at.encode)([OT,{fileId:N,size:A.size},L]))),L=$,e._socket.writableNeedDrain&&(le.debug?.("draining",N),await new Promise(W=>e._socket.once("drain",W)),le.debug?.("drained",N)),We($.length,"bytes-sent",`${_}.${u}`,"replication","blob");le.debug?.("Sending final blob chunk",N,"length",L.length),e.send((0,at.encode)([OT,{fileId:N,size:A.size,finished:!0},L]))}catch(L){le.warn?.("Error sending blob",L,"blob id",N,"for record",U),e.send((0,at.encode)([OT,{fileId:N,finished:!0,error:RO(L)},Buffer.alloc(0)]))}finally{vu.delete(N),$e--,$e<ki&&Ir?.()}}a(Ga,"sendBlobs");function qa(A,U){let N=Z_(A),L=Ne.get(N);le.debug?.("Received transaction with blob",N,"has stream",!!L,"ended",!!L?.writableEnded),L?L.writableEnded&&Ne.delete(N):(L=new IO.PassThrough,Ne.set(N,L)),L.connectedToBlob=!0,L.lastChunk=Date.now(),L.recordId=U,A.size===void 0&&L.expectedSize&&(A.size=L.expectedSize);let $=L.blob??createBlob(L,A);L.blob=$;let W=Yo(()=>Ym($).saving,h.auditStore?.rootStore);return W&&(W.blobId=N,Ke.push(W),W.finally(()=>{le.debug?.(`Finished receiving blob stream ${N}`),Ke.splice(Ke.indexOf(W),1)})),$}a(qa,"receiveBlobs");function mm(){if(p||(p=!0,t.connection?.on("subscriptions-updated",mm)),!f&&h&&(f=h.auditStore),t.connection?.isFinished)throw new Error("Can not make a subscription request on a connection that is already closed");let A=new Map;f||(f=h?.auditStore);try{for(let L of h?.dbisDB?.getRange({start:Symbol.for("seq"),end:[Symbol.for("seq"),Buffer.from([255])]})||[])for(let $ of L.value.nodes||[])$.lastTxnTime>(A.get($.id)??0)&&A.set($.id,$.lastTxnTime)}catch(L){if(!L.message.includes("Can not re"))throw L}let U=t.connection?.nodeSubscriptions?.[0];S=[];let N=t.connection?.nodeSubscriptions.map((L,$)=>{let W=[],{replicateByDefault:J}=L;if(L.subscriptions){for(let _e of L.subscriptions)if(_e.subscribe&&(_e.schema||_e.database)===u){let re=_e.table;E?.[re]?.replicate!==!1&&W.push(re)}J=!1}else for(let _e in E)(J?E[_e].replicate===!1:E[_e].replicate)&&W.push(_e);let F=f&&gT(L.name,f),he=h?.dbisDB?.get([Symbol.for("seq"),F])??1,ue=Math.max(he?.seqId??1,(typeof L.startTime=="string"?new Date(L.startTime).getTime():L.startTime)??1);if(le.debug?.("Starting time recorded in db",L.name,F,u,he?.seqId,"start time:",ue,new Date(ue)),U!==L){let _e=f&&gT(U.name,f),re=h?.dbisDB?.get([Symbol.for("seq"),_e])??1;for(let oe of re?.nodes||[])oe.name===L.name&&(ue=oe.seqId,le.debug?.("Using sequence id from proxy node",U.name,ue))}return F===void 0?le.warn("Starting subscription request from node",L,"but no node id found"):S.push(F),A.get(F)>ue&&(ue=A.get(F),le.debug?.("Updating start time from more recent txn recorded",U.name,ue)),ue===1&&(L.isLeader?(le.warn?.(`Requesting full copy of database ${u} from ${L.url}`),ue=0):ue=Date.now()-6e4),le.trace?.(s,"defining subscription request",L.name,u,new Date(ue)),{name:L.name,replicateByDefault:J,tables:W,startTime:ue,isLeader:L.isLeader,endTime:L.endTime}});if(N)if(le.debug?.(s,"sending subscription request",N,h?.dbisDB?.path),clearTimeout(Y),N.length>0)e.send((0,at.encode)([$1,N]));else{let L=a(()=>{let $=performance.now();Y=setTimeout(()=>{ce<=$?Fr(1008,"Connection has no subscriptions and is no longer used"):L()},z).unref()},"scheduleClose");L()}}a(mm,"sendSubscriptionRequestUpdate");function l_(A,U){if(!A)return;let N=ve[A];return N||(N=U.getResidencyRecord(A),ve[A]=N),N}a(l_,"getResidence");function $a(A){return!(yc&&yc!="*"&&!yc[A]&&!yc.includes?.(A)&&!yc.some?.(U=>U.name===A))}a($a,"checkDatabaseAccess");function Jc(A){if(h=h||d.get(A),!$a(A))throw new Error(`Access to database "${A}" is not permitted`);h||le.warn?.(`No database named "${A}" was declared and registered`),f=h?.auditStore,E||(E=lt()?.[A]);let U=nt();if(U===_)throw U?new Error("Should not connect to self",U):new Error("Node name not defined");return Mu(U,A),!0}a(Jc,"setDatabase");function Mu(A,U){let N=lt()?.[U],L=[];for(let $ in N){let W=N[$];L.push({table:$,schemaDefined:W.schemaDefined,attributes:W.attributes.map(J=>({name:J.name,type:J.type,isPrimaryKey:J.isPrimaryKey}))})}le.trace?.("Sending database info for node",A,"database name",U),e.send((0,at.encode)([V1,A,U,L]))}a(Mu,"sendNodeDBName");function K(A){let U=lt()?.[A],N=[];for(let L in U){if(pn&&!pn.some(W=>W.replicateByDefault?!W.tables.includes(L):W.tables.includes(L)))continue;let $=U[L];N.push({table:L,schemaDefined:$.schemaDefined,attributes:$.attributes.map(W=>({name:W.name,type:W.type,isPrimaryKey:W.isPrimaryKey}))})}e.send((0,at.encode)([J1,N,A]))}a(K,"sendDBSchema"),k=setInterval(()=>{for(let[A,U]of Ne)U.lastChunk+Se<Date.now()&&(le.warn?.(`Timeout waiting for blob stream to finish ${A} for record ${U.recordId??"unknown"} from ${_}`),Ne.delete(A),U.end())},Se).unref();let g=1,T=[];return{end(){xo&&xo.end(),Dn&&Dn.emit("close")},getRecord(A){let U=g++;return new Promise((N,L)=>{let $=[W1,U,A.table.tableId,A.id];T[A.table.tableId]||($.push(A.table.tableName),T[A.table.tableId]=!0),e.send((0,at.encode)($)),ce=performance.now(),R.set(U,{tableId:A.table.tableId,key:A.id,resolve(W){let{table:J,entry:F}=A;if(N(W),W)return J._recordRelocate(F,W)},reject:L})})},sendOperation(A){let U=g++;return A.requestId=U,e.send((0,at.encode)([wO,A])),new Promise((N,L)=>{R.set(U,{resolve:N,reject:L})})}};function C(A){B(5),A<128?o[c++]=A:A<16384?(l.setUint16(c,A|32768),c+=2):A<1056964608?(l.setUint32(c,A|3221225472),c+=4):(o[c]=255,l.setUint32(c+1,A),c+=5)}function P(A,U=0,N=A.length){let L=N-U;B(L),A.copy(o,c,U,N),c+=L}function O(A){B(8),l.setFloat64(c,A),c+=8}function B(A){if(A+16>o.length-c){let U=Buffer.allocUnsafeSlow(c+A-i+65536>>10<<11);o.copy(U,0,i,c),c=c-i,i=0,o=U,l=new DataView(o.buffer,0,o.length)}}function v(A,U){let N=A.database??"data";U||(U={});let L=U.schemaDefined,$=!1,W=A.schemaDefined,J=U.attributes||[];for(let F=0;F<A.attributes?.length;F++){let he=A.attributes[F],ue=J.find(_e=>_e.name===he.name);(!ue||ue.type!==he.type)&&(L?le.error?.(`Schema for '${u}.${A.table}' is defined locally, but attribute '${he.name}: ${he.type}' from '${_}' does not match local attribute ${ue?"'"+ue.name+": "+ue.type+"'":"which does not exist"}`):($=!0,W||(he.indexed=!0),ue?J[J.indexOf(ue)]=he:J.push(he)))}return $?(le.debug?.("(Re)creating",A),ze({table:A.table,database:A.database,schemaDefined:A.schemaDefined,attributes:J,...U})):U}}var eK,at,tK,rK,nK,CO,sK,iK,OO,oK,IO,aK,Bde,RO,le,$1,V1,K1,Oh,Y1,bO,W1,NT,wO,CT,j1,z1,J1,OT,cK,LT,DT,Ph,MT,vT,lK,NO,uK,PO,Rc,PT,Q1,Fde,X1,AO,af,Z1,cf,LO=se(()=>{Oe();qi();cO();xI();gs();eK=b(fe());G();pl();at=require("msgpackr"),tK=require("ws"),rK=require("worker_threads"),nK=b(Q());wh();CO=require("events"),sK=b(Ts()),iK=b(require("node:tls"));tf();OO=b(require("node:process")),oK=require("node:net");os();is();IO=require("node:stream"),aK=require("lmdb"),{forComponent:Bde,errorToString:RO}=nK.default,le=Bde("replication").conditional,$1=129,V1=140,K1=141,Oh=142,Y1=130,bO=132,W1=133,NT=134,wO=136,CT=137,j1=143,z1=144,J1=145,OT=146,cK=0,LT=1,DT=2,Ph=3,MT=4,vT=5,lK=6,NO=0,uK=1,PO=new Map,Rc=new Map,PT=!0,Q1=300,Fde=2,X1=3e4;a(UT,"createWebSocket");Z1=500,cf=class extends CO.EventEmitter{static{a(this,"NodeReplicationConnection")}socket;startTime;retryTime=Z1;retries=0;isConnected=!0;isFinished=!1;nodeSubscriptions;latency=0;replicateTablesByDefault;session;sessionResolve;sessionReject;url;subscription;databaseName;nodeName;authorization;constructor(t,r,n,s,i){super(),this.url=t,this.subscription=r,this.databaseName=n,this.authorization=i,this.nodeName=this.nodeName??Ti(t)}async connect(){this.session||this.resetSession();let t=[];this.socket=await UT(this.url,{serverName:this.nodeName,authorization:this.authorization});let r;le.debug?.(`Connecting to ${this.url}, db: ${this.databaseName}, process ${OO.pid}`),this.socket.on("open",()=>{this.socket._socket.unref(),le[this.isConnected?"info":"warn"]?.(`Connected to ${this.url}, db: ${this.databaseName}`),this.retries=0,this.retryTime=Z1,this.nodeSubscriptions&&zl({name:this.nodeName,database:this.databaseName,url:this.url}),this.isConnected=!0,r=Lh(this.socket,{database:this.databaseName,subscription:this.subscription,url:this.url,connection:this,isSubscriptionConnection:this.nodeSubscriptions!==void 0},{replicates:!0}),this.sessionResolve(r)}),this.socket.on("error",n=>{n.code==="SELF_SIGNED_CERT_IN_CHAIN"?(le.warn?.(`Can not connect to ${this.url}, this server does not have a certificate authority for the certificate provided by ${this.url}`),n.isHandled=!0):n.code!=="ECONNREFUSED"&&(n.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"?le.error?.(`Can not connect to ${this.url}, the certificate provided by ${this.url} is not trusted, this node needs to be added to the cluster, or a certificate authority needs to be added`):le.error?.(`Error in connection to ${this.url} due to ${n.message}`)),this.sessionReject(n)}),this.socket.on("close",(n,s)=>{if(this.isConnected&&(this.nodeSubscriptions&&nf({name:this.nodeName,database:this.databaseName,url:this.url,finished:this.socket.isFinished}),this.isConnected=!1),this.removeAllListeners("subscriptions-updated"),this.socket.isFinished){this.isFinished=!0,r?.end(),this.emit("finished");return}if(++this.retries%20===1){let i=s?.toString();le.warn?.(`${r?"Disconnected from":"Failed to connect to"} ${this.url} (db: "${this.databaseName}"), due to ${i?'"'+i+'" ':""}(code: ${n})`)}r=null,this.resetSession(),setTimeout(()=>{this.connect()},this.retryTime).unref(),this.retryTime+=this.retryTime>>8})}resetSession(){this.session=new Promise((t,r)=>{this.sessionResolve=t,this.sessionReject=r})}subscribe(t,r){this.nodeSubscriptions=t,this.replicateTablesByDefault=r,this.emit("subscriptions-updated",t)}unsubscribe(){this.socket.isFinished=!0,this.socket.close(1008,"No longer subscribed")}getRecord(t){return this.session.then(r=>r.getRecord(t))}};a(Lh,"replicateOverWS")});function bc(e,t){let r=e.toString("base64"),n=[`-----BEGIN ${t}-----`];for(let s=0;s<r.length;s+=64)n.push(r.substring(s,s+64));return n.push(`-----END ${t}-----`),n.join(`
19
19
  `)}function mK(e){let t=[],r=e;for(;r?.raw;){let n={cert:r.raw};if(r.issuerCertificate&&r.issuerCertificate!==r&&r.issuerCertificate.raw&&(n.issuer=r.issuerCertificate.raw),t.push(n),r.issuerCertificate&&r.issuerCertificate!==r)r=r.issuerCertificate;else break}return t}function MO(e){try{let t=Xl(e),n=Eo.Certificate.fromBER(t).extensions?.find(c=>c.extnID==="2.5.29.31");if(!n)return po.debug?.("Certificate has no CRL Distribution Points extension"),[];let s=ho.fromBER(n.extnValue.valueBlock.valueHexView);if(s.offset===-1)throw new Error("Failed to parse ASN.1 structure in CRL Distribution Points extension");let i=new Eo.CRLDistributionPoints({schema:s.result}),o=[];for(let c of i.distributionPoints)if(c.distributionPoint&&Array.isArray(c.distributionPoint)){for(let l of c.distributionPoint)if(l.type===6&&typeof l.value=="string"){let u=l.value;(u.startsWith("http://")||u.startsWith("https://"))&&o.push(u)}}return po.debug?.(`Found ${o.length} CRL distribution points: ${o}`),o}catch(t){return po.warn?.(`Failed to extract CRL distribution points: ${t}`),[]}}function pK(e){try{let t=Xl(e),r=Eo.Certificate.fromBER(t),n=[],s=[];for(let i of r.extensions||[])if(i.extnID==="2.5.29.31")try{let o=ho.fromBER(i.extnValue.valueBlock.valueHexView);if(o.offset!==-1){let c=new Eo.CRLDistributionPoints({schema:o.result});for(let l of c.distributionPoints)if(l.distributionPoint&&Array.isArray(l.distributionPoint)){for(let u of l.distributionPoint)if(u.type===6&&typeof u.value=="string"){let d=u.value;(d.startsWith("http://")||d.startsWith("https://"))&&n.push(d)}}}}catch(o){po.warn?.(`Failed to parse CRL Distribution Points extension: ${o}`)}else if(i.extnID==="1.3.6.1.5.5.7.1.1")try{let o=ho.fromBER(i.extnValue.valueBlock.valueHexView);if(o.offset!==-1&&o.result instanceof ho.Sequence){for(let c of o.result.valueBlock.value)if(c instanceof ho.Sequence&&c.valueBlock.value.length>=2){let l=c.valueBlock.value[0],u=c.valueBlock.value[1];if(l instanceof ho.ObjectIdentifier&&l.valueBlock.toString()==="1.3.6.1.5.5.7.48.1"&&u.idBlock.tagNumber===6){let d=String.fromCharCode(...Array.from(u.valueBlock.valueHexView));(d.startsWith("http://")||d.startsWith("https://"))&&s.push(d)}}}}catch(o){po.warn?.(`Failed to parse Authority Information Access extension: ${o}`)}return po.debug?.(`Found ${n.length} CRL distribution points and ${s.length} OCSP responder URLs`),{crlUrls:n,ocspUrls:s}}catch(t){return po.warn?.(`Failed to extract revocation URLs: ${t}`),{crlUrls:[],ocspUrls:[]}}}function Xl(e){let t=e.replace(/-----BEGIN [^-]+-----/g,"").replace(/-----END [^-]+-----/g,"").replace(/\s/g,""),r=atob(t),n=new ArrayBuffer(r.length),s=new Uint8Array(n);for(let i=0;i<r.length;i++)s[i]=r.charCodeAt(i);return n}function BT(e,t,r,n){let s={certPem:e,issuerPem:t,method:r,...n},i=(0,vO.createHash)("sha256").update(JSON.stringify(s)).digest("hex");return`${r}:${i}`}function UO(e,t){return`${e}:${t}`}function hK(e){try{let t=Xl(e),n=Eo.Certificate.fromBER(t).serialNumber.valueBlock.valueHexView;return Array.from(n).map(s=>s.toString(16).padStart(2,"0")).join("")}catch(t){throw po.error?.(`Failed to extract serial number: ${t}`),new Error(`Failed to extract certificate serial number: ${t.message}`)}}function xO(e){try{let t=Xl(e),r=Eo.Certificate.fromBER(t),n=r.extensions?.find(i=>i.extnID==="2.5.29.35");if(n)try{let i=ho.fromBER(n.extnValue.valueBlock.valueHexView);if(i.offset!==-1){let o=new Eo.AuthorityKeyIdentifier({schema:i.result});if(o.keyIdentifier){let c=o.keyIdentifier.valueBlock.valueHexView;return Array.from(c).map(l=>l.toString(16).padStart(2,"0")).join("")}}}catch(i){po.debug?.(`Failed to parse Authority Key Identifier: ${i}, falling back to hash`)}let s=r.issuer.typesAndValues.map(i=>`${i.type}=${i.value.valueBlock.value}`).join(",");return(0,vO.createHash)("sha256").update(s).digest("hex")}catch(t){throw po.error?.(`Failed to extract issuer key ID: ${t}`),new Error(`Failed to extract issuer key ID: ${t.message}`)}}function FT(){return DO||(DO=ze({table:"hdb_certificate_cache",database:"system",attributes:[{name:"certificate_id",isPrimaryKey:!0},{name:"status"},{name:"reason"},{name:"checked_at"},{name:"expiresAt",expiresAt:!0,indexed:!0},{name:"method"}]})),DO}var vO,Eo,ho,fK,po,DO,kT=se(()=>{vO=require("node:crypto"),Eo=b(require("pkijs")),ho=b(require("asn1js")),fK=b(sr());Oe();po=(0,fK.loggerWithTag)("cert-verification-utils");a(bc,"bufferToPem");a(mK,"extractCertificateChain");a(MO,"extractCRLDistributionPoints");a(pK,"extractRevocationUrls");a(Xl,"pemToBuffer");a(BT,"createCacheKey");a(UO,"createRevokedCertificateId");a(hK,"extractSerialNumber");a(xO,"extractIssuerKeyId");DO=null;a(FT,"getCertificateCacheTable")});function EK(e){let{error:t,value:r}=qde.validate(e,{abortEarly:!1,allowUnknown:!1});if(t){let n=t.details.map(s=>s.message).join("; ");throw new Error(`Invalid certificate verification configuration: ${n}`)}return r}var Yr,kde,lf,uf,BO,Hde,Gde,qde,_K=se(()=>{Yr=b(require("joi")),kde="fail-closed",lf={timeout:5e3,cacheTtl:36e5,errorCacheTtl:3e5,failureMode:"fail-closed"},uf={timeout:1e4,cacheTtl:864e5,failureMode:"fail-closed",gracePeriod:864e5},BO=Yr.default.string().valid("fail-open","fail-closed"),Hde=Yr.default.alternatives().try(Yr.default.boolean().custom(e=>e===!1?{enabled:!1}:{enabled:!0,...uf}),Yr.default.object({enabled:Yr.default.boolean().default(!0),timeout:Yr.default.number().min(1e3).default(uf.timeout).messages({"number.min":"CRL timeout must be at least 1000ms (1 second)"}),cacheTtl:Yr.default.number().min(1e3).default(uf.cacheTtl).messages({"number.min":"CRL cacheTtl must be at least 1000ms (1 second)"}),failureMode:BO.default(uf.failureMode),gracePeriod:Yr.default.number().min(0).default(uf.gracePeriod).messages({"number.min":"CRL gracePeriod must be at least 0ms"})})),Gde=Yr.default.alternatives().try(Yr.default.boolean().custom(e=>e===!1?{enabled:!1}:{enabled:!0,...lf}),Yr.default.object({enabled:Yr.default.boolean().default(!0),timeout:Yr.default.number().min(1e3).default(lf.timeout).messages({"number.min":"OCSP timeout must be at least 1000ms (1 second)"}),cacheTtl:Yr.default.number().min(1e3).default(lf.cacheTtl).messages({"number.min":"OCSP cacheTtl must be at least 1000ms (1 second)"}),errorCacheTtl:Yr.default.number().min(1e3).default(lf.errorCacheTtl).messages({"number.min":"OCSP errorCacheTtl must be at least 1000ms (1 second)"}),failureMode:BO.default(lf.failureMode)})),qde=Yr.default.object({failureMode:BO.default(kde),crl:Hde.default({enabled:!0,...uf}),ocsp:Gde.default({enabled:!0,...lf})});a(EK,"validateAndParseCertificateVerificationConfig")});function wK(e){if(typeof e=="boolean"||e==null){if(e===FO&&kO)return _o.trace?.("Using cached validation error result (primitive) - returning disabled"),!1;if(e===FO&&HT!==null)return _o.trace?.("Using cached certificate verification config (primitive)"),HT;_o.trace?.("Parsing and caching certificate verification config (primitive)"),FO=e;try{return HT=TK(e),kO=null,HT}catch(n){return kO=n,_o.error?.(`Certificate verification config validation failed - defaulting to disabled: ${n.message}`),!1}}if(SK.get(e))return _o.trace?.("Using cached validation error result (object) - returning disabled"),!1;let r=gK.get(e);if(r!==void 0)return _o.trace?.("Using cached certificate verification config (object)"),r;_o.trace?.("Parsing and caching certificate verification config (object)");try{let n=TK(e);return gK.set(e,n),n}catch(n){return SK.set(e,n),_o.error?.(`Certificate verification config validation failed - defaulting to disabled: ${n.message}`),!1}}function TK(e){if(_o.trace?.(`getCertificateVerificationConfig called with: ${JSON.stringify({mtlsConfig:e})}`),!e)return!1;let t=e===!0?void 0:e.certificateVerification;return _o.trace?.(`Certificate verification config: ${JSON.stringify({verificationConfig:t})}`),t==null||t===!1?!1:EK(t===!0?{}:t)}var yK,RK,_o,bK,AK,IK,gK,FO,HT,SK,kO,HO=se(()=>{yK=b(sr()),RK=b(Rt());_K();_o=(0,yK.loggerWithTag)("cert-verification-config"),bK=10080*60*1e3,AK=3e5,IK=`Harper/${RK.packageJson.version} CRL-Client`,gK=new WeakMap,FO=null,HT=null,SK=new WeakMap,kO=null;a(wK,"getCachedCertificateVerificationConfig");a(TK,"getCertificateVerificationConfig")});function Dh(e){return e===CK||e===$de}function Vde(e){return e===OK||e===PK}function GO(e){return e===CK?OK:PK}function Kde(){if(NK)return;NK=!0;let e=Zl.CryptoEngine.prototype,t=Zl.Certificate.prototype,r={getHashAlgorithm:e.getHashAlgorithm,getAlgorithmByOID:e.getAlgorithmByOID,getAlgorithmParameters:e.getAlgorithmParameters,verifyWithPublicKey:e.verifyWithPublicKey,certificateVerify:t.verify,getPublicKey:t.getPublicKey};e.getHashAlgorithm=function(...n){let[s]=n;return Dh(s.algorithmId)?"UNUSED-EDDSA-BUILTIN-HASH":r.getHashAlgorithm.call(this,s)},e.getAlgorithmByOID=function(...n){let[s]=n;return Dh(s)?{name:GO(s)}:r.getAlgorithmByOID.call(this,...n)},e.getAlgorithmParameters=function(...n){let[s,i]=n;return Vde(s)?{algorithm:{name:s},usages:i==="sign"?["sign"]:["verify"]}:r.getAlgorithmParameters.call(this,...n)},t.getPublicKey=async function(...n){let[,s=Zl.getCrypto(!0)]=n,i=this.subjectPublicKeyInfo.algorithm.algorithmId;if(Dh(i)){let o=GO(i);return s.importKey("spki",this.subjectPublicKeyInfo.toSchema().toBER(!1),o,!0,["verify"])}return r.getPublicKey.call(this,...n)},t.verify=async function(...n){let[s]=n;if(Dh(this.signatureAlgorithm.algorithmId))try{let i=this.toSchema().toBER(!1),o=s.toSchema().toBER(!1),c=new vh.X509Certificate(Buffer.from(i)),l=new vh.X509Certificate(Buffer.from(o));return c.verify(l.publicKey)}catch{return!1}return r.certificateVerify.call(this,...n)},r.verifyWithPublicKey&&(e.verifyWithPublicKey=async function(...n){let[s,i,o]=n,c=o.algorithm.algorithmId;if(Dh(c)){let l=GO(c);try{let u=this.crypto?.subtle||this.subtle||Zl.getCrypto(!0)?.subtle||vh.webcrypto?.subtle;if(!u)throw new Error("No crypto.subtle available");let d=await u.importKey("spki",o.toSchema().toBER(!1),l,!1,["verify"]),f=i.valueBlock.valueHexView;return"unusedBits"in i.valueBlock&&i.valueBlock.unusedBits>0&&(f=f.slice(0,f.length-1)),await u.verify(l,d,f,s)}catch{return!1}}return r.verifyWithPublicKey.call(this,...n)})}var Zl,vh,CK,$de,OK,PK,NK,LK=se(()=>{Zl=b(require("pkijs")),vh=require("node:crypto"),CK="1.3.101.112",$de="1.3.101.113",OK="Ed25519",PK="Ed448",NK=!1;a(Dh,"isEd25519OrEd448");a(Vde,"isEdDSAAlgorithmName");a(GO,"getEdDSAAlgorithmName");a(Kde,"applyEd25519Patch");Kde()});var UK={};ye(UK,{CRLSignatureVerificationError:()=>Mh,performCRLCheck:()=>jde,verifyCRL:()=>VO});function Yde(){return GT||(GT=FT(),GT.sourcedFrom(df)),GT}function Wde(){return qT||(qT=ze({table:"hdb_crl_cache",database:"system",attributes:[{name:"distribution_point",isPrimaryKey:!0},{name:"issuer_dn"},{name:"crl_blob"},{name:"this_update"},{name:"next_update"},{name:"signature_valid"},{name:"expiresAt",expiresAt:!0,indexed:!0}]}),qT.sourcedFrom($O)),qT}function vK(){return qO||(qO=ze({table:"hdb_revoked_certificates",database:"system",attributes:[{name:"composite_id",isPrimaryKey:!0},{name:"serial_number",indexed:!0},{name:"issuer_key_id",indexed:!0},{name:"revocation_date"},{name:"revocation_reason"},{name:"crl_source",indexed:!0},{name:"crl_next_update"},{name:"expiresAt",expiresAt:!0,indexed:!0}]})),qO}async function VO(e,t,r,n){if(r?.enabled===!1)return{valid:!0,status:"disabled",method:"disabled"};try{let s=bc(e,"CERTIFICATE"),i=bc(t,"CERTIFICATE"),o=n??MO(s);if(o.length===0)return{valid:!0,status:"no-crl-distribution-points",method:"crl"};let c=BT(s,i,"crl"),l=await Yde().get(c,{certPem:s,issuerPem:i,distributionPoint:o[0],config:{crl:r??{}}});if(!l)return Or.error?.("Cache fetch returned null - this indicates a source configuration issue"),r.failureMode==="fail-closed"?{valid:!1,status:"error",error:"Cache fetch failed",method:"crl"}:(Or.warn?.("CRL cache fetch failed, allowing connection (fail-open mode)"),{valid:!0,status:"error-allowed",method:"crl"});let u=l,d=l.wasLoadedFromSource?.();return Or.trace?.(`CRL ${d?"source fetch":"cache hit"} for certificate`),{valid:u.status==="good",status:u.status,cached:!d,method:u.method||"crl"}}catch(s){return Or.error?.(`CRL verification error: ${s}`),r.failureMode==="fail-closed"?{valid:!1,status:"error",error:s.message,method:"crl"}:(Or.warn?.("CRL check failed, allowing connection (fail-open mode)"),{valid:!0,status:"error-allowed",method:"crl"})}}async function jde(e,t,r,n){let s=n??MO(e);if(s.length===0)return{status:"good"};let i=hK(e),o=xO(t),c=UO(o,i);try{let u=await vK().get(c);if(u){let f=Date.now(),m=u;return m.crl_next_update>f?{status:"revoked",reason:m.revocation_reason||"unspecified",source:m.crl_source}:m.crl_next_update+r.gracePeriod>f?(Or.warn?.("Using expired CRL data within grace period"),{status:"revoked",reason:m.revocation_reason||"unspecified",source:m.crl_source}):(Or.warn?.("CRL data is too old, treating as unknown"),{status:"unknown",reason:"crl-expired"})}let d=await zde(s,t,r);return d.upToDate?{status:"good",source:d.source}:(Or.warn?.("CRL data is stale or missing, treating as unknown"),{status:"unknown",reason:d.reason||"crl-unavailable"})}catch(l){return Or.error?.(`CRL lookup error: ${l}`),{status:"unknown",reason:l.message}}}async function zde(e,t,r){let n=Date.now();for(let s of e)try{let i=Wde(),o=null,c=null;try{c=await i.get(s),(c&&c.next_update>n||c&&c.next_update+r.gracePeriod>n)&&(o=c)}catch{}o||(o=await MK(s,t,r.timeout));let l=o.next_update;if(l>n){if(!c)try{await i.put(s,o)}catch{}return{upToDate:!0,source:s}}else return l+r.gracePeriod>n?{upToDate:!0,source:s}:{upToDate:!1,reason:"crl-expired"}}catch(i){if(i instanceof Mh)throw i}return{upToDate:!1,reason:"no-current-crl-data"}}async function MK(e,t,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let i=await fetch(e,{signal:n.signal,headers:{"User-Agent":IK}});if(clearTimeout(s),!i.ok)throw new Error(`CRL download failed: ${i.status}`);let o=Buffer.from(await i.arrayBuffer()),c,l=o.toString("utf8");l.includes("-----BEGIN X509 CRL-----")?c=Buffer.from(Xl(l)):c=o;let u=$T.CertificateRevocationList.fromBER(c),d=$T.Certificate.fromBER(Xl(t)),f=await u.verify({issuerCertificate:d});if(!f){let _=`CRL signature verification failed for: ${e}`;throw Or.error?.(_),new Mh(_)}let m=u.thisUpdate.value.getTime(),p=u.nextUpdate?.value.getTime()??m+bK,h=d.issuer.typesAndValues.map(_=>`${_.type}=${_.value.valueBlock.value}`).join(","),E={distribution_point:e,issuer_dn:h,crl_blob:o,this_update:m,next_update:p,signature_valid:f,expiresAt:p};return Jde(u,t,e,p).catch(_=>{Or.error?.(`Error processing revoked certificates: ${_}`)}),E}finally{clearTimeout(s)}}async function Jde(e,t,r,n){let s=vK(),i=xO(t),o=r;try{await Qde(s,o)}catch(c){Or.warn?.(`Failed to clear existing CRL entries: ${c}`)}if(e.revokedCertificates)for(let c of e.revokedCertificates)try{let l=c.userCertificate.valueBlock.valueHexView;if(!l){Or.warn?.("Could not extract serial number from revoked certificate");continue}let u=Array.from(l).map(h=>h.toString(16).padStart(2,"0")).join(""),d=UO(i,u),f=c.revocationDate.value.getTime(),p={composite_id:d,serial_number:u,issuer_key_id:i,revocation_date:f,revocation_reason:"unspecified",crl_source:o,crl_next_update:n,expiresAt:n};await s.create(p.composite_id,p)}catch(l){Or.warn?.(`Failed to process revoked certificate: ${l}`)}}async function Qde(e,t){try{let r=e.search([{attribute:"crl_source",value:t}]);for await(let n of r)try{await e.delete(n.composite_id)}catch(s){Or.warn?.(`Failed to delete revoked certificate entry: ${s}`)}}catch(r){throw Or.error?.(`Failed to search for existing CRL entries: ${r}`),r}}var $T,DK,Mh,Or,GT,$O,qT,qO,KO=se(()=>{$T=b(require("pkijs")),DK=b(sr());Oe();ji();kT();HO();YO();Mh=class extends Error{static{a(this,"CRLSignatureVerificationError")}constructor(t){super(t),this.name="CRLSignatureVerificationError"}},Or=(0,DK.loggerWithTag)("crl-verification");a(Yde,"getCertificateCacheTable");$O=class extends Xt{static{a(this,"CertificateRevocationListSource")}async get(t){let n=this.getContext()?.requestContext;if(!n?.distributionPoint||!n?.issuerPem)throw new Error(`No CRL data provided for cache key: ${t}`);let{distributionPoint:s,issuerPem:i,config:o}=n;try{let c=await MK(s,i,o.timeout),l=c.next_update,u=Date.now()+o.cacheTtl,d=Math.min(l,u);return{...c,expiresAt:d}}catch(c){if(Or.error?.(`CRL fetch error for: ${s} - ${c}`),o.failureMode==="fail-closed"){let l=Date.now()+AK;return{crl_id:t,distribution_point:s,issuer_dn:"unknown",crl_blob:Buffer.alloc(0),this_update:Date.now(),next_update:l,signature_valid:!1,expiresAt:l}}return Or.warn?.("CRL fetch failed, not caching (fail-open mode)"),null}}};a(Wde,"getCRLCacheTable");a(vK,"getRevokedCertificateTable");a(VO,"verifyCRL");a(jde,"performCRLCheck");a(zde,"checkCRLFreshness");a(MK,"downloadAndParseCRL");a(Jde,"processRevokedCertificates");a(Qde,"clearExistingCRLEntries")});async function Xde(){WO||(WO=(await Promise.resolve().then(()=>(KO(),UK))).performCRLCheck),jO||(jO=(await Promise.resolve().then(()=>(zO(),BK))).performOCSPCheck)}var xK,cBe,WO,jO,df,YO=se(()=>{ji();xK=b(sr()),cBe=(0,xK.loggerWithTag)("cert-verification-source");a(Xde,"loadVerificationFunctions");df=class extends Xt{static{a(this,"CertificateVerificationSource")}async get(t){let r=t.id,s=this.getContext()?.requestContext;if(!s||!s.certPem||!s.issuerPem)return null;let{certPem:i,issuerPem:o,ocspUrls:c,config:l}=s,u;r.startsWith("crl:")?u="crl":r.startsWith("ocsp:")?u="ocsp":u="unknown",await Xde();let d,f;if(u==="crl"){f=l.crl;let p=s.distributionPoint?[s.distributionPoint]:void 0;d=await WO(i,o,f,p)}else if(u==="ocsp")f=l.ocsp,d=await jO(i,o,f,c);else throw new Error(`Unsupported verification method: ${u} for ID: ${r}`);let m=Date.now()+f.cacheTtl;return{certificate_id:r,status:d.status,reason:d.reason,checked_at:Date.now(),expiresAt:m,method:u}}}});var BK={};ye(BK,{performOCSPCheck:()=>efe,verifyOCSP:()=>JO});function Zde(){return KT||(KT=FT(),KT.sourcedFrom(df)),KT}async function JO(e,t,r,n){if(r?.enabled===!1)return{valid:!0,status:"disabled",method:"disabled"};try{let s=bc(e,"CERTIFICATE"),i=bc(t,"CERTIFICATE"),o=BT(s,i,"ocsp"),c=await Zde().get(o,{certPem:s,issuerPem:i,ocspUrls:n,config:{ocsp:r??{}}});if(!c)return r.failureMode==="fail-closed"?{valid:!1,status:"error",error:"Cache fetch failed",method:"ocsp"}:(VT.warn?.("OCSP cache fetch failed, allowing connection (fail-open mode)"),{valid:!0,status:"error-allowed",method:"ocsp"});let l=c,u=c.wasLoadedFromSource?.();return VT.trace?.(`OCSP ${u?"source fetch":"cache hit"} for certificate`),{valid:l.status==="good",status:l.status,cached:!u,method:l.method||"ocsp"}}catch(s){return VT.error?.(`OCSP verification error: ${s}`),r.failureMode==="fail-closed"?{valid:!1,status:"error",error:s.message,method:"ocsp"}:(VT.warn?.("OCSP check failed, allowing connection (fail-open mode)"),{valid:!0,status:"error-allowed",method:"ocsp"})}}async function efe(e,t,r,n){try{let s=await(0,FK.getCertStatus)(e,{ca:t,timeout:r.timeout,...n?.length&&{ocspUrl:n[0]}});switch(s.status){case"good":return{status:"good"};case"revoked":return{status:"revoked",reason:s.revocationReason?.toString()||"unspecified"};default:return{status:"unknown",reason:"unknown-status"}}}catch(s){return{status:"unknown",reason:s.name==="AbortError"?"timeout":"ocsp-error"}}}var FK,kK,VT,KT,zO=se(()=>{LK();FK=require("easy-ocsp"),kK=b(sr());kT();YO();VT=(0,kK.loggerWithTag)("ocsp-verification");a(Zde,"getCertificateCacheTable");a(JO,"verifyOCSP");a(efe,"performOCSPCheck")});async function ff(e,t){cn.debug?.(`verifyCertificate called for: ${e.subject?.CN||"unknown"}`);let r=wK(t);if(r===!1)return cn.debug?.("Certificate verification disabled"),{valid:!0,status:"disabled",method:"disabled"};let n=mK(e);if(cn.trace?.(`Certificate chain length: ${n.length}`),n.length<2||!n[0].issuer)return cn.debug?.("Certificate chain insufficient for revocation checking - need certificate and issuer"),{valid:!0,status:"no-issuer-cert",method:"disabled"};let s=bc(n[0].cert,"CERTIFICATE"),{crlUrls:i,ocspUrls:o}=pK(s);if(cn.debug?.(`Certificate extensions: CRL distribution points=${i.length}, OCSP URLs=${o.length}`),i.length>0)if(r.crl.enabled)try{cn.debug?.("Attempting CRL verification");let c=await VO(n[0].cert,n[0].issuer,r.crl,i);if(c.status==="good"||c.status==="revoked")return cn.debug?.(`CRL verification result: ${c.status}`),c;cn.debug?.(`CRL verification inconclusive: ${c.status}, trying OCSP fallback`)}catch(c){cn.warn?.(`CRL verification failed: ${c}`)}else cn.debug?.("Skipping CRL - disabled in configuration");else cn.debug?.("Skipping CRL - no distribution points in certificate");if(o.length>0)if(r.ocsp.enabled)try{cn.debug?.("Attempting OCSP verification");let c=await JO(n[0].cert,n[0].issuer,r.ocsp,o);return cn.debug?.(`OCSP verification result: ${c.status}`),c}catch(c){cn.warn?.(`OCSP verification failed: ${c}`)}else cn.debug?.("Skipping OCSP - disabled in configuration");else cn.debug?.("Skipping OCSP - no responder URLs in certificate");return r.failureMode==="fail-closed"?{valid:!1,status:"no-verification-available",method:"disabled"}:{valid:!0,status:"verification-unavailable-allowed",method:"disabled"}}var HK,cn,YT=se(()=>{HK=b(sr());kT();HO();zO();KO();cn=(0,HK.loggerWithTag)("cert-verification");a(ff,"verifyCertificate")});var aa={};ye(aa,{buildReplicationMtlsConfig:()=>zK,clearThisNodeName:()=>lfe,disableReplication:()=>sfe,enabledDatabases:()=>yc,forEachReplicatedDatabase:()=>Ec,getThisNodeId:()=>xT,getThisNodeName:()=>nt,getThisNodeUrl:()=>_c,hostnameToUrl:()=>QT,lastTimeInAuditStore:()=>yh,monitorNodeCAs:()=>JK,replicateOperation:()=>dfe,replicationCertificateAuthorities:()=>ca,sendOperationToNode:()=>Uh,servers:()=>rfe,setReplicator:()=>XK,start:()=>nfe,startOnMainThread:()=>lO,subscribeToNode:()=>Ih,unsubscribeFromNode:()=>yT,urlToNodeName:()=>Ti});function zK(e){return e?.mtls&&typeof e.mtls=="object"?e.mtls:!0}function nfe(e){if(!e.port&&!e.securePort&&(e.port=Ks.default.get(x.OPERATIONSAPI_NETWORK_PORT),e.securePort=Ks.default.get(x.OPERATIONSAPI_NETWORK_SECUREPORT)),!nt())throw new Error("Can not load replication without a url (see replication.url in the config)");let t=new Map;for(let i of bh(e))t.set(Ti(i.url),i);ife(e);let r=zK(e);e={isOperationsServer:!0,maxPayload:10*1024*1024*1024,...e,mtls:r};let n=Ue.ws(async(i,o,c,l)=>{if(wt.debug("Incoming WS connection received "+o.url),o.headers.get("sec-websocket-protocol")!=="harperdb-replication-v1")return l(i,o,c);i._socket.unref(),Lh(i,e,c.then(()=>o?.user)),i.on("error",u=>{u.code!=="ECONNREFUSED"&&wt.error("Error in connection to "+this.url,u.message)})},e);e.runFirst=!0,Ue.http(async(i,o)=>{if(i.isWebSocket&&i.headers.get("Sec-WebSocket-Protocol")==="harperdb-replication-v1"){wt.debug("Incoming replication WS connection received, authorized: "+i.authorized),!i.authorized&&i._nodeRequest.socket.authorizationError&&wt.error(`Incoming client connection from ${i.ip} did not have valid certificate, you may need turn on enableRootCAs in the config if you are using a publicly signed certificate, or add the CA to the server's trusted CAs`,i._nodeRequest.socket.authorizationError);let c=Gt().primaryStore;if(i.authorized&&i.peerCertificate.subjectaltname){let l=(0,WK.getHostnamesFromCertificate)(i.peerCertificate),u;for(let d of l)if(u=d&&(c.get(d)||t.get(d)),u)break;if(u){let d=await ff(i.peerCertificate,e.mtls);if(!d.valid){wt.warn("Certificate verification failed:",d.status,"for node",u.name,"certificate serial number",i.peerCertificate.serialNumber);return}if(u?.revoked_certificates?.includes(i.peerCertificate.serialNumber)){wt.warn("Revoked certificate used in attempt to connect to node",u.name,"certificate serial number",i.peerCertificate.serialNumber);return}else i.user=u}else wt.warn(`No node found for certificate common name/SANs: ${l}, available nodes are ${Array.from(c.getRange({}).filter(({value:d})=>d).map(({key:d})=>d)).join(", ")} and routes ${Array.from(t.keys()).join(", ")}, connection will require credentials.`)}else{let l=c.get(i.ip)||t.get(i.ip);l?i.user=l:wt.warn(`No node found for IP address ${i.ip}, available nodes are ${Array.from(new Set([...c.getKeys(),...t.keys()])).join(", ")}, connection will require credentials.`)}}return o(i)},e);let s=[];for(let i of n)if(i.secureContexts){let o=a(()=>{let c=new Set(i.secureContexts.values());i.defaultContext&&c.add(i.defaultContext);for(let l of c)try{let u=Array.from(ca);l.options.availableCAs&&u.push(...l.options.availableCAs.values());let d={...l.options,ca:u};l.updatedContext=JT.createSecureContext(d)}catch(u){wt.error("Error creating replication TLS config",u)}},"updateContexts");i.secureContextsListeners.push(o),s.push(o),Ks.default.get(x.REPLICATION_ENABLEROOTCAS)!==!1&&o()}JK(()=>{for(let i of s)i()})}function JK(e){let t=0;ef(r=>{r?.ca&&(ca.add(r.ca),ca.size!==t&&(t=ca.size,e?.()))})}function sfe(e=!0){jK=e}function ife(e){jK||(lt(),yc=e.databases,Ec(e,(t,r)=>{if(!t){let n=e.databaseSubscriptions||Rc;for(let[s,i]of jT){let o=i.get(r);o&&(o.subscribe([],!1),i.delete(r))}n.delete(r);return}for(let n in t){let s=t[n];XK(r,s,e),PO.get(s)?.forEach(i=>i(s))}}))}function XK(e,t,r){if(!t)return console.error(`Attempt to replicate non-existent table ${t.name} from database ${e}`);if(t.replicate===!1||t.sources?.some(s=>s.isReplicator))return;let n;t.sourcedFrom(class QK extends Xt{static{a(this,"Replicator")}static connection;static subscription;static async subscribe(){let i=r.databaseSubscriptions||Rc,o=i.get(e),c=o?.tableById||[];c[t.tableId]=t;let l=o?.ready;if(wt.trace("Setting up replicator subscription to database",e),!o?.auditStore)return this.subscription=o=new ss,i.set(e,o),o.tableById=c,o.auditStore=t.auditStore,o.dbisDB=t.dbisDB,o.databaseName=e,l&&l(o),o;this.subscription=o}static subscribeOnThisThread(i,o){return!0}static async load(i){if(i){let o=i.residencyId,c=i.residency||t.dbisDB.get([Symbol.for("residency_by_id"),o]);if(c){let l,u=new Set;do{let d,f="",m=1/0;for(let h of c){if(u.has(h)||h===Ue.hostname)continue;let E=afe(h,QK.subscription,e);if(E?.isConnected){let _=Zd(t.auditStore,e,h)[MT];(!d||_<m)&&(d=E,f=h,m=_)}}if(!d)throw l||new KK.ServerError(`No connection to any other nodes are available: ${c}`,502);let p={requestId:tfe++,table:t,entry:i,id:i.key};u.add(f);try{return await d.getRecord(p)}catch(h){if(d.isConnected)throw h;wt.warn("Error in load from node",zT,h),l||(l=h)}}while(!0)}}}static isReplicator=!0},{intermediateSource:!0})}function ofe(e,t,r,n,s,i){let o=t+"-"+e,c=jT.get(o);c||(c=new Map,jT.set(o,c));let l=c.get(n);if(l)return l;if(r)return c.set(n,l=new cf(t,r,n,s,i)),l.connect(),l.once("finished",()=>c.delete(n)),l}function afe(e,t,r){let n=GK.get(e);n||(n=new Map,GK.set(e,n));let s=n.get(r);if(s)return s;let i=Gt().primaryStore.get(e);return i?.url&&(s=new cf(i.url,t,r,e,i.authorization),n.set(r,s),s.connect(),s.once("finished",()=>n.delete(r))),s}async function Uh(e,t,r){r||(r={}),r.serverName=e.name;let n=await UT(e.url,r),s=Lh(n,{},{});return new Promise((i,o)=>{n.on("open",()=>{wt.debug("Sending operation connection to "+e.url+" opened",t),i(s.sendOperation(t))}),n.on("error",c=>{o(c)}),n.on("close",c=>{wt.info("Sending operation connection to "+e.url+" closed",c)})}).finally(()=>{n.close()})}function Ih(e){try{YK.isMainThread&&wt.warn("Subscribing on main thread (should not happen in multi-threaded instance)",e.nodes[0].url,e.database);let t=Rc.get(e.database);if(!t){let n;t=new Promise(s=>{wt.info("Waiting for subscription to database "+e.database),n=s}),t.ready=n,Rc.set(e.database,t)}let r=ofe(e.nodes[0].url,e.url,t,e.database,e.name,e.nodes[0].authorization);e.nodes[0].name===void 0?r.tentativeNode=e.nodes[0]:r.nodeName=e.nodes[0].name,r.subscribe(e.nodes.filter(n=>Rh(n,e.database)),e.replicateByDefault)}catch(t){wt.error("Error in subscription to node",e.nodes[0]?.url,t)}}async function yT({url:e,nodes:t,database:r}){wt.trace("Unsubscribing from node",e,r,"nodes",Array.from(Gt().primaryStore.getRange({})));let n=e+"-"+(t[0]?.url??e),s=jT.get(n);if(s){let i=s.get(r);i&&(i.unsubscribe(),s.delete(r))}}function cfe(){if(QO!==void 0)return QO;let e=Ks.default.get(x.OPERATIONSAPI_TLS_CERTIFICATE)||Ks.default.get(x.TLS_CERTIFICATE);if(e)return QO=new $K.X509Certificate((0,VK.readFileSync)(e)).subject?.match(/CN=(.*)/)?.[1]??null}function nt(){return zT||(zT=Ks.default.get("replication_hostname")??Ti(Ks.default.get("replication_url"))??cfe()??qK("operationsapi_network_secureport")??qK("operationsapi_network_port")??"127.0.0.1")}function lfe(){zT=void 0}function qK(e){let t=Ks.default.get(e),r=t?.lastIndexOf?.(":");if(r>0)return t.slice(0,r)}function WT(e){let t=Ks.default.get(e),r=t?.lastIndexOf?.(":");return r>0?+t.slice(r+1).replace(/[\[\]]/g,""):+t}function xT(e){return Th(e)?.[nt()]}function _c(){let e=Ks.default.get("replication_url");return e||QT(nt())}function QT(e){let t=WT("replication_port");if(t)return`ws://${e}:${t}`;if(t=WT("replication_secureport"),t)return`wss://${e}:${t}`;if(t=WT("operationsapi_network_port"),t)return`ws://${e}:${t}`;if(t=WT("operationsapi_network_secureport"),t)return`wss://${e}:${t}`}function Ti(e){if(e)return new URL(e).hostname}function Ec(e,t){for(let n of Object.getOwnPropertyNames(Me))r(n);return nh(n=>{r(n)}),ql((n,s)=>{r(n.databaseName)});function r(n){let s=Me[n];wt.trace("Checking replication status of ",n,e?.databases),e?.databases===void 0||e.databases==="*"||e.databases.includes(n)||e.databases.some?.(i=>i.name===n)||!s?t(s,n,!0):ufe(n)&&t(s,n,!1)}a(r,"forDatabase")}function ufe(e){let t=Me[e];for(let r in t)if(t[r].replicate)return!0}function yh(e){for(let t of e.getKeys({limit:1,reverse:!0}))return t}async function dfe(e){let t={message:""};if(e.replicated){e.replicated=!1,wt.trace?.("Replicating operation",e.operation,"to nodes",Ue.nodes.map(n=>n.name));let r=await Promise.allSettled(Ue.nodes.map(n=>Uh(n,e)));t.replicated=r.map((n,s)=>{let i=n.status==="rejected"?{status:"failed",reason:n.reason.toString()}:n.value;return i.node=Ue.nodes[s]?.name,i})}return t}var Ks,wt,$K,VK,JT,KK,YK,WK,jK,tfe,rfe,ca,yc,jT,GK,QO,zT,gs=se(()=>{Oe();ji();qu();LO();Hr();Ks=b(fe()),wt=b(Q()),$K=require("crypto");YT();VK=require("fs");wh();tf();G();cO();JT=b(require("node:tls")),KK=b(Ee()),YK=require("worker_threads"),WK=b(Ts()),tfe=1,rfe=[],ca=Ks.default.get(x.REPLICATION_ENABLEROOTCAS)!==!1?new Set(JT.rootCertificates):new Set;a(zK,"buildReplicationMtlsConfig");a(nfe,"start");a(JK,"monitorNodeCAs");a(sfe,"disableReplication");a(ife,"assignReplicationSource");a(XK,"setReplicator");jT=new Map;a(ofe,"getSubscriptionConnection");GK=new Map;a(afe,"getRetrievalConnectionByName");a(Uh,"sendOperationToNode");a(Ih,"subscribeToNode");a(yT,"unsubscribeFromNode");a(cfe,"getCommonNameFromCert");a(nt,"getThisNodeName");a(lfe,"clearThisNodeName");Object.defineProperty(Ue,"hostname",{get(){return nt()}});a(qK,"getHostFromListeningPort");a(WT,"getPortFromListeningPort");a(xT,"getThisNodeId");Ue.replication={getThisNodeId:xT,exportIdMapping:Th};a(_c,"getThisNodeUrl");a(QT,"hostnameToUrl");a(Ti,"urlToNodeName");a(Ec,"forEachReplicatedDatabase");a(ufe,"hasExplicitlyReplicatedTable");a(yh,"lastTimeInAuditStore");a(dfe,"replicateOperation")});var ry=M((DBe,nY)=>{"use strict";var mf=PV(),{validateBySchema:xh}=mt(),{commonValidators:pf,schemaRegex:XO}=Ji(),Sr=require("joi"),ffe=Q(),mfe=require("uuid").v4,ey=Xo(),hf=(G(),D(j)),pfe=require("util"),Ac=ms(),{handleHDBError:la,hdbErrors:hfe,ClientError:eu}=Ee(),{HDB_ERROR_MSGS:XT,HTTP_STATUS_CODES:ua}=hfe,{SchemaEventMsg:ty}=us(),ZK=_r(),{getDatabases:Efe}=(Oe(),D(pt)),{transformReq:Ef}=ae(),{replicateOperation:eY}=(gs(),D(aa)),{cleanupOrphans:_fe}=(is(),D(rg)),ZT=Sr.string().min(1).max(pf.schema_length.maximum).pattern(XO).messages({"string.pattern.base":"{:#label} "+pf.schema_format.message}),gfe=Sr.string().min(1).max(pf.schema_length.maximum).pattern(XO).messages({"string.pattern.base":"{:#label} "+pf.schema_format.message}).required(),Sfe=Sr.string().min(1).max(pf.schema_length.maximum).pattern(XO).messages({"string.pattern.base":"{:#label} "+pf.schema_format.message,"any.required":"'primary_key' is required","string.base":"'primary_key' must be a string"}).required();nY.exports={createSchema:Tfe,createSchemaStructure:tY,createTable:yfe,createTableStructure:rY,createAttribute:wfe,dropSchema:Rfe,dropTable:bfe,dropAttribute:Afe,getBackup:Nfe,cleanupOrphanBlobs:Cfe};async function Tfe(e){let t=await tY(e);return ey.signalSchemaChange(new ty(process.pid,e.operation,e.schema)),t}a(Tfe,"createSchema");async function tY(e){let t=xh(e,Sr.object({database:ZT,schema:ZT}));if(t)throw new eu(t.message);if(Ef(e),!await mf.checkSchemaExists(e.schema))throw la(new Error,XT.SCHEMA_EXISTS_ERR(e.schema),ua.BAD_REQUEST,hf.LOG_LEVELS.ERROR,XT.SCHEMA_EXISTS_ERR(e.schema),!0);return await Ac.createSchema(e),`database '${e.schema}' successfully created`}a(tY,"createSchemaStructure");async function yfe(e){return Ef(e),e.hash_attribute=e.primary_key??e.hash_attribute,await rY(e)}a(yfe,"createTable");async function rY(e){let t=xh(e,Sr.object({database:ZT,schema:ZT,table:gfe,residence:Sr.array().items(Sr.string().min(1)).optional(),hash_attribute:Sfe}));if(t)throw new eu(t.message);if(!await mf.checkSchemaTableExists(e.schema,e.table))throw la(new Error,XT.TABLE_EXISTS_ERR(e.schema,e.table),ua.BAD_REQUEST,hf.LOG_LEVELS.ERROR,XT.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:mfe(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await Ac.createTable(n,e);else throw la(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",ua.BAD_REQUEST);else await Ac.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(rY,"createTableStructure");async function Rfe(e){let t=xh(e,Sr.object({database:Sr.string(),schema:Sr.string()}).or("database","schema").messages({"object.missing":"'database' is required"}));if(t)throw new eu(t.message);Ef(e);let r=await mf.checkSchemaExists(e.schema);if(r)throw la(new Error,r,ua.NOT_FOUND,hf.LOG_LEVELS.ERROR,r,!0);let n=await mf.schemaDescribe.describeSchema({schema:e.schema}),s=Object.keys(global.hdb_schema[e.schema]);await Ac.dropSchema(e),ey.signalSchemaChange(new ty(process.pid,e.operation,e.schema)),await ZK.purgeSchemaTableStreams(e.schema,s);let i=await eY(e);return i.message=`successfully deleted '${e.schema}'`,i}a(Rfe,"dropSchema");async function bfe(e){let t=xh(e,Sr.object({database:Sr.string(),schema:Sr.string(),table:Sr.string().required()}));if(t)throw new eu(t.message);Ef(e);let r=await mf.checkSchemaTableExists(e.schema,e.table);if(r)throw la(new Error,r,ua.NOT_FOUND,hf.LOG_LEVELS.ERROR,r,!0);await Ac.dropTable(e),await ZK.purgeTableStream(e.schema,e.table);let n=await eY(e);return n.message=`successfully deleted table '${e.schema}.${e.table}'`,n}a(bfe,"dropTable");async function Afe(e){let t=xh(e,Sr.object({database:Sr.string(),schema:Sr.string(),table:Sr.string().required(),attribute:Sr.string().required()}));if(t)throw new eu(t.message);Ef(e);let r=await mf.checkSchemaTableExists(e.schema,e.table);if(r)throw la(new Error,r,ua.NOT_FOUND,hf.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw la(new Error,"You cannot drop a hash attribute",ua.BAD_REQUEST,void 0,void 0,!0);if(hf.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw la(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,ua.BAD_REQUEST,void 0,void 0,!0);try{return await Ac.dropAttribute(e),Ife(e),ey.signalSchemaChange(new ty(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw ffe.error(`Got an error deleting attribute ${pfe.inspect(e)}.`),n}}a(Afe,"dropAttribute");function Ife(e){let t=Object.values(global.hdb_schema[e.schema][e.table].attributes);for(let r=0;r<t.length;r++)t[r].attribute===e.attribute&&global.hdb_schema[e.schema][e.table].attributes.splice(r,1)}a(Ife,"dropAttributeFromGlobal");async function wfe(e){Ef(e);let t=Efe()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw la(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,ua.BAD_REQUEST,void 0,void 0,!0);return await Ac.createAttribute(e),ey.signalSchemaChange(new ty(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(wfe,"createAttribute");function Nfe(e){return Ac.getBackup(e)}a(Nfe,"getBackup");function Cfe(e){if(!e.database)throw new eu('Must provide "database" name for search for orphaned blobs');if(!databases[e.database])throw new eu(`Unknown database '${e.database}'`);return _fe(databases[e.database],e.database),{message:"Orphaned blobs cleanup started, check logs for progress"}}a(Cfe,"cleanupOrphanBlobs")});var iY=M((MBe,sY)=>{"use strict";var{OPERATIONS_ENUM:Ofe}=(G(),D(j)),ZO=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=Ofe.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};sY.exports=ZO});var eP=M((BBe,uY)=>{"use strict";var Pfe=ms(),xBe=iY(),ny=ae(),sy=(G(),D(j)),Lfe=fe(),{handleHDBError:oY,hdbErrors:Dfe}=Ee(),{HDB_ERROR_MSGS:aY,HTTP_STATUS_CODES:cY}=Dfe,vfe=Object.values(sy.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),lY="To use this operation audit log must be enabled in harperdb-config.yaml";uY.exports=Mfe;async function Mfe(e){if(ny.isEmpty(e.schema))throw new Error(aY.SCHEMA_REQUIRED_ERR);if(ny.isEmpty(e.table))throw new Error(aY.TABLE_REQUIRED_ERR);if(!Lfe.get(sy.CONFIG_PARAMS.LOGGING_AUDITLOG))throw oY(new Error,lY,cY.BAD_REQUEST,sy.LOG_LEVELS.ERROR,lY,!0);let t=ny.checkSchemaTableExist(e.schema,e.table);if(t)throw oY(new Error,t,cY.NOT_FOUND,sy.LOG_LEVELS.ERROR,t,!0);if(!ny.isEmpty(e.search_type)&&vfe.indexOf(e.search_type)<0)throw new Error(`Invalid searchType '${read_audit_log_object.search_type}'`);return await Pfe.readAuditLog(e)}a(Mfe,"readAuditLog")});var fY=M((kBe,dY)=>{"use strict";var{OPERATIONS_ENUM:Ufe}=(G(),D(j)),tP=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=Ufe.GET_BACKUP,this.schema=t,this.table=r}};dY.exports=tP});var hY=M(($Be,pY)=>{"use strict";var xfe=ms(),GBe=fY(),rP=ae(),Bfe=(G(),D(j)),qBe=fe(),{handleHDBError:Ffe,hdbErrors:kfe}=Ee(),{HDB_ERROR_MSGS:mY,HTTP_STATUS_CODES:Hfe}=kfe;pY.exports=Gfe;async function Gfe(e){if(rP.isEmpty(e.schema))throw new Error(mY.SCHEMA_REQUIRED_ERR);if(rP.isEmpty(e.table))throw new Error(mY.TABLE_REQUIRED_ERR);let t=rP.checkSchemaTableExist(e.schema,e.table);if(t)throw Ffe(new Error,t,Hfe.NOT_FOUND,Bfe.LOG_LEVELS.ERROR,t,!0);return await xfe.getBackup(readAuditLogObject)}a(Gfe,"getBackup")});var gY=M((KBe,_Y)=>{"use strict";var qfe=fe(),da=require("joi"),$fe=mt(),EY=require("moment"),Vfe=require("fs-extra"),sP=require("path"),Kfe=require("lodash"),Bh=(G(),D(j)),{LOG_LEVELS:tu}=(G(),D(j)),Yfe="YYYY-MM-DD hh:mm:ss",Wfe=sP.resolve(__dirname,"../logs");_Y.exports=function(e){return $fe.validateBySchema(e,jfe)};var jfe=da.object({from:da.custom(nP),until:da.custom(nP),to:da.custom(nP),level:da.valid(tu.NOTIFY,tu.FATAL,tu.ERROR,tu.WARN,tu.INFO,tu.DEBUG,tu.TRACE),order:da.valid("asc","desc"),limit:da.number().min(1),start:da.number().min(0),log_name:da.custom(zfe)});function nP(e,t){if(EY(e,EY.ISO_8601).format(Yfe)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(nP,"validateDatetime");function zfe(e,t){if(Kfe.invert(Bh.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=qfe.get(Bh.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?Bh.LOG_NAMES.HDB:e,i=s===Bh.LOG_NAMES.INSTALL?sP.join(Wfe,Bh.LOG_NAMES.INSTALL):sP.join(n,s);return Vfe.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(zfe,"validateReadLogPath")});var oP=M((WBe,TY)=>{"use strict";var iy=(G(),D(j)),Jfe=Q(),Qfe=fe(),Xfe=gY(),iP=require("path"),SY=require("fs-extra"),{once:Zfe}=require("events"),{handleHDBError:eme,hdbErrors:tme}=Ee(),{PACKAGE_ROOT:rme}=Rt(),{replicateOperation:nme}=(gs(),D(aa)),sme=iP.join(rme,"logs"),ime=1e3,ome=200;TY.exports=ame;async function ame(e){let t=Xfe(e);if(t)throw eme(t,t.message,tme.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=nme(e),n=Qfe.get(iy.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?iy.LOG_NAMES.HDB:e.log_name,i=s===iy.LOG_NAMES.INSTALL?iP.join(sme,iy.LOG_NAMES.INSTALL):iP.join(n,s);e.to===void 0&&e.until!==void 0&&(e.to=e.until);let o=e.level!==void 0,c=o?e.level:void 0,l=e.from!==void 0,u=l?new Date(e.from):void 0,d=e.to!==void 0,f=d?new Date(e.to):void 0,m=e.limit===void 0?ime:e.limit,p=e.order===void 0?void 0:e.order,h=e.start===void 0?0:e.start,E=h+m,_=0;p==="desc"&&!u&&!f&&(_=Math.max(SY.statSync(i).size-(E+5)*ome,0));let R=SY.createReadStream(i,{start:_});R.on("error",q=>{Jfe.error(q)});let S=0,y=[],w="",I;R.on("data",q=>{let k=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d.]+Z) \[(.+?)]: /g;q=w+q;let z=0,Y;for(;(Y=k.exec(q))&&!R.destroyed;){I&&(I.message=q.slice(z,Y.index),H(I));let[ce,de,te]=Y,Se=te.split("] ["),Ne=Se[0],Ke=Se[1];Se.splice(0,2),I={timestamp:de,thread:Ne,level:Ke,tags:Se,message:""},z=Y.index+ce.length}w=q.slice(z)}),R.on("end",q=>{R.destroyed||I&&(I.message=w.trim(),H(I))}),R.resume();function H(q){let k,z,Y;switch(!0){case(o&&l&&d):k=new Date(q.timestamp),z=new Date(u),Y=new Date(f),q.level===c&&k>=z&&k<=Y&&S<h?S++:q.level===c&&k>=z&&k<=Y&&(go(q,p,y),S++,S===E&&R.destroy());break;case(o&&l):k=new Date(q.timestamp),z=new Date(u),q.level===c&&k>=z&&S<h?S++:q.level===c&&k>=z&&(go(q,p,y),S++,S===E&&R.destroy());break;case(o&&d):k=new Date(q.timestamp),Y=new Date(f),q.level===c&&k<=Y&&S<h?S++:q.level===c&&k<=Y&&(go(q,p,y),S++,S===E&&R.destroy());break;case(l&&d):k=new Date(q.timestamp),z=new Date(u),Y=new Date(f),k>=z&&k<=Y&&S<h?S++:k>=z&&k<=Y&&(go(q,p,y),S++,S===E&&R.destroy());break;case o:q.level===c&&S<h?S++:q.level===c&&(go(q,p,y),S++,S===E&&R.destroy());break;case l:k=new Date(q.timestamp),z=new Date(u),k>=z&&S<h?S++:k>=z&&S>=h&&(go(q,p,y),S++,S===E&&R.destroy());break;case d:k=new Date(q.timestamp),Y=new Date(f),k<=Y&&S<h?S++:k<=Y&&S>=h&&(go(q,p,y),S++,S===E&&R.destroy());break;default:S<h?S++:(go(q,p,y),S++,S===E&&R.destroy())}}a(H,"onLogMessage"),await Zfe(R,"close");let X=await r;if(X.replicated){for(let q of y)q.node=server.hostname;for(let q of X.replicated){let k=q.node;if(q.status==="failed")go({timestamp:new Date().toISOString(),level:"error",node:k,message:`Error retrieving logs: ${q.reason}`},p,y);else for(let z of q.results)z.node=k,go(z,p,y)}}return y}a(ame,"readLog");function go(e,t,r){t==="desc"?cme(e,r):t==="asc"?lme(e,r):r.push(e)}a(go,"pushLineToResult");function cme(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)>r?n=i+1:s=i}t.splice(n,0,e)}a(cme,"insertDescending");function lme(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)<r?n=i+1:s=i}t.splice(n,0,e)}a(lme,"insertAscending")});var oy=M((ZBe,AY)=>{"use strict";var aP=require("joi"),{string:_f,boolean:yY,date:ume}=aP.types(),dme=mt(),{validateSchemaExists:zBe,validateTableExists:JBe,validateSchemaName:QBe}=Ji(),fme=(G(),D(j)),mme=vt(),RY=fe();RY.initSync();var XBe=_f.invalid(RY.get(fme.CONFIG_PARAMS.CLUSTERING_NODENAME)??"node_name").pattern(mme.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null),bY={operation:_f.valid("add_node","update_node","set_node_replication"),node_name:_f.optional(),subscriptions:aP.array().items({table:_f.optional(),schema:_f.optional(),database:_f.optional(),subscribe:yY.required(),publish:yY.required().custom(hme),start_time:ume.iso()})};function pme(e){return dme.validateBySchema(e,aP.object(bY))}a(pme,"addUpdateNodeValidator");function hme(e,t){if(t.state.ancestors[2].operation==="add_node"&&e===!1&&t.state.ancestors[0].subscribe===!1)return t.message(`'subscriptions[${t.state.path[1]}]' subscribe and/or publish must be set to true when adding a node`)}a(hme,"checkForFalsy");AY.exports={addUpdateNodeValidator:pme,validationSchema:bY}});var gf=M((tFe,IY)=>{"use strict";var cP=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},lP=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};IY.exports={Node:cP,NodeSubscription:lP}});var NY=M((nFe,wY)=>{"use strict";var Eme=(G(),D(j)).OPERATIONS_ENUM,uP=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=Eme.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};wY.exports=uP});var Fh=M((iFe,CY)=>{"use strict";var dP=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},fP=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,n,s,i,o,c){this.schema=t,this.table=r,this.hash_attribute=n,this.publish=s,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};CY.exports={RemotePayloadObject:dP,RemotePayloadSubscription:fP}});var PY=M((aFe,OY)=>{"use strict";var mP=class{static{a(this,"TableSizeObject")}constructor(t,r,n=0,s=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=n,this.record_count=s,this.transaction_log_size=i,this.transaction_log_record_count=o}};OY.exports=mP});var DY=M((mFe,LY)=>{"use strict";var _me=PY(),lFe=Jt(),uFe=gt(),gme=Q(),{getSchemaPath:dFe,getTransactionAuditStorePath:fFe}=bt(),{getDatabases:Sme}=(Oe(),D(pt));LY.exports=Tme;async function Tme(e){let t=new _me;try{let r=Sme()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats();t.schema=e.schema,t.table=e.name,t.record_count=n.entryCount,t.transaction_log_record_count=s.entryCount}catch(r){gme.warn(`unable to stat table dbi due to ${r}`)}return t}a(Tme,"lmdbGetTableSize")});var MY=M((hFe,vY)=>{"use strict";var pP=class{static{a(this,"SystemInformationObject")}constructor(t,r,n,s,i,o,c){this.system=t,this.time=r,this.cpu=n,this.memory=s,this.disk=i,this.network=o,this.harperdb_processes=c}};vY.exports=pP});var Hh=M((yFe,FY)=>{"use strict";var yme=require("fs-extra"),Rme=require("path"),An=require("systeminformation"),Ic=Q(),UY=_r(),_Fe=vt(),Sf=(G(),D(j)),bme=DY(),Ame=Vl(),{getThreadInfo:xY}=st(),kh=fe();kh.initSync();var Ime=MY(),{openEnvironment:gFe}=gt(),{getSchemaPath:SFe}=bt(),{database:TFe,databases:hP}=(Oe(),D(pt)),ay;FY.exports={getHDBProcessInfo:SP,getNetworkInfo:yP,getDiskInfo:TP,getMemoryInfo:gP,getCPUInfo:_P,getTimeInfo:EP,getSystemInformation:RP,systemInformation:wme,getTableSize:bP,getMetrics:AP};function EP(){return An.time()}a(EP,"getTimeInfo");async function _P(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:l,cache:u,...d}=await An.cpu();d.cpu_speed=await An.cpuCurrentSpeed();let{rawCurrentload:f,rawCurrentloadIdle:m,rawCurrentloadIrq:p,rawCurrentloadNice:h,rawCurrentloadSystem:E,rawCurrentloadUser:_,cpus:R,...S}=await An.currentLoad();return S.cpus=[],R.forEach(y=>{let{rawLoad:w,rawLoadIdle:I,rawLoadIrq:H,rawLoadNice:X,rawLoadSystem:q,rawLoadUser:k,...z}=y;S.cpus.push(z)}),d.current_load=S,d}catch(e){return Ic.error(`error in getCPUInfo: ${e}`),{}}}a(_P,"getCPUInfo");async function gP(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await An.mem();return Object.assign(s,process.memoryUsage())}catch(e){return Ic.error(`error in getMemoryInfo: ${e}`),{}}}a(gP,"getMemoryInfo");async function SP(){let e={core:[],clustering:[]};try{let t=await An.processes(),r;try{r=Number.parseInt(await yme.readFile(Rme.join(kh.get(Sf.CONFIG_PARAMS.ROOTPATH),Sf.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===Sf.NODE_ERROR_CODES.ENOENT)Ic.warn("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB. This could be because HarperDB is not running.");else throw n}t.list.forEach(n=>{n.pid===r?e.core.push(n):n.name==="nats-server"&&e.clustering.push(n)});for(let n of e.core)for(let s of t.list)s.pid===n.parentPid&&(s.name==="PM2"||s.command==="PM2")&&(n.parent="PM2");return e}catch(t){return Ic.error(`error in getHDBProcessInfo: ${t}`),e}}a(SP,"getHDBProcessInfo");async function TP(){let e={};try{if(!kh.get(Sf.CONFIG_PARAMS.OPERATIONSAPI_SYSINFO_DISK))return e;let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await An.disksIO();e.io=i;let{rxSec:o,txSec:c,wxSec:l,...u}=await An.fsStats();return e.read_write=u,e.size=await An.fsSize(),e}catch(t){return Ic.error(`error in getDiskInfo: ${t}`),e}}a(TP,"getDiskInfo");async function yP(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return kh.get(Sf.CONFIG_PARAMS.OPERATIONSAPI_SYSINFO_NETWORK)&&(e.default_interface=await An.networkInterfaceDefault(),e.latency=await An.inetChecksite("google.com"),(await An.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:l,ieee8021xAuth:u,ieee8021xState:d,carrierChanges:f,...m}=n;e.interfaces.push(m)}),(await An.networkStats()).forEach(n=>{let{rxSec:s,txSec:i,ms:o,...c}=n;e.stats.push(c)})),e}catch(t){return Ic.error(`error in getNetworkInfo: ${t}`),e}}a(yP,"getNetworkInfo");async function RP(){if(ay!==void 0)return ay;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await An.osInfo();e=c;let l=await An.versions("node, npm");return e.node_version=l.node,e.npm_version=l.npm,ay=e,ay}catch(t){return Ic.error(`error in getSystemInformation: ${t}`),e}}a(RP,"getSystemInformation");async function bP(){let e=[],t=await Ame.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await bme(n));return e}a(bP,"getTableSize");async function AP(){let e={};for(let t in hP){let r=e[t]={},n=r.tables={};for(let s in hP[t])try{let i=hP[t][s];if(!r.readers&&(Object.assign(r,i.primaryStore.rootStore.getStats()),delete r.root,r.readers=i.primaryStore.rootStore.readerList().split(/\n\s+/).slice(1).map(l=>{let[u,d,f]=l.trim().split(" ");return{pid:u,thread:d,txnid:f}}),i.auditStore)){let{treeDepth:l,treeBranchPageCount:u,treeLeafPageCount:d,entryCount:f,overflowPages:m}=i.auditStore.getStats();r.audit={treeDepth:l,treeBranchPageCount:u,treeLeafPageCount:d,entryCount:f,overflowPages:m}}let o=i.primaryStore.getStats(),c={};for(let l of["treeDepth","treeBranchPageCount","treeLeafPageCount","entryCount","overflowPages"])c[l]=o[l];n[s]=c}catch(i){Ic.notify(`Error getting stats for table ${s}: ${i}`)}}return e}a(AP,"getMetrics");async function BY(){if(kh.get(Sf.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await UY.getNATSReferences(),t=await UY.listStreams(),r=[];for(let n of t){let s=[],i=await e.consumers.list(n.config.name);for await(let c of i)s.push({name:c.name,created:c.created,num_ack_pending:c.num_ack_pending,num_redelivered:c.num_redelivered,num_waiting:c.num_waiting,num_pending:c.num_pending});let o={stream_name:n.config.name,database:n.config.subjects[0].split(".")[1],table:n.config.subjects[0].split(".")[2],state:n.state,consumers:s};r.push(o)}return r}}a(BY,"getNatsStreamInfo");async function wme(e){let t=new Ime;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await RP(),t.time=EP(),t.cpu=await _P(),t.memory=await gP(),t.disk=await TP(),t.network=await yP(),t.harperdb_processes=await SP(),t.table_size=await bP(),t.metrics=await AP(),t.threads=await xY(),t.replication=await BY(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await RP();break;case"time":t.time=EP();break;case"cpu":t.cpu=await _P();break;case"memory":t.memory=await gP();break;case"disk":t.disk=await TP();break;case"network":t.network=await yP();break;case"harperdb_processes":t.harperdb_processes=await SP();break;case"table_size":t.table_size=await bP();break;case"database_metrics":case"metrics":t.metrics=await AP();break;case"threads":t.threads=await xY();break;case"replication":t.replication=await BY();break;default:break}return t}a(wme,"systemInformation")});var fa=M((wFe,qY)=>{"use strict";var Nme=Vn(),IP=ae(),Cme=require("util"),ru=(G(),D(j)),kY=fe();kY.initSync();var Ome=OC(),HY=Sn(),{Node:bFe,NodeSubscription:AFe}=gf(),Pme=pd(),Lme=NY(),{RemotePayloadObject:Dme,RemotePayloadSubscription:vme}=Fh(),{handleHDBError:Mme,hdbErrors:Ume}=Ee(),{HTTP_STATUS_CODES:xme,HDB_ERROR_MSGS:Bme}=Ume,Fme=di(),kme=Hh(),{packageJson:Hme}=Rt(),{getDatabases:Gme}=(Oe(),D(pt)),IFe=Cme.promisify(Ome.authorize),qme=HY.searchByHash,$me=HY.searchByValue;qY.exports={isEmpty:Vme,getNodeRecord:Kme,upsertNodeRecord:Yme,buildNodePayloads:Wme,checkClusteringEnabled:jme,getAllNodeRecords:zme,getSystemInfo:Jme,reverseSubscription:GY};function Vme(e){return e==null}a(Vme,"isEmpty");async function Kme(e){let t=new Pme(ru.SYSTEM_SCHEMA_NAME,ru.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return qme(t)}a(Kme,"getNodeRecord");async function Yme(e){let t=new Lme(ru.SYSTEM_SCHEMA_NAME,ru.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return Nme.upsert(t)}a(Yme,"upsertNodeRecord");function GY(e){if(IP.isEmpty(e.subscribe)||IP.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:n}=e,s={schema:t,table:r,hash_attribute:n};return e.subscribe===!0&&e.publish===!1?(s.subscribe=!1,s.publish=!0):e.subscribe===!1&&e.publish===!0?(s.subscribe=!0,s.publish=!1):(s.subscribe=e.subscribe,s.publish=e.publish),s}a(GY,"reverseSubscription");function Wme(e,t,r,n){let s=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:l,table:u}=c,d=IP.getTableHashAttribute(l,u),{subscribe:f,publish:m}=GY(c),p=Gme()[l]?.[u],h=new vme(l,u,d,m,f,c.start_time,p.schemaDefined?p.attributes:void 0);s.push(h)}return new Dme(r,t,s,n)}a(Wme,"buildNodePayloads");function jme(){if(!kY.get(ru.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Mme(new Error,Bme.CLUSTERING_NOT_ENABLED,xme.BAD_REQUEST,void 0,void 0,!0)}a(jme,"checkClusteringEnabled");async function zme(){let e=new Fme(ru.SYSTEM_SCHEMA_NAME,ru.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await $me(e))}a(zme,"getAllNodeRecords");async function Jme(){let e=await kme.getSystemInformation();return{hdb_version:Hme.version,node_version:e.node_version,platform:e.platform}}a(Jme,"getSystemInfo")});var wP=M((CFe,JY)=>{"use strict";var cy=_r(),$Y=ae(),VY=vt(),KY=(G(),D(j)),ly=Q(),YY=ry(),Qme=Ap(),{RemotePayloadObject:Xme}=Fh(),{handleHDBError:WY,hdbErrors:Zme}=Ee(),{HTTP_STATUS_CODES:jY}=Zme,{NodeSubscription:zY}=gf();JY.exports=epe;async function epe(e,t){let r;try{r=await cy.request(`${t}.${VY.REQUEST_SUFFIX}`,new Xme(KY.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),ly.trace("Response from remote describe all request:",r)}catch(o){ly.error(`addNode received error from describe all request to remote node: ${o}`);let c=cy.requestErrorHandler(o,"add_node",t);throw WY(new Error,c,jY.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===VY.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw WY(new Error,o,jY.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,l=o.database??o.schema??"data";if(l===KY.SYSTEM_SCHEMA_NAME){await cy.createLocalTableStream(l,c);let h=new zY(l,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let u=$Y.doesSchemaExist(l),d=n[l]!==void 0,f=c?$Y.doesTableExist(l,c):!0,m=c?n?.[l]?.[c]!==void 0:!0;if(!u&&!d||!f&&!m){s.push(o);continue}if(!u&&d&&(ly.trace(`addNode creating schema: ${l}`),await YY.createSchema({operation:"create_schema",schema:l})),!f&&m){ly.trace(`addNode creating table: ${c} in schema: ${l} with attributes ${JSON.stringify(n[l][c].attributes)}`);let h=new Qme(l,c,n[l][c].hash_attribute);n[l][c].attributes&&(h.attributes=n[l][c].attributes),await YY.createTable(h)}await cy.createLocalTableStream(l,c);let p=new zY(l,c,o.publish,o.subscribe);p.start_time=o.start_time,i.push(p)}return{added:i,skipped:s}}a(epe,"reviewSubscriptions")});var Tf={};ye(Tf,{addNodeBack:()=>NP,removeNodeBack:()=>CP,setNode:()=>spe});async function spe(e){e.node_name&&!e.hostname&&(e.hostname=e.node_name),e.verify_tls!==void 0&&(e.rejectUnauthorized=e.verify_tls);let{url:t,hostname:r}=e;t?r||(r=e.hostname=Ti(t)):t=QT(r);let n=(0,XY.validateBySchema)(e,npe);if(n)throw(0,ma.handleHDBError)(n,n.message,rpe.BAD_REQUEST,void 0,void 0,!0);if(e.operation==="remove_node"){if(!t&&!r)throw new ma.ClientError("url or hostname is required for remove_node operation");let p=r,h=Gt(),E=await h.get(p);if(!E)throw new ma.ClientError(p+" does not exist");try{await Uh({url:E.url},{operation:V.REMOVE_NODE_BACK,name:E?.subscriptions?.length>0?nt():p},void 0)}catch(_){ys.warn(`Error removing node from target node ${p}, if it is offline and we be online in the future, you may need to clean up this node manually, or retry:`,_)}return await h.delete(p),`Successfully removed '${p}' from cluster`}if(!t)throw new ma.ClientError("url required for this operation");let s=_c();if(s==null)throw new ma.ClientError("replication url is missing from harperdb-config.yaml");let i,o,c;if(t?.startsWith("wss:")){i=await(0,Ys.getReplicationCert)();let p=await(0,Ys.getReplicationCertAuth)();if(!i)throw new Error("Unable to find a certificate to use for replication");i.options.is_self_signed?(o=await(0,Ys.createCsr)(),ys.info("Sending CSR to target node:",t)):p&&(c=p.certificate,ys.info("Sending CA named",p.name,"to target node",t))}let l={operation:V.ADD_NODE_BACK,hostname:(0,Nc.get)(x.REPLICATION_HOSTNAME),target_hostname:r,url:s,csr:o,cert_auth:c,authorization:e.retain_authorization?e.authorization:null};if((0,Nc.get)(x.REPLICATION_SHARD)!==void 0&&(l.shard=(0,Nc.get)(x.REPLICATION_SHARD)),e.subscriptions?l.subscriptions=e.subscriptions.map(QY):l.subscriptions=null,e.hasOwnProperty("subscribe")||e.hasOwnProperty("publish")){let p=QY(e);l.subscribe=p.subscribe,l.publish=p.publish}e?.authorization?.username&&e?.authorization?.password&&(e.authorization="Basic "+Buffer.from(e.authorization.username+":"+e.authorization.password).toString("base64"));let u,d;try{u=await Uh({url:t},l,e)}catch(p){p.message=`Error returned from ${t}: `+p.message,ys.warn("Error adding node:",t,"to cluster:",p),d=p}if(o&&(!u?.certificate||!u?.certificate?.includes?.("BEGIN CERTIFICATE")))throw d?(d.message+=" and connection was required to sign certificate",d):new Error(`Unexpected certificate signature response from node ${t} response: ${JSON.stringify(u)}`);o&&(ys.info("CSR response received from node:",t,"saving certificate and CA in hdb_certificate"),await(0,Ys.setCertTable)({name:tpe.certificateFromPem(u.signingCA).issuer.getField("CN").value,certificate:u.signingCA,is_authority:!0}),u.certificate&&await(0,Ys.setCertTable)({name:nt(),uses:["https","operations","wss"],certificate:u.certificate,private_key_name:i?.options?.key_file,is_authority:!1,is_self_signed:!1}),c=u.signingCA);let f={url:t,ca:u?.usingCA};if(e.hostname&&(f.name=e.hostname),e.subscriptions?f.subscriptions=e.subscriptions:f.replicates=!0,e.start_time&&(f.start_time=typeof e.start_time=="string"?new Date(e.start_time).getTime():e.start_time),e.retain_authorization&&(f.authorization=e.authorization),e.revoked_certificates&&(f.revoked_certificates=e.revoked_certificates),u?.shard!==void 0?f.shard=u.shard:e.shard!==void 0&&(f.shard=e.shard),f.replicates){let p={url:s,ca:c,replicates:!0,subscriptions:null};(0,Nc.get)(x.REPLICATION_SHARD)!==void 0&&(p.shard=(0,Nc.get)(x.REPLICATION_SHARD)),e.retain_authorization&&(p.authorization=e.authorization),e.start_time&&(p.start_time=e.start_time),await ia(nt(),p)}await ia(u?u.nodeName:f.name??Ti(t),f);let m;return e.operation==="update_node"?m=`Successfully updated '${t}'`:m=`Successfully added '${t}' to cluster`,d&&(m+=" but there was an error updating target node: "+d.message),m}async function NP(e){ys.trace("addNodeBack received request:",e);let t=await(0,Ys.signCertificate)(e),r;e.csr?(r=t.signingCA,ys.info("addNodeBack received CSR from node:",e.url,"this node will use and respond with CA that was used to issue CSR")):(r=e?.cert_auth,ys.info("addNodeBack received CA from node:",e.url));let n={url:e.url,ca:r};e.subscriptions?n.subscriptions=e.subscriptions:(n.replicates=!0,n.subscriptions=null),e.start_time&&(n.start_time=e.start_time),e.authorization&&(n.authorization=e.authorization),e.shard!==void 0&&(n.shard=e.shard);let s=await(0,Ys.getReplicationCertAuth)();if(n.replicates){let i={url:_c(),ca:s?.certificate,replicates:!0,subscriptions:null};(0,Nc.get)(x.REPLICATION_SHARD)!==void 0&&(i.shard=(0,Nc.get)(x.REPLICATION_SHARD),t.shard=i.shard),e.start_time&&(i.start_time=e.start_time),e.authorization&&(i.authorization=e.authorization),await ia(nt(),i)}return await ia(e.hostname,n),t.nodeName=nt(),t.usingCA=s?.certificate,ys.info("addNodeBack responding to:",e.url,"with CA named:",s?.name),t}async function CP(e){ys.trace("removeNodeBack received request:",e),await Gt().delete(e.name)}function QY(e){let{subscribe:t,publish:r}=e;return{...e,subscribe:r,publish:t}}var Ys,XY,wc,Nc,ys,ma,tpe,rpe,npe,yf=se(()=>{Ys=b(Ts()),XY=b(mt()),wc=b(require("joi")),Nc=b(fe());G();wh();tf();gs();ys=b(Q()),ma=b(Ee()),{pki:tpe}=require("node-forge"),{HTTP_STATUS_CODES:rpe}=ma.hdbErrors,npe=wc.default.object({hostname:wc.default.string(),verify_tls:wc.default.boolean(),replicates:wc.default.boolean(),subscriptions:wc.default.array(),revoked_certificates:wc.default.array(),shard:wc.default.number()});a(spe,"setNode");a(NP,"addNodeBack");a(CP,"removeNodeBack");a(QY,"reverseSubscription")});var py=M((BFe,eW)=>{"use strict";var{handleHDBError:uy,hdbErrors:ipe}=Ee(),{HTTP_STATUS_CODES:dy}=ipe,{addUpdateNodeValidator:ope}=oy(),fy=Q(),my=(G(),D(j)),ZY=vt(),ape=ae(),Gh=_r(),qh=fa(),OP=fe(),cpe=wP(),{Node:lpe,NodeSubscription:upe}=gf(),{broadcast:dpe}=st(),{setNode:fpe}=(yf(),D(Tf)),UFe=fe(),xFe=(G(),D(j)),mpe="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",ppe="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",hpe=OP.get(my.CONFIG_PARAMS.CLUSTERING_NODENAME);eW.exports=Epe;async function Epe(e,t=!1){if(fy.trace("addNode called with:",e),OP.get(my.CONFIG_PARAMS.REPLICATION_URL)||OP.get(my.CONFIG_PARAMS.REPLICATION_HOSTNAME))return fpe(e);qh.checkClusteringEnabled();let r=ope(e);if(r)throw uy(r,r.message,dy.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let f=await qh.getNodeRecord(n);if(!ape.isEmptyOrZeroLength(f))throw uy(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,dy.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await cpe(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=mpe,o;let c=qh.buildNodePayloads(s,hpe,my.OPERATIONS_ENUM.ADD_NODE,await qh.getSystemInfo()),l=[];for(let f=0,m=s.length;f<m;f++){let p=s[f];s[f].start_time===void 0&&delete s[f].start_time,l.push(new upe(p.schema,p.table,p.publish,p.subscribe))}fy.trace("addNode sending remote payload:",c);let u;try{u=await Gh.request(`${n}.${ZY.REQUEST_SUFFIX}`,c)}catch(f){fy.error(`addNode received error from request: ${f}`);for(let p=0,h=s.length;p<h;p++){let E=s[p];E.publish=!1,E.subscribe=!1,await Gh.updateRemoteConsumer(E,n)}let m=Gh.requestErrorHandler(f,"add_node",n);throw uy(new Error,m,dy.INTERNAL_SERVER_ERROR,"error",m)}if(u.status===ZY.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let f=`Error returned from remote node ${n}: ${u.message}`;throw uy(new Error,f,dy.INTERNAL_SERVER_ERROR,"error",f)}fy.trace(u);for(let f=0,m=s.length;f<m;f++){let p=s[f];await Gh.updateRemoteConsumer(p,n),p.subscribe===!0&&await Gh.updateConsumerIterator(p.schema,p.table,n,"start")}let d=new lpe(n,l,u.system_info);return await qh.upsertNodeRecord(d),dpe({type:"nats_update"}),i.length>0?o.message=ppe:o.message=`Successfully added '${n}' to manifest`,o}a(Epe,"addNode")});var vP=M((HFe,rW)=>{"use strict";var{handleHDBError:PP,hdbErrors:_pe}=Ee(),{HTTP_STATUS_CODES:LP}=_pe,{addUpdateNodeValidator:gpe}=oy(),$h=Q(),hy=(G(),D(j)),tW=vt(),kFe=ae(),Vh=_r(),Kh=fa(),DP=fe(),{cloneDeep:Spe}=require("lodash"),Tpe=wP(),{Node:ype,NodeSubscription:Rpe}=gf(),{broadcast:bpe}=st(),{setNode:Ape}=(yf(),D(Tf)),Ipe="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",wpe="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Npe=DP.get(hy.CONFIG_PARAMS.CLUSTERING_NODENAME);rW.exports=Cpe;async function Cpe(e){if($h.trace("updateNode called with:",e),DP.get(hy.CONFIG_PARAMS.REPLICATION_URL)??DP.get(hy.CONFIG_PARAMS.REPLICATION_HOSTNAME))return Ape(e);Kh.checkClusteringEnabled();let t=gpe(e);if(t)throw PP(t,t.message,LP.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Kh.getNodeRecord(r);s.length>0&&(n=Spe(s));let{added:i,skipped:o}=await Tpe(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=Ipe,c;let l=Kh.buildNodePayloads(i,Npe,hy.OPERATIONS_ENUM.UPDATE_NODE,await Kh.getSystemInfo());for(let d=0,f=i.length;d<f;d++){let m=i[d];$h.trace(`updateNode updating work stream for node: ${r} subscription:`,m),i[d].start_time===void 0&&delete i[d].start_time}$h.trace("updateNode sending remote payload:",l);let u;try{u=await Vh.request(`${r}.${tW.REQUEST_SUFFIX}`,l)}catch(d){$h.error(`updateNode received error from request: ${d}`);let f=Vh.requestErrorHandler(d,"update_node",r);throw PP(new Error,f,LP.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===tW.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${r}: ${u.message}`;throw PP(new Error,d,LP.INTERNAL_SERVER_ERROR,"error",d)}$h.trace(u);for(let d=0,f=i.length;d<f;d++){let m=i[d];await Vh.updateRemoteConsumer(m,r),m.subscribe===!0?await Vh.updateConsumerIterator(m.schema,m.table,r,"start"):await Vh.updateConsumerIterator(m.schema,m.table,r,"stop")}return n||(n=[new ype(r,[],u.system_info)]),await Ope(n[0],i,u.system_info),o.length>0?c.message=wpe:c.message=`Successfully updated '${r}'`,c}a(Cpe,"updateNode");async function Ope(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let o=t[s],c=!1;for(let l=0,u=e.subscriptions.length;l<u;l++){let d=n.subscriptions[l];if(d.schema===o.schema&&d.table===o.table){d.publish=o.publish,d.subscribe=o.subscribe,c=!0;break}}c||n.subscriptions.push(new Rpe(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Kh.upsertNodeRecord(n),bpe({type:"nats_update"})}a(Ope,"updateNodeTable")});var aW=M((qFe,oW)=>{"use strict";var iW=require("joi"),{string:nW}=iW.types(),Ppe=mt(),sW=(G(),D(j)),Lpe=fe(),Dpe=vt();oW.exports=vpe;function vpe(e){let t=nW.invalid(Lpe.get(sW.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(Dpe.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null),r=iW.object({operation:nW.valid(sW.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return Ppe.validateBySchema(e,r)}a(vpe,"removeNodeValidator")});var Ey=M((VFe,fW)=>{"use strict";var{handleHDBError:cW,hdbErrors:Mpe}=Ee(),{HTTP_STATUS_CODES:lW}=Mpe,Upe=aW(),Yh=Q(),uW=fa(),xpe=ae(),Rf=(G(),D(j)),dW=vt(),MP=_r(),UP=fe(),{RemotePayloadObject:Bpe}=Fh(),{NodeSubscription:Fpe}=gf(),kpe=bp(),Hpe=Ul(),{broadcast:Gpe}=st(),{setNode:qpe}=(yf(),D(Tf)),$pe=UP.get(Rf.CONFIG_PARAMS.CLUSTERING_NODENAME);fW.exports=Vpe;async function Vpe(e){if(Yh.trace("removeNode called with:",e),UP.get(Rf.CONFIG_PARAMS.REPLICATION_URL)??UP.get(Rf.CONFIG_PARAMS.REPLICATION_HOSTNAME))return qpe(e);uW.checkClusteringEnabled();let t=Upe(e);if(t)throw cW(t,t.message,lW.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await uW.getNodeRecord(r);if(xpe.isEmptyOrZeroLength(n))throw cW(new Error,`Node '${r}' was not found.`,lW.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new Bpe(Rf.OPERATIONS_ENUM.REMOVE_NODE,$pe,[]),i,o=!1;for(let l=0,u=n.subscriptions.length;l<u;l++){let d=n.subscriptions[l];d.subscribe===!0&&await MP.updateConsumerIterator(d.schema,d.table,r,"stop");try{await MP.updateRemoteConsumer(new Fpe(d.schema,d.table,!1,!1),r)}catch(f){Yh.error(f)}}try{i=await MP.request(`${r}.${dW.REQUEST_SUFFIX}`,s),Yh.trace("Remove node reply from remote node:",r,i)}catch(l){Yh.error("removeNode received error from request:",l),o=!0}let c=new kpe(Rf.SYSTEM_SCHEMA_NAME,Rf.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await Hpe.deleteRecord(c),Gpe({type:"nats_update"}),i?.status===dW.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Yh.error("Error returned from remote node:",r,i?.message),`Successfully removed '${r}' from local manifest, however there was an error reaching remote node. Check the logs for more details.`):`Successfully removed '${r}' from manifest`}a(Vpe,"removeNode")});var hW=M((YFe,pW)=>{"use strict";var mW=require("joi"),{string:Kpe,array:Ype}=mW.types(),Wpe=mt(),jpe=oy();pW.exports=zpe;function zpe(e){let t=mW.object({operation:Kpe.valid("configure_cluster").required(),connections:Ype.items(jpe.validationSchema).required()});return Wpe.validateBySchema(e,t)}a(zpe,"configureClusterValidator")});var xP=M((jFe,TW)=>{"use strict";var EW=(G(),D(j)),_y=Q(),Jpe=ae(),Qpe=fe(),Xpe=Ey(),Zpe=py(),ehe=fa(),the=hW(),{handleHDBError:_W,hdbErrors:rhe}=Ee(),{HTTP_STATUS_CODES:gW}=rhe,nhe="Configure cluster complete.",she="Failed to configure the cluster. Check the logs for more details.",ihe="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";TW.exports=ohe;async function ohe(e){_y.trace("configure cluster called with:",e);let t=the(e);if(t)throw _W(t,t.message,gW.BAD_REQUEST,void 0,void 0,!0);let r=await ehe.getAllNodeRecords(),n=[];if(Qpe.get(EW.CONFIG_PARAMS.CLUSTERING_ENABLED)){for(let d=0,f=r.length;d<f;d++){let m=await SW(Xpe,{operation:EW.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[d].name},r[d].name);n.push(m)}_y.trace("All results from configure_cluster remove node:",n)}let s=[],i=e.connections.length;for(let d=0;d<i;d++){let f=e.connections[d],m=await SW(Zpe,f,f.node_name);s.push(m)}_y.trace("All results from configure_cluster add node:",s);let o=[],c=[],l=!1,u=n.concat(s);for(let d=0,f=u.length;d<f;d++){let m=u[d];m.status==="rejected"&&(_y.error(m.node_name,m?.error?.message,m?.error?.stack),o.includes(m.node_name)||o.push(m.node_name)),(m?.result?.message?.includes?.("Successfully")||m?.result?.includes?.("Successfully"))&&(l=!0),!(typeof m.result=="string"&&m.result.includes("Successfully removed")||m.status==="rejected")&&c.push({node_name:m?.node_name,response:m?.result})}if(Jpe.isEmptyOrZeroLength(o))return{message:nhe,connections:c};if(l)return{message:ihe,failed_nodes:o,connections:c};throw _W(new Error,she,gW.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(ohe,"configureCluster");async function SW(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(SW,"functionWrapper")});var AW=M((JFe,bW)=>{"use strict";var Wh=require("joi"),ahe=mt(),{validateSchemaExists:yW,validateTableExists:che,validateSchemaName:RW}=Ji(),lhe=Wh.object({operation:Wh.string().valid("purge_stream"),schema:Wh.string().custom(yW).custom(RW).optional(),database:Wh.string().custom(yW).custom(RW).optional(),table:Wh.string().custom(che).required()});function uhe(e){return ahe.validateBySchema(e,lhe)}a(uhe,"purgeStreamValidator");bW.exports=uhe});var BP=M((XFe,IW)=>{"use strict";var{handleHDBError:dhe,hdbErrors:fhe}=Ee(),{HTTP_STATUS_CODES:mhe}=fhe,phe=AW(),hhe=_r(),Ehe=fa();IW.exports=_he;async function _he(e){e.schema=e.schema??e.database;let t=phe(e);if(t)throw dhe(t,t.message,mhe.BAD_REQUEST,void 0,void 0,!0);Ehe.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await hhe.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(_he,"purgeStream")});var HP=M((eke,vW)=>{"use strict";var kP=fa(),ghe=_r(),Sy=fe(),bf=(G(),D(j)),nu=vt(),She=ae(),FP=Q(),{RemotePayloadObject:The}=Fh(),{ErrorCode:wW}=require("nats"),{parentPort:NW}=require("worker_threads"),{onMessageByType:yhe}=st(),{getThisNodeName:Rhe}=(gs(),D(aa)),{requestClusterStatus:bhe}=(wh(),D(y1)),{getReplicationSharedStatus:Ahe,getHDBNodeTable:Ihe}=(tf(),D(p1)),{CONFIRMATION_STATUS_POSITION:whe,RECEIVED_VERSION_POSITION:CW,RECEIVED_TIME_POSITION:Nhe,SENDING_TIME_POSITION:Che,RECEIVING_STATUS_POSITION:Ohe,RECEIVING_STATUS_RECEIVING:Phe,BACK_PRESSURE_RATIO_POSITION:Lhe}=(LO(),D(dK)),OW=Sy.get(bf.CONFIG_PARAMS.CLUSTERING_ENABLED),PW=Sy.get(bf.CONFIG_PARAMS.CLUSTERING_NODENAME);vW.exports={clusterStatus:Dhe,buildNodeStatus:DW};var LW;yhe("cluster-status",async e=>{LW(e)});async function Dhe(){if(Sy.get(bf.CONFIG_PARAMS.REPLICATION_URL)||Sy.get(bf.CONFIG_PARAMS.REPLICATION_HOSTNAME)){let n;NW?(NW.postMessage({type:"request-cluster-status"}),n=await new Promise(i=>{LW=i})):n=bhe();for(let i of n.connections){let o=i.name;for(let c of i.database_sockets){let l=c.database,u;for(let f of Object.values(databases[l]||{}))if(u=f.auditStore,u)break;if(!u)continue;let d=Ahe(u,l,o);c.lastCommitConfirmed=gy(d[whe]),c.lastReceivedRemoteTime=gy(d[CW]),c.lastReceivedLocalTime=gy(d[Nhe]),c.lastReceivedVersion=d[CW],c.sendingMessage=gy(d[Che]),c.backPressurePercent=d[Lhe]*100,c.lastReceivedStatus=d[Ohe]===Phe?"Receiving":"Waiting"}}n.node_name=Rhe();let s=Ihe().primaryStore.get(n.node_name);return s?.shard&&(n.shard=s.shard),s?.url&&(n.url=s.url),n.is_enabled=!0,n}let e={node_name:PW,is_enabled:OW,connections:[]};if(!OW)return e;let t=await kP.getAllNodeRecords();if(She.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(DW(t[n],e.connections));return await Promise.allSettled(r),e}a(Dhe,"clusterStatus");function gy(e){return e?e===1?"Copying":new Date(e).toUTCString():void 0}a(gy,"asDate");async function DW(e,t){let r=e.name,n=new The(bf.OPERATIONS_ENUM.CLUSTER_STATUS,PW,void 0,await kP.getSystemInfo()),s,i,o=nu.CLUSTER_STATUS_STATUSES.OPEN;try{let l=Date.now();s=await ghe.request(nu.REQUEST_SUBJECT(r),n),i=Date.now()-l,s.status===nu.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=nu.CLUSTER_STATUS_STATUSES.CLOSED,FP.error(`Error getting node status from ${r} `,s))}catch(l){FP.warn(`Error getting node status from ${r}`,l),l.code===wW.NoResponders?o=nu.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:l.code===wW.Timeout?o=nu.CLUSTER_STATUS_STATUSES.TIMEOUT:o=nu.CLUSTER_STATUS_STATUSES.CLOSED}let c=new vhe(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let l={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==bf.PRE_4_0_0_VERSION&&await kP.upsertNodeRecord(l)}catch(l){FP.error("Cluster status encountered an error updating system info for node:",r,l)}t.push(c)}a(DW,"buildNodeStatus");function vhe(e,t,r,n,s,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:n},this.latency_ms=s,this.uptime=i,this.subscriptions=o,this.system_info=c}a(vhe,"NodeStatusObject")});var qP=M((rke,MW)=>{"use strict";var{handleHDBError:Mhe,hdbErrors:Uhe}=Ee(),{HTTP_STATUS_CODES:xhe}=Uhe,Bhe=_r(),Fhe=fa(),GP=ae(),Ty=require("joi"),khe=mt(),Hhe=2e3,Ghe=Ty.object({timeout:Ty.number().min(1),connected_nodes:Ty.boolean(),routes:Ty.boolean()});MW.exports=qhe;async function qhe(e){Fhe.checkClusteringEnabled();let t=khe.validateBySchema(e,Ghe);if(t)throw Mhe(t,t.message,xhe.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||GP.autoCastBoolean(n),o=s===void 0||GP.autoCastBoolean(s),c={nodes:[]},l=await Bhe.getServerList(r??Hhe),u={};if(i)for(let d=0,f=l.length;d<f;d++){let m=l[d].statsz;m&&(u[l[d].server.name]=m.routes)}for(let d=0,f=l.length;d<f;d++){if(l[d].statsz)continue;let m=l[d].server,p=l[d].data;if(m.name.endsWith("-hub")){let h={name:m.name.slice(0,-4),response_time:l[d].response_time};i&&(h.connected_nodes=[],u[m.name]&&u[m.name].forEach(E=>{h.connected_nodes.includes(E.name.slice(0,-4))||h.connected_nodes.push(E.name.slice(0,-4))})),o&&(h.routes=p.cluster?.urls?p.cluster?.urls.map(E=>({host:E.split(":")[0],port:GP.autoCast(E.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(qhe,"clusterNetwork")});var FW=M((ske,BW)=>{"use strict";var $P=require("joi"),UW=mt(),{routeConstraints:xW}=uA();BW.exports={setRoutesValidator:$he,deleteRoutesValidator:Vhe};function $he(e){let t=$P.object({server:$P.valid("hub","leaf"),routes:xW.required()});return UW.validateBySchema(e,t)}a($he,"setRoutesValidator");function Vhe(e){let t=$P.object({routes:xW.required()});return UW.validateBySchema(e,t)}a(Vhe,"deleteRoutesValidator")});var yy=M((oke,KW)=>{"use strict";var pa=_t(),VP=ae(),Ws=(G(),D(j)),Af=fe(),kW=FW(),{handleHDBError:HW,hdbErrors:Khe}=Ee(),{HTTP_STATUS_CODES:GW}=Khe,qW="cluster routes successfully set",$W="cluster routes successfully deleted";KW.exports={setRoutes:Whe,getRoutes:jhe,deleteRoutes:zhe};function Yhe(e){let t=pa.getClusteringRoutes(),r=e.server==="hub"?t.hub_routes:t.leaf_routes,n=e.server==="hub"?t.leaf_routes:t.hub_routes,s=[],i=[];for(let o=0,c=e.routes.length;o<c;o++){let l=e.routes[o];l.port=VP.autoCast(l.port);let u=r.some(f=>f.host===l.host&&f.port===l.port),d=n.some(f=>f.host===l.host&&f.port===l.port);u||d?s.push(l):(r.push(l),i.push(l))}return e.server==="hub"?pa.updateConfigValue(Ws.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,r):pa.updateConfigValue(Ws.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,r),{message:qW,set:i,skipped:s}}a(Yhe,"setRoutesNats");function Whe(e){let t=kW.setRoutesValidator(e);if(t)throw HW(t,t.message,GW.BAD_REQUEST,void 0,void 0,!0);if(Af.get(Ws.CONFIG_PARAMS.CLUSTERING_ENABLED))return Yhe(e);let r=[],n=[],s=Af.get(Ws.CONFIG_PARAMS.REPLICATION_ROUTES)??[];return e.routes.forEach(i=>{VW(s,i)?n.push(i):(s.push(i),r.push(i))}),pa.updateConfigValue(Ws.CONFIG_PARAMS.REPLICATION_ROUTES,s),{message:qW,set:r,skipped:n}}a(Whe,"setRoutes");function VW(e,t){return typeof t=="string"?e.includes(t):typeof t=="object"&&t!==null?e.some(r=>(r.host===t.host||r.hostname===t.hostname)&&r.port===t.port):!1}a(VW,"existsInArray");function jhe(){if(Af.get(Ws.CONFIG_PARAMS.CLUSTERING_ENABLED)){let e=pa.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}else return Af.get(Ws.CONFIG_PARAMS.REPLICATION_ROUTES)??[]}a(jhe,"getRoutes");function zhe(e){let t=kW.deleteRoutesValidator(e);if(t)throw HW(t,t.message,GW.BAD_REQUEST,void 0,void 0,!0);if(Af.get(Ws.CONFIG_PARAMS.CLUSTERING_ENABLED))return Jhe(e);let r=[],n=[],s=Af.get(Ws.CONFIG_PARAMS.REPLICATION_ROUTES)??[],i=[];return s.forEach(o=>{VW(e.routes,o)?r.push(o):(i.push(o),n.push(o))}),pa.updateConfigValue(Ws.CONFIG_PARAMS.REPLICATION_ROUTES,i),{message:$W,deleted:r,skipped:n}}a(zhe,"deleteRoutes");function Jhe(e){let t=pa.getClusteringRoutes(),r=t.hub_routes,n=t.leaf_routes,s=[],i=[],o=!1,c=!1;for(let l=0,u=e.routes.length;l<u;l++){let d=e.routes[l],f=!1;for(let m=0,p=r.length;m<p;m++){let h=r[m];if(d.host===h.host&&d.port===h.port){r.splice(m,1),f=!0,o=!0,s.push(d);break}}if(!f){let m=!0;for(let p=0,h=n.length;p<h;p++){let E=n[p];if(d.host===E.host&&d.port===E.port){n.splice(p,1),c=!0,m=!1,s.push(d);break}}m&&i.push(d)}}return o&&(r=VP.isEmptyOrZeroLength(r)?null:r,pa.updateConfigValue(Ws.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,r)),c&&(n=VP.isEmptyOrZeroLength(n)?null:n,pa.updateConfigValue(Ws.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:$W,deleted:s,skipped:i}}a(Jhe,"deleteRoutesNats")});var WW=M((cke,YW)=>{"use strict";var Qhe=vt(),KP=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,l,u,d,f,m,p,h){this.port=t,o===null&&(o=void 0),this.server_name=r+Qhe.SERVER_SUFFIX.HUB,this.pid_file=n,this.max_payload=67108864,this.reconnect_error_reports=100,this.jetstream={enabled:!1},this.tls={cert_file:s,key_file:i,ca_file:o,insecure:c,verify:l},this.leafnodes={port:u,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:d,port:f,routes:m,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:l}},this.accounts={SYS:{users:p},HDB:{users:h}},this.system_account="SYS"}};YW.exports=KP});var JW=M((uke,zW)=>{"use strict";var jW=vt(),YP=class{static{a(this,"LeafConfigObject")}constructor(t,r,n,s,i,o,c,l,u,d,f){this.port=t,f===null&&(f=void 0),this.server_name=r+jW.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+jW.SERVER_SUFFIX.LEAF},this.tls={cert_file:u,key_file:d,ca_file:f,insecure:!0},this.leafnodes={remotes:[{tls:{ca_file:f,insecure:!0},urls:i,account:"SYS"},{tls:{ca_file:f,insecure:!0},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:l,jetstream:"enabled"}},this.system_account="SYS"}};zW.exports=YP});var XW=M((fke,QW)=>{"use strict";var WP=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};QW.exports=WP});var ej=M((pke,ZW)=>{"use strict";var Xhe=vt(),jP=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+Xhe.SERVER_SUFFIX.ADMIN,this.password=r}};ZW.exports=jP});var Iy=M((Eke,nj)=>{"use strict";var su=require("path"),iu=require("fs-extra"),Zhe=WW(),eEe=JW(),tEe=XW(),rEe=ej(),zP=(hs(),D(oo)),wf=ae(),Wn=_t(),by=(G(),D(j)),jh=vt(),{CONFIG_PARAMS:cr}=by,Nf=Q(),zh=fe(),tj=no(),JP=_r(),nEe=Ts(),If="clustering",sEe=1e4,rj=50;nj.exports={generateNatsConfig:oEe,removeNatsConfig:aEe,getHubConfigPath:iEe};function iEe(){let e=zh.get(cr.ROOTPATH);return su.join(e,If,jh.NATS_CONFIG_FILES.HUB_SERVER)}a(iEe,"getHubConfigPath");async function oEe(e=!1,t=void 0){console.error("Warning: NATS replication is deprecated and will be removed in version 5.0 of Harper");let r=zh.get(cr.ROOTPATH);iu.ensureDirSync(su.join(r,"clustering","leaf")),zh.initSync();let n=Wn.getConfigFromFile(cr.CLUSTERING_TLS_CERT_AUTH),s=Wn.getConfigFromFile(cr.CLUSTERING_TLS_PRIVATEKEY),i=Wn.getConfigFromFile(cr.CLUSTERING_TLS_CERTIFICATE);!await iu.exists(i)&&!await iu.exists(!n)&&await nEe.createNatsCerts();let o=su.join(r,If,jh.PID_FILES.HUB),c=su.join(r,If,jh.PID_FILES.LEAF),l=Wn.getConfigFromFile(cr.CLUSTERING_LEAFSERVER_STREAMS_PATH),u=su.join(r,If,jh.NATS_CONFIG_FILES.HUB_SERVER),d=su.join(r,If,jh.NATS_CONFIG_FILES.LEAF_SERVER),f=Wn.getConfigFromFile(cr.CLUSTERING_TLS_INSECURE),m=Wn.getConfigFromFile(cr.CLUSTERING_TLS_VERIFY),p=Wn.getConfigFromFile(cr.CLUSTERING_NODENAME),h=Wn.getConfigFromFile(cr.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await JP.checkNATSServerInstalled()||Ay("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let E=await zP.listUsers(),_=Wn.getConfigFromFile(cr.CLUSTERING_USER),R=await zP.getClusterUser();(wf.isEmpty(R)||R.active!==!0)&&Ay(`Invalid cluster user '${_}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await Ry(cr.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await Ry(cr.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await Ry(cr.CLUSTERING_HUBSERVER_NETWORK_PORT),await Ry(cr.CLUSTERING_LEAFSERVER_NETWORK_PORT));let S=[],y=[];for(let[z,Y]of E.entries())Y.role?.role===by.ROLE_TYPES_ENUM.CLUSTER_USER&&Y.active&&(S.push(new rEe(Y.username,tj.decrypt(Y.hash))),y.push(new tEe(Y.username,tj.decrypt(Y.hash))));let w=[],{hub_routes:I}=Wn.getClusteringRoutes();if(!wf.isEmptyOrZeroLength(I))for(let z of I)w.push(`tls://${R.sys_name_encoded}:${R.uri_encoded_d_hash}@${z.host}:${z.port}`);let H=new Zhe(Wn.getConfigFromFile(cr.CLUSTERING_HUBSERVER_NETWORK_PORT),p,o,i,s,n,f,m,h,Wn.getConfigFromFile(cr.CLUSTERING_HUBSERVER_CLUSTER_NAME),Wn.getConfigFromFile(cr.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),w,S,y);n==null&&(delete H.tls.ca_file,delete H.leafnodes.tls.ca_file),t=wf.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===by.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await iu.writeJson(u,H),Nf.trace(`Hub server config written to ${u}`));let X=`tls://${R.sys_name_encoded}:${R.uri_encoded_d_hash}@0.0.0.0:${h}`,q=`tls://${R.uri_encoded_name}:${R.uri_encoded_d_hash}@0.0.0.0:${h}`,k=new eEe(Wn.getConfigFromFile(cr.CLUSTERING_LEAFSERVER_NETWORK_PORT),p,c,l,[X],[q],S,y,i,s,n,f);n==null&&delete k.tls.ca_file,(t===void 0||t===by.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await iu.writeJson(d,k),Nf.trace(`Leaf server config written to ${d}`))}a(oEe,"generateNatsConfig");async function Ry(e){let t=zh.get(e);return wf.isEmpty(t)&&Ay(`port undefined for '${e}'`),await wf.isPortTaken(t)&&Ay(`'${e}' port '${t}' is is in use by another process, check to see if HarperDB is already running or another process is using this port.`),!0}a(Ry,"isPortAvailable");function Ay(e){let t=`Error generating clustering config: ${e}`;Nf.error(t),console.error(t),process.exit(1)}a(Ay,"generateNatsConfigError");async function aEe(e){let{port:t,config_file:r}=JP.getServerConfig(e),{username:n,decrypt_hash:s}=await zP.getClusterUser(),i=0,o=2e3;for(;i<rj;){try{let d=await JP.createConnection(t,n,s,!1);if(d.protocol.connected===!0){d.close();break}}catch(d){Nf.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${d}`)}if(i++,i>=rj)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);let u=o*(i*2);u>3e4&&Nf.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await wf.asyncSetTimeout(u)}let c="0".repeat(sEe),l=su.join(zh.get(cr.ROOTPATH),If,r);await iu.writeFile(l,c),await iu.remove(l),Nf.notify(e,"started.")}a(aEe,"removeNatsConfig")});var ZP={};ye(ZP,{compactOnStart:()=>cEe,copyDb:()=>lj});async function cEe(){ha.notify("Running compact on start"),console.log("Running compact on start");let e=(0,QP.get)(x.ROOTPATH),t=new Map,r=lt();(0,XP.updateConfigValue)(x.STORAGE_COMPACTONSTART,!1);try{for(let n in r){if(n==="system"||n.endsWith("-copy"))continue;let s;for(let l in r[n]){s=r[n][l].primaryStore.path;break}if(!s){console.log("Couldn't find any tables in database",n);continue}let i=(0,wy.join)(e,"backup",n+".mdb"),o=(0,wy.join)(e,Zc,n+"-copy.mdb"),c=0;try{c=await sj(n),console.log("Database",n,"before compact has a total record count of",c)}catch(l){ha.error("Error getting record count for database",n,l),console.error("Error getting record count for database",n,l)}t.set(n,{dbPath:s,copyDest:o,backupDest:i,recordCount:c}),await lj(n,o),console.log("Backing up",n,"to",i);try{await(0,ou.move)(s,i,{overwrite:!0})}catch(l){console.log("Error moving database",s,"to",i,l)}console.log("Moving copy compacted",n,"to",s),await(0,ou.move)(o,s,{overwrite:!0}),await(0,ou.remove)((0,wy.join)(e,Zc,`${n}-copy.mdb-lock`))}try{Ud()}catch(n){ha.error("Error resetting databases after backup",n),console.error("Error resetting databases after backup",n)}try{Ud()}catch(n){ha.error("Error resetting databases after backup",n),console.error("Error resetting databases after backup",n),process.exit(0)}}catch(n){ha.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,XP.updateConfigValue)(x.STORAGE_COMPACTONSTART,!1);for(let[s,{dbPath:i,backupDest:o}]of t){console.error("Moving backup database",o,"back to",i);try{await(0,ou.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw Ud(),n}for(let[n,{backupDest:s,recordCount:i}]of t){let o=await sj(n);if(console.log("Database",n,"after compact has a total record count of",o),i!==o){let c=`There is a discrepancy between pre and post compact record count for database ${n}.
20
20
  Total record count before compaction: ${i}, total after: ${o}.
21
21
  Database backup has not been removed and can be found here: ${s}`;ha.warn(c),console.warn(c)}(0,QP.get)(x.STORAGE_COMPACTONSTARTKEEPBACKUP)!==!0&&(console.log("Removing backup",s),await(0,ou.remove)(s))}}async function sj(e){let t=await(0,cj.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}function Cf(){}async function lj(e,t){console.log(`Copying database ${e} to ${t}`);let r=lt()[e];if(!r)throw new Error(`Source database not found: ${e}`);let n;for(let f in r){let m=r[f];m.primaryStore.put=Cf,m.primaryStore.remove=Cf;for(let p in m.indices){let h=m.indices[p];h.put=Cf,h.remove=Cf}m.auditStore&&(m.auditStore.put=Cf,m.auditStore.remove=Cf),n=m.primaryStore.rootStore}if(!n)throw new Error(`Source database does not have any tables: ${e}`);let s=n.dbisDb,i=n.auditStore,o=(0,ij.open)(new oj.default(t)),c=o.openDB(Ny.INTERNAL_DBIS_NAME),l,u=0,d=s.useReadTransaction();try{for(let{key:m,value:p}of s.getRange({transaction:d})){let h=p.is_hash_attribute||p.isPrimaryKey,E,_;if(h&&(E=p.compression,_=LS(),_?p.compression=_:delete p.compression,E?.dictionary?.toString()===_?.dictionary?.toString()&&(E=null,_=null)),c.put(m,p),!(h||p.indexed))continue;let R=new aj.OpenDBIObject(!h,h);R.encoding="binary",R.compression=E;let S=n.openDB(m,R);S.decoder=null,S.decoderCopies=!1,S.encoding="binary",R.compression=_;let y=o.openDB(m,R);y.encoder=null,console.log("copying",m,"from",e,"to",t),await f(S,y,h,d)}if(i){let m=n.openDB(Ny.AUDIT_STORE_NAME,Qm);console.log("copying audit log for",e,"to",t),f(i,m,!1,d)}async function f(m,p,h,E){let _=0,R=0,S=0,y=1e7,w=null;for(;y-- >0;)try{for(let I of m.getKeys({start:w,transaction:E}))try{w=I;let{value:H,version:X}=m.getEntry(I,{transaction:E});if(H?.length<14&&h){S++;continue}l=p.put(I,H,h?X:void 0),_++,E.openTimer&&(E.openTimer=0),R+=(I?.length||10)+H.length,u++>5e3&&(await l,console.log("copied",_,"entries",S,"delete records,",R,"bytes"),u=0)}catch(H){console.error("Error copying record",typeof I=="symbol"?"symbol":I,"from",e,"to",t,H)}console.log("finish copying, copied",_,"entries",S,"delete records,",R,"bytes");return}catch{if(typeof w=="string"){if(w==="z")return console.error("Reached end of dbi",w,"for",e,"to",t);w=w.slice(0,-2)+"z"}else if(typeof w=="number")w++;else return console.error("Unknown key type",w,"for",e,"to",t)}}a(f,"copyDbi"),await l,console.log("copied database "+e+" to "+t)}finally{d.done(),o.close()}}var ij,wy,ou,QP,oj,aj,Ny,cj,XP,ha,eL=se(()=>{Oe();ij=require("lmdb"),wy=require("path"),ou=require("fs-extra"),QP=b(fe()),oj=b(dp()),aj=b(up()),Ny=b(Jt());G();qi();cj=b(Vl()),XP=b(_t()),ha=b(Q());a(cEe,"compactOnStart");a(sj,"getTotalDBRecordCount");a(Cf,"noop");a(lj,"copyDb")});var rL=M((Rke,uj)=>{"use strict";var Jh=fe();Jh.initSync();var Of=require("fs-extra"),tL=require("path"),Pf=(G(),D(j)),lEe=require("crypto"),uEe=require("uuid").v4;uj.exports=dEe;function dEe(){if(Jh.getHdbBasePath()!==void 0){let e=tL.join(Jh.getHdbBasePath(),Pf.LICENSE_KEY_DIR_NAME,Pf.JWT_ENUM.JWT_PRIVATE_KEY_NAME),t=tL.join(Jh.getHdbBasePath(),Pf.LICENSE_KEY_DIR_NAME,Pf.JWT_ENUM.JWT_PUBLIC_KEY_NAME),r=tL.join(Jh.getHdbBasePath(),Pf.LICENSE_KEY_DIR_NAME,Pf.JWT_ENUM.JWT_PASSPHRASE_NAME);try{Of.accessSync(r),Of.accessSync(e),Of.accessSync(t)}catch(n){if(n.code==="ENOENT"){let s=uEe(),i=lEe.generateKeyPairSync("rsa",{modulusLength:4096,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem",cipher:"aes-256-cbc",passphrase:s}});Of.writeFileSync(r,s),Of.writeFileSync(e,i.privateKey),Of.writeFileSync(t,i.publicKey)}else throw n}}}a(dEe,"checkJWTTokenExist")});var fj=M((Ake,dj)=>{"use strict";var nL=class{static{a(this,"HdbInfoInsertObject")}constructor(t,r,n){this.info_id=t,this.data_version_num=r,this.hdb_version_num=n}};dj.exports={HdbInfoInsertObject:nL}});var hj=M((wke,pj)=>{"use strict";var mj=(G(),D(j)),sL=class{static{a(this,"UpgradeObject")}constructor(t,r){this[mj.UPGRADE_JSON_FIELD_NAMES_ENUM.DATA_VERSION]=t,this[mj.UPGRADE_JSON_FIELD_NAMES_ENUM.UPGRADE_VERSION]=r}};pj.exports={UpgradeObject:sL}});var Cy=M((Cke,_j)=>{"use strict";var js=require("prompt"),Lf=require("chalk"),Ej=Q(),bi=require("os"),iL=el(),oL=["yes","y"];async function fEe(e){let t=`${bi.EOL}`+Lf.bold.green("Your current HarperDB version requires that we complete an update process.")+`${bi.EOL}If a backup of your data has not been created, we recommend you cancel this process and backup before proceeding.${bi.EOL}${bi.EOL}You can read more about the changes in this upgrade at https://harperdb.io/developers/release-notes/${bi.EOL}`;js.override=iL(["CONFIRM_UPGRADE"]),js.start(),js.message=t;let r={properties:{CONFIRM_UPGRADE:{description:Lf.magenta(`${bi.EOL}[CONFIRM_UPGRADE] Do you want to upgrade your HDB instance now? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"no",required:!0}}},n;try{n=await js.get([r])}catch(s){return Ej.error("There was an error when prompting user about an upgrade."),Ej.error(s),!1}return oL.includes(n.CONFIRM_UPGRADE)}a(fEe,"forceUpdatePrompt");async function mEe(e){let t=`${bi.EOL}`+Lf.bold.green(`Your installed HarperDB version is older than the version used to create your data. Downgrading is not recommended as it is not tested and guaranteed to work. However, if you need to downgrade, and a backup of your data has not been created, we recommend you cancel this process and backup before proceeding.${bi.EOL}`);js.override=iL(["CONFIRM_DOWNGRADE"]),js.start(),js.message=t;let r={properties:{CONFIRM_DOWNGRADE:{description:Lf.magenta(`${bi.EOL}[CONFIRM_DOWNGRADE] Do you want to proceed with using your downgraded HDB instance now? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"no",required:!0}}},n=await js.get([r]);return oL.includes(n.CONFIRM_DOWNGRADE)}a(mEe,"forceDowngradePrompt");async function pEe(){let e=`${bi.EOL}`+Lf.bold.green("We now require a Certifacte Authority certificate. HarperDB can generate all new certificates for you (your existing certificates will be backed up) or you can keep any existing certificates and add your own CA certificate. To add your own CA certificate set the <certificateAuthority> parameter in harperdb-config.yaml");js.override=iL(["GENERATE_CERTS"]),js.start(),js.message=e;let t={properties:{GENERATE_CERTS:{description:Lf.magenta(`${bi.EOL}[GENERATE_CERTS] Do you want HarperDB to generate all new certificates? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"yes",required:!0}}},r=await js.get([t]);return oL.includes(r.GENERATE_CERTS)}a(pEe,"upgradeCertsPrompt");_j.exports={forceUpdatePrompt:fEe,forceDowngradePrompt:mEe,upgradeCertsPrompt:pEe}});var Oy=M((Pke,gj)=>{"use strict";var aL=class{static{a(this,"UpgradeDirective")}constructor(t){this.version=t,this.sync_functions=[],this.async_functions=[]}};gj.exports=aL});var Tj=M((xke,Sj)=>{"use strict";var hEe=ae(),EEe=_t(),Dke=Q(),vke=require("path"),Mke=require("fs"),Uke=(G(),D(j));Sj.exports={getOldPropsValue:_Ee};function _Ee(e,t,r=!1){let n=t.getRaw(e);return hEe.isNotEmptyAndHasValue(n)?n:r?EEe.getDefaultConfig(e):""}a(_Ee,"getOldPropsValue")});var Aj=M((Fke,bj)=>{"use strict";var Cc=require("path"),Oc=require("fs-extra"),gEe=require("properties-reader"),SEe=Oy(),Tr=Q(),{getOldPropsValue:St}=Tj(),{HDB_SETTINGS_NAMES:be,CONFIG_PARAMS:au}=(G(),D(j)),cu=_t(),Py=fe(),yj=ae(),So=(G(),D(j)),cL=new SEe("3.1.0"),Rj=[];function TEe(){let e=gEe(Py.get(be.SETTINGS_PATH_KEY)),t="Updating settings file for version 3.1.0";console.log(t),Tr.info(t);let r=` ;Settings for the HarperDB process.