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.
- package/README.md +1 -1
- package/bin/harperdb.js +1 -1
- package/bin/lite.js +1 -1
- package/launchServiceScripts/launchNatsIngestService.js +1 -1
- package/launchServiceScripts/launchNatsReplyService.js +1 -1
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/jobs/jobProcess.js +1 -1
- package/server/threads/threadServer.js +1 -1
- package/studio/web/assets/{index-DzmdGhay.js → index-B9_qS7Kl.js} +1 -1
- package/studio/web/assets/{index-4tz9iZO6.js → index-DTFv2HfO.js} +4 -4
- package/studio/web/assets/{index-n1A9yxoS.js → index-zg8oq7u7.js} +1 -1
- package/studio/web/assets/{index.lazy-DhQph7si.js → index.lazy-WznRtvfY.js} +1 -1
- package/studio/web/assets/{profiler-xCOLgFE8.js → profiler-B8q4d48d.js} +1 -1
- package/studio/web/assets/{react-redux-C8VgMI21.js → react-redux-DGTs_kVY.js} +1 -1
- package/studio/web/assets/{startRecording-CapM7c3R.js → startRecording-DFPWzJie.js} +1 -1
- package/studio/web/index.html +1 -1
- package/utility/scripts/restartHdb.js +1 -1
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
`)}}});var vq,Hl,Mq,mc,Gp,Pd,Wce,bS,XN=se(()=>{vq=b(ls()),Hl=b(tt());H();Mq=b(ir());wd();RS();mc=(0,Mq.loggerWithTag)("componentStatus.crossThread"),Gp=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,Hl.onMessageByType)(P_.COMPONENT_STATUS_RESPONSE,({message:t})=>{let r=t.isMainThread?"main":`worker-${t.workerIndex}`;mc.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&&(mc.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,Hl.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(),mc.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),mc.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,vq.sendItcEvent)({type:P_.COMPONENT_STATUS_REQUEST,message:{requestId:r}}).then(()=>{_()}).catch(y=>{E=!0,S(),this.responseCheckers.delete(r),h(new Cd("sendItcEvent",y))})});this.responseCheckers.delete(r);let u=new Map,d=t.getAllStatuses(),f=(0,Hl.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 mc.debug?.(`Collected component status from ${l.length+1} threads (including local)`),u}catch(r){return r instanceof Cd?mc.error?.(`ITC failure during component status collection: ${r.message}`):mc.warn?.("Failed to collect component status from all threads:",r),mc.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,Hl.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)}},Pd=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}},Wce=parseInt(process.env.COMPONENT_STATUS_TIMEOUT||"5000"),bS=new Gp(Wce)});var pc,AS=se(()=>{jN();wd();XN();RS();pc=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 Od(String(t),"setStatus","Component name must be a non-empty string");if(!Object.values(Pe).includes(r))throw new Od(t,"setStatus",`Invalid status level: ${r}. Must be one of: ${Object.values(Pe).join(", ")}`);this.statusMap.set(t,new Nd(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 bS.collect(t);return Pd.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 Er,IS=se(()=>{AS();Er=new pc});function xq(e){let t=Uq.get(e);return t||(t=new ZN(e),Uq.set(e,t)),t}function Bq(){Er.reset()}var ZN,Uq,lo,Fq,kq=se(()=>{IS();wd();ZN=class{static{a(this,"ComponentStatusBuilder")}componentName;constructor(t){this.componentName=t}healthy(t){return Er.setStatus(this.componentName,Pe.HEALTHY,t),this}warning(t){return Er.setStatus(this.componentName,Pe.WARNING,t),this}error(t,r){return Er.setStatus(this.componentName,Pe.ERROR,t,r),this}loading(t){return Er.setStatus(this.componentName,Pe.LOADING,t||"Loading..."),this}unknown(t){return Er.setStatus(this.componentName,Pe.UNKNOWN,t),this}get(){return Er.getStatus(this.componentName)}},Uq=new Map;a(xq,"statusForComponent");lo={loading(e,t){Er.initializeLoading(e,t)},loaded(e,t){Er.markLoaded(e,t)},failed(e,t,r){Er.markFailed(e,t,r)}};a(Bq,"reset");Fq=Pe});var qp={};ye(qp,{AggregationError:()=>JN,COMPONENT_STATUS_LEVELS:()=>Pe,ComponentStatus:()=>Nd,ComponentStatusError:()=>fc,ComponentStatusOperationError:()=>Od,ComponentStatusRegistry:()=>pc,CrossThreadCollectionError:()=>QN,CrossThreadStatusCollector:()=>Gp,CrossThreadTimeoutError:()=>zN,ITCError:()=>Cd,StatusAggregator:()=>Pd,componentStatusRegistry:()=>Er,crossThreadCollector:()=>bS,query:()=>jce});var jce,Hq=se(()=>{IS();AS();jN();AS();XN();IS();RS();wd();jce={get(e){return Er.getStatus(e)},all(){return Er.getAllStatuses()},byStatus(e){return Er.getComponentsByStatus(e)},summary(){return Er.getStatusSummary()},async allThreads(){return pc.getAggregatedFromAllThreads(Er)}}});var eC={};ye(eC,{STATUS:()=>Fq,internal:()=>qp,lifecycle:()=>lo,reset:()=>Bq,statusForComponent:()=>xq});var $p=se(()=>{kq();Hq()});var Kp=M((Mxe,$q)=>{"use strict";var _s=Q(),yn=(H(),D(W)),zce=ZB(),Jce=(Es(),D(co)),{validateEvent:tC}=ls(),Vp=fs(),Qce=require("process"),{resetDatabases:Xce}=(Oe(),D(pt)),Zce={[yn.ITC_EVENT_TYPES.SCHEMA]:ele,[yn.ITC_EVENT_TYPES.USER]:qq,[yn.ITC_EVENT_TYPES.COMPONENT_STATUS_REQUEST]:rle};async function ele(e){let t=tC(e);if(t){_s.error(t);return}_s.trace("ITC schemaHandler received schema event:",e),await zce(e.message),await tle(e.message)}a(ele,"schemaHandler");async function tle(e){try{Vp.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Vp.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Vp.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=Xce();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){_s.error(t)}}a(tle,"syncSchemaMetadata");var Gq=[];async function qq(e){try{try{Vp.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Vp.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){_s.warn(r)}let t=tC(e);if(t){_s.error(t);return}_s.trace(`ITC userHandler ${yn.HDB_ITC_CLIENT_PREFIX}${Qce.pid} received user event:`,e),await Jce.setUsersWithRolesCache();for(let r of Gq)r()}catch(t){_s.error(t)}}a(qq,"userHandler");qq.addListener=function(e){Gq.push(e)};async function rle(e){try{let t=tC(e);if(t){_s.error(t);return}_s.trace("ITC componentStatusRequestHandler received request:",e);let{internal:r}=($p(),D(eC)),{getWorkerIndex:n}=tt(),{sendItcEvent:s}=ls(),i=r.componentStatusRegistry.getAllStatuses(),o=Array.from(i.entries()),c=n(),l=c===void 0,u=e.message.originator,d={type:yn.ITC_EVENT_TYPES.COMPONENT_STATUS_RESPONSE,message:{requestId:e.message.requestId,statuses:o,workerIndex:c,isMainThread:l}};u!==void 0&&threads.sendToThread(u,d)?_s.trace(`Sent component status response directly to thread ${u}`):(u===void 0?_s.debug("No originator threadId, falling back to broadcast"):_s.warn(`Failed to send direct response to thread ${u}, falling back to broadcast`),await s(d))}catch(t){_s.error("Error handling component status request:",t)}}a(rle,"componentStatusRequestHandler");$q.exports=Zce});var ls=M((Hxe,Kq)=>{"use strict";var xxe=Q(),rC=ae(),nle=(H(),D(W)),{ITC_ERRORS:Yp}=Jr(),{parentPort:Bxe,threadId:sle,isMainThread:ile,workerData:Fxe}=require("worker_threads"),{onMessageFromWorkers:ole,broadcast:kxe,broadcastWithAcknowledgement:ale}=tt();Kq.exports={sendItcEvent:cle,validateEvent:Vq,SchemaEventMsg:lle,UserEventMsg:ule};var wS;ole(async(e,t)=>{wS=wS||Kp(),Vq(e),wS[e.type]&&await wS[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function cle(e){return!ile&&e.message&&(e.message.originator=sle),ale(e)}a(cle,"sendItcEvent");function Vq(e){if(typeof e!="object")return Yp.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||rC.isEmpty(e.type))return Yp.MISSING_TYPE;if(!e.hasOwnProperty("message")||rC.isEmpty(e.message))return Yp.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||rC.isEmpty(e.message.originator))return Yp.MISSING_ORIGIN;if(nle.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Yp.INVALID_EVENT(e.type)}a(Vq,"validateEvent");function lle(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(lle,"SchemaEventMsg");function ule(e){this.originator=e}a(ule,"UserEventMsg")});var Xo=M(($xe,zq)=>{"use strict";var Yq=(H(),D(W)),qxe=ae(),NS=Q(),Wq=UB(),Ld,{sendItcEvent:jq}=ls();function dle(e){try{NS.debug("signalSchemaChange called with message:",e),Ld=Ld||Kp();let t=new Wq(Yq.ITC_EVENT_TYPES.SCHEMA,e);return Ld.schema(t),jq(t)}catch(t){NS.error(t)}}a(dle,"signalSchemaChange");function fle(e){try{NS.trace("signalUserChange called with message:",e),Ld=Ld||Kp();let t=new Wq(Yq.ITC_EVENT_TYPES.USER,e);return Ld.user(t),jq(t)}catch(t){NS.error(t)}}a(fle,"signalUserChange");zq.exports={signalSchemaChange:dle,signalUserChange:fle}});function Wp(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 Jq(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,jp=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(Wp,"appendHeader");a(Jq,"mergeHeaders")});function CS(e,t,r=ple){let n;return function(...i){return n?n.length*nC>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();nC=(nC*4+c-i)/5;let l=n.shift();if(l){let{args:u,fn:d}=l;d(),s(c,u)}else n=null})}}var Zq,mle,ple,Qq,hle,sC,Xq,nC,iC=se(()=>{Zq=b(ir()),mle=3e3,ple=2e4,Qq=0,hle=3e4,sC=3e3,Xq=performance.now()+sC,nC=0;a(CS,"throttle");setInterval(()=>{let e=performance.now();e-Xq-sC>mle&&Qq+hle<e&&(Zq.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"),Qq=e),Xq=e},sC).unref()});var u$={};ye(u$,{EVICTED:()=>Tl,INVALIDATED:()=>kn,coerceType:()=>PS,makeTable:()=>LS});function LS(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=NI(i,n,l),w,I,G={},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&&(G=K);let Y,le=[],fe=[],te=1,Se=2,Ne={},Ke={},$e=864e5,Ir=0,sr,zr,xr,Du=!1,Zc,Ft,Ps,Ga=ql.get(x.REPLICATION_DATABASES);if(Array.isArray(Ga)){for(let K of Ga)if(K.name===c&&K.replicateTo>=0){Ps=K.replicateTo;break}}let h_=i.getRange({start:!1,end:!1}).constructor,mm=10,E_=6;_&&gm(),Ym(i.env.path,K=>{if(I)return $a(K)});class pm extends Pl{static{a(this,"Updatable")}getUpdatedTime(){return Za.get(this.getRecord())?.version}getExpiresAt(){return Za.get(this.getRecord())?.expiresAt}addTo(g,T){if(typeof T=="number"||typeof T=="bigint")this.set(g,new Ap(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 Zt{#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 j of A){if(U?.source===j)break;$.push(j[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,j=N.table?Me[c][N.table]:ve;if(c===Rm&&(N.table===Fu.ROLE_TABLE_NAME||N.table===Fu.USER_TABLE_NAME)&&(v=!0),N.id===void 0&&(N.id=$[j.primaryKey],N.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(N));N.source=g;let J={residencyId:el(N.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:N.nodeId,async:!0},F=N.id,he=await j.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,Gl.getWorkerIndex)(),L):(0,Gl.getWorkerIndex)()===0,j=N&&$&&await g.subscribe?.(L);if(j){let J;for await(let F of j)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 de=It(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"}),Jp.signalSchemaChange(new Qp.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=de),v&&de&&!de?.waitingForUserChange&&(de.then(()=>Jp.signalUserChange(new Qp.UserEventMsg(process.pid))),de.waitingForUserChange=!0),F.onCommit&&(de?de.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){Gi(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 Bo(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 ft.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=G?.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&&(!Nle(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 j of i.getKeys({start:L,limit:1,reverse:!0}))A=j;U=B;for(let j of i.getKeys({start:L+1,end:B,limit:1}))U=j;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 j=i.getEntry(Symbol.for("id_allocation"));return(j?.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,...j.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,$a()}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,gm(),ve.audit=!0)}static coerceId(g){return g===""?null:PS(g,G)}static async dropTable(){delete Me[c][s];for(let g of i.getRange({versions:!0,snapshot:!1,lazy:!0}))g.metadataFlags&Xr&&g.value&&Ja(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(),aC.default.unlinkSync(i.env.path);Jp.signalSchemaChange(new Qp.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(hm(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);Gi(B);let v=!0;return g.checkPermission&&(v=this.allowRead(C.user,g)),Gs(Gs(v,A=>{if(!A)throw new ft.AccessViolation(C.user);let U=!0;return Bo(B,C,{transaction:O,ensureLoaded:U},!1,N=>{if(C.onlyIfCached){if(!N?.value)throw new ft.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?sd(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=vn(g,T);if(C?.read){if(C.isSuperUser)return!0;let P=C.attribute_permissions,O=T?.select;if(P?.length>0||Du&&O){if(T||(T={}),O){let B=Array.isArray(O)?O:[O],v=P?.length>0&&oC(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=vn(g,C);if(P?.update){let O=P.attribute_permissions;if(O?.length>0){let B=oC(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 qa(this.getContext())}}allowCreate(g,T,C){if(this.isCollection){let P=vn(g,C);if(P?.insert){let O=P.attribute_permissions;if(O?.length>0){let B=oC(O,"insert");for(let v in T)if(!B[v])return!1;return qa(this.getContext())}else return qa(this.getContext())}}else return this.allowUpdate(g,{})}allowDelete(g,T){return vn(g,T)?.delete&&qa(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 ft.AccessViolation(B.user);return Gs(i.get(Ls(g)),N=>{let L=new pm(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===t$?this.set(g,(+this.getProperty(g)||0)+T):(this.#s||this.update(),this.set(g,new Ap(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 ft.AccessViolation(C.user);this._writeInvalidate(g?Ls(g):this.getId())})}_writeInvalidate(g,T,C){let P=this.getContext();Gi(g),Br(this.getContext()).addWrite({key:g,store:i,invalidated:!0,entry:this.#r,before:Ne.invalidate?.bind(this,P,g),beforeIntermediate:xu(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();Gi(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=Va(this.getResidency(T.value,C)),O;if(P){if(!P.includes(server.hostname))return!1;O=el(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,Tl,null,null,null,!0)}return i.ifVersion(g,C,()=>{vu(g,T,null)}),Sl(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 ft.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 ft.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 ft.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);Gi(g);let v=this.#r??i.getEntry(g);this.#s=C?t$:ble;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,Ll(this)):null,"writeToSources"),U={key:g,store:i,entry:v,nodeName:O?.nodeName,validate:a(N=>{T||(T=this.#t),C||T&&eS(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=Ll(T))):B.removeWrite(U)},"validate"),before:A(Ne),beforeIntermediate:xu(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 j=L?.value,J;this.#s=0;let F=!1,he=Fr(N,L,P?.nodeId),de,_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=wt(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),de=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=W_(J??T,Te,C),!J)return me(!1)}}else{if(C)return me(!1);J=W_(J??T,j,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=Ll(j,J??T):(this.#e=j,ge=Ll(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=Va(ve.getResidency(ge,O));if(ie&&!ie.includes(server.hostname))if(de??=ge,F=!0,ve.getResidencyById)ge=void 0;else{ge=null;for(let Ce in r)ge||(ge={}),ge[Ce]=de[Ce]}re=el(ie)}C||(de=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""}})()),vu(g,j,ge),me(!0),O.expiresAt&&$a();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?de:de??T)}a(me,"writeCommit")},"commit")};B.addWrite(U)}async delete(g){if(hm(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 ft.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());Gi(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)&&(vu(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"),_||$a()):Sl(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 ft.AccessViolation(T.user);T&&(T.lastModified=Sle);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?G:zi(S,Ce);if(Be)(Be.type||OI[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,ft.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,Et;if(He.comparator==="gt"||He.comparator==="greater_than"||He.comparator==="ge"||He.comparator==="greater_than_equal"?(Te=ie,Et=He):(Te=He,Et=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 Ot=Et.comparator==="ge"||Et.comparator==="greater_than_equal",Pt=Te.comparator==="le"||Te.comparator==="less_than_equal";ie.comparator=(Ot?"ge":"gt")+(Pt?"le":"lt"),ie.value=[Et.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"?Ele(oe,Og(ve)):oe}a(U,"orderConditions");function N(oe,ge){return Array.isArray(oe)?oe.map(me=>PS(me,ge)):PS(oe,ge)}a(N,"coerceTypedValues");let L=g.operator;(P.length>0||L)&&(P=A(P,L));let $=typeof g.sort=="object"&&g.sort,j;if($&&L!=="or"){let oe=$.attribute;if(oe==null)throw new ft.ClientError("Sort requires an attribute");if(B=P.find(ge=>td(ge.attribute)===td(oe)),!B){let ge=zi(S,oe);if(!ge)throw(0,ft.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,ft.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&&(j={dbOrderedAttribute:$.attribute,attribute:$.next.attribute,descending:$.next.descending,next:$.next.next}):(B&&P.splice(P.indexOf(B),1),j=$));let J=g.select;if(P.length===0&&(P=[{attribute:t,comparator:"greater_than",value:!0}]),g.explain)return{conditions:P,operator:L,postOrdering:j,selectApplied:!!J};let F=C.useReadTxn(),he=PI(P,L,ve,F,g,T,(oe,ge)=>_m(oe,J,T,F,ge),v),de=g.ensureLoaded!==!1,_e=ve.transformEntryForSelect(J,T,F,v,de,!0),re=ve.transformToOrderedSelect(he,J,j,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 h_;if(C){g=_m(g,T,P,O,null);let A;v.iterate=function(){let N,L=g[Symbol.asyncIterator]?g[Symbol.asyncIterator]():g[Symbol.iterator](),$,j=C.dbOrderedAttribute,J,F,he=!0;function de(re){let oe=re.next&&de(re.next),ge=re.descending;return P.sort=re,(me,ie)=>{let Ce=Mu(me,re.attribute,P),Be=Mu(ie,re.attribute,P),He=ge?(0,$l.compareKeys)(Be,Ce):(0,$l.compareKeys)(Ce,Be);return He===0?oe?.(me,ie)||0:He}}a(de,"createComparator");let _e=de(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),j){let ge=Mu(oe,j,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],j;if($.name===N.attribute[0]){for(j=$.sort||($.sort={});j.next;)j=j.next;j.attribute=N.attribute.slice(1),j.descending=N.descending}else $===N.attribute[0]&&(T[L]=j={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 Ec.SKIP;if(N=Bo(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|Tl)||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?Ec.SKIP:L;if(g&&!(g[0]==="*"&&g.length===1)){let $,j=a((F,he)=>{let de;typeof F=="object"?de=F.name:de=F;let _e=xr?.[de],re;if(_e){let oe=P?.[de];if(oe)if(oe.hasMappings){let me=_e.from?L[_e.from]:td(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,de);if(me&&typeof me=="object"){let ie=_e.definition?.tableClass||ve;A||(A={});let Ce=A[de]||(A[de]=ie.transformEntryForSelect(de===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(Ot=>{for(;!Ot.done;){if(Ot?.then)return Ot.then(Te);Be.push(Ot.value),Ot=He.next()}he(Be,de)},"nextValue"),Et=Te(He.next());Et&&($||($=[]),$.push(Et));return}else if(me=Ce.call(this,me),me?.then){$||($=[]),$.push(me.then(Be=>he(Be,de)));return}}he(me,de)},"handleResolvedValue");re?.then?($||($=[]),$.push(re.then(ge))):ge(re);return}else re=L[de],re&&typeof re=="object"&&de!==F&&(re=ve.transformEntryForSelect(F.select||F,T,C,null)({value:re}));he(re,de)},"selectAttribute"),J;if(typeof g=="string")j(g,F=>{J=F});else if(Array.isArray(g))if(g.asArray)J=[],g.forEach((F,he)=>{F==="*"?g[he]=L:j(F,de=>J[he]=de)});else{J={};let F=g.forceNulls;for(let he of g)if(he==="*")for(let de in L)J[de]=L[de];else j(he,(de,_e)=>{de===void 0&&F&&(de=null),J[_e]=de})}else throw new ft.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=BI(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 j={id:v,localTime:U,value:L,version:A.version,type:$,beginTxn:N};C?C.push(j):(c!=="system"&&Ye(A.size??1,"db-message",s,null),this.send(j))}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 ft.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 $=wt(L);if($.tableId!==n)continue;let j=$.recordId;if(v==null||i$(v,j)){let J=$.getValue(i,T,N);if(B({id:j,localTime:N,value:J,version:$.version,type:$.type,size:$.size}),P.queue?.length>n$&&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 j=wt($);if(j.tableId!==n)continue;let J=j.recordId;if(v==null||i$(v,J)){let F=j.getValue(i,T,L);if(N.push({id:J,localTime:L,value:F,version:j.version,type:j.type}),--A<=0)break}}catch(j){Fe.default.error("Error getting history entry",L,j)}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:j,size:J}of i.getRange({start:v??!1,end:v==null?void 0:[v,$l.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(L&&(B({id:N,localTime:j,value:L,version:$,type:"put",size:J}),P.queue?.length>n$&&await P.waitForDrain()===!1))return}}else{A&&!U&&(U=0);let N=this.#r?.localTime;if(N===wI&&(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 j=l.get($);if(j){g.omitCurrent=!0;let J=wt(j),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 j=L.length;j>0;)B(L[--j]);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"&&Ye(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 ft.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&&Gi(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:xu(T,Ke.publish?.bind(this,O,g,T)),commit:a((B,v,A)=>{v===void 0&&R&&!_&&$a(),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 Ds)){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 ft.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 ft.ClientError("Attribute name is required");if(C.name.match(/[`/]/))throw new ft.ClientError("Attribute names cannot include backticks or forward slashes");_le(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=aC.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 hc(),!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 hc();let L=U*2,$=(v+N)/L,j=Math.pow((v-N+1)/U/2,2)+$*(1-$)/L,J=Math.max(Math.sqrt(j)*T,1),F=Math.round($*T),he=Math.max(F-1.96*J,v+N),de=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(de)]}}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&&(G=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)"),Du=!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?ed({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(j=>{let J=P.tableClass.primaryStore[A?"getEntry":"get"](j,{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(j=>j.filter(o$)):$.filter(o$):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}}Ip(this,this),Ip(pm,this,!0);for(let g of S){let T=g.name;g.resolve&&(Object.defineProperty(i.encoder.structPrototype,T,{get(){return g.resolve(this,nd.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=zi(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 hc(),wt(O).tableId===n&&(C=pg(l,P,O));if(T)for(let P of i.getRange({start:0,versions:!0})){let{key:O,value:B,localTime:v}=P;await hc(),B===null&&v<g&&(C=Sl(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 hc();let O=wt(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 hc();let B=l.get(P);if(B){let v=wt(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 __=CS(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 ft.ServerError("Service unavailable, exceeded request queue limit for resolving cache record",503)});ve.updatedAttributes();let sA=ve.prototype;return h&&ve.setTTLExpiration(h/1e3),z&&g_(),ve;function vu(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,zp.getIndexedValues)(A,N),$=(0,zp.getIndexedValues)(U,N);if($?.length>0){let j=new Set($);if(L=L?L.filter(J=>{if(j.has(J))j.delete(J);else return!0}):[],$=Array.from(j),($.length>0||L.length>0)&&e$){let J=$.concat(L).map(F=>({key:F,value:K}));O.prefetch(J,s$)}for(let J=0,F=$.length;J<F;J++)O.remove($[J],K)}else L?.length>0&&e$&&O.prefetch(L.map(j=>({key:j,value:K})),s$);if(L)for(let j=0,J=L.length;j<J;j++)O.put(L[j],K)}return C}a(vu,"updateIndices");function Gi(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>r$)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,$l.writeKey)(K,Ale,0)>r$)throw new Error("Primary key size is too large: "+K.length);return!0}a(Gi,"checkValidId");function Ls(K){return typeof K=="object"&&K?K.id:K}a(Ls,"requestTargetToId");function hm(K){return typeof K=="object"&&K&&K.isCollection}a(hm,"isSearchTarget");function Em(K){}a(Em,"isRequestTarget");function Bo(K,g,T,C,P){if(ve.getResidencyById&&T.ensureLoaded&&g?.replicateFrom!==!1){let B=Va(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")&&(l$.default.trace?.("Recording db-read action for",`${c}.${s}`),Ye(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()})):(le.push(K),fe.push(U),le.length>E_&&(te--,A()));function A(){if(le.length>0){let N=fe;i.prefetch(le,()=>{te===-1?A():te++;for(let L of N)L()}),le=[],fe=[],Se>2&&Se--}else te=Se,Se<mm&&Se++}a(A,"prefetch");function U(){try{B(O())}catch(N){v(N)}}a(U,"load")})}a(Bo,"loadLocalRecord");function vn(K,g){let T=g?.checkPermission;if(typeof T!="object"){if(!K?.role)return;T=K.role.permission}if(T.super_user)return Ile;let C=T[c],P,O=C?.tables;if(O)return O[s];if(c==="data"&&(P=T[s])&&!P.tables)return P}a(vn,"getTablePermissions");function pn(K,g,T,C){if(I){let P=!1;if(T.noCache?P=!0:(g?(!g.value||g.metadataFlags&(kn|Tl)||g.expiresAt!=null&&g.expiresAt<Date.now())&&(P=!0):P=!0,en(!P,"cache-hit",s)),P){let O=Uu(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 ft.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 V_}a(Br,"txnForContext");function Mu(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(Mu,"getAttributeValue");function _m(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 Ec.SKIP;for(let $=0;$<O;$++)if(!v?.includes($)&&!P[$](L,U))return Ec.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 Ec.SKIP;for(let L=0;L<O;L++){let j=P[L].idFilter;if(j){if(!j(N))return Ec.SKIP;v||(v=[]),v.push(L)}}return Bo(N,T,B,!1,A)});return Array.isArray(K)&&(U=U.filter(N=>N!==Ec.SKIP)),U.hasEntries=!0,U}return K}a(_m,"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=wt(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 Uu(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|Tl)?O(Uu(K,i.getEntry(K),T)):O(N)}))return new Promise(N=>{O=N,B=setTimeout(()=>{i.unlock(K,P)},Rle)});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(It(A,async j=>{let J=performance.now(),F,he,de;try{F=await __(K,A,g),de=C&kn;let re=A.lastModified||de&&P;re||(re=(0,zp.getNextMonotonicTime)()),he=de||re>P||!v;let oe=performance.now()-J;if(Ye(oe,"cache-resolution",s,null,"success"),U&&Wp(U,"Server-Timing",`cache-resolve;dur=${oe.toFixed(2)}`,!0),j.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 ft.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;Ye(oe,"cache-resolution",s,null,"fail"),U&&Wp(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:xu(F),commit:a((re,oe)=>{if(oe?.version!==P)return;let ge=vu(K,v,F);if(F){Ke.put?.(A,K,F),oe&&(T.previousResidency=ve.getResidencyRecord(oe.residencyId));let me,ie=!1,Ce,Be=Va(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=el(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",!!de,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",!!de):Sl(i,oe,P))},"commit")})}),()=>{i.unlock(K,P)},j=>{i.unlock(K,P),$&&Fe.default.error?.("Error committing cache update",j)})})}a(Uu,"getFromSource");function qa(K){if(!K||K.user?.role?.permission?.super_user)return!0;if(K.replicateTo)throw new ft.ClientError("Can not specify replication parameters without super user permissions",403);if(K.replicatedConfirmation)throw new ft.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}a(qa,"checkContextPermissions");function $a(K){let g=!1;if(K&&(K-Ir>1&&(g=!0),Ir=K),!($e===sr&&!g)&&(sr=$e,(0,Gl.getWorkerIndex)()===(0,Gl.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)*(ql.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 j(J,F,he,de){let _e=J+$-Date.now();if(_e<0)return!0;if(Ir){let re=i.lastSize;return he&Xr&&cl(de,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(j,"shouldEvict");try{let J=0;for(let F of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:he,value:de,version:_e,expiresAt:re,metadataFlags:oe}=F,ge;de===null&&!_&&_e+yle<Date.now()?ge=Sl(i,F,_e):re!=null&&j(re,_e,oe,de)&&(ge=ve.evict(he,de,_e),J++),ge&&(await U[N],U[N]=ge.catch(me=>{Fe.default.error?.("Cleanup error",me)}),++N>=A&&(N=0)),await hc()}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($a,"scheduleCleanup");function gm(){Y=l?.addDeleteRemovalCallback(n,i,(K,g)=>{i.remove(K,g)})}a(gm,"addDeleteRemoval");function g_(){(0,Gl.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 hc()}}catch(K){Fe.default.error?.("Error in evicting old records",K)}finally{Zc=!1}}},Tle).unref()}a(g_,"runRecordExpirationEviction");function Va(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(Va,"residencyFromFunction");function el(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(el,"getResidencyId");function xu(K,g){let T=JA(K,i.rootStore);if(T){let C=g;return C?async()=>{await C(),await T}:()=>T}return g}a(xu,"preCommitBlobsForRecordBefore")}function oC(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 s$(){}function PS(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 OS(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return OS(+e);case"Float":return e==="null"?null:OS(+e);case"BigInt":return e==="null"?null:BigInt(e);case"Boolean":return(0,Dd.autoCastBooleanStrict)(e);case"Date":if(isNaN(e)){if(e==="null")return null;wle.test(e)||(e+="Z");let n=new Date(e);return OS(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,Dd.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function OS(e){if(isNaN(e))throw new SyntaxError;return e}function i$(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 o$(e){return e!=null}function qs(e){try{return JSON.stringify(e)}catch{return e}}function Nle(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var Ec,zp,a$,c$,ql,ft,Jp,Qp,Fe,$l,Gl,Dd,aC,l$,Ele,_le,gle,Sle,Tle,yle,e$,Rle,t$,ble,kn,Tl,Ale,r$,n$,Ile,d0e,wle,hc,Dg=se(()=>{H();Ec=require("lmdb"),zp=b(xn()),a$=b(require("lodash")),c$=b(vm());Ji();Um();ql=b(ce());FI();ft=b(Ee()),Jp=b(Xo()),Qp=b(ls());Oe();Lg();Fe=b(ir());Yw();ja();$l=require("ordered-binary"),Gl=b(tt());Vi();Dd=b(ae());hl();is();j_();jp();aC=b(require("node:fs"));ss();ug();l$=b(Q());iC();({sortBy:Ele}=a$.default),{validateAttribute:_le}=c$.default,gle=new Uint8Array(9);gle[8]=192;Sle=1/0,Tle=6e4,yle=864e5;ql.initSync();e$=ql.get(x.STORAGE_PREFETCHWRITES),Rle=1e4,t$=1,ble=2,kn=1,Tl=8,Ale=Buffer.allocUnsafeSlow(8192),r$=1978,n$=100,Ile={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},d0e=(0,Dd.convertToMS)(ql.get(x.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(LS,"makeTable");a(oC,"attributesAsObject");a(s$,"noop");wle=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(PS,"coerceType");a(OS,"rejectNaN");a(i$,"isDescendantId");hc=a(()=>new Promise(setImmediate),"rest");a(Gs,"when");a(o$,"exists");a(qs,"stringify");a(Nle,"hasOtherProcesses")});function DS(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 vS(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 d$=se(()=>{a(DS,"euclideanDistance");a(vS,"cosineDistance")});var f$,m$,Md,uo,vd,Cle,Ole,MS,p$=se(()=>{d$();f$=require("msgpackr"),m$=b(ir()),Md=b(Ee()),uo=(0,m$.loggerWithTag)("HNSW"),vd=Symbol.for("entryPoint"),Cle=Symbol.for("key"),Ole=10,MS=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=f$.FLOAT32_OPTIONS.ALWAYS),this.distance=r?.distance==="euclidean"?DS:vS,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"?[Cle,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(vd);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);uo.debug?.("setting entry point to",i),this.indexStore.put(vd,i);return}let m=c.level??Math.min(Math.floor(-Math.log(Math.random())*this.mL),Ole),p=f.level;if(m>=p){if(typeof i!="number")throw new Error("Invalid nodeId: "+i);uo.debug?.("setting entry point to",i),this.indexStore.put(vd,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&&uo.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 G=[];if(this.optimizeRouting){let k=!1,z=I[E],Y=1+this.optimizeRouting*(1+.5*S/this.M);for(let le=0;le<z?.length;le++){let{id:fe,distance:te}=z[le],Se=1+this.optimizeRouting*(1+.5*le/this.M);for(let Ne=0;Ne<R.length;Ne++){let{id:Ke,distance:$e}=R[Ne];if(Ke===fe){w*Y>$e+te?k=!0:te*Se>w+$e&&(G.push({fromId:Ke,toId:y}),G.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 G){let Y=d(k);Y||(Y=d(k,this.indexStore.get(k)));for(let le=0;le<Y[E].length;le++)if(Y[E][le].id===z){Object.isFrozen(Y[E])&&(Y[E]=Y[E].slice()),Y[E].splice(le,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(vd);else{if(typeof l!="number")throw new Error("Invalid nodeId: "+l);uo.debug?.("setting entry point to",l),this.indexStore.put(vd,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&&(uo.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(vd);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 Md.ClientError(`Can not use "${i}" comparator with HNSW`)}if(n)throw new Md.ClientError("Can not use descending sort order with HNSW");let c;if(s==="cosine")c=vS;else if(s==="euclidean")c=DS;else{if(s)throw new Md.ClientError("Unknown distance function");c=this.distance}if(!t)throw new Md.ClientError("A target vector must be provided for an HNSW query");if(!Array.isArray(t))throw new Md.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){uo.info?.("could not find neighbor node",o);continue}o[n]?.find(({id:l})=>l==t)||uo.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)){uo.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&&uo.info?.("should not remove last connection",t,n))}}r[s].find(({id:l})=>l===n)?uo.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"?DS:vS);let c=o(s.target,t);return i.set(n,c),c}return t}}});var cC,h$=se(()=>{p$();cC={HNSW:MS}});var pt={};ye(pt,{NON_REPLICATING_SYSTEM_TABLES:()=>US,database:()=>_d,databaseEnvs:()=>na,databases:()=>Me,dropDatabase:()=>Qw,dropTableMeta:()=>Ule,getDatabases:()=>ut,getDefaultCompression:()=>qS,getTables:()=>Lle,onRemovedDB:()=>sh,onUpdatedTable:()=>Vl,readMetaDb:()=>Xp,resetDatabases:()=>kd,table:()=>ze,tables:()=>Rn});function nh(e,t){let r=HS.OpenDBIObject??HS.default.OpenDBIObject;return new r(e,t)}function Lle(){return kS||ut(),Rn||{}}function ut(){if(kS)return Me;kS=!0,Bd=new Map;let e=(0,er.getHdbBasePath)()&&(0,Ht.join)((0,er.getHdbBasePath)(),nl),t=(0,er.get)(x.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,er.get)(x.STORAGE_PATH)||e&&((0,gs.existsSync)(e)?e:(0,Ht.join)((0,er.getHdbBasePath)(),N_)),!!e){if((0,gs.existsSync)(e))for(let r of(0,gs.readdirSync)(e,{withFileTypes:!0})){let n=(0,Ht.basename)(r.name,".mdb");r.isFile()&&(0,Ht.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&Xp((0,Ht.join)(e,r.name),null,n)}if((0,gs.existsSync)((0,xd.getBaseSchemaPath)())){for(let r of(0,gs.readdirSync)((0,xd.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,Ht.join)((0,xd.getBaseSchemaPath)(),r.name),s=(0,Ht.join)((0,xd.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,gs.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,Ht.extname)(i.name).toLowerCase()===".mdb"){let o=(0,Ht.join)(s,i.name);Xp((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,gs.existsSync)(s))for(let o of(0,gs.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,Ht.extname)(o.name).toLowerCase()===".mdb"&&Xp((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,gs.existsSync)(l)&&Xp(l,o,r,null,!0)}}for(let r in Me){let n=Bd.get(r);if(n){let s=Me[r];r.includes("delete")&&Or.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(Or.trace(`delete table class ${i}`),delete s[i])}else if(delete Me[r],r==="data"){for(let s in Rn)delete Rn[s];delete Rn[GS]}}if((0,er.get)(x.ANALYTICS_REPLICATE)===!1?US.includes("hdb_analytics")||US.push("hdb_analytics"):(Me.system?.hdb_analytics?.enableAuditing(),Me.system?.hdb_analytics_hostname?.enableAuditing()),Me.system)for(let r of US)Me.system[r]&&(Me.system[r].replicate=!1);return Bd=null,Me}}function kd(){kS=!1;for(let[,e]of na)e.needsDeletion=!0;ut();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],eh.forEach(i=>i(t.databaseName));break}}return Me}function Xp(e,t,r=dC,n,s){let i=new lC.default(e,!1);try{let o=na.get(e);o?o.needsDeletion=!1:(o=(0,Fd.open)(i),na.set(e,o));let c=new nh(!1),l=o.dbisDb||(o.dbisDb=o.openDB(xS.INTERNAL_DBIS_NAME,c)),u=o.auditStore;u||(n?(0,gs.existsSync)(n)&&(i.path=n,u=(0,Fd.open)(i),u.isLegacy=!0):u=mg(o));let d=T$(r),f=d[GS],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(!_){Or.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,G=typeof _.audit=="boolean"?_.audit:(0,er.get)(x.LOGGING_AUDITLOG),X=_.trackDeletes,q=_.expiration,k=_.eviction,z=_.sealed,Y=_.splitSegments,le=_.replicate;if(R)S=R.indices,y=R.attributes,R.schemaVersion++;else{w=_.tableId,w?w>=(l.get(Ud)||0)&&(l.putSync(Ud,w+1),Or.info(`Updating next table id (it was out of sync) to ${w+1} for ${p}`)):(_.tableId=w=l.get(Ud),w||(w=1),Or.debug("Table {tableName} missing an id, assigning {tableId}"),l.putSync(Ud,w+1),l.putSync(_.key,_));let te=new nh(!_.is_hash_attribute,_.is_hash_attribute);if(te.compression=_.compression,te.compression){let Se=(0,er.get)(x.STORAGE_COMPRESSION_THRESHOLD)||S$;te.compression.threshold=Se}I=Ng(o.openDB(_.key,te),o),o.databaseName=r,I.tableId=w}let fe;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=R$(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),fe=!0}}catch(Se){Or.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){Or.error("Unable to remove existing primary key attribute",te);continue}te.indexed&&(y.splice(y.indexOf(te),1),fe=!0)}if(R)fe&&(R.schemaVersion++,R.updatedAttributes());else{R=y$(d,p,LS({primaryStore:I,auditStore:u,audit:G,sealed:z,splitSegments:Y,replicate:le,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 Zp)te(R)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function T$(e){let t=Me[e];if(t||(e==="data"?t=Me[e]=Rn:e==="system"?Object.defineProperty(Me,"system",{value:t=Object.create(null),configurable:!0}):t=Me[e]=Object.create(null)),Bd&&!Bd.has(e)){let r=new Set;t[GS]=r,Bd.set(e,r)}return t}function y$(e,t,r){return e[t]=r,r}function _d({database:e,table:t}){e||(e=dC),ut();let r=T$(e),n=(0,Ht.join)((0,er.getHdbBasePath)(),nl),s=(0,er.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,er.get)(x.STORAGE_PATH)||((0,gs.existsSync)(n)?n:(0,Ht.join)((0,er.getHdbBasePath)(),N_));let o=(0,Ht.join)(n,(i?t:e)+".mdb"),c=na.get(o);if(!c||c.status==="closed"){let l=new lC.default(o,!1);c=(0,Fd.open)(l),na.set(o,c)}return c.auditStore||(c.auditStore=mg(c)),c}async function Qw(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 th.remove(r.path));if(r||(r=_d({database:e,table:null}),r.status==="open"&&(await r.close(),await th.remove(r.path))),e==="data"){for(let n in Rn)delete Rn[n];delete Rn[GS]}delete Me[e],eh.forEach(n=>n(e)),await zA(r)}function R$(e,t,r){let n=r.is_hash_attribute||r.indexed.type&&cC[r.indexed.type]?.useObjectStore,s=new nh(!n,n),i=t.openDB(e,s);if(r.indexed.type){let o=cC[r.indexed.type];o?i.customIndex=new o(i,r.indexed):Or.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=dC);let h=_d({database:r,table:t}),E=Me[r];Or.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 nh(!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,G;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=qS(),f&&(S.trackDeletes=!0),c=S.audit=typeof c=="boolean"?c:(0,er.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]),Or.trace(`${t} table loading, opening primary store`);let le=new nh(!1,!0);le.compression=S.compression;let fe=t+"/";if(y=h.dbisDb=h.openDB(xS.INTERNAL_DBIS_NAME,w),z(),y.get(fe))return G&&G(),kd(),ze(e);let te=Ng(h.openDB(fe,le),h);h.databaseName=r,te.tableId=y.get(Ud),Or.trace(`Assigning new table id ${te.tableId} for ${t}`),te.tableId||(te.tableId=1),y.put(Ud,te.tableId+1),S.tableId=te.tableId,_=y$(E,t,LS({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(fe,S)}let X=_.indices;y=y||(h.dbisDb=h.openDB(xS.INTERNAL_DBIS_NAME,w)),_.dbisDB=y;let q=[];for(let{key:Y,value:le}of y.getRange({start:!0})){let[fe,te]=Y.toString().split("/");if(te===""&&(te=le.name),te){if(fe!==t)continue}else continue;let Se=o.find(Ke=>Ke.name===te),Ne=!Se?.indexed&&le.indexed&&!le.isPrimaryKey;if((!Se||Ne)&&(z(),I=!0,Se||y.remove(Y),Ne)){let Ke=_.indices[fe];Ke&&q.push(Ke)}}let k=[];try{for(let Y of o||[]){if((Y.relationship||Y.computed)&&(I=!0,Y.relationship))continue;let le=t+"/"+(Y.name||"");Object.defineProperty(Y,"key",{value:le,configurable:!0});let fe=y.get(le);if(Y.isPrimaryKey){if(fe=fe||y.get(le=t+"/")||{},c!==void 0&&c!==_.audit||l!==void 0&&l!==_.sealed||d!==void 0&&d!==_.replicate||(+n||void 0)!==(+fe.expiration||void 0)||(+s||void 0)!==(+fe.eviction||void 0)||Y.type!==fe.type){let Se={...fe};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(le,Se)}continue}fe?.attribute&&!fe.name&&(fe.indexed=!0);let te=!fe||fe.type!==Y.type||JSON.stringify(fe.indexed)!==JSON.stringify(Y.indexed)||fe.nullable!==Y.nullable||fe.version!==Y.version||fe.enumerable!==Y.enumerable||JSON.stringify(fe.properties)!==JSON.stringify(Y.properties)||JSON.stringify(fe.elements)!==JSON.stringify(Y.elements);if(Y.indexed){let Se=R$(le,h,Y);(te||fe.indexingPID&&fe.indexingPID!==process.pid||fe.restartNumber<rh.workerData?.restartNumber)&&(I=!0,z(),fe=y.get(le),(te||fe.indexingPID&&fe.indexingPID!==process.pid||fe.restartNumber<rh.workerData?.restartNumber)&&(I=!0,Y.indexNulls===void 0&&(Y.indexNulls=!0),_.primaryStore.getStats().entryCount>0&&(Y.lastIndexedKey=fe?.lastIndexedKey??void 0,Y.indexingPID=process.pid,Se.isIndexing=!0,Object.defineProperty(Y,"dbi",{value:Se}),k.push(Y))),y.put(le,Y)),fe?.indexNulls&&Y.indexNulls===void 0&&(Y.indexNulls=!0),Se.indexNulls=Y.indexNulls,X[Y.name]=Se}else te&&(I=!0,z(),y.put(le,Y))}}finally{G&&G()}if(I&&(_.schemaVersion++,_.updatedAttributes()),Or.trace(`${t} table loading, running index`),k.length>0||q.length>0?_.indexingOperation=Mle(_,k,q):I&&BS.signalSchemaChange(new FS.SchemaEventMsg(process.pid,"schema-change",_.databaseName,_.tableName)),_.origin=p,I)for(let Y of Zp)Y(_,p!=="cluster");return(n||s||i)&&_.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Or.trace(`${t} table loaded`),_;function z(){G||h.transactionSync(()=>({then(Y){G=Y}}))}a(z,"startTxn")}async function Mle(e,t,r){try{Or.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await BS.signalSchemaChange(new FS.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,Fd.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,E$.getIndexedValues)(y,R.indexNulls);if(w)for(let I=0,G=w.length;I<G;I++)R.put(w[I],f)}catch(S){o[_]||(o[_]=!0,Or.error(`Error indexing attribute ${_}`,S))}}}),s.then(()=>d--,h=>{d--,Or.error(h)}),rh.workerData&&rh.workerData.restartNumber!==g$.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>Dle?await s:d>vle&&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 BS.signalSchemaChange(new FS.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Or.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Or.error("Error in indexing",n)}}function Ule({table:e,database:t}){let r=_d({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 Vl(e){return Zp.push(e),{remove(){let t=Zp.indexOf(e);t>-1&&Zp.splice(t,1)}}}function sh(e){return eh.push(e),{remove(){let t=eh.indexOf(e);t>-1&&eh.splice(t,1)}}}function qS(){let e=(0,er.get)(x.STORAGE_COMPRESSION),t=(0,er.get)(x.STORAGE_COMPRESSION_DICTIONARY),r=(0,er.get)(x.STORAGE_COMPRESSION_THRESHOLD)||S$,n={startingOffset:32};return t&&(n.dictionary=th.readFileSync(t)),r&&(n.threshold=r),e&&n}var er,xS,Fd,Ht,gs,xd,lC,th,uC,E$,BS,FS,rh,_$,g$,HS,Ple,Or,dC,GS,S$,US,Rn,Me,Ud,Zp,eh,kS,na,Bd,Dle,vle,Oe=se(()=>{er=b(ce()),xS=b(Qt()),Fd=require("lmdb"),Ht=require("path"),gs=require("fs"),xd=b(At());Dg();lC=b(lp());H();th=b(require("fs-extra")),uC=b(ai()),E$=b(xn()),BS=b(Xo()),FS=b(ls()),rh=require("worker_threads"),_$=b(Q()),g$=b(tt());Vi();hl();ss();h$();HS=b(cp()),{forComponent:Ple}=_$.default;a(nh,"OpenDBIObject");Or=Ple("storage"),dC="data",GS=Symbol("defined-tables"),S$=((0,er.get)(x.STORAGE_PAGESIZE)||4096)-60;(0,er.initSync)();US=["hdb_temp","hdb_certificate","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_info"],Rn=Object.create(null),Me=Object.create(null);(0,uC._assignPackageExport)("databases",Me);(0,uC._assignPackageExport)("tables",Rn);Ud=Symbol.for("next-table-id"),Zp=[],eh=[],na=new Map;a(Lle,"getTables");a(ut,"getDatabases");a(kd,"resetDatabases");a(Xp,"readMetaDb");a(T$,"ensureDB");a(y$,"setTable");a(_d,"database");a(Qw,"dropDatabase");a(R$,"openIndex");a(ze,"table");Dle=1e3,vle=10;a(Mle,"runIndexing");a(Ule,"dropTableMeta");a(Vl,"onUpdatedTable");a(sh,"onRemovedDB");a(qS,"getDefaultCompression")});var pC={};ye(pC,{loadGQLSchema:()=>Fle,start:()=>mC,startOnMainThread:()=>Ble});function mC({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 G=function(q){if(q.kind==="NonNullType"){let Y=G(q.type);return Y.nullable=!1,Y}if(q.kind==="ListType")return{type:"array",elements:G(q.type)};let z={type:q.name?.value};return Object.defineProperty(z,"location",{value:q.loc.startToken}),z};a(G,"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=G(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 le={};for(let fe of z.arguments||[])le[fe.name.value]=fe.value.value;k.indexed=le}else if(Y==="computed"){for(let le of z.arguments||[])if(le.name.value==="from"){let fe=le.value.value;k.computed={from:_(fe,le,X)},k.version==null&&(k.version=fe)}else le.name.value==="version"&&(k.version=le.value.value);k.computed=k.computed||!0}else if(Y==="relationship"){let le={};for(let fe of z.arguments)le[fe.name.value]=fe.value.value;k.relationship=le}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 le=k.authorizedRoles=[];for(let fe of z.arguments)fe.name.value==="role"&&le.push(fe.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):xle.includes(R.type)||(0,A$.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,fC.dirname)(n),R.tableClass):i.set((0,fC.dirname)(n)+"/"+(R.export.name||R.type),R.tableClass,R.export));function _(R,S,y){return new b$.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 fC,b$,A$,xle,Ble,Fle,I$=se(()=>{fC=require("path"),b$=require("node:vm");Oe();A$=b(tt());tc();xle=["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(mC,"start");Ble=mC,Fle=a(e=>mC({ensureTable:ze}).handleFile(e,null,null,new id),"loadGQLSchema")});var EC={};ye(EC,{start:()=>Wle});function kle(e){if(e.kind!==Ge.Kind.OPERATION_DEFINITION&&e.kind!==Ge.Kind.FRAGMENT_DEFINITION)throw new Vr(`Unexpected non-executable definition type ${e.kind}.`)}function w$(e){if(typeof e!="object"||e===null)throw new fo("Request body must be an object.");if(!("query"in e))throw new fo("Request body must contain a `query` field.");if(typeof e.query!="string")throw new fo("Request body `query` field must be a string.");if("variables"in e&&(typeof e.variables!="object"||e.variables===null))throw new fo("Request body `variables` field must be an object.");if("operationName"in e&&typeof e.operationName!="string")throw new fo("Request body `operationName` field must be a string.")}function hC(e){return parseInt(e.value,10)}function C$(e){return parseFloat(e.value)}function O$(e,t,r){let n=r.get(e.name.value);return P$(n)?L$(n,t):{attribute:t,value:n}}function P$(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}function L$(e,t){return t=typeof t=="string"?[t]:t,Object.entries(e).flatMap(([r,n])=>(t=[...t,r],P$(n)?L$(n,t):{attribute:t,value:n}))}function Hle(e,t,r){switch(t=[...t,e.name.value],e.value.kind){case Ge.Kind.NULL:return{attribute:t,value:null};case Ge.Kind.INT:return{attribute:t,value:hC(e.value)};case Ge.Kind.FLOAT:return{attribute:t,value:C$(e.value)};case Ge.Kind.BOOLEAN:case Ge.Kind.STRING:return{attribute:t,value:e.value.value};case Ge.Kind.VARIABLE:return O$(e.value,t,r);case Ge.Kind.OBJECT:return D$(e.value,t,r);case Ge.Kind.LIST:case Ge.Kind.ENUM:default:throw new Vr(`Value type, ${e.value.kind}, is not supported.`)}}function D$(e,t,r){return e.fields.flatMap(n=>Hle(n,t,r))}function Gle(e,t){switch(e.value.kind){case Ge.Kind.NULL:return{attribute:e.name.value,value:null};case Ge.Kind.INT:return{attribute:e.name.value,value:hC(e.value)};case Ge.Kind.FLOAT:return{attribute:e.name.value,value:C$(e.value)};case Ge.Kind.BOOLEAN:case Ge.Kind.STRING:return{attribute:e.name.value,value:e.value.value};case Ge.Kind.VARIABLE:return O$(e.value,e.name.value,t);case Ge.Kind.OBJECT:return D$(e.value,[e.name.value],t);case Ge.Kind.LIST:case Ge.Kind.ENUM:default:throw new Vr(`Argument type, ${e.value.kind}, is not supported.`)}}function qle(e,t){return e.flatMap(r=>Gle(r,t))}function $S(e,t){return e.selections.flatMap(r=>{switch(r.kind){case Ge.Kind.FIELD:return r;case Ge.Kind.FRAGMENT_SPREAD:{let n=r.name.value,s=t.get(n);if(s==null)throw new Vr(`Fragment \`${n}\` not found.`);return $S(s.selectionSet,t)}case Ge.Kind.INLINE_FRAGMENT:return $S(r.selectionSet,t)}})}function v$(e,t){return $S(e,t).map(r=>r.selectionSet?.selections.length>0?{name:r.name.value,select:v$(r.selectionSet,t)}:r.name.value)}async function $le(e,t,r,n){let s=xs.getMatch(e.name.value,"graphql");if(s===void 0)throw new Vr(`Resource \`${e.name.value}\` not found.`);let i=s.Resource,o={select:v$(e.selectionSet,r),conditions:qle(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 M$(e){switch(e.kind){case Ge.Kind.NULL:return null;case Ge.Kind.INT:return hC(e);case Ge.Kind.FLOAT:return parseFloat(e.value);case Ge.Kind.STRING:case Ge.Kind.BOOLEAN:return e.value;case Ge.Kind.OBJECT:return e.fields.reduce((t,r)=>({[r.name.value]:M$(r.value),...t}),{});case Ge.Kind.LIST:case Ge.Kind.ENUM:default:throw new Vr(`Value type, ${e.kind}, is not supported.`)}}function Vle(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=M$(n.defaultValue)),n.type.kind===Ge.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 Kle(e,t,r,n){if(e.operation===Ge.OperationTypeNode.SUBSCRIPTION)throw new Vr("Subscriptions are not supported.");if(e.operation===Ge.OperationTypeNode.MUTATION)throw new Vr("Mutations are not supported yet.");let s=Vle(e.variableDefinitions,t),i=await Promise.all($S(e.selectionSet,r).map(c=>$le(c,s,r,n))),o={data:{}};for(let[c,l]of i)o.data[c]=l;return o}async function N$({query:e,variables:t={},operationName:r},n){let s=Ge.parse(e),i=new Map,o=new Map;for(let u of s.definitions)if(kle(u),u.kind===Ge.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 Kle(c,t,o,n);return{status:200,headers:{"Content-Type":"application/graphql-response+json; charset=utf-8"},body:JSON.stringify(l)}}async function Yle(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 w$(r),N$(r,e)}case"POST":{let r=await $o(e.headers.get("content-type"),!0)(e._nodeRequest);return w$(r),N$(r,e)}default:throw new fo("Method Not Allowed",405,{Allow:"GET, POST"})}}function Wle(e){e.server.http(async(t,r)=>{if(!t.url.startsWith("/graphql"))return r(t);try{return await Yle(t)}catch(n){logger.error(n);let s=t.headers.get("accept")??"application/graphql-response+json";switch(s){case"application/json":{if(n instanceof fo)return{status:n.statusCode,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/json",...n.headers}};if(n instanceof Ge.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 fo)return{status:n.statusCode,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/graphql-response+json",...n.headers}};if(n instanceof Ge.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 Ge,Vr,fo,U$=se(()=>{Ge=b(require("graphql"));Vo();tc();a(kle,"assertExecutableDefinitionNode");a(w$,"assertRequestParams");a(hC,"processIntValueNode");a(C$,"processFloatValueNode");a(O$,"processVariableNode");a(P$,"isObject");a(L$,"transformObjectIntoQueryCondition");a(Hle,"processObjectFieldNode");a(D$,"processObjectValueNode");a(Gle,"processArgumentNode");a(qle,"buildConditionsQuery");a($S,"fillInFragments");a(v$,"buildSelectQuery");a($le,"processFieldNode");a(M$,"processConstValueNode");a(Vle,"resolveVariables");a(Kle,"executeOperation");a(N$,"resolver");Vr=class extends Error{static{a(this,"GraphQLQueryingError")}},fo=class extends Error{static{a(this,"HTTPError")}statusCode;headers;constructor(t,r=400,n={}){super(t),this.statusCode=r,this.headers=n}};a(Yle,"graphqlQueryingHandler");a(Wle,"start")});var G$=M((v0e,H$)=>{var Hd=require("validate.js"),B$=at(),Gd=(H(),D(W)),{handleHDBError:jle,hdbErrors:zle}=Ee(),{HDB_ERROR_MSGS:cr,HTTP_STATUS_CODES:Jle}=zle,_C=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),Qle={STRUCTURE_USER:"structure_user"},x$=Object.values(Gd.ROLE_TYPES_ENUM),Xle="attribute_permissions",Zle="attribute_name",{PERMS_CRUD_ENUM:qd}=Gd,eue=[Xle,...Object.values(qd)],F$=[qd.READ,qd.INSERT,qd.UPDATE],tue=[Zle,...F$];function rue(e){let t=_C();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,k$(e,t)}a(rue,"addRoleValidation");function nue(e){let t=_C();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,k$(e,t)}a(nue,"alterRoleValidation");function sue(e){let t=_C();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,B$.validateObject(e,t)}a(sue,"dropRoleValidation");var iue=["operation","role","id","permission","hdb_user","access"];function k$(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)iue.includes(n[o])||s.push(n[o]);s.length>0&&_r(cr.INVALID_ROLE_JSON_KEYS(s),r);let i=B$.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{_r(o,r)}),e.permission){let o=oue(e);o&&_r(o,r),x$.forEach(c=>{e.permission[c]&&!Hd.isBoolean(e.permission[c])&&_r(cr.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(x$.indexOf(o)<0){if(o===Qle.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]||_r(cr.SCHEMA_NOT_FOUND(f),r)}continue}_r(cr.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){_r(cr.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]){_r(cr.TABLE_NOT_FOUND(o,l),r);continue}if(Object.keys(u).forEach(d=>{eue.includes(d)||_r(cr.INVALID_PERM_KEY(d),r,o,l)}),Object.values(qd).forEach(d=>{Hd.isDefined(u[d])?Hd.isBoolean(u[d])||_r(cr.TABLE_PERM_NOT_BOOLEAN(d),r,o,l):_r(cr.TABLE_PERM_MISSING(d),r,o,l)}),u.attribute_permissions===void 0){_r(cr.ATTR_PERMS_ARRAY_MISSING,r,o,l);continue}else if(!(Array.isArray(u.attribute_permissions)||u.attribute_permissions===null)){_r(cr.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=>{!tue.includes(E)&&E!==qd.DELETE&&_r(cr.INVALID_ATTR_PERM_KEY(E),r,o,l)}),!Hd.isDefined(p.attribute_name)){_r(cr.ATTR_PERM_MISSING_NAME,r,o,l);continue}let h=p.attribute_name;if(!d.includes(h)){_r(cr.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,l);continue}F$.forEach(E=>{Hd.isDefined(p[E])?Hd.isBoolean(p[E])||_r(cr.ATTR_PERM_NOT_BOOLEAN(E,h),r,o,l):_r(cr.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}`;_r(cr.MISMATCHED_TABLE_ATTR_PERMS(m),r,o,l)}}}}return aue(r)}a(k$,"customValidate");H$.exports={addRoleValidation:rue,alterRoleValidation:nue,dropRoleValidation:sue};function oue(e){let{operation:t,permission:r}=e;if(t===Gd.OPERATIONS_ENUM.ADD_ROLE||t===Gd.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 cr.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?Gd.ROLE_TYPES_ENUM.SUPER_USER:Gd.ROLE_TYPES_ENUM.CLUSTER_USER;return cr.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(oue,"validateNoSUPerms");function aue(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:cr.ROLE_PERMS_ERROR,...e};return jle(new Error,n,Jle.BAD_REQUEST)}else return null}a(aue,"generateRolePermResponse");function _r(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(_r,"addPermError")});var oh=M((x0e,K$)=>{"use strict";var q$=_n(),$$=Sn(),cue=cc(),SC=G$(),TC=Xo(),U0e=require("uuid").v4,lue=require("util"),VS=(H(),D(W)),uue=ae(),yC=$$.searchByValue,due=$$.searchByHash,fue=lue.promisify(cue.delete),mue=di(),pue=md(),{hdbErrors:hue,handleHDBError:Kl}=Ee(),{HDB_ERROR_MSGS:V$,HTTP_STATUS_CODES:ih}=hue,{UserEventMsg:RC}=ls();K$.exports={addRole:Eue,alterRole:_ue,dropRole:gue,listRoles:Sue};function gC(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(gC,"scrubRoleDetails");async function Eue(e){let t=SC.addRoleValidation(e);if(t)throw t;e=gC(e);let r={schema:"system",table:"hdb_role",attribute:"role",value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await yC(r)||[])}catch(i){throw Kl(i)}if(n&&n.length>0)throw Kl(new Error,V$.ROLE_ALREADY_EXISTS(e.role),ih.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 q$.insert(s),TC.signalUserChange(new RC(process.pid)),e=gC(e),e}a(Eue,"addRole");async function _ue(e){let t=SC.alterRoleValidation(e);if(t)throw t;e=gC(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await q$.update(r)}catch(s){throw Kl(s)}if(n&&n?.message==="updated 0 of 1 records")throw Kl(new Error,"Invalid role id",ih.BAD_REQUEST,void 0,void 0,!0);return await TC.signalUserChange(new RC(process.pid)),e}a(_ue,"alterRole");async function gue(e){let t=SC.dropRoleValidation(e);if(t)throw Kl(new Error,t,ih.BAD_REQUEST,void 0,void 0,!0);let r=new pue(VS.SYSTEM_SCHEMA_NAME,VS.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await due(r));if(n.length===0)throw Kl(new Error,V$.ROLE_NOT_FOUND,ih.NOT_FOUND,void 0,void 0,!0);let s=new mue(VS.SYSTEM_SCHEMA_NAME,VS.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await yC(s)),o=!1;if(uue.isEmptyOrZeroLength(i)===!1){for(let l=0;l<i.length;l++)if(i[l].active===!0){o=!0;break}}if(o===!0)throw Kl(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,ih.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await fue(c),TC.signalUserChange(new RC(process.pid)),`${n[0].role} successfully deleted`}a(gue,"dropRole");async function Sue(){return yC({table:"hdb_role",schema:"system",hash_attribute:"id",attribute:"id",value:"*",get_attributes:["*"]})}a(Sue,"listRoles")});var bC={};ye(bC,{start:()=>j$,startOnMainThread:()=>Rue});function j$({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r){let n=(0,Y$.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(Tue.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 yue(i)}}}async function yue(e){let t=ut().system.hdb_role;for await(let r of t.search([{attribute:"role",value:e.role}])){let{__createdtime__:n,__updatedtime__:s,...i}=r;return(0,W$.isEqual)(i,e)?void 0:(e.id=r.id,(0,KS.alterRole)(e))}return(0,KS.addRole)(e)}var KS,Y$,W$,Tue,Rue,z$=se(()=>{Oe();KS=b(oh()),Y$=require("yaml"),W$=require("lodash"),Tue=["super_user","cluster_user","structure_user"];a(j$,"start");a(yue,"ensureRole");Rue=j$});async function YS(e){let t=(0,X$.pathToFileURL)(e).toString();if(bue)return ah||(ah=Aue(wue)),(await(await ah).import(t)).namespace;try{return await import(t)}catch(r){try{(await import("internal/util")).default.decorateErrorStack(r)}catch{}throw r}}async function Aue(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),ah=new Compartment({console,Math,Date,fetch:Iue,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,Q$.extname)(r)||(r+=".js"),r)},importHook:a(async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){s.Resource=Zt,s.tables=Rn,s.databases=Me}};let n=await(0,J$.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)},"importHook")}),ah}function Iue(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 wue(){return{Resource:Zt,tables:Rn}}var J$,Q$,X$,bue,ah,AC=se(()=>{Ji();Oe();J$=require("fs/promises"),Q$=require("path"),X$=require("url"),bue=!1;a(YS,"secureImport");a(Aue,"getCompartment");a(Iue,"secureOnlyFetch");a(wue,"getGlobalVars")});var IC={};ye(IC,{ResourceLoadError:()=>WS,handleApplication:()=>Nue,suppressHandleApplicationWarning:()=>Cue});function eV(e){return typeof e=="function"&&("get"in e||"put"in e||"post"in e||"delete"in e)}async function Nue(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 YS(r.absolutePath),s=(0,Z$.dirname)(r.urlPath).replace(/\\/g,"/").replace(/^\/$/,"");eV(n.default)&&(e.resources.set(s,n.default),e.logger.debug(`Registered root resource: ${s}`)),tV(e,n,s)}catch(n){throw new WS(r.absolutePath,n)}},"handleResourceEntry"))}function tV(e,t,r){for(let n in t){let s=t[n],i=`${r}/${n}`;eV(s)?(e.resources.set(i,s),e.logger.debug(`Registered resource: ${i}`)):typeof s=="object"&&tV(e,s,i)}}var Z$,WS,Cue,rV=se(()=>{AC();Z$=require("path");a(eV,"isResource");WS=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(Nue,"handleApplication");a(tV,"recurseForResources");Cue=!0});var NC={};ye(NC,{start:()=>Oue});function Oue({resources:e}){e.set("login",wC),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var wC,nV=se(()=>{Ji();a(Oue,"start");wC=class extends Zt{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 zS(e,t){let r={openapi:Pue,info:{title:"HarperDB HTTP REST interface",version:lV.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)jS[l.type]?o[l.name]=new OC(jS[l.type],l.type):l.properties?(o[l.name]=new dV(l.type),s(l)):l.elements?.properties&&(o[l.name]=new Mue(l.elements.type),s(l.elements)),l.nullable===!1&&c.push(l.name);r.components.schemas[i.type]=new cV(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:le,definition:fe,nullable:te}of l){let Se=fe??Y?.definition;Se&&s(Se),te===!1&&h.push(z),le?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 OC(jS[Y.type],Y.type)}:k==="Any"?m[z]={format:k}:m[z]=new OC(jS[k],k),p.push(new PC(z,"query",m[z]))}let E=Object.keys(m),_=new PC(f,"path",{type:"string",format:"ID"});_.required=!0,_.description="primary key of record";let R=new PC("property","path",{enum:E});R.required=!0,r.components.schemas[c]=new cV(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",G=typeof d.patch=="function",X=`/${o}/`;r.paths[X]||(r.paths[X]={}),S&&(r.paths[X].post=new Lue(c,n,{200:new $d({$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 sV(p,n,{200:new iV},"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 CC(p,n,{200:new $d({type:"array",items:{$ref:$s+c}})},"search for records by the specified property name and value pairs")),I&&(r.paths[X].delete=new aV(p,n,"delete all the records that match the provided query",{204:new oV}));let q="/"+o+"/{"+f+"}";if(r.paths[q]||(r.paths[q]={}),r.paths[q].options=new sV(p,n,{200:new iV},"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 CC([_],n,{200:new $d({$ref:$s+c})},"retrieve a record by its primary key")),y&&(r.paths[q].put=new Due([_],n,c,{200:new $d({$ref:$s+c})},"create or update the record with the URL path that maps to the record's primary key")),G&&(r.paths[q].patch=new vue([_],n,c,{200:new $d({$ref:$s+c})},"patch the record with the URL path that maps to the record's primary key")),I&&(r.paths[q].delete=new aV([_],n,"delete a record with the given primary key",{204:new oV})),w&&R.schema.enum.length>0){let k=`/${o}/{${f}}.{property}`;r.paths[k]||(r.paths[k]={}),r.paths[k].get=new CC([_,R],n,{200:new $d({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 Lue(e,t,r,n){this.description=n,this.requestBody={content:{"application/json":{schema:{$ref:$s+e}}}},this.security=t,this.responses=r}function CC(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function sV(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function iV(){this.description=uV,this.headers={},this.content={}}function $d(e,t){this.description=uV,this.content={"application/json":{schema:e}},this.headers=t}function oV(){this.description="successfully processed request, no content returned to client"}function Due(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 vue(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 aV(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function cV(e,t,r){this.type="object",this.properties=e,this.additionalProperties=t,this.required=r}function OC(e,t){this.type=e,(e==="string"||e==="number"||e==="integer")&&t!=="String"&&(this.format=t)}function dV(e){this.$ref=`#/components/schemas/${e}`}function Mue(e){this.type="array",this.items=new dV(e)}function PC(e,t,r){this.name=e,this.in=t,this.schema=r}var lV,Pue,jS,$s,uV,LC=se(()=>{lV=b(bt()),Pue="3.0.3",jS={Int:"integer",Float:"number",Long:"integer",ID:"string",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer"},$s="#/components/schemas/",uV="successful operation";a(zS,"generateJsonApi");a(Lue,"Post");a(CC,"Get");a(sV,"Options");a(iV,"ResponseOptions200");a($d,"Response200");a(oV,"Response204");a(Due,"Put");a(vue,"Patch");a(aV,"Delete");a(cV,"ResourceSchema");a(OC,"Type");a(dV,"Ref");a(Mue,"ArrayRef");a(PC,"Parameter")});var mV={};ye(mV,{Request:()=>_c,createReuseportFd:()=>JS});var fV,_c,DC,vC,JS,ch=se(()=>{fV=require("os"),_c=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 vC(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 DC(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)}},DC=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)}},vC=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,fV.platform)()!="win32"&&(JS=require("node-unix-socket").createReuseportFd)});var XS={};ye(XS,{parseHeaderValue:()=>UC,start:()=>Bue});async function xue(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream",s=n?"CONNECT":e.method;e.search&&Pg(e);let i=new Hs;try{e.responseHeaders=i;let o=e.url.slice(1),c,l;if(o!==pV){let _=QS.getMatch(o,n?"sse":"rest");if(!_)return t(e);e.handlerPath=_.path,c=new Us(_.relativeURL),c.async=!0,l=_.Resource}if(l?.isCaching){let _=r["cache-control"];if(_){let R=UC(_);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 _=UC(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 It(e,()=>{if(r["content-length"]||r["transfer-encoding"])try{e.data=$o(r["content-type"],!0)(e.body,e.headers)}catch(_){throw new Vd.ClientError(_,400)}if(e.authorize=!0,o===pV&&s==="GET"){if(e?.user?.role?.permission?.super_user)return zS(QS,`${e.protocol}://${e.hostname}`);throw new Vd.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 Vd.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Vd.ServerError(`Method ${s} is not recognized`,501)}}),m=200,p=e.lastModified;if(f==null)m=s==="GET"||s==="HEAD"?404:204,MC.lastModified&&isFinite(p)&&i.setIfNone("Last-Modified",new Date(p).toUTCString());else if(f.status>0&&f.headers){let _=Jq(f.headers,i);return f.headers!==_&&(f.headers=_),f.data!==void 0&&(f.body=Gm(f.data,e,f)),f}else if(isFinite(p)){Uue[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",_),MC.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=Gm(f,e,h),s==="HEAD"&&(h.body=void 0)),h}catch(o){o.statusCode?o.statusCode===500?gi.warn(o):gi.info(o):gi.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=Gm(o instanceof Error?_V(o):o,e,c),c}}function Bue(e){MC=e,e.includeExpensiveRecordCountEstimates&&(_c.prototype.includeExpensiveRecordCountEstimates=!0),!hV&&(hV=!0,QS=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return xue(t,r)},e),e.webSocket!==!1&&e.server.ws(async(t,r,n)=>{lh++;let s=new ns;EV||(EV=!0,np(l=>{lh>0&&l.push({metric:"ws-connections",connections:lh,byThread:!0})}));let i;t.on("error",l=>{i=!0,gi.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);Ye(u.length,"bytes-received",r.handlerPath,"message","ws"),s.push(d)},"message"));let c;t.on("close",()=>{lh--,en(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()});try{await n;let l=r.url.slice(1),u=QS.getMatch(l,"ws");if(en(!!u,"connection","ws","connect"),u){r.handlerPath=u.path,Ye(h=>({count:h.count,total:lh}),"connections",r.handlerPath,"connect","ws"),r.authorize=!0;let d=new Us(u.relativeURL);d.checkPermission=r.user?.role?.permission??{};let f=u.Resource;c=(await It(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),Ye(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?gi.warn(l):gi.info(l):gi.error(l),t.close(Fue[l.statusCode]||1011,_V(l))}t.close()},e))}function UC(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 gi,Vd,_V,sn,Uue,MC,pV,hV,QS,EV,lh,Fue,gV=se(()=>{Vo();is();gi=b(Q()),Vd=b(Ee());Lg();Gu();ja();jp();LC();ch();vg();({errorToString:_V}=gi),sn=new Uint8Array(8),Uue=new Float64Array(sn.buffer,0,1),MC={},pV="openapi";a(xue,"http");lh=0;a(Bue,"start");Fue={401:3e3,403:3003};a(UC,"parseHeaderValue")});var xC=M((cBe,TV)=>{var{recordAction:ZS,recordActionBinary:SV}=(is(),D(yg)),kue=require("fastify-plugin"),Hue=200;TV.exports=kue(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),ZS(o,"duration",u,f,d),SV(s.raw.statusCode<400,"success",u,f,d),SV(1,"response_"+s.raw.statusCode,u,f,d);let m=Hue;i?.pipe?(i.on("data",_=>{m+=_.length}),i.on("end",()=>{ZS(performance.now()-c,"transfer",u,f,d),ZS(m,"bytes-sent",u,f,d)})):(m+=i?.length||0,ZS(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 RV=M((lBe,yV)=>{var Gue=at(),que={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};yV.exports=function(e){return Gue.validateObject(e,que)}});var uh=M((uBe,bV)=>{"use strict";var $ue=(H(),D(W)).OPERATIONS_ENUM,BC=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=$ue.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};bV.exports=BC});var mh={};ye(mh,{createTokens:()=>kC,getJWTRSAKeys:()=>sT,refreshOperationToken:()=>HC,validateOperationToken:()=>GC,validateRefreshToken:()=>iT});async function sT(){if(eT)return eT;try{let e=dh.default.join(fh.default.getHdbBasePath(),pA),t=await tT.default.readFile(dh.default.join(e,Am.JWT_PASSPHRASE_NAME),"utf8"),r=await tT.default.readFile(dh.default.join(e,Am.JWT_PRIVATE_KEY_NAME),"utf8");return eT={publicKey:await tT.default.readFile(dh.default.join(e,Am.JWT_PUBLIC_KEY_NAME),"utf8"),privateKey:r,passphrase:t},eT}catch(e){throw nT.default.error(e),new Si.ClientError(Yd.NO_ENCRYPTION_KEYS,Kd.INTERNAL_SERVER_ERROR)}}async function kC(e){let t=(0,FC.validateBySchema)(e,mo.default.object({username:mo.default.string().optional(),password:mo.default.string().optional(),role:mo.default.string().optional(),expires_in:mo.default.alternatives(mo.default.string(),mo.default.number()).optional()}));if(t)throw new Si.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 Id(e.username,e.password,f)}catch(f){throw nT.default.error(f),new Si.ClientError(Yd.INVALID_CREDENTIALS,Kd.UNAUTHORIZED)}if(!r)throw new Si.ClientError(Yd.INVALID_CREDENTIALS,Kd.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 sT(),c=await Wd.default.sign(i,{key:o.privateKey,passphrase:o.passphrase},{expiresIn:e.expires_in??CV,algorithm:rT,subject:jd.OPERATION}),l=await Wd.default.sign(i,{key:o.privateKey,passphrase:o.passphrase},{expiresIn:Vue,algorithm:rT,subject:jd.REFRESH}),u=lN(l,$r.SHA256);if((await(0,AV.update)(new IV.default(Rm,Fu.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]))).skipped_hashes.length>0)throw new Si.ClientError(Yd.REFRESH_TOKEN_SAVE_FAILED,Kd.INTERNAL_SERVER_ERROR);return wV.default.signalUserChange(new NV.UserEventMsg(process.pid)),{operation_token:c,refresh_token:l}}async function HC(e){let t=(0,FC.validateBySchema)(e,mo.default.object({refresh_token:mo.default.string().required()}).required());if(t)throw new Si.ClientError(t.message);let{refresh_token:r}=e;await iT(r);let n=await sT(),s=await Wd.default.decode(r);return{operation_token:await Wd.default.sign({username:s.username,super_user:s.super_user,cluster_user:s.cluster_user},{key:n.privateKey,passphrase:n.passphrase},{expiresIn:CV,algorithm:rT,subject:jd.OPERATION})}}async function GC(e){return OV(e,jd.OPERATION)}async function iT(e){return OV(e,jd.REFRESH)}async function OV(e,t){try{let r=await sT(),n=await Wd.default.verify(e,r.publicKey,{algorithms:rT,subject:t});if(n.role)throw new Error("Invalid token");let s=await Id(n.username,void 0,!1);if(t===jd.REFRESH&&!uN(s.refresh_token,e))throw new Error("Invalid token");return s}catch(r){throw nT.default.warn(r),r?.name==="TokenExpiredError"?new Si.ClientError(Yd.TOKEN_EXPIRED,Kd.FORBIDDEN):new Si.ClientError(Yd.INVALID_TOKEN,Kd.UNAUTHORIZED)}}var Wd,tT,dh,mo,FC,Si,nT,AV,IV,wV,NV,fh,Kd,Yd,CV,Vue,rT,jd,eT,zd=se(()=>{Wd=b(require("jsonwebtoken")),tT=b(require("fs-extra")),dh=b(require("node:path")),mo=b(require("joi")),FC=b(at());H();Si=b(Ee()),nT=b(Q());fN();Es();AV=b(_n()),IV=b(uh()),wV=b(Xo()),NV=b(ls()),fh=b(ce()),{HTTP_STATUS_CODES:Kd,AUTHENTICATION_ERROR_MSGS:Yd}=Si.hdbErrors;fh.default.initSync();CV=fh.default.get(x.AUTHENTICATION_OPERATIONTOKENTIMEOUT)||"1d",Vue=fh.default.get(x.AUTHENTICATION_REFRESHTOKENTIMEOUT)||"30d",rT="RS256",jd={OPERATION:"operation",REFRESH:"refresh"};a(sT,"getJWTRSAKeys");a(kC,"createTokens");a(HC,"refreshOperationToken");a(GC,"validateOperationToken");a(iT,"validateRefreshToken");a(OV,"validateToken")});var qC=M((EBe,DV)=>{"use strict";var Kue=RV(),Jd=require("passport"),Yue=require("passport-local").Strategy,Wue=require("passport-http").BasicStrategy,jue=require("util"),zue=(Es(),D(co)),LV=jue.callbackify(zue.findAndValidateUser),hBe=Jr(),Jue=(H(),D(W)),PV=(zd(),D(mh)),{AccessViolation:Que}=Ee();Jd.use(new Yue(function(e,t,r){LV(e,t,r)}));Jd.use(new Wue(function(e,t,r){LV(e,t,r)}));Jd.serializeUser(function(e,t){t(null,e)});Jd.deserializeUser(function(e,t){t(null,e)});function Xue(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 Que)}switch(a(i,"handleResponse"),n){case"Basic":Jd.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===Jue.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?PV.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):PV.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Jd.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(Xue,"authorize");function Zue(e,t){let r=Kue(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(Zue,"checkPermissions");DV.exports={authorize:Xue,checkPermissions:Zue}});var jC=M((TBe,xV)=>{var lT=require("clone"),uT=at(),ede=ae(),aT=(H(),D(W)),gBe=Q(),$C=require("fs"),KC=require("joi"),{string:cT}=KC.types(),{hdbErrors:tde,handleHDBError:oT}=Ee(),{HDB_ERROR_MSGS:SBe,HTTP_STATUS_CODES:VC}=tde,{commonValidators:Qd}=Xi(),vV=" is required",rde=["insert","update","upsert"],YC={database:{presence:!1,format:Qd.schema_format,length:Qd.schema_length},schema:{presence:!1,format:Qd.schema_format,length:Qd.schema_length},table:{presence:!0,format:Qd.schema_format,length:Qd.schema_length},action:{inclusion:{within:rde,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},nde={schema:cT.required(),table:cT.required(),action:cT.valid("insert","update","upsert")},{AWS_ACCESS_KEY:sde,AWS_SECRET:ide,AWS_BUCKET:ode,AWS_FILE_KEY:ade,REGION:cde}=aT.S3_BUCKET_AUTH_KEYS,lde={s3:{presence:!0},[`s3.${sde}`]:{presence:!0,type:"String"},[`s3.${ide}`]:{presence:!0,type:"String"},[`s3.${ode}`]:{presence:!0,type:"String"},[`s3.${ade}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${cde}`]:{presence:!0,type:"String"}},MV=lT(YC);MV.data.presence={message:vV};var UV=lT(YC);UV.file_path.presence={message:vV};var ude=Object.assign(lT(YC),lde),WC=lT(nde);WC.csv_url=cT.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();WC.passthrough_headers=KC.object();function dde(e){let t=uT.validateObject(e,MV);return dT(e,t)}a(dde,"dataObject");function fde(e){let t=uT.validateBySchema(e,KC.object(WC));return dT(e,t)}a(fde,"urlObject");function mde(e){let t=uT.validateObject(e,UV);return dT(e,t)}a(mde,"fileObject");function pde(e){let t=uT.validateObject(e,ude);return dT(e,t)}a(pde,"s3FileObject");function dT(e,t){if(!t){let r=ede.checkGlobalSchemaTable(e.schema,e.table);if(r)return oT(new Error,r,VC.BAD_REQUEST);if(e.operation===aT.OPERATIONS_ENUM.CSV_FILE_LOAD)try{$C.accessSync(e.file_path,$C.constants.R_OK|$C.constants.F_OK)}catch(n){return n.code===aT.NODE_ERROR_CODES.ENOENT?oT(n,`No such file or directory ${n.path}`,VC.BAD_REQUEST):n.code===aT.NODE_ERROR_CODES.EACCES?oT(n,`Permission denied ${n.path}`,VC.BAD_REQUEST):oT(n)}}return t}a(dT,"postValidateChecks");xV.exports={dataObject:dde,urlObject:fde,fileObject:mde,s3FileObject:pde}});var zC=M((RBe,BV)=>{"use strict";var ph=Q(),fT=(H(),D(W));async function hde(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===fT.OPERATIONS_ENUM.INSERT||t.operation===fT.OPERATIONS_ENUM.UPDATE||t.operation===fT.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===fT.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(ph.info(i.message),i):i.http_resp_msg?(ph.error(`Error calling operation: ${e.name}`),ph.error(i.http_resp_msg),i):(ph.error(`Error calling operation: ${e.name}`),ph.error(i),i)}}a(hde,"callOperationFunctionAsAwait");BV.exports={callOperationFunctionAsAwait:hde}});var JC=M((ABe,kV)=>{"use strict";var{S3:Ede,GetObjectCommand:_de}=require("@aws-sdk/client-s3");kV.exports={getFileStreamFromS3:gde,getS3AuthObj:FV};async function gde(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 _de(r))).Body}a(gde,"getFileStreamFromS3");function FV(e,t,r){return new Ede({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(FV,"getS3AuthObj")});var GV=M((wBe,HV)=>{"use strict";var QC=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}},XC=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};HV.exports={BulkLoadFileObject:QC,BulkLoadDataObject:XC}});var $V=M((CBe,qV)=>{"use strict";var ZC=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}};qV.exports=ZC});var KV=M((PBe,VV)=>{"use strict";var eO=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};VV.exports=eO});var rO=M((DBe,WV)=>{"use strict";var YV=$V(),Sde=KV(),{HDB_ERROR_MSGS:Tde}=Jr(),tO=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=Tde.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 YV(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let l=new Sde(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 YV(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}};WV.exports=tO});var gc=M((UBe,QV)=>{"use strict";var MBe=Sn(),hh=Q(),{validateBySchema:jV}=at(),sa=require("joi"),yde=so(),mT=ae(),{handleHDBError:pT,hdbErrors:Rde,ClientError:zV}=Ee(),{HDB_ERROR_MSGS:hT,HTTP_STATUS_CODES:nO}=Rde,JV=ce();JV.initSync();var{getDatabases:sO}=(Oe(),D(pt)),bde=require("fs-extra"),Ade=(H(),D(W));QV.exports={describeAll:Ide,describeTable:ET,describeSchema:wde};async function Ide(e={}){try{let t=mT.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=sO(),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 ET({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 ET({schema:m,table:h,exact_count:u,include_computed:d},_)}E&&l.push(E)}catch(E){hh.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 hh.error("Got an error in describeAll"),hh.error(t),pT(new Error,hT.DESCRIBE_ALL_ERR)}}a(Ide,"describeAll");async function ET(e,t){mT.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=jV(e,sa.object({database:sa.string(),table:sa.string().required(),exact_count:sa.boolean().strict(),include_computed:sa.boolean().strict()}));if(i)throw new zV(i.message);let c=sO()[r];if(!c)throw pT(new Error,hT.SCHEMA_NOT_FOUND(e.schema),nO.NOT_FOUND);let l=c[n];if(!l)throw pT(new Error,hT.TABLE_NOT_FOUND(e.schema,e.table),nO.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 bde.stat(l.primaryStore.env.path)).size}catch(p){hh.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")),JV.get(Ade.CONFIG_PARAMS.CLUSTERING_ENABLED)&&(m.clustering_stream_name=yde.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){hh.warn(`unable to stat table dbi due to ${p}`)}return m}a(ET,"descTable");async function wde(e){mT.transformReq(e);let t=jV(e,sa.object({database:sa.string(),exact_count:sa.boolean().strict(),include_computed:sa.boolean().strict()}));if(t)throw new zV(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=sO()[n];if(!i)throw pT(new Error,hT.SCHEMA_NOT_FOUND(e.schema),nO.NOT_FOUND);let o={};for(let c in i){let l;if(r&&r.tables[c]&&(l=r.tables[c]),mT.isEmpty(l)||l.describe){let u=await ET({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(wde,"describeSchema")});var r1=M((BBe,t1)=>{"use strict";var Nde=gc(),{hdbErrors:XV}=Ee(),{getDatabases:ZV}=(Oe(),D(pt));t1.exports={checkSchemaExists:e1,checkSchemaTableExists:Cde,schemaDescribe:Nde};async function e1(e){if(!ZV()[e])return XV.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(e1,"checkSchemaExists");async function Cde(e,t){let r=await e1(e);if(r)return r;if(!ZV()[e][t])return XV.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Cde,"checkSchemaTableExists")});var _T=M((kBe,n1)=>{"use strict";var Ode=fs();n1.exports={writeTransaction:Pde};function Pde(e,t,r){return Ode.writeTransaction(e,t,r)}a(Pde,"writeTransaction")});var lO=M((VBe,h1)=>{"use strict";var{decode:Lde}=require("msgpackr"),{isMainThread:GBe,parentPort:qBe,threadId:$Be}=require("worker_threads"),TT=Gt(),Xd=ht(),aO=(H(),D(W)),bn=Q(),oO=ce(),Dde=(H(),D(W)),{onMessageByType:vde}=tt(),a1=so(),{recordAction:s1,recordActionBinary:Mde}=(is(),D(yg)),{publishToStream:Ude}=TT,{ConsumerEvents:i1}=require("nats"),xde=Sn(),{promisify:Bde}=require("util"),{decodeBlobsWithWrites:Fde}=(ss(),D(og)),c1=Bde(setTimeout),yT=1e4,RT,ST,kde,Hde,l1,Eh=new Map,Zd=new Map;h1.exports={initialize:u1,ingestConsumer:cO,setSubscription:Gde,setIgnoreOrigin:Vde,getDatabaseSubscriptions:$de,updateConsumer:d1};async function u1(){vde(aO.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,async n=>{await d1(n)}),l1=!0,bn.notify("Initializing clustering ingest service.");let{connection:e,jsm:t,js:r}=await TT.getNATSReferences();RT=e,ST=e.info.server_name,kde=t,Hde=r}a(u1,"initialize");async function d1(e){if(e.status==="start"){let{js:t,jsm:r}=await f1(e.node_domain_name);cO(e.stream_name,t,r,e.node_domain_name)}else if(e.status==="stop"){let t=Eh.get(e.stream_name+e.node_domain_name);t&&(bn.notify("Closing ingest consumer for node:",e.node_domain_name,"stream:",e.stream_name),await t.close?.(),Eh.set(e.stream_name+e.node_domain_name,"close")),Zd.get(e.node_domain_name)==="failed"&&Zd.set(e.node_domain_name,"close")}}a(d1,"updateConsumer");var bT=new Map;function Gde(e,t,r){let n=bT.get(e);n||bT.set(e,n=new Map),n.set(t,r),l1||u1().then(qde)}a(Gde,"setSubscription");async function qde(){let e=await xde.searchByValue({database:"system",table:"hdb_nodes",attribute:"name",value:"*"});for await(let t of e){let r=t.name+Xd.SERVER_SUFFIX.LEAF,n,s;for(let i of t.subscriptions||[])if(i.subscribe===!0){if(!n&&({js:n,jsm:s}=await f1(r),!n))break;let{schema:o,table:c}=i,l=a1.createNatsTableStreamName(o,c);cO(l,n,s,r)}}}a(qde,"accessConsumers");async function f1(e){let t,r,n=1;for(;!r;)try{t=await RT.jetstream({domain:e}),r=await RT.jetstreamManager({domain:e,checkAPI:!1})}catch(s){if(Zd.get(e)==="close")break;Zd.set(e,"failed"),n%10===1&&bn.warn("Nats ingest attempting to connect to:",e,"Nats error:",s.message);let i=n++*100<yT?n++*100:yT;await c1(i)}return{js:t,jsm:r}}a(f1,"connectToRemoteJS");function $de(){return bT}a($de,"getDatabaseSubscriptions");var m1;function Vde(e){m1=e}a(Vde,"setIgnoreOrigin");var p1=100,o1=new Array(p1),gT=0;async function cO(e,t,r,n){let{connection:s}=await TT.getNATSReferences();RT=s,ST=s.info.server_name;let i,o=1;for(;!i;)try{i=await t.consumers.get(e,ST),bn.notify("Initializing ingest consumer for node:",n,"stream:",e)}catch(u){if(Zd.get(n)==="close")break;o%10===1&&bn.warn("Nats ingest error getting consumer:",n,"stream:",e,"Nats error:",u.message),u.code==="404"&&(bn.notify("Nats ingest creating consumer for node:",n,"stream:",e),i=await TT.createConsumer(r,e,ST,new Date(Date.now()).toISOString()));let d=o++*100<yT?o++*100:yT;await c1(d)}let c=!1,l;for(;!c;){if(Eh.get(e+n)==="close"||Zd.get(n)==="close"){Eh.delete(e+n),c=!0;continue}l=await i.consume({max_messages:oO.get(aO.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS)??100,bind:!0}),Eh.set(e+n,l);let u=!1;(async()=>{for await(let d of await l.status())if(d.type===i1.ConsumerDeleted&&(await l.close(),c=!0),d.type===i1.HeartbeatsMissed){let f=d.data;bn.trace(`${f} clustering ingest consumer heartbeats missed, node: ${n} stream: ${l.consumer.stream}`),f===100&&(bn.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 o1[gT],o1[gT]=Kde(d).catch(f=>{bn.error(f)}),++gT>=p1&&(gT=0)}catch(d){d.message==="consumer deleted"?(bn.notify("Nats consumer deleted, closing messages for node:",n,"stream:",l.consumer.stream),await l.close(),c=!0):bn.error("Error consuming clustering ingest, restarting consumer",d)}}}a(cO,"ingestConsumer");async function Kde(e){let t;await Fde(()=>{t=Lde(e.data)}),s1(e.data.length,"bytes-received",e.subject,t.operation,"ingest"),bn.trace("Nats message processor message size:",e?.msg?._msg?.size,"bytes");let r=e.headers,n=!1,s=oO.get(aO.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(Xd.MSG_HEADERS.TRANSACTED_NODES)&&r.values(Xd.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(Xd.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!m1),Mde(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(Xd.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;bn.trace("processing message:",o,c,u,(d?"records: "+d.map(I=>I?.id):"")+(f?"ids: "+f:""),"with sequence:",e.seq),bn.trace(`messageProcessor nats msg id: ${e.headers.get(Xd.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=bT.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:iO(o),value:d[0],id:f?.[0],expiresAt:p,timestamp:_,table:u,onCommit:h,user:R,nodeName:S});else{let I=d.map((G,X)=>({type:iO(o),value:G,expiresAt:p,id:f?.[X],table:u}));for(;l;)I.push({type:iO(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})}oO.get(Dde.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&Ude(e.subject.split(".").slice(0,-1).join("."),a1.createNatsTableStreamName(c,u),e.headers,e.data),await E;let w=Date.now()-_;_&&s1(w,"replication-latency",e.subject,o,"ingest")}catch(o){bn.error(o)}e.ack()}a(Kde,"messageProcessor");function iO(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(iO,"convertOperation")});var Gt=M((QBe,D1)=>{"use strict";var Kr=ce();Kr.initSync();var Yde=require("fs-extra"),Wde=require("semver"),Sh=require("path"),{monotonicFactory:jde}=require("ulidx"),_1=jde(),zde=require("util"),g1=require("child_process"),Jde=zde.promisify(g1.exec),Qde=g1.spawn,on=ht(),rt=(H(),D(W)),{packageJson:Xde,PACKAGE_ROOT:Zde}=bt(),AT=ae(),Ti=Q(),IT=so(),efe=_T(),_h=St(),{broadcast:tfe,onMessageByType:rfe,getWorkerIndex:nfe}=tt(),{isMainThread:S1}=require("worker_threads"),{Encoder:sfe,decode:mO}=require("msgpackr"),T1=new sfe,{isEmpty:zl}=AT,y1=(Es(),D(co)),YBe=48*36e11;S1&&rfe(rt.ITC_EVENT_TYPES.RESTART,()=>{An=void 0,jl=void 0});var{connect:ife,StorageType:ofe,RetentionPolicy:afe,AckPolicy:pO,DeliverPolicy:hO,DiscardPolicy:cfe,NatsConnection:WBe,JetStreamManager:jBe,JetStreamClient:zBe,StringCodec:JBe,JSONCodec:lfe,createInbox:EO,headers:ufe,ErrorCode:E1}=require("nats"),{recordAction:dfe}=(is(),D(yg)),{encodeBlobsAsBuffers:ffe}=(ss(),D(og)),R1=lfe(),mfe="clustering",pfe=Xde.engines[on.NATS_SERVER_NAME],hfe=Sh.join(Zde,"dependencies"),fO=Sh.join(hfe,`${process.platform}-${process.arch}`,on.NATS_BINARY_NAME),uO,dO,gh,Yl,Wl;D1.exports={runCommand:b1,checkNATSServerInstalled:Efe,createConnection:_O,getConnection:Th,getJetStreamManager:yh,getJetStream:I1,getNATSReferences:po,getServerList:gfe,createLocalStream:gO,listStreams:w1,deleteLocalStream:Sfe,getServerConfig:ef,listRemoteStreams:Tfe,viewStream:yfe,viewStreamIterator:Rfe,publishToStream:bfe,request:wfe,reloadNATS:SO,reloadNATSHub:Nfe,reloadNATSLeaf:Cfe,extractServerName:Ife,requestErrorHandler:Ofe,createLocalTableStream:P1,createTableStreams:Dfe,purgeTableStream:L1,purgeSchemaTableStreams:vfe,getStreamInfo:Mfe,updateLocalStreams:xfe,closeConnection:_fe,getJsmServerName:wT,addNatsMsgHeader:N1,clearClientCache:A1,updateRemoteConsumer:Pfe,createConsumer:C1,updateConsumerIterator:Lfe};async function b1(e,t=void 0){let{stdout:r,stderr:n}=await Jde(e,{cwd:t});if(n)throw new Error(n.replace(`
|
|
16
16
|
`,""));return r.replace(`
|
|
17
17
|
`,"")}a(b1,"runCommand");async function Efe(){try{await Yde.access(fO)}catch{return!1}let e=await b1(`${fO} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return Wde.eq(t,pfe)}a(Efe,"checkNATSServerInstalled");async function _O(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await y1.getClusterUser();if(zl(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Ti.trace("create nats connection called");let i=await ife({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(),Ti.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Ti.error("Error with Nats client connection, connection closed",o),i===An&&A1()}),i}a(_O,"createConnection");function A1(){An=void 0,Yl=void 0,Wl=void 0,jl=void 0}a(A1,"clearClientCache");async function _fe(){An&&(await An.drain(),An=void 0,Yl=void 0,Wl=void 0,jl=void 0)}a(_fe,"closeConnection");var An,jl;async function Th(){return jl||(jl=_O(Kr.get(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),An=await jl),An||jl}a(Th,"getConnection");async function yh(){if(Yl)return Yl;zl(An)&&await Th();let{domain:e}=ef(rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(zl(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Yl=await An.jetstreamManager({domain:e,timeout:6e4}),Yl}a(yh,"getJetStreamManager");async function I1(){if(Wl)return Wl;zl(An)&&await Th();let{domain:e}=ef(rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(zl(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Wl=An.jetstream({domain:e,timeout:6e4}),Wl}a(I1,"getJetStream");async function po(){let e=An||await Th(),t=Yl||await yh(),r=Wl||await I1();return{connection:e,jsm:t,js:r}}a(po,"getNATSReferences");async function gfe(e){let t=Kr.get(rt.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await y1.getClusterUser(),s=await _O(t,r,n),i=EO(),o=s.subscribe(i),c=[],l,u=(async()=>{for await(let d of o){let f=R1.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 AT.asyncSetTimeout(e),await o.drain(),await s.close(),await u,c}a(gfe,"getServerList");async function gO(e,t){let{jsm:r}=await po(),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:ofe.File,retention:afe.Limits,subjects:t,discard:cfe.Old,maxMsgs:s,maxBytes:i,maxAge:n})}a(gO,"createLocalStream");async function w1(){let{jsm:e}=await po(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(w1,"listStreams");async function Sfe(e){let{jsm:t}=await po();await t.streams.delete(e)}a(Sfe,"deleteLocalStream");async function Tfe(e){let{connection:t}=await po(),r=[],n=EO(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(R1.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(Tfe,"listRemoteStreams");async function yfe(e,t=void 0,r=void 0){let{jsm:n,js:s}=await po(),i=_1(),o={durable_name:i,ack_policy:pO.Explicit};t&&(o.deliver_policy=hO.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=mO(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(yfe,"viewStream");async function*Rfe(e,t=void 0,r=void 0){let{jsm:n,js:s}=await po(),i=_1(),o={durable_name:i,ack_policy:pO.Explicit};t&&(o.deliver_policy=hO.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=mO(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(Rfe,"viewStreamIterator");async function bfe(e,t,r,n){Ti.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=N1(n,r);let{js:s}=await po(),i=await wT(),o=`${e}.${i}`,c=await ffe(()=>n instanceof Uint8Array?n:T1.encode(n));try{Ti.trace(`publishToStream publishing to subject: ${o}`),dfe(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 O1(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(l.code&&l.code.toString()==="503"){Ti.trace(`publishToStream creating stream: ${t}`);let d=o.split(".");d[2]="*",await gO(t,[o]),await s.publish(o,c,{headers:r})}else throw l}});throw l}}a(bfe,"publishToStream");function N1(e,t){t===void 0&&(t=ufe());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(N1,"addNatsMsgHeader");function ef(e){e=e.toLowerCase();let t=Sh.join(Kr.get(rt.CONFIG_PARAMS.ROOTPATH),mfe);if(e===rt.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return zl(dO)&&(dO={port:_h.getConfigFromFile(rt.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:_h.getConfigFromFile(rt.CONFIG_PARAMS.CLUSTERING_NODENAME)+on.SERVER_SUFFIX.HUB,config_file:on.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:Sh.join(t,on.PID_FILES.HUB),hdbNatsPath:t}),dO;if(e===rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return zl(uO)&&(uO={port:_h.getConfigFromFile(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:_h.getConfigFromFile(rt.CONFIG_PARAMS.CLUSTERING_NODENAME)+on.SERVER_SUFFIX.LEAF,config_file:on.NATS_CONFIG_FILES.LEAF_SERVER,domain:_h.getConfigFromFile(rt.CONFIG_PARAMS.CLUSTERING_NODENAME)+on.SERVER_SUFFIX.LEAF,pid_file_path:Sh.join(t,on.PID_FILES.LEAF),hdbNatsPath:t}),uO;Ti.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(ef,"getServerConfig");async function C1(e,t,r,n){try{await e.consumers.add(t,{ack_policy:pO.Explicit,durable_name:r,deliver_policy:hO.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(C1,"createConsumer");async function Afe(e,t,r){await e.consumers.delete(t,r)}a(Afe,"removeConsumer");function Ife(e){return e.split(".")[1]}a(Ife,"extractServerName");async function wfe(e,t,r=6e4,n=EO()){if(!AT.isObject(t))throw new Error("data param must be an object");let s=T1.encode(t),{connection:i}=await po(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return mO(c.data)}a(wfe,"request");function SO(e){return new Promise(async(t,r)=>{let n=Qde(fO,["--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(SO,"reloadNATS");async function Nfe(){let{pid_file_path:e}=ef(rt.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await SO(e)}a(Nfe,"reloadNATSHub");async function Cfe(){let{pid_file_path:e}=ef(rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await SO(e)}a(Cfe,"reloadNATSLeaf");function Ofe(e,t,r){let n;switch(e.code){case E1.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case E1.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(Ofe,"requestErrorHandler");async function Pfe(e,t){let r=t+on.SERVER_SUFFIX.LEAF,{connection:n}=await po(),{jsm:s}=await Ffe(r),{schema:i,table:o}=e,c=IT.createNatsTableStreamName(i,o),l=e.start_time?e.start_time:new Date(Date.now()).toISOString();await O1(async()=>{if(e.subscribe===!0)await C1(s,c,n.info.server_name,l);else try{await Afe(s,c,n.info.server_name)}catch(u){Ti.trace(u)}})}a(Pfe,"updateRemoteConsumer");async function Lfe(e,t,r,n){let s=IT.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(!S1&&nfe()<Kr.get(rt.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=lO();await c(o)}await tfe(o),n==="stop"&&await AT.asyncSetTimeout(1e3)}a(Lfe,"updateConsumerIterator");function O1(e){return efe.writeTransaction(rt.SYSTEM_SCHEMA_NAME,rt.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(O1,"exclusiveLock");async function P1(e,t){let r=IT.createNatsTableStreamName(e,t),n=await wT(),s=Ufe(e,t,n);await gO(r,[s])}a(P1,"createLocalTableStream");async function Dfe(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await P1(n,s)}}a(Dfe,"createTableStreams");async function L1(e,t,r=void 0){if(Kr.get(rt.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=IT.createNatsTableStreamName(e,t),{domain:s}=ef(rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await(await(await Th()).jetstreamManager({domain:s,timeout:24e4})).streams.purge(n,r)}catch(n){if(n.message==="stream not found")Ti.warn(n);else throw n}}a(L1,"purgeTableStream");async function vfe(e,t){if(Kr.get(rt.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await L1(e,t[r])}a(vfe,"purgeSchemaTableStreams");async function Mfe(e){return(await yh()).streams.info(e)}a(Mfe,"getStreamInfo");function Ufe(e,t,r){return`${on.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(Ufe,"createSubjectName");async function wT(){if(gh)return gh;if(gh=(await yh())?.nc?.info?.server_name,gh===void 0)throw new Error("Unable to get jetstream manager server name");return gh}a(wT,"getJsmServerName");async function xfe(){let e=await yh(),t=await wT(),r=await w1();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=Bfe(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(".");Ti.trace(`Updating stream subject name from: ${i} to: ${d}`),s.subjects[0]=d,await e.streams.update(s.name,s)}}a(xfe,"updateLocalStreams");function Bfe(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(Bfe,"updateStreamLimits");async function Ffe(e){let t,r;try{t=await An.jetstream({domain:e}),r=await An.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw Ti.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a(Ffe,"connectToRemoteJS")});function TO(e){let t=e.get(NT),r=t?(0,tf.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:bh(e)??1,nodes:[]})})}i[n]=0,e.putSync(NT,(0,tf.pack)(r))}return r}function Rh(e){return TO(e).remoteNameToId}function M1(e,t){let r=TO(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(NT,(0,tf.pack)(r)),s}function CT(e,t){let r=TO(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(NT,(0,tf.pack)(r))}return v1.trace?.("The remote node name map",e,n,s),s}var v1,tf,NT,yO=se(()=>{v1=b(ir());Ss();tf=require("msgpackr"),NT=Symbol.for("remote-ids");a(TO,"getIdMappingRecord");a(Rh,"exportIdMapping");a(M1,"remoteToLocalNodeId");a(CT,"getIdOfRemoteNode")});var H1={};ye(H1,{commitsAwaitingReplication:()=>rf,getHDBNodeTable:()=>qt,getReplicationSharedStatus:()=>nf,iterateRoutes:()=>Ih,shouldReplicateToNode:()=>Ah,subscribeToNodeUpdates:()=>sf});function qt(){return U1||(U1=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 nf(e,t,r,n){return new Float64Array(e.getUserSharedBuffer(["replicated",t,r],new ArrayBuffer(64),n&&{callback:n}))}function sf(e){qt().subscribe({}).then(async t=>{for await(let r of t){let n=r?.value?.name;k1.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 qt().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 Ah(e,t){let r=Sc.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===Sc.default.get(x.REPLICATION_SHARD))))&&qt().primaryStore.get(nt())?.replicates||e.subscriptions?.some(n=>(n.database||n.schema)===t&&n.subscribe)}function kfe(){sf(e=>{Tc({},(t,r)=>{let n=e.name,s=x1.get(n);if(s||x1.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=nf(i,r,n,()=>{let c=o[0],l=o.lastTime;for(let{txnTime:u,onConfirm:d}of rf.get(r)||[])u>l&&u<=c&&d();o.lastTime=c});o.lastTime=0,s.set(r,o)}})})}function*Ih(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=Sc.default.get(x.REPLICATION_SECUREPORT)??(!Sc.default.get(x.REPLICATION_PORT)&&Sc.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||Sc.default.get(x.REPLICATION_PORT)||Sc.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){B1.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 B1,F1,Sc,k1,U1,x1,rf,of=se(()=>{Oe();Ss();Um();B1=require("worker_threads"),F1=b(Ee()),Sc=b(ce());H();k1=b(ir());server.nodes=[];a(qt,"getHDBNodeTable");a(nf,"getReplicationSharedStatus");a(sf,"subscribeToNodeUpdates");a(Ah,"shouldReplicateToNode");x1=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})`);rf||(rf=new Map,kfe());let n=rf.get(e);return n||(n=[],rf.set(e,n)),new Promise(s=>{let i=0;n.push({txnTime:t,onConfirm:a(()=>{++i===r&&s()},"onConfirm")})})});a(kfe,"startSubscriptionToReplications");a(Ih,"iterateRoutes")});var W1={};ye(W1,{connectedToNode:()=>Jl,disconnectedFromNode:()=>cf,ensureNode:()=>ia,requestClusterStatus:()=>Y1,startOnMainThread:()=>RO});async function RO(e){let t=0,r=ut();for(let o of Object.getOwnPropertyNames(r)){let c=r[o];for(let l in c){let u=c[l];if(u.auditStore){OT.set(o,bh(u.auditStore));break}}}yi.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=qt().primaryStore.get(c);if(u!==null){let d=e.url??yc();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"),qt().primaryStore.get(c)&&l();for(let u of Ih(e))try{let d=!u.subscriptions;if(d&&await l(),d&&u.replicates==null&&(u.replicates=!0),G1.push(u),o.find(f=>f.url===u.url))continue;s(u)}catch(d){console.error(d)}sf(s)});let n;function s(o,c=o?.name){let l=nt()&&c===nt()||yc()&&o?.url===yc();if(l){let m=!!o?.replicates;if(n!==void 0&&n!==m)for(let p of qt().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 ho){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){ho.get(m).iterator.remove(),ho.delete(m);return}}return}if(l)return;if(!o.url){ot.info(`Node ${o.name} is missing url`);return}let u=ho.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 af)if(o.url===p.url){af.delete(m);break}af.set(o.name,o)}let d=ut();if(u||(u=new Map,ho.set(o.url,u)),u.iterator=Tc(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}];OT.has(m)&&wh.default.get(x.REPLICATION_FAILOVER)&&(_.push({replicateByDefault:p,name:nt(),startTime:OT.get(m),endTime:Date.now(),replicates:!0}),OT.delete(m));let R=Ah(o,m),S=yi.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=Hfe.HDB_LEADER_URL??process.env.HDB_LEADER_URL??G1[0]?.url,w=y?new URL(y).hostname:Array.from(qt().primaryStore.getKeys({}).filter(G=>G!==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 G={..._[0],type:"subscribe-to-node",database:m,nodes:_};E?E.postMessage(G):Nh(G)},Gfe)}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:qt().primaryStore.get(nt())?.replicates}),qt().primaryStore.get(nt())?.replicates||(n=!1,ot.info("Disabling replication, this node name",nt(),qt().primaryStore.get(nt()),m));let y={type:"unsubscribe-from-node",database:m,url:o.url,name:o.name,nodes:_};E?E.postMessage(y):LT(y)}}a(f,"onDatabase")}a(s,"onNodeUpdate"),cf=a(function(o){try{ot.info("Disconnected from node",o.name,o.url,"finished",!!o.finished);let c=Array.from(af.keys()),l=c.sort(),u=l.indexOf(o.name||Ri(o.url));if(u===-1){ot.warn("Disconnected node not found in node map",o.name,c);return}let d=ho.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||!wh.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],_=af.get(E);d=ho.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"),Jl=a(function(o){let c=ho.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(!wh.default.get(x.REPLICATION_FAILOVER))return;l.nodes=[u];let d=!1;for(let f of ho.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=yi.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]}):Nh({url:l.url,name:l.name,database:c,nodes:[o]})}a(i,"connectToNextWorker"),(0,yi.onMessageByType)("disconnected-from-node",cf),(0,yi.onMessageByType)("connected-to-node",Jl),(0,yi.onMessageByType)("request-cluster-status",Y1)}function Y1(e,t){let r=[];for(let[n,s]of af)try{let i=ho.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=qt();e=e??Ri(t.url),t.name=e;try{if(t.ca){let s=new V1.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&&!wh.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 yi,PT,ot,q1,wh,V1,K1,$1,Hfe,Gfe,ho,cf,Jl,af,OT,G1,Ch=se(()=>{Oe();yi=b(tt());Ss();PT=require("worker_threads");of();ot=b(Q()),q1=b(require("lodash")),wh=b(ce());H();V1=require("crypto"),K1=b(require("minimist")),{cloneDeep:$1}=q1.default,Hfe=(0,K1.default)(process.argv),Gfe=200,ho=new Map,af=new Map,OT=new Map,G1=[];a(RO,"startOnMainThread");a(Y1,"requestClusterStatus");PT.parentPort&&(cf=a(e=>{PT.parentPort.postMessage({type:"disconnected-from-node",...e})},"disconnectedFromNode"),Jl=a(e=>{PT.parentPort.postMessage({type:"connected-to-node",...e})},"connectedToNode"),(0,yi.onMessageByType)("subscribe-to-node",e=>{Nh(e)}),(0,yi.onMessageByType)("unsubscribe-from-node",e=>{LT(e)}));a(ia,"ensureNode")});var ys=M($t=>{"use strict";var gr=require("path"),{watch:qfe}=require("chokidar"),Wn=require("fs-extra"),lf=require("node-forge"),Z1=require("net"),{generateKeyPair:bO,X509Certificate:oa,createPrivateKey:eK,randomBytes:$fe}=require("node:crypto"),Vfe=require("util");bO=Vfe.promisify(bO);var Mt=lf.pki,bi=require("joi"),{v4:tK}=require("uuid"),{validateBySchema:NO}=at(),{forComponent:Kfe}=Q(),Ts=ce(),Vs=(H(),D(W)),{CONFIG_PARAMS:Xl}=Vs,Ai=IN(),{ClientError:Rc}=Ee(),vT=require("node:tls"),{relative:rK,join:Yfe}=require("node:path"),{CERTIFICATE_VALUES:j1}=Ai,Wfe=sl(),AO=St(),{table:jfe,getDatabases:zfe,databases:DT}=(Oe(),D(pt)),{getJWTRSAKeys:z1}=(zd(),D(mh)),Xe=Kfe("tls").conditional;$t.generateKeys=PO;$t.updateConfigCert=uK;$t.createCsr=rme;$t.signCertificate=nme;$t.setCertTable=uf;$t.loadCertificates=aK;$t.reviewSelfSignedCert=DO;$t.createTLSSelector=fK;$t.listCertificates=pK;$t.addCertificate=lme;$t.removeCertificate=dme;$t.createNatsCerts=ome;$t.generateCertsKeys=ime;$t.getReplicationCert=Ph;$t.getReplicationCertAuth=tme;$t.renewSelfSigned=ame;$t.hostnamesFromCert=MO;$t.getKey=fme;$t.getHostnamesFromCertificate=mme;$t.getPrimaryHostName=vO;$t.generateSerialNumber=xT;var{urlToNodeName:nK,getThisNodeUrl:Jfe,getThisNodeName:UT,clearThisNodeName:Qfe}=(Ss(),D(aa)),{readFileSync:Xfe,statSync:sK}=require("node:fs"),fFe=ce(),{getTicketKeys:Zfe,onMessageFromWorkers:eme}=tt(),{isMainThread:iK}=require("worker_threads"),{TLSSocket:oK,createSecureContext:mFe}=require("node:tls"),CO=3650,Oh=["127.0.0.1","localhost","::1"],OO=[{name:"countryName",value:"USA"},{name:"stateOrProvinceName",value:"Colorado"},{name:"localityName",value:"Denver"},{name:"organizationName",value:"HarperDB, Inc."}];function xT(){let e=$fe(8);return e[0]=e[0]&127|1,e.toString("hex")}a(xT,"generateSerialNumber");eme(async e=>{e.type===Vs.ITC_EVENT_TYPES.RESTART&&(Ts.initSync(!0),await DO())});var an;function Ac(){return an||(an=zfe().system.hdb_certificate,an||(an=jfe({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(Ac,"getCertTable");async function Ph(){let e=fK("operations-api"),t={secureContexts:null,setSecureContext:a(s=>{},"setSecureContext")};await e.initialize(t);let r=t.secureContexts.get(UT());if(!r)return;let n=new oa(r.options.cert);return r.cert_parsed=n,r.issuer=n.issuer,r}a(Ph,"getReplicationCert");async function tme(){Ac();let e=(await Ph()).options.cert,r=new oa(e).issuer.match(/CN=(.*)/)?.[1];return an.get(r)}a(tme,"getReplicationCertAuth");var J1,bc=new Map;function aK(){if(J1)return;J1=!0;let e=[{configKey:Xl.TLS},{configKey:Xl.OPERATIONSAPI_TLS}];Ac();let t=gr.dirname(AO.getConfigFilePath()),r;for(let{configKey:n}of e){let s=AO.getConfigFromFile(n);if(s){Array.isArray(s)||(s=[s]);for(let i of s){let o=i.privateKey,c=o&&rK(Yfe(t,"keys"),o);c&&Q1(o,l=>{bc.set(c,l)},"private key");for(let l of[!1,!0]){let u=i[l?"certificateAuthority":"certificate"];if(u&&iK){let d;Q1(u,f=>{if(j1.cert===f)return;let m=i.hostname??i.hostnames??i.host??i.hosts;m&&!Array.isArray(m)&&(m=[m]);let p=dK(u),h=new oa(p),E;try{E=vO(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(j1.cert)))return;let _=an.primaryStore.get(E),R=sK(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(aK,"loadCertificates");function Q1(e,t,r){let n,s=a((i,o)=>{try{let c=o.mtimeMs;c&&c!==n&&(n&&iK&&Xe.warn?.(`Reloading ${r}:`,i),n=c,t(dK(i)))}catch(c){Xe.error?.(`Error loading ${r}:`,i,c)}},"loadFile");Wn.existsSync(e)?s(e,sK(e)):Xe.error?.(`${r} file not found:`,e),qfe(e,{persistent:!1}).on("change",s)}a(Q1,"loadAndWatch");function IO(){let e=Jfe();if(e==null){let t=Oh[0];return Xe.info?.("replication url is missing from harperdb-config.yaml, using default host"+t),t}return nK(e)}a(IO,"getHost");function MT(){let e=UT();if(e==null){let t=Oh[0];return Xe.info?.("replication url is missing from harperdb-config.yaml, using default host"+t),t}return e}a(MT,"getCommonName");async function rme(){let e=await Ph(),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:MT()},...OO];Xe.info?.("Creating CSR with subject",s),n.setSubject(s);let i=[{name:"unstructuredName",value:"HarperDB, Inc."},{name:"extensionRequest",extensions:cK()}];return Xe.info?.("Creating CSR with attributes",i),n.setAttributes(i),n.sign(r),lf.pki.certificationRequestToPem(n)}a(rme,"createCsr");function cK(){let e=Oh.includes(MT())?Oh:[...Oh,MT()];return e.includes(IO())||e.push(IO()),[{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=>Z1.isIP(t)?{type:7,ip:t}:{type:2,value:t})}]}a(cK,"certExtensions");async function nme(e){let t={},r=gr.join(Ts.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME);if(e.csr){let n,s;Ac();for await(let d of an.search([]))if(d.is_authority&&!d.details.issuer.includes("HarperDB-Certificate-Authority")){if(bc.has(d.private_key_name)){n=bc.get(d.private_key_name),s=d;break}else if(d.private_key_name&&await Wn.exists(gr.join(r,d.private_key_name))){n=Wn.readFile(gr.join(r,d.private_key_name)),s=d;break}}if(!n){let d=await wO();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=lf.pki.createCertificate();c.serialNumber=xT(),c.validity.notBefore=new Date;let l=new Date;c.validity.notAfter=l,c.validity.notAfter.setDate(l.getDate()+CO),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,lf.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(nme,"signCertificate");async function sme(e,t){await uf({name:UT(),uses:["https","wss"],certificate:e,private_key_name:"privateKey.pem",is_authority:!1,is_self_signed:!0}),await uf({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(sme,"createCertificateTable");async function uf(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},Ac(),await an.patch(e)}a(uf,"setCertTable");async function PO(){let e=await bO("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(PO,"generateKeys");async function LO(e,t,r){let n=Mt.createCertificate();if(!t){let o=await Ph();t=Mt.certificateFromPem(o.options.cert).publicKey}n.publicKey=t,n.serialNumber=xT(),n.validity.notBefore=new Date;let s=new Date;n.validity.notAfter=s,n.validity.notAfter.setDate(s.getDate()+CO);let i=[{name:"commonName",value:MT()},...OO];return n.setSubject(i),n.setIssuer(r.subject.attributes),n.setExtensions(cK()),n.sign(e,lf.md.sha256.create()),Mt.certificateToPem(n)}a(LO,"generateCertificates");async function wO(){let e=await pK(),t;for(let r of e){if(!r.is_authority)continue;let n=await mK(r.private_key_name);if(r.private_key_name&&n&&new oa(r.certificate).checkPrivateKey(eK(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(wO,"getCertAuthority");async function lK(e,t,r=!0){let n=Mt.createCertificate();n.publicKey=t,n.serialNumber=xT(),n.validity.notBefore=new Date;let s=new Date;n.validity.notAfter=s,n.validity.notAfter.setDate(s.getDate()+CO);let i=[{name:"commonName",value:`HarperDB-Certificate-Authority-${Ts.get(Xl.REPLICATION_HOSTNAME)??nK(Ts.get(Xl.REPLICATION_URL))??tK().split("-")[0]}`},...OO];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,lf.md.sha256.create());let o=gr.join(Ts.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME),c=gr.join(o,Ai.PRIVATEKEY_PEM_NAME);return r&&await Wn.writeFile(c,Mt.privateKeyToPem(e)),n}a(lK,"generateCertAuthority");async function ime(){let{privateKey:e,publicKey:t}=await PO(),r=await lK(e,t),n=await LO(e,t,r);await sme(n,r),uK()}a(ime,"generateCertsKeys");async function ome(){let e=await LO(Mt.privateKeyFromPem(Ai.CERTIFICATE_VALUES.key),void 0,Mt.certificateFromPem(Ai.CERTIFICATE_VALUES.cert)),t=gr.join(Ts.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME),r=gr.join(t,Ai.NATS_CERTIFICATE_PEM_NAME);await Wn.exists(r)||await Wn.writeFile(r,e);let n=gr.join(t,Ai.NATS_CA_PEM_NAME);await Wn.exists(n)||await Wn.writeFile(n,Ai.CERTIFICATE_VALUES.cert)}a(ome,"createNatsCerts");async function ame(){Ac();for await(let e of an.search([{attribute:"is_self_signed",value:!0}]))await an.delete(e.name);await DO()}a(ame,"renewSelfSigned");async function DO(){Qfe(),await aK(),Ac();let e=await wO();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(Wn.readFileSync(u)),keyPath:u}}catch(d){return Xe.warn?.(`Failed to parse private key from ${u}:`,d.message),{key:null,keyPath:u}}},"tryToParseKey"),n=Ts.get(Xl.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=Ts.get(Xl.TLS_PRIVATEKEY),d=r(u);s=d.key,i=d.keyPath}let o=gr.join(Ts.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME),c=rK(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 PO(),Wn.existsSync(gr.join(o,Ai.PRIVATEKEY_PEM_NAME))&&(c=`privateKey${tK().split("-")[0]}.pem`),await Wn.writeFile(gr.join(o,c),Mt.privateKeyToPem(s)));let l=await lK(s,Mt.setRsaPublicKey(s.n,s.e),!1);await uf({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 Ph()){let r=UT();Xe.notify?.(`A suitable replication certificate was not found, creating new self singed cert named: ${r}`),e=e??await wO();let n=Mt.certificateFromPem(e.ca.certificate),s=n.publicKey,i=await LO(Mt.privateKeyFromPem(e.private_key),s,n);await uf({name:r,uses:["https","operations","wss"],certificate:i,is_authority:!1,private_key_name:e.ca.private_key_name,is_self_signed:!0})}}a(DO,"reviewSelfSignedCert");function uK(){let e=Wfe(Object.keys(Vs.CONFIG_PARAM_MAP),!0),t=gr.join(Ts.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME),r=gr.join(t,Ai.PRIVATEKEY_PEM_NAME),n=gr.join(t,Ai.NATS_CERTIFICATE_PEM_NAME),s=gr.join(t,Ai.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),AO.updateConfigValue(void 0,void 0,o,!1,!0)}a(uK,"updateConfigCert");function dK(e){return e.startsWith("-----BEGIN")?e:Xfe(e,"utf8")}a(dK,"readPEM");var X1=vT.createSecureContext;vT.createSecureContext=function(e){if(!e.cert||!e.key)return X1(e);let t={...e};delete t.key,delete t.cert;let r=X1(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};var cme=oK.prototype._init;oK.prototype._init=function(e,t){cme.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 Ql=new Map;function fK(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(),Ql.clear();let d=0;if(DT===void 0){c();return}for await(let f of DT.system.hdb_certificate.search([])){let m=f.certificate,p=new oa(m);f.is_authority&&(p.asString=m,Ql.set(p.subject,m))}for await(let f of DT.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 mK(f.private_key_name),E=f.certificate,_=new oa(E);if(Ql.has(_.issuer)&&(E+=`
|
|
18
|
-
`+Ql.get(_.issuer)),!h||!E)throw new Error("Missing private key or certificate for secure server");let R={ciphers:f.ciphers,ticketKeys:Zfe(),availableCAs:Ql,ca:t&&Array.from(Ql.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??MO(_);Array.isArray(S)||(S=[S]);for(let I of S)I===IO()&&(p+=1);let y=vT.createSecureContext(R);y.name=f.name,y.options=R,y.quality=p,y.certificateAuthorities=Array.from(Ql),y.certStart=E.toString().slice(0,100);let w;for(let I of S)if(I){I[0]==="*"&&(s=!0,I=I.slice(1)),Z1.isIP(I)&&(w=!0);let G=r.get(I)?.quality??0;Xe.trace?.("Assigning TLS for hostname",I,"if",p,">",G),p>G&&r.set(I,y)}else Xe.error?.("No hostname found for certificate at",vT.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"),DT?.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(fK,"createTLSSelector");async function mK(e){let t=bc.get(e);return!t&&e?await Wn.readFile(gr.join(Ts.get(Xl.ROOTPATH),Vs.LICENSE_KEY_DIR_NAME,e),"utf8"):t}a(mK,"getPrivateKeyByName");async function pK(){Ac();let e=[];for await(let t of an.search([]))e.push(t);return e}a(pK,"listCertificates");async function lme(e){let t=NO(e,bi.object({name:bi.string().required(),certificate:bi.string().required(),is_authority:bi.boolean().required(),private_key:bi.string(),hosts:bi.array(),uses:bi.array()}));if(t)throw new Rc(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 bc)!s&&!c&&o.checkPrivateKey(eK(h))&&(c=!0,u=p),s&&s===h&&(l=!0,u=p);if(!i&&!s&&!c)throw new Rc("A suitable private key was not found for this certificate");let d;if(!r){try{d=vO(o)}catch(p){Xe.error?.(p)}if(d==null)throw new Rc("Error extracting certificate host name, please provide a name parameter")}let f=ume(r??d);s&&!c&&!l&&(await Wn.writeFile(gr.join(Ts.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,f+".pem"),s),bc.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 uf(m),"Successfully added certificate: "+f}a(lme,"addCertificate");function ume(e){return e.replace(/[^a-z0-9\.]/gi,"-")}a(ume,"sanitizeName");async function dme(e){let t=NO(e,bi.object({name:bi.string().required()}));if(t)throw new Rc(t.message);let{name:r}=e;Ac();let n=await an.get(r);if(!n)throw new Rc(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 Wn.remove(gr.join(Ts.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,s)))}return await an.delete(r),"Successfully removed "+r}a(dme,"removeCertificate");function vO(e){let t=e.subject?.match(/CN=(.*)/)?.[1];return t||MO(e)[0]}a(vO,"getPrimaryHostName");function MO(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(MO,"hostnamesFromCert");async function fme(e){if(e.bypass_auth!==!0)throw new Rc("Unauthorized","401");let t=NO(e,bi.object({name:bi.string().required()}));if(t)throw new Rc(t.message);let{name:r}=e;if(r===".jwtPrivate")return(await z1()).privateKey;if(r===".jwtPublic")return(await z1()).publicKey;if(bc.get(r))return bc.get(e.name);throw new Rc("Key not found")}a(fme,"getKey");function mme(e){return[e.subject?.CN,...e.subjectaltname.split(",").filter(t=>t.trim().startsWith("DNS:")).map(t=>t.trim().substring(4))]}a(mme,"getHostnamesFromCertificate")});var BK={};ye(BK,{BACK_PRESSURE_RATIO_POSITION:()=>UK,CONFIRMATION_STATUS_POSITION:()=>MK,LATENCY_POSITION:()=>VT,NodeReplicationConnection:()=>ff,OPERATION_REQUEST:()=>kO,RECEIVED_TIME_POSITION:()=>qT,RECEIVED_VERSION_POSITION:()=>GT,RECEIVING_STATUS_POSITION:()=>$T,RECEIVING_STATUS_RECEIVING:()=>xK,RECEIVING_STATUS_WAITING:()=>HO,SENDING_TIME_POSITION:()=>Dh,createWebSocket:()=>KT,databaseSubscriptions:()=>wc,replicateOverWS:()=>vh,tableUpdateListeners:()=>$O});async function KT(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(!BO){let l=(0,PK.createTLSSelector)("operations-api"),u={secureContexts:null};await l.initialize(u),BO=u.secureContexts}if(i=BO.get(s),i&&ue.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,DK.isIP)(t?.serverName)?void 0:t?.serverName,noDelay:!0,highWaterMark:128*1024,rejectUnauthorized:n!==!1,secureContext:void 0};return i&&((df?.caCount!==ca.size||df?.derivedFromContext!==i)&&(df=LK.createSecureContext({...i.options,ca:[...ca,...i.options.availableCAs.values()]}),df.caCount=ca.size,df.derivedFromContext=i),c.secureContext=df),new NK.WebSocket(e,"harperdb-replication-v1",c)}function vh(e,t,r){let n=t.port||t.securePort,s=qO.pid%1e3+"-"+CK.threadId+(n?"s:"+n:"c:"+t.url?.slice(-4))+" "+Math.random().toString().slice(2,3);ue.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||wc,f,m,p=!1,h=t.subscription;h?.then&&h.then(A=>{h=A,h.auditStore&&(f=h.auditStore)});let E=t.tables||u&&ut()[u],_,R=new Map,S=[];_=r.name,_&&t.connection&&(t.connection.nodeName=_);let y,w,I,G,X,q,k,z=6e4,Y,le=0,fe=0,te=0,Se=wK.default.get(x.REPLICATION_BLOBTIMEOUT)??12e4,Ne=new Map,Ke=[],$e=0,Ir;if(t.url){let A=a(()=>{X&&fe===e._socket?.bytesRead&&te===e._socket?.bytesWritten?e.terminate():(X=performance.now(),e.ping(),fe=e._socket?.bytesRead,te=e._socket?.bytesWritten)},"sendPing");I=setInterval(A,AK).unref(),A()}else sr();e._socket?.setMaxListeners(200);function sr(){clearTimeout(G),fe=e._socket?.bytesRead,te=e._socket?.bytesWritten,G=setTimeout(()=>{fe===e._socket?.bytesRead&&te===e._socket?.bytesWritten&&(ue.warn?.(`Timeout waiting for ping from ${_}, terminating connection and reconnecting`),e.terminate())},AK*2).unref()}a(sr,"resetPingTimer");let zr=0,xr=0,Du=!1,Zc=3e4;function Ft(){if(pn?.length>0){let A=performance.now(),U=A-xr;zr=(zr*Zc+(Du?U:0))/(Zc+U),m&&(m[UK]=zr),xr=A}}a(Ft,"updateBackPressureRatio"),setInterval(Ft,Zc).unref();function Ps(){if(!(!_||!u))return m||(m=nf(f,u,_)),m}a(Ps,"getSharedStatus"),u&&el(u);let Ga,h_,mm=[],E_=[],pm,ve=[],__=[],sA=[],vu=150,Gi=25,Ls=0,hm=0,Em=!1,Bo,vn,pn,Br;e.on("message",Mu);async function Mu(A){if(r=await r,!r){ue.error?.(s,"No authorization provided"),Fr(1008,"Unauthorized");return}_m(A),e.off("message",Mu),e.on("message",_m)}a(Mu,"onWSMessageWhenAuthorized");function _m(A){le=performance.now();try{let U=A.dataView=new dl(A.buffer,A.byteOffset,A.byteLength);if(A[0]>127){let j=(0,ct.decode)(A),[J,F,he]=j;switch(J){case EK:{if(F){if(_){if(_!==F){ue.error?.(s,`Node name mismatch, expecting to connect to ${_}, but peer reported name as ${F}, disconnecting`),e.send((0,ct.encode)([Lh])),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=_),ue.debug?.(s,"received node name:",_,"db:",u??j[2]),!u)try{el(u=j[2]),u==="system"&&(Ga=Tc(t,(me,ie)=>{Va(ie)&&K(ie)}),e.on("close",()=>{Ga?.remove()}))}catch(me){ue.warn?.(s,"Error setting database",me),e.send((0,ct.encode)([Lh])),Fr(1008,me.message);return}gm()}break}case RK:{ue.debug?.(s,"Received table definitions for",F.map(me=>me.table));for(let me of F){let ie=j[2];me.database=ie;let Ce;if(Va(ie)){if(u==="system")Me[ie]?.[me.table]||(Ce=v(me,Me[ie]?.[me.table]));else{if(ie!=="data"&&!Me[ie]){ue.warn?.("Database not found",ie);return}Ce=v(me,Me[ie]?.[me.table])}f||(f=Ce?.auditStore),E||(E=ut()?.[ie])}}break}case Lh:Fr();break;case kO:try{let me=r?.replicates||r?.subscribers||r?.name;ue.debug?.("Received operation request",F,"from",_),server.operation(F,{user:r},!me).then(ie=>{ue.debug?.("Requested request from finished",_,ie),Array.isArray(ie)&&(ie={results:ie}),ie.requestId=F.requestId,e.send((0,ct.encode)([FT,ie]))},ie=>{ue.debug?.("Failed requested operation from",_,ie),e.send((0,ct.encode)([FT,{requestId:F.requestId,error:UO(ie)}]))})}catch(me){e.send((0,ct.encode)([FT,{requestId:F.requestId,error:UO(me)}]))}break;case FT:let{resolve:de,reject:_e}=R.get(F.requestId);ue.debug?.("Received completed operation request",_,F),F.error?_e(new Error(F.error)):de(F),R.delete(F.requestId);break;case xO:let re=j[3];if(!E){u?ue.error?.(s,"No database found for",u):ue.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),mm[he]={name:re,decoder:new ct.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 _K:Br=f?M1(F,f):new Map,pm=j[2],ue.debug?.(s,`Acknowledged subscription request, receiving messages for nodes: ${pm}`);break;case gK:let ge=he;sA[ge]=F;break;case yK:Ps()[MK]=F,ue.trace?.(s,"received and broadcasting committed update",F),Ps().buffer.notify();break;case TK:y=F,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),Ps(),replication_shared_status[GT]=last_sequence_id_received,replication_shared_status[qT]=Date.now(),replication_shared_status[$T]=HO;break;case kT:{let me=j[1],{fileId:ie,size:Ce,finished:Be,error:He}=me,Te=Ne.get(ie);ue.debug?.("Received blob",ie,"has stream",!!Te,"connectedToBlob",!!Te?.connectedToBlob,"length",j[2].length,"finished",Be),Te||(Te=new FO.PassThrough,Te.expectedSize=Ce,Ne.set(ie,Te)),Te.lastChunk=Date.now();let Et=j[2];Ye(Et.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(Et),Te.connectedToBlob&&Ne.delete(ie)):Te.write(Et)}catch(Ot){ue.error?.(`Error receiving blob for ${Te.recordId} from ${_} and streaming to storage`,Ot),Ne.delete(ie)}break}case SK:{let me=F,ie;try{let Ce=j[3],Be=E_[he]||(E_[he]=E[j[4]]);if(!Be)return ue.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!==hm){hm=Te;let Ot=(0,ct.decode)(He);e.send((0,ct.encode)([xO,{typedStructs:Ot.typed,structures:Ot.named},he,Be.tableName]))}let Et=Be.primaryStore.getBinaryFast(Ce);if(Et){let Ot=Be.primaryStore.decoder.decode(Et,{valueAsBuffer:!0}),Pt=dt||{};Pt.version=(0,vK.getLastVersion)(),dt&&dt[Ju]&Xr&&(Ot=Buffer.from(Ot),Km(()=>Be.primaryStore.decoder.decode(Et),S_=>qa(S_,Ce),Be.primaryStore.rootStore)),ie=(0,ct.encode)([BT,me,{value:Ot,expiresAt:Pt.expiresAt,version:Pt.version,residencyId:Pt.residencyId,nodeId:Pt.nodeId,user:Pt.user}])}else ie=(0,ct.encode)([BT,me])}catch(Ce){ie=(0,ct.encode)([BT,me,{error:Ce.message}])}e.send(ie);break}case BT:{let{resolve:me,reject:ie,tableId:Ce,key:Be}=R.get(j[1]),He=j[2];if(He?.error)ie(new Error(He.error));else if(He){let Te;ig(()=>{let Et=mm[Ce].decoder.decode(He.value);He.value=Et,He.key=Be,me(He)||Te&&setTimeout(()=>Te.forEach(rg),6e4).unref()},f?.rootStore,Et=>{let Ot=$a(Et,Be);return Te||(Te=[]),Te.push(Ot),Ot})}else me();R.delete(j[1]);break}case hK:{pn=F;let me,ie,Ce=!1;if(h){if(u!==h.databaseName&&!h.then){ue.error?.("Subscription request for wrong database",u,h.databaseName);return}}else h=d.get(u);if(ue.debug?.(s,"received subscription request for",u,"at",pn),!h){let De;h=new Promise(mt=>{ue.debug?.("Waiting for subscription to database "+u),De=mt}),h.ready=De,wc.set(u,h)}if(r.name)ie=qt().subscribe(r.name),ie.then(async De=>{me=De;for await(let mt of me){let kr=mt.value;if(!(kr?.replicates===!0||kr?.replicates?.receives||kr?.subscriptions?.some(mr=>(mr.database||mr.schema)===u&&mr.publish!==!1))){Ce=!0,Fr(1008,`Unauthorized database subscription to ${u}`);return}}},De=>{ue.error?.(s,"Error subscribing to HDB nodes",De)});else if(!(r?.role?.permission?.super_user||r.replicates)){e.send((0,ct.encode)([Lh])),Fr(1008,`Unauthorized database subscription to ${u}`);return}if(vn&&(ue.debug?.(s,"stopping previous subscription",u),vn.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},Et,Ot,Pt=1/0,S_,T_=a((De,mt)=>{if(De.type==="end_txn"){Te.txnTime&&(o[i]!==66&&ue.error?.("Invalid encoding of message"),C(9),C(Eg),O(S_=mt),bU()),i=c,Te.txnTime=0;return}let kr=De.nodeId,mr=De.tableId,Jt=Ot[mr];if(!Jt&&(Jt=Ot[mr]=He(h.tableById[mr]),!Jt))return ue.debug?.("Not subscribed to table",mr);let Rt=Jt.table,Bu=Rt.primaryStore,ii=Bu.encoder;(De.extendedType&wg||!ii.typedStructs)&&(ii._mergeStructures(ii.getStructures()),ii.typedStructs&&(ii.lastTypedStructuresLength=ii.typedStructs.length));let y_=Et[kr];if(!(y_&&y_.startTime<mt&&(!y_.endTime||y_.endTime>mt)))return HT&&ue.trace?.(s,"skipping replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",Et),AU();HT&&ue.trace?.(s,"sending replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",Et);let iA=De.version,tl=De.residencyId,oA=g_(tl,Rt),R_;if(oA&&!oA.includes(_)){let qi=g_(De.previousResidencyId,Rt);if(qi&&!qi.includes(_)&&(De.type==="put"||De.type==="patch")||Rt.getResidencyById)return AU();let rl=De.recordId;ue.trace?.(s,"sending invalidation",rl,_,"from",kr);let Sm=0;tl&&(Sm|=fl),De.previousResidencyId&&(Sm|=ml);let lA,b_=null;for(let IU in Rt.indices){if(!b_){if(lA=De.getValue(Bu,!0),!lA)break;b_={}}b_[IU]=lA[IU]}R_=pl(De.version,mr,rl,null,kr,De.user,De.type==="put"||De.type==="patch"?"invalidate":De.type,ii.encode(b_),Sm,tl,De.previousResidencyId,De.expiresAt)}function AU(){return ue.trace?.(s,"skipping audit record",De.recordId),q||(q=setTimeout(()=>{q=null,(S_||0)+bK/2<Pt&&(HT&&ue.trace?.(s,"sending skipped sequence update",Pt),e.send((0,ct.encode)([TK,Pt])))},bK).unref()),new Promise(setImmediate)}a(AU,"skipAuditRecord");let aA=ii.typedStructs,cA=ii.structures;if((aA?.length!=Jt.typed_length||cA?.length!=Jt.structure_length)&&(Jt.typed_length=aA?.length,Jt.structure_length=cA.length,ue.debug?.(s,"send table struct",Jt.typed_length,Jt.structure_length),Jt.sentName||(Jt.sentName=!0),e.send((0,ct.encode)([xO,{typedStructs:aA,structures:cA,attributes:Rt.attributes,schemaDefined:Rt.schemaDefined},mr,Jt.table.tableName]))),tl&&!__[tl]&&(e.send((0,ct.encode)([gK,oA,tl])),__[tl]=!0),Te.txnTime!==iA&&(Te.txnTime&&(HT&&ue.trace?.(s,"new txn time, sending queued txn",Te.txnTime),o[i]!==66&&ue.error?.("Invalid encoding of message"),bU()),Te.txnTime=iA,i=c,O(iA)),R_)C(R_.length),P(R_);else{let qi=De.encoded;De.extendedType&Xr&&Km(()=>De.getValue(Bu),Sm=>qa(Sm,De.recordId),Bu.rootStore);let rl=qi[0]===66?8:0;C(qi.length-rl),P(qi,rl),ue.trace?.("wrote record",De.recordId,"length:",qi.length)}if(e._socket.writableNeedDrain){let qi=performance.now();return Du=!0,Ft(),new Promise(rl=>{ue.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",()=>{rl(),Du=!1,Ft()})})}else return $e>Gi?new Promise(qi=>{Ir=qi}):new Promise(setImmediate)},"sendAuditRecord"),bU=a(()=>{c-i>8?(e.send(o.subarray(i,c)),ue.debug?.(s,"Sent message, size:",c-i),u!=="system"&&Ye(c-i,"bytes-sent",`${_}.${u}`,"replication","egress")):ue.debug?.(s,"skipping empty transaction")},"sendQueuedData");vn=new GO.EventEmitter,vn.once("close",()=>{Ce=!0,me?.end()});for(let{startTime:De}of pn)De<Pt&&(Pt=De);(ie||Promise.resolve()).then(async()=>{h=await h,f=h.auditStore,Ot=h.tableById.map(He),Et=[];for(let{name:mt,startTime:kr,endTime:mr}of pn){let Jt=CT(mt,f);ue.debug?.("subscription to",mt,"using local id",Jt,"starting",kr),Et[Jt]={startTime:kr,endTime:mr}}K(u),Ga||(Ga=Vl(mt=>{mt.databaseName===u&&K(u)}),h_=sh(mt=>{mt===u&&(e.send((0,ct.encode)([Lh])),Fr())}),e.on("close",()=>{Ga?.remove(),h_?.remove()})),e.send((0,ct.encode)([_K,Rh(h.auditStore),pn.map(({name:mt})=>mt)]));let De=!0;do{if(isFinite(Pt)||(ue.warn?.("Invalid sequence id "+Pt),Fr(1008,"Invalid sequence id"+Pt)),De&&!Ce&&(De=!1,Pt===0)){ue.info?.("Replicating all tables to",_);let mt=Date.now(),kr=YT(f);for(let mr in E){if(!He(mr))continue;let Jt=E[mr];for(let Rt of Jt.primaryStore.getRange({snapshot:!1,versions:!0})){if(Ce)return;ue.trace?.(s,"Copying record from",u,mr,Rt.key,Rt.localTime),mt=Math.max(Rt.localTime??1,mt),Ps()[Dh]=1;let Bu=pl(Rt.version,Jt.tableId,Rt.key,null,kr,null,"put",Km(()=>Jt.primaryStore.encoder.encode(Rt.value),ii=>qa(ii,Rt.key)),Rt.metadataFlags&-256,Rt.residencyId,null,Rt.expiresAt);await T_({recordId:Rt.key,tableId:Jt.tableId,type:"put",getValue(){return Rt.value},encoded:Bu,version:Rt.version,residencyId:Rt.residencyId,nodeId:kr,extendedType:Rt.metadataFlags},Rt.localTime)}}Te.txnTime||(Te.txnTime=mt,O(mt)),c-i>8&&T_({type:"end_txn"},Pt),Ps()[Dh]=0,Pt=mt}for(let{key:mt,value:kr}of f.getRange({start:Pt||1,exclusiveStart:!0,snapshot:!1})){if(Ce)return;let mr=wt(kr);ue.debug?.("sending audit record",mt,mr.recordId),Ps()[Dh]=mt,Pt=mt,await T_(mr,mt),vn.startTime=mt}c-i>8&&T_({type:"end_txn"},Pt),Ps()[Dh]=0,await vB(f)}while(!Ce)}).catch(De=>{ue.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 j=U.readInt();if(j===9&&U.getUint8(U.position)==Eg){U.position++,y=$=U.readFloat64(),m[GT]=y,m[qT]=Date.now(),m[$T]=HO,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),ue.trace?.("received remote sequence update",y,u);break}let J=U.position,F=wt(A,J,J+j),he=mm[F.tableId];he||ue.error?.(`No table found with an id of ${F.tableId}`);let de;F.residencyId&&(de=sA[F.residencyId],ue.trace?.(s,"received residency list",de,F.type,F.recordId));let _e=F.recordId;try{ig(()=>{L={table:he.name,id:F.recordId,type:F.type,nodeId:Br.get(F.nodeId),residencyList:de,timestamp:F.version,value:F.getValue(he),user:F.user,beginTxn:N,expiresAt:F.expiresAt}},f?.rootStore,re=>$a(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,ue.debug?.(s,"received replication message",F.type,"id",L.id,"version",new Date(F.version),"nodeId",L.nodeId),m[GT]=F.version,m[qT]=Date.now(),m[$T]=xK,h.send(L),U.position=J+j}while(U.position<A.byteLength);Ls++,u!=="system"&&Ye(A.byteLength,"bytes-received",`${_}.${u}.${L?.table||"unknown_table"}`,"replication","ingest"),Ls>vu&&!Em&&(Em=!0,e.pause(),ue.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 j=Date.now()-L.timestamp;u!=="system"&&Ye(j,"replication-latency",_+"."+u+"."+L.table,L.type,"ingest")}Ls--,Em&&(Em=!1,e.resume(),ue.debug?.(`Replication resuming ${_}`)),Ke.length>0&&await Promise.all(Ke),ue.trace?.("All blobs finished"),!w&&$&&(ue.trace?.(s,"queuing confirmation of a commit at",$),setTimeout(()=>{e.send((0,ct.encode)([yK,w])),ue.trace?.(s,"sent confirmation of a commit at",w),w=null},hme)),w=$,ue.debug?.("last sequence committed",new Date($),u)}})}catch(U){ue.error?.(s,"Error handling incoming replication message",U)}}a(_m,"onWSMessage"),e.on("ping",sr),e.on("pong",()=>{if(t.connection){let A=performance.now()-X;t.connection.latency=A,Ps()&&(m[VT]=A),t.isSubscriptionConnection&&Jl({name:_,database:u,url:t.url,latency:A})}X=null}),e.on("close",(A,U)=>{clearInterval(I),clearTimeout(G),clearInterval(k),vn&&vn.emit("close"),Bo&&Bo.end();for(let[N,{reject:L}]of R)L(new Error(`Connection closed ${U?.toString()} ${A}`));ue.debug?.(s,"closed",A,U?.toString())});function Fr(A,U){try{e.isFinished=!0,ue.debug?.(s,"closing",_,u,A,U),e.close(A,U),t.connection?.emit("finished")}catch(N){ue.error?.(s,"Error closing connection",N)}}a(Fr,"close");let Uu=new Set;async function qa(A,U){let N=ng(A);if(Uu.has(N)){ue.debug?.("Blob already being sent",N);return}Uu.add(N);try{let L;$e++;for await(let $ of A.stream())L&&(ue.debug?.("Sending blob chunk",N,"length",L.length),e.send((0,ct.encode)([kT,{fileId:N,size:A.size},L]))),L=$,e._socket.writableNeedDrain&&(ue.debug?.("draining",N),await new Promise(j=>e._socket.once("drain",j)),ue.debug?.("drained",N)),Ye($.length,"bytes-sent",`${_}.${u}`,"replication","blob");ue.debug?.("Sending final blob chunk",N,"length",L.length),e.send((0,ct.encode)([kT,{fileId:N,size:A.size,finished:!0},L]))}catch(L){ue.warn?.("Error sending blob",L,"blob id",N,"for record",U),e.send((0,ct.encode)([kT,{fileId:N,finished:!0,error:UO(L)},Buffer.alloc(0)]))}finally{Uu.delete(N),$e--,$e<Gi&&Ir?.()}}a(qa,"sendBlobs");function $a(A,U){let N=ng(A),L=Ne.get(N);ue.debug?.("Received transaction with blob",N,"has stream",!!L,"ended",!!L?.writableEnded),L?L.writableEnded&&Ne.delete(N):(L=new FO.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 j=Yo(()=>Vm($).saving,h.auditStore?.rootStore);return j&&(j.blobId=N,Ke.push(j),j.finally(()=>{ue.debug?.(`Finished receiving blob stream ${N}`),Ke.splice(Ke.indexOf(j),1)})),$}a($a,"receiveBlobs");function gm(){if(p||(p=!0,t.connection?.on("subscriptions-updated",gm)),!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 j=[],{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&&j.push(re)}J=!1}else for(let _e in E)(J?E[_e].replicate===!1:E[_e].replicate)&&j.push(_e);let F=f&&CT(L.name,f),he=h?.dbisDB?.get([Symbol.for("seq"),F])??1,de=Math.max(he?.seqId??1,(typeof L.startTime=="string"?new Date(L.startTime).getTime():L.startTime)??1);if(ue.debug?.("Starting time recorded in db",L.name,F,u,he?.seqId,"start time:",de,new Date(de)),U!==L){let _e=f&&CT(U.name,f),re=h?.dbisDB?.get([Symbol.for("seq"),_e])??1;for(let oe of re?.nodes||[])oe.name===L.name&&(de=oe.seqId,ue.debug?.("Using sequence id from proxy node",U.name,de))}return F===void 0?ue.warn("Starting subscription request from node",L,"but no node id found"):S.push(F),A.get(F)>de&&(de=A.get(F),ue.debug?.("Updating start time from more recent txn recorded",U.name,de)),de===1&&(L.isLeader?(ue.warn?.(`Requesting full copy of database ${u} from ${L.url}`),de=0):de=Date.now()-6e4),ue.trace?.(s,"defining subscription request",L.name,u,new Date(de)),{name:L.name,replicateByDefault:J,tables:j,startTime:de,isLeader:L.isLeader,endTime:L.endTime}});if(N)if(ue.debug?.(s,"sending subscription request",N,h?.dbisDB?.path),clearTimeout(Y),N.length>0)e.send((0,ct.encode)([hK,N]));else{let L=a(()=>{let $=performance.now();Y=setTimeout(()=>{le<=$?Fr(1008,"Connection has no subscriptions and is no longer used"):L()},z).unref()},"scheduleClose");L()}}a(gm,"sendSubscriptionRequestUpdate");function g_(A,U){if(!A)return;let N=ve[A];return N||(N=U.getResidencyRecord(A),ve[A]=N),N}a(g_,"getResidence");function Va(A){return!(Ic&&Ic!="*"&&!Ic[A]&&!Ic.includes?.(A)&&!Ic.some?.(U=>U.name===A))}a(Va,"checkDatabaseAccess");function el(A){if(h=h||d.get(A),!Va(A))throw new Error(`Access to database "${A}" is not permitted`);h||ue.warn?.(`No database named "${A}" was declared and registered`),f=h?.auditStore,E||(E=ut()?.[A]);let U=nt();if(U===_)throw U?new Error("Should not connect to self",U):new Error("Node name not defined");return xu(U,A),!0}a(el,"setDatabase");function xu(A,U){let N=ut()?.[U],L=[];for(let $ in N){let j=N[$];L.push({table:$,schemaDefined:j.schemaDefined,attributes:j.attributes.map(J=>({name:J.name,type:J.type,isPrimaryKey:J.isPrimaryKey}))})}ue.trace?.("Sending database info for node",A,"database name",U),e.send((0,ct.encode)([EK,A,U,L]))}a(xu,"sendNodeDBName");function K(A){let U=ut()?.[A],N=[];for(let L in U){if(pn&&!pn.some(j=>j.replicateByDefault?!j.tables.includes(L):j.tables.includes(L)))continue;let $=U[L];N.push({table:L,schemaDefined:$.schemaDefined,attributes:$.attributes.map(j=>({name:j.name,type:j.type,isPrimaryKey:j.isPrimaryKey}))})}e.send((0,ct.encode)([RK,N,A]))}a(K,"sendDBSchema"),k=setInterval(()=>{for(let[A,U]of Ne)U.lastChunk+Se<Date.now()&&(ue.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(){Bo&&Bo.end(),vn&&vn.emit("close")},getRecord(A){let U=g++;return new Promise((N,L)=>{let $=[SK,U,A.table.tableId,A.id];T[A.table.tableId]||($.push(A.table.tableName),T[A.table.tableId]=!0),e.send((0,ct.encode)($)),le=performance.now(),R.set(U,{tableId:A.table.tableId,key:A.id,resolve(j){let{table:J,entry:F}=A;if(N(j),j)return J._recordRelocate(F,j)},reject:L})})},sendOperation(A){let U=g++;return A.requestId=U,e.send((0,ct.encode)([kO,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,j=A.schemaDefined,J=U.attributes||[];for(let F=0;F<A.attributes?.length;F++){let he=A.attributes[F],de=J.find(_e=>_e.name===he.name);(!de||de.type!==he.type)&&(L?ue.error?.(`Schema for '${u}.${A.table}' is defined locally, but attribute '${he.name}: ${he.type}' from '${_}' does not match local attribute ${de?"'"+de.name+": "+de.type+"'":"which does not exist"}`):($=!0,j||(he.indexed=!0),de?J[J.indexOf(de)]=he:J.push(he)))}return $?(ue.debug?.("(Re)creating",A),ze({table:A.table,database:A.database,schemaDefined:A.schemaDefined,attributes:J,...U})):U}}var wK,ct,NK,CK,OK,GO,PK,LK,qO,DK,FO,vK,pme,UO,ue,hK,EK,_K,Lh,gK,xO,SK,BT,kO,FT,TK,yK,RK,kT,MK,GT,qT,Dh,VT,$T,UK,HO,xK,$O,wc,HT,bK,hme,AK,BO,df,IK,ff,VO=se(()=>{Oe();Vi();yO();FI();Ss();wK=b(ce());H();hl();ct=require("msgpackr"),NK=require("ws"),CK=require("worker_threads"),OK=b(Q());Ch();GO=require("events"),PK=b(ys()),LK=b(require("node:tls"));of();qO=b(require("node:process")),DK=require("node:net");is();ss();FO=require("node:stream"),vK=require("lmdb"),{forComponent:pme,errorToString:UO}=OK.default,ue=pme("replication").conditional,hK=129,EK=140,_K=141,Lh=142,gK=130,xO=132,SK=133,BT=134,kO=136,FT=137,TK=143,yK=144,RK=145,kT=146,MK=0,GT=1,qT=2,Dh=3,VT=4,$T=5,UK=6,HO=0,xK=1,$O=new Map,wc=new Map,HT=!0,bK=300,hme=2,AK=3e4;a(KT,"createWebSocket");IK=500,ff=class extends GO.EventEmitter{static{a(this,"NodeReplicationConnection")}socket;startTime;retryTime=IK;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??Ri(t)}async connect(){this.session||this.resetSession();let t=[];this.socket=await KT(this.url,{serverName:this.nodeName,authorization:this.authorization});let r;ue.debug?.(`Connecting to ${this.url}, db: ${this.databaseName}, process ${qO.pid}`),this.socket.on("open",()=>{this.socket._socket.unref(),ue[this.isConnected?"info":"warn"]?.(`Connected to ${this.url}, db: ${this.databaseName}`),this.retries=0,this.retryTime=IK,this.nodeSubscriptions&&Jl({name:this.nodeName,database:this.databaseName,url:this.url}),this.isConnected=!0,r=vh(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"?(ue.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"?ue.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`):ue.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&&cf({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();ue.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(vh,"replicateOverWS")});function Nc(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
|
+
`+Ql.get(_.issuer)),!h||!E)throw new Error("Missing private key or certificate for secure server");let R={ciphers:f.ciphers,ticketKeys:Zfe(),availableCAs:Ql,ca:t&&Array.from(Ql.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??MO(_);Array.isArray(S)||(S=[S]);for(let I of S)I===IO()&&(p+=1);let y=vT.createSecureContext(R);y.name=f.name,y.options=R,y.quality=p,y.certificateAuthorities=Array.from(Ql),y.certStart=E.toString().slice(0,100);let w;for(let I of S)if(I){I[0]==="*"&&(s=!0,I=I.slice(1)),Z1.isIP(I)&&(w=!0);let G=r.get(I)?.quality??0;Xe.trace?.("Assigning TLS for hostname",I,"if",p,">",G),p>G&&r.set(I,y)}else Xe.error?.("No hostname found for certificate at",vT.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"),DT?.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(fK,"createTLSSelector");async function mK(e){let t=bc.get(e);return!t&&e?await Wn.readFile(gr.join(Ts.get(Xl.ROOTPATH),Vs.LICENSE_KEY_DIR_NAME,e),"utf8"):t}a(mK,"getPrivateKeyByName");async function pK(){Ac();let e=[];for await(let t of an.search([]))e.push(t);return e}a(pK,"listCertificates");async function lme(e){let t=NO(e,bi.object({name:bi.string().required(),certificate:bi.string().required(),is_authority:bi.boolean().required(),private_key:bi.string(),hosts:bi.array(),uses:bi.array()}));if(t)throw new Rc(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 bc)!s&&!c&&o.checkPrivateKey(eK(h))&&(c=!0,u=p),s&&s===h&&(l=!0,u=p);if(!i&&!s&&!c)throw new Rc("A suitable private key was not found for this certificate");let d;if(!r){try{d=vO(o)}catch(p){Xe.error?.(p)}if(d==null)throw new Rc("Error extracting certificate host name, please provide a name parameter")}let f=ume(r??d);s&&!c&&!l&&(await Wn.writeFile(gr.join(Ts.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,f+".pem"),s),bc.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 uf(m),"Successfully added certificate: "+f}a(lme,"addCertificate");function ume(e){return e.replace(/[^a-z0-9\.]/gi,"-")}a(ume,"sanitizeName");async function dme(e){let t=NO(e,bi.object({name:bi.string().required()}));if(t)throw new Rc(t.message);let{name:r}=e;Ac();let n=await an.get(r);if(!n)throw new Rc(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 Wn.remove(gr.join(Ts.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,s)))}return await an.delete(r),"Successfully removed "+r}a(dme,"removeCertificate");function vO(e){let t=e.subject?.match(/CN=(.*)/)?.[1];return t||MO(e)[0]}a(vO,"getPrimaryHostName");function MO(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(MO,"hostnamesFromCert");async function fme(e){if(e.bypass_auth!==!0)throw new Rc("Unauthorized","401");let t=NO(e,bi.object({name:bi.string().required()}));if(t)throw new Rc(t.message);let{name:r}=e;if(r===".jwtPrivate")return(await z1()).privateKey;if(r===".jwtPublic")return(await z1()).publicKey;if(bc.get(r))return bc.get(e.name);throw new Rc("Key not found")}a(fme,"getKey");function mme(e){return[e.subject?.CN,...e.subjectaltname.split(",").filter(t=>t.trim().startsWith("DNS:")).map(t=>t.trim().substring(4))]}a(mme,"getHostnamesFromCertificate")});var BK={};ye(BK,{BACK_PRESSURE_RATIO_POSITION:()=>UK,CONFIRMATION_STATUS_POSITION:()=>MK,LATENCY_POSITION:()=>VT,NodeReplicationConnection:()=>ff,OPERATION_REQUEST:()=>kO,RECEIVED_TIME_POSITION:()=>qT,RECEIVED_VERSION_POSITION:()=>GT,RECEIVING_STATUS_POSITION:()=>$T,RECEIVING_STATUS_RECEIVING:()=>xK,RECEIVING_STATUS_WAITING:()=>HO,SENDING_TIME_POSITION:()=>Dh,createWebSocket:()=>KT,databaseSubscriptions:()=>wc,replicateOverWS:()=>vh,tableUpdateListeners:()=>$O});async function KT(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(!BO){let l=(0,PK.createTLSSelector)("operations-api"),u={secureContexts:null};await l.initialize(u),BO=u.secureContexts}if(i=BO.get(s),i&&ue.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,DK.isIP)(t?.serverName)?void 0:t?.serverName,noDelay:!0,highWaterMark:128*1024,rejectUnauthorized:n!==!1,secureContext:void 0};return i&&((df?.caCount!==ca.size||df?.derivedFromContext!==i)&&(df=LK.createSecureContext({...i.options,ca:[...ca,...i.options.availableCAs.values()]}),df.caCount=ca.size,df.derivedFromContext=i),c.secureContext=df),new NK.WebSocket(e,"harperdb-replication-v1",c)}function vh(e,t,r){let n=t.port||t.securePort,s=qO.pid%1e3+"-"+CK.threadId+(n?"s:"+n:"c:"+t.url?.slice(-4))+" "+Math.random().toString().slice(2,3);ue.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||wc,f,m,p=!1,h=t.subscription;h?.then&&h.then(A=>{h=A,h.auditStore&&(f=h.auditStore)});let E=t.tables||u&&ut()[u],_,R=new Map,S=[];_=r.name,_&&t.connection&&(t.connection.nodeName=_);let y,w,I,G,X,q,k,z=6e4,Y,le=0,fe=0,te=0,Se=wK.default.get(x.REPLICATION_BLOBTIMEOUT)??12e4,Ne=new Map,Ke=[],$e=0,Ir;if(t.url){let A=a(()=>{X&&fe===e._socket?.bytesRead&&te===e._socket?.bytesWritten?e.terminate():(X=performance.now(),e.ping(),fe=e._socket?.bytesRead,te=e._socket?.bytesWritten)},"sendPing");I=setInterval(A,AK).unref(),A()}else sr();e._socket?.setMaxListeners(200);function sr(){clearTimeout(G),fe=e._socket?.bytesRead,te=e._socket?.bytesWritten,G=setTimeout(()=>{fe===e._socket?.bytesRead&&te===e._socket?.bytesWritten&&(ue.warn?.(`Timeout waiting for ping from ${_}, terminating connection and reconnecting`),e.terminate())},AK*2).unref()}a(sr,"resetPingTimer");let zr=0,xr=0,Du=!1,Zc=3e4;function Ft(){if(pn?.length>0){let A=performance.now(),U=A-xr;zr=(zr*Zc+(Du?U:0))/(Zc+U),m&&(m[UK]=zr),xr=A}}a(Ft,"updateBackPressureRatio"),setInterval(Ft,Zc).unref();function Ps(){if(!(!_||!u))return m||(m=nf(f,u,_)),m}a(Ps,"getSharedStatus"),u&&el(u);let Ga,h_,mm=[],E_=[],pm,ve=[],__=[],sA=[],vu=150,Gi=25,Ls=0,hm=0,Em=!1,Bo,vn,pn,Br;e.on("message",Mu);async function Mu(A){if(r=await r,!r){ue.error?.(s,"No authorization provided"),Fr(1008,"Unauthorized");return}_m(A),e.off("message",Mu),e.on("message",_m)}a(Mu,"onWSMessageWhenAuthorized");function _m(A){le=performance.now();try{let U=A.dataView=new dl(A.buffer,A.byteOffset,A.byteLength);if(A[0]>127){let j=(0,ct.decode)(A),[J,F,he]=j;switch(J){case EK:{if(F){if(_){if(_!==F){ue.error?.(s,`Node name mismatch, expecting to connect to ${_}, but peer reported name as ${F}, disconnecting`),e.send((0,ct.encode)([Lh])),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=_),ue.debug?.(s,"received node name:",_,"db:",u??j[2]),!u)try{el(u=j[2]),u==="system"&&(Ga=Tc(t,(me,ie)=>{Va(ie)&&K(ie)}),e.on("close",()=>{Ga?.remove()}))}catch(me){ue.warn?.(s,"Error setting database",me),e.send((0,ct.encode)([Lh])),Fr(1008,me.message);return}gm()}break}case RK:{ue.debug?.(s,"Received table definitions for",F.map(me=>me.table));for(let me of F){let ie=j[2];me.database=ie;let Ce;if(Va(ie)){if(u==="system")Me[ie]?.[me.table]||(Ce=v(me,Me[ie]?.[me.table]));else{if(ie!=="data"&&!Me[ie]){ue.warn?.("Database not found",ie);return}Ce=v(me,Me[ie]?.[me.table])}f||(f=Ce?.auditStore),E||(E=ut()?.[ie])}}break}case Lh:Fr();break;case kO:try{let me=r?.replicates||r?.subscribers||r?.name;ue.debug?.("Received operation request",F,"from",_),server.operation(F,{user:r},!me).then(ie=>{ue.debug?.("Requested request from finished",_,ie),Array.isArray(ie)&&(ie={results:ie}),ie.requestId=F.requestId,e.send((0,ct.encode)([FT,ie]))},ie=>{ue.debug?.("Failed requested operation from",_,ie),e.send((0,ct.encode)([FT,{requestId:F.requestId,error:UO(ie)}]))})}catch(me){e.send((0,ct.encode)([FT,{requestId:F.requestId,error:UO(me)}]))}break;case FT:let{resolve:de,reject:_e}=R.get(F.requestId);ue.debug?.("Received completed operation request",_,F),F.error?_e(new Error(F.error)):de(F),R.delete(F.requestId);break;case xO:let re=j[3];if(!E){u?ue.error?.(s,"No database found for",u):ue.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),mm[he]={name:re,decoder:new ct.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 _K:Br=f?M1(F,f):new Map,pm=j[2],ue.debug?.(s,`Acknowledged subscription request, receiving messages for nodes: ${pm}`);break;case gK:let ge=he;sA[ge]=F;break;case yK:Ps()[MK]=F,ue.trace?.(s,"received and broadcasting committed update",F),Ps().buffer.notify();break;case TK:y=F,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),Ps(),m[GT]=last_sequence_id_received,m[qT]=Date.now(),m[$T]=HO;break;case kT:{let me=j[1],{fileId:ie,size:Ce,finished:Be,error:He}=me,Te=Ne.get(ie);ue.debug?.("Received blob",ie,"has stream",!!Te,"connectedToBlob",!!Te?.connectedToBlob,"length",j[2].length,"finished",Be),Te||(Te=new FO.PassThrough,Te.expectedSize=Ce,Ne.set(ie,Te)),Te.lastChunk=Date.now();let Et=j[2];Ye(Et.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(Et),Te.connectedToBlob&&Ne.delete(ie)):Te.write(Et)}catch(Ot){ue.error?.(`Error receiving blob for ${Te.recordId} from ${_} and streaming to storage`,Ot),Ne.delete(ie)}break}case SK:{let me=F,ie;try{let Ce=j[3],Be=E_[he]||(E_[he]=E[j[4]]);if(!Be)return ue.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!==hm){hm=Te;let Ot=(0,ct.decode)(He);e.send((0,ct.encode)([xO,{typedStructs:Ot.typed,structures:Ot.named},he,Be.tableName]))}let Et=Be.primaryStore.getBinaryFast(Ce);if(Et){let Ot=Be.primaryStore.decoder.decode(Et,{valueAsBuffer:!0}),Pt=dt||{};Pt.version=(0,vK.getLastVersion)(),dt&&dt[Ju]&Xr&&(Ot=Buffer.from(Ot),Km(()=>Be.primaryStore.decoder.decode(Et),S_=>qa(S_,Ce),Be.primaryStore.rootStore)),ie=(0,ct.encode)([BT,me,{value:Ot,expiresAt:Pt.expiresAt,version:Pt.version,residencyId:Pt.residencyId,nodeId:Pt.nodeId,user:Pt.user}])}else ie=(0,ct.encode)([BT,me])}catch(Ce){ie=(0,ct.encode)([BT,me,{error:Ce.message}])}e.send(ie);break}case BT:{let{resolve:me,reject:ie,tableId:Ce,key:Be}=R.get(j[1]),He=j[2];if(He?.error)ie(new Error(He.error));else if(He){let Te;ig(()=>{let Et=mm[Ce].decoder.decode(He.value);He.value=Et,He.key=Be,me(He)||Te&&setTimeout(()=>Te.forEach(rg),6e4).unref()},f?.rootStore,Et=>{let Ot=$a(Et,Be);return Te||(Te=[]),Te.push(Ot),Ot})}else me();R.delete(j[1]);break}case hK:{pn=F;let me,ie,Ce=!1;if(h){if(u!==h.databaseName&&!h.then){ue.error?.("Subscription request for wrong database",u,h.databaseName);return}}else h=d.get(u);if(ue.debug?.(s,"received subscription request for",u,"at",pn),!h){let De;h=new Promise(mt=>{ue.debug?.("Waiting for subscription to database "+u),De=mt}),h.ready=De,wc.set(u,h)}if(r.name)ie=qt().subscribe(r.name),ie.then(async De=>{me=De;for await(let mt of me){let kr=mt.value;if(!(kr?.replicates===!0||kr?.replicates?.receives||kr?.subscriptions?.some(mr=>(mr.database||mr.schema)===u&&mr.publish!==!1))){Ce=!0,Fr(1008,`Unauthorized database subscription to ${u}`);return}}},De=>{ue.error?.(s,"Error subscribing to HDB nodes",De)});else if(!(r?.role?.permission?.super_user||r.replicates)){e.send((0,ct.encode)([Lh])),Fr(1008,`Unauthorized database subscription to ${u}`);return}if(vn&&(ue.debug?.(s,"stopping previous subscription",u),vn.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},Et,Ot,Pt=1/0,S_,T_=a((De,mt)=>{if(De.type==="end_txn"){Te.txnTime&&(o[i]!==66&&ue.error?.("Invalid encoding of message"),C(9),C(Eg),O(S_=mt),bU()),i=c,Te.txnTime=0;return}let kr=De.nodeId,mr=De.tableId,Jt=Ot[mr];if(!Jt&&(Jt=Ot[mr]=He(h.tableById[mr]),!Jt))return ue.debug?.("Not subscribed to table",mr);let Rt=Jt.table,Bu=Rt.primaryStore,ii=Bu.encoder;(De.extendedType&wg||!ii.typedStructs)&&(ii._mergeStructures(ii.getStructures()),ii.typedStructs&&(ii.lastTypedStructuresLength=ii.typedStructs.length));let y_=Et[kr];if(!(y_&&y_.startTime<mt&&(!y_.endTime||y_.endTime>mt)))return HT&&ue.trace?.(s,"skipping replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",Et),AU();HT&&ue.trace?.(s,"sending replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",Et);let iA=De.version,tl=De.residencyId,oA=g_(tl,Rt),R_;if(oA&&!oA.includes(_)){let qi=g_(De.previousResidencyId,Rt);if(qi&&!qi.includes(_)&&(De.type==="put"||De.type==="patch")||Rt.getResidencyById)return AU();let rl=De.recordId;ue.trace?.(s,"sending invalidation",rl,_,"from",kr);let Sm=0;tl&&(Sm|=fl),De.previousResidencyId&&(Sm|=ml);let lA,b_=null;for(let IU in Rt.indices){if(!b_){if(lA=De.getValue(Bu,!0),!lA)break;b_={}}b_[IU]=lA[IU]}R_=pl(De.version,mr,rl,null,kr,De.user,De.type==="put"||De.type==="patch"?"invalidate":De.type,ii.encode(b_),Sm,tl,De.previousResidencyId,De.expiresAt)}function AU(){return ue.trace?.(s,"skipping audit record",De.recordId),q||(q=setTimeout(()=>{q=null,(S_||0)+bK/2<Pt&&(HT&&ue.trace?.(s,"sending skipped sequence update",Pt),e.send((0,ct.encode)([TK,Pt])))},bK).unref()),new Promise(setImmediate)}a(AU,"skipAuditRecord");let aA=ii.typedStructs,cA=ii.structures;if((aA?.length!=Jt.typed_length||cA?.length!=Jt.structure_length)&&(Jt.typed_length=aA?.length,Jt.structure_length=cA.length,ue.debug?.(s,"send table struct",Jt.typed_length,Jt.structure_length),Jt.sentName||(Jt.sentName=!0),e.send((0,ct.encode)([xO,{typedStructs:aA,structures:cA,attributes:Rt.attributes,schemaDefined:Rt.schemaDefined},mr,Jt.table.tableName]))),tl&&!__[tl]&&(e.send((0,ct.encode)([gK,oA,tl])),__[tl]=!0),Te.txnTime!==iA&&(Te.txnTime&&(HT&&ue.trace?.(s,"new txn time, sending queued txn",Te.txnTime),o[i]!==66&&ue.error?.("Invalid encoding of message"),bU()),Te.txnTime=iA,i=c,O(iA)),R_)C(R_.length),P(R_);else{let qi=De.encoded;De.extendedType&Xr&&Km(()=>De.getValue(Bu),Sm=>qa(Sm,De.recordId),Bu.rootStore);let rl=qi[0]===66?8:0;C(qi.length-rl),P(qi,rl),ue.trace?.("wrote record",De.recordId,"length:",qi.length)}if(e._socket.writableNeedDrain){let qi=performance.now();return Du=!0,Ft(),new Promise(rl=>{ue.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",()=>{rl(),Du=!1,Ft()})})}else return $e>Gi?new Promise(qi=>{Ir=qi}):new Promise(setImmediate)},"sendAuditRecord"),bU=a(()=>{c-i>8?(e.send(o.subarray(i,c)),ue.debug?.(s,"Sent message, size:",c-i),u!=="system"&&Ye(c-i,"bytes-sent",`${_}.${u}`,"replication","egress")):ue.debug?.(s,"skipping empty transaction")},"sendQueuedData");vn=new GO.EventEmitter,vn.once("close",()=>{Ce=!0,me?.end()});for(let{startTime:De}of pn)De<Pt&&(Pt=De);(ie||Promise.resolve()).then(async()=>{h=await h,f=h.auditStore,Ot=h.tableById.map(He),Et=[];for(let{name:mt,startTime:kr,endTime:mr}of pn){let Jt=CT(mt,f);ue.debug?.("subscription to",mt,"using local id",Jt,"starting",kr),Et[Jt]={startTime:kr,endTime:mr}}K(u),Ga||(Ga=Vl(mt=>{mt.databaseName===u&&K(u)}),h_=sh(mt=>{mt===u&&(e.send((0,ct.encode)([Lh])),Fr())}),e.on("close",()=>{Ga?.remove(),h_?.remove()})),e.send((0,ct.encode)([_K,Rh(h.auditStore),pn.map(({name:mt})=>mt)]));let De=!0;do{if(isFinite(Pt)||(ue.warn?.("Invalid sequence id "+Pt),Fr(1008,"Invalid sequence id"+Pt)),De&&!Ce&&(De=!1,Pt===0)){ue.info?.("Replicating all tables to",_);let mt=Date.now(),kr=YT(f);for(let mr in E){if(!He(mr))continue;let Jt=E[mr];for(let Rt of Jt.primaryStore.getRange({snapshot:!1,versions:!0})){if(Ce)return;ue.trace?.(s,"Copying record from",u,mr,Rt.key,Rt.localTime),mt=Math.max(Rt.localTime??1,mt),Ps()[Dh]=1;let Bu=pl(Rt.version,Jt.tableId,Rt.key,null,kr,null,"put",Km(()=>Jt.primaryStore.encoder.encode(Rt.value),ii=>qa(ii,Rt.key)),Rt.metadataFlags&-256,Rt.residencyId,null,Rt.expiresAt);await T_({recordId:Rt.key,tableId:Jt.tableId,type:"put",getValue(){return Rt.value},encoded:Bu,version:Rt.version,residencyId:Rt.residencyId,nodeId:kr,extendedType:Rt.metadataFlags},Rt.localTime)}}Te.txnTime||(Te.txnTime=mt,O(mt)),c-i>8&&T_({type:"end_txn"},Pt),Ps()[Dh]=0,Pt=mt}for(let{key:mt,value:kr}of f.getRange({start:Pt||1,exclusiveStart:!0,snapshot:!1})){if(Ce)return;let mr=wt(kr);ue.debug?.("sending audit record",mt,mr.recordId),Ps()[Dh]=mt,Pt=mt,await T_(mr,mt),vn.startTime=mt}c-i>8&&T_({type:"end_txn"},Pt),Ps()[Dh]=0,await vB(f)}while(!Ce)}).catch(De=>{ue.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 j=U.readInt();if(j===9&&U.getUint8(U.position)==Eg){U.position++,y=$=U.readFloat64(),m[GT]=y,m[qT]=Date.now(),m[$T]=HO,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),ue.trace?.("received remote sequence update",y,u);break}let J=U.position,F=wt(A,J,J+j),he=mm[F.tableId];he||ue.error?.(`No table found with an id of ${F.tableId}`);let de;F.residencyId&&(de=sA[F.residencyId],ue.trace?.(s,"received residency list",de,F.type,F.recordId));let _e=F.recordId;try{ig(()=>{L={table:he.name,id:F.recordId,type:F.type,nodeId:Br.get(F.nodeId),residencyList:de,timestamp:F.version,value:F.getValue(he),user:F.user,beginTxn:N,expiresAt:F.expiresAt}},f?.rootStore,re=>$a(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,ue.debug?.(s,"received replication message",F.type,"id",L.id,"version",new Date(F.version),"nodeId",L.nodeId),m[GT]=F.version,m[qT]=Date.now(),m[$T]=xK,h.send(L),U.position=J+j}while(U.position<A.byteLength);Ls++,u!=="system"&&Ye(A.byteLength,"bytes-received",`${_}.${u}.${L?.table||"unknown_table"}`,"replication","ingest"),Ls>vu&&!Em&&(Em=!0,e.pause(),ue.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 j=Date.now()-L.timestamp;u!=="system"&&Ye(j,"replication-latency",_+"."+u+"."+L.table,L.type,"ingest")}Ls--,Em&&(Em=!1,e.resume(),ue.debug?.(`Replication resuming ${_}`)),Ke.length>0&&await Promise.all(Ke),ue.trace?.("All blobs finished"),!w&&$&&(ue.trace?.(s,"queuing confirmation of a commit at",$),setTimeout(()=>{e.send((0,ct.encode)([yK,w])),ue.trace?.(s,"sent confirmation of a commit at",w),w=null},hme)),w=$,ue.debug?.("last sequence committed",new Date($),u)}})}catch(U){ue.error?.(s,"Error handling incoming replication message",U)}}a(_m,"onWSMessage"),e.on("ping",sr),e.on("pong",()=>{if(t.connection){let A=performance.now()-X;t.connection.latency=A,Ps()&&(m[VT]=A),t.isSubscriptionConnection&&Jl({name:_,database:u,url:t.url,latency:A})}X=null}),e.on("close",(A,U)=>{clearInterval(I),clearTimeout(G),clearInterval(k),vn&&vn.emit("close"),Bo&&Bo.end();for(let[N,{reject:L}]of R)L(new Error(`Connection closed ${U?.toString()} ${A}`));ue.debug?.(s,"closed",A,U?.toString())});function Fr(A,U){try{e.isFinished=!0,ue.debug?.(s,"closing",_,u,A,U),e.close(A,U),t.connection?.emit("finished")}catch(N){ue.error?.(s,"Error closing connection",N)}}a(Fr,"close");let Uu=new Set;async function qa(A,U){let N=ng(A);if(Uu.has(N)){ue.debug?.("Blob already being sent",N);return}Uu.add(N);try{let L;$e++;for await(let $ of A.stream())L&&(ue.debug?.("Sending blob chunk",N,"length",L.length),e.send((0,ct.encode)([kT,{fileId:N,size:A.size},L]))),L=$,e._socket.writableNeedDrain&&(ue.debug?.("draining",N),await new Promise(j=>e._socket.once("drain",j)),ue.debug?.("drained",N)),Ye($.length,"bytes-sent",`${_}.${u}`,"replication","blob");ue.debug?.("Sending final blob chunk",N,"length",L.length),e.send((0,ct.encode)([kT,{fileId:N,size:A.size,finished:!0},L]))}catch(L){ue.warn?.("Error sending blob",L,"blob id",N,"for record",U),e.send((0,ct.encode)([kT,{fileId:N,finished:!0,error:UO(L)},Buffer.alloc(0)]))}finally{Uu.delete(N),$e--,$e<Gi&&Ir?.()}}a(qa,"sendBlobs");function $a(A,U){let N=ng(A),L=Ne.get(N);ue.debug?.("Received transaction with blob",N,"has stream",!!L,"ended",!!L?.writableEnded),L?L.writableEnded&&Ne.delete(N):(L=new FO.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 j=Yo(()=>Vm($).saving,h.auditStore?.rootStore);return j&&(j.blobId=N,Ke.push(j),j.finally(()=>{ue.debug?.(`Finished receiving blob stream ${N}`),Ke.splice(Ke.indexOf(j),1)})),$}a($a,"receiveBlobs");function gm(){if(p||(p=!0,t.connection?.on("subscriptions-updated",gm)),!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 j=[],{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&&j.push(re)}J=!1}else for(let _e in E)(J?E[_e].replicate===!1:E[_e].replicate)&&j.push(_e);let F=f&&CT(L.name,f),he=h?.dbisDB?.get([Symbol.for("seq"),F])??1,de=Math.max(he?.seqId??1,(typeof L.startTime=="string"?new Date(L.startTime).getTime():L.startTime)??1);if(ue.debug?.("Starting time recorded in db",L.name,F,u,he?.seqId,"start time:",de,new Date(de)),U!==L){let _e=f&&CT(U.name,f),re=h?.dbisDB?.get([Symbol.for("seq"),_e])??1;for(let oe of re?.nodes||[])oe.name===L.name&&(de=oe.seqId,ue.debug?.("Using sequence id from proxy node",U.name,de))}return F===void 0?ue.warn("Starting subscription request from node",L,"but no node id found"):S.push(F),A.get(F)>de&&(de=A.get(F),ue.debug?.("Updating start time from more recent txn recorded",U.name,de)),de===1&&(L.isLeader?(ue.warn?.(`Requesting full copy of database ${u} from ${L.url}`),de=0):de=Date.now()-6e4),ue.trace?.(s,"defining subscription request",L.name,u,new Date(de)),{name:L.name,replicateByDefault:J,tables:j,startTime:de,isLeader:L.isLeader,endTime:L.endTime}});if(N)if(ue.debug?.(s,"sending subscription request",N,h?.dbisDB?.path),clearTimeout(Y),N.length>0)e.send((0,ct.encode)([hK,N]));else{let L=a(()=>{let $=performance.now();Y=setTimeout(()=>{le<=$?Fr(1008,"Connection has no subscriptions and is no longer used"):L()},z).unref()},"scheduleClose");L()}}a(gm,"sendSubscriptionRequestUpdate");function g_(A,U){if(!A)return;let N=ve[A];return N||(N=U.getResidencyRecord(A),ve[A]=N),N}a(g_,"getResidence");function Va(A){return!(Ic&&Ic!="*"&&!Ic[A]&&!Ic.includes?.(A)&&!Ic.some?.(U=>U.name===A))}a(Va,"checkDatabaseAccess");function el(A){if(h=h||d.get(A),!Va(A))throw new Error(`Access to database "${A}" is not permitted`);h||ue.warn?.(`No database named "${A}" was declared and registered`),f=h?.auditStore,E||(E=ut()?.[A]);let U=nt();if(U===_)throw U?new Error("Should not connect to self",U):new Error("Node name not defined");return xu(U,A),!0}a(el,"setDatabase");function xu(A,U){let N=ut()?.[U],L=[];for(let $ in N){let j=N[$];L.push({table:$,schemaDefined:j.schemaDefined,attributes:j.attributes.map(J=>({name:J.name,type:J.type,isPrimaryKey:J.isPrimaryKey}))})}ue.trace?.("Sending database info for node",A,"database name",U),e.send((0,ct.encode)([EK,A,U,L]))}a(xu,"sendNodeDBName");function K(A){let U=ut()?.[A],N=[];for(let L in U){if(pn&&!pn.some(j=>j.replicateByDefault?!j.tables.includes(L):j.tables.includes(L)))continue;let $=U[L];N.push({table:L,schemaDefined:$.schemaDefined,attributes:$.attributes.map(j=>({name:j.name,type:j.type,isPrimaryKey:j.isPrimaryKey}))})}e.send((0,ct.encode)([RK,N,A]))}a(K,"sendDBSchema"),k=setInterval(()=>{for(let[A,U]of Ne)U.lastChunk+Se<Date.now()&&(ue.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(){Bo&&Bo.end(),vn&&vn.emit("close")},getRecord(A){let U=g++;return new Promise((N,L)=>{let $=[SK,U,A.table.tableId,A.id];T[A.table.tableId]||($.push(A.table.tableName),T[A.table.tableId]=!0),e.send((0,ct.encode)($)),le=performance.now(),R.set(U,{tableId:A.table.tableId,key:A.id,resolve(j){let{table:J,entry:F}=A;if(N(j),j)return J._recordRelocate(F,j)},reject:L})})},sendOperation(A){let U=g++;return A.requestId=U,e.send((0,ct.encode)([kO,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,j=A.schemaDefined,J=U.attributes||[];for(let F=0;F<A.attributes?.length;F++){let he=A.attributes[F],de=J.find(_e=>_e.name===he.name);(!de||de.type!==he.type)&&(L?ue.error?.(`Schema for '${u}.${A.table}' is defined locally, but attribute '${he.name}: ${he.type}' from '${_}' does not match local attribute ${de?"'"+de.name+": "+de.type+"'":"which does not exist"}`):($=!0,j||(he.indexed=!0),de?J[J.indexOf(de)]=he:J.push(he)))}return $?(ue.debug?.("(Re)creating",A),ze({table:A.table,database:A.database,schemaDefined:A.schemaDefined,attributes:J,...U})):U}}var wK,ct,NK,CK,OK,GO,PK,LK,qO,DK,FO,vK,pme,UO,ue,hK,EK,_K,Lh,gK,xO,SK,BT,kO,FT,TK,yK,RK,kT,MK,GT,qT,Dh,VT,$T,UK,HO,xK,$O,wc,HT,bK,hme,AK,BO,df,IK,ff,VO=se(()=>{Oe();Vi();yO();FI();Ss();wK=b(ce());H();hl();ct=require("msgpackr"),NK=require("ws"),CK=require("worker_threads"),OK=b(Q());Ch();GO=require("events"),PK=b(ys()),LK=b(require("node:tls"));of();qO=b(require("node:process")),DK=require("node:net");is();ss();FO=require("node:stream"),vK=require("lmdb"),{forComponent:pme,errorToString:UO}=OK.default,ue=pme("replication").conditional,hK=129,EK=140,_K=141,Lh=142,gK=130,xO=132,SK=133,BT=134,kO=136,FT=137,TK=143,yK=144,RK=145,kT=146,MK=0,GT=1,qT=2,Dh=3,VT=4,$T=5,UK=6,HO=0,xK=1,$O=new Map,wc=new Map,HT=!0,bK=300,hme=2,AK=3e4;a(KT,"createWebSocket");IK=500,ff=class extends GO.EventEmitter{static{a(this,"NodeReplicationConnection")}socket;startTime;retryTime=IK;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??Ri(t)}async connect(){this.session||this.resetSession();let t=[];this.socket=await KT(this.url,{serverName:this.nodeName,authorization:this.authorization});let r;ue.debug?.(`Connecting to ${this.url}, db: ${this.databaseName}, process ${qO.pid}`),this.socket.on("open",()=>{this.socket._socket.unref(),ue[this.isConnected?"info":"warn"]?.(`Connected to ${this.url}, db: ${this.databaseName}`),this.retries=0,this.retryTime=IK,this.nodeSubscriptions&&Jl({name:this.nodeName,database:this.databaseName,url:this.url}),this.isConnected=!0,r=vh(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"?(ue.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"?ue.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`):ue.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&&cf({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();ue.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(vh,"replicateOverWS")});function Nc(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 kK(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 WO(e){try{let t=Zl(e),n=go.Certificate.fromBER(t).extensions?.find(c=>c.extnID==="2.5.29.31");if(!n)return Eo.debug?.("Certificate has no CRL Distribution Points extension"),[];let s=_o.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 go.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 Eo.debug?.(`Found ${o.length} CRL distribution points: ${o}`),o}catch(t){return Eo.warn?.(`Failed to extract CRL distribution points: ${t}`),[]}}function HK(e){try{let t=Zl(e),r=go.Certificate.fromBER(t),n=[],s=[];for(let i of r.extensions||[])if(i.extnID==="2.5.29.31")try{let o=_o.fromBER(i.extnValue.valueBlock.valueHexView);if(o.offset!==-1){let c=new go.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){Eo.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=_o.fromBER(i.extnValue.valueBlock.valueHexView);if(o.offset!==-1&&o.result instanceof _o.Sequence){for(let c of o.result.valueBlock.value)if(c instanceof _o.Sequence&&c.valueBlock.value.length>=2){let l=c.valueBlock.value[0],u=c.valueBlock.value[1];if(l instanceof _o.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){Eo.warn?.(`Failed to parse Authority Information Access extension: ${o}`)}return Eo.debug?.(`Found ${n.length} CRL distribution points and ${s.length} OCSP responder URLs`),{crlUrls:n,ocspUrls:s}}catch(t){return Eo.warn?.(`Failed to extract revocation URLs: ${t}`),{crlUrls:[],ocspUrls:[]}}}function Zl(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 WT(e,t,r,n){let s={certPem:e,issuerPem:t,method:r,...n},i=(0,YO.createHash)("sha256").update(JSON.stringify(s)).digest("hex");return`${r}:${i}`}function jO(e,t){return`${e}:${t}`}function GK(e){try{let t=Zl(e),n=go.Certificate.fromBER(t).serialNumber.valueBlock.valueHexView;return Array.from(n).map(s=>s.toString(16).padStart(2,"0")).join("")}catch(t){throw Eo.error?.(`Failed to extract serial number: ${t}`),new Error(`Failed to extract certificate serial number: ${t.message}`)}}function zO(e){try{let t=Zl(e),r=go.Certificate.fromBER(t),n=r.extensions?.find(i=>i.extnID==="2.5.29.35");if(n)try{let i=_o.fromBER(n.extnValue.valueBlock.valueHexView);if(i.offset!==-1){let o=new go.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){Eo.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,YO.createHash)("sha256").update(s).digest("hex")}catch(t){throw Eo.error?.(`Failed to extract issuer key ID: ${t}`),new Error(`Failed to extract issuer key ID: ${t.message}`)}}function jT(){return KO||(KO=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"}]})),KO}var YO,go,_o,FK,Eo,KO,zT=se(()=>{YO=require("node:crypto"),go=b(require("pkijs")),_o=b(require("asn1js")),FK=b(ir());Oe();Eo=(0,FK.loggerWithTag)("cert-verification-utils");a(Nc,"bufferToPem");a(kK,"extractCertificateChain");a(WO,"extractCRLDistributionPoints");a(HK,"extractRevocationUrls");a(Zl,"pemToBuffer");a(WT,"createCacheKey");a(jO,"createRevokedCertificateId");a(GK,"extractSerialNumber");a(zO,"extractIssuerKeyId");KO=null;a(jT,"getCertificateCacheTable")});function qK(e){let{error:t,value:r}=Sme.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,Eme,mf,pf,JO,_me,gme,Sme,$K=se(()=>{Yr=b(require("joi")),Eme="fail-closed",mf={timeout:5e3,cacheTtl:36e5,errorCacheTtl:3e5,failureMode:"fail-closed"},pf={timeout:1e4,cacheTtl:864e5,failureMode:"fail-closed",gracePeriod:864e5},JO=Yr.default.string().valid("fail-open","fail-closed"),_me=Yr.default.alternatives().try(Yr.default.boolean().custom(e=>e===!1?{enabled:!1}:{enabled:!0,...pf}),Yr.default.object({enabled:Yr.default.boolean().default(!0),timeout:Yr.default.number().min(1e3).default(pf.timeout).messages({"number.min":"CRL timeout must be at least 1000ms (1 second)"}),cacheTtl:Yr.default.number().min(1e3).default(pf.cacheTtl).messages({"number.min":"CRL cacheTtl must be at least 1000ms (1 second)"}),failureMode:JO.default(pf.failureMode),gracePeriod:Yr.default.number().min(0).default(pf.gracePeriod).messages({"number.min":"CRL gracePeriod must be at least 0ms"})})),gme=Yr.default.alternatives().try(Yr.default.boolean().custom(e=>e===!1?{enabled:!1}:{enabled:!0,...mf}),Yr.default.object({enabled:Yr.default.boolean().default(!0),timeout:Yr.default.number().min(1e3).default(mf.timeout).messages({"number.min":"OCSP timeout must be at least 1000ms (1 second)"}),cacheTtl:Yr.default.number().min(1e3).default(mf.cacheTtl).messages({"number.min":"OCSP cacheTtl must be at least 1000ms (1 second)"}),errorCacheTtl:Yr.default.number().min(1e3).default(mf.errorCacheTtl).messages({"number.min":"OCSP errorCacheTtl must be at least 1000ms (1 second)"}),failureMode:JO.default(mf.failureMode)})),Sme=Yr.default.object({failureMode:JO.default(Eme),crl:_me.default({enabled:!0,...pf}),ocsp:gme.default({enabled:!0,...mf})});a(qK,"validateAndParseCertificateVerificationConfig")});function XK(e){if(typeof e=="boolean"||e==null){if(e===QO&&XO)return So.trace?.("Using cached validation error result (primitive) - returning disabled"),!1;if(e===QO&&JT!==null)return So.trace?.("Using cached certificate verification config (primitive)"),JT;So.trace?.("Parsing and caching certificate verification config (primitive)"),QO=e;try{return JT=YK(e),XO=null,JT}catch(n){return XO=n,So.error?.(`Certificate verification config validation failed - defaulting to disabled: ${n.message}`),!1}}if(KK.get(e))return So.trace?.("Using cached validation error result (object) - returning disabled"),!1;let r=VK.get(e);if(r!==void 0)return So.trace?.("Using cached certificate verification config (object)"),r;So.trace?.("Parsing and caching certificate verification config (object)");try{let n=YK(e);return VK.set(e,n),n}catch(n){return KK.set(e,n),So.error?.(`Certificate verification config validation failed - defaulting to disabled: ${n.message}`),!1}}function YK(e){if(So.trace?.(`getCertificateVerificationConfig called with: ${JSON.stringify({mtlsConfig:e})}`),!e)return!1;let t=e===!0?void 0:e.certificateVerification;return So.trace?.(`Certificate verification config: ${JSON.stringify({verificationConfig:t})}`),t==null||t===!1?!1:qK(t===!0?{}:t)}var WK,jK,So,zK,JK,QK,VK,QO,JT,KK,XO,ZO=se(()=>{WK=b(ir()),jK=b(bt());$K();So=(0,WK.loggerWithTag)("cert-verification-config"),zK=10080*60*1e3,JK=3e5,QK=`Harper/${jK.packageJson.version} CRL-Client`,VK=new WeakMap,QO=null,JT=null,KK=new WeakMap,XO=null;a(XK,"getCachedCertificateVerificationConfig");a(YK,"getCertificateVerificationConfig")});function Mh(e){return e===eY||e===Tme}function yme(e){return e===tY||e===rY}function eP(e){return e===eY?tY:rY}function Rme(){if(ZK)return;ZK=!0;let e=eu.CryptoEngine.prototype,t=eu.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 Mh(s.algorithmId)?"UNUSED-EDDSA-BUILTIN-HASH":r.getHashAlgorithm.call(this,s)},e.getAlgorithmByOID=function(...n){let[s]=n;return Mh(s)?{name:eP(s)}:r.getAlgorithmByOID.call(this,...n)},e.getAlgorithmParameters=function(...n){let[s,i]=n;return yme(s)?{algorithm:{name:s},usages:i==="sign"?["sign"]:["verify"]}:r.getAlgorithmParameters.call(this,...n)},t.getPublicKey=async function(...n){let[,s=eu.getCrypto(!0)]=n,i=this.subjectPublicKeyInfo.algorithm.algorithmId;if(Mh(i)){let o=eP(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(Mh(this.signatureAlgorithm.algorithmId))try{let i=this.toSchema().toBER(!1),o=s.toSchema().toBER(!1),c=new Uh.X509Certificate(Buffer.from(i)),l=new Uh.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(Mh(c)){let l=eP(c);try{let u=this.crypto?.subtle||this.subtle||eu.getCrypto(!0)?.subtle||Uh.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 eu,Uh,eY,Tme,tY,rY,ZK,nY=se(()=>{eu=b(require("pkijs")),Uh=require("node:crypto"),eY="1.3.101.112",Tme="1.3.101.113",tY="Ed25519",rY="Ed448",ZK=!1;a(Mh,"isEd25519OrEd448");a(yme,"isEdDSAAlgorithmName");a(eP,"getEdDSAAlgorithmName");a(Rme,"applyEd25519Patch");Rme()});var aY={};ye(aY,{CRLSignatureVerificationError:()=>xh,performCRLCheck:()=>Ime,verifyCRL:()=>nP});function bme(){return QT||(QT=jT(),QT.sourcedFrom(hf)),QT}function Ame(){return XT||(XT=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}]}),XT.sourcedFrom(rP)),XT}function iY(){return tP||(tP=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}]})),tP}async function nP(e,t,r,n){if(r?.enabled===!1)return{valid:!0,status:"disabled",method:"disabled"};try{let s=Nc(e,"CERTIFICATE"),i=Nc(t,"CERTIFICATE"),o=n??WO(s);if(o.length===0)return{valid:!0,status:"no-crl-distribution-points",method:"crl"};let c=WT(s,i,"crl"),l=await bme().get(c,{certPem:s,issuerPem:i,distributionPoint:o[0],config:{crl:r??{}}});if(!l)return Pr.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"}:(Pr.warn?.("CRL cache fetch failed, allowing connection (fail-open mode)"),{valid:!0,status:"error-allowed",method:"crl"});let u=l,d=l.wasLoadedFromSource?.();return Pr.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 Pr.error?.(`CRL verification error: ${s}`),r.failureMode==="fail-closed"?{valid:!1,status:"error",error:s.message,method:"crl"}:(Pr.warn?.("CRL check failed, allowing connection (fail-open mode)"),{valid:!0,status:"error-allowed",method:"crl"})}}async function Ime(e,t,r,n){let s=n??WO(e);if(s.length===0)return{status:"good"};let i=GK(e),o=zO(t),c=jO(o,i);try{let u=await iY().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?(Pr.warn?.("Using expired CRL data within grace period"),{status:"revoked",reason:m.revocation_reason||"unspecified",source:m.crl_source}):(Pr.warn?.("CRL data is too old, treating as unknown"),{status:"unknown",reason:"crl-expired"})}let d=await wme(s,t,r);return d.upToDate?{status:"good",source:d.source}:(Pr.warn?.("CRL data is stale or missing, treating as unknown"),{status:"unknown",reason:d.reason||"crl-unavailable"})}catch(l){return Pr.error?.(`CRL lookup error: ${l}`),{status:"unknown",reason:l.message}}}async function wme(e,t,r){let n=Date.now();for(let s of e)try{let i=Ame(),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 oY(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 xh)throw i}return{upToDate:!1,reason:"no-current-crl-data"}}async function oY(e,t,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let i=await fetch(e,{signal:n.signal,headers:{"User-Agent":QK}});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(Zl(l)):c=o;let u=ZT.CertificateRevocationList.fromBER(c),d=ZT.Certificate.fromBER(Zl(t)),f=await u.verify({issuerCertificate:d});if(!f){let _=`CRL signature verification failed for: ${e}`;throw Pr.error?.(_),new xh(_)}let m=u.thisUpdate.value.getTime(),p=u.nextUpdate?.value.getTime()??m+zK,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 Nme(u,t,e,p).catch(_=>{Pr.error?.(`Error processing revoked certificates: ${_}`)}),E}finally{clearTimeout(s)}}async function Nme(e,t,r,n){let s=iY(),i=zO(t),o=r;try{await Cme(s,o)}catch(c){Pr.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){Pr.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=jO(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){Pr.warn?.(`Failed to process revoked certificate: ${l}`)}}async function Cme(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){Pr.warn?.(`Failed to delete revoked certificate entry: ${s}`)}}catch(r){throw Pr.error?.(`Failed to search for existing CRL entries: ${r}`),r}}var ZT,sY,xh,Pr,QT,rP,XT,tP,sP=se(()=>{ZT=b(require("pkijs")),sY=b(ir());Oe();Ji();zT();ZO();iP();xh=class extends Error{static{a(this,"CRLSignatureVerificationError")}constructor(t){super(t),this.name="CRLSignatureVerificationError"}},Pr=(0,sY.loggerWithTag)("crl-verification");a(bme,"getCertificateCacheTable");rP=class extends Zt{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 oY(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(Pr.error?.(`CRL fetch error for: ${s} - ${c}`),o.failureMode==="fail-closed"){let l=Date.now()+JK;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 Pr.warn?.("CRL fetch failed, not caching (fail-open mode)"),null}}};a(Ame,"getCRLCacheTable");a(iY,"getRevokedCertificateTable");a(nP,"verifyCRL");a(Ime,"performCRLCheck");a(wme,"checkCRLFreshness");a(oY,"downloadAndParseCRL");a(Nme,"processRevokedCertificates");a(Cme,"clearExistingCRLEntries")});async function Ome(){oP||(oP=(await Promise.resolve().then(()=>(sP(),aY))).performCRLCheck),aP||(aP=(await Promise.resolve().then(()=>(cP(),lY))).performOCSPCheck)}var cY,KFe,oP,aP,hf,iP=se(()=>{Ji();cY=b(ir()),KFe=(0,cY.loggerWithTag)("cert-verification-source");a(Ome,"loadVerificationFunctions");hf=class extends Zt{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 Ome();let d,f;if(u==="crl"){f=l.crl;let p=s.distributionPoint?[s.distributionPoint]:void 0;d=await oP(i,o,f,p)}else if(u==="ocsp")f=l.ocsp,d=await aP(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 lY={};ye(lY,{performOCSPCheck:()=>Lme,verifyOCSP:()=>lP});function Pme(){return ty||(ty=jT(),ty.sourcedFrom(hf)),ty}async function lP(e,t,r,n){if(r?.enabled===!1)return{valid:!0,status:"disabled",method:"disabled"};try{let s=Nc(e,"CERTIFICATE"),i=Nc(t,"CERTIFICATE"),o=WT(s,i,"ocsp"),c=await Pme().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"}:(ey.warn?.("OCSP cache fetch failed, allowing connection (fail-open mode)"),{valid:!0,status:"error-allowed",method:"ocsp"});let l=c,u=c.wasLoadedFromSource?.();return ey.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 ey.error?.(`OCSP verification error: ${s}`),r.failureMode==="fail-closed"?{valid:!1,status:"error",error:s.message,method:"ocsp"}:(ey.warn?.("OCSP check failed, allowing connection (fail-open mode)"),{valid:!0,status:"error-allowed",method:"ocsp"})}}async function Lme(e,t,r,n){try{let s=await(0,uY.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 uY,dY,ey,ty,cP=se(()=>{nY();uY=require("easy-ocsp"),dY=b(ir());zT();iP();ey=(0,dY.loggerWithTag)("ocsp-verification");a(Pme,"getCertificateCacheTable");a(lP,"verifyOCSP");a(Lme,"performOCSPCheck")});async function Ef(e,t){cn.debug?.(`verifyCertificate called for: ${e.subject?.CN||"unknown"}`);let r=XK(t);if(r===!1)return cn.debug?.("Certificate verification disabled"),{valid:!0,status:"disabled",method:"disabled"};let n=kK(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=Nc(n[0].cert,"CERTIFICATE"),{crlUrls:i,ocspUrls:o}=HK(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 nP(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 lP(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 fY,cn,ry=se(()=>{fY=b(ir());zT();ZO();cP();sP();cn=(0,fY.loggerWithTag)("cert-verification");a(Ef,"verifyCertificate")});var aa={};ye(aa,{buildReplicationMtlsConfig:()=>yY,clearThisNodeName:()=>Hme,disableReplication:()=>Ume,enabledDatabases:()=>Ic,forEachReplicatedDatabase:()=>Tc,getThisNodeId:()=>YT,getThisNodeName:()=>nt,getThisNodeUrl:()=>yc,hostnameToUrl:()=>ay,lastTimeInAuditStore:()=>bh,monitorNodeCAs:()=>RY,replicateOperation:()=>qme,replicationCertificateAuthorities:()=>ca,sendOperationToNode:()=>Bh,servers:()=>vme,setReplicator:()=>AY,start:()=>Mme,startOnMainThread:()=>RO,subscribeToNode:()=>Nh,unsubscribeFromNode:()=>LT,urlToNodeName:()=>Ri});function yY(e){return e?.mtls&&typeof e.mtls=="object"?e.mtls:!0}function Mme(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 Ih(e))t.set(Ri(i.url),i);xme(e);let r=yY(e);e={isOperationsServer:!0,maxPayload:10*1024*1024*1024,...e,mtls:r};let n=Ue.ws(async(i,o,c,l)=>{if(Nt.debug("Incoming WS connection received "+o.url),o.headers.get("sec-websocket-protocol")!=="harperdb-replication-v1")return l(i,o,c);i._socket.unref(),vh(i,e,c.then(()=>o?.user)),i.on("error",u=>{u.code!=="ECONNREFUSED"&&Nt.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"){Nt.debug("Incoming replication WS connection received, authorized: "+i.authorized),!i.authorized&&i._nodeRequest.socket.authorizationError&&Nt.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=qt().primaryStore;if(i.authorized&&i.peerCertificate.subjectaltname){let l=(0,SY.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 Ef(i.peerCertificate,e.mtls);if(!d.valid){Nt.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)){Nt.warn("Revoked certificate used in attempt to connect to node",u.name,"certificate serial number",i.peerCertificate.serialNumber);return}else i.user=u}else Nt.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:Nt.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=oy.createSecureContext(d)}catch(u){Nt.error("Error creating replication TLS config",u)}},"updateContexts");i.secureContextsListeners.push(o),s.push(o),Ks.default.get(x.REPLICATION_ENABLEROOTCAS)!==!1&&o()}RY(()=>{for(let i of s)i()})}function RY(e){let t=0;sf(r=>{r?.ca&&(ca.add(r.ca),ca.size!==t&&(t=ca.size,e?.()))})}function Ume(e=!0){TY=e}function xme(e){TY||(ut(),Ic=e.databases,Tc(e,(t,r)=>{if(!t){let n=e.databaseSubscriptions||wc;for(let[s,i]of sy){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];AY(r,s,e),$O.get(s)?.forEach(i=>i(s))}}))}function AY(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 bY extends Zt{static{a(this,"Replicator")}static connection;static subscription;static async subscribe(){let i=r.databaseSubscriptions||wc,o=i.get(e),c=o?.tableById||[];c[t.tableId]=t;let l=o?.ready;if(Nt.trace("Setting up replicator subscription to database",e),!o?.auditStore)return this.subscription=o=new ns,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=Fme(h,bY.subscription,e);if(E?.isConnected){let _=nf(t.auditStore,e,h)[VT];(!d||_<m)&&(d=E,f=h,m=_)}}if(!d)throw l||new _Y.ServerError(`No connection to any other nodes are available: ${c}`,502);let p={requestId:Dme++,table:t,entry:i,id:i.key};u.add(f);try{return await d.getRecord(p)}catch(h){if(d.isConnected)throw h;Nt.warn("Error in load from node",iy,h),l||(l=h)}}while(!0)}}}static isReplicator=!0},{intermediateSource:!0})}function Bme(e,t,r,n,s,i){let o=t+"-"+e,c=sy.get(o);c||(c=new Map,sy.set(o,c));let l=c.get(n);if(l)return l;if(r)return c.set(n,l=new ff(t,r,n,s,i)),l.connect(),l.once("finished",()=>c.delete(n)),l}function Fme(e,t,r){let n=mY.get(e);n||(n=new Map,mY.set(e,n));let s=n.get(r);if(s)return s;let i=qt().primaryStore.get(e);return i?.url&&(s=new ff(i.url,t,r,e,i.authorization),n.set(r,s),s.connect(),s.once("finished",()=>n.delete(r))),s}async function Bh(e,t,r){r||(r={}),r.serverName=e.name;let n=await KT(e.url,r),s=vh(n,{},{});return new Promise((i,o)=>{n.on("open",()=>{Nt.debug("Sending operation connection to "+e.url+" opened",t),i(s.sendOperation(t))}),n.on("error",c=>{o(c)}),n.on("close",c=>{Nt.info("Sending operation connection to "+e.url+" closed",c)})}).finally(()=>{n.close()})}function Nh(e){try{gY.isMainThread&&Nt.warn("Subscribing on main thread (should not happen in multi-threaded instance)",e.nodes[0].url,e.database);let t=wc.get(e.database);if(!t){let n;t=new Promise(s=>{Nt.info("Waiting for subscription to database "+e.database),n=s}),t.ready=n,wc.set(e.database,t)}let r=Bme(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=>Ah(n,e.database)),e.replicateByDefault)}catch(t){Nt.error("Error in subscription to node",e.nodes[0]?.url,t)}}async function LT({url:e,nodes:t,database:r}){Nt.trace("Unsubscribing from node",e,r,"nodes",Array.from(qt().primaryStore.getRange({})));let n=e+"-"+(t[0]?.url??e),s=sy.get(n);if(s){let i=s.get(r);i&&(i.unsubscribe(),s.delete(r))}}function kme(){if(uP!==void 0)return uP;let e=Ks.default.get(x.OPERATIONSAPI_TLS_CERTIFICATE)||Ks.default.get(x.TLS_CERTIFICATE);if(e)return uP=new hY.X509Certificate((0,EY.readFileSync)(e)).subject?.match(/CN=(.*)/)?.[1]??null}function nt(){return iy||(iy=Ks.default.get("replication_hostname")??Ri(Ks.default.get("replication_url"))??kme()??pY("operationsapi_network_secureport")??pY("operationsapi_network_port")??"127.0.0.1")}function Hme(){iy=void 0}function pY(e){let t=Ks.default.get(e),r=t?.lastIndexOf?.(":");if(r>0)return t.slice(0,r)}function ny(e){let t=Ks.default.get(e),r=t?.lastIndexOf?.(":");return r>0?+t.slice(r+1).replace(/[\[\]]/g,""):+t}function YT(e){return Rh(e)?.[nt()]}function yc(){let e=Ks.default.get("replication_url");return e||ay(nt())}function ay(e){let t=ny("replication_port");if(t)return`ws://${e}:${t}`;if(t=ny("replication_secureport"),t)return`wss://${e}:${t}`;if(t=ny("operationsapi_network_port"),t)return`ws://${e}:${t}`;if(t=ny("operationsapi_network_secureport"),t)return`wss://${e}:${t}`}function Ri(e){if(e)return new URL(e).hostname}function Tc(e,t){for(let n of Object.getOwnPropertyNames(Me))r(n);return sh(n=>{r(n)}),Vl((n,s)=>{r(n.databaseName)});function r(n){let s=Me[n];Nt.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):Gme(n)&&t(s,n,!1)}a(r,"forDatabase")}function Gme(e){let t=Me[e];for(let r in t)if(t[r].replicate)return!0}function bh(e){for(let t of e.getKeys({limit:1,reverse:!0}))return t}async function qme(e){let t={message:""};if(e.replicated){e.replicated=!1,Nt.trace?.("Replicating operation",e.operation,"to nodes",Ue.nodes.map(n=>n.name));let r=await Promise.allSettled(Ue.nodes.map(n=>Bh(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,Nt,hY,EY,oy,_Y,gY,SY,TY,Dme,vme,ca,Ic,sy,mY,uP,iy,Ss=se(()=>{Oe();Ji();Gu();VO();Hr();Ks=b(ce()),Nt=b(Q()),hY=require("crypto");ry();EY=require("fs");Ch();of();H();yO();oy=b(require("node:tls")),_Y=b(Ee()),gY=require("worker_threads"),SY=b(ys()),Dme=1,vme=[],ca=Ks.default.get(x.REPLICATION_ENABLEROOTCAS)!==!1?new Set(oy.rootCertificates):new Set;a(yY,"buildReplicationMtlsConfig");a(Mme,"start");a(RY,"monitorNodeCAs");a(Ume,"disableReplication");a(xme,"assignReplicationSource");a(AY,"setReplicator");sy=new Map;a(Bme,"getSubscriptionConnection");mY=new Map;a(Fme,"getRetrievalConnectionByName");a(Bh,"sendOperationToNode");a(Nh,"subscribeToNode");a(LT,"unsubscribeFromNode");a(kme,"getCommonNameFromCert");a(nt,"getThisNodeName");a(Hme,"clearThisNodeName");Object.defineProperty(Ue,"hostname",{get(){return nt()}});a(pY,"getHostFromListeningPort");a(ny,"getPortFromListeningPort");a(YT,"getThisNodeId");Ue.replication={getThisNodeId:YT,exportIdMapping:Rh};a(yc,"getThisNodeUrl");a(ay,"hostnameToUrl");a(Ri,"urlToNodeName");a(Tc,"forEachReplicatedDatabase");a(Gme,"hasExplicitlyReplicatedTable");a(bh,"lastTimeInAuditStore");a(qme,"replicateOperation")});var kh=M((hke,OY)=>{"use strict";var _f=r1(),{validateBySchema:Fh}=at(),{commonValidators:gf,schemaRegex:dP}=Xi(),Sr=require("joi"),$me=Q(),Vme=require("uuid").v4,uy=Xo(),Sf=(H(),D(W)),Kme=require("util"),Cc=fs(),{handleHDBError:la,hdbErrors:Yme,ClientError:tu}=Ee(),{HDB_ERROR_MSGS:cy,HTTP_STATUS_CODES:ua}=Yme,{SchemaEventMsg:dy}=ls(),IY=Gt(),{getDatabases:Wme}=(Oe(),D(pt)),{transformReq:Tf}=ae(),{replicateOperation:wY}=(Ss(),D(aa)),{cleanupOrphans:jme}=(ss(),D(og)),ly=Sr.string().min(1).max(gf.schema_length.maximum).pattern(dP).messages({"string.pattern.base":"{:#label} "+gf.schema_format.message}),zme=Sr.string().min(1).max(gf.schema_length.maximum).pattern(dP).messages({"string.pattern.base":"{:#label} "+gf.schema_format.message}).required(),Jme=Sr.string().min(1).max(gf.schema_length.maximum).pattern(dP).messages({"string.pattern.base":"{:#label} "+gf.schema_format.message,"any.required":"'primary_key' is required","string.base":"'primary_key' must be a string"}).required();OY.exports={createSchema:Qme,createSchemaStructure:NY,createTable:Xme,createTableStructure:CY,createAttribute:npe,dropSchema:Zme,dropTable:epe,dropAttribute:tpe,getBackup:spe,cleanupOrphanBlobs:ipe};async function Qme(e){let t=await NY(e);return uy.signalSchemaChange(new dy(process.pid,e.operation,e.schema)),t}a(Qme,"createSchema");async function NY(e){let t=Fh(e,Sr.object({database:ly,schema:ly}));if(t)throw new tu(t.message);if(Tf(e),!await _f.checkSchemaExists(e.schema))throw la(new Error,cy.SCHEMA_EXISTS_ERR(e.schema),ua.BAD_REQUEST,Sf.LOG_LEVELS.ERROR,cy.SCHEMA_EXISTS_ERR(e.schema),!0);return await Cc.createSchema(e),`database '${e.schema}' successfully created`}a(NY,"createSchemaStructure");async function Xme(e){return Tf(e),e.hash_attribute=e.primary_key??e.hash_attribute,await CY(e)}a(Xme,"createTable");async function CY(e){let t=Fh(e,Sr.object({database:ly,schema:ly,table:zme,residence:Sr.array().items(Sr.string().min(1)).optional(),hash_attribute:Jme}));if(t)throw new tu(t.message);if(!await _f.checkSchemaTableExists(e.schema,e.table))throw la(new Error,cy.TABLE_EXISTS_ERR(e.schema,e.table),ua.BAD_REQUEST,Sf.LOG_LEVELS.ERROR,cy.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:Vme(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await Cc.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 Cc.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(CY,"createTableStructure");async function Zme(e){let t=Fh(e,Sr.object({database:Sr.string(),schema:Sr.string()}).or("database","schema").messages({"object.missing":"'database' is required"}));if(t)throw new tu(t.message);Tf(e);let r=await _f.checkSchemaExists(e.schema);if(r)throw la(new Error,r,ua.NOT_FOUND,Sf.LOG_LEVELS.ERROR,r,!0);let n=await _f.schemaDescribe.describeSchema({schema:e.schema}),s=Object.keys(global.hdb_schema[e.schema]);await Cc.dropSchema(e),uy.signalSchemaChange(new dy(process.pid,e.operation,e.schema)),await IY.purgeSchemaTableStreams(e.schema,s);let i=await wY(e);return i.message=`successfully deleted '${e.schema}'`,i}a(Zme,"dropSchema");async function epe(e){let t=Fh(e,Sr.object({database:Sr.string(),schema:Sr.string(),table:Sr.string().required()}));if(t)throw new tu(t.message);Tf(e);let r=await _f.checkSchemaTableExists(e.schema,e.table);if(r)throw la(new Error,r,ua.NOT_FOUND,Sf.LOG_LEVELS.ERROR,r,!0);await Cc.dropTable(e),await IY.purgeTableStream(e.schema,e.table);let n=await wY(e);return n.message=`successfully deleted table '${e.schema}.${e.table}'`,n}a(epe,"dropTable");async function tpe(e){let t=Fh(e,Sr.object({database:Sr.string(),schema:Sr.string(),table:Sr.string().required(),attribute:Sr.string().required()}));if(t)throw new tu(t.message);Tf(e);let r=await _f.checkSchemaTableExists(e.schema,e.table);if(r)throw la(new Error,r,ua.NOT_FOUND,Sf.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(Sf.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 Cc.dropAttribute(e),rpe(e),uy.signalSchemaChange(new dy(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw $me.error(`Got an error deleting attribute ${Kme.inspect(e)}.`),n}}a(tpe,"dropAttribute");function rpe(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(rpe,"dropAttributeFromGlobal");async function npe(e){Tf(e);let t=Wme()[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 Cc.createAttribute(e),uy.signalSchemaChange(new dy(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(npe,"createAttribute");function spe(e){return Cc.getBackup(e)}a(spe,"getBackup");function ipe(e){if(!e.database)throw new tu('Must provide "database" name for search for orphaned blobs');if(!databases[e.database])throw new tu(`Unknown database '${e.database}'`);return jme(databases[e.database],e.database),{message:"Orphaned blobs cleanup started, check logs for progress"}}a(ipe,"cleanupOrphanBlobs")});var LY=M((_ke,PY)=>{"use strict";var{OPERATIONS_ENUM:ope}=(H(),D(W)),fP=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=ope.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};PY.exports=fP});var mP=M((Tke,xY)=>{"use strict";var ape=fs(),Ske=LY(),fy=ae(),my=(H(),D(W)),cpe=ce(),{handleHDBError:DY,hdbErrors:lpe}=Ee(),{HDB_ERROR_MSGS:vY,HTTP_STATUS_CODES:MY}=lpe,upe=Object.values(my.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),UY="To use this operation audit log must be enabled in harperdb-config.yaml";xY.exports=dpe;async function dpe(e){if(fy.isEmpty(e.schema))throw new Error(vY.SCHEMA_REQUIRED_ERR);if(fy.isEmpty(e.table))throw new Error(vY.TABLE_REQUIRED_ERR);if(!cpe.get(my.CONFIG_PARAMS.LOGGING_AUDITLOG))throw DY(new Error,UY,MY.BAD_REQUEST,my.LOG_LEVELS.ERROR,UY,!0);let t=fy.checkSchemaTableExist(e.schema,e.table);if(t)throw DY(new Error,t,MY.NOT_FOUND,my.LOG_LEVELS.ERROR,t,!0);if(!fy.isEmpty(e.search_type)&&upe.indexOf(e.search_type)<0)throw new Error(`Invalid searchType '${read_audit_log_object.search_type}'`);return await ape.readAuditLog(e)}a(dpe,"readAuditLog")});var FY=M((Rke,BY)=>{"use strict";var{OPERATIONS_ENUM:fpe}=(H(),D(W)),pP=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=fpe.GET_BACKUP,this.schema=t,this.table=r}};BY.exports=pP});var GY=M((wke,HY)=>{"use strict";var mpe=fs(),Ake=FY(),hP=ae(),ppe=(H(),D(W)),Ike=ce(),{handleHDBError:hpe,hdbErrors:Epe}=Ee(),{HDB_ERROR_MSGS:kY,HTTP_STATUS_CODES:_pe}=Epe;HY.exports=gpe;async function gpe(e){if(hP.isEmpty(e.schema))throw new Error(kY.SCHEMA_REQUIRED_ERR);if(hP.isEmpty(e.table))throw new Error(kY.TABLE_REQUIRED_ERR);let t=hP.checkSchemaTableExist(e.schema,e.table);if(t)throw hpe(new Error,t,_pe.NOT_FOUND,ppe.LOG_LEVELS.ERROR,t,!0);return await mpe.getBackup(readAuditLogObject)}a(gpe,"getBackup")});var VY=M((Cke,$Y)=>{"use strict";var Spe=ce(),da=require("joi"),Tpe=at(),qY=require("moment"),ype=require("fs-extra"),_P=require("path"),Rpe=require("lodash"),Hh=(H(),D(W)),{LOG_LEVELS:ru}=(H(),D(W)),bpe="YYYY-MM-DD hh:mm:ss",Ape=_P.resolve(__dirname,"../logs");$Y.exports=function(e){return Tpe.validateBySchema(e,Ipe)};var Ipe=da.object({from:da.custom(EP),until:da.custom(EP),to:da.custom(EP),level:da.valid(ru.NOTIFY,ru.FATAL,ru.ERROR,ru.WARN,ru.INFO,ru.DEBUG,ru.TRACE),order:da.valid("asc","desc"),limit:da.number().min(1),start:da.number().min(0),log_name:da.custom(wpe)});function EP(e,t){if(qY(e,qY.ISO_8601).format(bpe)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(EP,"validateDatetime");function wpe(e,t){if(Rpe.invert(Hh.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=Spe.get(Hh.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?Hh.LOG_NAMES.HDB:e,i=s===Hh.LOG_NAMES.INSTALL?_P.join(Ape,Hh.LOG_NAMES.INSTALL):_P.join(n,s);return ype.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(wpe,"validateReadLogPath")});var SP=M((Pke,YY)=>{"use strict";var py=(H(),D(W)),Npe=Q(),Cpe=ce(),Ope=VY(),gP=require("path"),KY=require("fs-extra"),{once:Ppe}=require("events"),{handleHDBError:Lpe,hdbErrors:Dpe}=Ee(),{PACKAGE_ROOT:vpe}=bt(),{replicateOperation:Mpe}=(Ss(),D(aa)),Upe=gP.join(vpe,"logs"),xpe=1e3,Bpe=200;YY.exports=Fpe;async function Fpe(e){let t=Ope(e);if(t)throw Lpe(t,t.message,Dpe.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=Mpe(e),n=Cpe.get(py.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?py.LOG_NAMES.HDB:e.log_name,i=s===py.LOG_NAMES.INSTALL?gP.join(Upe,py.LOG_NAMES.INSTALL):gP.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?xpe: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(KY.statSync(i).size-(E+5)*Bpe,0));let R=KY.createReadStream(i,{start:_});R.on("error",q=>{Npe.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),G(I));let[le,fe,te]=Y,Se=te.split("] ["),Ne=Se[0],Ke=Se[1];Se.splice(0,2),I={timestamp:fe,thread:Ne,level:Ke,tags:Se,message:""},z=Y.index+le.length}w=q.slice(z)}),R.on("end",q=>{R.destroyed||I&&(I.message=w.trim(),G(I))}),R.resume();function G(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&&(To(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&&(To(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&&(To(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&&(To(q,p,y),S++,S===E&&R.destroy());break;case o:q.level===c&&S<h?S++:q.level===c&&(To(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&&(To(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&&(To(q,p,y),S++,S===E&&R.destroy());break;default:S<h?S++:(To(q,p,y),S++,S===E&&R.destroy())}}a(G,"onLogMessage"),await Ppe(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")To({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,To(z,p,y)}}return y}a(Fpe,"readLog");function To(e,t,r){t==="desc"?kpe(e,r):t==="asc"?Hpe(e,r):r.push(e)}a(To,"pushLineToResult");function kpe(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(kpe,"insertDescending");function Hpe(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(Hpe,"insertAscending")});var hy=M((xke,JY)=>{"use strict";var TP=require("joi"),{string:yf,boolean:WY,date:Gpe}=TP.types(),qpe=at(),{validateSchemaExists:Dke,validateTableExists:vke,validateSchemaName:Mke}=Xi(),$pe=(H(),D(W)),Vpe=ht(),jY=ce();jY.initSync();var Uke=yf.invalid(jY.get($pe.CONFIG_PARAMS.CLUSTERING_NODENAME)??"node_name").pattern(Vpe.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),zY={operation:yf.valid("add_node","update_node","set_node_replication"),node_name:yf.optional(),subscriptions:TP.array().items({table:yf.optional(),schema:yf.optional(),database:yf.optional(),subscribe:WY.required(),publish:WY.required().custom(Ype),start_time:Gpe.iso()})};function Kpe(e){return qpe.validateBySchema(e,TP.object(zY))}a(Kpe,"addUpdateNodeValidator");function Ype(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(Ype,"checkForFalsy");JY.exports={addUpdateNodeValidator:Kpe,validationSchema:zY}});var Oc=M((Fke,QY)=>{"use strict";var yP=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},RP=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};QY.exports={Node:yP,NodeSubscription:RP}});var ZY=M((Hke,XY)=>{"use strict";var Wpe=(H(),D(W)).OPERATIONS_ENUM,bP=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=Wpe.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};XY.exports=bP});var Gh=M((qke,eW)=>{"use strict";var AP=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},IP=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)}};eW.exports={RemotePayloadObject:AP,RemotePayloadSubscription:IP}});var rW=M((Vke,tW)=>{"use strict";var wP=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}};tW.exports=wP});var sW=M((Jke,nW)=>{"use strict";var jpe=rW(),Yke=Qt(),Wke=_t(),zpe=Q(),{getSchemaPath:jke,getTransactionAuditStorePath:zke}=At(),{getDatabases:Jpe}=(Oe(),D(pt));nW.exports=Qpe;async function Qpe(e){let t=new jpe;try{let r=Jpe()[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){zpe.warn(`unable to stat table dbi due to ${r}`)}return t}a(Qpe,"lmdbGetTableSize")});var oW=M((Xke,iW)=>{"use strict";var NP=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}};iW.exports=NP});var $h=M((sHe,uW)=>{"use strict";var Xpe=require("fs-extra"),Zpe=require("path"),In=require("systeminformation"),Pc=Q(),aW=Gt(),eHe=ht(),Rf=(H(),D(W)),ehe=sW(),the=gc(),{getThreadInfo:cW}=tt(),qh=ce();qh.initSync();var rhe=oW(),{openEnvironment:tHe}=_t(),{getSchemaPath:rHe}=At(),{database:nHe,databases:CP}=(Oe(),D(pt)),Ey;uW.exports={getHDBProcessInfo:DP,getNetworkInfo:MP,getDiskInfo:vP,getMemoryInfo:LP,getCPUInfo:PP,getTimeInfo:OP,getSystemInformation:UP,systemInformation:nhe,getTableSize:xP,getMetrics:BP};function OP(){return In.time()}a(OP,"getTimeInfo");async function PP(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:l,cache:u,...d}=await In.cpu();d.cpu_speed=await In.cpuCurrentSpeed();let{rawCurrentload:f,rawCurrentloadIdle:m,rawCurrentloadIrq:p,rawCurrentloadNice:h,rawCurrentloadSystem:E,rawCurrentloadUser:_,cpus:R,...S}=await In.currentLoad();return S.cpus=[],R.forEach(y=>{let{rawLoad:w,rawLoadIdle:I,rawLoadIrq:G,rawLoadNice:X,rawLoadSystem:q,rawLoadUser:k,...z}=y;S.cpus.push(z)}),d.current_load=S,d}catch(e){return Pc.error(`error in getCPUInfo: ${e}`),{}}}a(PP,"getCPUInfo");async function LP(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await In.mem();return Object.assign(s,process.memoryUsage())}catch(e){return Pc.error(`error in getMemoryInfo: ${e}`),{}}}a(LP,"getMemoryInfo");async function DP(){let e={core:[],clustering:[]};try{let t=await In.processes(),r;try{r=Number.parseInt(await Xpe.readFile(Zpe.join(qh.get(Rf.CONFIG_PARAMS.ROOTPATH),Rf.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===Rf.NODE_ERROR_CODES.ENOENT)Pc.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 Pc.error(`error in getHDBProcessInfo: ${t}`),e}}a(DP,"getHDBProcessInfo");async function vP(){let e={};try{if(!qh.get(Rf.CONFIG_PARAMS.OPERATIONSAPI_SYSINFO_DISK))return e;let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await In.disksIO();e.io=i;let{rxSec:o,txSec:c,wxSec:l,...u}=await In.fsStats();return e.read_write=u,e.size=await In.fsSize(),e}catch(t){return Pc.error(`error in getDiskInfo: ${t}`),e}}a(vP,"getDiskInfo");async function MP(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return qh.get(Rf.CONFIG_PARAMS.OPERATIONSAPI_SYSINFO_NETWORK)&&(e.default_interface=await In.networkInterfaceDefault(),e.latency=await In.inetChecksite("google.com"),(await In.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 In.networkStats()).forEach(n=>{let{rxSec:s,txSec:i,ms:o,...c}=n;e.stats.push(c)})),e}catch(t){return Pc.error(`error in getNetworkInfo: ${t}`),e}}a(MP,"getNetworkInfo");async function UP(){if(Ey!==void 0)return Ey;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await In.osInfo();e=c;let l=await In.versions("node, npm");return e.node_version=l.node,e.npm_version=l.npm,Ey=e,Ey}catch(t){return Pc.error(`error in getSystemInformation: ${t}`),e}}a(UP,"getSystemInformation");async function xP(){let e=[],t=await the.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await ehe(n));return e}a(xP,"getTableSize");async function BP(){let e={};for(let t in CP){let r=e[t]={},n=r.tables={};for(let s in CP[t])try{let i=CP[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){Pc.notify(`Error getting stats for table ${s}: ${i}`)}}return e}a(BP,"getMetrics");async function lW(){if(qh.get(Rf.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await aW.getNATSReferences(),t=await aW.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(lW,"getNatsStreamInfo");async function nhe(e){let t=new rhe;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await UP(),t.time=OP(),t.cpu=await PP(),t.memory=await LP(),t.disk=await vP(),t.network=await MP(),t.harperdb_processes=await DP(),t.table_size=await xP(),t.metrics=await BP(),t.threads=await cW(),t.replication=await lW(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await UP();break;case"time":t.time=OP();break;case"cpu":t.cpu=await PP();break;case"memory":t.memory=await LP();break;case"disk":t.disk=await vP();break;case"network":t.network=await MP();break;case"harperdb_processes":t.harperdb_processes=await DP();break;case"table_size":t.table_size=await xP();break;case"database_metrics":case"metrics":t.metrics=await BP();break;case"threads":t.threads=await cW();break;case"replication":t.replication=await lW();break;default:break}return t}a(nhe,"systemInformation")});var Ys=M((lHe,pW)=>{"use strict";var she=_n(),FP=ae(),ihe=require("util"),nu=(H(),D(W)),dW=ce();dW.initSync();var ohe=qC(),fW=Sn(),{Node:oHe,NodeSubscription:aHe}=Oc(),ahe=md(),che=ZY(),{RemotePayloadObject:lhe,RemotePayloadSubscription:uhe}=Gh(),{handleHDBError:dhe,hdbErrors:fhe}=Ee(),{HTTP_STATUS_CODES:mhe,HDB_ERROR_MSGS:phe}=fhe,hhe=di(),Ehe=$h(),{packageJson:_he}=bt(),{getDatabases:ghe}=(Oe(),D(pt)),cHe=ihe.promisify(ohe.authorize),She=fW.searchByHash,The=fW.searchByValue;pW.exports={isEmpty:yhe,getNodeRecord:Rhe,upsertNodeRecord:bhe,buildNodePayloads:Ahe,checkClusteringEnabled:Ihe,getAllNodeRecords:whe,getSystemInfo:Nhe,reverseSubscription:mW};function yhe(e){return e==null}a(yhe,"isEmpty");async function Rhe(e){let t=new ahe(nu.SYSTEM_SCHEMA_NAME,nu.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return She(t)}a(Rhe,"getNodeRecord");async function bhe(e){let t=new che(nu.SYSTEM_SCHEMA_NAME,nu.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return she.upsert(t)}a(bhe,"upsertNodeRecord");function mW(e){if(FP.isEmpty(e.subscribe)||FP.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(mW,"reverseSubscription");function Ahe(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=FP.getTableHashAttribute(l,u),{subscribe:f,publish:m}=mW(c),p=ghe()[l]?.[u],h=new uhe(l,u,d,m,f,c.start_time,p.schemaDefined?p.attributes:void 0);s.push(h)}return new lhe(r,t,s,n)}a(Ahe,"buildNodePayloads");function Ihe(){if(!dW.get(nu.CONFIG_PARAMS.CLUSTERING_ENABLED))throw dhe(new Error,phe.CLUSTERING_NOT_ENABLED,mhe.BAD_REQUEST,void 0,void 0,!0)}a(Ihe,"checkClusteringEnabled");async function whe(){let e=new hhe(nu.SYSTEM_SCHEMA_NAME,nu.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await The(e))}a(whe,"getAllNodeRecords");async function Nhe(){let e=await Ehe.getSystemInformation();return{hdb_version:_he.version,node_version:e.node_version,platform:e.platform}}a(Nhe,"getSystemInfo")});var kP=M((dHe,RW)=>{"use strict";var _y=Gt(),hW=ae(),EW=ht(),_W=(H(),D(W)),gy=Q(),gW=kh(),Che=hd(),{RemotePayloadObject:Ohe}=Gh(),{handleHDBError:SW,hdbErrors:Phe}=Ee(),{HTTP_STATUS_CODES:TW}=Phe,{NodeSubscription:yW}=Oc();RW.exports=Lhe;async function Lhe(e,t){let r;try{r=await _y.request(`${t}.${EW.REQUEST_SUFFIX}`,new Ohe(_W.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),gy.trace("Response from remote describe all request:",r)}catch(o){gy.error(`addNode received error from describe all request to remote node: ${o}`);let c=_y.requestErrorHandler(o,"add_node",t);throw SW(new Error,c,TW.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===EW.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw SW(new Error,o,TW.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===_W.SYSTEM_SCHEMA_NAME){await _y.createLocalTableStream(l,c);let h=new yW(l,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let u=hW.doesSchemaExist(l),d=n[l]!==void 0,f=c?hW.doesTableExist(l,c):!0,m=c?n?.[l]?.[c]!==void 0:!0;if(!u&&!d||!f&&!m){s.push(o);continue}if(!u&&d&&(gy.trace(`addNode creating schema: ${l}`),await gW.createSchema({operation:"create_schema",schema:l})),!f&&m){gy.trace(`addNode creating table: ${c} in schema: ${l} with attributes ${JSON.stringify(n[l][c].attributes)}`);let h=new Che(l,c,n[l][c].hash_attribute);n[l][c].attributes&&(h.attributes=n[l][c].attributes),await gW.createTable(h)}await _y.createLocalTableStream(l,c);let p=new yW(l,c,o.publish,o.subscribe);p.start_time=o.start_time,i.push(p)}return{added:i,skipped:s}}a(Lhe,"reviewSubscriptions")});var bf={};ye(bf,{addNodeBack:()=>HP,removeNodeBack:()=>GP,setNode:()=>Uhe});async function Uhe(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=Ri(t)):t=ay(r);let n=(0,AW.validateBySchema)(e,Mhe);if(n)throw(0,fa.handleHDBError)(n,n.message,vhe.BAD_REQUEST,void 0,void 0,!0);if(e.operation==="remove_node"){if(!t&&!r)throw new fa.ClientError("url or hostname is required for remove_node operation");let p=r,h=qt(),E=await h.get(p);if(!E)throw new fa.ClientError(p+" does not exist");try{await Bh({url:E.url},{operation:V.REMOVE_NODE_BACK,name:E?.subscriptions?.length>0?nt():p},void 0)}catch(_){Rs.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 fa.ClientError("url required for this operation");let s=yc();if(s==null)throw new fa.ClientError("replication url is missing from harperdb-config.yaml");let i,o,c;if(t?.startsWith("wss:")){i=await(0,Ws.getReplicationCert)();let p=await(0,Ws.getReplicationCertAuth)();if(!i)throw new Error("Unable to find a certificate to use for replication");i.options.is_self_signed?(o=await(0,Ws.createCsr)(),Rs.info("Sending CSR to target node:",t)):p&&(c=p.certificate,Rs.info("Sending CA named",p.name,"to target node",t))}let l={operation:V.ADD_NODE_BACK,hostname:(0,Dc.get)(x.REPLICATION_HOSTNAME),target_hostname:r,url:s,csr:o,cert_auth:c,authorization:e.retain_authorization?e.authorization:null};if((0,Dc.get)(x.REPLICATION_SHARD)!==void 0&&(l.shard=(0,Dc.get)(x.REPLICATION_SHARD)),e.subscriptions?l.subscriptions=e.subscriptions.map(bW):l.subscriptions=null,e.hasOwnProperty("subscribe")||e.hasOwnProperty("publish")){let p=bW(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 Bh({url:t},l,e)}catch(p){p.message=`Error returned from ${t}: `+p.message,Rs.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&&(Rs.info("CSR response received from node:",t,"saving certificate and CA in hdb_certificate"),await(0,Ws.setCertTable)({name:Dhe.certificateFromPem(u.signingCA).issuer.getField("CN").value,certificate:u.signingCA,is_authority:!0}),u.certificate&&await(0,Ws.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,Dc.get)(x.REPLICATION_SHARD)!==void 0&&(p.shard=(0,Dc.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??Ri(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 HP(e){Rs.trace("addNodeBack received request:",e);let t=await(0,Ws.signCertificate)(e),r;e.csr?(r=t.signingCA,Rs.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,Rs.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,Ws.getReplicationCertAuth)();if(n.replicates){let i={url:yc(),ca:s?.certificate,replicates:!0,subscriptions:null};(0,Dc.get)(x.REPLICATION_SHARD)!==void 0&&(i.shard=(0,Dc.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,Rs.info("addNodeBack responding to:",e.url,"with CA named:",s?.name),t}async function GP(e){Rs.trace("removeNodeBack received request:",e),await qt().delete(e.name)}function bW(e){let{subscribe:t,publish:r}=e;return{...e,subscribe:r,publish:t}}var Ws,AW,Lc,Dc,Rs,fa,Dhe,vhe,Mhe,Af=se(()=>{Ws=b(ys()),AW=b(at()),Lc=b(require("joi")),Dc=b(ce());H();Ch();of();Ss();Rs=b(Q()),fa=b(Ee()),{pki:Dhe}=require("node-forge"),{HTTP_STATUS_CODES:vhe}=fa.hdbErrors,Mhe=Lc.default.object({hostname:Lc.default.string(),verify_tls:Lc.default.boolean(),replicates:Lc.default.boolean(),subscriptions:Lc.default.array(),revoked_certificates:Lc.default.array(),shard:Lc.default.number()});a(Uhe,"setNode");a(HP,"addNodeBack");a(GP,"removeNodeBack");a(bW,"reverseSubscription")});var by=M((THe,wW)=>{"use strict";var{handleHDBError:Sy,hdbErrors:xhe}=Ee(),{HTTP_STATUS_CODES:Ty}=xhe,{addUpdateNodeValidator:Bhe}=hy(),yy=Q(),Ry=(H(),D(W)),IW=ht(),Fhe=ae(),Vh=Gt(),Kh=Ys(),qP=ce(),khe=kP(),{Node:Hhe,NodeSubscription:Ghe}=Oc(),{broadcast:qhe}=tt(),{setNode:$he}=(Af(),D(bf)),gHe=ce(),SHe=(H(),D(W)),Vhe="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",Khe="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Yhe=qP.get(Ry.CONFIG_PARAMS.CLUSTERING_NODENAME);wW.exports=Whe;async function Whe(e,t=!1){if(yy.trace("addNode called with:",e),qP.get(Ry.CONFIG_PARAMS.REPLICATION_URL)||qP.get(Ry.CONFIG_PARAMS.REPLICATION_HOSTNAME))return $he(e);Kh.checkClusteringEnabled();let r=Bhe(e);if(r)throw Sy(r,r.message,Ty.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let f=await Kh.getNodeRecord(n);if(!Fhe.isEmptyOrZeroLength(f))throw Sy(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,Ty.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await khe(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=Vhe,o;let c=Kh.buildNodePayloads(s,Yhe,Ry.OPERATIONS_ENUM.ADD_NODE,await Kh.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 Ghe(p.schema,p.table,p.publish,p.subscribe))}yy.trace("addNode sending remote payload:",c);let u;try{u=await Vh.request(`${n}.${IW.REQUEST_SUFFIX}`,c)}catch(f){yy.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 Vh.updateRemoteConsumer(E,n)}let m=Vh.requestErrorHandler(f,"add_node",n);throw Sy(new Error,m,Ty.INTERNAL_SERVER_ERROR,"error",m)}if(u.status===IW.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let f=`Error returned from remote node ${n}: ${u.message}`;throw Sy(new Error,f,Ty.INTERNAL_SERVER_ERROR,"error",f)}yy.trace(u);for(let f=0,m=s.length;f<m;f++){let p=s[f];await Vh.updateRemoteConsumer(p,n),p.subscribe===!0&&await Vh.updateConsumerIterator(p.schema,p.table,n,"start")}let d=new Hhe(n,l,u.system_info);return await Kh.upsertNodeRecord(d),qhe({type:"nats_update"}),i.length>0?o.message=Khe:o.message=`Successfully added '${n}' to manifest`,o}a(Whe,"addNode")});var YP=M((bHe,CW)=>{"use strict";var{handleHDBError:$P,hdbErrors:jhe}=Ee(),{HTTP_STATUS_CODES:VP}=jhe,{addUpdateNodeValidator:zhe}=hy(),Yh=Q(),Ay=(H(),D(W)),NW=ht(),RHe=ae(),Wh=Gt(),jh=Ys(),KP=ce(),{cloneDeep:Jhe}=require("lodash"),Qhe=kP(),{Node:Xhe,NodeSubscription:Zhe}=Oc(),{broadcast:eEe}=tt(),{setNode:tEe}=(Af(),D(bf)),rEe="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",nEe="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",sEe=KP.get(Ay.CONFIG_PARAMS.CLUSTERING_NODENAME);CW.exports=iEe;async function iEe(e){if(Yh.trace("updateNode called with:",e),KP.get(Ay.CONFIG_PARAMS.REPLICATION_URL)??KP.get(Ay.CONFIG_PARAMS.REPLICATION_HOSTNAME))return tEe(e);jh.checkClusteringEnabled();let t=zhe(e);if(t)throw $P(t,t.message,VP.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await jh.getNodeRecord(r);s.length>0&&(n=Jhe(s));let{added:i,skipped:o}=await Qhe(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=rEe,c;let l=jh.buildNodePayloads(i,sEe,Ay.OPERATIONS_ENUM.UPDATE_NODE,await jh.getSystemInfo());for(let d=0,f=i.length;d<f;d++){let m=i[d];Yh.trace(`updateNode updating work stream for node: ${r} subscription:`,m),i[d].start_time===void 0&&delete i[d].start_time}Yh.trace("updateNode sending remote payload:",l);let u;try{u=await Wh.request(`${r}.${NW.REQUEST_SUFFIX}`,l)}catch(d){Yh.error(`updateNode received error from request: ${d}`);let f=Wh.requestErrorHandler(d,"update_node",r);throw $P(new Error,f,VP.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===NW.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${r}: ${u.message}`;throw $P(new Error,d,VP.INTERNAL_SERVER_ERROR,"error",d)}Yh.trace(u);for(let d=0,f=i.length;d<f;d++){let m=i[d];await Wh.updateRemoteConsumer(m,r),m.subscribe===!0?await Wh.updateConsumerIterator(m.schema,m.table,r,"start"):await Wh.updateConsumerIterator(m.schema,m.table,r,"stop")}return n||(n=[new Xhe(r,[],u.system_info)]),await oEe(n[0],i,u.system_info),o.length>0?c.message=nEe:c.message=`Successfully updated '${r}'`,c}a(iEe,"updateNode");async function oEe(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 Zhe(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await jh.upsertNodeRecord(n),eEe({type:"nats_update"})}a(oEe,"updateNodeTable")});var vW=M((IHe,DW)=>{"use strict";var LW=require("joi"),{string:OW}=LW.types(),aEe=at(),PW=(H(),D(W)),cEe=ce(),lEe=ht();DW.exports=uEe;function uEe(e){let t=OW.invalid(cEe.get(PW.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(lEe.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=LW.object({operation:OW.valid(PW.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return aEe.validateBySchema(e,r)}a(uEe,"removeNodeValidator")});var Iy=M((NHe,FW)=>{"use strict";var{handleHDBError:MW,hdbErrors:dEe}=Ee(),{HTTP_STATUS_CODES:UW}=dEe,fEe=vW(),zh=Q(),xW=Ys(),mEe=ae(),If=(H(),D(W)),BW=ht(),WP=Gt(),jP=ce(),{RemotePayloadObject:pEe}=Gh(),{NodeSubscription:hEe}=Oc(),EEe=pd(),_Ee=cc(),{broadcast:gEe}=tt(),{setNode:SEe}=(Af(),D(bf)),TEe=jP.get(If.CONFIG_PARAMS.CLUSTERING_NODENAME);FW.exports=yEe;async function yEe(e){if(zh.trace("removeNode called with:",e),jP.get(If.CONFIG_PARAMS.REPLICATION_URL)??jP.get(If.CONFIG_PARAMS.REPLICATION_HOSTNAME))return SEe(e);xW.checkClusteringEnabled();let t=fEe(e);if(t)throw MW(t,t.message,UW.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await xW.getNodeRecord(r);if(mEe.isEmptyOrZeroLength(n))throw MW(new Error,`Node '${r}' was not found.`,UW.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new pEe(If.OPERATIONS_ENUM.REMOVE_NODE,TEe,[]),i,o=!1;for(let l=0,u=n.subscriptions.length;l<u;l++){let d=n.subscriptions[l];d.subscribe===!0&&await WP.updateConsumerIterator(d.schema,d.table,r,"stop");try{await WP.updateRemoteConsumer(new hEe(d.schema,d.table,!1,!1),r)}catch(f){zh.error(f)}}try{i=await WP.request(`${r}.${BW.REQUEST_SUFFIX}`,s),zh.trace("Remove node reply from remote node:",r,i)}catch(l){zh.error("removeNode received error from request:",l),o=!0}let c=new EEe(If.SYSTEM_SCHEMA_NAME,If.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await _Ee.deleteRecord(c),gEe({type:"nats_update"}),i?.status===BW.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(zh.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(yEe,"removeNode")});var GW=M((OHe,HW)=>{"use strict";var kW=require("joi"),{string:REe,array:bEe}=kW.types(),AEe=at(),IEe=hy();HW.exports=wEe;function wEe(e){let t=kW.object({operation:REe.valid("configure_cluster").required(),connections:bEe.items(IEe.validationSchema).required()});return AEe.validateBySchema(e,t)}a(wEe,"configureClusterValidator")});var zP=M((LHe,YW)=>{"use strict";var qW=(H(),D(W)),wy=Q(),NEe=ae(),CEe=ce(),OEe=Iy(),PEe=by(),LEe=Ys(),DEe=GW(),{handleHDBError:$W,hdbErrors:vEe}=Ee(),{HTTP_STATUS_CODES:VW}=vEe,MEe="Configure cluster complete.",UEe="Failed to configure the cluster. Check the logs for more details.",xEe="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";YW.exports=BEe;async function BEe(e){wy.trace("configure cluster called with:",e);let t=DEe(e);if(t)throw $W(t,t.message,VW.BAD_REQUEST,void 0,void 0,!0);let r=await LEe.getAllNodeRecords(),n=[];if(CEe.get(qW.CONFIG_PARAMS.CLUSTERING_ENABLED)){for(let d=0,f=r.length;d<f;d++){let m=await KW(OEe,{operation:qW.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[d].name},r[d].name);n.push(m)}wy.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 KW(PEe,f,f.node_name);s.push(m)}wy.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"&&(wy.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(NEe.isEmptyOrZeroLength(o))return{message:MEe,connections:c};if(l)return{message:xEe,failed_nodes:o,connections:c};throw $W(new Error,UEe,VW.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(BEe,"configureCluster");async function KW(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(KW,"functionWrapper")});var JW=M((vHe,zW)=>{"use strict";var Jh=require("joi"),FEe=at(),{validateSchemaExists:WW,validateTableExists:kEe,validateSchemaName:jW}=Xi(),HEe=Jh.object({operation:Jh.string().valid("purge_stream"),schema:Jh.string().custom(WW).custom(jW).optional(),database:Jh.string().custom(WW).custom(jW).optional(),table:Jh.string().custom(kEe).required()});function GEe(e){return FEe.validateBySchema(e,HEe)}a(GEe,"purgeStreamValidator");zW.exports=GEe});var JP=M((UHe,QW)=>{"use strict";var{handleHDBError:qEe,hdbErrors:$Ee}=Ee(),{HTTP_STATUS_CODES:VEe}=$Ee,KEe=JW(),YEe=Gt(),WEe=Ys();QW.exports=jEe;async function jEe(e){e.schema=e.schema??e.database;let t=KEe(e);if(t)throw qEe(t,t.message,VEe.BAD_REQUEST,void 0,void 0,!0);WEe.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await YEe.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(jEe,"purgeStream")});var ZP=M((BHe,ij)=>{"use strict";var XP=Ys(),zEe=Gt(),Cy=ce(),wf=(H(),D(W)),su=ht(),JEe=ae(),QP=Q(),{RemotePayloadObject:QEe}=Gh(),{ErrorCode:XW}=require("nats"),{parentPort:ZW}=require("worker_threads"),{onMessageByType:XEe}=tt(),{getThisNodeName:ZEe}=(Ss(),D(aa)),{requestClusterStatus:e_e}=(Ch(),D(W1)),{getReplicationSharedStatus:t_e,getHDBNodeTable:r_e}=(of(),D(H1)),{CONFIRMATION_STATUS_POSITION:n_e,RECEIVED_VERSION_POSITION:ej,RECEIVED_TIME_POSITION:s_e,SENDING_TIME_POSITION:i_e,RECEIVING_STATUS_POSITION:o_e,RECEIVING_STATUS_RECEIVING:a_e,BACK_PRESSURE_RATIO_POSITION:c_e}=(VO(),D(BK)),tj=Cy.get(wf.CONFIG_PARAMS.CLUSTERING_ENABLED),rj=Cy.get(wf.CONFIG_PARAMS.CLUSTERING_NODENAME);ij.exports={clusterStatus:l_e,buildNodeStatus:sj};var nj;XEe("cluster-status",async e=>{nj(e)});async function l_e(){if(Cy.get(wf.CONFIG_PARAMS.REPLICATION_URL)||Cy.get(wf.CONFIG_PARAMS.REPLICATION_HOSTNAME)){let n;ZW?(ZW.postMessage({type:"request-cluster-status"}),n=await new Promise(i=>{nj=i})):n=e_e();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=t_e(u,l,o);c.lastCommitConfirmed=Ny(d[n_e]),c.lastReceivedRemoteTime=Ny(d[ej]),c.lastReceivedLocalTime=Ny(d[s_e]),c.lastReceivedVersion=d[ej],c.sendingMessage=Ny(d[i_e]),c.backPressurePercent=d[c_e]*100,c.lastReceivedStatus=d[o_e]===a_e?"Receiving":"Waiting"}}n.node_name=ZEe();let s=r_e().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:rj,is_enabled:tj,connections:[]};if(!tj)return e;let t=await XP.getAllNodeRecords();if(JEe.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(sj(t[n],e.connections));return await Promise.allSettled(r),e}a(l_e,"clusterStatus");function Ny(e){return e?e===1?"Copying":new Date(e).toUTCString():void 0}a(Ny,"asDate");async function sj(e,t){let r=e.name,n=new QEe(wf.OPERATIONS_ENUM.CLUSTER_STATUS,rj,void 0,await XP.getSystemInfo()),s,i,o=su.CLUSTER_STATUS_STATUSES.OPEN;try{let l=Date.now();s=await zEe.request(su.REQUEST_SUBJECT(r),n),i=Date.now()-l,s.status===su.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=su.CLUSTER_STATUS_STATUSES.CLOSED,QP.error(`Error getting node status from ${r} `,s))}catch(l){QP.warn(`Error getting node status from ${r}`,l),l.code===XW.NoResponders?o=su.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:l.code===XW.Timeout?o=su.CLUSTER_STATUS_STATUSES.TIMEOUT:o=su.CLUSTER_STATUS_STATUSES.CLOSED}let c=new u_e(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!==wf.PRE_4_0_0_VERSION&&await XP.upsertNodeRecord(l)}catch(l){QP.error("Cluster status encountered an error updating system info for node:",r,l)}t.push(c)}a(sj,"buildNodeStatus");function u_e(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(u_e,"NodeStatusObject")});var tL=M((kHe,oj)=>{"use strict";var{handleHDBError:d_e,hdbErrors:f_e}=Ee(),{HTTP_STATUS_CODES:m_e}=f_e,p_e=Gt(),h_e=Ys(),eL=ae(),Oy=require("joi"),E_e=at(),__e=2e3,g_e=Oy.object({timeout:Oy.number().min(1),connected_nodes:Oy.boolean(),routes:Oy.boolean()});oj.exports=S_e;async function S_e(e){h_e.checkClusteringEnabled();let t=E_e.validateBySchema(e,g_e);if(t)throw d_e(t,t.message,m_e.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||eL.autoCastBoolean(n),o=s===void 0||eL.autoCastBoolean(s),c={nodes:[]},l=await p_e.getServerList(r??__e),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:eL.autoCast(E.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(S_e,"clusterNetwork")});var uj=M((GHe,lj)=>{"use strict";var rL=require("joi"),aj=at(),{routeConstraints:cj}=NN();lj.exports={setRoutesValidator:T_e,deleteRoutesValidator:y_e};function T_e(e){let t=rL.object({server:rL.valid("hub","leaf"),routes:cj.required()});return aj.validateBySchema(e,t)}a(T_e,"setRoutesValidator");function y_e(e){let t=rL.object({routes:cj.required()});return aj.validateBySchema(e,t)}a(y_e,"deleteRoutesValidator")});var Py=M(($He,_j)=>{"use strict";var ma=St(),nL=ae(),js=(H(),D(W)),Nf=ce(),dj=uj(),{handleHDBError:fj,hdbErrors:R_e}=Ee(),{HTTP_STATUS_CODES:mj}=R_e,pj="cluster routes successfully set",hj="cluster routes successfully deleted";_j.exports={setRoutes:A_e,getRoutes:I_e,deleteRoutes:w_e};function b_e(e){let t=ma.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=nL.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"?ma.updateConfigValue(js.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,r):ma.updateConfigValue(js.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,r),{message:pj,set:i,skipped:s}}a(b_e,"setRoutesNats");function A_e(e){let t=dj.setRoutesValidator(e);if(t)throw fj(t,t.message,mj.BAD_REQUEST,void 0,void 0,!0);if(Nf.get(js.CONFIG_PARAMS.CLUSTERING_ENABLED))return b_e(e);let r=[],n=[],s=Nf.get(js.CONFIG_PARAMS.REPLICATION_ROUTES)??[];return e.routes.forEach(i=>{Ej(s,i)?n.push(i):(s.push(i),r.push(i))}),ma.updateConfigValue(js.CONFIG_PARAMS.REPLICATION_ROUTES,s),{message:pj,set:r,skipped:n}}a(A_e,"setRoutes");function Ej(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(Ej,"existsInArray");function I_e(){if(Nf.get(js.CONFIG_PARAMS.CLUSTERING_ENABLED)){let e=ma.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}else return Nf.get(js.CONFIG_PARAMS.REPLICATION_ROUTES)??[]}a(I_e,"getRoutes");function w_e(e){let t=dj.deleteRoutesValidator(e);if(t)throw fj(t,t.message,mj.BAD_REQUEST,void 0,void 0,!0);if(Nf.get(js.CONFIG_PARAMS.CLUSTERING_ENABLED))return N_e(e);let r=[],n=[],s=Nf.get(js.CONFIG_PARAMS.REPLICATION_ROUTES)??[],i=[];return s.forEach(o=>{Ej(e.routes,o)?r.push(o):(i.push(o),n.push(o))}),ma.updateConfigValue(js.CONFIG_PARAMS.REPLICATION_ROUTES,i),{message:hj,deleted:r,skipped:n}}a(w_e,"deleteRoutes");function N_e(e){let t=ma.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=nL.isEmptyOrZeroLength(r)?null:r,ma.updateConfigValue(js.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,r)),c&&(n=nL.isEmptyOrZeroLength(n)?null:n,ma.updateConfigValue(js.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:hj,deleted:s,skipped:i}}a(N_e,"deleteRoutesNats")});var Sj=M((KHe,gj)=>{"use strict";var C_e=ht(),sL=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+C_e.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"}};gj.exports=sL});var Rj=M((WHe,yj)=>{"use strict";var Tj=ht(),iL=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+Tj.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+Tj.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"}};yj.exports=iL});var Aj=M((zHe,bj)=>{"use strict";var oL=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};bj.exports=oL});var wj=M((QHe,Ij)=>{"use strict";var O_e=ht(),aL=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+O_e.SERVER_SUFFIX.ADMIN,this.password=r}};Ij.exports=aL});var My=M((ZHe,Oj)=>{"use strict";var iu=require("path"),ou=require("fs-extra"),P_e=Sj(),L_e=Rj(),D_e=Aj(),v_e=wj(),cL=(Es(),D(co)),Of=ae(),jn=St(),Dy=(H(),D(W)),Qh=ht(),{CONFIG_PARAMS:lr}=Dy,Pf=Q(),Xh=ce(),Nj=so(),lL=Gt(),M_e=ys(),Cf="clustering",U_e=1e4,Cj=50;Oj.exports={generateNatsConfig:B_e,removeNatsConfig:F_e,getHubConfigPath:x_e};function x_e(){let e=Xh.get(lr.ROOTPATH);return iu.join(e,Cf,Qh.NATS_CONFIG_FILES.HUB_SERVER)}a(x_e,"getHubConfigPath");async function B_e(e=!1,t=void 0){console.error("Warning: NATS replication is deprecated and will be removed in version 5.0 of Harper");let r=Xh.get(lr.ROOTPATH);ou.ensureDirSync(iu.join(r,"clustering","leaf")),Xh.initSync();let n=jn.getConfigFromFile(lr.CLUSTERING_TLS_CERT_AUTH),s=jn.getConfigFromFile(lr.CLUSTERING_TLS_PRIVATEKEY),i=jn.getConfigFromFile(lr.CLUSTERING_TLS_CERTIFICATE);!await ou.exists(i)&&!await ou.exists(!n)&&await M_e.createNatsCerts();let o=iu.join(r,Cf,Qh.PID_FILES.HUB),c=iu.join(r,Cf,Qh.PID_FILES.LEAF),l=jn.getConfigFromFile(lr.CLUSTERING_LEAFSERVER_STREAMS_PATH),u=iu.join(r,Cf,Qh.NATS_CONFIG_FILES.HUB_SERVER),d=iu.join(r,Cf,Qh.NATS_CONFIG_FILES.LEAF_SERVER),f=jn.getConfigFromFile(lr.CLUSTERING_TLS_INSECURE),m=jn.getConfigFromFile(lr.CLUSTERING_TLS_VERIFY),p=jn.getConfigFromFile(lr.CLUSTERING_NODENAME),h=jn.getConfigFromFile(lr.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await lL.checkNATSServerInstalled()||vy("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let E=await cL.listUsers(),_=jn.getConfigFromFile(lr.CLUSTERING_USER),R=await cL.getClusterUser();(Of.isEmpty(R)||R.active!==!0)&&vy(`Invalid cluster user '${_}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await Ly(lr.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await Ly(lr.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await Ly(lr.CLUSTERING_HUBSERVER_NETWORK_PORT),await Ly(lr.CLUSTERING_LEAFSERVER_NETWORK_PORT));let S=[],y=[];for(let[z,Y]of E.entries())Y.role?.role===Dy.ROLE_TYPES_ENUM.CLUSTER_USER&&Y.active&&(S.push(new v_e(Y.username,Nj.decrypt(Y.hash))),y.push(new D_e(Y.username,Nj.decrypt(Y.hash))));let w=[],{hub_routes:I}=jn.getClusteringRoutes();if(!Of.isEmptyOrZeroLength(I))for(let z of I)w.push(`tls://${R.sys_name_encoded}:${R.uri_encoded_d_hash}@${z.host}:${z.port}`);let G=new P_e(jn.getConfigFromFile(lr.CLUSTERING_HUBSERVER_NETWORK_PORT),p,o,i,s,n,f,m,h,jn.getConfigFromFile(lr.CLUSTERING_HUBSERVER_CLUSTER_NAME),jn.getConfigFromFile(lr.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),w,S,y);n==null&&(delete G.tls.ca_file,delete G.leafnodes.tls.ca_file),t=Of.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===Dy.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await ou.writeJson(u,G),Pf.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 L_e(jn.getConfigFromFile(lr.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===Dy.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await ou.writeJson(d,k),Pf.trace(`Leaf server config written to ${d}`))}a(B_e,"generateNatsConfig");async function Ly(e){let t=Xh.get(e);return Of.isEmpty(t)&&vy(`port undefined for '${e}'`),await Of.isPortTaken(t)&&vy(`'${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(Ly,"isPortAvailable");function vy(e){let t=`Error generating clustering config: ${e}`;Pf.error(t),console.error(t),process.exit(1)}a(vy,"generateNatsConfigError");async function F_e(e){let{port:t,config_file:r}=lL.getServerConfig(e),{username:n,decrypt_hash:s}=await cL.getClusterUser(),i=0,o=2e3;for(;i<Cj;){try{let d=await lL.createConnection(t,n,s,!1);if(d.protocol.connected===!0){d.close();break}}catch(d){Pf.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${d}`)}if(i++,i>=Cj)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&&Pf.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await Of.asyncSetTimeout(u)}let c="0".repeat(U_e),l=iu.join(Xh.get(lr.ROOTPATH),Cf,r);await ou.writeFile(l,c),await ou.remove(l),Pf.notify(e,"started.")}a(F_e,"removeNatsConfig")});var Uj=M((tGe,Mj)=>{"use strict";var bs=ce(),et=(H(),D(W)),Zh=ht(),pa=require("path"),{PACKAGE_ROOT:xy}=bt(),Pj=ce(),Uy=ae(),Lf="/dev/null",k_e=pa.join(xy,"launchServiceScripts"),Lj=pa.join(xy,"utility/scripts"),H_e=pa.join(Lj,et.HDB_RESTART_SCRIPT),Dj=pa.resolve(xy,"dependencies",`${process.platform}-${process.arch}`,Zh.NATS_BINARY_NAME);function vj(){let e={[et.PROCESS_NAME_ENV_PROP]:et.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0,...process.env};return Uy.noBootFile()&&(e[et.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Uy.getEnvCliRootPath()),{name:et.PROCESS_DESCRIPTORS.HDB,script:et.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:e,execArgv:process.execArgv,cwd:xy}}a(vj,"generateMainServerConfig");var G_e=9930;function q_e(){bs.initSync(!0);let e=bs.get(et.CONFIG_PARAMS.ROOTPATH),t=pa.join(e,"clustering",Zh.NATS_CONFIG_FILES.HUB_SERVER),r=pa.join(bs.get(et.HDB_SETTINGS_NAMES.LOG_PATH_KEY),et.LOG_NAMES.HDB),n=Pj.get(et.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=Zh.LOG_LEVEL_FLAGS[bs.get(et.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:et.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==G_e?"-"+n:""),binFile:Dj,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[et.PROCESS_NAME_ENV_PROP]:et.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return bs.get(et.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Lf,i.error_file=Lf),i}a(q_e,"generateNatsHubServerConfig");var $_e=9940;function V_e(){bs.initSync(!0);let e=bs.get(et.CONFIG_PARAMS.ROOTPATH),t=pa.join(e,"clustering",Zh.NATS_CONFIG_FILES.LEAF_SERVER),r=pa.join(bs.get(et.HDB_SETTINGS_NAMES.LOG_PATH_KEY),et.LOG_NAMES.HDB),n=Pj.get(et.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=Zh.LOG_LEVEL_FLAGS[bs.get(et.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==$_e?"-"+n:""),binFile:Dj,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[et.PROCESS_NAME_ENV_PROP]:et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return bs.get(et.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Lf,i.error_file=Lf),i}a(V_e,"generateNatsLeafServerConfig");function K_e(){bs.initSync();let e=pa.join(bs.get(et.CONFIG_PARAMS.LOGGING_ROOT),et.LOG_NAMES.HDB),t={name:et.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,binFile:et.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[et.PROCESS_NAME_ENV_PROP]:et.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:k_e,autorestart:!1};return bs.get(et.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=Lf,t.error_file=Lf),t}a(K_e,"generateClusteringUpgradeV4ServiceConfig");function Y_e(){let e={[et.PROCESS_NAME_ENV_PROP]:et.PROCESS_DESCRIPTORS.RESTART_HDB};return Uy.noBootFile()&&(e[et.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Uy.getEnvCliRootPath()),{...{name:et.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:Lj},script:H_e}}a(Y_e,"generateRestart");function W_e(){return{apps:[vj()]}}a(W_e,"generateAllServiceConfigs");Mj.exports={generateAllServiceConfigs:W_e,generateMainServerConfig:vj,generateRestart:Y_e,generateNatsHubServerConfig:q_e,generateNatsLeafServerConfig:V_e,generateClusteringUpgradeV4ServiceConfig:K_e}});var Df=M((sGe,qj)=>{"use strict";var Lr=(H(),D(W)),nGe=ae(),Ea=My(),By=Gt(),ha=ht(),vc=Uj(),dL=ce(),Mc=Q(),j_e=Ys(),{startWorker:xj,onMessageFromWorkers:z_e}=tt(),Bj=require("fs"),J_e=require("node:path"),Q_e=(H(),D(W)),{setTimeout:X_e}=require("node:timers/promises"),{execFile:Z_e,fork:ege}=require("node:child_process");qj.exports={start:Uc,restart:rge,kill:oge,startAllServices:age,startService:kj,restartHdb:nge,startClusteringProcesses:Hj,startClusteringThreads:Gj,isHdbRestartRunning:sge,getHdbPid:ige,cleanupChildrenProcesses:eE,reloadClustering:lge,expectedRestartOfChildren:Fj};z_e(e=>{e.type==="restart"&&dL.initSync(!0)});var yo=[],tge=10,uL;function Uc(e,t=!1){let r=typeof e.args=="string"?e.args.split(" "):e.args;e.silent=!0,e.detached=!0;let n=e.script?ege(e.script,r,e):Z_e(e.binFile,r,e);n.name=e.name,n.config=e,n.on("error",(o,c)=>{console.error(o,c)}),n.on("exit",async o=>{let c=yo.indexOf(n);c>-1&&yo.splice(c,1),!uL&&o!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<tge&&(Bj.existsSync(Ea.getHubConfigPath())?Uc(e):(await Ea.generateNatsConfig(!0),Uc(e),await new Promise(l=>setTimeout(l,3e3)),await Ea.removeNatsConfig(Lr.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Ea.removeNatsConfig(Lr.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let s={serviceName:e.name.replace(/ /g,"-")};function i(o){let c=dL.get(Lr.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),l=/\[\d+][^\[]+\[(\w+)]/g,u,d=0,f;for(;u=l.exec(o);){if(u.index&&ha.LOG_LEVEL_HIERARCHY[c]>=ha.LOG_LEVEL_HIERARCHY[f||"info"]){let h=f===ha.LOG_LEVELS.ERR||f===ha.LOG_LEVELS.WRN?Mc.OUTPUTS.STDERR:Mc.OUTPUTS.STDOUT;Mc.logCustomLevel(f||"info",h,s,o.slice(d,u.index).trim())}let[m,p]=u;d=u.index+m.length,f=ha.LOG_LEVELS[p]}if(ha.LOG_LEVEL_HIERARCHY[c]>=ha.LOG_LEVEL_HIERARCHY[f||"info"]){let m=f===ha.LOG_LEVELS.ERR||f===ha.LOG_LEVELS.WRN?Mc.OUTPUTS.STDERR:Mc.OUTPUTS.STDOUT;Mc.logCustomLevel(f||"info",m,s,o.toString().slice(d).trim())}}a(i,"extractMessages"),n.stdout.on("data",i),n.stderr.on("data",i),n.unref(),yo.length===0&&(t||(process.on("exit",eE),process.on("SIGINT",eE),process.on("SIGQUIT",eE),process.on("SIGTERM",eE))),yo.push(n)}a(Uc,"start");function eE(e=!0){if(!uL&&(uL=!0,yo.length!==0))if(Mc.info("Killing child processes..."),yo.map(t=>t.kill()),e)process.exit(0);else return X_e(2e3)}a(eE,"cleanupChildrenProcesses");function rge(e){Fj();for(let t of yo)t.name===e&&t.kill()}a(rge,"restart");function Fj(){for(let e of yo)e.config&&(e.config.restarts=0)}a(Fj,"expectedRestartOfChildren");async function nge(){await Uc(vc.generateRestart())}a(nge,"restartHdb");async function sge(){let e=await list();for(let t in e)if(e[t].name===Lr.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(sge,"isHdbRestartRunning");function ige(){let e=dL.getHdbBasePath();if(!e)return;let t=J_e.join(e,Q_e.HDB_PID_FILE),r=uge(t);if(!(!r||r===process.pid)&&dge(r))return r}a(ige,"getHdbPid");function oge(){for(let e of yo)e.kill();yo=[]}a(oge,"kill");async function age(){await Hj(),await Gj(),await Uc(vc.generateAllServiceConfigs())}a(age,"startAllServices");async function kj(e,t=!1){let r;switch(e=e.toLowerCase(),e){case Lr.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=vc.generateMainServerConfig();break;case Lr.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=vc.generateNatsIngestServiceConfig();break;case Lr.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=vc.generateNatsReplyServiceConfig();break;case Lr.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=vc.generateNatsHubServerConfig(),await Uc(r,t),await Ea.removeNatsConfig(e);return;case Lr.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=vc.generateNatsLeafServerConfig(),await Uc(r,t),await Ea.removeNatsConfig(e);return;case Lr.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=vc.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}Uc(r,t)}a(kj,"startService");var cge;async function Hj(e=!1){for(let t in Lr.CLUSTERING_PROCESSES){let r=Lr.CLUSTERING_PROCESSES[t];await kj(r,e)}}a(Hj,"startClusteringProcesses");async function Gj(){cge=xj(Lr.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Lr.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await By.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await By.updateLocalStreams();let e=await j_e.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Lr.PRE_4_0_0_VERSION){Mc.info("Starting clustering upgrade 4.0.0 process"),xj(Lr.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(Gj,"startClusteringThreads");async function lge(){await Ea.generateNatsConfig(!0),await By.reloadNATSHub(),await By.reloadNATSLeaf(),await Ea.removeNatsConfig(Lr.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Ea.removeNatsConfig(Lr.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(lge,"reloadClustering");function uge(e){try{return Number.parseInt(Bj.readFileSync(e,"utf8"),10)}catch{return null}}a(uge,"readPidFile");function dge(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}a(dge,"isProcessRunning")});var pL={};ye(pL,{compactOnStart:()=>fge,copyDb:()=>jj});async function fge(){_a.notify("Running compact on start"),console.log("Running compact on start");let e=(0,fL.get)(x.ROOTPATH),t=new Map,r=ut();(0,mL.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,Fy.join)(e,"backup",n+".mdb"),o=(0,Fy.join)(e,nl,n+"-copy.mdb"),c=0;try{c=await $j(n),console.log("Database",n,"before compact has a total record count of",c)}catch(l){_a.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 jj(n,o),console.log("Backing up",n,"to",i);try{await(0,au.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,au.move)(o,s,{overwrite:!0}),await(0,au.remove)((0,Fy.join)(e,nl,`${n}-copy.mdb-lock`))}try{kd()}catch(n){_a.error("Error resetting databases after backup",n),console.error("Error resetting databases after backup",n)}try{kd()}catch(n){_a.error("Error resetting databases after backup",n),console.error("Error resetting databases after backup",n),process.exit(0)}}catch(n){_a.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,mL.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,au.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw kd(),n}for(let[n,{backupDest:s,recordCount:i}]of t){let o=await $j(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}`;_a.warn(c),console.warn(c)}(0,fL.get)(x.STORAGE_COMPACTONSTARTKEEPBACKUP)!==!0&&(console.log("Removing backup",s),await(0,au.remove)(s))}}async function $j(e){let t=await(0,Wj.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}function vf(){}async function jj(e,t){console.log(`Copying database ${e} to ${t}`);let r=ut()[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=vf,m.primaryStore.remove=vf;for(let p in m.indices){let h=m.indices[p];h.put=vf,h.remove=vf}m.auditStore&&(m.auditStore.put=vf,m.auditStore.remove=vf),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,Vj.open)(new Kj.default(t)),c=o.openDB(ky.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,_=qS(),_?p.compression=_:delete p.compression,E?.dictionary?.toString()===_?.dictionary?.toString()&&(E=null,_=null)),c.put(m,p),!(h||p.indexed))continue;let R=new Yj.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(ky.AUDIT_STORE_NAME,zm);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:G,version:X}=m.getEntry(I,{transaction:E});if(G?.length<14&&h){S++;continue}l=p.put(I,G,h?X:void 0),_++,E.openTimer&&(E.openTimer=0),R+=(I?.length||10)+G.length,u++>5e3&&(await l,console.log("copied",_,"entries",S,"delete records,",R,"bytes"),u=0)}catch(G){console.error("Error copying record",typeof I=="symbol"?"symbol":I,"from",e,"to",t,G)}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 Vj,Fy,au,fL,Kj,Yj,ky,Wj,mL,_a,hL=se(()=>{Oe();Vj=require("lmdb"),Fy=require("path"),au=require("fs-extra"),fL=b(ce()),Kj=b(lp()),Yj=b(cp()),ky=b(Qt());H();Vi();Wj=b(gc()),mL=b(St()),_a=b(Q());a(fge,"compactOnStart");a($j,"getTotalDBRecordCount");a(vf,"noop");a(jj,"copyDb")});var _L=M((uGe,zj)=>{"use strict";var tE=ce();tE.initSync();var Mf=require("fs-extra"),EL=require("path"),Uf=(H(),D(W)),mge=require("crypto"),pge=require("uuid").v4;zj.exports=hge;function hge(){if(tE.getHdbBasePath()!==void 0){let e=EL.join(tE.getHdbBasePath(),Uf.LICENSE_KEY_DIR_NAME,Uf.JWT_ENUM.JWT_PRIVATE_KEY_NAME),t=EL.join(tE.getHdbBasePath(),Uf.LICENSE_KEY_DIR_NAME,Uf.JWT_ENUM.JWT_PUBLIC_KEY_NAME),r=EL.join(tE.getHdbBasePath(),Uf.LICENSE_KEY_DIR_NAME,Uf.JWT_ENUM.JWT_PASSPHRASE_NAME);try{Mf.accessSync(r),Mf.accessSync(e),Mf.accessSync(t)}catch(n){if(n.code==="ENOENT"){let s=pge(),i=mge.generateKeyPairSync("rsa",{modulusLength:4096,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem",cipher:"aes-256-cbc",passphrase:s}});Mf.writeFileSync(r,s),Mf.writeFileSync(e,i.privateKey),Mf.writeFileSync(t,i.publicKey)}else throw n}}}a(hge,"checkJWTTokenExist")});var Qj=M((fGe,Jj)=>{"use strict";var gL=class{static{a(this,"HdbInfoInsertObject")}constructor(t,r,n){this.info_id=t,this.data_version_num=r,this.hdb_version_num=n}};Jj.exports={HdbInfoInsertObject:gL}});var ez=M((pGe,Zj)=>{"use strict";var Xj=(H(),D(W)),SL=class{static{a(this,"UpgradeObject")}constructor(t,r){this[Xj.UPGRADE_JSON_FIELD_NAMES_ENUM.DATA_VERSION]=t,this[Xj.UPGRADE_JSON_FIELD_NAMES_ENUM.UPGRADE_VERSION]=r}};Zj.exports={UpgradeObject:SL}});var Hy=M((EGe,rz)=>{"use strict";var zs=require("prompt"),xf=require("chalk"),tz=Q(),Ii=require("os"),TL=sl(),yL=["yes","y"];async function Ege(e){let t=`${Ii.EOL}`+xf.bold.green("Your current HarperDB version requires that we complete an update process.")+`${Ii.EOL}If a backup of your data has not been created, we recommend you cancel this process and backup before proceeding.${Ii.EOL}${Ii.EOL}You can read more about the changes in this upgrade at https://harperdb.io/developers/release-notes/${Ii.EOL}`;zs.override=TL(["CONFIRM_UPGRADE"]),zs.start(),zs.message=t;let r={properties:{CONFIRM_UPGRADE:{description:xf.magenta(`${Ii.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 zs.get([r])}catch(s){return tz.error("There was an error when prompting user about an upgrade."),tz.error(s),!1}return yL.includes(n.CONFIRM_UPGRADE)}a(Ege,"forceUpdatePrompt");async function _ge(e){let t=`${Ii.EOL}`+xf.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.${Ii.EOL}`);zs.override=TL(["CONFIRM_DOWNGRADE"]),zs.start(),zs.message=t;let r={properties:{CONFIRM_DOWNGRADE:{description:xf.magenta(`${Ii.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 zs.get([r]);return yL.includes(n.CONFIRM_DOWNGRADE)}a(_ge,"forceDowngradePrompt");async function gge(){let e=`${Ii.EOL}`+xf.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");zs.override=TL(["GENERATE_CERTS"]),zs.start(),zs.message=e;let t={properties:{GENERATE_CERTS:{description:xf.magenta(`${Ii.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 zs.get([t]);return yL.includes(r.GENERATE_CERTS)}a(gge,"upgradeCertsPrompt");rz.exports={forceUpdatePrompt:Ege,forceDowngradePrompt:_ge,upgradeCertsPrompt:gge}});var Gy=M((gGe,nz)=>{"use strict";var RL=class{static{a(this,"UpgradeDirective")}constructor(t){this.version=t,this.sync_functions=[],this.async_functions=[]}};nz.exports=RL});var iz=M((AGe,sz)=>{"use strict";var Sge=ae(),Tge=St(),TGe=Q(),yGe=require("path"),RGe=require("fs"),bGe=(H(),D(W));sz.exports={getOldPropsValue:yge};function yge(e,t,r=!1){let n=t.getRaw(e);return Sge.isNotEmptyAndHasValue(n)?n:r?Tge.getDefaultConfig(e):""}a(yge,"getOldPropsValue")});var lz=M((wGe,cz)=>{"use strict";var xc=require("path"),Bc=require("fs-extra"),Rge=require("properties-reader"),bge=Gy(),Tr=Q(),{getOldPropsValue:Tt}=iz(),{HDB_SETTINGS_NAMES:be,CONFIG_PARAMS:cu}=(H(),D(W)),lu=St(),qy=ce(),oz=ae(),Ro=(H(),D(W)),bL=new bge("3.1.0"),az=[];function Age(){let e=Rge(qy.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.
|