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.
@@ -13,7 +13,7 @@
13
13
  `)},Moe="certificate.pem",Uoe="privateKey.pem",xoe="caCertificate.pem",Boe="natsCertificate.pem",Foe="natsCaCertificate.pem",Dt={DEFAULT:"default","DEFAULT-CA":"default-ca",SERVER:"server",CA:"ca","OPERATIONS-API":"operations-api","OPERATIONS-CA":"operations-ca"},koe={tls_certificate:Dt.SERVER,tlsCertificateAuthority:Dt.CA,customFunctions_tls_certificate:Dt.SERVER,customFunctionsTlsCertificateAuthority:Dt.CA,operationsApi_tls_certificate:Dt["OPERATIONS-API"],operationsApiTlsCertificateAuthority:Dt["OPERATIONS-CA"]},Hoe={[Dt.SERVER]:2,[Dt.DEFAULT]:1},Goe={[Dt["OPERATIONS-API"]]:3,[Dt.SERVER]:2,[Dt.DEFAULT]:1},qoe={[Dt["OPERATIONS-API"]]:3,[Dt.SERVER]:2,[Dt.DEFAULT]:1},$oe={[Dt["OPERATIONS-CA"]]:3,[Dt.CA]:2,[Dt["DEFAULT-CA"]]:1},Voe={[Dt["OPERATIONS-CA"]]:3,[Dt.CA]:2,[Dt["DEFAULT-CA"]]:1},Koe={[Dt.CA]:2,[Dt["DEFAULT-CA"]]:1};Sn.CERTIFICATE_PEM_NAME=Moe;Sn.PRIVATEKEY_PEM_NAME=Uoe;Sn.CA_PEM_NAME=xoe;Sn.CERT_NAME=Dt;Sn.CERT_CONFIG_NAME_MAP=koe;Sn.CERT_PREFERENCE_APP=Hoe;Sn.CERT_PREFERENCE_OPS=Goe;Sn.CERT_PREFERENCE_REP=qoe;Sn.CA_CERT_PREFERENCE_REP=$oe;Sn.CA_CERT_PREFERENCE_OPS=Voe;Sn.CA_CERT_PREFERENCE_APP=Koe;Sn.CERTIFICATE_VALUES=voe;Sn.NATS_CERTIFICATE_PEM_NAME=Boe;Sn.NATS_CA_PEM_NAME=Foe});var _N=M((dMe,UG)=>{"use strict";var vG=require("fs-extra"),Re=require("joi"),Yoe=require("os"),{boolean:We,string:_t,number:pr,array:ac}=Re.types(),{totalmem:PG}=require("os"),Ml=require("path"),Woe=Q(),EN=ae(),uMe=hN(),LG=(G(),v(j)),joe=pt(),DG="log",zoe="components",Joe="Invalid logging.rotation.maxSize unit. Available units are G, M or K",Qoe="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",Xoe="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",Zoe="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",eae="rootPath config parameter is undefined",Yn=Re.alternatives([pr.min(0),_t]).optional().empty(null),rS=Re.alternatives([ac.items(_t,{host:_t.required(),port:Yn},{hostname:_t.required(),port:Yn}).empty(null),ac.items(_t)]),so,MG=!1;UG.exports={configValidator:tae,routesValidator:aae,routeConstraints:rS};function tae(e,t=!1){if(MG=t,so=e.rootPath,EN.isEmpty(so))throw eae;let r=We.optional(),n=pr.min(0).max(1e3).empty(null).default(oae),s=_t.pattern(/^[\\\/]$|([\\\/a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Pp),i=_t.optional().empty(null),o=_t.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=Re.string().empty(null).default(Pp),l=Re.custom(nae).empty(null).default(Pp),u=e.clustering?.enabled,d=Re.object({certificate:i,certificateAuthority:i,privateKey:i}),f;return u===!0?f=Re.object({enabled:r,hubServer:Re.object({cluster:Re.object({name:Re.required().empty(null),network:Re.object({port:Yn,routes:rS}).required()}).required(),leafNodes:Re.object({network:Re.object({port:Yn}).required()}).required(),network:Re.object({port:Yn}).required()}).required(),leafServer:Re.object({network:Re.object({port:Yn,routes:rS}).required(),streams:Re.object({maxAge:pr.min(120).allow(null).optional(),maxBytes:pr.min(1).allow(null).optional(),maxMsgs:pr.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:Re.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:We.optional(),databaseLevel:We.optional(),tls:Re.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:We.required(),verify:We.optional()}),user:_t.optional().empty(null)}).optional():f=Re.object({enabled:r,tls:Re.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:We.optional()})}).optional(),Re.object({authentication:Re.alternatives(Re.object({authorizeLocal:We,cacheTTL:pr.required(),cookie:Re.object({domains:ac.items(_t).optional(),expires:_t.optional()}),enableSessions:We,hashFunction:_t.valid("md5","sha256","argon2id").optional().empty(null)}),We).optional(),analytics:Re.object({aggregatePeriod:pr,replicate:We.optional()}),replication:Re.object({hostname:Re.alternatives(_t,pr).optional().empty(null),url:_t.optional().empty(null),port:Yn,securePort:Yn,routes:ac.optional().empty(null),databases:Re.alternatives(_t,ac),enableRootCAs:We.optional(),copyTablesToCatchUp:We.optional()}).optional(),componentsRoot:s.optional(),clustering:f,localStudio:Re.object({enabled:r}).required(),logging:Re.object({auditAuthEvents:Re.object({logFailed:We,logSuccessful:We}),file:We.required(),level:Re.valid("notify","fatal","error","warn","info","debug","trace"),rotation:Re.object({enabled:We.optional(),compress:We.optional(),interval:_t.custom(iae).optional().empty(null),maxSize:_t.custom(sae).optional().empty(null),path:_t.optional().empty(null).default(Pp)}).required(),root:s,stdStreams:We.required(),auditLog:We.required()}).required(),operationsApi:Re.object({network:Re.object({cors:We.optional(),corsAccessList:ac.optional(),headersTimeout:pr.min(1).optional(),keepAliveTimeout:pr.min(1).optional(),port:Yn,domainSocket:Re.optional().empty("hdb/operations-server").default(Pp),securePort:Yn,timeout:pr.min(1).optional()}).optional(),tls:Re.alternatives([Re.array().items(d),d])}).required(),rootPath:_t.pattern(/^[\\\/]$|([\\\/a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:Re.object({network:Re.object({port:Yn,securePort:Yn,mtls:Re.alternatives([We.optional(),Re.object({user:_t.optional(),certificateAuthority:i,required:We.optional()})])}).required(),webSocket:We.optional(),requireAuthentication:We.optional()}),http:Re.object({compressionThreshold:pr.optional(),cors:We.optional(),corsAccessList:ac.optional(),headersTimeout:pr.min(1).optional(),port:Yn,securePort:Yn,maxHeaderSize:pr.optional(),mtls:Re.alternatives([We.optional(),Re.object({user:_t.optional(),certificateAuthority:i,required:We.optional()})]),threadRange:Re.alternatives([ac.optional(),_t.optional()])}).required(),threads:Re.alternatives(n.optional(),Re.object({count:n.optional(),debug:Re.alternatives(We.optional(),Re.object({startingPort:pr.min(1).optional(),host:_t.optional(),waitForDebugger:We.optional()})),maxHeapMemory:pr.min(0).optional()})),storage:Re.object({writeAsync:We.required(),overlappingSync:We.optional(),caching:We.optional(),compression:Re.alternatives([We.optional(),Re.object({dictionary:_t.optional(),threshold:pr.optional()})]),compactOnStart:We.optional(),compactOnStartKeepBackup:We.optional(),noReadAhead:We.optional(),path:l,prefetchWrites:We.optional(),maxFreeSpaceToLoad:pr.optional(),maxFreeSpaceToRetain:pr.optional()}).required(),ignoreScripts:We.optional(),tls:Re.alternatives([Re.array().items(d),d])}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(tae,"configValidator");function rae(e){return MG||vG.existsSync(e)?null:`Specified path ${e} does not exist.`}a(rae,"doesPathExist");function nae(e,t){Re.assert(e,_t.pattern(/^[\\\/]$|([\\\/a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=rae(e);if(r)return t.message(r)}a(nae,"validatePath");function sae(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(Joe);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(Xoe):e}a(sae,"validateRotationMaxSize");function iae(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(Qoe);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(Zoe):e}a(iae,"validateRotationInterval");function oae(e,t){let r=t.state.path.join("."),n=Yoe.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||PG();return i=Math.round(Math.min(i,PG())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),Woe.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(oae,"setDefaultThreads");function Pp(e,t){let r=t.state.path.join(".");if(!EN.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(EN.isEmpty(so))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Ml.join(so,zoe);case"logging.root":return Ml.join(so,DG);case"clustering.leafServer.streams.path":return Ml.join(so,"clustering","leaf");case"storage.path":let n=Ml.join(so,LG.LEGACY_DATABASES_DIR_NAME);return vG.existsSync(n)?n:Ml.join(so,LG.DATABASES_DIR_NAME);case"logging.rotation.path":return Ml.join(so,DG);case"operationsApi.network.domainSocket":return r==null?null:Ml.join(so,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Pp,"setDefaultRoot");function aae(e){let t=Re.object({routes:rS});return joe.validateBySchema({routes:e},t)}a(aae,"routesValidator")});var BG={};ye(BG,{getBackupDirPath:()=>nS});function nS(e){return xG.join(e,sA)}var xG,gN=se(()=>{xG=b(require("node:path"));G();a(nS,"getBackupDirPath")});var $G={};ye($G,{ConfigEnvVarError:()=>Ed,applyRuntimeEnvConfig:()=>Eae});function TN(){let{loggerWithTag:e}=sr();return e("env-config")}function sS(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.toString.call(e)==="[object Object]"}function Lp(e,t=""){let r={};for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let s=e[n],i=t?`${t}.${n}`:n;sS(s)?Object.assign(r,Lp(s,i)):r[i]=s}return r}function Dp(e,t){let r=t.split("."),n=e;for(let s of r){if(n==null)return;n=n[s]}return n}function vp(e,t,r){let n=t.split("."),s=e;for(let i=0;i<n.length-1;i++){let o=n[i];sS(s[o])||(s[o]={}),s=s[o]}s[n[n.length-1]]=r}function yN(e,t){let r=t.split("."),n=e;for(let s=0;s<r.length-1;s++){let i=r[s];if(!sS(n[i]))return;n=n[i]}delete n[r[r.length-1]]}function cae(e){let t=a(n=>n===null||typeof n!="object"?JSON.stringify(n):Array.isArray(n)?"["+n.map(t).join(",")+"]":"{"+Object.keys(n).sort().map(o=>JSON.stringify(o)+":"+t(n[o])).join(",")+"}","sortedStringify"),r=t(e);return GG.createHash("sha256").update(r).digest("hex")}function lae(e,t){if(!e||e.trim()==="")return null;try{let r=JSON.parse(e.trim());if(!sS(r))throw new Ed(`${t} must be a JSON object, got: ${typeof r}`,t);return r}catch(r){throw r instanceof Ed?r:new Ed(`Invalid JSON syntax in ${t}: ${r.message}`,t,r)}}function uae(e){let t=SN.join(nS(e),qG);if(!cc.existsSync(t))return{version:"1.0",sources:{},originalValues:{},snapshots:{}};try{let r=cc.readJsonSync(t);return r.originalValues||(r.originalValues={}),r}catch(r){return TN().warn(`Failed to load config state file, starting fresh: ${r.message}`),{version:"1.0",sources:{},originalValues:{},snapshots:{}}}}function dae(e,t){let r=nS(e),n=SN.join(r,qG);cc.ensureDirSync(r),cc.writeJsonSync(n,t,{spaces:2})}function fae(e,t){let r=[];for(let[n,s]of Object.entries(t.sources)){if(s!=="HARPER_DEFAULT_CONFIG"&&s!=="HARPER_SET_CONFIG")continue;let i=t.snapshots[s];if(!i)continue;let o=Dp(e,n),c=Dp(i.config,n);JSON.stringify(o)!==JSON.stringify(c)&&r.push(n)}return r}function FG(e,t,r,n,s={}){let{respectSources:i=[],storeOriginals:o=!1}=s,c=Lp(r);for(let[l,u]of Object.entries(c)){let d=t.sources[l],f=Dp(e,l);d&&i.includes(d)||(o&&!d&&f!==void 0&&f!==null&&(l in t.originalValues||(t.originalValues[l]=f)),vp(e,l,u),t.sources[l]=n)}}function mae(e,t,r,n,s){let i=Object.keys(Lp(r)),o=Object.keys(Lp(n)),c=i.filter(l=>!o.includes(l));for(let l of c)t.sources[l]===s&&((s==="HARPER_DEFAULT_CONFIG"||s==="HARPER_SET_CONFIG")&&l in t.originalValues?(vp(e,l,t.originalValues[l]),delete t.originalValues[l]):yN(e,l),delete t.sources[l])}function pae(e,t,r){let n=Object.keys(t.sources).filter(s=>t.sources[s]===r);for(let s of n)yN(e,s),delete t.sources[s]}function hae(e,t,r){let n={};for(let s in t.sources)if(t.sources[s]===r){let i=Dp(e,s);i!==void 0&&vp(n,s,i)}return n}function kG(e,t,r,n,s={}){let i=process.env[r];if(!i)return;let o=TN(),c=lae(i,r);if(!c)return;let l=cae(c),u=t.snapshots[n];if(n==="HARPER_SET_CONFIG")FG(e,t,c,n,{respectSources:[],storeOriginals:!0});else if(n==="HARPER_DEFAULT_CONFIG")if(s.isInstall)FG(e,t,c,n,{respectSources:["HARPER_SET_CONFIG","user"],storeOriginals:!0});else{let m=Lp(c);for(let[p,h]of Object.entries(m)){let E=t.sources[p],_=Dp(e,p);if(!(E&&E!=="HARPER_DEFAULT_CONFIG")){if(!E&&_!=null){p in t.originalValues||(t.originalValues[p]=_);continue}vp(e,p,h),t.sources[p]=n}}}u&&u.hash!==l&&mae(e,t,u.config,c,n);let d=hae(e,t,n);t.snapshots[n]={hash:l,config:d};let f=s.isInstall?"installation":"runtime";o.debug?.(`Applied ${r} at ${f}`)}function HG(e,t,r,n){if(!t.snapshots[n])return;let s=TN();if(n==="HARPER_DEFAULT_CONFIG"||n==="HARPER_SET_CONFIG"){let i=Object.keys(t.sources).filter(o=>t.sources[o]===n);for(let o of i)o in t.originalValues?(vp(e,o,t.originalValues[o]),delete t.originalValues[o]):yN(e,o),delete t.sources[o]}else pae(e,t,n);delete t.snapshots[n],s.debug?.(`${r} removed, cleaned up values`)}function Eae(e,t,r={}){let n=process.env.HARPER_DEFAULT_CONFIG,s=process.env.HARPER_SET_CONFIG,i=uae(t);if(!n&&!s&&Object.keys(i.snapshots).length===0)return e;if(!r.isInstall){let o=fae(e,i);for(let c of o)i.sources[c]="user"}return kG(e,i,"HARPER_DEFAULT_CONFIG","HARPER_DEFAULT_CONFIG",r),n||HG(e,i,"HARPER_DEFAULT_CONFIG","HARPER_DEFAULT_CONFIG"),kG(e,i,"HARPER_SET_CONFIG","HARPER_SET_CONFIG",r),s||HG(e,i,"HARPER_SET_CONFIG","HARPER_SET_CONFIG"),dae(t,i),e}var cc,SN,GG,qG,Ed,VG=se(()=>{cc=b(require("fs-extra")),SN=b(require("node:path")),GG=b(require("node:crypto"));gN();qG=".harper-config-state.json";a(TN,"getLogger");Ed=class extends Error{static{a(this,"ConfigEnvVarError")}envVarName;originalError;constructor(t,r,n){super(t),this.name="ConfigEnvVarError",this.envVarName=r,this.originalError=n}};a(sS,"isPlainObject");a(Lp,"flattenObject");a(Dp,"getNestedValue");a(vp,"setNestedValue");a(yN,"deleteNestedValue");a(cae,"hashConfig");a(lae,"parseConfigEnvVar");a(uae,"loadConfigState");a(dae,"saveConfigState");a(fae,"detectConfigDrift");a(FG,"applyConfigLayer");a(mae,"handleDeletions");a(pae,"removeValuesWithSource");a(hae,"buildSnapshot");a(kG,"processEnvVar");a(HG,"cleanupRemovedEnvVar");a(Eae,"applyRuntimeEnvConfig")});var gt=M(or=>{"use strict";var ks=(G(),v(j)),Cr=ae(),vt=Q(),{configValidator:_ae,routesValidator:KG}=_N(),nn=require("fs-extra"),aS=require("yaml"),hs=require("path"),gae=require("is-number"),WG=require("properties-reader"),Sae=require("lodash"),{handleHDBError:Tae}=Ee(),{HTTP_STATUS_CODES:yae,HDB_ERROR_MSGS:_d}=Jr(),{server:Rae}=(Hr(),v(Tm)),{PACKAGE_ROOT:jG}=Rt(),{getBackupDirPath:bae}=(gN(),v(BG)),{DATABASES_PARAM_CONFIG:Mp,CONFIG_PARAMS:ps,CONFIG_PARAM_MAP:mi}=ks,Aae="Unable to get config value because config is uninitialized",Iae="Config successfully initialized",wae="Error backing up config file",Nae="Empty parameter sent to getConfigValue",zG=hs.join(jG,"config","yaml",ks.HDB_DEFAULT_CONFIG_FILE),Cae=hs.join(jG,"config","yaml","defaultNatsConfig.yaml"),Oae="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",YG={logging_rotation_retain:"logging.rotation.retain",logging_rotation_rotate:"logging.rotation.rotate",logging_rotation_rotateinterval:"logging.rotation.rotateInterval",logging_rotation_rotatemodule:"logging.rotation.rotateModule",logging_rotation_timezone:"logging.rotation.timezone",logging_rotation_workerinterval:"logging.rotation.workerInterval"},iS,kt,oS;or.createConfigFile=Pae;or.getDefaultConfig=Lae;or.getConfigValue=QG;or.initConfig=cS;or.flattenConfig=gd;or.updateConfigValue=XG;or.updateConfigObject=vae;or.getConfiguration=xae;or.setConfiguration=Bae;or.readConfigFile=IN;or.getClusteringRoutes=Fae;or.initOldConfig=eq;or.getConfigFromFile=kae;or.getConfigFilePath=Ul;or.addConfig=Hae;or.deleteConfigFromFile=Gae;or.getConfigObj=qae;or.resolvePath=RN;or.getFlatConfigObj=$ae;function RN(e){if(e?.startsWith("~/"))return hs.join(Cr.getHomeDir(),e.slice(1));let t=fe();try{return hs.resolve(t.getHdbBasePath(),e)}catch(r){return console.error("Unable to resolve path",e,r),e}}a(RN,"resolvePath");function Pae(e,t=!1){let r=lc(zG);if(e.clustering_enabled||e.CLUSTERING_ENABLED||e.clustering){let c=aS.parseDocument(nn.readFileSync(Cae,"utf8"),{simpleKeys:!0});r.addIn(["clustering"],c.toJSON().clustering)}iS=gd(r.toJSON());let n;for(let c in e){let l=mi[c.toLowerCase()];if(l===ps.DATABASES){Array.isArray(e[c])?n=e[c]:n=Object.keys(e[c]).map(u=>({[u]:e[c][u]}));continue}if(!l&&(c.endsWith("_package")||c.endsWith("_port"))&&(l=c),l!==void 0){let u=l.split("_"),d=bN(l,e[c]);l==="rootPath"&&d?.endsWith("/")&&(d=d.slice(0,-1));try{u.length>1&&typeof r.getIn(u.slice(0,-1))=="boolean"&&r.deleteIn(u.slice(0,-1)),r.setIn([...u],d)}catch(f){vt.error(f)}}}n&&JG(r,n),AN(r,t),ZG(r,null,{isInstall:!0});let s=r.toJSON();kt=gd(s);let i=r.getIn(["rootPath"]),o=hs.join(i,ks.HDB_CONFIG_FILE);if(nn.createFileSync(o),r.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${r.errors}`);nn.writeFileSync(o,String(r)),vt.trace(`Config file written to ${o}`)}a(Pae,"createConfigFile");function JG(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!Cr.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(Mp.TABLES))for(let i in n[s][Mp.TABLES])for(let o in n[s][Mp.TABLES][i]){let c=n[s][Mp.TABLES][i][o],l=[ps.DATABASES,s,Mp.TABLES,i,o];e.hasIn(l)?e.setIn(l,c):e.addIn(l,c)}else for(let i in n[s]){let o=n[s][i],c=[ps.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){vt.error("Error parsing schemas CLI/env config arguments",n)}}a(JG,"setSchemasConfig");function Lae(e){if(iS===void 0){let r=lc(zG);iS=gd(r.toJSON())}let t=mi[e.toLowerCase()];if(t!==void 0)return iS[t.toLowerCase()]}a(Lae,"getDefaultConfig");function QG(e){if(e==null){vt.info(Nae);return}if(kt===void 0){vt.trace(Aae);return}let t=mi[e.toLowerCase()];if(t!==void 0)return kt[t.toLowerCase()]}a(QG,"getConfigValue");function Ul(e=Cr.getPropsFilePath()){let t=Cr.getEnvCliRootPath();if(t)return RN(hs.join(t,ks.HDB_CONFIG_FILE));let r=WG(e);return RN(r.get(ks.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY))}a(Ul,"getConfigFilePath");function cS(e=!1){if(kt===void 0||e){let t;if(!Cr.noBootFile()){t=Cr.getPropsFilePath();try{nn.accessSync(t,nn.constants.F_OK|nn.constants.R_OK)}catch(i){throw vt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Ul(t),n;if(r.includes("config/settings.js"))try{eq(r);return}catch(i){if(i.code!==ks.NODE_ERROR_CODES.ENOENT)throw i}try{n=lc(r)}catch(i){if(i.code===ks.NODE_ERROR_CODES.ENOENT){vt.trace(`HarperDB config file not found at ${r}.
14
14
  This can occur during early stages of install where the config file has not yet been created`);return}else throw vt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}Dae(n,r),ZG(n,r),AN(n);let s=n.toJSON();if(Rae.config=s,kt=gd(s),kt.logging_rotation_rotate)for(let i in YG)kt[i]&&vt.error(`Config ${YG[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);vt.trace(Iae)}}a(cS,"initConfig");function Dae(e,t){let r=e.getIn(["rootPath"]),n=!1;if(e.hasIn(["storage","path"])||(e.setIn(["storage","path"],hs.join(r,"database")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],hs.join(r,"log")),n=!0),e.hasIn(["authentication"])||(e.addIn(["authentication"],{cacheTTL:3e4,enableSessions:!0,operationTokenTimeout:e.getIn(["operationsApi","authentication","operationTokenTimeout"])??"1d",refreshTokenTimeout:e.getIn(["operationsApi","authentication","refreshTokenTimeout"])??"30d"}),n=!0),e.hasIn(["analytics"])||(e.addIn(["analytics"],{aggregatePeriod:60,replicate:!1}),n=!0),n){if(vt.trace("Updating config file with missing config params"),e.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${e.errors}`);nn.writeFileSync(t,String(e))}}a(Dae,"checkForUpdatedConfig");function AN(e,t=!1){let r=e.toJSON();if(r.componentsRoot=r.componentsRoot??r?.customFunctions?.root,r?.http?.threads&&(r.threads=r?.http?.threads),r.http?.port&&r.http?.port===r.http?.securePort)throw _d.CONFIG_VALIDATION("http.port and http.securePort cannot be the same value");if(r.operationsApi?.network?.port&&r.operationsApi?.network?.port===r.operationsApi?.network?.securePort)throw _d.CONFIG_VALIDATION("operationsApi.network.port and operationsApi.network.securePort cannot be the same value");let n=_ae(r,t);if(n.error)throw _d.CONFIG_VALIDATION(n.error.message);typeof n.value.threads=="object"?e.setIn(["threads","count"],n.value.threads.count):e.setIn(["threads"],n.value.threads),e.setIn(["componentsRoot"],n.value.componentsRoot),e.setIn(["logging","root"],n.value.logging.root),e.setIn(["storage","path"],n.value.storage.path),e.setIn(["logging","rotation","path"],n.value.logging.rotation.path),e.setIn(["operationsApi","network","domainSocket"],n.value?.operationsApi?.network?.domainSocket),r?.clustering?.enabled&&e.setIn(["clustering","leafServer","streams","path"],n.value.clustering.leafServer.streams?.path)}a(AN,"validateConfig");function vae(e,t){kt===void 0&&(kt={});let r=mi[e.toLowerCase()];if(r===void 0){vt.trace(`Unable to update config object because config param '${e}' does not exist`);return}kt[r.toLowerCase()]=t}a(vae,"updateConfigObject");function XG(e,t,r=void 0,n=!1,s=!1,i=!1){kt===void 0&&cS();let o=QG(mi.hdb_root),c=hs.join(o,ks.HDB_CONFIG_FILE),l=lc(c),u;if(r&&kt){let m=!1;for(let p in r)if(r[p]!=kt[p.toLowerCase()]){m=!0;break}if(!m){vt.trace("No changes detected in config parameters, skipping update");return}}if(r===void 0&&e.toLowerCase()===ps.DATABASES)u=t;else if(r===void 0){let m;if(i)m=e;else if(m=mi[e.toLowerCase()],m===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let p=m.split("_"),h=bN(m,t);l.setIn([...p],h)}else for(let m in r){let p=mi[m.toLowerCase()];if(p===ps.HTTP_SECUREPORT&&r[m]===kt[ps.HTTP_PORT]?.toString()&&l.setIn(["http","port"],null),p===ps.OPERATIONSAPI_NETWORK_SECUREPORT&&r[m]===kt[ps.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&l.setIn(["operationsApi","network","port"],null),p===ps.DATABASES){u=r[m];continue}if(p?.startsWith("threads_")){let h=l.getIn(["threads"]);h>=0&&(l.deleteIn(["threads"]),l.setIn(["threads","count"],h))}if(!p&&(m.endsWith("_package")||m.endsWith("_port"))&&(p=m),p!==void 0){let h=p.split("_"),E=ks.LEGACY_CONFIG_PARAMS[m.toUpperCase()];E&&E.startsWith("customFunctions")&&l.hasIn(E.split("_"))&&(p=E,h=E.split("_"));let _=bN(p,r[m]);p==="rootPath"&&_?.endsWith("/")&&(_=_.slice(0,-1));try{h.length>1&&typeof l.getIn(h.slice(0,-1))=="boolean"&&l.deleteIn(h.slice(0,-1)),l.setIn([...h],_)}catch(R){vt.error(R)}}}u&&JG(l,u),AN(l);let d=l.getIn(["rootPath"]),f=hs.join(d,ks.HDB_CONFIG_FILE);if(n===!0&&Mae(c,d),l.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${l.errors}`);nn.writeFileSync(f,String(l)),s&&(kt=gd(l.toJSON())),vt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(XG,"updateConfigValue");function Mae(e,t){try{let r=hs.join(bae(t),`${new Date(Date.now()).toISOString().replaceAll(":","-")}-${ks.HDB_CONFIG_FILE}.bak`);nn.copySync(e,r),vt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){vt.error(wae),vt.error(r)}}a(Mae,"backupConfigFile");var Uae=["databases"];function gd(e){return e.http&&Object.assign(e.http,e?.customFunctions?.network),e?.operationsApi?.network&&(e.operationsApi.network={...e.http,...e.operationsApi.network}),e?.operationsApi&&(e.operationsApi.tls={...e.tls,...e.operationsApi.tls}),oS=e,r(e);function r(n){let s={};for(let i in n)if(n.hasOwnProperty(i)){if(typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])&&!Uae.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let l=i+"_"+c;!ps[l.toUpperCase()]&&mi[l]&&(s[mi[l].toLowerCase()]=o[c]),s[l]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(gd,"flattenConfig");function bN(e,t){if(e===ps.CLUSTERING_NODENAME||e===ps.CLUSTERING_USER){if(t==null)return t;if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(gae(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Cr.isObject(t)||t===null)return t;if(typeof t=="string"&&t.toLowerCase()==="true")return!0;if(typeof t=="string"&&t.toLowerCase()==="false")return!1}if(t===void 0||t.toLowerCase()==="undefined")return null;if(typeof t=="string"&&(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))try{return JSON.parse(t)}catch{}return Cr.autoCast(t)}a(bN,"castConfigValue");function xae(){let e=Cr.getPropsFilePath(),t=Ul(e);return lc(t).toJSON()}a(xae,"getConfiguration");async function Bae(e){let{operation:t,hdb_user:r,hdbAuthHeader:n,...s}=e;try{return XG(void 0,void 0,s,!0),Oae}catch(i){throw typeof i=="string"||i instanceof String?Tae(i,i,yae.BAD_REQUEST,void 0,void 0,!0):i}}a(Bae,"setConfiguration");function IN(){let e=Cr.getPropsFilePath();try{nn.accessSync(e,nn.constants.F_OK|nn.constants.R_OK)}catch(n){if(!Cr.noBootFile())throw vt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Ul(e);return lc(t).toJSON()}a(IN,"readConfigFile");function lc(e){return aS.parseDocument(nn.readFileSync(e,"utf8"),{simpleKeys:!0})}a(lc,"parseYamlDoc");function ZG(e,t,r={}){let n=process.env.HARPER_DEFAULT_CONFIG,s=process.env.HARPER_SET_CONFIG;if(!n&&!s)return;let{applyRuntimeEnvConfig:i}=(VG(),v($G)),o=e.getIn(["rootPath"]);if(!o){vt.warn("Cannot apply runtime env config: rootPath not found in config");return}let c=e.toJSON();try{i(c,o,r);let l=aS.parseDocument(aS.stringify(c),{simpleKeys:!0});Object.assign(e,l)}catch(l){throw vt.error(`Failed to apply runtime env config: ${l.message}`),l}if(t)try{if(e.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml: ${e.errors}`);nn.writeFileSync(t,String(e)),vt.debug("Config file updated with runtime env var values")}catch(l){throw vt.error(`Failed to write config file after applying runtime env vars: ${l.message}`),l}}a(ZG,"applyRuntimeEnvVarConfig");function Fae(){let e=IN(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Cr.isEmptyOrZeroLength(t)?[]:t;let r=KG(t);if(r)throw _d.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Cr.isEmptyOrZeroLength(n)?[]:n;let s=KG(n);if(s)throw _d.CONFIG_VALIDATION(s.message);if(!Cr.isEmptyOrZeroLength(n)&&!Cr.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!Cr.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw _d.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(Fae,"getClusteringRoutes");function eq(e){let t=WG(e);kt={};for(let r in mi){let n=t.get(r.toUpperCase());if(Cr.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=mi[r].toLowerCase();s===ps.LOGGING_ROOT?kt[s]=hs.dirname(n):kt[s]=n}return kt}a(eq,"initOldConfig");function kae(e){let t=IN();return Sae.get(t,e.replaceAll("_","."))}a(kae,"getConfigFromFile");async function Hae(e,t){let r=lc(Ul());if(r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),r.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${r.errors}`);await nn.writeFile(Ul(),String(r))}a(Hae,"addConfig");function Gae(e){let t=Ul(Cr.getPropsFilePath()),r=lc(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=hs.join(n,ks.HDB_CONFIG_FILE);nn.writeFileSync(s,String(r))}a(Gae,"deleteConfigFromFile");function qae(){return oS||(cS(),oS)}a(qae,"getConfigObj");function $ae(){return kt||cS(),kt}a($ae,"getFlatConfigObj")});var ao={};ye(ao,{ACTIVE_BOOLEAN:()=>aq,ALTERUSER_NOTHING_TO_UPDATE:()=>sq,EMPTY_PASSWORD:()=>iq,EMPTY_ROLE:()=>oq,USERNAME_REQUIRED:()=>nq,addUser:()=>vN,alterUser:()=>MN,dropUser:()=>UN,findAndValidateUser:()=>Td,getClusterUser:()=>tce,getSuperUser:()=>Bp,getUsersWithRolesCache:()=>ece,listUsers:()=>dS,listUsersExternal:()=>BN,setUsersWithRolesCache:()=>hi,userInfo:()=>xN});async function vN(e){let t=uq.cleanAttributes(e,dq),r=lq.addUserValidation(t);if(r)throw new pi(r.message);let n=await xp.searchByValue({schema:"system",table:"hdb_role",attribute:"role",value:t.role,get_attributes:["id","permission","role"]});if(!n||n.length<1)throw new pi(Sd.ROLE_NAME_NOT_FOUND(t.role),ta.NOT_FOUND);if(n.length>1)throw new pi(Sd.DUP_ROLES_FOUND(t.role),ta.CONFLICT);n[0].permission.cluster_user===!0&&(t.hash=LN.encrypt(t.password)),t.password=await Up.hash(t.password,lS),t.hash_function=lS,t.role=n[0].id;let s=await cq.insert({operation:"insert",schema:"system",table:"hdb_user",records:[t]});if(PN.debug(s),await hi(),s.skipped_hashes.length===1)throw new pi(Sd.USER_ALREADY_EXISTS(t.username),ta.CONFLICT);return ON.signalUserChange(new DN(process.pid)),`${t.username} successfully added`}async function MN(e){let t=uq.cleanAttributes(e,dq);if(io.isEmptyOrZeroLength(t.username))throw new Error(nq);if(io.isEmptyOrZeroLength(t.password)&&io.isEmptyOrZeroLength(t.role)&&io.isEmptyOrZeroLength(t.active))throw new Error(sq);if(!io.isEmpty(t.password)&&io.isEmptyOrZeroLength(t.password.trim()))throw new Error(iq);if(!io.isEmpty(t.active)&&!io.isBoolean(t.active))throw new Error(aq);if(!io.isEmpty(t.password)&&!io.isEmptyOrZeroLength(t.password.trim())&&(Xae(t.username)&&(t.hash=LN.encrypt(t.password)),t.password=await Up.hash(t.password,lS),t.hash_function=lS),t.role==="")throw new Error(oq);if(t.role){let n=await xp.searchByValue({schema:"system",table:"hdb_role",attribute:"role",value:t.role,get_attributes:["*"]});if(!n||n.length===0)throw new pi(Sd.ALTER_USER_ROLE_NOT_FOUND(t.role),ta.NOT_FOUND);if(n.length>1)throw new pi(Sd.DUP_ROLES_FOUND(t.role),ta.CONFLICT);t.role=n[0].id}let r=await cq.update({operation:"update",schema:"system",table:"hdb_user",records:[t]});return await hi(),ON.signalUserChange(new DN(process.pid)),r}function Xae(e){let t=!1,r=oo.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}async function UN(e){let t=lq.dropUserValidation(e);if(t)throw new pi(t.message);if(oo.get(e.username)===void 0)throw new pi(Sd.USER_NOT_EXIST(e.username),ta.NOT_FOUND);let r=await Qae({table:"hdb_user",schema:"system",hash_values:[e.username]});return PN.debug(r),await hi(),ON.signalUserChange(new DN(process.pid)),`${e.username} successfully deleted`}async function xN(e){if(!e||!e.hdb_user)return"There was no user info in the body";let t=CN.cloneDeep(e.hdb_user),r=await xp.searchByHash({schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]});return t.role=r[0],delete t.password,delete t.refresh_token,delete t.hash,delete t.hash_function,t}async function BN(){let e=await dS();return e.forEach(t=>{delete t.password,delete t.hash,delete t.refresh_token,delete t.hash_function}),[...e.values()]}async function dS(){let e=await xp.searchByValue({schema:"system",table:"hdb_role",value:"*",attribute:"role",get_attributes:["*"]}),t={};for(let s of e)t[s.id]=CN.cloneDeep(s);if(Object.keys(t).length===0)return null;let r=await xp.searchByValue({schema:"system",table:"hdb_user",value:"*",attribute:"username",get_attributes:["*"]}),n=new Map;for(let s of r)s=CN.cloneDeep(s),s.role=t[s.role],Zae(s.role),n.set(s.username,s);return n}function Zae(e){if(!e){PN.error("invalid user role found.");return}e.permission.system||(e.permission.system={tables:{}}),e.permission.system.tables||(e.permission.system.tables={});for(let t of Object.keys(jae)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}async function hi(e=void 0){e?oo=e:oo=await dS()}async function ece(){return oo||await hi(),oo}async function Td(e,t,r=!0){oo||await hi();let n=oo.get(e);if(!n){if(!r)return{username:e};throw new pi(wN.GENERIC_AUTH_FAIL,ta.UNAUTHORIZED)}if(n&&!n.active)throw new pi(wN.USER_INACTIVE,ta.UNAUTHORIZED);let s={active:n.active,username:n.username};if(n.refresh_token&&(s.refresh_token=n.refresh_token),n.role&&(s.role=n.role),r===!0){if(rq.get(t)===n.password)return s;{let i=Up.validate(n.password,t,n.hash_function||Up.HASH_FUNCTION.MD5);if(i?.then&&(i=await i),i===!0)rq.set(t,n.password);else throw new pi(wN.GENERIC_AUTH_FAIL,ta.UNAUTHORIZED)}}return s}async function Bp(){oo||await hi();for(let[,e]of oo)if(e.role.role==="super_user")return e}async function tce(){let e=await dS(),t=Yae.getConfigFromFile(NN.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(r==null||r?.role?.role!==NN.ROLE_TYPES_ENUM.CLUSTER_USER)return;let n=LN.decrypt(r.hash);return r.decrypt_hash=n,r.uri_encoded_d_hash=encodeURIComponent(n),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+tq.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+tq.SERVER_SUFFIX.ADMIN,r}var nq,sq,iq,oq,aq,cq,Vae,Up,lq,xp,ON,io,uq,PN,Kae,LN,NN,tq,Yae,Wae,jae,zae,pi,ta,wN,Sd,DN,CN,uS,Jae,dq,rq,Qae,lS,oo,fq,Es=se(()=>{"use strict";nq="username is required",sq="nothing to update, must supply active, role or password to update",iq="password cannot be an empty string",oq="If role is specified, it cannot be empty.",aq="active must be true or false",cq=Vn(),Vae=Dl(),Up=(rN(),v(tN)),lq=jH(),xp=gn(),ON=Qo(),io=ae(),uq=require("validate.js"),PN=Q(),{promisify:Kae}=require("util"),LN=no(),NN=(G(),v(j)),tq=Lt(),Yae=gt(),Wae=fe(),jae=Xi(),{hdbErrors:zae,ClientError:pi}=Ee(),{HTTP_STATUS_CODES:ta,AUTHENTICATION_ERROR_MSGS:wN,HDB_ERROR_MSGS:Sd}=zae,{UserEventMsg:DN}=ls(),CN=require("lodash"),{server:uS}=(Hr(),v(Tm)),Jae=Q();uS.getUser=(e,t)=>Td(e,t,t!=null);uS.authenticateUser=(e,t)=>Td(e,t);dq={username:!0,active:!0,role:!0,password:!0},rq=new Map,Qae=Kae(Vae.delete),lS=Wae.get(NN.CONFIG_PARAMS.AUTHENTICATION_HASHFUNCTION)??Up.HASH_FUNCTION.SHA256;a(vN,"addUser");a(MN,"alterUser");a(Xae,"isClusterUser");a(UN,"dropUser");a(xN,"userInfo");a(BN,"listUsersExternal");a(dS,"listUsers");a(Zae,"appendSystemTablesToRole");a(hi,"setUsersWithRolesCache");a(ece,"getUsersWithRolesCache");a(Td,"findAndValidateUser");a(Bp,"getSuperUser");a(tce,"getClusterUser");fq=[];uS.invalidateUser=function(e){for(let t of fq)try{t(e)}catch(r){Jae.error("Error invalidating user",r)}};uS.onInvalidatedUser=function(e){fq.push(e)}});var Pe,yd=se(()=>{Pe={HEALTHY:"healthy",WARNING:"warning",ERROR:"error",UNKNOWN:"unknown",LOADING:"loading"}});var Rd,FN=se(()=>{yd();Rd=class{static{a(this,"ComponentStatus")}lastChecked;status;message;error;constructor(t,r,n){this.lastChecked=new Date,this.status=t,this.message=r,this.error=n}updateStatus(t,r){this.status=t,this.message=r,this.lastChecked=new Date,t!==Pe.ERROR&&(this.error=void 0)}markHealthy(t){this.updateStatus(Pe.HEALTHY,t||"Component is healthy")}markError(t,r){this.status=Pe.ERROR,this.error=t,this.message=r||(typeof t=="string"?t:t.message),this.lastChecked=new Date}markWarning(t){this.updateStatus(Pe.WARNING,t)}markLoading(t){this.updateStatus(Pe.LOADING,t||"Component is loading")}isHealthy(){return this.status===Pe.HEALTHY}hasError(){return this.status===Pe.ERROR}isLoading(){return this.status===Pe.LOADING}hasWarning(){return this.status===Pe.WARNING}getSummary(){let t=this.status.toUpperCase(),r=this.message?`: ${this.message}`:"";return`${t}${r}`}}});var xl,uc,kN,bd,HN,Ad,GN,fS=se(()=>{xl=b(Jr()),uc=class extends Error{static{a(this,"ComponentStatusError")}statusCode;timestamp;constructor(t,r=xl.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR){super(t),this.name="ComponentStatusError",this.statusCode=r,this.timestamp=new Date,Error.captureStackTrace(this,this.constructor)}},kN=class extends uc{static{a(this,"CrossThreadTimeoutError")}requestId;timeoutMs;collectedCount;constructor(t,r,n){super(`Component status collection timeout after ${r}ms. Collected ${n} responses for request ${t}.`,xl.HTTP_STATUS_CODES.GATEWAY_TIMEOUT),this.name="CrossThreadTimeoutError",this.requestId=t,this.timeoutMs=r,this.collectedCount=n}},bd=class extends uc{static{a(this,"ITCError")}operation;cause;constructor(t,r){super(`Inter-thread communication failed during ${t}: ${r?.message||"Unknown error"}`,xl.HTTP_STATUS_CODES.SERVICE_UNAVAILABLE),this.name="ITCError",this.operation=t,this.cause=r}},HN=class extends uc{static{a(this,"AggregationError")}componentCount;cause;constructor(t,r){super(`Failed to aggregate status for ${t} components: ${r?.message||"Unknown error"}`,xl.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR),this.name="AggregationError",this.componentCount=t,this.cause=r}},Ad=class extends uc{static{a(this,"ComponentStatusOperationError")}componentName;operation;constructor(t,r,n){super(`Component '${t}' ${r} failed: ${n}`,xl.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR),this.name="ComponentStatusOperationError",this.componentName=t,this.operation=r}},GN=class extends uc{static{a(this,"CrossThreadCollectionError")}result;constructor(t){let r=t.success?`Partial collection success: ${t.collectedFromThreads} threads responded`+(t.timedOutThreads.length>0?`, ${t.timedOutThreads.length} timed out`:""):`Collection failed: ${t.errors.map(n=>n.message).join(", ")}`;super(r,xl.HTTP_STATUS_CODES.OK),this.name="CrossThreadCollectionError",this.result=t}getDiagnostics(){let t=[`Cross-thread collection ${this.result.success?"partially succeeded":"failed"}`,`Threads responded: ${this.result.collectedFromThreads}`];return this.result.expectedThreads&&t.push(`Expected threads: ${this.result.expectedThreads}`),this.result.timedOutThreads.length>0&&t.push(`Timed out threads: ${this.result.timedOutThreads.join(", ")}`),this.result.errors.length>0&&(t.push("Errors:"),this.result.errors.forEach((r,n)=>{t.push(` ${n+1}. ${r.name}: ${r.message}`)})),t.join(`
15
15
  `)}}});var mq,Bl,pq,dc,Fp,Id,rce,mS,qN=se(()=>{mq=b(ls()),Bl=b(st());G();pq=b(sr());yd();fS();dc=(0,pq.loggerWithTag)("componentStatus.crossThread"),Fp=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,Bl.onMessageByType)(T_.COMPONENT_STATUS_RESPONSE,({message:t})=>{let r=t.isMainThread?"main":`worker-${t.workerIndex}`;dc.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&&(dc.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,Bl.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(),dc.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),dc.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,mq.sendItcEvent)({type:T_.COMPONENT_STATUS_REQUEST,message:{requestId:r}}).then(()=>{_()}).catch(y=>{E=!0,S(),this.responseCheckers.delete(r),h(new bd("sendItcEvent",y))})});this.responseCheckers.delete(r);let u=new Map,d=t.getAllStatuses(),f=(0,Bl.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 dc.debug?.(`Collected component status from ${l.length+1} threads (including local)`),u}catch(r){return r instanceof bd?dc.error?.(`ITC failure during component status collection: ${r.message}`):dc.warn?.("Failed to collect component status from all threads:",r),dc.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,Bl.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)}},Id=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}},rce=parseInt(process.env.COMPONENT_STATUS_TIMEOUT||"5000"),mS=new Fp(rce)});var fc,pS=se(()=>{FN();yd();qN();fS();fc=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 Ad(String(t),"setStatus","Component name must be a non-empty string");if(!Object.values(Pe).includes(r))throw new Ad(t,"setStatus",`Invalid status level: ${r}. Must be one of: ${Object.values(Pe).join(", ")}`);this.statusMap.set(t,new Rd(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 mS.collect(t);return Id.aggregate(r)}async getAggregatedStatusFor(t,r){r||(r=await e.getAggregatedFromAllThreads(this));let n=[],s=t+".",i=r.get(t);i&&n.push({key:t,...i});for(let[f,m]of r)f.startsWith(s)&&n.push({key:f,...m});if(n.length===0)return{status:Pe.UNKNOWN,message:"The component has not been loaded yet (may need a restart)",lastChecked:{workers:{}}};let o=n.some(f=>f.status===Pe.ERROR),c=n.some(f=>f.status===Pe.LOADING),l=o?Pe.ERROR:c?Pe.LOADING:Pe.HEALTHY,u="All components loaded successfully",d={};if(o||c){u=n.filter(m=>m.status===Pe.ERROR||m.status===Pe.LOADING).map(m=>`${m.key}: ${m.latestMessage||m.status}`).join("; ");for(let m of n)m.status!==Pe.HEALTHY&&(d[m.key]={status:m.status,message:m.latestMessage})}return{status:l,message:u,...Object.keys(d).length>0&&{details:d},lastChecked:n[0]?.lastChecked||{workers:{}}}}}});var hr,hS=se(()=>{pS();hr=new fc});function Eq(e){let t=hq.get(e);return t||(t=new $N(e),hq.set(e,t)),t}function _q(){hr.reset()}var $N,hq,co,gq,Sq=se(()=>{hS();yd();$N=class{static{a(this,"ComponentStatusBuilder")}componentName;constructor(t){this.componentName=t}healthy(t){return hr.setStatus(this.componentName,Pe.HEALTHY,t),this}warning(t){return hr.setStatus(this.componentName,Pe.WARNING,t),this}error(t,r){return hr.setStatus(this.componentName,Pe.ERROR,t,r),this}loading(t){return hr.setStatus(this.componentName,Pe.LOADING,t||"Loading..."),this}unknown(t){return hr.setStatus(this.componentName,Pe.UNKNOWN,t),this}get(){return hr.getStatus(this.componentName)}},hq=new Map;a(Eq,"statusForComponent");co={loading(e,t){hr.initializeLoading(e,t)},loaded(e,t){hr.markLoaded(e,t)},failed(e,t,r){hr.markFailed(e,t,r)}};a(_q,"reset");gq=Pe});var kp={};ye(kp,{AggregationError:()=>HN,COMPONENT_STATUS_LEVELS:()=>Pe,ComponentStatus:()=>Rd,ComponentStatusError:()=>uc,ComponentStatusOperationError:()=>Ad,ComponentStatusRegistry:()=>fc,CrossThreadCollectionError:()=>GN,CrossThreadStatusCollector:()=>Fp,CrossThreadTimeoutError:()=>kN,ITCError:()=>bd,StatusAggregator:()=>Id,componentStatusRegistry:()=>hr,crossThreadCollector:()=>mS,query:()=>nce});var nce,Tq=se(()=>{hS();pS();FN();pS();qN();hS();fS();yd();nce={get(e){return hr.getStatus(e)},all(){return hr.getAllStatuses()},byStatus(e){return hr.getComponentsByStatus(e)},summary(){return hr.getStatusSummary()},async allThreads(){return fc.getAggregatedFromAllThreads(hr)}}});var VN={};ye(VN,{STATUS:()=>gq,internal:()=>kp,lifecycle:()=>co,reset:()=>_q,statusForComponent:()=>Eq});var Hp=se(()=>{Sq();Tq()});var qp=M((QMe,bq)=>{"use strict";var _s=Q(),Tn=(G(),v(j)),sce=vB(),ice=(Es(),v(ao)),{validateEvent:KN}=ls(),Gp=fs(),oce=require("process"),{resetDatabases:ace}=(Oe(),v(mt)),cce={[Tn.ITC_EVENT_TYPES.SCHEMA]:lce,[Tn.ITC_EVENT_TYPES.USER]:Rq,[Tn.ITC_EVENT_TYPES.COMPONENT_STATUS_REQUEST]:dce};async function lce(e){let t=KN(e);if(t){_s.error(t);return}_s.trace("ITC schemaHandler received schema event:",e),await sce(e.message),await uce(e.message)}a(lce,"schemaHandler");async function uce(e){try{Gp.resetReadTxn(Tn.SYSTEM_SCHEMA_NAME,Tn.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Gp.resetReadTxn(Tn.SYSTEM_SCHEMA_NAME,Tn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Gp.resetReadTxn(Tn.SYSTEM_SCHEMA_NAME,Tn.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=ace();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){_s.error(t)}}a(uce,"syncSchemaMetadata");var yq=[];async function Rq(e){try{try{Gp.resetReadTxn(Tn.SYSTEM_SCHEMA_NAME,Tn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Gp.resetReadTxn(Tn.SYSTEM_SCHEMA_NAME,Tn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){_s.warn(r)}let t=KN(e);if(t){_s.error(t);return}_s.trace(`ITC userHandler ${Tn.HDB_ITC_CLIENT_PREFIX}${oce.pid} received user event:`,e),await ice.setUsersWithRolesCache();for(let r of yq)r()}catch(t){_s.error(t)}}a(Rq,"userHandler");Rq.addListener=function(e){yq.push(e)};async function dce(e){try{let t=KN(e);if(t){_s.error(t);return}_s.trace("ITC componentStatusRequestHandler received request:",e);let{internal:r}=(Hp(),v(VN)),{getWorkerIndex:n}=st(),{sendItcEvent:s}=ls(),i=r.componentStatusRegistry.getAllStatuses(),o=Array.from(i.entries()),c=n(),l=c===void 0,u=e.message.originator,d={type:Tn.ITC_EVENT_TYPES.COMPONENT_STATUS_RESPONSE,message:{requestId:e.message.requestId,statuses:o,workerIndex:c,isMainThread:l}};u!==void 0&&threads.sendToThread(u,d)?_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(dce,"componentStatusRequestHandler");bq.exports=cce});var ls=M((nUe,Iq)=>{"use strict";var ZMe=Q(),YN=ae(),fce=(G(),v(j)),{ITC_ERRORS:$p}=Jr(),{parentPort:eUe,threadId:mce,isMainThread:pce,workerData:tUe}=require("worker_threads"),{onMessageFromWorkers:hce,broadcast:rUe,broadcastWithAcknowledgement:Ece}=st();Iq.exports={sendItcEvent:_ce,validateEvent:Aq,SchemaEventMsg:gce,UserEventMsg:Sce};var ES;hce(async(e,t)=>{ES=ES||qp(),Aq(e),ES[e.type]&&await ES[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function _ce(e){return!pce&&e.message&&(e.message.originator=mce),Ece(e)}a(_ce,"sendItcEvent");function Aq(e){if(typeof e!="object")return $p.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||YN.isEmpty(e.type))return $p.MISSING_TYPE;if(!e.hasOwnProperty("message")||YN.isEmpty(e.message))return $p.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||YN.isEmpty(e.message.originator))return $p.MISSING_ORIGIN;if(fce.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return $p.INVALID_EVENT(e.type)}a(Aq,"validateEvent");function gce(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(gce,"SchemaEventMsg");function Sce(e){this.originator=e}a(Sce,"UserEventMsg")});var Qo=M((oUe,Oq)=>{"use strict";var wq=(G(),v(j)),iUe=ae(),_S=Q(),Nq=hB(),wd,{sendItcEvent:Cq}=ls();function Tce(e){try{_S.debug("signalSchemaChange called with message:",e),wd=wd||qp();let t=new Nq(wq.ITC_EVENT_TYPES.SCHEMA,e);return wd.schema(t),Cq(t)}catch(t){_S.error(t)}}a(Tce,"signalSchemaChange");function yce(e){try{_S.trace("signalUserChange called with message:",e),wd=wd||qp();let t=new Nq(wq.ITC_EVENT_TYPES.USER,e);return wd.user(t),Cq(t)}catch(t){_S.error(t)}}a(yce,"signalUserChange");Oq.exports={signalSchemaChange:Tce,signalUserChange:yce}});function Vp(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 Pq(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,Kp=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(Vp,"appendHeader");a(Pq,"mergeHeaders")});function gS(e,t,r=bce){let n;return function(...i){return n?n.length*WN>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();WN=(WN*4+c-i)/5;let l=n.shift();if(l){let{args:u,fn:d}=l;d(),s(c,u)}else n=null})}}var vq,Rce,bce,Lq,Ace,jN,Dq,WN,zN=se(()=>{vq=b(sr()),Rce=3e3,bce=2e4,Lq=0,Ace=3e4,jN=3e3,Dq=performance.now()+jN,WN=0;a(gS,"throttle");setInterval(()=>{let e=performance.now();e-Dq-jN>Rce&&Lq+Ace<e&&(vq.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"),Lq=e),Dq=e},jN).unref()});var Vq={};ye(Vq,{EVICTED:()=>El,INVALIDATED:()=>Fn,coerceType:()=>TS,makeTable:()=>yS});function yS(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=_I(i,n,l),w,I,H={},X=Promise.resolve(),q,k,z;for(let K of S)(K.assignCreatedTime||K.name==="__createdtime__")&&(q=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(k=K),K.expiresAt&&(z=K),K.isPrimaryKey&&(H=K);let Y,ce=[],de=[],te=1,Se=2,Ne={},Ke={},$e=864e5,Ir=0,nr,zr,xr,Ou=!1,zc,Ft,Ps,Ha=kl.get(x.REPLICATION_DATABASES);if(Array.isArray(Ha)){for(let K of Ha)if(K.name===c&&K.replicateTo>=0){Ps=K.replicateTo;break}}let o_=i.getRange({start:!1,end:!1}).constructor,cm=10,a_=6;_&&mm(),Gm(i.env.path,K=>{if(I)return qa(K)});class lm extends wl{static{a(this,"Updatable")}getUpdatedTime(){return Xa.get(this.getRecord())?.version}getExpiresAt(){return Xa.get(this.getRecord())?.expiresAt}addTo(g,T){if(typeof T=="number"||typeof T=="bigint")this.set(g,new yp(T));else throw new Error("Can not add or subtract a non-numeric value")}subtractFrom(g,T){return this.addTo(g,-T)}}class ve extends Xt{#e;#t;#n;#r;#s;#i;static name=s;static primaryStore=i;static auditStore=l;static primaryKey=t;static tableName=s;static tableId=n;static indices=r;static audit=_;static databasePath=o;static databaseName=c;static attributes=S;static replicate=p;static sealed=f;static splitSegments=m??!0;static createdTimeProperty=q;static updatedTimeProperty=k;static propertyResolvers;static userResolvers={};static sources=[];static getResidencyById;static get expirationMS(){return h}static dbisDB=d;static schemaDefined=u;static sourcedFrom(g,T){if(T&&(this.sourceOptions=T,(T.expiration||T.eviction||T.scanInterval)&&this.setTTLExpiration(T)),T?.intermediateSource)g.intermediateSource=!0,this.sources.unshift(g);else{if(this.sources.some(D=>!D.intermediateSource)){if(this.sources.some(D=>D.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(D=>{let A=this.sources;if(A=A.filter(U=>U.intermediateSource&&U[D]&&(!U[D].reliesOnPrototype||U.prototype[D])),A.length>0)if(A.length===1){let U=A[0];return(N,L,$)=>{if(N?.source!==U)return U[D](L,$,N)}}else return(U,N,L)=>{let $=[];for(let W of A){if(U?.source===W)break;$.push(W[D](N,L,U))}return Promise.all($)}},"getApplyToIntermediateSource"),P=this.sources[this.sources.length-1];P.intermediateSource&&(P={});let O=a(D=>{if(P[D]&&(!P[D].reliesOnPrototype||P.prototype[D]))return(A,U,N)=>{if(!A?.source)return P[D](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 D=!1,A,U=a(async(N,L)=>{let $=N.value,W=N.table?Me[c][N.table]:ve;if(c===_m&&(N.table===Uu.ROLE_TABLE_NAME||N.table===Uu.USER_TABLE_NAME)&&(D=!0),N.id===void 0&&(N.id=$[W.primaryKey],N.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(N));N.source=g;let J={residencyId:Jc(N.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:N.nodeId,async:!0},F=N.id,he=await W.getResource(F,L,J);switch(N.finished&&await N.finished,N.type){case"put":return B?he._writeInvalidate(F,$,J):he._writeUpdate(F,$,!0,J);case"patch":return B?he._writeInvalidate(F,$,J):he._writeUpdate(F,$,!1,J);case"delete":return he._writeDelete(F,J);case"publish":case"message":return he._writePublish(F,$,J);case"invalidate":return he._writeInvalidate(F,$,J);case"relocate":return he._writeRelocate(F,J);default:Fe.default.error?.("Unknown operation",N.type,N.id)}},"writeUpdate");try{let N=g.subscribe;N&&R==null&&(R=!0);let L={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},$=g.subscribeOnThisThread?g.subscribeOnThisThread((0,Fl.getWorkerIndex)(),L):(0,Fl.getWorkerIndex)()===0,W=N&&$&&await g.subscribe?.(L);if(W){let J;for await(let F of W)try{if(!(F.type==="transaction"?F.writes[0]:F)){Fe.default.error?.("Bad subscription event",F);continue}if(F.source=g,F.type==="end_txn"){J?.resolve();let _e;if(F.localTime&&A!==F.localTime&&F.remoteNodeIds?.length>0&&(_e=a(()=>{let re=[Symbol.for("seq"),F.remoteNodeIds[0]],oe=d.get(re),ge=oe?.nodes;ge||(ge=[]);for(let ie of F.remoteNodeIds.slice(1)){let Ce=ge.find(Be=>Be.id===ie);ge=ge.filter(Be=>Be.id!==ie||Be===Ce),Ce||(Ce={id:ie,seqId:0},ge.push(Ce)),Ce.seqId=Math.max(oe?.seqId??1,F.localTime),ie===J?.nodeId&&(Ce.lastTxnTime=F.timestamp)}let me=Math.max(oe?.seqId??1,F.localTime);Fe.default.trace?.("Received txn",c,me,new Date(me),F.localTime,new Date(F.localTime),F.remoteNodeIds),d.put(re,{seqId:me,nodes:ge})},"updateRecordedSequenceId"),A=F.localTime),F.onCommit){let re=J?J.committed.then(F.onCommit):F.onCommit();_e&&(re?.then?re.then(_e):_e())}else _e&&_e();continue}if(J)if(F.beginTxn)J.resolve();else{J.writePromises.push(U(F,J));continue}!F.timestamp&&F.version&&(F.timestamp=F.version);let ue=At(F,()=>{if(F.type==="transaction"){let _e=[];for(let re of F.writes)try{_e.push(U(re,F))}catch(oe){throw oe.message+=" writing "+JSON.stringify(re)+" of event "+JSON.stringify(F),oe}return Promise.all(_e)}else if(F.type==="define_schema"){let _e=this.attributes.slice(0),re=!1;for(let oe of F.attributes)_e.find(ge=>ge.name===oe.name)||(_e.push(oe),re=!0);re&&(ze({table:s,database:c,attributes:_e,origin:"cluster"}),Wp.signalSchemaChange(new jp.SchemaEventMsg(process.pid,V.CREATE_TABLE,c,s)))}else return F.beginTxn?(J=F,J.writePromises=[U(F,F)],new Promise(_e=>{J.resolve=()=>_e(Promise.all(J.writePromises))})):U(F,F)});J&&(J.committed=ue),D&&ue&&!ue?.waitingForUserChange&&(ue.then(()=>Wp.signalUserChange(new jp.UserEventMsg(process.pid))),ue.waitingForUserChange=!0),F.onCommit&&(ue?ue.then(F.onCommit):F.onCommit())}catch(he){Fe.default.error?.("error in subscription handler",he)}}}catch(N){Fe.default.error?.(N)}})(),this}static get isCaching(){return I}static get shouldRevalidateEvents(){return this.prototype.get!==ve.prototype.get}static getResource(g,T,C){let P=super.getResource(g,T,C);if(this.loadAsInstance===!1&&(T._freezeRecords=!0),g!=null&&this.loadAsInstance!==!1){ki(g);try{if(P.getRecord?.())return P;if(typeof g=="object"&&g&&!Array.isArray(g))throw new Error(`Invalid id ${JSON.stringify(g)}`);let O=!C?.async||i.cache?.get?.(g),B=Br(T),D=B.getReadTxn();if(D?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return xo(g,T,{transaction:D,ensureLoaded:C?.ensureLoaded},O,A=>{if(A?ve._updateResource(P,A):P.#e=null,T.onlyIfCached){if(!P.doesExist())throw new dt.ServerError("Entry is not cached",504)}else if(C?.ensureLoaded){let U=pn(g,A,T,P);if(U)return B?.disregardReadTxn(),P.#i=!0,T.loadedFromSource=!0,Gs(U,N=>(ve._updateResource(P,N),P))}return P})}catch(O){throw O.message.includes("Unable to serialize object")&&(O.message+=": "+JSON.stringify(g)),O}}return P}static _updateResource(g,T){g.#r=T,g.#e=T?.value??null,g.#n=T?.version}ensureLoaded(){let g=pn(this.getId(),this.#r,this.getContext());if(g)return this.#i=!0,this.getContext().loadedFromSource=!0,Gs(g,T=>{this.#r=T,this.#e=T.value,this.#n=T.version})}static getNewId(){let g=H?.type;if(g==="String"||g==="ID")return super.getNewId();if(!Ft){let O=i.getEntry(Symbol.for("id_allocation")),B=O?.value,D;if(B&&B.nodeName===server.hostname&&(!xce(i)||B.pid===process.pid)){let A=B.start,U=B.end;D=A;for(let N of i.getKeys({start:U,end:A,limit:1,reverse:!0}))D=N}else B=P(O?.version??null),D=B.start;Ft=new BigInt64Array([BigInt(D)+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 D=(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:D,limit:1,transaction:A}))D=$;A?.done();let{value:N,version:L}=i.getEntry(Symbol.for("id_allocation"));if(Ft.maxSafeId<D){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 ${D} 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,D=B/4,A,U,N=!1,L,$;do{L=Math.floor(Math.random()*B),$={start:L,end:L+(g==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},A=0;for(let W of i.getKeys({start:L,limit:1,reverse:!0}))A=W;U=B;for(let W of i.getKeys({start:L+1,end:B,limit:1}))U=W;D*=.875,D<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,D))}while(!(D<U-L&&(D<L-A||A===0)));return i.transactionSync(()=>{let W=i.getEntry(Symbol.for("id_allocation"));return(W?.version??null)==O?(Fe.default.info?.("Allocated new id range",$),i.put(Symbol.for("id_allocation"),$,Date.now()),$):(Fe.default.debug?.("Looks like ids were already allocated"),{alreadyUpdated:!0,...W.value})})}}static setTTLExpiration(g){if(typeof g=="number")h=g*1e3,E||(E=0);else if(g&&typeof g=="object")h=g.expiration*1e3,E=(g.eviction||0)*1e3,$e=g.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(h<0)throw new Error("Expiration can not be negative");$e=$e||(h+E)/4,qa()}static getResidencyRecord(g){return d.get([Symbol.for("residency_by_id"),g])}static setResidency(g){ve.getResidency=g&&((T,C)=>{try{return g(T,C)}catch(P){throw P.message+=` in residency function for table ${s}`,P}})}static setResidencyById(g){ve.getResidencyById=g&&(T=>{try{return g(T)}catch(C){throw C.message+=` in residency function for table ${s}`,C}})}static getResidency(g,T){if(ve.getResidencyById)return ve.getResidencyById(g[t]);let C=Ps;if(T.replicateTo!=null){if(Array.isArray(T.replicateTo))return T.replicateTo.includes(server.hostname)?T.replicateTo:[server.hostname,...T.replicateTo];T.replicateTo>=0&&(C=T.replicateTo)}if(C>=0&&server.nodes){let P=[server.hostname];if(T.previousResidency)P.push(...T.previousResidency.slice(0,C));else{let O=server.nodes.map(A=>A.name),B=Math.floor(O.length*Math.random());P.push(...O.slice(B,B+C));let D=B+C-O.length;D>0&&P.push(...O.slice(0,D))}return P}}static enableAuditing(){_||(_=!0,mm(),ve.audit=!0)}static coerceId(g){return g===""?null:TS(g,H)}static async dropTable(){delete Me[c][s];for(let g of i.getRange({versions:!0,snapshot:!1,lazy:!0}))g.metadataFlags&Xr&&g.value&&za(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(),QN.default.unlinkSync(i.env.path);Wp.signalSchemaChange(new jp.SchemaEventMsg(process.pid,V.DROP_TABLE,c,s))}get(g){let T=this.constructor;if(typeof g=="string"&&T.loadAsInstance!==!1)return this.getProperty(g);if(um(g))return this.search(g);if(g&&g.id===void 0&&!g.toString()){let C={records:"./",name:s,database:c,auditSize:l?.getStats().entryCount,attributes:S,recordCount:void 0,estimatedRecordRange:void 0};return this.getContext()?.includeExpensiveRecordCountEstimates?ve.getRecordCount().then(P=>(C.recordCount=P.recordCount,C.estimatedRecordRange=P.estimatedRange,C)):C}if(g!==void 0&&T.loadAsInstance===!1){let C=this.getContext(),P=Br(C),O=P.getReadTxn();if(O?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");let B=Ls(g);ki(B);let D=!0;return g.checkPermission&&(D=this.allowRead(C.user,g)),Gs(Gs(D,A=>{if(!A)throw new dt.AccessViolation(C.user);let U=!0;return xo(B,C,{transaction:O,ensureLoaded:U},!1,N=>{if(C.onlyIfCached){if(!N?.value)throw new dt.ServerError("Entry is not cached",504)}else if(U){let L=pn(B,N,C);if(L)return P?.disregardReadTxn(),C.loadedFromSource=!0,L.then($=>$?.value)}return N?.value})}),A=>{let U=g?.select;return U&&A!=null?td(U,this.constructor)(A):A})}if(g?.property)return this.getProperty(g.property);if(this.doesExist()||g?.ensureLoaded===!1||this.getContext()?.returnNonexistent)return this}allowRead(g,T){let C=Dn(g,T);if(C?.read){if(C.isSuperUser)return!0;let P=C.attribute_permissions,O=T?.select;if(P?.length>0||Ou&&O){if(T||(T={}),O){let B=Array.isArray(O)?O:[O],D=P?.length>0&&JN(P,"read");T.select=B.map(A=>{let U=A.name||A;if(!D||D[U]){let N=xr[U]?.definition?.tableClass;if(N){if(A.name||(A={name:A}),!A.checkPermission&&T.checkPermission&&(A.checkPermission=T.checkPermission),!N.prototype.allowRead.call(null,g,A))return!1;if(!A.select)return A.name}return A}}).filter(Boolean)}else T.select=P.filter(B=>B.read&&!xr[B.attribute_name]).map(B=>B.attribute_name);return T}else return!0}}allowUpdate(g,T,C){let P=Dn(g,C);if(P?.update){let O=P.attribute_permissions;if(O?.length>0){let B=JN(O,"update");for(let D in T)if(!B[D])return!1;for(let D of O){let A=D.attribute_name;!D.update&&!(A in T)&&(T[A]=this.getProperty(A))}}return Ga(this.getContext())}}allowCreate(g,T,C){if(this.isCollection){let P=Dn(g,C);if(P?.insert){let O=P.attribute_permissions;if(O?.length>0){let B=JN(O,"insert");for(let D in T)if(!B[D])return!1;return Ga(this.getContext())}else return Ga(this.getContext())}}else return this.allowUpdate(g,{})}allowDelete(g,T){return Dn(g,T)?.delete&&Ga(this.getContext())}update(g,T){let C,P=typeof T=="boolean"||T===void 0&&(g==null||typeof g=="object"&&!(g instanceof URLSearchParams)),O=!1;P?(O=T,T=g,C=this.getId()):C=Ls(g);let B=this.getContext();if(!Br(B))throw new Error("Can not update a table resource outside of a transaction");if(T===!1)return this;if(typeof T=="object"&&T)if(O)Object.isFrozen(T)&&(T={...T}),this.#e={},this.#t=T;else if(P){let A=this.#t;A&&(T=Object.assign(A,T)),this.#t=T}else{let A=!0;if(g==null)throw new TypeError("Can not put a record without a target");return g.checkPermission&&(A=this.allowUpdate(B.user,T,g)),Gs(A,U=>{if(!U)throw new dt.AccessViolation(B.user);return Gs(i.get(Ls(g)),N=>{let L=new lm(N);return L._setChanges(T),this._writeUpdate(C,L.getChanges(),!1),L})})}return this._writeUpdate(C,this.#t,O),this}addTo(g,T){if(typeof T=="number"||typeof T=="bigint")this.#s===Uq?this.set(g,(+this.getProperty(g)||0)+T):(this.#s||this.update(),this.set(g,new yp(T)));else throw new Error("Can not add a non-numeric value")}subtractFrom(g,T){if(typeof T=="number")return this.addTo(g,-T);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this.#r}getRecord(){return this.#e}getChanges(){return this.#t}_setChanges(g){this.#t=g}setRecord(g){this.#e=g}invalidate(g){let T=!0,C=this.getContext();return g?.checkPermission&&(T=this.allowDelete(C.user,g,C)),Gs(T,P=>{if(!P)throw new dt.AccessViolation(C.user);this._writeInvalidate(g?Ls(g):this.getId())})}_writeInvalidate(g,T,C){let P=this.getContext();ki(g),Br(this.getContext()).addWrite({key:g,store:i,invalidated:!0,entry:this.#r,before:Ne.invalidate?.bind(this,P,g),beforeIntermediate:vu(T,Ke.invalidate?.bind(this,P,g)),commit:a((B,D)=>{if(!(Fr(B,D,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,D,B,Fn,_,{user:P?.user,residencyId:C?.residencyId,nodeId:C?.nodeId,tableToTrack:s},"invalidate")}},"commit")})}_writeRelocate(g,T){let C=this.getContext();ki(g),Br(this.getContext()).addWrite({key:g,store:i,invalidated:!0,entry:this.#r,before:Ne.relocate?.bind(this,C,g),beforeIntermediate:Ke.relocate?.bind(this,C,g),commit:a((O,B)=>{if(Fr(O,B,T?.nodeId)<=0)return;let D=ve.getResidencyRecord(T.residencyId),A=0,U=null,N=B?.value;if(D&&!D.includes(server.hostname)){for(let L in r)U||(U={}),U[L]=N[L];A=Fn}else U=N;Fe.default.trace?.(`Relocating entry id: ${g}, timestamp: ${new Date(O).toISOString()}`),y(g,U,B,O,A,_,{user:C.user,residencyId:T.residencyId,nodeId:T.nodeId,expiresAt:T.expiresAt},"relocate",!1,null)},"commit")})}static _recordRelocate(g,T){if(this.getResidencyById)return!1;let C={previousResidency:this.getResidencyRecord(g.residencyId),isRelocation:!0},P=$a(this.getResidency(T.value,C)),O;if(P){if(!P.includes(server.hostname))return!1;O=Jc(P)}let B=0;Fe.default.debug?.("Performing a relocate of an entry",g.key,T.value,P);let D=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 D in r)B||(B={}),B[D]=T[D];if(B)return y(g,B,O,C,El,null,null,null,!0)}return i.ifVersion(g,C,()=>{Pu(g,T,null)}),hl(i,O??i.getEntry(g),C)}}lock(){throw new Error("Not yet implemented")}static operation(g,T){return g.table||=s,g.schema||=c,global.operation(g,T)}put(g,T){if(T===void 0||T instanceof URLSearchParams)this.update(g,!0);else{let C=!0;if(g==null)throw new TypeError("Can not put a record without a target");let P=this.getContext();return g.checkPermission&&(C=this.allowUpdate(P.user,T,g)),Gs(C,O=>{if(!O)throw new dt.AccessViolation(P.user);if(Array.isArray(T))for(let B of T){let D=B[t];this._writeUpdate(D,B,!0)}else{let B=Ls(g);this._writeUpdate(B,T,!0)}})}}create(g,T){let C=!0,P=this.getContext();if(!T&&!(g instanceof URLSearchParams)&&(T=g,g=void 0),!T||typeof T!="object"||Array.isArray(T))throw new TypeError("Can not create a record without an object");return g?.checkPermission&&(C=this.allowCreate(P.user,T,g)),Gs(C,O=>{if(!O)throw new dt.AccessViolation(P.user);let B=Ls(g)??T[t];if(B===void 0)B=this.constructor.getNewId(),T[t]=B;else if(i.get(B))throw new dt.ClientError("Record already exists",409);return this._writeUpdate(B,T,!0),T})}patch(g,T){if(T===void 0||T instanceof URLSearchParams)this.update(g,!1);else{let C=this.update(g,T);if(C?.then)return C.then(()=>{})}}_writeUpdate(g,T,C,P){let O=this.getContext(),B=Br(O);ki(g);let D=this.#r??i.getEntry(g);this.#s=C?Uq:Dce;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,Nl(this)):null,"writeToSources"),U={key:g,store:i,entry:D,nodeName:O?.nodeName,validate:a(N=>{T||(T=this.#t),C||T&&Vg(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&&(D?.value?T[q.name]=D?.value[q.name]:T[q.name]=q.type==="Date"?new Date(N):q.type==="String"?new Date(N).toISOString():N),T=Nl(T))):B.removeWrite(U)},"validate"),before:A(Ne),beforeIntermediate:vu(T,A(Ke)),commit:a((N,L,$)=>{if($){if(O&&L?.version>(O.lastModified||0)&&(O.lastModified=L.version),this.#r=L,L?.value&&L.value.getRecord)throw new Error("Can not assign a record to a record, check for circular references");C||(this.#e=L?.value??null)}this.#t=void 0,this.#n=N;let W=L?.value,J;this.#s=0;let F=!1,he=Fr(N,L,P?.nodeId),ue,_e=C?"put":"patch",re;P?.residencyId!=null&&(re=P.residencyId);let oe=O?.expiresAt??(h?h+Date.now():-1);if(he<=0){if(_){let ie=L.localTime,Ce=L.version;Fe.default.trace?.("Applying CRDT update to record with id: ",g,"txn time",new Date(N),"applying later update from:",new Date(Ce),"local recorded time",new Date(ie));let Be=[];for(;ie>N||Ce>=N&&ie>0;){let He=l.get(ie);if(!He)break;let Te=It(He);if(Ce=Te.version,Ce>=N){if(Ce===N){if(he=Fr(N,{version:Ce,localTime:ie},P?.nodeId),he===0)return me(!1);if(he>0){ie=Te.previousLocalTime;continue}}if(Te.type==="patch")Be.push(Te),ue=T;else if(Te.type==="put"||Te.type==="delete")return me(!1)}ie=Te.previousLocalTime}ie||Fe.default.debug?.("No further audit history, applying incremental updates based on available history",g,"existing version preserved",L),Be.sort((He,Te)=>He.version-Te.version);for(let He of Be){let Te=He.getValue(i);if(Fe.default.debug?.("Rebuilding update with future patch:",new Date(He.version),Te,He),J=B_(J??T,Te,C),!J)return me(!1)}}else{if(C)return me(!1);J=B_(J??T,W,C),Fe.default.debug?.("Rebuilding update without audit:",J)}Fe.default.trace?.("Rebuilt record to save:",J," is full update:",C)}let ge;if(C&&!J?ge=T:this.constructor.loadAsInstance===!1?ge=Nl(W,J??T):(this.#e=W,ge=Nl(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){D?.residencyId&&(O.previousResidency=ve.getResidencyRecord(D.residencyId));let ie=$a(ve.getResidency(ge,O));if(ie&&!ie.includes(server.hostname))if(ue??=ge,F=!0,ve.getResidencyById)ge=void 0;else{ge=null;for(let Ce in r)ge||(ge={}),ge[Ce]=ue[Ce]}re=Jc(ie)}C||(ue=T),Fe.default.trace?.(`Saving record with id: ${g}, timestamp: ${new Date(N).toISOString()}${oe?", expires at: "+new Date(oe).toISOString():""}${L?", replaces entry from: "+new Date(L.version).toISOString():", new entry"}`,(()=>{try{return JSON.stringify(ge).slice(0,100)}catch{return""}})()),Pu(g,W,ge),me(!0),O.expiresAt&&qa();function me(ie){y(g,ie?ge:void 0,ie?L:{...L,value:void 0},N,F?Fn:0,_,{omitLocalRecord:F,user:O?.user,residencyId:re,expiresAt:oe,nodeId:P?.nodeId,originatingOperation:O?.originatingOperation,tableToTrack:c==="system"?null:s},_e,!1,ie?ue:ue??T)}a(me,"writeCommit")},"commit")};B.addWrite(U)}async delete(g){if(um(g)){g.select=["$id"];for await(let T of this.search(g))this._writeDelete(T.$id);return!0}if(g){let T=!0,C=this.getContext();return g.checkPermission&&(T=this.allowDelete(C.user,g,C)),Gs(T,P=>{if(!P)throw new dt.AccessViolation(C.user);let O=Ls(g);return this._writeDelete(O),!0})}return this._writeDelete(this.getId()),!!this.#e}_writeDelete(g,T){let C=Br(this.getContext());ki(g);let P=this.getContext();return C.addWrite({key:g,store:i,entry:this.#r,nodeName:P?.nodeName,before:Ne.delete?.bind(this,P,g),beforeIntermediate:Ke.delete?.bind(this,P,g),commit:a((O,B,D)=>{let A=B?.value;D&&(P&&B?.version>(P.lastModified||0)&&(P.lastModified=B.version),ve._updateResource(this,B)),!(Fr(O,B,T?.nodeId)<=0)&&(Pu(this.getId(),A),Fe.default.trace?.(`Deleting record with id: ${g}, txn timestamp: ${new Date(O).toISOString()}`),_||R?(y(g,null,B,O,0,_,{user:P?.user,nodeId:T?.nodeId,tableToTrack:s},"delete"),_||qa()):hl(i,B))},"commit")}),!0}search(g){let T=this.getContext(),C=Br(T);if(!g)throw new Error("No query provided");if(g.parseError)throw g.parseError;if(g.checkPermission&&!this.allowRead(T.user,g))throw new dt.AccessViolation(T.user);T&&(T.lastModified=Cce);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,D={};function A(oe,ge){let me;switch(ge){case"and":case void 0:if(oe.length<1)throw new Error('An "and" operator requires at least one condition');me=!0;break;case"or":if(oe.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+ge)}for(let ie of oe){if(ie.conditions){ie.conditions=A(ie.conditions,ie.operator);continue}let Ce=ie[0]??ie.attribute,Be=Ce==null?H:Wi(S,Ce);if(Be)(Be.type||SI[ie.comparator])&&(ie[1]===void 0?ie.value=N(ie.value,Be):ie[1]=N(ie[1],Be));else if(Ce!=null&&!g.allowConditionsOnDynamicAttributes)throw(0,dt.handleHDBError)(new Error,`${Ce} is not a defined attribute`,404);if(ie.chainedConditions)if(ie.chainedConditions.length===1&&(!ie.operator||ie.operator=="and")){let He=ie.chainedConditions[0],Te,ht;if(He.comparator==="gt"||He.comparator==="greater_than"||He.comparator==="ge"||He.comparator==="greater_than_equal"?(Te=ie,ht=He):(Te=He,ht=ie),Te.comparator!=="lt"&&Te.comparator!=="less_than"&&Te.comparator!=="le"&&Te.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let Ct=ht.comparator==="ge"||ht.comparator==="greater_than_equal",Ot=Te.comparator==="le"||Te.comparator==="less_than_equal";ie.comparator=(Ct?"ge":"gt")+(Ot?"le":"lt"),ie.value=[ht.value,Te.value]}else throw new Error("Multiple chained conditions are not currently supported")}return oe}a(A,"prepareConditions");function U(oe,ge){if(g.enforceExecutionOrder)return oe;for(let me of oe)me.conditions&&(me.conditions=U(me.conditions,me.operator));return oe.length>1&&ge!=="or"?Ice(oe,Sg(ve)):oe}a(U,"orderConditions");function N(oe,ge){return Array.isArray(oe)?oe.map(me=>TS(me,ge)):TS(oe,ge)}a(N,"coerceTypedValues");let L=g.operator;(P.length>0||L)&&(P=A(P,L));let $=typeof g.sort=="object"&&g.sort,W;if($&&L!=="or"){let oe=$.attribute;if(oe==null)throw new dt.ClientError("Sort requires an attribute");if(B=P.find(ge=>Xu(ge.attribute)===Xu(oe)),!B){let ge=Wi(S,oe);if(!ge)throw(0,dt.handleHDBError)(new Error,`${Array.isArray(oe)?oe.join("."):oe} is not a defined attribute`,404);if(ge.indexed)B={...$,comparator:"sort"},P.push(B);else if(P.length===0&&!g.allowFullScan)throw(0,dt.handleHDBError)(new Error,`${Array.isArray(oe)?oe.join("."):oe} is not indexed and not combined with any other conditions`,404)}B&&(B.descending=!!$.descending)}P=U(P,L),$&&(B&&P[0]===B?$.next&&(W={dbOrderedAttribute:$.attribute,attribute:$.next.attribute,descending:$.next.descending,next:$.next.next}):(B&&P.splice(P.indexOf(B),1),W=$));let J=g.select;if(P.length===0&&(P=[{attribute:t,comparator:"greater_than",value:!0}]),g.explain)return{conditions:P,operator:L,postOrdering:W,selectApplied:!!J};let F=C.useReadTxn(),he=TI(P,L,ve,F,g,T,(oe,ge)=>fm(oe,J,T,F,ge),D),ue=g.ensureLoaded!==!1,_e=ve.transformEntryForSelect(J,T,F,D,ue,!0),re=ve.transformToOrderedSelect(he,J,W,T,F,_e);return(g.offset||g.limit!==void 0)&&(re=re.slice(g.offset,g.limit!==void 0?(g.offset||0)+g.limit:void 0)),re.onDone=()=>{re.onDone=null,C.doneReadTxn()},re.selectApplied=!0,re.getColumns=()=>{if(J){let oe=[];for(let ge of J)ge==="*"?oe.push(...S.map(me=>me.name)):oe.push(ge.name||ge);return oe}return S.filter(oe=>!oe.computed&&!oe.relationship).map(oe=>oe.name)},re}static transformToOrderedSelect(g,T,C,P,O,B){let D=new o_;if(C){g=fm(g,T,P,O,null);let A;D.iterate=function(){let N,L=g[Symbol.asyncIterator]?g[Symbol.asyncIterator]():g[Symbol.iterator](),$,W=C.dbOrderedAttribute,J,F,he=!0;function ue(re){let oe=re.next&&ue(re.next),ge=re.descending;return P.sort=re,(me,ie)=>{let Ce=Lu(me,re.attribute,P),Be=Lu(ie,re.attribute,P),He=ge?(0,Hl.compareKeys)(Be,Ce):(0,Hl.compareKeys)(Ce,Be);return He===0?oe?.(me,ie)||0:He}}a(ue,"createComparator");let _e=ue(C);return{async next(){let re;if(N)if(re=N.next(),re.done){if($)return D.onDone&&D.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 D.onDone&&D.onDone(),re}else{let oe=re.value;if(oe?.then&&(oe=await oe),W){let ge=Lu(oe,W,P);if(he)he=!1,F=ge;else if(ge!==F){F=ge,J=oe;break}}A.push(oe)}while(!0);return C.isGrouped,A.sort(_e),N=A[Symbol.iterator](),re=N.next(),re.done?(D.onDone&&D.onDone(),re):{value:await B.call(this,re.value)}},return(){return D.onDone&&D.onDone(),L.return()},throw(){return D.onDone&&D.onDone(),L.throw()}}};let U=a(N=>{if(typeof T=="object"&&Array.isArray(N.attribute))for(let L=0;L<T.length;L++){let $=T[L],W;if($.name===N.attribute[0]){for(W=$.sort||($.sort={});W.next;)W=W.next;W.attribute=N.attribute.slice(1),W.descending=N.descending}else $===N.attribute[0]&&(T[L]=W={name:$,sort:{attribute:N.attribute.slice(1),descending:N.descending}})}N.next&&U(N.next)},"applySortingOnSelect");U(C)}else D.iterate=(g[Symbol.asyncIterator]||g[Symbol.iterator]).bind(g),D=D.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 D}static transformEntryForSelect(g,T,C,P,O,B){let D;O&&I&&!(typeof g=="string"?[g]:g)?.every(N=>{let L;return typeof N=="object"?L=N.name:L=N,r[L]||L===t})&&(D=!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&Fn){if(N.metadataFlags&Fn&&T.replicateFrom===!1&&B&&N.residencyId)return pc.SKIP;if(N=xo(N.key??N,T,{transaction:C,lazy:g?.length<4,ensureLoaded:O},this?.isSync,$=>$),N?.then)return N.then(U.bind(this));L=N?.value}if(D&&N?.metadataFlags&(Fn|El)||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?pc.SKIP:L;if(g&&!(g[0]==="*"&&g.length===1)){let $,W=a((F,he)=>{let ue;typeof F=="object"?ue=F.name:ue=F;let _e=xr?.[ue],re;if(_e){let oe=P?.[ue];if(oe)if(oe.hasMappings){let me=_e.from?L[_e.from]:Xu(N.key);re=oe.get(me),re||(re=[])}else re=oe.fromRecord?.(L);else re=_e(L,T,N,!0);let ge=a(me=>{if(_e.directReturn)return he(me,ue);if(me&&typeof me=="object"){let ie=_e.definition?.tableClass||ve;A||(A={});let Ce=A[ue]||(A[ue]=ie.transformEntryForSelect(ue===F?null:F.select||(Array.isArray(F)?F:null),T,C,oe,O));if(Array.isArray(me)){let Be=[],He=ie.transformToOrderedSelect(me,F.select,typeof F.sort=="object"&&F.sort,T,C,Ce)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),Te=a(Ct=>{for(;!Ct.done;){if(Ct?.then)return Ct.then(Te);Be.push(Ct.value),Ct=He.next()}he(Be,ue)},"nextValue"),ht=Te(He.next());ht&&($||($=[]),$.push(ht));return}else if(me=Ce.call(this,me),me?.then){$||($=[]),$.push(me.then(Be=>he(Be,ue)));return}}he(me,ue)},"handleResolvedValue");re?.then?($||($=[]),$.push(re.then(ge))):ge(re);return}else re=L[ue],re&&typeof re=="object"&&ue!==F&&(re=ve.transformEntryForSelect(F.select||F,T,C,null)({value:re}));he(re,ue)},"selectAttribute"),J;if(typeof g=="string")W(g,F=>{J=F});else if(Array.isArray(g))if(g.asArray)J=[],g.forEach((F,he)=>{F==="*"?g[he]=L:W(F,ue=>J[he]=ue)});else{J={};let F=g.forceNulls;for(let he of g)if(he==="*")for(let ue in L)J[ue]=L[ue];else W(he,(ue,_e)=>{ue===void 0&&F&&(ue=null),J[_e]=ue})}else throw new dt.ClientError("Invalid select"+g);return $?Promise.all($).then(()=>J):J}return L},"transform");return U}async subscribe(g){if(!l)throw new Error("Can not subscribe to a table without an audit log");_||ze({table:s,database:c,schemaDefined:u,attributes:S,audit:!0}),g||(g={});let T=!g.rawEvents,C=[],P=NI(ve,this.getId()??null,function(D,A,U,N){try{let L=A.getValue?.(i,T),$=A.type;if(!L&&$==="patch"&&T){let J=i.getEntry(D);J?.version===A.version?L=J.value:L=A.getValue?.(i,!0,U),$="put"}let W={id:D,localTime:U,value:L,version:A.version,type:$,beginTxn:N};C?C.push(W):(c!=="system"&&Ye(A.size??1,"db-message",s,null),this.send(W))}catch(L){Fe.default.error?.(L)}},g.startTime||0,g),O=(async()=>{this.isCollection&&(P.includeDescendants=!0,g.onlyChildren&&(P.onlyChildren=!0)),g.supportsTransactions&&(P.supportsTransactions=!0);let D=this.getId(),A=g.previousCount;A>1e3&&(A=1e3);let U=g.startTime;if(this.isCollection){if(U){if(A)throw new dt.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:L}of l.getRange({start:U,exclusiveStart:!0,snapshot:!1})){let $=It(L);if($.tableId!==n)continue;let W=$.recordId;if(D==null||kq(D,W)){let J=$.getValue(i,T,N);if(B({id:W,localTime:N,value:J,version:$.version,type:$.type,size:$.size}),P.queue?.length>Bq&&await P.waitForDrain()===!1)return}P.startTime=N}}else if(A){let N=[];for(let{key:L,value:$}of l.getRange({start:"z",end:!1,reverse:!0}))try{let W=It($);if(W.tableId!==n)continue;let J=W.recordId;if(D==null||kq(D,J)){let F=W.getValue(i,T,L);if(N.push({id:J,localTime:L,value:F,version:W.version,type:W.type}),--A<=0)break}}catch(W){Fe.default.error("Error getting history entry",L,W)}for(let L=N.length;L>0;)B(N[--L]);N[0]&&(P.startTime=N[0].localTime)}else if(!g.omitCurrent){for(let{key:N,value:L,version:$,localTime:W,size:J}of i.getRange({start:D??!1,end:D==null?void 0:[D,Hl.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(L&&(B({id:N,localTime:W,value:L,version:$,type:"put",size:J}),P.queue?.length>Bq&&await P.waitForDrain()===!1))return}}else{A&&!U&&(U=0);let N=this.#r?.localTime;if(N===EI&&(i.cache?.delete(D),this.#r=i.getEntry(D),Fe.default.trace?.("re-retrieved record",N,this.#r?.localTime),N=this.#r?.localTime),Fe.default.trace?.("Subscription from",U,"from",D,N),U<N){let L=[],$=N;do{let W=l.get($);if(W){g.omitCurrent=!0;let J=It(W),F=J.getValue(i,T,$);T&&(J.type="put"),L.push({id:D,value:F,localTime:$,...J}),$=J.previousLocalTime}else break;A&&A--}while($>U&&A!==0);for(let W=L.length;W>0;)B(L[--W]);P.startTime=N}!g.omitCurrent&&this.doesExist()&&B({id:D,localTime:N,value:this.#e,version:this.#n,type:"put"})}for(let N of C)B(N);C=null})();function B(D){c!=="system"&&Ye(D.size??1,"db-message",s,null),P.send(D)}return a(B,"send"),g.listener&&P.on("data",g.listener),P}static subscribeOnThisThread(g,T){return g===0||T?.crossThreads===!1}doesExist(){return!!(this.#e||this.#s)}publish(g,T,C){if(T===void 0||T instanceof URLSearchParams)this._writePublish(this.getId(),g,T);else{let P=!0,O=this.getContext();return g.checkPermission&&(P=this.allowCreate(O.user,g,O)),Gs(P,B=>{if(!B)throw new dt.AccessViolation(O.user);let D=Ls(g);this._writePublish(D,T,C)})}}_writePublish(g,T,C){let P=Br(this.getContext());g??=null,g!==null&&ki(g);let O=this.getContext();P.addWrite({key:g,store:i,entry:this.#r,nodeName:O?.nodeName,validate:a(()=>{O?.source||(P.checkOverloaded(),this.validate(T))},"validate"),before:Ne.publish?.bind(this,O,g,T),beforeIntermediate:vu(T,Ke.publish?.bind(this,O,g,T)),commit:a((B,D,A)=>{D===void 0&&R&&!_&&qa(),Fe.default.trace?.(`Publishing message to id: ${g}, timestamp: ${new Date(B).toISOString()}`),y(g,D?.value??null,D,D?.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,D)=>{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 ${D} 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 ${D}.${L.name} may not be directly assigned a value`);continue}let $=P(O[L.name],L,D+"."+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 ${D}`)}else switch(B.type){case"Int":(typeof O!="number"||O>>0!==O)&&(C||(C=[])).push(`Value ${qs(O)} in property ${D} 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 ${D} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof O!="number"&&(C||(C=[])).push(`Value ${qs(O)} in property ${D} 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 ${D} must be a string, or an array of strings`);break;case"String":typeof O!="string"&&(C||(C=[])).push(`Value ${qs(O)} in property ${D} must be a string`);break;case"Boolean":typeof O!="boolean"&&(C||(C=[])).push(`Value ${qs(O)} in property ${D} 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 ${D} 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 ${D} 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 ${D} 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 ${D} 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,D+"[*]");L&&(O[A]=L)}}else(C||(C=[])).push(`Value ${qs(O)} in property ${D} must be an Array`);break}B.nullable===!1&&O==null&&(C||(C=[])).push(`Property ${D} is required (and not does not allow null values)`)},"validateValue");for(let O=0,B=S.length;O<B;O++){let D=S[O];if(D.relationship||D.computed){Object.hasOwn(g,D.name)&&(C||(C=[])).push(`Computed property ${D.name} may not be directly assigned a value`);continue}if(!T||D.name in g){let A=P(g[D.name],D,D.name);A!==void 0&&(g[D.name]=A)}}if(f)for(let O in g)S.find(B=>B.name===O)||(C||(C=[])).push(`Property ${O} is not allowed`);if(C)throw new dt.ClientError(C.join(". "))}getUpdatedTime(){return this.#n}wasLoadedFromSource(){return I?!!this.#i:void 0}static async addAttributes(g){let T=S.slice(0);for(let C of g){if(!C.name)throw new dt.ClientError("Attribute name is required");if(C.name.match(/[`/]/))throw new dt.ClientError("Attribute names cannot include backticks or forward slashes");wce(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=QN.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,D=0,A=0,U;for(let{value:N}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(N!=null&&D++,A++,await mc(),!B&&A<O&&performance.now()-P>C){U=A;break}if(U){let N=D;D=0;for(let{value:re}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:U,snapshot:!1}))re!=null&&D++,await mc();let L=U*2,$=(D+N)/L,W=Math.pow((D-N+1)/U/2,2)+$*(1-$)/L,J=Math.max(Math.sqrt(W)*T,1),F=Math.round($*T),he=Math.max(F-1.96*J,D+N),ue=Math.min(F+1.96*J,T),_e=Math.pow(10,Math.round(Math.log10(J)));return _e>F&&(_e=_e/10),D=Math.round(F/_e)*_e,{recordCount:D,estimatedRange:[Math.round(he),Math.round(ue)]}}return{recordCount:D}}static updatedAttributes(){xr=this.propertyResolvers={$id:a((g,T,C)=>({value:C.key}),"$id"),$updatedtime:a((g,T,C)=>C.version,"$updatedtime"),$updatedTime:a((g,T,C)=>C.version,"$updatedTime"),$expiresAt:a((g,T,C)=>C.expiresAt,"$expiresAt"),$record:a((g,T,C)=>C?{value:g}:g,"$record"),$distance:a((g,T,C)=>C&&(C.distance??T?.vectorDistances?.get(C)),"$distance")};for(let g of this.attributes){g.isPrimaryKey&&(H=g),g.resolve=null;let T=g.relationship,C=g.computed;if(T)if(g.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),C&&console.error("A relationship property is already computed and can not be combined with a computed function (the relationship will be given precedence)"),Ou=!0,T.to)g.elements?.definition?(xr[g.name]=g.resolve=(P,O,B,D)=>{let A=P[T.from?T.from:t],U=g.elements.definition.tableClass;return D?Qu({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,D,A)=>{let U=O[T.from];if(U===void 0)return;if(g.elements){let L,$=U?.map(W=>{let J=P.tableClass.primaryStore[A?"getEntry":"get"](W,{transaction:Br(B).getReadTxn()});return J?.then&&(L=!0),ve.loadAsInstance===!1&&Object.freeze(A?J?.value:J),J});return T.filterMissing?L?Promise.all($).then(W=>W.filter(Hq)):$.filter(Hq):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 D=B.map(A=>A.getId?.()||A[P.tableClass.primaryKey]);O[T.from]=D}else{let D=B.getId?.()||B[P.tableClass.primaryKey];O[T.from]=D}},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 D=typeof C.from=="string"?P[C.from]:P,A=this.userResolvers[g.name];if(A)return A(D,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,D)=>{let A=O[g.name];return P.propertyResolver(A,B,D)},xr[g.name].directReturn=!0}}Rp(this,this),Rp(lm,this,!0);for(let g of S){let T=g.name;g.resolve&&(Object.defineProperty(i.encoder.structPrototype,T,{get(){return g.resolve(this,ed.getStore())},set(C){return g.set(this,C)},configurable:!0,enumerable:g.enumerable}),g.enumerable&&!i.encoder.structPrototype.toJSON&&Object.defineProperty(i.encoder.structPrototype,"toJSON",{configurable:!0,value(){let C={};for(let P in this)C[P]=this[P];return C}}))}}static setComputedAttribute(g,T){let C=Wi(S,g);if(!C){console.error(`The attribute "${g}" does not exist in the table "${s}"`);return}if(!C.computed){console.error(`The attribute "${g}" is not defined as computed in the table "${s}"`);return}this.userResolvers[g]=T}static async deleteHistory(g=0,T=!1){let C;for(let{key:P,value:O}of l.getRange({start:0,end:g}))await mc(),It(O).tableId===n&&(C=sg(l,P,O));if(T)for(let P of i.getRange({start:0,versions:!0})){let{key:O,value:B,localTime:D}=P;await mc(),B===null&&D<g&&(C=hl(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 mc();let O=It(P);O.tableId===n&&(yield{id:O.recordId,localTime:C,version:O.version,type:O.type,value:O.getValue(i,!0,C),user:O.user,operation:O.originatingOperation})}}static async getHistoryOfRecord(g){let T=[];if(g==null)throw new Error("An id is required");let C=i.getEntry(g);if(!C)return T;let P=C.localTime;if(!P)throw new Error("The entry does not have a local audit time");let O=0;do{await mc();let B=l.get(P);if(B){let D=It(B);T.push({id:D.recordId,localTime:P,version:D.version,type:D.type,value:D.getValue(i,!0,P),user:D.user}),P=D.previousLocalTime}else break}while(O<1e3&&P);return T.reverse()}static cleanup(){Y?.remove()}}let c_=gS(async(K,g,T)=>{for(let C of ve.sources)if(C.get&&(!C.get.reliesOnPrototype||C.prototype.get)){if(C.available?.(T)===!1)continue;g.source=C;let P=await C.get(K,g);if(P)return P}},()=>{throw new dt.ServerError("Service unavailable, exceeded request queue limit for resolving cache record",503)});ve.updatedAttributes();let Wb=ve.prototype;return h&&ve.setTTLExpiration(h/1e3),z&&l_(),ve;function Pu(K,g,T){let C;for(let P in r){let O=r[P],B=O.isIndexing,D=xr[P],A=T&&(D?D(T):T[P]),U=g&&(D?D(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,Yp.getIndexedValues)(A,N),$=(0,Yp.getIndexedValues)(U,N);if($?.length>0){let W=new Set($);if(L=L?L.filter(J=>{if(W.has(J))W.delete(J);else return!0}):[],$=Array.from(W),($.length>0||L.length>0)&&Mq){let J=$.concat(L).map(F=>({key:F,value:K}));O.prefetch(J,Fq)}for(let J=0,F=$.length;J<F;J++)O.remove($[J],K)}else L?.length>0&&Mq&&O.prefetch(L.map(W=>({key:W,value:K})),Fq);if(L)for(let W=0,J=L.length;W<J;W++)O.put(L[W],K)}return C}a(Pu,"updateIndices");function ki(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>xq)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,Hl.writeKey)(K,vce,0)>xq)throw new Error("Primary key size is too large: "+K.length);return!0}a(ki,"checkValidId");function Ls(K){return typeof K=="object"&&K?K.id:K}a(Ls,"requestTargetToId");function um(K){return typeof K=="object"&&K&&K.isCollection}a(um,"isSearchTarget");function dm(K){}a(dm,"isRequestTarget");function xo(K,g,T,C,P){if(ve.getResidencyById&&T.ensureLoaded&&g?.replicateFrom!==!1){let B=$a(ve.getResidencyById(K));if(B&&!B.includes(server.hostname)&&w)return w({key:K,residency:B}).then(P)}let O=a(()=>{if(g?.transaction?.stale&&(g.transaction.stale=!1),T.transaction?.isDone)return P(null,K);let B=i.getEntry(K,T);return(c!=="system"||s==="hdb_analytics")&&($q.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&Fn&&w&&T.ensureLoaded&&g?.replicateFrom!==!1?w(B).then(D=>P(D,K),D=>(Fe.default.error?.("Error loading remote record",K,B,T,D),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,D)=>{te===0?(te--,i.prefetch([K],()=>{A(),U()})):(ce.push(K),de.push(U),ce.length>a_&&(te--,A()));function A(){if(ce.length>0){let N=de;i.prefetch(ce,()=>{te===-1?A():te++;for(let L of N)L()}),ce=[],de=[],Se>2&&Se--}else te=Se,Se<cm&&Se++}a(A,"prefetch");function U(){try{B(O())}catch(N){D(N)}}a(U,"load")})}a(xo,"loadLocalRecord");function Dn(K,g){let T=g?.checkPermission;if(typeof T!="object"){if(!K?.role)return;T=K.role.permission}if(T.super_user)return Mce;let C=T[c],P,O=C?.tables;if(O)return O[s];if(c==="data"&&(P=T[s])&&!P.tables)return P}a(Dn,"getTablePermissions");function pn(K,g,T,C){if(I){let P=!1;if(T.noCache?P=!0:(g?(!g.value||g.metadataFlags&(Fn|El)||g.expiresAt!=null&&g.expiresAt<Date.now())&&(P=!0):P=!0,en(!P,"cache-hit",s)),P){let O=Du(K,g,T).then(B=>(B?.value&&B?.value.getRecord?.()&&Fe.default.error?.("Can not assign a record that is already a resource"),T&&(B?.version>(T.lastModified||0)&&(T.lastModified=B.version),T.lastRefreshed=Date.now()),B));if(T?.onlyIfCached||g?.value&&C?.allowStaleWhileRevalidate?.(g,K)){if(O.catch(B=>Fe.default.warn?.(B)),T?.onlyIfCached&&!C.doesExist())throw new dt.ServerError("Entry is not cached",504);return}else return O}}else if(g?.value&&g.expiresAt!=null&&g.expiresAt<Date.now())return ve.evict(g.key,g.value,g.version),g.value=null,{then(P){return P(g)}}}a(pn,"ensureLoadedFromSource");function Br(K){let g=K?.transaction;if(g){if(!g.lmdbDb)return g.lmdbDb=i,g;do{if(g.lmdbDb?.path===i.path)return g;let T=g.next;if(!T)return g=g.next=new Fo,g.lmdbDb=i,g;g=T}while(!0)}else return new M_}a(Br,"txnForContext");function Lu(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 D=0,A=g.length;D<A;D++){let U=g[D],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(Lu,"getAttributeValue");function fm(K,g,T,C,P){let O=P?.length,B={transaction:C,lazy:O>0||typeof g=="string"||g?.length<4,alwaysPrefetch:!0},D;function A(U,N){let L=U?.value;if(!L)return pc.SKIP;for(let $=0;$<O;$++)if(!D?.includes($)&&!P[$](L,U))return pc.SKIP;return N!==void 0&&(U.key=N),U}if(a(A,"processEntry"),O>0||!K.hasEntries){let U=K.map(N=>{if(D=null,typeof N=="object"&&N?.key!==void 0)return O>0?A(N):N;if(N==null)return pc.SKIP;for(let L=0;L<O;L++){let W=P[L].idFilter;if(W){if(!W(N))return pc.SKIP;D||(D=[]),D.push(L)}}return xo(N,T,B,!1,A)});return Array.isArray(K)&&(U=U.filter(N=>N!==pc.SKIP)),U.hasEntries=!0,U}return K}a(fm,"transformToEntries");function Fr(K,g,T=server.replication?.getThisNodeId(l)){if(K<=g?.version){if(g?.version===K&&T!==void 0){let C=server.replication?.exportIdMapping(l),P=g.localTime,O=P&&l.get(P);if(O){let B,D,A=It(O);for(let U in C)C[U]===T&&(B=U),C[U]===A.nodeId&&(D=U);if(B>D)return 1;if(B===D)return 0}}return-1}return 1}a(Fr,"precedesExistingVersion");async function Du(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&(Fn|El)?O(Du(K,i.getEntry(K),T)):O(N)}))return new Promise(N=>{O=N,B=setTimeout(()=>{i.unlock(K,P)},Lce)});let D=g?.value,A={requestContext:T,replacingRecord:D,replacingEntry:g,replacingVersion:P,noCacheStore:!1,source:null,resourceCache:T?.resourceCache,transaction:void 0,expiresAt:void 0,lastModified:void 0},U=T?.responseHeaders;return new Promise((N,L)=>{let $;Gs(At(A,async W=>{let J=performance.now(),F,he,ue;try{F=await c_(K,A,g),ue=C&Fn;let re=A.lastModified||ue&&P;re||(re=(0,Yp.getNextMonotonicTime)()),he=ue||re>P||!D;let oe=performance.now()-J;if(Ye(oe,"cache-resolution",s,null,"success"),U&&Vp(U,"Server-Timing",`cache-resolve;dur=${oe.toFixed(2)}`,!0),W.timestamp=re,h&&A.expiresAt==null&&(A.expiresAt=Date.now()+h),F){if(typeof F!="object")throw new Error("Only objects can be cached and stored in tables");if(F.status>0&&F.headers)if(F.status>=300)if(F.status===304)F=D,re=P;else throw new dt.ServerError(F.body||"Error from source",F.status);else F=F.body;typeof F.toJSON=="function"&&(F=F.toJSON()),t&&F[t]!==K&&(F[t]=K)}$=!0,N({key:K,version:re,value:F})}catch(re){re.message+=` while resolving record ${K} for ${s}`,D&&((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:D}),Fe.default.trace?.(re.message,"(returned stale record)")):L(re);let oe=performance.now()-J;Ye(oe,"cache-resolution",s,null,"fail"),U&&Vp(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:vu(F),commit:a((re,oe)=>{if(oe?.version!==P)return;let ge=Pu(K,D,F);if(F){Ke.put?.(A,K,F),oe&&(T.previousResidency=ve.getResidencyRecord(oe.residencyId));let me,ie=!1,Ce,Be=$a(ve.getResidency(F,T));if(Be){if(!Be.includes(server.hostname))if(me=F,ie=!0,ve.getResidencyById)F=void 0;else{F=null;for(let He in r)F||(F={}),F[He]=me[He]}Ce=Jc(Be)}Fe.default.trace?.(`Writing resolved record from source with id: ${K}, timestamp: ${new Date(re).toISOString()}`),y(K,F,oe,re,ie?Fn:0,_&&(he||ie)||null,{user:A?.user,expiresAt:A.expiresAt,residencyId:Ce,tableToTrack:s},"put",!!ue,me)}else oe&&(Ke.delete?.(A,K),Fe.default.trace?.(`Deleting resolved record from source with id: ${K}, timestamp: ${new Date(re).toISOString()}`),_||R?y(K,null,oe,re,0,_&&he||null,{user:A?.user,tableToTrack:s},"delete",!!ue):hl(i,oe,P))},"commit")})}),()=>{i.unlock(K,P)},W=>{i.unlock(K,P),$&&Fe.default.error?.("Error committing cache update",W)})})}a(Du,"getFromSource");function Ga(K){if(!K||K.user?.role?.permission?.super_user)return!0;if(K.replicateTo)throw new dt.ClientError("Can not specify replication parameters without super user permissions",403);if(K.replicatedConfirmation)throw new dt.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}a(Ga,"checkContextPermissions");function qa(K){let g=!1;if(K&&(K-Ir>1&&(g=!0),Ir=K),!($e===nr&&!g)&&(nr=$e,(0,Fl.getWorkerIndex)()===(0,Fl.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(D=>{Fe.default.trace?.(`Scheduled next cleanup scan at ${new Date(D)}`),zr=setTimeout(()=>X=X.then(async()=>{if(B(Math.max(D+$e,Date.now())),i.rootStore.status!=="open"){clearTimeout(zr);return}let A=50,U=new Array(A),N=0,L=Math.pow(Ir,8)*(kl.get(x.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),$=E/Math.pow(Math.max(Ir,1),4);Fe.default.debug?.(`Starting cleanup scan for ${s}, evict threshold ${L}, adjusted eviction ${$}ms`);function W(J,F,he,ue){let _e=J+$-Date.now();if(_e<0)return!0;if(Ir){let re=i.lastSize;return he&Xr&&sl(ue,oe=>{oe.size&&(re+=oe.size)}),Fe.default.trace?.(`shouldEvict adjusted ${_e} ${re}, ${_e*(J-F)/re} < ${L}`),_e*(J-F)/re<L}return!1}a(W,"shouldEvict");try{let J=0;for(let F of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:he,value:ue,version:_e,expiresAt:re,metadataFlags:oe}=F,ge;ue===null&&!_&&_e+Pce<Date.now()?ge=hl(i,F,_e):re!=null&&W(re,_e,oe,ue)&&(ge=ve.evict(he,ue,_e),J++),ge&&(await U[N],U[N]=ge.catch(me=>{Fe.default.error?.("Cleanup error",me)}),++N>=A&&(N=0)),await mc()}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(D-Date.now(),2147483647)).unref()},"startNextTimer");B(O)}):void 0}a(qa,"scheduleCleanup");function mm(){Y=l?.addDeleteRemovalCallback(n,i,(K,g)=>{i.remove(K,g)})}a(mm,"addDeleteRemoval");function l_(){(0,Fl.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 mc()}}catch(K){Fe.default.error?.("Error in evicting old records",K)}finally{zc=!1}}},Oce).unref()}a(l_,"runRecordExpirationEviction");function $a(K){if(K!=null){if(Array.isArray(K))return K;if(typeof K=="number"){if(K>=65536)throw new Error(`Shard id ${K} must be below 65536`);let g=server.shards?.get?.(K);if(g)return Fe.default.trace?.(`Shard ${K} mapped to ${g.map(T=>T.name).join(", ")}`),g.map(T=>T.name);throw new Error(`Shard ${K} is not defined`)}throw new Error(`Shard or residency list ${K} is not a valid type, must be a shard number or residency list of node hostnames`)}}a($a,"residencyFromFunction");function Jc(K){if(K){let g=K.join(","),T=d.get([Symbol.for("residency_by_set"),g]);return T||(d.put([Symbol.for("residency_by_set"),g],T=Math.floor(Math.random()*2147418112)+65535),d.put([Symbol.for("residency_by_id"),T],K),T)}}a(Jc,"getResidencyId");function vu(K,g){let T=HA(K,i.rootStore);if(T){let C=g;return C?async()=>{await C(),await T}:()=>T}return g}a(vu,"preCommitBlobsForRecordBefore")}function JN(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 Fq(){}function TS(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 SS(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return SS(+e);case"Float":return e==="null"?null:SS(+e);case"BigInt":return e==="null"?null:BigInt(e);case"Boolean":return(0,Nd.autoCastBooleanStrict)(e);case"Date":if(isNaN(e)){if(e==="null")return null;Uce.test(e)||(e+="Z");let n=new Date(e);return SS(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,Nd.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function SS(e){if(isNaN(e))throw new SyntaxError;return e}function kq(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 Hq(e){return e!=null}function qs(e){try{return JSON.stringify(e)}catch{return e}}function xce(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var pc,Yp,Gq,qq,kl,dt,Wp,jp,Fe,Hl,Fl,Nd,QN,$q,Ice,wce,Nce,Cce,Oce,Pce,Mq,Lce,Uq,Dce,Fn,El,vce,xq,Bq,Mce,CUe,Uce,mc,Rg=se(()=>{G();pc=require("lmdb"),Yp=b(Un()),Gq=b(require("lodash")),qq=b(Cm());ji();Pm();kl=b(fe());CI();dt=b(Ee()),Wp=b(Qo()),jp=b(ls());Oe();yg();Fe=b(sr());xw();Wa();Hl=require("ordered-binary"),Fl=b(st());qi();Nd=b(ae());dl();is();F_();Kp();QN=b(require("node:fs"));ss();eg();$q=b(Q());zN();({sortBy:Ice}=Gq.default),{validateAttribute:wce}=qq.default,Nce=new Uint8Array(9);Nce[8]=192;Cce=1/0,Oce=6e4,Pce=864e5;kl.initSync();Mq=kl.get(x.STORAGE_PREFETCHWRITES),Lce=1e4,Uq=1,Dce=2,Fn=1,El=8,vce=Buffer.allocUnsafeSlow(8192),xq=1978,Bq=100,Mce={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},CUe=(0,Nd.convertToMS)(kl.get(x.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(yS,"makeTable");a(JN,"attributesAsObject");a(Fq,"noop");Uce=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(TS,"coerceType");a(SS,"rejectNaN");a(kq,"isDescendantId");mc=a(()=>new Promise(setImmediate),"rest");a(Gs,"when");a(Hq,"exists");a(qs,"stringify");a(xce,"hasOtherProcesses")});function RS(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 bS(e,t){if(!Array.isArray(e)||!Array.isArray(t))throw new Error("Cosine distance comparison requires an array");let r=0,n=0,s=0,i=Math.max(e.length,t.length);for(let o=0;o<i;o++){let c=e[o]||0,l=t[o]||0;r+=c*l,n+=c*c,s+=l*l}return n=Math.sqrt(n),s=Math.sqrt(s),1-r/(n*s||1)}var Kq=se(()=>{a(RS,"euclideanDistance");a(bS,"cosineDistance")});var Yq,Wq,Od,lo,Cd,Bce,Fce,AS,jq=se(()=>{Kq();Yq=require("msgpackr"),Wq=b(sr()),Od=b(Ee()),lo=(0,Wq.loggerWithTag)("HNSW"),Cd=Symbol.for("entryPoint"),Bce=Symbol.for("key"),Fce=10,AS=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=Yq.FLOAT32_OPTIONS.ALWAYS),this.distance=r?.distance==="euclidean"?RS:bS,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"?[Bce,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(Cd);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);lo.debug?.("setting entry point to",i),this.indexStore.put(Cd,i);return}let m=c.level??Math.min(Math.floor(-Math.log(Math.random())*this.mL),Fce),p=f.level;if(m>=p){if(typeof i!="number")throw new Error("Invalid nodeId: "+i);lo.debug?.("setting entry point to",i),this.indexStore.put(Cd,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&&lo.info?.("should not have zero connections for",l);let R=h[E];for(let S=0;S<_.length;S++){let{id:y,distance:w,node:I}=_[S];if(y===i)continue;let H=[];if(this.optimizeRouting){let k=!1,z=I[E],Y=1+this.optimizeRouting*(1+.5*S/this.M);for(let ce=0;ce<z?.length;ce++){let{id:de,distance:te}=z[ce],Se=1+this.optimizeRouting*(1+.5*ce/this.M);for(let Ne=0;Ne<R.length;Ne++){let{id:Ke,distance:$e}=R[Ne];if(Ke===de){w*Y>$e+te?k=!0:te*Se>w+$e&&(H.push({fromId:Ke,toId:y}),H.push({fromId:y,toId:Ke}));break}}if(k)break}if(k)continue}else if(S>=(E>0?this.M:this.M<<1))continue;R.push({id:y,distance:w});for(let{fromId:k,toId:z}of H){let Y=d(k);Y||(Y=d(k,this.indexStore.get(k)));for(let ce=0;ce<Y[E].length;ce++)if(Y[E][ce].id===z){Object.isFrozen(Y[E])&&(Y[E]=Y[E].slice()),Y[E].splice(ce,1);break}}let X=c[E],q=X?.find(({id:k})=>k===y);if(q){let k=X?.indexOf(q);X.copied||(X=[...X],X.copied=!0,c[E]=X),X.splice(k,1)}else this.addConnection(y,d(y,I),i,E,w,d)}}this.indexStore.put(i,{vector:r,level:m,primaryKey:t,...h})}else{if(l===i){let f=c.level??0;for(let m=f;m>=0&&(l=c[m]?.[0]?.id,l===void 0);m--);if(l===void 0){let m=-1;for(let{key:p,value:h}of this.indexStore.getRange({start:0,end:1/0}))if(h.level>m){if(l=p,h.level===f)break;m=h.level}}if(l===void 0)this.indexStore.remove(Cd);else{if(typeof l!="number")throw new Error("Invalid nodeId: "+l);lo.debug?.("setting entry point to",l),this.indexStore.put(Cd,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&&(lo.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(Cd);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 Od.ClientError(`Can not use "${i}" comparator with HNSW`)}if(n)throw new Od.ClientError("Can not use descending sort order with HNSW");let c;if(s==="cosine")c=bS;else if(s==="euclidean")c=RS;else{if(s)throw new Od.ClientError("Unknown distance function");c=this.distance}if(!t)throw new Od.ClientError("A target vector must be provided for an HNSW query");if(!Array.isArray(t))throw new Od.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){lo.info?.("could not find neighbor node",o);continue}o[n]?.find(({id:l})=>l==t)||lo.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)){lo.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&&lo.info?.("should not remove last connection",t,n))}}r[s].find(({id:l})=>l===n)?lo.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"?RS:bS);let c=o(s.target,t);return i.set(n,c),c}return t}}});var XN,zq=se(()=>{jq();XN={HNSW:AS}});var mt={};ye(mt,{NON_REPLICATING_SYSTEM_TABLES:()=>IS,database:()=>fd,databaseEnvs:()=>ra,databases:()=>Me,dropDatabase:()=>Gw,dropTableMeta:()=>Vce,getDatabases:()=>lt,getDefaultCompression:()=>DS,getTables:()=>Hce,onRemovedDB:()=>th,onUpdatedTable:()=>Gl,readMetaDb:()=>zp,resetDatabases:()=>Md,table:()=>ze,tables:()=>yn});function eh(e,t){let r=PS.OpenDBIObject??PS.default.OpenDBIObject;return new r(e,t)}function Hce(){return OS||lt(),yn||{}}function lt(){if(OS)return Me;OS=!0,Dd=new Map;let e=(0,Zt.getHdbBasePath)()&&(0,Ht.join)((0,Zt.getHdbBasePath)(),Zc),t=(0,Zt.get)(x.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Zt.get)(x.STORAGE_PATH)||e&&((0,gs.existsSync)(e)?e:(0,Ht.join)((0,Zt.getHdbBasePath)(),__)),!!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&&zp((0,Ht.join)(e,r.name),null,n)}if((0,gs.existsSync)((0,Ld.getBaseSchemaPath)())){for(let r of(0,gs.readdirSync)((0,Ld.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,Ht.join)((0,Ld.getBaseSchemaPath)(),r.name),s=(0,Ht.join)((0,Ld.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);zp((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"&&zp((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)&&zp(l,o,r,null,!0)}}for(let r in Me){let n=Dd.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 yn)delete yn[s];delete yn[LS]}}if((0,Zt.get)(x.ANALYTICS_REPLICATE)===!1?IS.includes("hdb_analytics")||IS.push("hdb_analytics"):(Me.system?.hdb_analytics?.enableAuditing(),Me.system?.hdb_analytics_hostname?.enableAuditing()),Me.system)for(let r of IS)Me.system[r]&&(Me.system[r].replicate=!1);return Dd=null,Me}}function Md(){OS=!1;for(let[,e]of ra)e.needsDeletion=!0;lt();for(let[e,t]of ra)if(t.needsDeletion&&!e.endsWith("system.mdb")){t.close(),ra.delete(e);let r=Me[t.databaseName];for(let n in r)if(r[n].primaryStore.path===e){delete Me[t.databaseName],Qp.forEach(i=>i(t.databaseName));break}}return Me}function zp(e,t,r=tC,n,s){let i=new ZN.default(e,!1);try{let o=ra.get(e);o?o.needsDeletion=!1:(o=(0,vd.open)(i),ra.set(e,o));let c=new eh(!1),l=o.dbisDb||(o.dbisDb=o.openDB(wS.INTERNAL_DBIS_NAME,c)),u=o.auditStore;u||(n?(0,gs.existsSync)(n)&&(i.path=n,u=(0,vd.open)(i),u.isLegacy=!0):u=ng(o));let d=e$(r),f=d[LS],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,H=typeof _.audit=="boolean"?_.audit:(0,Zt.get)(x.LOGGING_AUDITLOG),X=_.trackDeletes,q=_.expiration,k=_.eviction,z=_.sealed,Y=_.splitSegments,ce=_.replicate;if(R)S=R.indices,y=R.attributes,R.schemaVersion++;else{w=_.tableId,w?w>=(l.get(Pd)||0)&&(l.putSync(Pd,w+1),Or.info(`Updating next table id (it was out of sync) to ${w+1} for ${p}`)):(_.tableId=w=l.get(Pd),w||(w=1),Or.debug("Table {tableName} missing an id, assigning {tableId}"),l.putSync(Pd,w+1),l.putSync(_.key,_));let te=new eh(!_.is_hash_attribute,_.is_hash_attribute);if(te.compression=_.compression,te.compression){let Se=(0,Zt.get)(x.STORAGE_COMPRESSION_THRESHOLD)||Zq;te.compression.threshold=Se}I=_g(o.openDB(_.key,te),o),o.databaseName=r,I.tableId=w}let de;for(let te of E){te.attribute=te.name;try{if(!te.is_hash_attribute&&(te.indexed||te.attribute&&!te.name)){if(!S[te.name]){let Ne=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),de=!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),de=!0)}if(R)de&&(R.schemaVersion++,R.updatedAttributes());else{R=t$(d,p,yS({primaryStore:I,auditStore:u,audit:H,sealed:z,splitSegments:Y,replicate:ce,expirationMS:q&&q*1e3,evictionMS:k&&k*1e3,trackDeletes:X,tableName:p,tableId:w,primaryKey:_.name,databasePath:s?r+"/"+p:r,databaseName:r,indices:S,attributes:E,schemaDefined:_.schemaDefined,dbisDB:l})),R.schemaVersion=1;for(let te of Jp)te(R)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function e$(e){let t=Me[e];if(t||(e==="data"?t=Me[e]=yn:e==="system"?Object.defineProperty(Me,"system",{value:t=Object.create(null),configurable:!0}):t=Me[e]=Object.create(null)),Dd&&!Dd.has(e)){let r=new Set;t[LS]=r,Dd.set(e,r)}return t}function t$(e,t,r){return e[t]=r,r}function fd({database:e,table:t}){e||(e=tC),lt();let r=e$(e),n=(0,Ht.join)((0,Zt.getHdbBasePath)(),Zc),s=(0,Zt.get)(x.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,Zt.get)(x.STORAGE_PATH)||((0,gs.existsSync)(n)?n:(0,Ht.join)((0,Zt.getHdbBasePath)(),__));let o=(0,Ht.join)(n,(i?t:e)+".mdb"),c=ra.get(o);if(!c||c.status==="closed"){let l=new ZN.default(o,!1);c=(0,vd.open)(l),ra.set(o,c)}return c.auditStore||(c.auditStore=ng(c)),c}async function Gw(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,ra.delete(r.path),r.status==="open"&&(await r.close(),await Xp.remove(r.path));if(r||(r=fd({database:e,table:null}),r.status==="open"&&(await r.close(),await Xp.remove(r.path))),e==="data"){for(let n in yn)delete yn[n];delete yn[LS]}delete Me[e],Qp.forEach(n=>n(e)),await kA(r)}function r$(e,t,r){let n=r.is_hash_attribute||r.indexed.type&&XN[r.indexed.type]?.useObjectStore,s=new eh(!n,n),i=t.openDB(e,s);if(r.indexed.type){let o=XN[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=tC);let h=fd({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 eh(!1);for(let Y of o)Y.attribute&&!Y.name?(Y.name=Y.attribute,Y.indexed=!0):Y.attribute=Y.name,Y.expiresAt&&(Y.indexed=!0);let I,H;if(_){if(R=_.primaryKey,_.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${t} class`);u==null&&(u=_.splitSegments),_.attributes.splice(0,_.attributes.length,...o)}else{let Y=h.auditStore;S=o.find(Se=>Se.isPrimaryKey)||{},R=S.name,S.is_hash_attribute=S.isPrimaryKey=!0,S.schemaDefined=m,S.compression=DS(),f&&(S.trackDeletes=!0),c=S.audit=typeof c=="boolean"?c:(0,Zt.get)(x.LOGGING_AUDITLOG),n&&(S.expiration=n),s&&(S.eviction=s),u??=!1,S.splitSegments=u,typeof l=="boolean"&&(S.sealed=l),typeof d=="boolean"&&(S.replicate=d),p&&(S.origins?S.origins.includes(p)||S.origins.push(p):S.origins=[p]),Or.trace(`${t} table loading, opening primary store`);let ce=new eh(!1,!0);ce.compression=S.compression;let de=t+"/";if(y=h.dbisDb=h.openDB(wS.INTERNAL_DBIS_NAME,w),z(),y.get(de))return H&&H(),Md(),ze(e);let te=_g(h.openDB(de,ce),h);h.databaseName=r,te.tableId=y.get(Pd),Or.trace(`Assigning new table id ${te.tableId} for ${t}`),te.tableId||(te.tableId=1),y.put(Pd,te.tableId+1),S.tableId=te.tableId,_=t$(E,t,yS({primaryStore:te,auditStore:Y,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:R,tableName:t,tableId:te.tableId,databasePath:r,databaseName:r,indices:{},attributes:o,schemaDefined:m,dbisDB:y})),_.schemaVersion=1,I=!0,y.put(de,S)}let X=_.indices;y=y||(h.dbisDb=h.openDB(wS.INTERNAL_DBIS_NAME,w)),_.dbisDB=y;let q=[];for(let{key:Y,value:ce}of y.getRange({start:!0})){let[de,te]=Y.toString().split("/");if(te===""&&(te=ce.name),te){if(de!==t)continue}else continue;let Se=o.find(Ke=>Ke.name===te),Ne=!Se?.indexed&&ce.indexed&&!ce.isPrimaryKey;if((!Se||Ne)&&(z(),I=!0,Se||y.remove(Y),Ne)){let Ke=_.indices[de];Ke&&q.push(Ke)}}let k=[];try{for(let Y of o||[]){if((Y.relationship||Y.computed)&&(I=!0,Y.relationship))continue;let ce=t+"/"+(Y.name||"");Object.defineProperty(Y,"key",{value:ce,configurable:!0});let de=y.get(ce);if(Y.isPrimaryKey){if(de=de||y.get(ce=t+"/")||{},c!==void 0&&c!==_.audit||l!==void 0&&l!==_.sealed||d!==void 0&&d!==_.replicate||(+n||void 0)!==(+de.expiration||void 0)||(+s||void 0)!==(+de.eviction||void 0)||Y.type!==de.type){let Se={...de};typeof c=="boolean"&&(c&&_.enableAuditing(c),Se.audit=c),n&&(Se.expiration=+n),s&&(Se.eviction=+s),l!==void 0&&(Se.sealed=l),d!==void 0&&(Se.replicate=d),Y.type&&(Se.type=Y.type),I=!0,z(),y.put(ce,Se)}continue}de?.attribute&&!de.name&&(de.indexed=!0);let te=!de||de.type!==Y.type||JSON.stringify(de.indexed)!==JSON.stringify(Y.indexed)||de.nullable!==Y.nullable||de.version!==Y.version||de.enumerable!==Y.enumerable||JSON.stringify(de.properties)!==JSON.stringify(Y.properties)||JSON.stringify(de.elements)!==JSON.stringify(Y.elements);if(Y.indexed){let Se=r$(ce,h,Y);(te||de.indexingPID&&de.indexingPID!==process.pid||de.restartNumber<Zp.workerData?.restartNumber)&&(I=!0,z(),de=y.get(ce),(te||de.indexingPID&&de.indexingPID!==process.pid||de.restartNumber<Zp.workerData?.restartNumber)&&(I=!0,Y.indexNulls===void 0&&(Y.indexNulls=!0),_.primaryStore.getStats().entryCount>0&&(Y.lastIndexedKey=de?.lastIndexedKey??void 0,Y.indexingPID=process.pid,Se.isIndexing=!0,Object.defineProperty(Y,"dbi",{value:Se}),k.push(Y))),y.put(ce,Y)),de?.indexNulls&&Y.indexNulls===void 0&&(Y.indexNulls=!0),Se.indexNulls=Y.indexNulls,X[Y.name]=Se}else te&&(I=!0,z(),y.put(ce,Y))}}finally{H&&H()}if(I&&(_.schemaVersion++,_.updatedAttributes()),Or.trace(`${t} table loading, running index`),k.length>0||q.length>0?_.indexingOperation=$ce(_,k,q):I&&NS.signalSchemaChange(new CS.SchemaEventMsg(process.pid,"schema-change",_.databaseName,_.tableName)),_.origin=p,I)for(let Y of Jp)Y(_,p!=="cluster");return(n||s||i)&&_.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Or.trace(`${t} table loaded`),_;function z(){H||h.transactionSync(()=>({then(Y){H=Y}}))}a(z,"startTxn")}async function $ce(e,t,r){try{Or.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await NS.signalSchemaChange(new CS.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,vd.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,Jq.getIndexedValues)(y,R.indexNulls);if(w)for(let I=0,H=w.length;I<H;I++)R.put(w[I],f)}catch(S){o[_]||(o[_]=!0,Or.error(`Error indexing attribute ${_}`,S))}}}),s.then(()=>d--,h=>{d--,Or.error(h)}),Zp.workerData&&Zp.workerData.restartNumber!==Xq.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>Gce?await s:d>qce&&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 NS.signalSchemaChange(new CS.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 Vce({table:e,database:t}){let r=fd({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 Gl(e){return Jp.push(e),{remove(){let t=Jp.indexOf(e);t>-1&&Jp.splice(t,1)}}}function th(e){return Qp.push(e),{remove(){let t=Qp.indexOf(e);t>-1&&Qp.splice(t,1)}}}function DS(){let e=(0,Zt.get)(x.STORAGE_COMPRESSION),t=(0,Zt.get)(x.STORAGE_COMPRESSION_DICTIONARY),r=(0,Zt.get)(x.STORAGE_COMPRESSION_THRESHOLD)||Zq,n={startingOffset:32};return t&&(n.dictionary=Xp.readFileSync(t)),r&&(n.threshold=r),e&&n}var Zt,wS,vd,Ht,gs,Ld,ZN,Xp,eC,Jq,NS,CS,Zp,Qq,Xq,PS,kce,Or,tC,LS,Zq,IS,yn,Me,Pd,Jp,Qp,OS,ra,Dd,Gce,qce,Oe=se(()=>{Zt=b(fe()),wS=b(Jt()),vd=require("lmdb"),Ht=require("path"),gs=require("fs"),Ld=b(bt());Rg();ZN=b(sp());G();Xp=b(require("fs-extra")),eC=b(oi()),Jq=b(Un()),NS=b(Qo()),CS=b(ls()),Zp=require("worker_threads"),Qq=b(Q()),Xq=b(st());qi();dl();ss();zq();PS=b(np()),{forComponent:kce}=Qq.default;a(eh,"OpenDBIObject");Or=kce("storage"),tC="data",LS=Symbol("defined-tables"),Zq=((0,Zt.get)(x.STORAGE_PAGESIZE)||4096)-60;(0,Zt.initSync)();IS=["hdb_temp","hdb_certificate","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_info"],yn=Object.create(null),Me=Object.create(null);(0,eC._assignPackageExport)("databases",Me);(0,eC._assignPackageExport)("tables",yn);Pd=Symbol.for("next-table-id"),Jp=[],Qp=[],ra=new Map;a(Hce,"getTables");a(lt,"getDatabases");a(Md,"resetDatabases");a(zp,"readMetaDb");a(e$,"ensureDB");a(t$,"setTable");a(fd,"database");a(Gw,"dropDatabase");a(r$,"openIndex");a(ze,"table");Gce=1e3,qce=10;a($ce,"runIndexing");a(Vce,"dropTableMeta");a(Gl,"onUpdatedTable");a(th,"onRemovedDB");a(DS,"getDefaultCompression")});var sC={};ye(sC,{loadGQLSchema:()=>Wce,start:()=>nC,startOnMainThread:()=>Yce});function nC({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:l,NamedTypeNode:u,StringValueNode:d}=await import("graphql"),f=o(new c(r.toString(),s)),m=new Map,p=[],h;for(let R of f.definitions)switch(R.kind){case l.OBJECT_TYPE_DEFINITION:let H=function(q){if(q.kind==="NonNullType"){let Y=H(q.type);return Y.nullable=!1,Y}if(q.kind==="ListType")return{type:"array",elements:H(q.type)};let z={type:q.name?.value};return Object.defineProperty(z,"location",{value:q.loc.startToken}),z};a(H,"getProperty");let S=R.name.value,y=[],w={table:null,database:null,properties:y};m.set(S,w),i.allTypes.set(S,w);for(let q of R.directives){if(q.name.value==="table"){for(let z of q.arguments)w[z.name.value]=z.value.value;w.schema&&(w.database=w.schema),w.table||(w.table=S),w.audit&&(w.audit=w.audit!=="false"),w.attributes=w.properties,p.push(w)}if(q.name.value==="sealed"&&(w.sealed=!0),q.name.value==="splitSegments"&&(w.splitSegments=!0),q.name.value==="replicate"&&(w.replicate=!0),q.name.value==="export"){w.export=!0;for(let z of q.arguments)typeof w.export!="object"&&(w.export={}),w.export[z.name.value]=z.value.value}}let I=!1,X={};for(let q of R.fields){let k=H(q.type);k.name=q.name.value,y.push(k),X[k.name]=void 0;for(let z of q.directives){let Y=z.name.value;if(Y==="primaryKey")I?console.warn("Can not define two attributes as a primary key at",z.loc):(k.isPrimaryKey=!0,I=!0);else if(Y==="indexed"){let ce={};for(let de of z.arguments||[])ce[de.name.value]=de.value.value;k.indexed=ce}else if(Y==="computed"){for(let ce of z.arguments||[])if(ce.name.value==="from"){let de=ce.value.value;k.computed={from:_(de,ce,X)},k.version==null&&(k.version=de)}else ce.name.value==="version"&&(k.version=ce.value.value);k.computed=k.computed||!0}else if(Y==="relationship"){let ce={};for(let de of z.arguments)ce[de.name.value]=de.value.value;k.relationship=ce}else if(Y==="createdTime")k.assignCreatedTime=!0;else if(Y==="updatedTime")k.assignUpdatedTime=!0;else if(Y==="expiresAt")k.expiresAt=!0;else if(Y==="enumerable")k.enumerable=!0;else if(Y==="allow"){let ce=k.authorizedRoles=[];for(let de of z.arguments)de.name.value==="role"&&ce.push(de.value.value)}else server.knownGraphQLDirectives.includes(Y)&&console.warn(`@${Y} is an unknown directive, at`,z.loc)}}w.type=S,S==="Query"&&(h=w)}function E(R){let S=m.get(R.type);S?(Object.defineProperty(R,"properties",{value:S.properties}),Object.defineProperty(R,"definition",{value:S})):R.type==="array"?E(R.elements):Kce.includes(R.type)||(0,s$.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,rC.dirname)(n),R.tableClass):i.set((0,rC.dirname)(n)+"/"+(R.export.name||R.type),R.tableClass,R.export));function _(R,S,y){return new n$.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 rC,n$,s$,Kce,Yce,Wce,i$=se(()=>{rC=require("path"),n$=require("node:vm");Oe();s$=b(st());ec();Kce=["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(nC,"start");Yce=nC,Wce=a(e=>nC({ensureTable:ze}).handleFile(e,null,null,new rd),"loadGQLSchema")});var oC={};ye(oC,{start:()=>rle});function jce(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 o$(e){if(typeof e!="object"||e===null)throw new uo("Request body must be an object.");if(!("query"in e))throw new uo("Request body must contain a `query` field.");if(typeof e.query!="string")throw new uo("Request body `query` field must be a string.");if("variables"in e&&(typeof e.variables!="object"||e.variables===null))throw new uo("Request body `variables` field must be an object.");if("operationName"in e&&typeof e.operationName!="string")throw new uo("Request body `operationName` field must be a string.")}function iC(e){return parseInt(e.value,10)}function c$(e){return parseFloat(e.value)}function l$(e,t,r){let n=r.get(e.name.value);return u$(n)?d$(n,t):{attribute:t,value:n}}function u$(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}function d$(e,t){return t=typeof t=="string"?[t]:t,Object.entries(e).flatMap(([r,n])=>(t=[...t,r],u$(n)?d$(n,t):{attribute:t,value:n}))}function zce(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:iC(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 l$(e.value,t,r);case Ge.Kind.OBJECT:return f$(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 f$(e,t,r){return e.fields.flatMap(n=>zce(n,t,r))}function Jce(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:iC(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 l$(e.value,e.name.value,t);case Ge.Kind.OBJECT:return f$(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 Qce(e,t){return e.flatMap(r=>Jce(r,t))}function vS(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 vS(s.selectionSet,t)}case Ge.Kind.INLINE_FRAGMENT:return vS(r.selectionSet,t)}})}function m$(e,t){return vS(e,t).map(r=>r.selectionSet?.selections.length>0?{name:r.name.value,select:m$(r.selectionSet,t)}:r.name.value)}async function Xce(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:m$(e.selectionSet,r),conditions:Qce(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 p$(e){switch(e.kind){case Ge.Kind.NULL:return null;case Ge.Kind.INT:return iC(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]:p$(r.value),...t}),{});case Ge.Kind.LIST:case Ge.Kind.ENUM:default:throw new Vr(`Value type, ${e.kind}, is not supported.`)}}function Zce(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=p$(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 ele(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=Zce(e.variableDefinitions,t),i=await Promise.all(vS(e.selectionSet,r).map(c=>Xce(c,s,r,n))),o={data:{}};for(let[c,l]of i)o.data[c]=l;return o}async function a$({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(jce(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 ele(c,t,o,n);return{status:200,headers:{"Content-Type":"application/graphql-response+json; charset=utf-8"},body:JSON.stringify(l)}}async function tle(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 o$(r),a$(r,e)}case"POST":{let r=await qo(e.headers.get("content-type"),!0)(e._nodeRequest);return o$(r),a$(r,e)}default:throw new uo("Method Not Allowed",405,{Allow:"GET, POST"})}}function rle(e){e.server.http(async(t,r)=>{if(!t.url.startsWith("/graphql"))return r(t);try{return await tle(t)}catch(n){logger.error(n);let s=t.headers.get("accept")??"application/graphql-response+json";switch(s){case"application/json":{if(n instanceof uo)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 uo)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,uo,h$=se(()=>{Ge=b(require("graphql"));$o();ec();a(jce,"assertExecutableDefinitionNode");a(o$,"assertRequestParams");a(iC,"processIntValueNode");a(c$,"processFloatValueNode");a(l$,"processVariableNode");a(u$,"isObject");a(d$,"transformObjectIntoQueryCondition");a(zce,"processObjectFieldNode");a(f$,"processObjectValueNode");a(Jce,"processArgumentNode");a(Qce,"buildConditionsQuery");a(vS,"fillInFragments");a(m$,"buildSelectQuery");a(Xce,"processFieldNode");a(p$,"processConstValueNode");a(Zce,"resolveVariables");a(ele,"executeOperation");a(a$,"resolver");Vr=class extends Error{static{a(this,"GraphQLQueryingError")}},uo=class extends Error{static{a(this,"HTTPError")}statusCode;headers;constructor(t,r=400,n={}){super(t),this.statusCode=r,this.headers=n}};a(tle,"graphqlQueryingHandler");a(rle,"start")});var y$=M((JUe,T$)=>{var Ud=require("validate.js"),_$=pt(),xd=(G(),v(j)),{handleHDBError:nle,hdbErrors:sle}=Ee(),{HDB_ERROR_MSGS:ar,HTTP_STATUS_CODES:ile}=sle,aC=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),ole={STRUCTURE_USER:"structure_user"},E$=Object.values(xd.ROLE_TYPES_ENUM),ale="attribute_permissions",cle="attribute_name",{PERMS_CRUD_ENUM:Bd}=xd,lle=[ale,...Object.values(Bd)],g$=[Bd.READ,Bd.INSERT,Bd.UPDATE],ule=[cle,...g$];function dle(e){let t=aC();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,S$(e,t)}a(dle,"addRoleValidation");function fle(e){let t=aC();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,S$(e,t)}a(fle,"alterRoleValidation");function mle(e){let t=aC();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,_$.validateObject(e,t)}a(mle,"dropRoleValidation");var ple=["operation","role","id","permission","hdb_user","access"];function S$(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)ple.includes(n[o])||s.push(n[o]);s.length>0&&Er(ar.INVALID_ROLE_JSON_KEYS(s),r);let i=_$.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{Er(o,r)}),e.permission){let o=hle(e);o&&Er(o,r),E$.forEach(c=>{e.permission[c]&&!Ud.isBoolean(e.permission[c])&&Er(ar.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(E$.indexOf(o)<0){if(o===ole.STRUCTURE_USER){let l=e.permission[o];if(typeof l=="boolean")continue;if(Array.isArray(l)){for(let u=0,d=l.length;u<d;u++){let f=l[u];global.hdb_schema[f]||Er(ar.SCHEMA_NOT_FOUND(f),r)}continue}Er(ar.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){Er(ar.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let l in c.tables){let u=c.tables[l];if(!l||!global.hdb_schema[o][l]){Er(ar.TABLE_NOT_FOUND(o,l),r);continue}if(Object.keys(u).forEach(d=>{lle.includes(d)||Er(ar.INVALID_PERM_KEY(d),r,o,l)}),Object.values(Bd).forEach(d=>{Ud.isDefined(u[d])?Ud.isBoolean(u[d])||Er(ar.TABLE_PERM_NOT_BOOLEAN(d),r,o,l):Er(ar.TABLE_PERM_MISSING(d),r,o,l)}),u.attribute_permissions===void 0){Er(ar.ATTR_PERMS_ARRAY_MISSING,r,o,l);continue}else if(!(Array.isArray(u.attribute_permissions)||u.attribute_permissions===null)){Er(ar.ATTR_PERMS_NOT_ARRAY,r,o,l);continue}if(u.attribute_permissions){let d=global.hdb_schema[o][l].attributes.map(({attribute:m})=>m),f={read:!1,insert:!1,update:!1};for(let m in u.attribute_permissions){let p=u.attribute_permissions[m];if(Object.keys(p).forEach(E=>{!ule.includes(E)&&E!==Bd.DELETE&&Er(ar.INVALID_ATTR_PERM_KEY(E),r,o,l)}),!Ud.isDefined(p.attribute_name)){Er(ar.ATTR_PERM_MISSING_NAME,r,o,l);continue}let h=p.attribute_name;if(!d.includes(h)){Er(ar.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,l);continue}g$.forEach(E=>{Ud.isDefined(p[E])?Ud.isBoolean(p[E])||Er(ar.ATTR_PERM_NOT_BOOLEAN(E,h),r,o,l):Er(ar.ATTR_PERM_MISSING(E,h),r,o,l)}),!f.read&&p.read===!0&&(f.read=!0),!f.insert&&p.insert===!0&&(f.insert=!0),!f.update&&p.update===!0&&(f.update=!0)}if(u.read===!1&&f.read===!0||u.insert===!1&&f.insert===!0||u.update===!1&&f.update===!0){let m=`${o}.${l}`;Er(ar.MISMATCHED_TABLE_ATTR_PERMS(m),r,o,l)}}}}return Ele(r)}a(S$,"customValidate");T$.exports={addRoleValidation:dle,alterRoleValidation:fle,dropRoleValidation:mle};function hle(e){let{operation:t,permission:r}=e;if(t===xd.OPERATIONS_ENUM.ADD_ROLE||t===xd.OPERATIONS_ENUM.ALTER_ROLE){let n=r.super_user===!0,s=r.cluster_user===!0;if(Object.keys(r).length>1&&(n||s)){if(s&&n)return ar.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?xd.ROLE_TYPES_ENUM.SUPER_USER:xd.ROLE_TYPES_ENUM.CLUSTER_USER;return ar.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(hle,"validateNoSUPerms");function Ele(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:ar.ROLE_PERMS_ERROR,...e};return nle(new Error,n,ile.BAD_REQUEST)}else return null}a(Ele,"generateRolePermResponse");function Er(e,t,r,n){if(!r)t.main_permissions.push(e);else{let s=n?r+"_"+n:r;t.schema_permissions[s]?t.schema_permissions[s].push(e):t.schema_permissions[s]=[e]}}a(Er,"addPermError")});var nh=M((ZUe,I$)=>{"use strict";var R$=Vn(),b$=gn(),_le=Dl(),lC=y$(),uC=Qo(),XUe=require("uuid").v4,gle=require("util"),MS=(G(),v(j)),Sle=ae(),dC=b$.searchByValue,Tle=b$.searchByHash,yle=gle.promisify(_le.delete),Rle=ui(),ble=ud(),{hdbErrors:Ale,handleHDBError:ql}=Ee(),{HDB_ERROR_MSGS:A$,HTTP_STATUS_CODES:rh}=Ale,{UserEventMsg:fC}=ls();I$.exports={addRole:Ile,alterRole:wle,dropRole:Nle,listRoles:Cle};function cC(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(cC,"scrubRoleDetails");async function Ile(e){let t=lC.addRoleValidation(e);if(t)throw t;e=cC(e);let r={schema:"system",table:"hdb_role",attribute:"role",value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await dC(r)||[])}catch(i){throw ql(i)}if(n&&n.length>0)throw ql(new Error,A$.ROLE_ALREADY_EXISTS(e.role),rh.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 R$.insert(s),uC.signalUserChange(new fC(process.pid)),e=cC(e),e}a(Ile,"addRole");async function wle(e){let t=lC.alterRoleValidation(e);if(t)throw t;e=cC(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await R$.update(r)}catch(s){throw ql(s)}if(n&&n?.message==="updated 0 of 1 records")throw ql(new Error,"Invalid role id",rh.BAD_REQUEST,void 0,void 0,!0);return await uC.signalUserChange(new fC(process.pid)),e}a(wle,"alterRole");async function Nle(e){let t=lC.dropRoleValidation(e);if(t)throw ql(new Error,t,rh.BAD_REQUEST,void 0,void 0,!0);let r=new ble(MS.SYSTEM_SCHEMA_NAME,MS.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await Tle(r));if(n.length===0)throw ql(new Error,A$.ROLE_NOT_FOUND,rh.NOT_FOUND,void 0,void 0,!0);let s=new Rle(MS.SYSTEM_SCHEMA_NAME,MS.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await dC(s)),o=!1;if(Sle.isEmptyOrZeroLength(i)===!1){for(let l=0;l<i.length;l++)if(i[l].active===!0){o=!0;break}}if(o===!0)throw ql(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,rh.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await yle(c),uC.signalUserChange(new fC(process.pid)),`${n[0].role} successfully deleted`}a(Nle,"dropRole");async function Cle(){return dC({table:"hdb_role",schema:"system",hash_attribute:"id",attribute:"id",value:"*",get_attributes:["*"]})}a(Cle,"listRoles")});var mC={};ye(mC,{start:()=>C$,startOnMainThread:()=>Lle});function C$({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r){let n=(0,w$.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(Ole.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 Ple(i)}}}async function Ple(e){let t=lt().system.hdb_role;for await(let r of t.search([{attribute:"role",value:e.role}])){let{__createdtime__:n,__updatedtime__:s,...i}=r;return(0,N$.isEqual)(i,e)?void 0:(e.id=r.id,(0,US.alterRole)(e))}return(0,US.addRole)(e)}var US,w$,N$,Ole,Lle,O$=se(()=>{Oe();US=b(nh()),w$=require("yaml"),N$=require("lodash"),Ole=["super_user","cluster_user","structure_user"];a(C$,"start");a(Ple,"ensureRole");Lle=C$});async function xS(e){let t=(0,D$.pathToFileURL)(e).toString();if(Dle)return sh||(sh=vle(Ule)),(await(await sh).import(t)).namespace;try{return await import(t)}catch(r){try{(await import("internal/util")).default.decorateErrorStack(r)}catch{}throw r}}async function vle(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),sh=new Compartment({console,Math,Date,fetch:Mle,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,L$.extname)(r)||(r+=".js"),r)},importHook:a(async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){s.Resource=Xt,s.tables=yn,s.databases=Me}};let n=await(0,P$.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)},"importHook")}),sh}function Mle(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 Ule(){return{Resource:Xt,tables:yn}}var P$,L$,D$,Dle,sh,pC=se(()=>{ji();Oe();P$=require("fs/promises"),L$=require("path"),D$=require("url"),Dle=!1;a(xS,"secureImport");a(vle,"getCompartment");a(Mle,"secureOnlyFetch");a(Ule,"getGlobalVars")});var hC={};ye(hC,{ResourceLoadError:()=>BS,handleApplication:()=>xle,suppressHandleApplicationWarning:()=>Ble});function M$(e){return typeof e=="function"&&("get"in e||"put"in e||"post"in e||"delete"in e)}async function xle(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 xS(r.absolutePath),s=(0,v$.dirname)(r.urlPath).replace(/\\/g,"/").replace(/^\/$/,"");M$(n.default)&&(e.resources.set(s,n.default),e.logger.debug(`Registered root resource: ${s}`)),U$(e,n,s)}catch(n){throw new BS(r.absolutePath,n)}},"handleResourceEntry"))}function U$(e,t,r){for(let n in t){let s=t[n],i=`${r}/${n}`;M$(s)?(e.resources.set(i,s),e.logger.debug(`Registered resource: ${i}`)):typeof s=="object"&&U$(e,s,i)}}var v$,BS,Ble,x$=se(()=>{pC();v$=require("path");a(M$,"isResource");BS=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(xle,"handleApplication");a(U$,"recurseForResources");Ble=!0});var _C={};ye(_C,{start:()=>Fle});function Fle({resources:e}){e.set("login",EC),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var EC,B$=se(()=>{ji();a(Fle,"start");EC=class extends Xt{static{a(this,"Login")}static async get(t,r,n){}static async post(t,r,n){let{username:s,password:i,redirect:o}=r;return{data:await n.login(s,i)}}}});function kS(e,t){let r={openapi:kle,info:{title:"HarperDB HTTP REST interface",version:$$.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)FS[l.type]?o[l.name]=new SC(FS[l.type],l.type):l.properties?(o[l.name]=new K$(l.type),s(l)):l.elements?.properties&&(o[l.name]=new $le(l.elements.type),s(l.elements)),l.nullable===!1&&c.push(l.name);r.components.schemas[i.type]=new q$(o,!i.sealed,c)}},"includeDefinitionInSchema");for(let[,i]of e){if(!i.path||i.Resource.isError)continue;let{path:o}=i,c=o.split("/").pop(),{attributes:l,sealed:u}=i.Resource,{prototype:d,primaryKey:f="id"}=i.Resource;if(!l&&e.allTypes.has(i.path)){let k=e.allTypes.get(i.path);u=k.sealed,l=k.properties}if(!f)continue;let m={},p=[],h=[];if(l)for(let{type:k,name:z,elements:Y,relationship:ce,definition:de,nullable:te}of l){let Se=de??Y?.definition;Se&&s(Se),te===!1&&h.push(z),ce?k==="array"?m[z]={type:"array",items:{$ref:$s+Y.type}}:m[z]={$ref:$s+k}:Se?k==="array"?m[z]={type:"array",items:{$ref:$s+Se.type}}:m[z]={$ref:$s+Se.type}:k==="array"?Y.type==="Any"?m[z]={type:"array",items:{format:Y.type}}:m[z]={type:"array",items:new SC(FS[Y.type],Y.type)}:k==="Any"?m[z]={format:k}:m[z]=new SC(FS[k],k),p.push(new TC(z,"query",m[z]))}let E=Object.keys(m),_=new TC(f,"path",{type:"string",format:"ID"});_.required=!0,_.description="primary key of record";let R=new TC("property","path",{enum:E});R.required=!0,r.components.schemas[c]=new q$(m,!u,h);let S=d.post!==Resource.prototype.post||d.update,y=typeof d.put=="function",w=typeof d.get=="function",I=typeof d.delete=="function",H=typeof d.patch=="function",X=`/${o}/`;r.paths[X]||(r.paths[X]={}),S&&(r.paths[X].post=new Hle(c,n,{200:new Fd({$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 F$(p,n,{200:new k$},"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 gC(p,n,{200:new Fd({type:"array",items:{$ref:$s+c}})},"search for records by the specified property name and value pairs")),I&&(r.paths[X].delete=new G$(p,n,"delete all the records that match the provided query",{204:new H$}));let q="/"+o+"/{"+f+"}";if(r.paths[q]||(r.paths[q]={}),r.paths[q].options=new F$(p,n,{200:new k$},"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 gC([_],n,{200:new Fd({$ref:$s+c})},"retrieve a record by its primary key")),y&&(r.paths[q].put=new Gle([_],n,c,{200:new Fd({$ref:$s+c})},"create or update the record with the URL path that maps to the record's primary key")),H&&(r.paths[q].patch=new qle([_],n,c,{200:new Fd({$ref:$s+c})},"patch the record with the URL path that maps to the record's primary key")),I&&(r.paths[q].delete=new G$([_],n,"delete a record with the given primary key",{204:new H$})),w&&R.schema.enum.length>0){let k=`/${o}/{${f}}.{property}`;r.paths[k]||(r.paths[k]={}),r.paths[k].get=new gC([_,R],n,{200:new Fd({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 Hle(e,t,r,n){this.description=n,this.requestBody={content:{"application/json":{schema:{$ref:$s+e}}}},this.security=t,this.responses=r}function gC(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function F$(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function k$(){this.description=V$,this.headers={},this.content={}}function Fd(e,t){this.description=V$,this.content={"application/json":{schema:e}},this.headers=t}function H$(){this.description="successfully processed request, no content returned to client"}function Gle(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 qle(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 G$(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function q$(e,t,r){this.type="object",this.properties=e,this.additionalProperties=t,this.required=r}function SC(e,t){this.type=e,(e==="string"||e==="number"||e==="integer")&&t!=="String"&&(this.format=t)}function K$(e){this.$ref=`#/components/schemas/${e}`}function $le(e){this.type="array",this.items=new K$(e)}function TC(e,t,r){this.name=e,this.in=t,this.schema=r}var $$,kle,FS,$s,V$,yC=se(()=>{$$=b(Rt()),kle="3.0.3",FS={Int:"integer",Float:"number",Long:"integer",ID:"string",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer"},$s="#/components/schemas/",V$="successful operation";a(kS,"generateJsonApi");a(Hle,"Post");a(gC,"Get");a(F$,"Options");a(k$,"ResponseOptions200");a(Fd,"Response200");a(H$,"Response204");a(Gle,"Put");a(qle,"Patch");a(G$,"Delete");a(q$,"ResourceSchema");a(SC,"Type");a(K$,"Ref");a($le,"ArrayRef");a(TC,"Parameter")});var W$={};ye(W$,{Request:()=>hc,createReuseportFd:()=>HS});var Y$,hc,RC,bC,HS,ih=se(()=>{Y$=require("os"),hc=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 bC(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 RC(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)}},RC=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)}},bC=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,Y$.platform)()!="win32"&&(HS=require("node-unix-socket").createReuseportFd)});var qS={};ye(qS,{parseHeaderValue:()=>IC,start:()=>Yle});async function Kle(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream",s=n?"CONNECT":e.method;e.search&&Tg(e);let i=new Hs;try{e.responseHeaders=i;let o=e.url.slice(1),c,l;if(o!==j$){let _=GS.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=IC(_);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 _=IC(u).map(R=>(R.next?.name==="confirm"&&R.next.value>=0&&(e.replicatedConfirmation=+R.next.value),R.name));e.replicateTo=_.length===1&&+_[0]>=0?+_[0]:_[0]==="*"?void 0:_}r["x-replicate-from"]==="none"&&(e.replicateFrom=!1);let f=await At(e,()=>{if(r["content-length"]||r["transfer-encoding"])try{e.data=qo(r["content-type"],!0)(e.body,e.headers)}catch(_){throw new kd.ClientError(_,400)}if(e.authorize=!0,o===j$&&s==="GET"){if(e?.user?.role?.permission?.super_user)return kS(GS,`${e.protocol}://${e.hostname}`);throw new kd.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 kd.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new kd.ServerError(`Method ${s} is not recognized`,501)}}),m=200,p=e.lastModified;if(f==null)m=s==="GET"||s==="HEAD"?404:204,AC.lastModified&&isFinite(p)&&i.setIfNone("Last-Modified",new Date(p).toUTCString());else if(f.status>0&&f.headers){let _=Pq(f.headers,i);return f.headers!==_&&(f.headers=_),f.data!==void 0&&(f.body=xm(f.data,e,f)),f}else if(isFinite(p)){Vle[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",_),AC.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=xm(f,e,h),s==="HEAD"&&(h.body=void 0)),h}catch(o){o.statusCode?o.statusCode===500?Ei.warn(o):Ei.info(o):Ei.error(o),o.statusCode===405&&(o.method&&(o.message+=` to handle HTTP method ${o.method.toUpperCase()||""}`),o.allow&&(o.allow.push("trace","head","options"),i.setIfNone("Allow",o.allow.map(l=>l.toUpperCase()).join(", "))));let c={status:o.statusCode||500,headers:i,body:void 0};return c.body=xm(o instanceof Error?Q$(o):o,e,c),c}}function Yle(e){AC=e,e.includeExpensiveRecordCountEstimates&&(hc.prototype.includeExpensiveRecordCountEstimates=!0),!z$&&(z$=!0,GS=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return Kle(t,r)},e),e.webSocket!==!1&&e.server.ws(async(t,r,n)=>{oh++;let s=new ns;J$||(J$=!0,Xm(l=>{oh>0&&l.push({metric:"ws-connections",connections:oh,byThread:!0})}));let i;t.on("error",l=>{i=!0,Ei.warn(l)});let o;t.on("message",a(function(u){o||(o=qo(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",()=>{oh--,en(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()});try{await n;let l=r.url.slice(1),u=GS.getMatch(l,"ws");if(en(!!u,"connection","ws","connect"),u){r.handlerPath=u.path,Ye(h=>({count:h.count,total:oh}),"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 At(r,()=>f.connect(d,s,r)))[Symbol.asyncIterator]();let p;for(;!(p=await c.next()).done;){let h=await Go(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?Ei.warn(l):Ei.info(l):Ei.error(l),t.close(Wle[l.statusCode]||1011,Q$(l))}t.close()},e))}function IC(e){return e.trim().split(",").map(t=>{let r,n=t.trim().split(";"),s;for(;s=n.pop();)if(s.includes("=")){let[i,o]=s.trim().split("=");i=i.trim(),o&&(o=o.trim()),r={name:i.toLowerCase(),value:o,next:r}}else r={name:s.toLowerCase(),next:r};return r})}var Ei,kd,Q$,sn,Vle,AC,j$,z$,GS,J$,oh,Wle,X$=se(()=>{$o();is();Ei=b(Q()),kd=b(Ee());yg();Fu();Wa();Kp();yC();ih();bg();({errorToString:Q$}=Ei),sn=new Uint8Array(8),Vle=new Float64Array(sn.buffer,0,1),AC={},j$="openapi";a(Kle,"http");oh=0;a(Yle,"start");Wle={401:3e3,403:3003};a(IC,"parseHeaderValue")});var wC=M((Ixe,eV)=>{var{recordAction:$S,recordActionBinary:Z$}=(is(),v(dg)),jle=require("fastify-plugin"),zle=200;eV.exports=jle(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),$S(o,"duration",u,f,d),Z$(s.raw.statusCode<400,"success",u,f,d),Z$(1,"response_"+s.raw.statusCode,u,f,d);let m=zle;i?.pipe?(i.on("data",_=>{m+=_.length}),i.on("end",()=>{$S(performance.now()-c,"transfer",u,f,d),$S(m,"bytes-sent",u,f,d)})):(m+=i?.length||0,$S(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((wxe,tV)=>{var Jle=pt(),Qle={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};tV.exports=function(e){return Jle.validateObject(e,Qle)}});var VS=M((Nxe,nV)=>{"use strict";var Xle=(G(),v(j)).OPERATIONS_ENUM,NC=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=Xle.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};nV.exports=NC});var lh={};ye(lh,{createTokens:()=>OC,getJWTRSAKeys:()=>zS,refreshOperationToken:()=>PC,validateOperationToken:()=>LC,validateRefreshToken:()=>JS});async function zS(){if(KS)return KS;try{let e=ah.default.join(ch.default.getHdbBasePath(),nA),t=await YS.default.readFile(ah.default.join(e,Sm.JWT_PASSPHRASE_NAME),"utf8"),r=await YS.default.readFile(ah.default.join(e,Sm.JWT_PRIVATE_KEY_NAME),"utf8");return KS={publicKey:await YS.default.readFile(ah.default.join(e,Sm.JWT_PUBLIC_KEY_NAME),"utf8"),privateKey:r,passphrase:t},KS}catch(e){throw jS.default.error(e),new _i.ClientError(Gd.NO_ENCRYPTION_KEYS,Hd.INTERNAL_SERVER_ERROR)}}async function OC(e){let t=(0,CC.validateBySchema)(e,fo.default.object({username:fo.default.string().optional(),password:fo.default.string().optional(),role:fo.default.string().optional(),expires_in:fo.default.alternatives(fo.default.string(),fo.default.number()).optional()}));if(t)throw new _i.ClientError(t.message);let r;try{let f=e.bypass_auth!==!0;!e.username&&!e.password&&(e.username=e.hdb_user?.username,f=!1),r=await Td(e.username,e.password,f)}catch(f){throw jS.default.error(f),new _i.ClientError(Gd.INVALID_CREDENTIALS,Hd.UNAUTHORIZED)}if(!r)throw new _i.ClientError(Gd.INVALID_CREDENTIALS,Hd.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 zS(),c=await qd.default.sign(i,{key:o.privateKey,passphrase:o.passphrase},{expiresIn:e.expires_in??cV,algorithm:WS,subject:$d.OPERATION}),l=await qd.default.sign(i,{key:o.privateKey,passphrase:o.passphrase},{expiresIn:Zle,algorithm:WS,subject:$d.REFRESH}),u=Zw(l,$r.SHA256);if((await(0,sV.update)(new iV.default(_m,Uu.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]))).skipped_hashes.length>0)throw new _i.ClientError(Gd.REFRESH_TOKEN_SAVE_FAILED,Hd.INTERNAL_SERVER_ERROR);return oV.default.signalUserChange(new aV.UserEventMsg(process.pid)),{operation_token:c,refresh_token:l}}async function PC(e){let t=(0,CC.validateBySchema)(e,fo.default.object({refresh_token:fo.default.string().required()}).required());if(t)throw new _i.ClientError(t.message);let{refresh_token:r}=e;await JS(r);let n=await zS(),s=await qd.default.decode(r);return{operation_token:await qd.default.sign({username:s.username,super_user:s.super_user,cluster_user:s.cluster_user},{key:n.privateKey,passphrase:n.passphrase},{expiresIn:cV,algorithm:WS,subject:$d.OPERATION})}}async function LC(e){return lV(e,$d.OPERATION)}async function JS(e){return lV(e,$d.REFRESH)}async function lV(e,t){try{let r=await zS(),n=await qd.default.verify(e,r.publicKey,{algorithms:WS,subject:t});if(n.role)throw new Error("Invalid token");let s=await Td(n.username,void 0,!1);if(t===$d.REFRESH&&!eN(s.refresh_token,e))throw new Error("Invalid token");return s}catch(r){throw jS.default.warn(r),r?.name==="TokenExpiredError"?new _i.ClientError(Gd.TOKEN_EXPIRED,Hd.FORBIDDEN):new _i.ClientError(Gd.INVALID_TOKEN,Hd.UNAUTHORIZED)}}var qd,YS,ah,fo,CC,_i,jS,sV,iV,oV,aV,ch,Hd,Gd,cV,Zle,WS,$d,KS,Vd=se(()=>{qd=b(require("jsonwebtoken")),YS=b(require("fs-extra")),ah=b(require("node:path")),fo=b(require("joi")),CC=b(pt());G();_i=b(Ee()),jS=b(Q());rN();Es();sV=b(Vn()),iV=b(VS()),oV=b(Qo()),aV=b(ls()),ch=b(fe()),{HTTP_STATUS_CODES:Hd,AUTHENTICATION_ERROR_MSGS:Gd}=_i.hdbErrors;ch.default.initSync();cV=ch.default.get(x.AUTHENTICATION_OPERATIONTOKENTIMEOUT)||"1d",Zle=ch.default.get(x.AUTHENTICATION_REFRESHTOKENTIMEOUT)||"30d",WS="RS256",$d={OPERATION:"operation",REFRESH:"refresh"};a(zS,"getJWTRSAKeys");a(OC,"createTokens");a(PC,"refreshOperationToken");a(LC,"validateOperationToken");a(JS,"validateRefreshToken");a(lV,"validateToken")});var DC=M((vxe,fV)=>{"use strict";var eue=rV(),Kd=require("passport"),tue=require("passport-local").Strategy,rue=require("passport-http").BasicStrategy,nue=require("util"),sue=(Es(),v(ao)),dV=nue.callbackify(sue.findAndValidateUser),Dxe=Jr(),iue=(G(),v(j)),uV=(Vd(),v(lh)),{AccessViolation:oue}=Ee();Kd.use(new tue(function(e,t,r){dV(e,t,r)}));Kd.use(new rue(function(e,t,r){dV(e,t,r)}));Kd.serializeUser(function(e,t){t(null,e)});Kd.deserializeUser(function(e,t){t(null,e)});function aue(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 oue)}switch(a(i,"handleResponse"),n){case"Basic":Kd.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===iue.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?uV.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):uV.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Kd.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(aue,"authorize");function cue(e,t){let r=eue(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(cue,"checkPermissions");fV.exports={authorize:aue,checkPermissions:cue}});var FC=M((Bxe,EV)=>{var eT=require("clone"),tT=pt(),lue=ae(),XS=(G(),v(j)),Uxe=Q(),vC=require("fs"),UC=require("joi"),{string:ZS}=UC.types(),{hdbErrors:uue,handleHDBError:QS}=Ee(),{HDB_ERROR_MSGS:xxe,HTTP_STATUS_CODES:MC}=uue,{commonValidators:Yd}=Ji(),mV=" is required",due=["insert","update","upsert"],xC={database:{presence:!1,format:Yd.schema_format,length:Yd.schema_length},schema:{presence:!1,format:Yd.schema_format,length:Yd.schema_length},table:{presence:!0,format:Yd.schema_format,length:Yd.schema_length},action:{inclusion:{within:due,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},fue={schema:ZS.required(),table:ZS.required(),action:ZS.valid("insert","update","upsert")},{AWS_ACCESS_KEY:mue,AWS_SECRET:pue,AWS_BUCKET:hue,AWS_FILE_KEY:Eue,REGION:_ue}=XS.S3_BUCKET_AUTH_KEYS,gue={s3:{presence:!0},[`s3.${mue}`]:{presence:!0,type:"String"},[`s3.${pue}`]:{presence:!0,type:"String"},[`s3.${hue}`]:{presence:!0,type:"String"},[`s3.${Eue}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${_ue}`]:{presence:!0,type:"String"}},pV=eT(xC);pV.data.presence={message:mV};var hV=eT(xC);hV.file_path.presence={message:mV};var Sue=Object.assign(eT(xC),gue),BC=eT(fue);BC.csv_url=ZS.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();BC.passthrough_headers=UC.object();function Tue(e){let t=tT.validateObject(e,pV);return rT(e,t)}a(Tue,"dataObject");function yue(e){let t=tT.validateBySchema(e,UC.object(BC));return rT(e,t)}a(yue,"urlObject");function Rue(e){let t=tT.validateObject(e,hV);return rT(e,t)}a(Rue,"fileObject");function bue(e){let t=tT.validateObject(e,Sue);return rT(e,t)}a(bue,"s3FileObject");function rT(e,t){if(!t){let r=lue.checkGlobalSchemaTable(e.schema,e.table);if(r)return QS(new Error,r,MC.BAD_REQUEST);if(e.operation===XS.OPERATIONS_ENUM.CSV_FILE_LOAD)try{vC.accessSync(e.file_path,vC.constants.R_OK|vC.constants.F_OK)}catch(n){return n.code===XS.NODE_ERROR_CODES.ENOENT?QS(n,`No such file or directory ${n.path}`,MC.BAD_REQUEST):n.code===XS.NODE_ERROR_CODES.EACCES?QS(n,`Permission denied ${n.path}`,MC.BAD_REQUEST):QS(n)}}return t}a(rT,"postValidateChecks");EV.exports={dataObject:Tue,urlObject:yue,fileObject:Rue,s3FileObject:bue}});var kC=M((kxe,_V)=>{"use strict";var uh=Q(),nT=(G(),v(j));async function Aue(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===nT.OPERATIONS_ENUM.INSERT||t.operation===nT.OPERATIONS_ENUM.UPDATE||t.operation===nT.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===nT.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(uh.info(i.message),i):i.http_resp_msg?(uh.error(`Error calling operation: ${e.name}`),uh.error(i.http_resp_msg),i):(uh.error(`Error calling operation: ${e.name}`),uh.error(i),i)}}a(Aue,"callOperationFunctionAsAwait");_V.exports={callOperationFunctionAsAwait:Aue}});var HC=M((Gxe,SV)=>{"use strict";var{S3:Iue,GetObjectCommand:wue}=require("@aws-sdk/client-s3");SV.exports={getFileStreamFromS3:Nue,getS3AuthObj:gV};async function Nue(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await gV(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new wue(r))).Body}a(Nue,"getFileStreamFromS3");function gV(e,t,r){return new Iue({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(gV,"getS3AuthObj")});var yV=M(($xe,TV)=>{"use strict";var GC=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}},qC=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};TV.exports={BulkLoadFileObject:GC,BulkLoadDataObject:qC}});var bV=M((Kxe,RV)=>{"use strict";var $C=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}};RV.exports=$C});var IV=M((Wxe,AV)=>{"use strict";var VC=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};AV.exports=VC});var YC=M((zxe,NV)=>{"use strict";var wV=bV(),Cue=IV(),{HDB_ERROR_MSGS:Oue}=Jr(),KC=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=Oue.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 wV(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let l=new Cue(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 wV(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}};NV.exports=KC});var $l=M((Xxe,LV)=>{"use strict";var Qxe=gn(),dh=Q(),{validateBySchema:CV}=pt(),na=require("joi"),Pue=no(),sT=ae(),{handleHDBError:iT,hdbErrors:Lue,ClientError:OV}=Ee(),{HDB_ERROR_MSGS:oT,HTTP_STATUS_CODES:WC}=Lue,PV=fe();PV.initSync();var{getDatabases:jC}=(Oe(),v(mt)),Due=require("fs-extra"),vue=(G(),v(j));LV.exports={describeAll:Mue,describeTable:aT,describeSchema:Uue};async function Mue(e={}){try{let t=sT.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=jC(),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 aT({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 aT({schema:m,table:h,exact_count:u,include_computed:d},_)}E&&l.push(E)}catch(E){dh.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 dh.error("Got an error in describeAll"),dh.error(t),iT(new Error,oT.DESCRIBE_ALL_ERR)}}a(Mue,"describeAll");async function aT(e,t){sT.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=CV(e,na.object({database:na.string(),table:na.string().required(),exact_count:na.boolean().strict(),include_computed:na.boolean().strict()}));if(i)throw new OV(i.message);let c=jC()[r];if(!c)throw iT(new Error,oT.SCHEMA_NOT_FOUND(e.schema),WC.NOT_FOUND);let l=c[n];if(!l)throw iT(new Error,oT.TABLE_NOT_FOUND(e.schema,e.table),WC.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 Due.stat(l.primaryStore.env.path)).size}catch(p){dh.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")),PV.get(vue.CONFIG_PARAMS.CLUSTERING_ENABLED)&&(m.clustering_stream_name=Pue.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){dh.warn(`unable to stat table dbi due to ${p}`)}return m}a(aT,"descTable");async function Uue(e){sT.transformReq(e);let t=CV(e,na.object({database:na.string(),exact_count:na.boolean().strict(),include_computed:na.boolean().strict()}));if(t)throw new OV(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=jC()[n];if(!i)throw iT(new Error,oT.SCHEMA_NOT_FOUND(e.schema),WC.NOT_FOUND);let o={};for(let c in i){let l;if(r&&r.tables[c]&&(l=r.tables[c]),sT.isEmpty(l)||l.describe){let u=await aT({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(Uue,"describeSchema")});var xV=M((e0e,UV)=>{"use strict";var xue=$l(),{hdbErrors:DV}=Ee(),{getDatabases:vV}=(Oe(),v(mt));UV.exports={checkSchemaExists:MV,checkSchemaTableExists:Bue,schemaDescribe:xue};async function MV(e){if(!vV()[e])return DV.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(MV,"checkSchemaExists");async function Bue(e,t){let r=await MV(e);if(r)return r;if(!vV()[e][t])return DV.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Bue,"checkSchemaTableExists")});function zC(e){let t=e.get(cT),r=t?(0,Wd.unpack)(t):null;r||(r={remoteNameToId:{}});let n=tt(),s=!1;r.nodeName=tt();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:mh(e)??1,nodes:[]})})}i[n]=0,e.putSync(cT,(0,Wd.pack)(r))}return r}function fh(e){return zC(e).remoteNameToId}function FV(e,t){let r=zC(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(cT,(0,Wd.pack)(r)),s}function lT(e,t){let r=zC(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(cT,(0,Wd.pack)(r))}return BV.trace?.("The remote node name map",e,n,s),s}var BV,Wd,cT,JC=se(()=>{BV=b(sr());Ss();Wd=require("msgpackr"),cT=Symbol.for("remote-ids");a(zC,"getIdMappingRecord");a(fh,"exportIdMapping");a(FV,"remoteToLocalNodeId");a(lT,"getIdOfRemoteNode")});var VV={};ye(VV,{commitsAwaitingReplication:()=>jd,getHDBNodeTable:()=>Gt,getReplicationSharedStatus:()=>zd,iterateRoutes:()=>hh,shouldReplicateToNode:()=>ph,subscribeToNodeUpdates:()=>Jd});function Gt(){return kV||(kV=ze({table:"hdb_nodes",database:"system",attributes:[{name:"name",isPrimaryKey:!0},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"url"},{attribute:"routes"},{attribute:"ca"},{attribute:"ca_info"},{attribute:"replicates"},{attribute:"revoked_certificates"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]}))}function zd(e,t,r,n){return new Float64Array(e.getUserSharedBuffer(["replicated",t,r],new ArrayBuffer(64),n&&{callback:n}))}function Jd(e){Gt().subscribe({}).then(async t=>{for await(let r of t){let n=r?.value?.name;$V.debug?.("adding node",n,"on node",tt()," on process",process.pid),server.nodes=server.nodes.filter(i=>i.name!==n),r.type==="put"&&n!==tt()&&(r.value?server.nodes.push(r.value):console.error("Invalid node update event",r));let s=new Map;for await(let i of Gt().search({}))if(i.shard!=null){let o=s.get(i.shard);o||s.set(i.shard,o=[]),o.push(i)}server.shards=s,(r.type==="put"||r.type==="delete")&&e(r.value,r.id)}})}function ph(e,t){let r=Ec.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===Ec.default.get(x.REPLICATION_SHARD))))&&Gt().primaryStore.get(tt())?.replicates||e.subscriptions?.some(n=>(n.database||n.schema)===t&&n.subscribe)}function Fue(){Jd(e=>{_c({},(t,r)=>{let n=e.name,s=HV.get(n);if(s||HV.set(n,s=new Map),s.has(r))return;let i;for(let o in t)if(i=t[o].auditStore,i)break;if(i){let o=zd(i,r,n,()=>{let c=o[0],l=o.lastTime;for(let{txnTime:u,onConfirm:d}of jd.get(r)||[])u>l&&u<=c&&d();o.lastTime=c});o.lastTime=0,s.set(r,o)}})})}function*hh(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=Ec.default.get(x.REPLICATION_SECUREPORT)??(!Ec.default.get(x.REPLICATION_PORT)&&Ec.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||Ec.default.get(x.REPLICATION_PORT)||Ec.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){GV.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 GV,qV,Ec,$V,kV,HV,jd,Qd=se(()=>{Oe();Ss();Pm();GV=require("worker_threads"),qV=b(Ee()),Ec=b(fe());G();$V=b(sr());server.nodes=[];a(Gt,"getHDBNodeTable");a(zd,"getReplicationSharedStatus");a(Jd,"subscribeToNodeUpdates");a(ph,"shouldReplicateToNode");HV=new Map;hx((e,t,r)=>{if(r>server.nodes.length)throw new qV.ClientError(`Cannot confirm replication to more nodes (${r}) than are in the network (${server.nodes.length})`);jd||(jd=new Map,Fue());let n=jd.get(e);return n||(n=[],jd.set(e,n)),new Promise(s=>{let i=0;n.push({txnTime:t,onConfirm:a(()=>{++i===r&&s()},"onConfirm")})})});a(Fue,"startSubscriptionToReplications");a(hh,"iterateRoutes")});var QV={};ye(QV,{connectedToNode:()=>Vl,disconnectedFromNode:()=>Zd,ensureNode:()=>sa,requestClusterStatus:()=>JV,startOnMainThread:()=>QC});async function QC(e){let t=0,r=lt();for(let o of Object.getOwnPropertyNames(r)){let c=r[o];for(let l in c){let u=c[l];if(u.auditStore){uT.set(o,mh(u.auditStore));break}}}gi.whenThreadsStarted.then(async()=>{let o=[];for await(let u of r.system.hdb_nodes?.search([])||[])o.push(u);let c=tt();function l(){let u=Gt().primaryStore.get(c);if(u!==null){let d=e.url??gc();if(u===void 0||u.url!==d||u.shard!==e.shard)return sa(c,{name:c,url:d,shard:e.shard,replicates:!0})}}a(l,"ensureThisNode"),Gt().primaryStore.get(c)&&l();for(let u of hh(e))try{let d=!u.subscriptions;if(d&&await l(),d&&u.replicates==null&&(u.replicates=!0),KV.push(u),o.find(f=>f.url===u.url))continue;s(u)}catch(d){console.error(d)}Jd(s)});let n;function s(o,c=o?.name){let l=tt()&&c===tt()||gc()&&o?.url===gc();if(l){let m=!!o?.replicates;if(n!==void 0&&n!==m)for(let p of Gt().search([]))p.replicates&&p.name!==c&&s(p,p.name);n=m}if(ot.trace("Setting up node replication for",o),!o){for(let[m,p]of mo){let h;for(let[E,{worker:_,nodes:R}]of p){let S=R[0];if(S&&S.name==c){h=!0;for(let[y,{worker:w}]of p)p.delete(y),ot.warn("Node was deleted, unsubscribing from node",c,y,m),w?.postMessage({type:"unsubscribe-from-node",node:c,nodes:R,database:y,url:m});break}}if(h){mo.get(m).iterator.remove(),mo.delete(m);return}}return}if(l)return;if(!o.url){ot.info(`Node ${o.name} is missing url`);return}let u=mo.get(o.url);if(u&&u.iterator.remove(),!(o.replicates===!0||o.replicates?.sends)&&!o.subscriptions?.length&&!u)return;if(ot.info(`Added node ${o.name} at ${o.url} for process ${tt()}`),o.replicates&&o.subscriptions&&(o={...o,subscriptions:null}),o.name){for(let[m,p]of Xd)if(o.url===p.url){Xd.delete(m);break}Xd.set(o.name,o)}let d=lt();if(u||(u=new Map,mo.set(o.url,u)),u.iterator=_c(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}];uT.has(m)&&Eh.default.get(x.REPLICATION_FAILOVER)&&(_.push({replicateByDefault:p,name:tt(),startTime:uT.get(m),endTime:Date.now(),replicates:!0}),uT.delete(m));let R=ph(o,m),S=gi.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=kue.HDB_LEADER_URL??process.env.HDB_LEADER_URL??KV[0]?.url,w=y?new URL(y).hostname:Array.from(Gt().primaryStore.getKeys({}).filter(H=>H!==tt()))[0],I=_[0].name??(_[0].url&&new URL(_[0].url).hostname);ot.warn(`Setting up subscription with leader ${w} for node ${I}`),_[0].isLeader=!w||I===w,setTimeout(()=>{let H={..._[0],type:"subscribe-to-node",database:m,nodes:_};E?E.postMessage(H):_h(H)},Hue)}else{ot.info("Node no longer should be used, unsubscribing from node",{replicates:o.replicates,databaseName:m,node:o,subscriptions:o.subscriptions,hasDatabase:!!d[m],thisReplicates:Gt().primaryStore.get(tt())?.replicates}),Gt().primaryStore.get(tt())?.replicates||(n=!1,ot.info("Disabling replication, this node name",tt(),Gt().primaryStore.get(tt()),m));let y={type:"unsubscribe-from-node",database:m,url:o.url,name:o.name,nodes:_};E?E.postMessage(y):fT(y)}}a(f,"onDatabase")}a(s,"onNodeUpdate"),Zd=a(function(o){try{ot.info("Disconnected from node",o.name,o.url,"finished",!!o.finished);let c=Array.from(Xd.keys()),l=c.sort(),u=l.indexOf(o.name||Si(o.url));if(u===-1){ot.warn("Disconnected node not found in node map",o.name,c);return}let d=mo.get(o.url),f=d?.get(o.database);if(!f){ot.warn("Disconnected node not found in replication map",o.database,d);return}if(f.connected=!1,o.finished||!Eh.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],_=Xd.get(E);d=mo.get(_.url);let R=d?.get(o.database);if(!R||R.connected===!1||R.nodes[0].shard!==p){h=(h+1)%l.length;continue}let{nodes:S}=R,y=!1;for(let w of f.nodes){if(S.some(I=>I.name===w.name)){ot.info(`Disconnected node is already failing over to ${E} for ${o.database}`);continue}w.endTime<Date.now()||(S.push(w),ot.info(`Failing over ${o.database} from ${o.name} to ${E}`),i(w,o.database,R.nodes[0]),y=!0)}f.nodes=[f.nodes[0]],y||ot.info(`Disconnected node ${o.name} has no nodes to fail over to ${E}`);return}ot.warn("Unable to find any other node to fail over to",o.name,o.url)}catch(c){ot.error("Error failing over node",c)}},"disconnectedFromNode"),Vl=a(function(o){let c=mo.get(o.url),l=c?.get(o.database);if(!l){ot.warn("Connected node not found in replication map, this may be because the node is being removed",o.database,c);return}l.connected=!0,l.latency=o.latency;let u=l.nodes[0];if(!u){ot.warn("Newly connected node has no node subscriptions",o.database,l);return}if(!u.name){ot.debug("Connected node is not named yet",o.database,l);return}if(!Eh.default.get(x.REPLICATION_FAILOVER))return;l.nodes=[u];let d=!1;for(let f of mo.values()){let m=f.get(o.database);if(!m||m==l)continue;let{worker:p,nodes:h,connected:E}=m;if(h)if(E===!1&&h[0].shard===u.shard&&node.url===u.url)for(let _ of h)i(_,o.database);else{let _=h.filter(R=>{if(R)return R.name===u.name&&R.worker?(R.worker.postMessage({type:"unsubscribe-to-node",database:o.database,url:o.url,nodes:[R]}),!1):!0});_.length<h.length&&(m.nodes=_)}}},"connectedToNode");function i(o,c,l=o){let u=gi.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]}):_h({url:l.url,name:l.name,database:c,nodes:[o]})}a(i,"connectToNextWorker"),(0,gi.onMessageByType)("disconnected-from-node",Zd),(0,gi.onMessageByType)("connected-to-node",Vl),(0,gi.onMessageByType)("request-cluster-status",JV)}function JV(e,t){let r=[];for(let[n,s]of Xd)try{let i=mo.get(s.url);ot.info("Getting cluster status for",n,s.url,"has dbs",i?.size);let o=[];if(i){for(let[l,{worker:u,connected:d,nodes:f,latency:m}]of i)o.push({database:l,connected:d,latency:m,threadId:u?.threadId,nodes:f.filter(p=>!(p.endTime<Date.now())).map(p=>p.name)});let c=WV(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 sa(e,t){let r=Gt();e=e??Si(t.url),t.name=e;try{if(t.ca){let s=new jV.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&&!Eh.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=WV(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 gi,dT,ot,YV,Eh,jV,zV,WV,kue,Hue,mo,Zd,Vl,Xd,uT,KV,gh=se(()=>{Oe();gi=b(st());Ss();dT=require("worker_threads");Qd();ot=b(Q()),YV=b(require("lodash")),Eh=b(fe());G();jV=require("crypto"),zV=b(require("minimist")),{cloneDeep:WV}=YV.default,kue=(0,zV.default)(process.argv),Hue=200,mo=new Map,Xd=new Map,uT=new Map,KV=[];a(QC,"startOnMainThread");a(JV,"requestClusterStatus");dT.parentPort&&(Zd=a(e=>{dT.parentPort.postMessage({type:"disconnected-from-node",...e})},"disconnectedFromNode"),Vl=a(e=>{dT.parentPort.postMessage({type:"connected-to-node",...e})},"connectedToNode"),(0,gi.onMessageByType)("subscribe-to-node",e=>{_h(e)}),(0,gi.onMessageByType)("unsubscribe-from-node",e=>{fT(e)}));a(sa,"ensureNode")});var ys=M(qt=>{"use strict";var _r=require("path"),{watch:Gue}=require("chokidar"),Wn=require("fs-extra"),ef=require("node-forge"),n1=require("net"),{generateKeyPair:XC,X509Certificate:ia,createPrivateKey:s1,randomBytes:que}=require("node:crypto"),$ue=require("util");XC=$ue.promisify(XC);var Mt=ef.pki,Ti=require("joi"),{v4:i1}=require("uuid"),{validateBySchema:rO}=pt(),{forComponent:Vue}=Q(),Ts=fe(),Vs=(G(),v(j)),{CONFIG_PARAMS:Yl}=Vs,yi=hN(),{ClientError:Sc}=Ee(),pT=require("node:tls"),{relative:o1,join:Kue}=require("node:path"),{CERTIFICATE_VALUES:XV}=yi,Yue=el(),ZC=gt(),{table:Wue,getDatabases:jue,databases:mT}=(Oe(),v(mt)),{getJWTRSAKeys:ZV}=(Vd(),v(lh)),Xe=Vue("tls").conditional;qt.generateKeys=iO;qt.updateConfigCert=p1;qt.createCsr=tde;qt.signCertificate=rde;qt.setCertTable=tf;qt.loadCertificates=d1;qt.reviewSelfSignedCert=aO;qt.createTLSSelector=E1;qt.listCertificates=g1;qt.addCertificate=cde;qt.removeCertificate=ude;qt.createNatsCerts=ide;qt.generateCertsKeys=sde;qt.getReplicationCert=Th;qt.getReplicationCertAuth=ede;qt.renewSelfSigned=ode;qt.hostnamesFromCert=lO;qt.getKey=dde;qt.getHostnamesFromCertificate=fde;qt.getPrimaryHostName=cO;qt.generateSerialNumber=_T;var{urlToNodeName:a1,getThisNodeUrl:zue,getThisNodeName:ET,clearThisNodeName:Jue}=(Ss(),v(oa)),{readFileSync:Que,statSync:c1}=require("node:fs"),h0e=fe(),{getTicketKeys:Xue,onMessageFromWorkers:Zue}=st(),{isMainThread:l1}=require("worker_threads"),{TLSSocket:u1,createSecureContext:E0e}=require("node:tls"),nO=3650,Sh=["127.0.0.1","localhost","::1"],sO=[{name:"countryName",value:"USA"},{name:"stateOrProvinceName",value:"Colorado"},{name:"localityName",value:"Denver"},{name:"organizationName",value:"HarperDB, Inc."}];function _T(){let e=que(8);return e[0]=e[0]&127|1,e.toString("hex")}a(_T,"generateSerialNumber");Zue(async e=>{e.type===Vs.ITC_EVENT_TYPES.RESTART&&(Ts.initSync(!0),await aO())});var on;function yc(){return on||(on=jue().system.hdb_certificate,on||(on=Wue({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__"}]}))),on}a(yc,"getCertTable");async function Th(){let e=E1("operations-api"),t={secureContexts:null,setSecureContext:a(s=>{},"setSecureContext")};await e.initialize(t);let r=t.secureContexts.get(ET());if(!r)return;let n=new ia(r.options.cert);return r.cert_parsed=n,r.issuer=n.issuer,r}a(Th,"getReplicationCert");async function ede(){yc();let e=(await Th()).options.cert,r=new ia(e).issuer.match(/CN=(.*)/)?.[1];return on.get(r)}a(ede,"getReplicationCertAuth");var e1,Tc=new Map;function d1(){if(e1)return;e1=!0;let e=[{configKey:Yl.TLS},{configKey:Yl.OPERATIONSAPI_TLS}];yc();let t=_r.dirname(ZC.getConfigFilePath()),r;for(let{configKey:n}of e){let s=ZC.getConfigFromFile(n);if(s){Array.isArray(s)||(s=[s]);for(let i of s){let o=i.privateKey,c=o&&o1(Kue(t,"keys"),o);c&&t1(o,l=>{Tc.set(c,l)},"private key");for(let l of[!1,!0]){let u=i[l?"certificateAuthority":"certificate"];if(u&&l1){let d;t1(u,f=>{if(XV.cert===f)return;let m=i.hostname??i.hostnames??i.host??i.hosts;m&&!Array.isArray(m)&&(m=[m]);let p=h1(u),h=new ia(p),E;try{E=cO(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 ia(XV.cert)))return;let _=on.primaryStore.get(E),R=c1(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=on.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(d1,"loadCertificates");function t1(e,t,r){let n,s=a((i,o)=>{try{let c=o.mtimeMs;c&&c!==n&&(n&&l1&&Xe.warn?.(`Reloading ${r}:`,i),n=c,t(h1(i)))}catch(c){Xe.error?.(`Error loading ${r}:`,i,c)}},"loadFile");Wn.existsSync(e)?s(e,c1(e)):Xe.error?.(`${r} file not found:`,e),Gue(e,{persistent:!1}).on("change",s)}a(t1,"loadAndWatch");function eO(){let e=zue();if(e==null){let t=Sh[0];return Xe.info?.("replication url is missing from harperdb-config.yaml, using default host"+t),t}return a1(e)}a(eO,"getHost");function hT(){let e=ET();if(e==null){let t=Sh[0];return Xe.info?.("replication url is missing from harperdb-config.yaml, using default host"+t),t}return e}a(hT,"getCommonName");async function tde(){let e=await Th(),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:hT()},...sO];Xe.info?.("Creating CSR with subject",s),n.setSubject(s);let i=[{name:"unstructuredName",value:"HarperDB, Inc."},{name:"extensionRequest",extensions:f1()}];return Xe.info?.("Creating CSR with attributes",i),n.setAttributes(i),n.sign(r),ef.pki.certificationRequestToPem(n)}a(tde,"createCsr");function f1(){let e=Sh.includes(hT())?Sh:[...Sh,hT()];return e.includes(eO())||e.push(eO()),[{name:"basicConstraints",cA:!1,critical:!0},{name:"keyUsage",digitalSignature:!0,keyEncipherment:!0,critical:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"nsCertType",client:!0,server:!0},{name:"subjectAltName",altNames:e.map(t=>n1.isIP(t)?{type:7,ip:t}:{type:2,value:t})}]}a(f1,"certExtensions");async function rde(e){let t={},r=_r.join(Ts.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME);if(e.csr){let n,s;yc();for await(let d of on.search([]))if(d.is_authority&&!d.details.issuer.includes("HarperDB-Certificate-Authority")){if(Tc.has(d.private_key_name)){n=Tc.get(d.private_key_name),s=d;break}else if(d.private_key_name&&await Wn.exists(_r.join(r,d.private_key_name))){n=Wn.readFile(_r.join(r,d.private_key_name)),s=d;break}}if(!n){let d=await tO();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=ef.pki.createCertificate();c.serialNumber=_T(),c.validity.notBefore=new Date;let l=new Date;c.validity.notAfter=l,c.validity.notAfter.setDate(l.getDate()+nO),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,ef.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(rde,"signCertificate");async function nde(e,t){await tf({name:ET(),uses:["https","wss"],certificate:e,private_key_name:"privateKey.pem",is_authority:!1,is_self_signed:!0}),await tf({name:t.subject.getField("CN").value,uses:["https","wss"],certificate:Mt.certificateToPem(t),private_key_name:"privateKey.pem",is_authority:!0,is_self_signed:!0})}a(nde,"createCertificateTable");async function tf(e){let t;try{t=new ia(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},yc(),await on.patch(e)}a(tf,"setCertTable");async function iO(){let e=await XC("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(iO,"generateKeys");async function oO(e,t,r){let n=Mt.createCertificate();if(!t){let o=await Th();t=Mt.certificateFromPem(o.options.cert).publicKey}n.publicKey=t,n.serialNumber=_T(),n.validity.notBefore=new Date;let s=new Date;n.validity.notAfter=s,n.validity.notAfter.setDate(s.getDate()+nO);let i=[{name:"commonName",value:hT()},...sO];return n.setSubject(i),n.setIssuer(r.subject.attributes),n.setExtensions(f1()),n.sign(e,ef.md.sha256.create()),Mt.certificateToPem(n)}a(oO,"generateCertificates");async function tO(){let e=await g1(),t;for(let r of e){if(!r.is_authority)continue;let n=await _1(r.private_key_name);if(r.private_key_name&&n&&new ia(r.certificate).checkPrivateKey(s1(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(tO,"getCertAuthority");async function m1(e,t,r=!0){let n=Mt.createCertificate();n.publicKey=t,n.serialNumber=_T(),n.validity.notBefore=new Date;let s=new Date;n.validity.notAfter=s,n.validity.notAfter.setDate(s.getDate()+nO);let i=[{name:"commonName",value:`HarperDB-Certificate-Authority-${Ts.get(Yl.REPLICATION_HOSTNAME)??a1(Ts.get(Yl.REPLICATION_URL))??i1().split("-")[0]}`},...sO];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,ef.md.sha256.create());let o=_r.join(Ts.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME),c=_r.join(o,yi.PRIVATEKEY_PEM_NAME);return r&&await Wn.writeFile(c,Mt.privateKeyToPem(e)),n}a(m1,"generateCertAuthority");async function sde(){let{privateKey:e,publicKey:t}=await iO(),r=await m1(e,t),n=await oO(e,t,r);await nde(n,r),p1()}a(sde,"generateCertsKeys");async function ide(){let e=await oO(Mt.privateKeyFromPem(yi.CERTIFICATE_VALUES.key),void 0,Mt.certificateFromPem(yi.CERTIFICATE_VALUES.cert)),t=_r.join(Ts.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME),r=_r.join(t,yi.NATS_CERTIFICATE_PEM_NAME);await Wn.exists(r)||await Wn.writeFile(r,e);let n=_r.join(t,yi.NATS_CA_PEM_NAME);await Wn.exists(n)||await Wn.writeFile(n,yi.CERTIFICATE_VALUES.cert)}a(ide,"createNatsCerts");async function ode(){yc();for await(let e of on.search([{attribute:"is_self_signed",value:!0}]))await on.delete(e.name);await aO()}a(ode,"renewSelfSigned");async function aO(){Jue(),await d1(),yc();let e=await tO();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(Yl.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(Yl.TLS_PRIVATEKEY),d=r(u);s=d.key,i=d.keyPath}let o=_r.join(Ts.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME),c=o1(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 iO(),Wn.existsSync(_r.join(o,yi.PRIVATEKEY_PEM_NAME))&&(c=`privateKey${i1().split("-")[0]}.pem`),await Wn.writeFile(_r.join(o,c),Mt.privateKeyToPem(s)));let l=await m1(s,Mt.setRsaPublicKey(s.n,s.e),!1);await tf({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 Th()){let r=ET();Xe.notify?.(`A suitable replication certificate was not found, creating new self singed cert named: ${r}`),e=e??await tO();let n=Mt.certificateFromPem(e.ca.certificate),s=n.publicKey,i=await oO(Mt.privateKeyFromPem(e.private_key),s,n);await tf({name:r,uses:["https","operations","wss"],certificate:i,is_authority:!1,private_key_name:e.ca.private_key_name,is_self_signed:!0})}}a(aO,"reviewSelfSignedCert");function p1(){let e=Yue(Object.keys(Vs.CONFIG_PARAM_MAP),!0),t=_r.join(Ts.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME),r=_r.join(t,yi.PRIVATEKEY_PEM_NAME),n=_r.join(t,yi.NATS_CERTIFICATE_PEM_NAME),s=_r.join(t,yi.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),ZC.updateConfigValue(void 0,void 0,o,!1,!0)}a(p1,"updateConfigCert");function h1(e){return e.startsWith("-----BEGIN")?e:Que(e,"utf8")}a(h1,"readPEM");var r1=pT.createSecureContext;pT.createSecureContext=function(e){if(!e.cert||!e.key)return r1(e);let t={...e};delete t.key,delete t.cert;let r=r1(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};var ade=u1.prototype._init;u1.prototype._init=function(e,t){ade.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 Kl=new Map;function E1(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(),Kl.clear();let d=0;if(mT===void 0){c();return}for await(let f of mT.system.hdb_certificate.search([])){let m=f.certificate,p=new ia(m);f.is_authority&&(p.asString=m,Kl.set(p.subject,m))}for await(let f of mT.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 _1(f.private_key_name),E=f.certificate,_=new ia(E);if(Kl.has(_.issuer)&&(E+=`
16
- `+Kl.get(_.issuer)),!h||!E)throw new Error("Missing private key or certificate for secure server");let R={ciphers:f.ciphers,ticketKeys:Xue(),availableCAs:Kl,ca:t&&Array.from(Kl.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??lO(_);Array.isArray(S)||(S=[S]);for(let I of S)I===eO()&&(p+=1);let y=pT.createSecureContext(R);y.name=f.name,y.options=R,y.quality=p,y.certificateAuthorities=Array.from(Kl),y.certStart=E.toString().slice(0,100);let w;for(let I of S)if(I){I[0]==="*"&&(s=!0,I=I.slice(1)),n1.isIP(I)&&(w=!0);let H=r.get(I)?.quality??0;Xe.trace?.("Assigning TLS for hostname",I,"if",p,">",H),p>H&&r.set(I,y)}else Xe.error?.("No hostname found for certificate at",pT.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"),mT?.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(E1,"createTLSSelector");async function _1(e){let t=Tc.get(e);return!t&&e?await Wn.readFile(_r.join(Ts.get(Yl.ROOTPATH),Vs.LICENSE_KEY_DIR_NAME,e),"utf8"):t}a(_1,"getPrivateKeyByName");async function g1(){yc();let e=[];for await(let t of on.search([]))e.push(t);return e}a(g1,"listCertificates");async function cde(e){let t=rO(e,Ti.object({name:Ti.string().required(),certificate:Ti.string().required(),is_authority:Ti.boolean().required(),private_key:Ti.string(),hosts:Ti.array(),uses:Ti.array()}));if(t)throw new Sc(t.message);let{name:r,certificate:n,private_key:s,is_authority:i}=e,o=new ia(n),c=!1,l=!1,u;for(let[p,h]of Tc)!s&&!c&&o.checkPrivateKey(s1(h))&&(c=!0,u=p),s&&s===h&&(l=!0,u=p);if(!i&&!s&&!c)throw new Sc("A suitable private key was not found for this certificate");let d;if(!r){try{d=cO(o)}catch(p){Xe.error?.(p)}if(d==null)throw new Sc("Error extracting certificate host name, please provide a name parameter")}let f=lde(r??d);s&&!c&&!l&&(await Wn.writeFile(_r.join(Ts.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,f+".pem"),s),Tc.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 tf(m),"Successfully added certificate: "+f}a(cde,"addCertificate");function lde(e){return e.replace(/[^a-z0-9\.]/gi,"-")}a(lde,"sanitizeName");async function ude(e){let t=rO(e,Ti.object({name:Ti.string().required()}));if(t)throw new Sc(t.message);let{name:r}=e;yc();let n=await on.get(r);if(!n)throw new Sc(r+" not found");let{private_key_name:s}=n;if(s){let i=Array.from(await on.search([{attribute:"private_key_name",value:s}]));i.length===1&&i[0].name===r&&(Xe.info?.("Removing private key named",s),await Wn.remove(_r.join(Ts.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,s)))}return await on.delete(r),"Successfully removed "+r}a(ude,"removeCertificate");function cO(e){let t=e.subject?.match(/CN=(.*)/)?.[1];return t||lO(e)[0]}a(cO,"getPrimaryHostName");function lO(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(lO,"hostnamesFromCert");async function dde(e){if(e.bypass_auth!==!0)throw new Sc("Unauthorized","401");let t=rO(e,Ti.object({name:Ti.string().required()}));if(t)throw new Sc(t.message);let{name:r}=e;if(r===".jwtPrivate")return(await ZV()).privateKey;if(r===".jwtPublic")return(await ZV()).publicKey;if(Tc.get(r))return Tc.get(e.name);throw new Sc("Key not found")}a(dde,"getKey");function fde(e){return[e.subject?.CN,...e.subjectaltname.split(",").filter(t=>t.trim().startsWith("DNS:")).map(t=>t.trim().substring(4))]}a(fde,"getHostnamesFromCertificate")});var G1={};ye(G1,{BACK_PRESSURE_RATIO_POSITION:()=>k1,CONFIRMATION_STATUS_POSITION:()=>F1,LATENCY_POSITION:()=>IT,NodeReplicationConnection:()=>nf,OPERATION_REQUEST:()=>pO,RECEIVED_TIME_POSITION:()=>bT,RECEIVED_VERSION_POSITION:()=>RT,RECEIVING_STATUS_POSITION:()=>AT,RECEIVING_STATUS_RECEIVING:()=>H1,RECEIVING_STATUS_WAITING:()=>hO,SENDING_TIME_POSITION:()=>Rh,createWebSocket:()=>wT,databaseSubscriptions:()=>bc,replicateOverWS:()=>bh,tableUpdateListeners:()=>gO});async function wT(e,t){let{authorization:r,rejectUnauthorized:n}=t||{},s=tt(),i;if(e==null)throw new TypeError(`Invalid URL: Expected a string URL for node "${s}" but received ${e}`);if(e.includes("wss://")){if(!fO){let l=(0,M1.createTLSSelector)("operations-api"),u={secureContexts:null};await l.initialize(u),fO=u.secureContexts}if(i=fO.get(s),i&&le.debug?.("Creating web socket for URL",e,"with certificate named:",i.name),!i&&n!==!1)throw new Error("Unable to find a valid certificate to use for replication to connect to "+e)}let o={};r&&(o.Authorization=r);let c={headers:o,localAddress:s?.startsWith("127.0")?s:void 0,servername:(0,x1.isIP)(t?.serverName)?void 0:t?.serverName,noDelay:!0,highWaterMark:128*1024,rejectUnauthorized:n!==!1,secureContext:void 0};return i&&((rf?.caCount!==aa.size||rf?.derivedFromContext!==i)&&(rf=U1.createSecureContext({...i.options,ca:[...aa,...i.options.availableCAs.values()]}),rf.caCount=aa.size,rf.derivedFromContext=i),c.secureContext=rf),new L1.WebSocket(e,"harperdb-replication-v1",c)}function bh(e,t,r){let n=t.port||t.securePort,s=_O.pid%1e3+"-"+D1.threadId+(n?"s:"+n:"c:"+t.url?.slice(-4))+" "+Math.random().toString().slice(2,3);le.debug?.(s,"Initializing replication connection",r);let i=0,o=Buffer.allocUnsafeSlow(1024),c=0,l=new DataView(o.buffer,0,1024),u=t.database,d=t.databaseSubscriptions||bc,f,m,p=!1,h=t.subscription;h?.then&&h.then(A=>{h=A,h.auditStore&&(f=h.auditStore)});let E=t.tables||u&&lt()[u],_,R=new Map,S=[];_=r.name,_&&t.connection&&(t.connection.nodeName=_);let y,w,I,H,X,q,k,z=6e4,Y,ce=0,de=0,te=0,Se=P1.default.get(x.REPLICATION_BLOBTIMEOUT)??12e4,Ne=new Map,Ke=[],$e=0,Ir;if(t.url){let A=a(()=>{X&&de===e._socket?.bytesRead&&te===e._socket?.bytesWritten?e.terminate():(X=performance.now(),e.ping(),de=e._socket?.bytesRead,te=e._socket?.bytesWritten)},"sendPing");I=setInterval(A,C1).unref(),A()}else nr();e._socket?.setMaxListeners(200);function nr(){clearTimeout(H),de=e._socket?.bytesRead,te=e._socket?.bytesWritten,H=setTimeout(()=>{de===e._socket?.bytesRead&&te===e._socket?.bytesWritten&&(le.warn?.(`Timeout waiting for ping from ${_}, terminating connection and reconnecting`),e.terminate())},C1*2).unref()}a(nr,"resetPingTimer");let zr=0,xr=0,Ou=!1,zc=3e4;function Ft(){if(pn?.length>0){let A=performance.now(),U=A-xr;zr=(zr*zc+(Ou?U:0))/(zc+U),m&&(m[k1]=zr),xr=A}}a(Ft,"updateBackPressureRatio"),setInterval(Ft,zc).unref();function Ps(){if(!(!_||!u))return m||(m=zd(f,u,_)),m}a(Ps,"getSharedStatus"),u&&Jc(u);let Ha,o_,cm=[],a_=[],lm,ve=[],c_=[],Wb=[],Pu=150,ki=25,Ls=0,um=0,dm=!1,xo,Dn,pn,Br;e.on("message",Lu);async function Lu(A){if(r=await r,!r){le.error?.(s,"No authorization provided"),Fr(1008,"Unauthorized");return}fm(A),e.off("message",Lu),e.on("message",fm)}a(Lu,"onWSMessageWhenAuthorized");function fm(A){ce=performance.now();try{let U=A.dataView=new al(A.buffer,A.byteOffset,A.byteLength);if(A[0]>127){let W=(0,at.decode)(A),[J,F,he]=W;switch(J){case T1:{if(F){if(_){if(_!==F){le.error?.(s,`Node name mismatch, expecting to connect to ${_}, but peer reported name as ${F}, disconnecting`),e.send((0,at.encode)([yh])),Fr(1008,"Node name mismatch");return}}else if(_=F,t.connection?.tentativeNode){let me=t.connection.tentativeNode;me.name=_,t.connection.tentativeNode=null,sa(_,me)}if(t.connection&&(t.connection.nodeName=_),le.debug?.(s,"received node name:",_,"db:",u??W[2]),!u)try{Jc(u=W[2]),u==="system"&&(Ha=_c(t,(me,ie)=>{$a(ie)&&K(ie)}),e.on("close",()=>{Ha?.remove()}))}catch(me){le.warn?.(s,"Error setting database",me),e.send((0,at.encode)([yh])),Fr(1008,me.message);return}mm()}break}case w1:{le.debug?.(s,"Received table definitions for",F.map(me=>me.table));for(let me of F){let ie=W[2];me.database=ie;let Ce;if($a(ie)){if(u==="system")Me[ie]?.[me.table]||(Ce=D(me,Me[ie]?.[me.table]));else{if(ie!=="data"&&!Me[ie]){le.warn?.("Database not found",ie);return}Ce=D(me,Me[ie]?.[me.table])}f||(f=Ce?.auditStore),E||(E=lt()?.[ie])}}break}case yh:Fr();break;case pO:try{let me=r?.replicates||r?.subscribers||r?.name;le.debug?.("Received operation request",F,"from",_),server.operation(F,{user:r},!me).then(ie=>{le.debug?.("Requested request from finished",_,ie),Array.isArray(ie)&&(ie={results:ie}),ie.requestId=F.requestId,e.send((0,at.encode)([ST,ie]))},ie=>{le.debug?.("Failed requested operation from",_,ie),e.send((0,at.encode)([ST,{requestId:F.requestId,error:uO(ie)}]))})}catch(me){e.send((0,at.encode)([ST,{requestId:F.requestId,error:uO(me)}]))}break;case ST:let{resolve:ue,reject:_e}=R.get(F.requestId);le.debug?.("Received completed operation request",_,F),F.error?_e(new Error(F.error)):ue(F),R.delete(F.requestId);break;case dO:let re=W[3];if(!E){u?le.error?.(s,"No database found for",u):le.error?.(s,"Database name never received"),Fr();return}let oe=E[re];oe=D({table:re,database:u,attributes:F.attributes,schemaDefined:F.schemaDefined},oe),cm[he]={name:re,decoder:new at.Packr({useBigIntExtension:!0,randomAccessStructure:!0,freezeData:!0,typedStructs:F.typedStructs,structures:F.structures}),getEntry(me){return oe.primaryStore.getEntry(me)},rootStore:oe.primaryStore.rootStore};break;case y1:Br=f?FV(F,f):new Map,lm=W[2],le.debug?.(s,`Acknowledged subscription request, receiving messages for nodes: ${lm}`);break;case R1:let ge=he;Wb[ge]=F;break;case I1:Ps()[F1]=F,le.trace?.(s,"received and broadcasting committed update",F),Ps().buffer.notify();break;case A1:y=F,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),Ps(),replication_shared_status[RT]=last_sequence_id_received,replication_shared_status[bT]=Date.now(),replication_shared_status[AT]=hO;break;case TT:{let me=W[1],{fileId:ie,size:Ce,finished:Be,error:He}=me,Te=Ne.get(ie);le.debug?.("Received blob",ie,"has stream",!!Te,"connectedToBlob",!!Te?.connectedToBlob,"length",W[2].length,"finished",Be),Te||(Te=new mO.PassThrough,Te.expectedSize=Ce,Ne.set(ie,Te)),Te.lastChunk=Date.now();let ht=W[2];Ye(ht.byteLength,"bytes-received",`${_}.${u}`,"replication","blob");try{Be?(He?(Te.on("error",()=>{}),Te.destroy(new Error("Blob error: "+He+" for record "+(Te.recordId??"unknown")+" from "+_))):Te.end(ht),Te.connectedToBlob&&Ne.delete(ie)):Te.write(ht)}catch(Ct){le.error?.(`Error receiving blob for ${Te.recordId} from ${_} and streaming to storage`,Ct),Ne.delete(ie)}break}case b1:{let me=F,ie;try{let Ce=W[3],Be=a_[he]||(a_[he]=E[W[4]]);if(!Be)return le.warn?.("Unknown table id trying to handle record request",he);let He=Be.primaryStore.getBinaryFast(Symbol.for("structures")),Te=He?.length??0;if(Te>0&&Te!==um){um=Te;let Ct=(0,at.decode)(He);e.send((0,at.encode)([dO,{typedStructs:Ct.typed,structures:Ct.named},he,Be.tableName]))}let ht=Be.primaryStore.getBinaryFast(Ce);if(ht){let Ct=Be.primaryStore.decoder.decode(ht,{valueAsBuffer:!0}),Ot=ut||{};Ot.version=(0,B1.getLastVersion)(),ut&&ut[Wu]&Xr&&(Ct=Buffer.from(Ct),Hm(()=>Be.primaryStore.decoder.decode(ht),u_=>Ga(u_,Ce),Be.primaryStore.rootStore)),ie=(0,at.encode)([gT,me,{value:Ct,expiresAt:Ot.expiresAt,version:Ot.version,residencyId:Ot.residencyId,nodeId:Ot.nodeId,user:Ot.user}])}else ie=(0,at.encode)([gT,me])}catch(Ce){ie=(0,at.encode)([gT,me,{error:Ce.message}])}e.send(ie);break}case gT:{let{resolve:me,reject:ie,tableId:Ce,key:Be}=R.get(W[1]),He=W[2];if(He?.error)ie(new Error(He.error));else if(He){let Te;z_(()=>{let ht=cm[Ce].decoder.decode(He.value);He.value=ht,He.key=Be,me(He)||Te&&setTimeout(()=>Te.forEach(Y_),6e4).unref()},f?.rootStore,ht=>{let Ct=qa(ht,Be);return Te||(Te=[]),Te.push(Ct),Ct})}else me();R.delete(W[1]);break}case S1:{pn=F;let me,ie,Ce=!1;if(h){if(u!==h.databaseName&&!h.then){le.error?.("Subscription request for wrong database",u,h.databaseName);return}}else h=d.get(u);if(le.debug?.(s,"received subscription request for",u,"at",pn),!h){let De;h=new Promise(ft=>{le.debug?.("Waiting for subscription to database "+u),De=ft}),h.ready=De,bc.set(u,h)}if(r.name)ie=Gt().subscribe(r.name),ie.then(async De=>{me=De;for await(let ft of me){let kr=ft.value;if(!(kr?.replicates===!0||kr?.replicates?.receives||kr?.subscriptions?.some(fr=>(fr.database||fr.schema)===u&&fr.publish!==!1))){Ce=!0,Fr(1008,`Unauthorized database subscription to ${u}`);return}}},De=>{le.error?.(s,"Error subscribing to HDB nodes",De)});else if(!(r?.role?.permission?.super_user||r.replicates)){e.send((0,at.encode)([yh])),Fr(1008,`Unauthorized database subscription to ${u}`);return}if(Dn&&(le.debug?.(s,"stopping previous subscription",u),Dn.emit("close")),pn.length===0)return;let Be=pn[0],He=a(De=>{if(De&&(Be.replicateByDefault?!Be.tables.includes(De.tableName):Be.tables.includes(De.tableName)))return{table:De}},"tableToTableEntry"),Te={txnTime:0},ht,Ct,Ot=1/0,u_,d_=a((De,ft)=>{if(De.type==="end_txn"){Te.txnTime&&(o[i]!==66&&le.error?.("Invalid encoding of message"),C(9),C(og),O(u_=ft),nU()),i=c,Te.txnTime=0;return}let kr=De.nodeId,fr=De.tableId,zt=Ct[fr];if(!zt&&(zt=Ct[fr]=He(h.tableById[fr]),!zt))return le.debug?.("Not subscribed to table",fr);let yt=zt.table,Mu=yt.primaryStore,si=Mu.encoder;(De.extendedType&Eg||!si.typedStructs)&&(si._mergeStructures(si.getStructures()),si.typedStructs&&(si.lastTypedStructuresLength=si.typedStructs.length));let f_=ht[kr];if(!(f_&&f_.startTime<ft&&(!f_.endTime||f_.endTime>ft)))return yT&&le.trace?.(s,"skipping replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",ht),sU();yT&&le.trace?.(s,"sending replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",ht);let jb=De.version,Qc=De.residencyId,zb=l_(Qc,yt),m_;if(zb&&!zb.includes(_)){let Hi=l_(De.previousResidencyId,yt);if(Hi&&!Hi.includes(_)&&(De.type==="put"||De.type==="patch")||yt.getResidencyById)return sU();let Xc=De.recordId;le.trace?.(s,"sending invalidation",Xc,_,"from",kr);let pm=0;Qc&&(pm|=cl),De.previousResidencyId&&(pm|=ll);let Xb,p_=null;for(let iU in yt.indices){if(!p_){if(Xb=De.getValue(Mu,!0),!Xb)break;p_={}}p_[iU]=Xb[iU]}m_=ul(De.version,fr,Xc,null,kr,De.user,De.type==="put"||De.type==="patch"?"invalidate":De.type,si.encode(p_),pm,Qc,De.previousResidencyId,De.expiresAt)}function sU(){return le.trace?.(s,"skipping audit record",De.recordId),q||(q=setTimeout(()=>{q=null,(u_||0)+N1/2<Ot&&(yT&&le.trace?.(s,"sending skipped sequence update",Ot),e.send((0,at.encode)([A1,Ot])))},N1).unref()),new Promise(setImmediate)}a(sU,"skipAuditRecord");let Jb=si.typedStructs,Qb=si.structures;if((Jb?.length!=zt.typed_length||Qb?.length!=zt.structure_length)&&(zt.typed_length=Jb?.length,zt.structure_length=Qb.length,le.debug?.(s,"send table struct",zt.typed_length,zt.structure_length),zt.sentName||(zt.sentName=!0),e.send((0,at.encode)([dO,{typedStructs:Jb,structures:Qb,attributes:yt.attributes,schemaDefined:yt.schemaDefined},fr,zt.table.tableName]))),Qc&&!c_[Qc]&&(e.send((0,at.encode)([R1,zb,Qc])),c_[Qc]=!0),Te.txnTime!==jb&&(Te.txnTime&&(yT&&le.trace?.(s,"new txn time, sending queued txn",Te.txnTime),o[i]!==66&&le.error?.("Invalid encoding of message"),nU()),Te.txnTime=jb,i=c,O(jb)),m_)C(m_.length),P(m_);else{let Hi=De.encoded;De.extendedType&Xr&&Hm(()=>De.getValue(Mu),pm=>Ga(pm,De.recordId),Mu.rootStore);let Xc=Hi[0]===66?8:0;C(Hi.length-Xc),P(Hi,Xc),le.trace?.("wrote record",De.recordId,"length:",Hi.length)}if(e._socket.writableNeedDrain){let Hi=performance.now();return Ou=!0,Ft(),new Promise(Xc=>{le.debug?.(`Waiting for remote node ${_} to allow more commits ${e._socket.writableNeedDrain?"due to network backlog":"due to requested flow directive"}`),e._socket.once("drain",()=>{Xc(),Ou=!1,Ft()})})}else return $e>ki?new Promise(Hi=>{Ir=Hi}):new Promise(setImmediate)},"sendAuditRecord"),nU=a(()=>{c-i>8?(e.send(o.subarray(i,c)),le.debug?.(s,"Sent message, size:",c-i),u!=="system"&&Ye(c-i,"bytes-sent",`${_}.${u}`,"replication","egress")):le.debug?.(s,"skipping empty transaction")},"sendQueuedData");Dn=new EO.EventEmitter,Dn.once("close",()=>{Ce=!0,me?.end()});for(let{startTime:De}of pn)De<Ot&&(Ot=De);(ie||Promise.resolve()).then(async()=>{h=await h,f=h.auditStore,Ct=h.tableById.map(He),ht=[];for(let{name:ft,startTime:kr,endTime:fr}of pn){let zt=lT(ft,f);le.debug?.("subscription to",ft,"using local id",zt,"starting",kr),ht[zt]={startTime:kr,endTime:fr}}K(u),Ha||(Ha=Gl(ft=>{ft.databaseName===u&&K(u)}),o_=th(ft=>{ft===u&&(e.send((0,at.encode)([yh])),Fr())}),e.on("close",()=>{Ha?.remove(),o_?.remove()})),e.send((0,at.encode)([y1,fh(h.auditStore),pn.map(({name:ft})=>ft)]));let De=!0;do{if(isFinite(Ot)||(le.warn?.("Invalid sequence id "+Ot),Fr(1008,"Invalid sequence id"+Ot)),De&&!Ce&&(De=!1,Ot===0)){le.info?.("Replicating all tables to",_);let ft=Date.now(),kr=NT(f);for(let fr in E){if(!He(fr))continue;let zt=E[fr];for(let yt of zt.primaryStore.getRange({snapshot:!1,versions:!0})){if(Ce)return;le.trace?.(s,"Copying record from",u,fr,yt.key,yt.localTime),ft=Math.max(yt.localTime??1,ft),Ps()[Rh]=1;let Mu=ul(yt.version,zt.tableId,yt.key,null,kr,null,"put",Hm(()=>zt.primaryStore.encoder.encode(yt.value),si=>Ga(si,yt.key)),yt.metadataFlags&-256,yt.residencyId,null,yt.expiresAt);await d_({recordId:yt.key,tableId:zt.tableId,type:"put",getValue(){return yt.value},encoded:Mu,version:yt.version,residencyId:yt.residencyId,nodeId:kr,extendedType:yt.metadataFlags},yt.localTime)}}Te.txnTime||(Te.txnTime=ft,O(ft)),c-i>8&&d_({type:"end_txn"},Ot),Ps()[Rh]=0,Ot=ft}for(let{key:ft,value:kr}of f.getRange({start:Ot||1,exclusiveStart:!0,snapshot:!1})){if(Ce)return;let fr=It(kr);le.debug?.("sending audit record",ft,fr.recordId),Ps()[Rh]=ft,Ot=ft,await d_(fr,ft),Dn.startTime=ft}c-i>8&&d_({type:"end_txn"},Ot),Ps()[Rh]=0,await mB(f)}while(!Ce)}).catch(De=>{le.error?.(s,"Error handling subscription to node",De),Fr(1008,"Error handling subscription to node")});break}}return}U.position=8;let N=!0,L,$;do{Ps();let W=U.readInt();if(W===9&&U.getUint8(U.position)==og){U.position++,y=$=U.readFloat64(),m[RT]=y,m[bT]=Date.now(),m[AT]=hO,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),le.trace?.("received remote sequence update",y,u);break}let J=U.position,F=It(A,J,J+W),he=cm[F.tableId];he||le.error?.(`No table found with an id of ${F.tableId}`);let ue;F.residencyId&&(ue=Wb[F.residencyId],le.trace?.(s,"received residency list",ue,F.type,F.recordId));let _e=F.recordId;try{z_(()=>{L={table:he.name,id:F.recordId,type:F.type,nodeId:Br.get(F.nodeId),residencyList:ue,timestamp:F.version,value:F.getValue(he),user:F.user,beginTxn:N,expiresAt:F.expiresAt}},f?.rootStore,re=>qa(re,_e))}catch(re){throw re.message+=" record id: "+_e,re.message+=" typed structures for current decoder"+JSON.stringify(he.decoder.typedStructs),re.message+=" structures for current decoder"+JSON.stringify(he.decoder.structures),re}N=!1,le.debug?.(s,"received replication message",F.type,"id",L.id,"version",new Date(F.version),"nodeId",L.nodeId),m[RT]=F.version,m[bT]=Date.now(),m[AT]=H1,h.send(L),U.position=J+W}while(U.position<A.byteLength);Ls++,u!=="system"&&Ye(A.byteLength,"bytes-received",`${_}.${u}.${L?.table||"unknown_table"}`,"replication","ingest"),Ls>Pu&&!dm&&(dm=!0,e.pause(),le.debug?.(`Commit backlog causing replication back-pressure, requesting that ${_} pause replication`)),h.send({type:"end_txn",localTime:y,remoteNodeIds:S,async onCommit(){if(L){let W=Date.now()-L.timestamp;u!=="system"&&Ye(W,"replication-latency",_+"."+u+"."+L.table,L.type,"ingest")}Ls--,dm&&(dm=!1,e.resume(),le.debug?.(`Replication resuming ${_}`)),Ke.length>0&&await Promise.all(Ke),le.trace?.("All blobs finished"),!w&&$&&(le.trace?.(s,"queuing confirmation of a commit at",$),setTimeout(()=>{e.send((0,at.encode)([I1,w])),le.trace?.(s,"sent confirmation of a commit at",w),w=null},pde)),w=$,le.debug?.("last sequence committed",new Date($),u)}})}catch(U){le.error?.(s,"Error handling incoming replication message",U)}}a(fm,"onWSMessage"),e.on("ping",nr),e.on("pong",()=>{if(t.connection){let A=performance.now()-X;t.connection.latency=A,Ps()&&(m[IT]=A),t.isSubscriptionConnection&&Vl({name:_,database:u,url:t.url,latency:A})}X=null}),e.on("close",(A,U)=>{clearInterval(I),clearTimeout(H),clearInterval(k),Dn&&Dn.emit("close"),xo&&xo.end();for(let[N,{reject:L}]of R)L(new Error(`Connection closed ${U?.toString()} ${A}`));le.debug?.(s,"closed",A,U?.toString())});function Fr(A,U){try{e.isFinished=!0,le.debug?.(s,"closing",_,u,A,U),e.close(A,U),t.connection?.emit("finished")}catch(N){le.error?.(s,"Error closing connection",N)}}a(Fr,"close");let Du=new Set;async function Ga(A,U){let N=W_(A);if(Du.has(N)){le.debug?.("Blob already being sent",N);return}Du.add(N);try{let L;$e++;for await(let $ of A.stream())L&&(le.debug?.("Sending blob chunk",N,"length",L.length),e.send((0,at.encode)([TT,{fileId:N,size:A.size},L]))),L=$,e._socket.writableNeedDrain&&(le.debug?.("draining",N),await new Promise(W=>e._socket.once("drain",W)),le.debug?.("drained",N)),Ye($.length,"bytes-sent",`${_}.${u}`,"replication","blob");le.debug?.("Sending final blob chunk",N,"length",L.length),e.send((0,at.encode)([TT,{fileId:N,size:A.size,finished:!0},L]))}catch(L){le.warn?.("Error sending blob",L,"blob id",N,"for record",U),e.send((0,at.encode)([TT,{fileId:N,finished:!0,error:uO(L)},Buffer.alloc(0)]))}finally{Du.delete(N),$e--,$e<ki&&Ir?.()}}a(Ga,"sendBlobs");function qa(A,U){let N=W_(A),L=Ne.get(N);le.debug?.("Received transaction with blob",N,"has stream",!!L,"ended",!!L?.writableEnded),L?L.writableEnded&&Ne.delete(N):(L=new mO.PassThrough,Ne.set(N,L)),L.connectedToBlob=!0,L.lastChunk=Date.now(),L.recordId=U,A.size===void 0&&L.expectedSize&&(A.size=L.expectedSize);let $=L.blob??createBlob(L,A);L.blob=$;let W=Ko(()=>km($).saving,h.auditStore?.rootStore);return W&&(W.blobId=N,Ke.push(W),W.finally(()=>{le.debug?.(`Finished receiving blob stream ${N}`),Ke.splice(Ke.indexOf(W),1)})),$}a(qa,"receiveBlobs");function mm(){if(p||(p=!0,t.connection?.on("subscriptions-updated",mm)),!f&&h&&(f=h.auditStore),t.connection?.isFinished)throw new Error("Can not make a subscription request on a connection that is already closed");let A=new Map;f||(f=h?.auditStore);try{for(let L of h?.dbisDB?.getRange({start:Symbol.for("seq"),end:[Symbol.for("seq"),Buffer.from([255])]})||[])for(let $ of L.value.nodes||[])$.lastTxnTime>(A.get($.id)??0)&&A.set($.id,$.lastTxnTime)}catch(L){if(!L.message.includes("Can not re"))throw L}let U=t.connection?.nodeSubscriptions?.[0];S=[];let N=t.connection?.nodeSubscriptions.map((L,$)=>{let W=[],{replicateByDefault:J}=L;if(L.subscriptions){for(let _e of L.subscriptions)if(_e.subscribe&&(_e.schema||_e.database)===u){let re=_e.table;E?.[re]?.replicate!==!1&&W.push(re)}J=!1}else for(let _e in E)(J?E[_e].replicate===!1:E[_e].replicate)&&W.push(_e);let F=f&&lT(L.name,f),he=h?.dbisDB?.get([Symbol.for("seq"),F])??1,ue=Math.max(he?.seqId??1,(typeof L.startTime=="string"?new Date(L.startTime).getTime():L.startTime)??1);if(le.debug?.("Starting time recorded in db",L.name,F,u,he?.seqId,"start time:",ue,new Date(ue)),U!==L){let _e=f&&lT(U.name,f),re=h?.dbisDB?.get([Symbol.for("seq"),_e])??1;for(let oe of re?.nodes||[])oe.name===L.name&&(ue=oe.seqId,le.debug?.("Using sequence id from proxy node",U.name,ue))}return F===void 0?le.warn("Starting subscription request from node",L,"but no node id found"):S.push(F),A.get(F)>ue&&(ue=A.get(F),le.debug?.("Updating start time from more recent txn recorded",U.name,ue)),ue===1&&(L.isLeader?(le.warn?.(`Requesting full copy of database ${u} from ${L.url}`),ue=0):ue=Date.now()-6e4),le.trace?.(s,"defining subscription request",L.name,u,new Date(ue)),{name:L.name,replicateByDefault:J,tables:W,startTime:ue,isLeader:L.isLeader,endTime:L.endTime}});if(N)if(le.debug?.(s,"sending subscription request",N,h?.dbisDB?.path),clearTimeout(Y),N.length>0)e.send((0,at.encode)([S1,N]));else{let L=a(()=>{let $=performance.now();Y=setTimeout(()=>{ce<=$?Fr(1008,"Connection has no subscriptions and is no longer used"):L()},z).unref()},"scheduleClose");L()}}a(mm,"sendSubscriptionRequestUpdate");function l_(A,U){if(!A)return;let N=ve[A];return N||(N=U.getResidencyRecord(A),ve[A]=N),N}a(l_,"getResidence");function $a(A){return!(Rc&&Rc!="*"&&!Rc[A]&&!Rc.includes?.(A)&&!Rc.some?.(U=>U.name===A))}a($a,"checkDatabaseAccess");function Jc(A){if(h=h||d.get(A),!$a(A))throw new Error(`Access to database "${A}" is not permitted`);h||le.warn?.(`No database named "${A}" was declared and registered`),f=h?.auditStore,E||(E=lt()?.[A]);let U=tt();if(U===_)throw U?new Error("Should not connect to self",U):new Error("Node name not defined");return vu(U,A),!0}a(Jc,"setDatabase");function vu(A,U){let N=lt()?.[U],L=[];for(let $ in N){let W=N[$];L.push({table:$,schemaDefined:W.schemaDefined,attributes:W.attributes.map(J=>({name:J.name,type:J.type,isPrimaryKey:J.isPrimaryKey}))})}le.trace?.("Sending database info for node",A,"database name",U),e.send((0,at.encode)([T1,A,U,L]))}a(vu,"sendNodeDBName");function K(A){let U=lt()?.[A],N=[];for(let L in U){if(pn&&!pn.some(W=>W.replicateByDefault?!W.tables.includes(L):W.tables.includes(L)))continue;let $=U[L];N.push({table:L,schemaDefined:$.schemaDefined,attributes:$.attributes.map(W=>({name:W.name,type:W.type,isPrimaryKey:W.isPrimaryKey}))})}e.send((0,at.encode)([w1,N,A]))}a(K,"sendDBSchema"),k=setInterval(()=>{for(let[A,U]of Ne)U.lastChunk+Se<Date.now()&&(le.warn?.(`Timeout waiting for blob stream to finish ${A} for record ${U.recordId??"unknown"} from ${_}`),Ne.delete(A),U.end())},Se).unref();let g=1,T=[];return{end(){xo&&xo.end(),Dn&&Dn.emit("close")},getRecord(A){let U=g++;return new Promise((N,L)=>{let $=[b1,U,A.table.tableId,A.id];T[A.table.tableId]||($.push(A.table.tableName),T[A.table.tableId]=!0),e.send((0,at.encode)($)),ce=performance.now(),R.set(U,{tableId:A.table.tableId,key:A.id,resolve(W){let{table:J,entry:F}=A;if(N(W),W)return J._recordRelocate(F,W)},reject:L})})},sendOperation(A){let U=g++;return A.requestId=U,e.send((0,at.encode)([pO,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 D(A,U){let N=A.database??"data";U||(U={});let L=U.schemaDefined,$=!1,W=A.schemaDefined,J=U.attributes||[];for(let F=0;F<A.attributes?.length;F++){let he=A.attributes[F],ue=J.find(_e=>_e.name===he.name);(!ue||ue.type!==he.type)&&(L?le.error?.(`Schema for '${u}.${A.table}' is defined locally, but attribute '${he.name}: ${he.type}' from '${_}' does not match local attribute ${ue?"'"+ue.name+": "+ue.type+"'":"which does not exist"}`):($=!0,W||(he.indexed=!0),ue?J[J.indexOf(ue)]=he:J.push(he)))}return $?(le.debug?.("(Re)creating",A),ze({table:A.table,database:A.database,schemaDefined:A.schemaDefined,attributes:J,...U})):U}}var P1,at,L1,D1,v1,EO,M1,U1,_O,x1,mO,B1,mde,uO,le,S1,T1,y1,yh,R1,dO,b1,gT,pO,ST,A1,I1,w1,TT,F1,RT,bT,Rh,IT,AT,k1,hO,H1,gO,bc,yT,N1,pde,C1,fO,rf,O1,nf,SO=se(()=>{Oe();qi();JC();CI();Ss();P1=b(fe());G();dl();at=require("msgpackr"),L1=require("ws"),D1=require("worker_threads"),v1=b(Q());gh();EO=require("events"),M1=b(ys()),U1=b(require("node:tls"));Qd();_O=b(require("node:process")),x1=require("node:net");is();ss();mO=require("node:stream"),B1=require("lmdb"),{forComponent:mde,errorToString:uO}=v1.default,le=mde("replication").conditional,S1=129,T1=140,y1=141,yh=142,R1=130,dO=132,b1=133,gT=134,pO=136,ST=137,A1=143,I1=144,w1=145,TT=146,F1=0,RT=1,bT=2,Rh=3,IT=4,AT=5,k1=6,hO=0,H1=1,gO=new Map,bc=new Map,yT=!0,N1=300,pde=2,C1=3e4;a(wT,"createWebSocket");O1=500,nf=class extends EO.EventEmitter{static{a(this,"NodeReplicationConnection")}socket;startTime;retryTime=O1;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??Si(t)}async connect(){this.session||this.resetSession();let t=[];this.socket=await wT(this.url,{serverName:this.nodeName,authorization:this.authorization});let r;le.debug?.(`Connecting to ${this.url}, db: ${this.databaseName}, process ${_O.pid}`),this.socket.on("open",()=>{this.socket._socket.unref(),le[this.isConnected?"info":"warn"]?.(`Connected to ${this.url}, db: ${this.databaseName}`),this.retries=0,this.retryTime=O1,this.nodeSubscriptions&&Vl({name:this.nodeName,database:this.databaseName,url:this.url}),this.isConnected=!0,r=bh(this.socket,{database:this.databaseName,subscription:this.subscription,url:this.url,connection:this,isSubscriptionConnection:this.nodeSubscriptions!==void 0},{replicates:!0}),this.sessionResolve(r)}),this.socket.on("error",n=>{n.code==="SELF_SIGNED_CERT_IN_CHAIN"?(le.warn?.(`Can not connect to ${this.url}, this server does not have a certificate authority for the certificate provided by ${this.url}`),n.isHandled=!0):n.code!=="ECONNREFUSED"&&(n.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"?le.error?.(`Can not connect to ${this.url}, the certificate provided by ${this.url} is not trusted, this node needs to be added to the cluster, or a certificate authority needs to be added`):le.error?.(`Error in connection to ${this.url} due to ${n.message}`)),this.sessionReject(n)}),this.socket.on("close",(n,s)=>{if(this.isConnected&&(this.nodeSubscriptions&&Zd({name:this.nodeName,database:this.databaseName,url:this.url,finished:this.socket.isFinished}),this.isConnected=!1),this.removeAllListeners("subscriptions-updated"),this.socket.isFinished){this.isFinished=!0,r?.end(),this.emit("finished");return}if(++this.retries%20===1){let i=s?.toString();le.warn?.(`${r?"Disconnected from":"Failed to connect to"} ${this.url} (db: "${this.databaseName}"), due to ${i?'"'+i+'" ':""}(code: ${n})`)}r=null,this.resetSession(),setTimeout(()=>{this.connect()},this.retryTime).unref(),this.retryTime+=this.retryTime>>8})}resetSession(){this.session=new Promise((t,r)=>{this.sessionResolve=t,this.sessionReject=r})}subscribe(t,r){this.nodeSubscriptions=t,this.replicateTablesByDefault=r,this.emit("subscriptions-updated",t)}unsubscribe(){this.socket.isFinished=!0,this.socket.close(1008,"No longer subscribed")}getRecord(t){return this.session.then(r=>r.getRecord(t))}};a(bh,"replicateOverWS")});function Ac(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(`
16
+ `+Kl.get(_.issuer)),!h||!E)throw new Error("Missing private key or certificate for secure server");let R={ciphers:f.ciphers,ticketKeys:Xue(),availableCAs:Kl,ca:t&&Array.from(Kl.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??lO(_);Array.isArray(S)||(S=[S]);for(let I of S)I===eO()&&(p+=1);let y=pT.createSecureContext(R);y.name=f.name,y.options=R,y.quality=p,y.certificateAuthorities=Array.from(Kl),y.certStart=E.toString().slice(0,100);let w;for(let I of S)if(I){I[0]==="*"&&(s=!0,I=I.slice(1)),n1.isIP(I)&&(w=!0);let H=r.get(I)?.quality??0;Xe.trace?.("Assigning TLS for hostname",I,"if",p,">",H),p>H&&r.set(I,y)}else Xe.error?.("No hostname found for certificate at",pT.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"),mT?.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(E1,"createTLSSelector");async function _1(e){let t=Tc.get(e);return!t&&e?await Wn.readFile(_r.join(Ts.get(Yl.ROOTPATH),Vs.LICENSE_KEY_DIR_NAME,e),"utf8"):t}a(_1,"getPrivateKeyByName");async function g1(){yc();let e=[];for await(let t of on.search([]))e.push(t);return e}a(g1,"listCertificates");async function cde(e){let t=rO(e,Ti.object({name:Ti.string().required(),certificate:Ti.string().required(),is_authority:Ti.boolean().required(),private_key:Ti.string(),hosts:Ti.array(),uses:Ti.array()}));if(t)throw new Sc(t.message);let{name:r,certificate:n,private_key:s,is_authority:i}=e,o=new ia(n),c=!1,l=!1,u;for(let[p,h]of Tc)!s&&!c&&o.checkPrivateKey(s1(h))&&(c=!0,u=p),s&&s===h&&(l=!0,u=p);if(!i&&!s&&!c)throw new Sc("A suitable private key was not found for this certificate");let d;if(!r){try{d=cO(o)}catch(p){Xe.error?.(p)}if(d==null)throw new Sc("Error extracting certificate host name, please provide a name parameter")}let f=lde(r??d);s&&!c&&!l&&(await Wn.writeFile(_r.join(Ts.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,f+".pem"),s),Tc.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 tf(m),"Successfully added certificate: "+f}a(cde,"addCertificate");function lde(e){return e.replace(/[^a-z0-9\.]/gi,"-")}a(lde,"sanitizeName");async function ude(e){let t=rO(e,Ti.object({name:Ti.string().required()}));if(t)throw new Sc(t.message);let{name:r}=e;yc();let n=await on.get(r);if(!n)throw new Sc(r+" not found");let{private_key_name:s}=n;if(s){let i=Array.from(await on.search([{attribute:"private_key_name",value:s}]));i.length===1&&i[0].name===r&&(Xe.info?.("Removing private key named",s),await Wn.remove(_r.join(Ts.getHdbBasePath(),Vs.LICENSE_KEY_DIR_NAME,s)))}return await on.delete(r),"Successfully removed "+r}a(ude,"removeCertificate");function cO(e){let t=e.subject?.match(/CN=(.*)/)?.[1];return t||lO(e)[0]}a(cO,"getPrimaryHostName");function lO(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(lO,"hostnamesFromCert");async function dde(e){if(e.bypass_auth!==!0)throw new Sc("Unauthorized","401");let t=rO(e,Ti.object({name:Ti.string().required()}));if(t)throw new Sc(t.message);let{name:r}=e;if(r===".jwtPrivate")return(await ZV()).privateKey;if(r===".jwtPublic")return(await ZV()).publicKey;if(Tc.get(r))return Tc.get(e.name);throw new Sc("Key not found")}a(dde,"getKey");function fde(e){return[e.subject?.CN,...e.subjectaltname.split(",").filter(t=>t.trim().startsWith("DNS:")).map(t=>t.trim().substring(4))]}a(fde,"getHostnamesFromCertificate")});var G1={};ye(G1,{BACK_PRESSURE_RATIO_POSITION:()=>k1,CONFIRMATION_STATUS_POSITION:()=>F1,LATENCY_POSITION:()=>IT,NodeReplicationConnection:()=>nf,OPERATION_REQUEST:()=>pO,RECEIVED_TIME_POSITION:()=>bT,RECEIVED_VERSION_POSITION:()=>RT,RECEIVING_STATUS_POSITION:()=>AT,RECEIVING_STATUS_RECEIVING:()=>H1,RECEIVING_STATUS_WAITING:()=>hO,SENDING_TIME_POSITION:()=>Rh,createWebSocket:()=>wT,databaseSubscriptions:()=>bc,replicateOverWS:()=>bh,tableUpdateListeners:()=>gO});async function wT(e,t){let{authorization:r,rejectUnauthorized:n}=t||{},s=tt(),i;if(e==null)throw new TypeError(`Invalid URL: Expected a string URL for node "${s}" but received ${e}`);if(e.includes("wss://")){if(!fO){let l=(0,M1.createTLSSelector)("operations-api"),u={secureContexts:null};await l.initialize(u),fO=u.secureContexts}if(i=fO.get(s),i&&le.debug?.("Creating web socket for URL",e,"with certificate named:",i.name),!i&&n!==!1)throw new Error("Unable to find a valid certificate to use for replication to connect to "+e)}let o={};r&&(o.Authorization=r);let c={headers:o,localAddress:s?.startsWith("127.0")?s:void 0,servername:(0,x1.isIP)(t?.serverName)?void 0:t?.serverName,noDelay:!0,highWaterMark:128*1024,rejectUnauthorized:n!==!1,secureContext:void 0};return i&&((rf?.caCount!==aa.size||rf?.derivedFromContext!==i)&&(rf=U1.createSecureContext({...i.options,ca:[...aa,...i.options.availableCAs.values()]}),rf.caCount=aa.size,rf.derivedFromContext=i),c.secureContext=rf),new L1.WebSocket(e,"harperdb-replication-v1",c)}function bh(e,t,r){let n=t.port||t.securePort,s=_O.pid%1e3+"-"+D1.threadId+(n?"s:"+n:"c:"+t.url?.slice(-4))+" "+Math.random().toString().slice(2,3);le.debug?.(s,"Initializing replication connection",r);let i=0,o=Buffer.allocUnsafeSlow(1024),c=0,l=new DataView(o.buffer,0,1024),u=t.database,d=t.databaseSubscriptions||bc,f,m,p=!1,h=t.subscription;h?.then&&h.then(A=>{h=A,h.auditStore&&(f=h.auditStore)});let E=t.tables||u&&lt()[u],_,R=new Map,S=[];_=r.name,_&&t.connection&&(t.connection.nodeName=_);let y,w,I,H,X,q,k,z=6e4,Y,ce=0,de=0,te=0,Se=P1.default.get(x.REPLICATION_BLOBTIMEOUT)??12e4,Ne=new Map,Ke=[],$e=0,Ir;if(t.url){let A=a(()=>{X&&de===e._socket?.bytesRead&&te===e._socket?.bytesWritten?e.terminate():(X=performance.now(),e.ping(),de=e._socket?.bytesRead,te=e._socket?.bytesWritten)},"sendPing");I=setInterval(A,C1).unref(),A()}else nr();e._socket?.setMaxListeners(200);function nr(){clearTimeout(H),de=e._socket?.bytesRead,te=e._socket?.bytesWritten,H=setTimeout(()=>{de===e._socket?.bytesRead&&te===e._socket?.bytesWritten&&(le.warn?.(`Timeout waiting for ping from ${_}, terminating connection and reconnecting`),e.terminate())},C1*2).unref()}a(nr,"resetPingTimer");let zr=0,xr=0,Ou=!1,zc=3e4;function Ft(){if(pn?.length>0){let A=performance.now(),U=A-xr;zr=(zr*zc+(Ou?U:0))/(zc+U),m&&(m[k1]=zr),xr=A}}a(Ft,"updateBackPressureRatio"),setInterval(Ft,zc).unref();function Ps(){if(!(!_||!u))return m||(m=zd(f,u,_)),m}a(Ps,"getSharedStatus"),u&&Jc(u);let Ha,o_,cm=[],a_=[],lm,ve=[],c_=[],Wb=[],Pu=150,ki=25,Ls=0,um=0,dm=!1,xo,Dn,pn,Br;e.on("message",Lu);async function Lu(A){if(r=await r,!r){le.error?.(s,"No authorization provided"),Fr(1008,"Unauthorized");return}fm(A),e.off("message",Lu),e.on("message",fm)}a(Lu,"onWSMessageWhenAuthorized");function fm(A){ce=performance.now();try{let U=A.dataView=new al(A.buffer,A.byteOffset,A.byteLength);if(A[0]>127){let W=(0,at.decode)(A),[J,F,he]=W;switch(J){case T1:{if(F){if(_){if(_!==F){le.error?.(s,`Node name mismatch, expecting to connect to ${_}, but peer reported name as ${F}, disconnecting`),e.send((0,at.encode)([yh])),Fr(1008,"Node name mismatch");return}}else if(_=F,t.connection?.tentativeNode){let me=t.connection.tentativeNode;me.name=_,t.connection.tentativeNode=null,sa(_,me)}if(t.connection&&(t.connection.nodeName=_),le.debug?.(s,"received node name:",_,"db:",u??W[2]),!u)try{Jc(u=W[2]),u==="system"&&(Ha=_c(t,(me,ie)=>{$a(ie)&&K(ie)}),e.on("close",()=>{Ha?.remove()}))}catch(me){le.warn?.(s,"Error setting database",me),e.send((0,at.encode)([yh])),Fr(1008,me.message);return}mm()}break}case w1:{le.debug?.(s,"Received table definitions for",F.map(me=>me.table));for(let me of F){let ie=W[2];me.database=ie;let Ce;if($a(ie)){if(u==="system")Me[ie]?.[me.table]||(Ce=D(me,Me[ie]?.[me.table]));else{if(ie!=="data"&&!Me[ie]){le.warn?.("Database not found",ie);return}Ce=D(me,Me[ie]?.[me.table])}f||(f=Ce?.auditStore),E||(E=lt()?.[ie])}}break}case yh:Fr();break;case pO:try{let me=r?.replicates||r?.subscribers||r?.name;le.debug?.("Received operation request",F,"from",_),server.operation(F,{user:r},!me).then(ie=>{le.debug?.("Requested request from finished",_,ie),Array.isArray(ie)&&(ie={results:ie}),ie.requestId=F.requestId,e.send((0,at.encode)([ST,ie]))},ie=>{le.debug?.("Failed requested operation from",_,ie),e.send((0,at.encode)([ST,{requestId:F.requestId,error:uO(ie)}]))})}catch(me){e.send((0,at.encode)([ST,{requestId:F.requestId,error:uO(me)}]))}break;case ST:let{resolve:ue,reject:_e}=R.get(F.requestId);le.debug?.("Received completed operation request",_,F),F.error?_e(new Error(F.error)):ue(F),R.delete(F.requestId);break;case dO:let re=W[3];if(!E){u?le.error?.(s,"No database found for",u):le.error?.(s,"Database name never received"),Fr();return}let oe=E[re];oe=D({table:re,database:u,attributes:F.attributes,schemaDefined:F.schemaDefined},oe),cm[he]={name:re,decoder:new at.Packr({useBigIntExtension:!0,randomAccessStructure:!0,freezeData:!0,typedStructs:F.typedStructs,structures:F.structures}),getEntry(me){return oe.primaryStore.getEntry(me)},rootStore:oe.primaryStore.rootStore};break;case y1:Br=f?FV(F,f):new Map,lm=W[2],le.debug?.(s,`Acknowledged subscription request, receiving messages for nodes: ${lm}`);break;case R1:let ge=he;Wb[ge]=F;break;case I1:Ps()[F1]=F,le.trace?.(s,"received and broadcasting committed update",F),Ps().buffer.notify();break;case A1:y=F,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),Ps(),m[RT]=last_sequence_id_received,m[bT]=Date.now(),m[AT]=hO;break;case TT:{let me=W[1],{fileId:ie,size:Ce,finished:Be,error:He}=me,Te=Ne.get(ie);le.debug?.("Received blob",ie,"has stream",!!Te,"connectedToBlob",!!Te?.connectedToBlob,"length",W[2].length,"finished",Be),Te||(Te=new mO.PassThrough,Te.expectedSize=Ce,Ne.set(ie,Te)),Te.lastChunk=Date.now();let ht=W[2];Ye(ht.byteLength,"bytes-received",`${_}.${u}`,"replication","blob");try{Be?(He?(Te.on("error",()=>{}),Te.destroy(new Error("Blob error: "+He+" for record "+(Te.recordId??"unknown")+" from "+_))):Te.end(ht),Te.connectedToBlob&&Ne.delete(ie)):Te.write(ht)}catch(Ct){le.error?.(`Error receiving blob for ${Te.recordId} from ${_} and streaming to storage`,Ct),Ne.delete(ie)}break}case b1:{let me=F,ie;try{let Ce=W[3],Be=a_[he]||(a_[he]=E[W[4]]);if(!Be)return le.warn?.("Unknown table id trying to handle record request",he);let He=Be.primaryStore.getBinaryFast(Symbol.for("structures")),Te=He?.length??0;if(Te>0&&Te!==um){um=Te;let Ct=(0,at.decode)(He);e.send((0,at.encode)([dO,{typedStructs:Ct.typed,structures:Ct.named},he,Be.tableName]))}let ht=Be.primaryStore.getBinaryFast(Ce);if(ht){let Ct=Be.primaryStore.decoder.decode(ht,{valueAsBuffer:!0}),Ot=ut||{};Ot.version=(0,B1.getLastVersion)(),ut&&ut[Wu]&Xr&&(Ct=Buffer.from(Ct),Hm(()=>Be.primaryStore.decoder.decode(ht),u_=>Ga(u_,Ce),Be.primaryStore.rootStore)),ie=(0,at.encode)([gT,me,{value:Ct,expiresAt:Ot.expiresAt,version:Ot.version,residencyId:Ot.residencyId,nodeId:Ot.nodeId,user:Ot.user}])}else ie=(0,at.encode)([gT,me])}catch(Ce){ie=(0,at.encode)([gT,me,{error:Ce.message}])}e.send(ie);break}case gT:{let{resolve:me,reject:ie,tableId:Ce,key:Be}=R.get(W[1]),He=W[2];if(He?.error)ie(new Error(He.error));else if(He){let Te;z_(()=>{let ht=cm[Ce].decoder.decode(He.value);He.value=ht,He.key=Be,me(He)||Te&&setTimeout(()=>Te.forEach(Y_),6e4).unref()},f?.rootStore,ht=>{let Ct=qa(ht,Be);return Te||(Te=[]),Te.push(Ct),Ct})}else me();R.delete(W[1]);break}case S1:{pn=F;let me,ie,Ce=!1;if(h){if(u!==h.databaseName&&!h.then){le.error?.("Subscription request for wrong database",u,h.databaseName);return}}else h=d.get(u);if(le.debug?.(s,"received subscription request for",u,"at",pn),!h){let De;h=new Promise(ft=>{le.debug?.("Waiting for subscription to database "+u),De=ft}),h.ready=De,bc.set(u,h)}if(r.name)ie=Gt().subscribe(r.name),ie.then(async De=>{me=De;for await(let ft of me){let kr=ft.value;if(!(kr?.replicates===!0||kr?.replicates?.receives||kr?.subscriptions?.some(fr=>(fr.database||fr.schema)===u&&fr.publish!==!1))){Ce=!0,Fr(1008,`Unauthorized database subscription to ${u}`);return}}},De=>{le.error?.(s,"Error subscribing to HDB nodes",De)});else if(!(r?.role?.permission?.super_user||r.replicates)){e.send((0,at.encode)([yh])),Fr(1008,`Unauthorized database subscription to ${u}`);return}if(Dn&&(le.debug?.(s,"stopping previous subscription",u),Dn.emit("close")),pn.length===0)return;let Be=pn[0],He=a(De=>{if(De&&(Be.replicateByDefault?!Be.tables.includes(De.tableName):Be.tables.includes(De.tableName)))return{table:De}},"tableToTableEntry"),Te={txnTime:0},ht,Ct,Ot=1/0,u_,d_=a((De,ft)=>{if(De.type==="end_txn"){Te.txnTime&&(o[i]!==66&&le.error?.("Invalid encoding of message"),C(9),C(og),O(u_=ft),nU()),i=c,Te.txnTime=0;return}let kr=De.nodeId,fr=De.tableId,zt=Ct[fr];if(!zt&&(zt=Ct[fr]=He(h.tableById[fr]),!zt))return le.debug?.("Not subscribed to table",fr);let yt=zt.table,Mu=yt.primaryStore,si=Mu.encoder;(De.extendedType&Eg||!si.typedStructs)&&(si._mergeStructures(si.getStructures()),si.typedStructs&&(si.lastTypedStructuresLength=si.typedStructs.length));let f_=ht[kr];if(!(f_&&f_.startTime<ft&&(!f_.endTime||f_.endTime>ft)))return yT&&le.trace?.(s,"skipping replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",ht),sU();yT&&le.trace?.(s,"sending replication update",De.recordId,"to:",_,"from:",kr,"subscribed:",ht);let jb=De.version,Qc=De.residencyId,zb=l_(Qc,yt),m_;if(zb&&!zb.includes(_)){let Hi=l_(De.previousResidencyId,yt);if(Hi&&!Hi.includes(_)&&(De.type==="put"||De.type==="patch")||yt.getResidencyById)return sU();let Xc=De.recordId;le.trace?.(s,"sending invalidation",Xc,_,"from",kr);let pm=0;Qc&&(pm|=cl),De.previousResidencyId&&(pm|=ll);let Xb,p_=null;for(let iU in yt.indices){if(!p_){if(Xb=De.getValue(Mu,!0),!Xb)break;p_={}}p_[iU]=Xb[iU]}m_=ul(De.version,fr,Xc,null,kr,De.user,De.type==="put"||De.type==="patch"?"invalidate":De.type,si.encode(p_),pm,Qc,De.previousResidencyId,De.expiresAt)}function sU(){return le.trace?.(s,"skipping audit record",De.recordId),q||(q=setTimeout(()=>{q=null,(u_||0)+N1/2<Ot&&(yT&&le.trace?.(s,"sending skipped sequence update",Ot),e.send((0,at.encode)([A1,Ot])))},N1).unref()),new Promise(setImmediate)}a(sU,"skipAuditRecord");let Jb=si.typedStructs,Qb=si.structures;if((Jb?.length!=zt.typed_length||Qb?.length!=zt.structure_length)&&(zt.typed_length=Jb?.length,zt.structure_length=Qb.length,le.debug?.(s,"send table struct",zt.typed_length,zt.structure_length),zt.sentName||(zt.sentName=!0),e.send((0,at.encode)([dO,{typedStructs:Jb,structures:Qb,attributes:yt.attributes,schemaDefined:yt.schemaDefined},fr,zt.table.tableName]))),Qc&&!c_[Qc]&&(e.send((0,at.encode)([R1,zb,Qc])),c_[Qc]=!0),Te.txnTime!==jb&&(Te.txnTime&&(yT&&le.trace?.(s,"new txn time, sending queued txn",Te.txnTime),o[i]!==66&&le.error?.("Invalid encoding of message"),nU()),Te.txnTime=jb,i=c,O(jb)),m_)C(m_.length),P(m_);else{let Hi=De.encoded;De.extendedType&Xr&&Hm(()=>De.getValue(Mu),pm=>Ga(pm,De.recordId),Mu.rootStore);let Xc=Hi[0]===66?8:0;C(Hi.length-Xc),P(Hi,Xc),le.trace?.("wrote record",De.recordId,"length:",Hi.length)}if(e._socket.writableNeedDrain){let Hi=performance.now();return Ou=!0,Ft(),new Promise(Xc=>{le.debug?.(`Waiting for remote node ${_} to allow more commits ${e._socket.writableNeedDrain?"due to network backlog":"due to requested flow directive"}`),e._socket.once("drain",()=>{Xc(),Ou=!1,Ft()})})}else return $e>ki?new Promise(Hi=>{Ir=Hi}):new Promise(setImmediate)},"sendAuditRecord"),nU=a(()=>{c-i>8?(e.send(o.subarray(i,c)),le.debug?.(s,"Sent message, size:",c-i),u!=="system"&&Ye(c-i,"bytes-sent",`${_}.${u}`,"replication","egress")):le.debug?.(s,"skipping empty transaction")},"sendQueuedData");Dn=new EO.EventEmitter,Dn.once("close",()=>{Ce=!0,me?.end()});for(let{startTime:De}of pn)De<Ot&&(Ot=De);(ie||Promise.resolve()).then(async()=>{h=await h,f=h.auditStore,Ct=h.tableById.map(He),ht=[];for(let{name:ft,startTime:kr,endTime:fr}of pn){let zt=lT(ft,f);le.debug?.("subscription to",ft,"using local id",zt,"starting",kr),ht[zt]={startTime:kr,endTime:fr}}K(u),Ha||(Ha=Gl(ft=>{ft.databaseName===u&&K(u)}),o_=th(ft=>{ft===u&&(e.send((0,at.encode)([yh])),Fr())}),e.on("close",()=>{Ha?.remove(),o_?.remove()})),e.send((0,at.encode)([y1,fh(h.auditStore),pn.map(({name:ft})=>ft)]));let De=!0;do{if(isFinite(Ot)||(le.warn?.("Invalid sequence id "+Ot),Fr(1008,"Invalid sequence id"+Ot)),De&&!Ce&&(De=!1,Ot===0)){le.info?.("Replicating all tables to",_);let ft=Date.now(),kr=NT(f);for(let fr in E){if(!He(fr))continue;let zt=E[fr];for(let yt of zt.primaryStore.getRange({snapshot:!1,versions:!0})){if(Ce)return;le.trace?.(s,"Copying record from",u,fr,yt.key,yt.localTime),ft=Math.max(yt.localTime??1,ft),Ps()[Rh]=1;let Mu=ul(yt.version,zt.tableId,yt.key,null,kr,null,"put",Hm(()=>zt.primaryStore.encoder.encode(yt.value),si=>Ga(si,yt.key)),yt.metadataFlags&-256,yt.residencyId,null,yt.expiresAt);await d_({recordId:yt.key,tableId:zt.tableId,type:"put",getValue(){return yt.value},encoded:Mu,version:yt.version,residencyId:yt.residencyId,nodeId:kr,extendedType:yt.metadataFlags},yt.localTime)}}Te.txnTime||(Te.txnTime=ft,O(ft)),c-i>8&&d_({type:"end_txn"},Ot),Ps()[Rh]=0,Ot=ft}for(let{key:ft,value:kr}of f.getRange({start:Ot||1,exclusiveStart:!0,snapshot:!1})){if(Ce)return;let fr=It(kr);le.debug?.("sending audit record",ft,fr.recordId),Ps()[Rh]=ft,Ot=ft,await d_(fr,ft),Dn.startTime=ft}c-i>8&&d_({type:"end_txn"},Ot),Ps()[Rh]=0,await mB(f)}while(!Ce)}).catch(De=>{le.error?.(s,"Error handling subscription to node",De),Fr(1008,"Error handling subscription to node")});break}}return}U.position=8;let N=!0,L,$;do{Ps();let W=U.readInt();if(W===9&&U.getUint8(U.position)==og){U.position++,y=$=U.readFloat64(),m[RT]=y,m[bT]=Date.now(),m[AT]=hO,h.send({type:"end_txn",localTime:y,remoteNodeIds:S}),le.trace?.("received remote sequence update",y,u);break}let J=U.position,F=It(A,J,J+W),he=cm[F.tableId];he||le.error?.(`No table found with an id of ${F.tableId}`);let ue;F.residencyId&&(ue=Wb[F.residencyId],le.trace?.(s,"received residency list",ue,F.type,F.recordId));let _e=F.recordId;try{z_(()=>{L={table:he.name,id:F.recordId,type:F.type,nodeId:Br.get(F.nodeId),residencyList:ue,timestamp:F.version,value:F.getValue(he),user:F.user,beginTxn:N,expiresAt:F.expiresAt}},f?.rootStore,re=>qa(re,_e))}catch(re){throw re.message+=" record id: "+_e,re.message+=" typed structures for current decoder"+JSON.stringify(he.decoder.typedStructs),re.message+=" structures for current decoder"+JSON.stringify(he.decoder.structures),re}N=!1,le.debug?.(s,"received replication message",F.type,"id",L.id,"version",new Date(F.version),"nodeId",L.nodeId),m[RT]=F.version,m[bT]=Date.now(),m[AT]=H1,h.send(L),U.position=J+W}while(U.position<A.byteLength);Ls++,u!=="system"&&Ye(A.byteLength,"bytes-received",`${_}.${u}.${L?.table||"unknown_table"}`,"replication","ingest"),Ls>Pu&&!dm&&(dm=!0,e.pause(),le.debug?.(`Commit backlog causing replication back-pressure, requesting that ${_} pause replication`)),h.send({type:"end_txn",localTime:y,remoteNodeIds:S,async onCommit(){if(L){let W=Date.now()-L.timestamp;u!=="system"&&Ye(W,"replication-latency",_+"."+u+"."+L.table,L.type,"ingest")}Ls--,dm&&(dm=!1,e.resume(),le.debug?.(`Replication resuming ${_}`)),Ke.length>0&&await Promise.all(Ke),le.trace?.("All blobs finished"),!w&&$&&(le.trace?.(s,"queuing confirmation of a commit at",$),setTimeout(()=>{e.send((0,at.encode)([I1,w])),le.trace?.(s,"sent confirmation of a commit at",w),w=null},pde)),w=$,le.debug?.("last sequence committed",new Date($),u)}})}catch(U){le.error?.(s,"Error handling incoming replication message",U)}}a(fm,"onWSMessage"),e.on("ping",nr),e.on("pong",()=>{if(t.connection){let A=performance.now()-X;t.connection.latency=A,Ps()&&(m[IT]=A),t.isSubscriptionConnection&&Vl({name:_,database:u,url:t.url,latency:A})}X=null}),e.on("close",(A,U)=>{clearInterval(I),clearTimeout(H),clearInterval(k),Dn&&Dn.emit("close"),xo&&xo.end();for(let[N,{reject:L}]of R)L(new Error(`Connection closed ${U?.toString()} ${A}`));le.debug?.(s,"closed",A,U?.toString())});function Fr(A,U){try{e.isFinished=!0,le.debug?.(s,"closing",_,u,A,U),e.close(A,U),t.connection?.emit("finished")}catch(N){le.error?.(s,"Error closing connection",N)}}a(Fr,"close");let Du=new Set;async function Ga(A,U){let N=W_(A);if(Du.has(N)){le.debug?.("Blob already being sent",N);return}Du.add(N);try{let L;$e++;for await(let $ of A.stream())L&&(le.debug?.("Sending blob chunk",N,"length",L.length),e.send((0,at.encode)([TT,{fileId:N,size:A.size},L]))),L=$,e._socket.writableNeedDrain&&(le.debug?.("draining",N),await new Promise(W=>e._socket.once("drain",W)),le.debug?.("drained",N)),Ye($.length,"bytes-sent",`${_}.${u}`,"replication","blob");le.debug?.("Sending final blob chunk",N,"length",L.length),e.send((0,at.encode)([TT,{fileId:N,size:A.size,finished:!0},L]))}catch(L){le.warn?.("Error sending blob",L,"blob id",N,"for record",U),e.send((0,at.encode)([TT,{fileId:N,finished:!0,error:uO(L)},Buffer.alloc(0)]))}finally{Du.delete(N),$e--,$e<ki&&Ir?.()}}a(Ga,"sendBlobs");function qa(A,U){let N=W_(A),L=Ne.get(N);le.debug?.("Received transaction with blob",N,"has stream",!!L,"ended",!!L?.writableEnded),L?L.writableEnded&&Ne.delete(N):(L=new mO.PassThrough,Ne.set(N,L)),L.connectedToBlob=!0,L.lastChunk=Date.now(),L.recordId=U,A.size===void 0&&L.expectedSize&&(A.size=L.expectedSize);let $=L.blob??createBlob(L,A);L.blob=$;let W=Ko(()=>km($).saving,h.auditStore?.rootStore);return W&&(W.blobId=N,Ke.push(W),W.finally(()=>{le.debug?.(`Finished receiving blob stream ${N}`),Ke.splice(Ke.indexOf(W),1)})),$}a(qa,"receiveBlobs");function mm(){if(p||(p=!0,t.connection?.on("subscriptions-updated",mm)),!f&&h&&(f=h.auditStore),t.connection?.isFinished)throw new Error("Can not make a subscription request on a connection that is already closed");let A=new Map;f||(f=h?.auditStore);try{for(let L of h?.dbisDB?.getRange({start:Symbol.for("seq"),end:[Symbol.for("seq"),Buffer.from([255])]})||[])for(let $ of L.value.nodes||[])$.lastTxnTime>(A.get($.id)??0)&&A.set($.id,$.lastTxnTime)}catch(L){if(!L.message.includes("Can not re"))throw L}let U=t.connection?.nodeSubscriptions?.[0];S=[];let N=t.connection?.nodeSubscriptions.map((L,$)=>{let W=[],{replicateByDefault:J}=L;if(L.subscriptions){for(let _e of L.subscriptions)if(_e.subscribe&&(_e.schema||_e.database)===u){let re=_e.table;E?.[re]?.replicate!==!1&&W.push(re)}J=!1}else for(let _e in E)(J?E[_e].replicate===!1:E[_e].replicate)&&W.push(_e);let F=f&&lT(L.name,f),he=h?.dbisDB?.get([Symbol.for("seq"),F])??1,ue=Math.max(he?.seqId??1,(typeof L.startTime=="string"?new Date(L.startTime).getTime():L.startTime)??1);if(le.debug?.("Starting time recorded in db",L.name,F,u,he?.seqId,"start time:",ue,new Date(ue)),U!==L){let _e=f&&lT(U.name,f),re=h?.dbisDB?.get([Symbol.for("seq"),_e])??1;for(let oe of re?.nodes||[])oe.name===L.name&&(ue=oe.seqId,le.debug?.("Using sequence id from proxy node",U.name,ue))}return F===void 0?le.warn("Starting subscription request from node",L,"but no node id found"):S.push(F),A.get(F)>ue&&(ue=A.get(F),le.debug?.("Updating start time from more recent txn recorded",U.name,ue)),ue===1&&(L.isLeader?(le.warn?.(`Requesting full copy of database ${u} from ${L.url}`),ue=0):ue=Date.now()-6e4),le.trace?.(s,"defining subscription request",L.name,u,new Date(ue)),{name:L.name,replicateByDefault:J,tables:W,startTime:ue,isLeader:L.isLeader,endTime:L.endTime}});if(N)if(le.debug?.(s,"sending subscription request",N,h?.dbisDB?.path),clearTimeout(Y),N.length>0)e.send((0,at.encode)([S1,N]));else{let L=a(()=>{let $=performance.now();Y=setTimeout(()=>{ce<=$?Fr(1008,"Connection has no subscriptions and is no longer used"):L()},z).unref()},"scheduleClose");L()}}a(mm,"sendSubscriptionRequestUpdate");function l_(A,U){if(!A)return;let N=ve[A];return N||(N=U.getResidencyRecord(A),ve[A]=N),N}a(l_,"getResidence");function $a(A){return!(Rc&&Rc!="*"&&!Rc[A]&&!Rc.includes?.(A)&&!Rc.some?.(U=>U.name===A))}a($a,"checkDatabaseAccess");function Jc(A){if(h=h||d.get(A),!$a(A))throw new Error(`Access to database "${A}" is not permitted`);h||le.warn?.(`No database named "${A}" was declared and registered`),f=h?.auditStore,E||(E=lt()?.[A]);let U=tt();if(U===_)throw U?new Error("Should not connect to self",U):new Error("Node name not defined");return vu(U,A),!0}a(Jc,"setDatabase");function vu(A,U){let N=lt()?.[U],L=[];for(let $ in N){let W=N[$];L.push({table:$,schemaDefined:W.schemaDefined,attributes:W.attributes.map(J=>({name:J.name,type:J.type,isPrimaryKey:J.isPrimaryKey}))})}le.trace?.("Sending database info for node",A,"database name",U),e.send((0,at.encode)([T1,A,U,L]))}a(vu,"sendNodeDBName");function K(A){let U=lt()?.[A],N=[];for(let L in U){if(pn&&!pn.some(W=>W.replicateByDefault?!W.tables.includes(L):W.tables.includes(L)))continue;let $=U[L];N.push({table:L,schemaDefined:$.schemaDefined,attributes:$.attributes.map(W=>({name:W.name,type:W.type,isPrimaryKey:W.isPrimaryKey}))})}e.send((0,at.encode)([w1,N,A]))}a(K,"sendDBSchema"),k=setInterval(()=>{for(let[A,U]of Ne)U.lastChunk+Se<Date.now()&&(le.warn?.(`Timeout waiting for blob stream to finish ${A} for record ${U.recordId??"unknown"} from ${_}`),Ne.delete(A),U.end())},Se).unref();let g=1,T=[];return{end(){xo&&xo.end(),Dn&&Dn.emit("close")},getRecord(A){let U=g++;return new Promise((N,L)=>{let $=[b1,U,A.table.tableId,A.id];T[A.table.tableId]||($.push(A.table.tableName),T[A.table.tableId]=!0),e.send((0,at.encode)($)),ce=performance.now(),R.set(U,{tableId:A.table.tableId,key:A.id,resolve(W){let{table:J,entry:F}=A;if(N(W),W)return J._recordRelocate(F,W)},reject:L})})},sendOperation(A){let U=g++;return A.requestId=U,e.send((0,at.encode)([pO,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 D(A,U){let N=A.database??"data";U||(U={});let L=U.schemaDefined,$=!1,W=A.schemaDefined,J=U.attributes||[];for(let F=0;F<A.attributes?.length;F++){let he=A.attributes[F],ue=J.find(_e=>_e.name===he.name);(!ue||ue.type!==he.type)&&(L?le.error?.(`Schema for '${u}.${A.table}' is defined locally, but attribute '${he.name}: ${he.type}' from '${_}' does not match local attribute ${ue?"'"+ue.name+": "+ue.type+"'":"which does not exist"}`):($=!0,W||(he.indexed=!0),ue?J[J.indexOf(ue)]=he:J.push(he)))}return $?(le.debug?.("(Re)creating",A),ze({table:A.table,database:A.database,schemaDefined:A.schemaDefined,attributes:J,...U})):U}}var P1,at,L1,D1,v1,EO,M1,U1,_O,x1,mO,B1,mde,uO,le,S1,T1,y1,yh,R1,dO,b1,gT,pO,ST,A1,I1,w1,TT,F1,RT,bT,Rh,IT,AT,k1,hO,H1,gO,bc,yT,N1,pde,C1,fO,rf,O1,nf,SO=se(()=>{Oe();qi();JC();CI();Ss();P1=b(fe());G();dl();at=require("msgpackr"),L1=require("ws"),D1=require("worker_threads"),v1=b(Q());gh();EO=require("events"),M1=b(ys()),U1=b(require("node:tls"));Qd();_O=b(require("node:process")),x1=require("node:net");is();ss();mO=require("node:stream"),B1=require("lmdb"),{forComponent:mde,errorToString:uO}=v1.default,le=mde("replication").conditional,S1=129,T1=140,y1=141,yh=142,R1=130,dO=132,b1=133,gT=134,pO=136,ST=137,A1=143,I1=144,w1=145,TT=146,F1=0,RT=1,bT=2,Rh=3,IT=4,AT=5,k1=6,hO=0,H1=1,gO=new Map,bc=new Map,yT=!0,N1=300,pde=2,C1=3e4;a(wT,"createWebSocket");O1=500,nf=class extends EO.EventEmitter{static{a(this,"NodeReplicationConnection")}socket;startTime;retryTime=O1;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??Si(t)}async connect(){this.session||this.resetSession();let t=[];this.socket=await wT(this.url,{serverName:this.nodeName,authorization:this.authorization});let r;le.debug?.(`Connecting to ${this.url}, db: ${this.databaseName}, process ${_O.pid}`),this.socket.on("open",()=>{this.socket._socket.unref(),le[this.isConnected?"info":"warn"]?.(`Connected to ${this.url}, db: ${this.databaseName}`),this.retries=0,this.retryTime=O1,this.nodeSubscriptions&&Vl({name:this.nodeName,database:this.databaseName,url:this.url}),this.isConnected=!0,r=bh(this.socket,{database:this.databaseName,subscription:this.subscription,url:this.url,connection:this,isSubscriptionConnection:this.nodeSubscriptions!==void 0},{replicates:!0}),this.sessionResolve(r)}),this.socket.on("error",n=>{n.code==="SELF_SIGNED_CERT_IN_CHAIN"?(le.warn?.(`Can not connect to ${this.url}, this server does not have a certificate authority for the certificate provided by ${this.url}`),n.isHandled=!0):n.code!=="ECONNREFUSED"&&(n.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"?le.error?.(`Can not connect to ${this.url}, the certificate provided by ${this.url} is not trusted, this node needs to be added to the cluster, or a certificate authority needs to be added`):le.error?.(`Error in connection to ${this.url} due to ${n.message}`)),this.sessionReject(n)}),this.socket.on("close",(n,s)=>{if(this.isConnected&&(this.nodeSubscriptions&&Zd({name:this.nodeName,database:this.databaseName,url:this.url,finished:this.socket.isFinished}),this.isConnected=!1),this.removeAllListeners("subscriptions-updated"),this.socket.isFinished){this.isFinished=!0,r?.end(),this.emit("finished");return}if(++this.retries%20===1){let i=s?.toString();le.warn?.(`${r?"Disconnected from":"Failed to connect to"} ${this.url} (db: "${this.databaseName}"), due to ${i?'"'+i+'" ':""}(code: ${n})`)}r=null,this.resetSession(),setTimeout(()=>{this.connect()},this.retryTime).unref(),this.retryTime+=this.retryTime>>8})}resetSession(){this.session=new Promise((t,r)=>{this.sessionResolve=t,this.sessionReject=r})}subscribe(t,r){this.nodeSubscriptions=t,this.replicateTablesByDefault=r,this.emit("subscriptions-updated",t)}unsubscribe(){this.socket.isFinished=!0,this.socket.close(1008,"No longer subscribed")}getRecord(t){return this.session.then(r=>r.getRecord(t))}};a(bh,"replicateOverWS")});function Ac(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(`
17
17
  `)}function $1(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 RO(e){try{let t=Wl(e),n=Eo.Certificate.fromBER(t).extensions?.find(c=>c.extnID==="2.5.29.31");if(!n)return po.debug?.("Certificate has no CRL Distribution Points extension"),[];let s=ho.fromBER(n.extnValue.valueBlock.valueHexView);if(s.offset===-1)throw new Error("Failed to parse ASN.1 structure in CRL Distribution Points extension");let i=new Eo.CRLDistributionPoints({schema:s.result}),o=[];for(let c of i.distributionPoints)if(c.distributionPoint&&Array.isArray(c.distributionPoint)){for(let l of c.distributionPoint)if(l.type===6&&typeof l.value=="string"){let u=l.value;(u.startsWith("http://")||u.startsWith("https://"))&&o.push(u)}}return po.debug?.(`Found ${o.length} CRL distribution points: ${o}`),o}catch(t){return po.warn?.(`Failed to extract CRL distribution points: ${t}`),[]}}function V1(e){try{let t=Wl(e),r=Eo.Certificate.fromBER(t),n=[],s=[];for(let i of r.extensions||[])if(i.extnID==="2.5.29.31")try{let o=ho.fromBER(i.extnValue.valueBlock.valueHexView);if(o.offset!==-1){let c=new Eo.CRLDistributionPoints({schema:o.result});for(let l of c.distributionPoints)if(l.distributionPoint&&Array.isArray(l.distributionPoint)){for(let u of l.distributionPoint)if(u.type===6&&typeof u.value=="string"){let d=u.value;(d.startsWith("http://")||d.startsWith("https://"))&&n.push(d)}}}}catch(o){po.warn?.(`Failed to parse CRL Distribution Points extension: ${o}`)}else if(i.extnID==="1.3.6.1.5.5.7.1.1")try{let o=ho.fromBER(i.extnValue.valueBlock.valueHexView);if(o.offset!==-1&&o.result instanceof ho.Sequence){for(let c of o.result.valueBlock.value)if(c instanceof ho.Sequence&&c.valueBlock.value.length>=2){let l=c.valueBlock.value[0],u=c.valueBlock.value[1];if(l instanceof ho.ObjectIdentifier&&l.valueBlock.toString()==="1.3.6.1.5.5.7.48.1"&&u.idBlock.tagNumber===6){let d=String.fromCharCode(...Array.from(u.valueBlock.valueHexView));(d.startsWith("http://")||d.startsWith("https://"))&&s.push(d)}}}}catch(o){po.warn?.(`Failed to parse Authority Information Access extension: ${o}`)}return po.debug?.(`Found ${n.length} CRL distribution points and ${s.length} OCSP responder URLs`),{crlUrls:n,ocspUrls:s}}catch(t){return po.warn?.(`Failed to extract revocation URLs: ${t}`),{crlUrls:[],ocspUrls:[]}}}function Wl(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 CT(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 bO(e,t){return`${e}:${t}`}function K1(e){try{let t=Wl(e),n=Eo.Certificate.fromBER(t).serialNumber.valueBlock.valueHexView;return Array.from(n).map(s=>s.toString(16).padStart(2,"0")).join("")}catch(t){throw po.error?.(`Failed to extract serial number: ${t}`),new Error(`Failed to extract certificate serial number: ${t.message}`)}}function AO(e){try{let t=Wl(e),r=Eo.Certificate.fromBER(t),n=r.extensions?.find(i=>i.extnID==="2.5.29.35");if(n)try{let i=ho.fromBER(n.extnValue.valueBlock.valueHexView);if(i.offset!==-1){let o=new Eo.AuthorityKeyIdentifier({schema:i.result});if(o.keyIdentifier){let c=o.keyIdentifier.valueBlock.valueHexView;return Array.from(c).map(l=>l.toString(16).padStart(2,"0")).join("")}}}catch(i){po.debug?.(`Failed to parse Authority Key Identifier: ${i}, falling back to hash`)}let s=r.issuer.typesAndValues.map(i=>`${i.type}=${i.value.valueBlock.value}`).join(",");return(0,yO.createHash)("sha256").update(s).digest("hex")}catch(t){throw po.error?.(`Failed to extract issuer key ID: ${t}`),new Error(`Failed to extract issuer key ID: ${t.message}`)}}function OT(){return TO||(TO=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"}]})),TO}var yO,Eo,ho,q1,po,TO,PT=se(()=>{yO=require("node:crypto"),Eo=b(require("pkijs")),ho=b(require("asn1js")),q1=b(sr());Oe();po=(0,q1.loggerWithTag)("cert-verification-utils");a(Ac,"bufferToPem");a($1,"extractCertificateChain");a(RO,"extractCRLDistributionPoints");a(V1,"extractRevocationUrls");a(Wl,"pemToBuffer");a(CT,"createCacheKey");a(bO,"createRevokedCertificateId");a(K1,"extractSerialNumber");a(AO,"extractIssuerKeyId");TO=null;a(OT,"getCertificateCacheTable")});function Y1(e){let{error:t,value:r}=gde.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 Kr,hde,sf,of,IO,Ede,_de,gde,W1=se(()=>{Kr=b(require("joi")),hde="fail-closed",sf={timeout:5e3,cacheTtl:36e5,errorCacheTtl:3e5,failureMode:"fail-closed"},of={timeout:1e4,cacheTtl:864e5,failureMode:"fail-closed",gracePeriod:864e5},IO=Kr.default.string().valid("fail-open","fail-closed"),Ede=Kr.default.alternatives().try(Kr.default.boolean().custom(e=>e===!1?{enabled:!1}:{enabled:!0,...of}),Kr.default.object({enabled:Kr.default.boolean().default(!0),timeout:Kr.default.number().min(1e3).default(of.timeout).messages({"number.min":"CRL timeout must be at least 1000ms (1 second)"}),cacheTtl:Kr.default.number().min(1e3).default(of.cacheTtl).messages({"number.min":"CRL cacheTtl must be at least 1000ms (1 second)"}),failureMode:IO.default(of.failureMode),gracePeriod:Kr.default.number().min(0).default(of.gracePeriod).messages({"number.min":"CRL gracePeriod must be at least 0ms"})})),_de=Kr.default.alternatives().try(Kr.default.boolean().custom(e=>e===!1?{enabled:!1}:{enabled:!0,...sf}),Kr.default.object({enabled:Kr.default.boolean().default(!0),timeout:Kr.default.number().min(1e3).default(sf.timeout).messages({"number.min":"OCSP timeout must be at least 1000ms (1 second)"}),cacheTtl:Kr.default.number().min(1e3).default(sf.cacheTtl).messages({"number.min":"OCSP cacheTtl must be at least 1000ms (1 second)"}),errorCacheTtl:Kr.default.number().min(1e3).default(sf.errorCacheTtl).messages({"number.min":"OCSP errorCacheTtl must be at least 1000ms (1 second)"}),failureMode:IO.default(sf.failureMode)})),gde=Kr.default.object({failureMode:IO.default(hde),crl:Ede.default({enabled:!0,...of}),ocsp:_de.default({enabled:!0,...sf})});a(Y1,"validateAndParseCertificateVerificationConfig")});function rK(e){if(typeof e=="boolean"||e==null){if(e===wO&&NO)return _o.trace?.("Using cached validation error result (primitive) - returning disabled"),!1;if(e===wO&&LT!==null)return _o.trace?.("Using cached certificate verification config (primitive)"),LT;_o.trace?.("Parsing and caching certificate verification config (primitive)"),wO=e;try{return LT=J1(e),NO=null,LT}catch(n){return NO=n,_o.error?.(`Certificate verification config validation failed - defaulting to disabled: ${n.message}`),!1}}if(z1.get(e))return _o.trace?.("Using cached validation error result (object) - returning disabled"),!1;let r=j1.get(e);if(r!==void 0)return _o.trace?.("Using cached certificate verification config (object)"),r;_o.trace?.("Parsing and caching certificate verification config (object)");try{let n=J1(e);return j1.set(e,n),n}catch(n){return z1.set(e,n),_o.error?.(`Certificate verification config validation failed - defaulting to disabled: ${n.message}`),!1}}function J1(e){if(_o.trace?.(`getCertificateVerificationConfig called with: ${JSON.stringify({mtlsConfig:e})}`),!e)return!1;let t=e===!0?void 0:e.certificateVerification;return _o.trace?.(`Certificate verification config: ${JSON.stringify({verificationConfig:t})}`),t==null||t===!1?!1:Y1(t===!0?{}:t)}var Q1,X1,_o,Z1,eK,tK,j1,wO,LT,z1,NO,CO=se(()=>{Q1=b(sr()),X1=b(Rt());W1();_o=(0,Q1.loggerWithTag)("cert-verification-config"),Z1=10080*60*1e3,eK=3e5,tK=`Harper/${X1.packageJson.version} CRL-Client`,j1=new WeakMap,wO=null,LT=null,z1=new WeakMap,NO=null;a(rK,"getCachedCertificateVerificationConfig");a(J1,"getCertificateVerificationConfig")});function Ah(e){return e===sK||e===Sde}function Tde(e){return e===iK||e===oK}function OO(e){return e===sK?iK:oK}function yde(){if(nK)return;nK=!0;let e=jl.CryptoEngine.prototype,t=jl.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 Ah(s.algorithmId)?"UNUSED-EDDSA-BUILTIN-HASH":r.getHashAlgorithm.call(this,s)},e.getAlgorithmByOID=function(...n){let[s]=n;return Ah(s)?{name:OO(s)}:r.getAlgorithmByOID.call(this,...n)},e.getAlgorithmParameters=function(...n){let[s,i]=n;return Tde(s)?{algorithm:{name:s},usages:i==="sign"?["sign"]:["verify"]}:r.getAlgorithmParameters.call(this,...n)},t.getPublicKey=async function(...n){let[,s=jl.getCrypto(!0)]=n,i=this.subjectPublicKeyInfo.algorithm.algorithmId;if(Ah(i)){let o=OO(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(Ah(this.signatureAlgorithm.algorithmId))try{let i=this.toSchema().toBER(!1),o=s.toSchema().toBER(!1),c=new Ih.X509Certificate(Buffer.from(i)),l=new Ih.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(Ah(c)){let l=OO(c);try{let u=this.crypto?.subtle||this.subtle||jl.getCrypto(!0)?.subtle||Ih.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 jl,Ih,sK,Sde,iK,oK,nK,aK=se(()=>{jl=b(require("pkijs")),Ih=require("node:crypto"),sK="1.3.101.112",Sde="1.3.101.113",iK="Ed25519",oK="Ed448",nK=!1;a(Ah,"isEd25519OrEd448");a(Tde,"isEdDSAAlgorithmName");a(OO,"getEdDSAAlgorithmName");a(yde,"applyEd25519Patch");yde()});var dK={};ye(dK,{CRLSignatureVerificationError:()=>wh,performCRLCheck:()=>Ade,verifyCRL:()=>DO});function Rde(){return DT||(DT=OT(),DT.sourcedFrom(af)),DT}function bde(){return vT||(vT=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}]}),vT.sourcedFrom(LO)),vT}function lK(){return PO||(PO=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}]})),PO}async function DO(e,t,r,n){if(r?.enabled===!1)return{valid:!0,status:"disabled",method:"disabled"};try{let s=Ac(e,"CERTIFICATE"),i=Ac(t,"CERTIFICATE"),o=n??RO(s);if(o.length===0)return{valid:!0,status:"no-crl-distribution-points",method:"crl"};let c=CT(s,i,"crl"),l=await Rde().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 Ade(e,t,r,n){let s=n??RO(e);if(s.length===0)return{status:"good"};let i=K1(e),o=AO(t),c=bO(o,i);try{let u=await lK().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 Ide(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 Ide(e,t,r){let n=Date.now();for(let s of e)try{let i=bde(),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 uK(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 wh)throw i}return{upToDate:!1,reason:"no-current-crl-data"}}async function uK(e,t,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let i=await fetch(e,{signal:n.signal,headers:{"User-Agent":tK}});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(Wl(l)):c=o;let u=MT.CertificateRevocationList.fromBER(c),d=MT.Certificate.fromBER(Wl(t)),f=await u.verify({issuerCertificate:d});if(!f){let _=`CRL signature verification failed for: ${e}`;throw Pr.error?.(_),new wh(_)}let m=u.thisUpdate.value.getTime(),p=u.nextUpdate?.value.getTime()??m+Z1,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 wde(u,t,e,p).catch(_=>{Pr.error?.(`Error processing revoked certificates: ${_}`)}),E}finally{clearTimeout(s)}}async function wde(e,t,r,n){let s=lK(),i=AO(t),o=r;try{await Nde(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=bO(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 Nde(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 MT,cK,wh,Pr,DT,LO,vT,PO,vO=se(()=>{MT=b(require("pkijs")),cK=b(sr());Oe();ji();PT();CO();MO();wh=class extends Error{static{a(this,"CRLSignatureVerificationError")}constructor(t){super(t),this.name="CRLSignatureVerificationError"}},Pr=(0,cK.loggerWithTag)("crl-verification");a(Rde,"getCertificateCacheTable");LO=class extends Xt{static{a(this,"CertificateRevocationListSource")}async get(t){let n=this.getContext()?.requestContext;if(!n?.distributionPoint||!n?.issuerPem)throw new Error(`No CRL data provided for cache key: ${t}`);let{distributionPoint:s,issuerPem:i,config:o}=n;try{let c=await uK(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()+eK;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(bde,"getCRLCacheTable");a(lK,"getRevokedCertificateTable");a(DO,"verifyCRL");a(Ade,"performCRLCheck");a(Ide,"checkCRLFreshness");a(uK,"downloadAndParseCRL");a(wde,"processRevokedCertificates");a(Nde,"clearExistingCRLEntries")});async function Cde(){UO||(UO=(await Promise.resolve().then(()=>(vO(),dK))).performCRLCheck),xO||(xO=(await Promise.resolve().then(()=>(BO(),mK))).performOCSPCheck)}var fK,j0e,UO,xO,af,MO=se(()=>{ji();fK=b(sr()),j0e=(0,fK.loggerWithTag)("cert-verification-source");a(Cde,"loadVerificationFunctions");af=class extends Xt{static{a(this,"CertificateVerificationSource")}async get(t){let r=t.id,s=this.getContext()?.requestContext;if(!s||!s.certPem||!s.issuerPem)return null;let{certPem:i,issuerPem:o,ocspUrls:c,config:l}=s,u;r.startsWith("crl:")?u="crl":r.startsWith("ocsp:")?u="ocsp":u="unknown",await Cde();let d,f;if(u==="crl"){f=l.crl;let p=s.distributionPoint?[s.distributionPoint]:void 0;d=await UO(i,o,f,p)}else if(u==="ocsp")f=l.ocsp,d=await xO(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 mK={};ye(mK,{performOCSPCheck:()=>Pde,verifyOCSP:()=>FO});function Ode(){return xT||(xT=OT(),xT.sourcedFrom(af)),xT}async function FO(e,t,r,n){if(r?.enabled===!1)return{valid:!0,status:"disabled",method:"disabled"};try{let s=Ac(e,"CERTIFICATE"),i=Ac(t,"CERTIFICATE"),o=CT(s,i,"ocsp"),c=await Ode().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"}:(UT.warn?.("OCSP cache fetch failed, allowing connection (fail-open mode)"),{valid:!0,status:"error-allowed",method:"ocsp"});let l=c,u=c.wasLoadedFromSource?.();return UT.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 UT.error?.(`OCSP verification error: ${s}`),r.failureMode==="fail-closed"?{valid:!1,status:"error",error:s.message,method:"ocsp"}:(UT.warn?.("OCSP check failed, allowing connection (fail-open mode)"),{valid:!0,status:"error-allowed",method:"ocsp"})}}async function Pde(e,t,r,n){try{let s=await(0,pK.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 pK,hK,UT,xT,BO=se(()=>{aK();pK=require("easy-ocsp"),hK=b(sr());PT();MO();UT=(0,hK.loggerWithTag)("ocsp-verification");a(Ode,"getCertificateCacheTable");a(FO,"verifyOCSP");a(Pde,"performOCSPCheck")});async function cf(e,t){an.debug?.(`verifyCertificate called for: ${e.subject?.CN||"unknown"}`);let r=rK(t);if(r===!1)return an.debug?.("Certificate verification disabled"),{valid:!0,status:"disabled",method:"disabled"};let n=$1(e);if(an.trace?.(`Certificate chain length: ${n.length}`),n.length<2||!n[0].issuer)return an.debug?.("Certificate chain insufficient for revocation checking - need certificate and issuer"),{valid:!0,status:"no-issuer-cert",method:"disabled"};let s=Ac(n[0].cert,"CERTIFICATE"),{crlUrls:i,ocspUrls:o}=V1(s);if(an.debug?.(`Certificate extensions: CRL distribution points=${i.length}, OCSP URLs=${o.length}`),i.length>0)if(r.crl.enabled)try{an.debug?.("Attempting CRL verification");let c=await DO(n[0].cert,n[0].issuer,r.crl,i);if(c.status==="good"||c.status==="revoked")return an.debug?.(`CRL verification result: ${c.status}`),c;an.debug?.(`CRL verification inconclusive: ${c.status}, trying OCSP fallback`)}catch(c){an.warn?.(`CRL verification failed: ${c}`)}else an.debug?.("Skipping CRL - disabled in configuration");else an.debug?.("Skipping CRL - no distribution points in certificate");if(o.length>0)if(r.ocsp.enabled)try{an.debug?.("Attempting OCSP verification");let c=await FO(n[0].cert,n[0].issuer,r.ocsp,o);return an.debug?.(`OCSP verification result: ${c.status}`),c}catch(c){an.warn?.(`OCSP verification failed: ${c}`)}else an.debug?.("Skipping OCSP - disabled in configuration");else an.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 EK,an,BT=se(()=>{EK=b(sr());PT();CO();BO();vO();an=(0,EK.loggerWithTag)("cert-verification");a(cf,"verifyCertificate")});var oa={};ye(oa,{buildReplicationMtlsConfig:()=>IK,clearThisNodeName:()=>kde,disableReplication:()=>Mde,enabledDatabases:()=>Rc,forEachReplicatedDatabase:()=>_c,getThisNodeId:()=>NT,getThisNodeName:()=>tt,getThisNodeUrl:()=>gc,hostnameToUrl:()=>qT,lastTimeInAuditStore:()=>mh,monitorNodeCAs:()=>wK,replicateOperation:()=>Gde,replicationCertificateAuthorities:()=>aa,sendOperationToNode:()=>Nh,servers:()=>Dde,setReplicator:()=>CK,start:()=>vde,startOnMainThread:()=>QC,subscribeToNode:()=>_h,unsubscribeFromNode:()=>fT,urlToNodeName:()=>Si});function IK(e){return e?.mtls&&typeof e.mtls=="object"?e.mtls:!0}function vde(e){if(!e.port&&!e.securePort&&(e.port=Ks.default.get(x.OPERATIONSAPI_NETWORK_PORT),e.securePort=Ks.default.get(x.OPERATIONSAPI_NETWORK_SECUREPORT)),!tt())throw new Error("Can not load replication without a url (see replication.url in the config)");let t=new Map;for(let i of hh(e))t.set(Si(i.url),i);Ude(e);let r=IK(e);e={isOperationsServer:!0,maxPayload:10*1024*1024*1024,...e,mtls:r};let n=Ue.ws(async(i,o,c,l)=>{if(wt.debug("Incoming WS connection received "+o.url),o.headers.get("sec-websocket-protocol")!=="harperdb-replication-v1")return l(i,o,c);i._socket.unref(),bh(i,e,c.then(()=>o?.user)),i.on("error",u=>{u.code!=="ECONNREFUSED"&&wt.error("Error in connection to "+this.url,u.message)})},e);e.runFirst=!0,Ue.http(async(i,o)=>{if(i.isWebSocket&&i.headers.get("Sec-WebSocket-Protocol")==="harperdb-replication-v1"){wt.debug("Incoming replication WS connection received, authorized: "+i.authorized),!i.authorized&&i._nodeRequest.socket.authorizationError&&wt.error(`Incoming client connection from ${i.ip} did not have valid certificate, you may need turn on enableRootCAs in the config if you are using a publicly signed certificate, or add the CA to the server's trusted CAs`,i._nodeRequest.socket.authorizationError);let c=Gt().primaryStore;if(i.authorized&&i.peerCertificate.subjectaltname){let l=(0,bK.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 cf(i.peerCertificate,e.mtls);if(!d.valid){wt.warn("Certificate verification failed:",d.status,"for node",u.name,"certificate serial number",i.peerCertificate.serialNumber);return}if(u?.revoked_certificates?.includes(i.peerCertificate.serialNumber)){wt.warn("Revoked certificate used in attempt to connect to node",u.name,"certificate serial number",i.peerCertificate.serialNumber);return}else i.user=u}else wt.warn(`No node found for certificate common name/SANs: ${l}, available nodes are ${Array.from(c.getRange({}).filter(({value:d})=>d).map(({key:d})=>d)).join(", ")} and routes ${Array.from(t.keys()).join(", ")}, connection will require credentials.`)}else{let l=c.get(i.ip)||t.get(i.ip);l?i.user=l:wt.warn(`No node found for IP address ${i.ip}, available nodes are ${Array.from(new Set([...c.getKeys(),...t.keys()])).join(", ")}, connection will require credentials.`)}}return o(i)},e);let s=[];for(let i of n)if(i.secureContexts){let o=a(()=>{let c=new Set(i.secureContexts.values());i.defaultContext&&c.add(i.defaultContext);for(let l of c)try{let u=Array.from(aa);l.options.availableCAs&&u.push(...l.options.availableCAs.values());let d={...l.options,ca:u};l.updatedContext=GT.createSecureContext(d)}catch(u){wt.error("Error creating replication TLS config",u)}},"updateContexts");i.secureContextsListeners.push(o),s.push(o),Ks.default.get(x.REPLICATION_ENABLEROOTCAS)!==!1&&o()}wK(()=>{for(let i of s)i()})}function wK(e){let t=0;Jd(r=>{r?.ca&&(aa.add(r.ca),aa.size!==t&&(t=aa.size,e?.()))})}function Mde(e=!0){AK=e}function Ude(e){AK||(lt(),Rc=e.databases,_c(e,(t,r)=>{if(!t){let n=e.databaseSubscriptions||bc;for(let[s,i]of kT){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];CK(r,s,e),gO.get(s)?.forEach(i=>i(s))}}))}function CK(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 NK extends Xt{static{a(this,"Replicator")}static connection;static subscription;static async subscribe(){let i=r.databaseSubscriptions||bc,o=i.get(e),c=o?.tableById||[];c[t.tableId]=t;let l=o?.ready;if(wt.trace("Setting up replicator subscription to database",e),!o?.auditStore)return this.subscription=o=new 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=Bde(h,NK.subscription,e);if(E?.isConnected){let _=zd(t.auditStore,e,h)[IT];(!d||_<m)&&(d=E,f=h,m=_)}}if(!d)throw l||new yK.ServerError(`No connection to any other nodes are available: ${c}`,502);let p={requestId:Lde++,table:t,entry:i,id:i.key};u.add(f);try{return await d.getRecord(p)}catch(h){if(d.isConnected)throw h;wt.warn("Error in load from node",HT,h),l||(l=h)}}while(!0)}}}static isReplicator=!0},{intermediateSource:!0})}function xde(e,t,r,n,s,i){let o=t+"-"+e,c=kT.get(o);c||(c=new Map,kT.set(o,c));let l=c.get(n);if(l)return l;if(r)return c.set(n,l=new nf(t,r,n,s,i)),l.connect(),l.once("finished",()=>c.delete(n)),l}function Bde(e,t,r){let n=_K.get(e);n||(n=new Map,_K.set(e,n));let s=n.get(r);if(s)return s;let i=Gt().primaryStore.get(e);return i?.url&&(s=new nf(i.url,t,r,e,i.authorization),n.set(r,s),s.connect(),s.once("finished",()=>n.delete(r))),s}async function Nh(e,t,r){r||(r={}),r.serverName=e.name;let n=await wT(e.url,r),s=bh(n,{},{});return new Promise((i,o)=>{n.on("open",()=>{wt.debug("Sending operation connection to "+e.url+" opened",t),i(s.sendOperation(t))}),n.on("error",c=>{o(c)}),n.on("close",c=>{wt.info("Sending operation connection to "+e.url+" closed",c)})}).finally(()=>{n.close()})}function _h(e){try{RK.isMainThread&&wt.warn("Subscribing on main thread (should not happen in multi-threaded instance)",e.nodes[0].url,e.database);let t=bc.get(e.database);if(!t){let n;t=new Promise(s=>{wt.info("Waiting for subscription to database "+e.database),n=s}),t.ready=n,bc.set(e.database,t)}let r=xde(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=>ph(n,e.database)),e.replicateByDefault)}catch(t){wt.error("Error in subscription to node",e.nodes[0]?.url,t)}}async function fT({url:e,nodes:t,database:r}){wt.trace("Unsubscribing from node",e,r,"nodes",Array.from(Gt().primaryStore.getRange({})));let n=e+"-"+(t[0]?.url??e),s=kT.get(n);if(s){let i=s.get(r);i&&(i.unsubscribe(),s.delete(r))}}function Fde(){if(kO!==void 0)return kO;let e=Ks.default.get(x.OPERATIONSAPI_TLS_CERTIFICATE)||Ks.default.get(x.TLS_CERTIFICATE);if(e)return kO=new SK.X509Certificate((0,TK.readFileSync)(e)).subject?.match(/CN=(.*)/)?.[1]??null}function tt(){return HT||(HT=Ks.default.get("replication_hostname")??Si(Ks.default.get("replication_url"))??Fde()??gK("operationsapi_network_secureport")??gK("operationsapi_network_port")??"127.0.0.1")}function kde(){HT=void 0}function gK(e){let t=Ks.default.get(e),r=t?.lastIndexOf?.(":");if(r>0)return t.slice(0,r)}function FT(e){let t=Ks.default.get(e),r=t?.lastIndexOf?.(":");return r>0?+t.slice(r+1).replace(/[\[\]]/g,""):+t}function NT(e){return fh(e)?.[tt()]}function gc(){let e=Ks.default.get("replication_url");return e||qT(tt())}function qT(e){let t=FT("replication_port");if(t)return`ws://${e}:${t}`;if(t=FT("replication_secureport"),t)return`wss://${e}:${t}`;if(t=FT("operationsapi_network_port"),t)return`ws://${e}:${t}`;if(t=FT("operationsapi_network_secureport"),t)return`wss://${e}:${t}`}function Si(e){if(e)return new URL(e).hostname}function _c(e,t){for(let n of Object.getOwnPropertyNames(Me))r(n);return th(n=>{r(n)}),Gl((n,s)=>{r(n.databaseName)});function r(n){let s=Me[n];wt.trace("Checking replication status of ",n,e?.databases),e?.databases===void 0||e.databases==="*"||e.databases.includes(n)||e.databases.some?.(i=>i.name===n)||!s?t(s,n,!0):Hde(n)&&t(s,n,!1)}a(r,"forDatabase")}function Hde(e){let t=Me[e];for(let r in t)if(t[r].replicate)return!0}function mh(e){for(let t of e.getKeys({limit:1,reverse:!0}))return t}async function Gde(e){let t={message:""};if(e.replicated){e.replicated=!1,wt.trace?.("Replicating operation",e.operation,"to nodes",Ue.nodes.map(n=>n.name));let r=await Promise.allSettled(Ue.nodes.map(n=>Nh(n,e)));t.replicated=r.map((n,s)=>{let i=n.status==="rejected"?{status:"failed",reason:n.reason.toString()}:n.value;return i.node=Ue.nodes[s]?.name,i})}return t}var Ks,wt,SK,TK,GT,yK,RK,bK,AK,Lde,Dde,aa,Rc,kT,_K,kO,HT,Ss=se(()=>{Oe();ji();Fu();SO();Hr();Ks=b(fe()),wt=b(Q()),SK=require("crypto");BT();TK=require("fs");gh();Qd();G();JC();GT=b(require("node:tls")),yK=b(Ee()),RK=require("worker_threads"),bK=b(ys()),Lde=1,Dde=[],aa=Ks.default.get(x.REPLICATION_ENABLEROOTCAS)!==!1?new Set(GT.rootCertificates):new Set;a(IK,"buildReplicationMtlsConfig");a(vde,"start");a(wK,"monitorNodeCAs");a(Mde,"disableReplication");a(Ude,"assignReplicationSource");a(CK,"setReplicator");kT=new Map;a(xde,"getSubscriptionConnection");_K=new Map;a(Bde,"getRetrievalConnectionByName");a(Nh,"sendOperationToNode");a(_h,"subscribeToNode");a(fT,"unsubscribeFromNode");a(Fde,"getCommonNameFromCert");a(tt,"getThisNodeName");a(kde,"clearThisNodeName");Object.defineProperty(Ue,"hostname",{get(){return tt()}});a(gK,"getHostFromListeningPort");a(FT,"getPortFromListeningPort");a(NT,"getThisNodeId");Ue.replication={getThisNodeId:NT,exportIdMapping:fh};a(gc,"getThisNodeUrl");a(qT,"hostnameToUrl");a(Si,"urlToNodeName");a(_c,"forEachReplicatedDatabase");a(Hde,"hasExplicitlyReplicatedTable");a(mh,"lastTimeInAuditStore");a(Gde,"replicateOperation")});var WT=M((gBe,vK)=>{"use strict";var lf=xV(),{validateBySchema:Ch}=pt(),{commonValidators:uf,schemaRegex:HO}=Ji(),gr=require("joi"),qde=Q(),$de=require("uuid").v4,KT=Qo(),df=(G(),v(j)),Vde=require("util"),Ic=fs(),{handleHDBError:ca,hdbErrors:Kde,ClientError:zl}=Ee(),{HDB_ERROR_MSGS:$T,HTTP_STATUS_CODES:la}=Kde,{SchemaEventMsg:YT}=ls(),OK=Sr(),{getDatabases:Yde}=(Oe(),v(mt)),{transformReq:ff}=ae(),{replicateOperation:PK}=(Ss(),v(oa)),{cleanupOrphans:Wde}=(ss(),v(J_)),VT=gr.string().min(1).max(uf.schema_length.maximum).pattern(HO).messages({"string.pattern.base":"{:#label} "+uf.schema_format.message}),jde=gr.string().min(1).max(uf.schema_length.maximum).pattern(HO).messages({"string.pattern.base":"{:#label} "+uf.schema_format.message}).required(),zde=gr.string().min(1).max(uf.schema_length.maximum).pattern(HO).messages({"string.pattern.base":"{:#label} "+uf.schema_format.message,"any.required":"'primary_key' is required","string.base":"'primary_key' must be a string"}).required();vK.exports={createSchema:Jde,createSchemaStructure:LK,createTable:Qde,createTableStructure:DK,createAttribute:rfe,dropSchema:Xde,dropTable:Zde,dropAttribute:efe,getBackup:nfe,cleanupOrphanBlobs:sfe};async function Jde(e){let t=await LK(e);return KT.signalSchemaChange(new YT(process.pid,e.operation,e.schema)),t}a(Jde,"createSchema");async function LK(e){let t=Ch(e,gr.object({database:VT,schema:VT}));if(t)throw new zl(t.message);if(ff(e),!await lf.checkSchemaExists(e.schema))throw ca(new Error,$T.SCHEMA_EXISTS_ERR(e.schema),la.BAD_REQUEST,df.LOG_LEVELS.ERROR,$T.SCHEMA_EXISTS_ERR(e.schema),!0);return await Ic.createSchema(e),`database '${e.schema}' successfully created`}a(LK,"createSchemaStructure");async function Qde(e){return ff(e),e.hash_attribute=e.primary_key??e.hash_attribute,await DK(e)}a(Qde,"createTable");async function DK(e){let t=Ch(e,gr.object({database:VT,schema:VT,table:jde,residence:gr.array().items(gr.string().min(1)).optional(),hash_attribute:zde}));if(t)throw new zl(t.message);if(!await lf.checkSchemaTableExists(e.schema,e.table))throw ca(new Error,$T.TABLE_EXISTS_ERR(e.schema,e.table),la.BAD_REQUEST,df.LOG_LEVELS.ERROR,$T.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:$de(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await Ic.createTable(n,e);else throw ca(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",la.BAD_REQUEST);else await Ic.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(DK,"createTableStructure");async function Xde(e){let t=Ch(e,gr.object({database:gr.string(),schema:gr.string()}).or("database","schema").messages({"object.missing":"'database' is required"}));if(t)throw new zl(t.message);ff(e);let r=await lf.checkSchemaExists(e.schema);if(r)throw ca(new Error,r,la.NOT_FOUND,df.LOG_LEVELS.ERROR,r,!0);let n=await lf.schemaDescribe.describeSchema({schema:e.schema}),s=Object.keys(global.hdb_schema[e.schema]);await Ic.dropSchema(e),KT.signalSchemaChange(new YT(process.pid,e.operation,e.schema)),await OK.purgeSchemaTableStreams(e.schema,s);let i=await PK(e);return i.message=`successfully deleted '${e.schema}'`,i}a(Xde,"dropSchema");async function Zde(e){let t=Ch(e,gr.object({database:gr.string(),schema:gr.string(),table:gr.string().required()}));if(t)throw new zl(t.message);ff(e);let r=await lf.checkSchemaTableExists(e.schema,e.table);if(r)throw ca(new Error,r,la.NOT_FOUND,df.LOG_LEVELS.ERROR,r,!0);await Ic.dropTable(e),await OK.purgeTableStream(e.schema,e.table);let n=await PK(e);return n.message=`successfully deleted table '${e.schema}.${e.table}'`,n}a(Zde,"dropTable");async function efe(e){let t=Ch(e,gr.object({database:gr.string(),schema:gr.string(),table:gr.string().required(),attribute:gr.string().required()}));if(t)throw new zl(t.message);ff(e);let r=await lf.checkSchemaTableExists(e.schema,e.table);if(r)throw ca(new Error,r,la.NOT_FOUND,df.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw ca(new Error,"You cannot drop a hash attribute",la.BAD_REQUEST,void 0,void 0,!0);if(df.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw ca(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,la.BAD_REQUEST,void 0,void 0,!0);try{return await Ic.dropAttribute(e),tfe(e),KT.signalSchemaChange(new YT(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw qde.error(`Got an error deleting attribute ${Vde.inspect(e)}.`),n}}a(efe,"dropAttribute");function tfe(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(tfe,"dropAttributeFromGlobal");async function rfe(e){ff(e);let t=Yde()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw ca(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,la.BAD_REQUEST,void 0,void 0,!0);return await Ic.createAttribute(e),KT.signalSchemaChange(new YT(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(rfe,"createAttribute");function nfe(e){return Ic.getBackup(e)}a(nfe,"getBackup");function sfe(e){if(!e.database)throw new zl('Must provide "database" name for search for orphaned blobs');if(!databases[e.database])throw new zl(`Unknown database '${e.database}'`);return Wde(databases[e.database],e.database),{message:"Orphaned blobs cleanup started, check logs for progress"}}a(sfe,"cleanupOrphanBlobs")});var UK=M((TBe,MK)=>{"use strict";var{OPERATIONS_ENUM:ife}=(G(),v(j)),GO=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=ife.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};MK.exports=GO});var qO=M((bBe,HK)=>{"use strict";var ofe=fs(),RBe=UK(),jT=ae(),zT=(G(),v(j)),afe=fe(),{handleHDBError:xK,hdbErrors:cfe}=Ee(),{HDB_ERROR_MSGS:BK,HTTP_STATUS_CODES:FK}=cfe,lfe=Object.values(zT.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),kK="To use this operation audit log must be enabled in harperdb-config.yaml";HK.exports=ufe;async function ufe(e){if(jT.isEmpty(e.schema))throw new Error(BK.SCHEMA_REQUIRED_ERR);if(jT.isEmpty(e.table))throw new Error(BK.TABLE_REQUIRED_ERR);if(!afe.get(zT.CONFIG_PARAMS.LOGGING_AUDITLOG))throw xK(new Error,kK,FK.BAD_REQUEST,zT.LOG_LEVELS.ERROR,kK,!0);let t=jT.checkSchemaTableExist(e.schema,e.table);if(t)throw xK(new Error,t,FK.NOT_FOUND,zT.LOG_LEVELS.ERROR,t,!0);if(!jT.isEmpty(e.search_type)&&lfe.indexOf(e.search_type)<0)throw new Error(`Invalid searchType '${read_audit_log_object.search_type}'`);return await ofe.readAuditLog(e)}a(ufe,"readAuditLog")});var qK=M((IBe,GK)=>{"use strict";var{OPERATIONS_ENUM:dfe}=(G(),v(j)),$O=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=dfe.GET_BACKUP,this.schema=t,this.table=r}};GK.exports=$O});var KK=M((OBe,VK)=>{"use strict";var ffe=fs(),NBe=qK(),VO=ae(),mfe=(G(),v(j)),CBe=fe(),{handleHDBError:pfe,hdbErrors:hfe}=Ee(),{HDB_ERROR_MSGS:$K,HTTP_STATUS_CODES:Efe}=hfe;VK.exports=_fe;async function _fe(e){if(VO.isEmpty(e.schema))throw new Error($K.SCHEMA_REQUIRED_ERR);if(VO.isEmpty(e.table))throw new Error($K.TABLE_REQUIRED_ERR);let t=VO.checkSchemaTableExist(e.schema,e.table);if(t)throw pfe(new Error,t,Efe.NOT_FOUND,mfe.LOG_LEVELS.ERROR,t,!0);return await ffe.getBackup(readAuditLogObject)}a(_fe,"getBackup")});var jK=M((LBe,WK)=>{"use strict";var gfe=fe(),ua=require("joi"),Sfe=pt(),YK=require("moment"),Tfe=require("fs-extra"),YO=require("path"),yfe=require("lodash"),Oh=(G(),v(j)),{LOG_LEVELS:Jl}=(G(),v(j)),Rfe="YYYY-MM-DD hh:mm:ss",bfe=YO.resolve(__dirname,"../logs");WK.exports=function(e){return Sfe.validateBySchema(e,Afe)};var Afe=ua.object({from:ua.custom(KO),until:ua.custom(KO),to:ua.custom(KO),level:ua.valid(Jl.NOTIFY,Jl.FATAL,Jl.ERROR,Jl.WARN,Jl.INFO,Jl.DEBUG,Jl.TRACE),order:ua.valid("asc","desc"),limit:ua.number().min(1),start:ua.number().min(0),log_name:ua.custom(Ife)});function KO(e,t){if(YK(e,YK.ISO_8601).format(Rfe)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(KO,"validateDatetime");function Ife(e,t){if(yfe.invert(Oh.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=gfe.get(Oh.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?Oh.LOG_NAMES.HDB:e,i=s===Oh.LOG_NAMES.INSTALL?YO.join(bfe,Oh.LOG_NAMES.INSTALL):YO.join(n,s);return Tfe.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(Ife,"validateReadLogPath")});var jO=M((vBe,JK)=>{"use strict";var JT=(G(),v(j)),wfe=Q(),Nfe=fe(),Cfe=jK(),WO=require("path"),zK=require("fs-extra"),{once:Ofe}=require("events"),{handleHDBError:Pfe,hdbErrors:Lfe}=Ee(),{PACKAGE_ROOT:Dfe}=Rt(),{replicateOperation:vfe}=(Ss(),v(oa)),Mfe=WO.join(Dfe,"logs"),Ufe=1e3,xfe=200;JK.exports=Bfe;async function Bfe(e){let t=Cfe(e);if(t)throw Pfe(t,t.message,Lfe.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=vfe(e),n=Nfe.get(JT.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?JT.LOG_NAMES.HDB:e.log_name,i=s===JT.LOG_NAMES.INSTALL?WO.join(Mfe,JT.LOG_NAMES.INSTALL):WO.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?Ufe: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(zK.statSync(i).size-(E+5)*xfe,0));let R=zK.createReadStream(i,{start:_});R.on("error",q=>{wfe.error(q)});let S=0,y=[],w="",I;R.on("data",q=>{let k=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d.]+Z) \[(.+?)]: /g;q=w+q;let z=0,Y;for(;(Y=k.exec(q))&&!R.destroyed;){I&&(I.message=q.slice(z,Y.index),H(I));let[ce,de,te]=Y,Se=te.split("] ["),Ne=Se[0],Ke=Se[1];Se.splice(0,2),I={timestamp:de,thread:Ne,level:Ke,tags:Se,message:""},z=Y.index+ce.length}w=q.slice(z)}),R.on("end",q=>{R.destroyed||I&&(I.message=w.trim(),H(I))}),R.resume();function H(q){let k,z,Y;switch(!0){case(o&&l&&d):k=new Date(q.timestamp),z=new Date(u),Y=new Date(f),q.level===c&&k>=z&&k<=Y&&S<h?S++:q.level===c&&k>=z&&k<=Y&&(go(q,p,y),S++,S===E&&R.destroy());break;case(o&&l):k=new Date(q.timestamp),z=new Date(u),q.level===c&&k>=z&&S<h?S++:q.level===c&&k>=z&&(go(q,p,y),S++,S===E&&R.destroy());break;case(o&&d):k=new Date(q.timestamp),Y=new Date(f),q.level===c&&k<=Y&&S<h?S++:q.level===c&&k<=Y&&(go(q,p,y),S++,S===E&&R.destroy());break;case(l&&d):k=new Date(q.timestamp),z=new Date(u),Y=new Date(f),k>=z&&k<=Y&&S<h?S++:k>=z&&k<=Y&&(go(q,p,y),S++,S===E&&R.destroy());break;case o:q.level===c&&S<h?S++:q.level===c&&(go(q,p,y),S++,S===E&&R.destroy());break;case l:k=new Date(q.timestamp),z=new Date(u),k>=z&&S<h?S++:k>=z&&S>=h&&(go(q,p,y),S++,S===E&&R.destroy());break;case d:k=new Date(q.timestamp),Y=new Date(f),k<=Y&&S<h?S++:k<=Y&&S>=h&&(go(q,p,y),S++,S===E&&R.destroy());break;default:S<h?S++:(go(q,p,y),S++,S===E&&R.destroy())}}a(H,"onLogMessage"),await Ofe(R,"close");let X=await r;if(X.replicated){for(let q of y)q.node=server.hostname;for(let q of X.replicated){let k=q.node;if(q.status==="failed")go({timestamp:new Date().toISOString(),level:"error",node:k,message:`Error retrieving logs: ${q.reason}`},p,y);else for(let z of q.results)z.node=k,go(z,p,y)}}return y}a(Bfe,"readLog");function go(e,t,r){t==="desc"?Ffe(e,r):t==="asc"?kfe(e,r):r.push(e)}a(go,"pushLineToResult");function Ffe(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(Ffe,"insertDescending");function kfe(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(kfe,"insertAscending")});var QT=M((kBe,eY)=>{"use strict";var zO=require("joi"),{string:mf,boolean:QK,date:Hfe}=zO.types(),Gfe=pt(),{validateSchemaExists:UBe,validateTableExists:xBe,validateSchemaName:BBe}=Ji(),qfe=(G(),v(j)),$fe=Lt(),XK=fe();XK.initSync();var FBe=mf.invalid(XK.get(qfe.CONFIG_PARAMS.CLUSTERING_NODENAME)??"node_name").pattern($fe.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),ZK={operation:mf.valid("add_node","update_node","set_node_replication"),node_name:mf.optional(),subscriptions:zO.array().items({table:mf.optional(),schema:mf.optional(),database:mf.optional(),subscribe:QK.required(),publish:QK.required().custom(Kfe),start_time:Hfe.iso()})};function Vfe(e){return Gfe.validateBySchema(e,zO.object(ZK))}a(Vfe,"addUpdateNodeValidator");function Kfe(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(Kfe,"checkForFalsy");eY.exports={addUpdateNodeValidator:Vfe,validationSchema:ZK}});var pf=M((GBe,tY)=>{"use strict";var JO=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},QO=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};tY.exports={Node:JO,NodeSubscription:QO}});var nY=M(($Be,rY)=>{"use strict";var Yfe=(G(),v(j)).OPERATIONS_ENUM,XO=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=Yfe.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};rY.exports=XO});var Ph=M((KBe,sY)=>{"use strict";var ZO=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},eP=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)}};sY.exports={RemotePayloadObject:ZO,RemotePayloadSubscription:eP}});var oY=M((WBe,iY)=>{"use strict";var tP=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}};iY.exports=tP});var cY=M((ZBe,aY)=>{"use strict";var Wfe=oY(),zBe=Jt(),JBe=Et(),jfe=Q(),{getSchemaPath:QBe,getTransactionAuditStorePath:XBe}=bt(),{getDatabases:zfe}=(Oe(),v(mt));aY.exports=Jfe;async function Jfe(e){let t=new Wfe;try{let r=zfe()[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){jfe.warn(`unable to stat table dbi due to ${r}`)}return t}a(Jfe,"lmdbGetTableSize")});var uY=M((tFe,lY)=>{"use strict";var rP=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}};lY.exports=rP});var Dh=M((aFe,pY)=>{"use strict";var Qfe=require("fs-extra"),Xfe=require("path"),Rn=require("systeminformation"),wc=Q(),dY=Sr(),nFe=Lt(),hf=(G(),v(j)),Zfe=cY(),eme=$l(),{getThreadInfo:fY}=st(),Lh=fe();Lh.initSync();var tme=uY(),{openEnvironment:sFe}=Et(),{getSchemaPath:iFe}=bt(),{database:oFe,databases:nP}=(Oe(),v(mt)),XT;pY.exports={getHDBProcessInfo:aP,getNetworkInfo:lP,getDiskInfo:cP,getMemoryInfo:oP,getCPUInfo:iP,getTimeInfo:sP,getSystemInformation:uP,systemInformation:rme,getTableSize:dP,getMetrics:fP};function sP(){return Rn.time()}a(sP,"getTimeInfo");async function iP(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:l,cache:u,...d}=await Rn.cpu();d.cpu_speed=await Rn.cpuCurrentSpeed();let{rawCurrentload:f,rawCurrentloadIdle:m,rawCurrentloadIrq:p,rawCurrentloadNice:h,rawCurrentloadSystem:E,rawCurrentloadUser:_,cpus:R,...S}=await Rn.currentLoad();return S.cpus=[],R.forEach(y=>{let{rawLoad:w,rawLoadIdle:I,rawLoadIrq:H,rawLoadNice:X,rawLoadSystem:q,rawLoadUser:k,...z}=y;S.cpus.push(z)}),d.current_load=S,d}catch(e){return wc.error(`error in getCPUInfo: ${e}`),{}}}a(iP,"getCPUInfo");async function oP(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await Rn.mem();return Object.assign(s,process.memoryUsage())}catch(e){return wc.error(`error in getMemoryInfo: ${e}`),{}}}a(oP,"getMemoryInfo");async function aP(){let e={core:[],clustering:[]};try{let t=await Rn.processes(),r;try{r=Number.parseInt(await Qfe.readFile(Xfe.join(Lh.get(hf.CONFIG_PARAMS.ROOTPATH),hf.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===hf.NODE_ERROR_CODES.ENOENT)wc.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 wc.error(`error in getHDBProcessInfo: ${t}`),e}}a(aP,"getHDBProcessInfo");async function cP(){let e={};try{if(!Lh.get(hf.CONFIG_PARAMS.OPERATIONSAPI_SYSINFO_DISK))return e;let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await Rn.disksIO();e.io=i;let{rxSec:o,txSec:c,wxSec:l,...u}=await Rn.fsStats();return e.read_write=u,e.size=await Rn.fsSize(),e}catch(t){return wc.error(`error in getDiskInfo: ${t}`),e}}a(cP,"getDiskInfo");async function lP(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return Lh.get(hf.CONFIG_PARAMS.OPERATIONSAPI_SYSINFO_NETWORK)&&(e.default_interface=await Rn.networkInterfaceDefault(),e.latency=await Rn.inetChecksite("google.com"),(await Rn.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 Rn.networkStats()).forEach(n=>{let{rxSec:s,txSec:i,ms:o,...c}=n;e.stats.push(c)})),e}catch(t){return wc.error(`error in getNetworkInfo: ${t}`),e}}a(lP,"getNetworkInfo");async function uP(){if(XT!==void 0)return XT;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await Rn.osInfo();e=c;let l=await Rn.versions("node, npm");return e.node_version=l.node,e.npm_version=l.npm,XT=e,XT}catch(t){return wc.error(`error in getSystemInformation: ${t}`),e}}a(uP,"getSystemInformation");async function dP(){let e=[],t=await eme.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await Zfe(n));return e}a(dP,"getTableSize");async function fP(){let e={};for(let t in nP){let r=e[t]={},n=r.tables={};for(let s in nP[t])try{let i=nP[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){wc.notify(`Error getting stats for table ${s}: ${i}`)}}return e}a(fP,"getMetrics");async function mY(){if(Lh.get(hf.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await dY.getNATSReferences(),t=await dY.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(mY,"getNatsStreamInfo");async function rme(e){let t=new tme;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await uP(),t.time=sP(),t.cpu=await iP(),t.memory=await oP(),t.disk=await cP(),t.network=await lP(),t.harperdb_processes=await aP(),t.table_size=await dP(),t.metrics=await fP(),t.threads=await fY(),t.replication=await mY(),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=sP();break;case"cpu":t.cpu=await iP();break;case"memory":t.memory=await oP();break;case"disk":t.disk=await cP();break;case"network":t.network=await lP();break;case"harperdb_processes":t.harperdb_processes=await aP();break;case"table_size":t.table_size=await dP();break;case"database_metrics":case"metrics":t.metrics=await fP();break;case"threads":t.threads=await fY();break;case"replication":t.replication=await mY();break;default:break}return t}a(rme,"systemInformation")});var da=M((fFe,gY)=>{"use strict";var nme=Vn(),mP=ae(),sme=require("util"),Ql=(G(),v(j)),hY=fe();hY.initSync();var ime=DC(),EY=gn(),{Node:lFe,NodeSubscription:uFe}=pf(),ome=ud(),ame=nY(),{RemotePayloadObject:cme,RemotePayloadSubscription:lme}=Ph(),{handleHDBError:ume,hdbErrors:dme}=Ee(),{HTTP_STATUS_CODES:fme,HDB_ERROR_MSGS:mme}=dme,pme=ui(),hme=Dh(),{packageJson:Eme}=Rt(),{getDatabases:_me}=(Oe(),v(mt)),dFe=sme.promisify(ime.authorize),gme=EY.searchByHash,Sme=EY.searchByValue;gY.exports={isEmpty:Tme,getNodeRecord:yme,upsertNodeRecord:Rme,buildNodePayloads:bme,checkClusteringEnabled:Ame,getAllNodeRecords:Ime,getSystemInfo:wme,reverseSubscription:_Y};function Tme(e){return e==null}a(Tme,"isEmpty");async function yme(e){let t=new ome(Ql.SYSTEM_SCHEMA_NAME,Ql.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return gme(t)}a(yme,"getNodeRecord");async function Rme(e){let t=new ame(Ql.SYSTEM_SCHEMA_NAME,Ql.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return nme.upsert(t)}a(Rme,"upsertNodeRecord");function _Y(e){if(mP.isEmpty(e.subscribe)||mP.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(_Y,"reverseSubscription");function bme(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=mP.getTableHashAttribute(l,u),{subscribe:f,publish:m}=_Y(c),p=_me()[l]?.[u],h=new lme(l,u,d,m,f,c.start_time,p.schemaDefined?p.attributes:void 0);s.push(h)}return new cme(r,t,s,n)}a(bme,"buildNodePayloads");function Ame(){if(!hY.get(Ql.CONFIG_PARAMS.CLUSTERING_ENABLED))throw ume(new Error,mme.CLUSTERING_NOT_ENABLED,fme.BAD_REQUEST,void 0,void 0,!0)}a(Ame,"checkClusteringEnabled");async function Ime(){let e=new pme(Ql.SYSTEM_SCHEMA_NAME,Ql.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await Sme(e))}a(Ime,"getAllNodeRecords");async function wme(){let e=await hme.getSystemInformation();return{hdb_version:Eme.version,node_version:e.node_version,platform:e.platform}}a(wme,"getSystemInfo")});var pP=M((pFe,wY)=>{"use strict";var ZT=Sr(),SY=ae(),TY=Lt(),yY=(G(),v(j)),ey=Q(),RY=WT(),Nme=_p(),{RemotePayloadObject:Cme}=Ph(),{handleHDBError:bY,hdbErrors:Ome}=Ee(),{HTTP_STATUS_CODES:AY}=Ome,{NodeSubscription:IY}=pf();wY.exports=Pme;async function Pme(e,t){let r;try{r=await ZT.request(`${t}.${TY.REQUEST_SUFFIX}`,new Cme(yY.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),ey.trace("Response from remote describe all request:",r)}catch(o){ey.error(`addNode received error from describe all request to remote node: ${o}`);let c=ZT.requestErrorHandler(o,"add_node",t);throw bY(new Error,c,AY.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===TY.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw bY(new Error,o,AY.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===yY.SYSTEM_SCHEMA_NAME){await ZT.createLocalTableStream(l,c);let h=new IY(l,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let u=SY.doesSchemaExist(l),d=n[l]!==void 0,f=c?SY.doesTableExist(l,c):!0,m=c?n?.[l]?.[c]!==void 0:!0;if(!u&&!d||!f&&!m){s.push(o);continue}if(!u&&d&&(ey.trace(`addNode creating schema: ${l}`),await RY.createSchema({operation:"create_schema",schema:l})),!f&&m){ey.trace(`addNode creating table: ${c} in schema: ${l} with attributes ${JSON.stringify(n[l][c].attributes)}`);let h=new Nme(l,c,n[l][c].hash_attribute);n[l][c].attributes&&(h.attributes=n[l][c].attributes),await RY.createTable(h)}await ZT.createLocalTableStream(l,c);let p=new IY(l,c,o.publish,o.subscribe);p.start_time=o.start_time,i.push(p)}return{added:i,skipped:s}}a(Pme,"reviewSubscriptions")});var Ef={};ye(Ef,{addNodeBack:()=>hP,removeNodeBack:()=>EP,setNode:()=>Mme});async function Mme(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=Si(t)):t=qT(r);let n=(0,CY.validateBySchema)(e,vme);if(n)throw(0,fa.handleHDBError)(n,n.message,Dme.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=Gt(),E=await h.get(p);if(!E)throw new fa.ClientError(p+" does not exist");try{await Nh({url:E.url},{operation:V.REMOVE_NODE_BACK,name:E?.subscriptions?.length>0?tt():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=gc();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,Ys.getReplicationCert)();let p=await(0,Ys.getReplicationCertAuth)();if(!i)throw new Error("Unable to find a certificate to use for replication");i.options.is_self_signed?(o=await(0,Ys.createCsr)(),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,Cc.get)(x.REPLICATION_HOSTNAME),target_hostname:r,url:s,csr:o,cert_auth:c,authorization:e.retain_authorization?e.authorization:null};if((0,Cc.get)(x.REPLICATION_SHARD)!==void 0&&(l.shard=(0,Cc.get)(x.REPLICATION_SHARD)),e.subscriptions?l.subscriptions=e.subscriptions.map(NY):l.subscriptions=null,e.hasOwnProperty("subscribe")||e.hasOwnProperty("publish")){let p=NY(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 Nh({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,Ys.setCertTable)({name:Lme.certificateFromPem(u.signingCA).issuer.getField("CN").value,certificate:u.signingCA,is_authority:!0}),u.certificate&&await(0,Ys.setCertTable)({name:tt(),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,Cc.get)(x.REPLICATION_SHARD)!==void 0&&(p.shard=(0,Cc.get)(x.REPLICATION_SHARD)),e.retain_authorization&&(p.authorization=e.authorization),e.start_time&&(p.start_time=e.start_time),await sa(tt(),p)}await sa(u?u.nodeName:f.name??Si(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,Ys.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,Ys.getReplicationCertAuth)();if(n.replicates){let i={url:gc(),ca:s?.certificate,replicates:!0,subscriptions:null};(0,Cc.get)(x.REPLICATION_SHARD)!==void 0&&(i.shard=(0,Cc.get)(x.REPLICATION_SHARD),t.shard=i.shard),e.start_time&&(i.start_time=e.start_time),e.authorization&&(i.authorization=e.authorization),await sa(tt(),i)}return await sa(e.hostname,n),t.nodeName=tt(),t.usingCA=s?.certificate,Rs.info("addNodeBack responding to:",e.url,"with CA named:",s?.name),t}async function EP(e){Rs.trace("removeNodeBack received request:",e),await Gt().delete(e.name)}function NY(e){let{subscribe:t,publish:r}=e;return{...e,subscribe:r,publish:t}}var Ys,CY,Nc,Cc,Rs,fa,Lme,Dme,vme,_f=se(()=>{Ys=b(ys()),CY=b(pt()),Nc=b(require("joi")),Cc=b(fe());G();gh();Qd();Ss();Rs=b(Q()),fa=b(Ee()),{pki:Lme}=require("node-forge"),{HTTP_STATUS_CODES:Dme}=fa.hdbErrors,vme=Nc.default.object({hostname:Nc.default.string(),verify_tls:Nc.default.boolean(),replicates:Nc.default.boolean(),subscriptions:Nc.default.array(),revoked_certificates:Nc.default.array(),shard:Nc.default.number()});a(Mme,"setNode");a(hP,"addNodeBack");a(EP,"removeNodeBack");a(NY,"reverseSubscription")});var iy=M((bFe,PY)=>{"use strict";var{handleHDBError:ty,hdbErrors:Ume}=Ee(),{HTTP_STATUS_CODES:ry}=Ume,{addUpdateNodeValidator:xme}=QT(),ny=Q(),sy=(G(),v(j)),OY=Lt(),Bme=ae(),vh=Sr(),Mh=da(),_P=fe(),Fme=pP(),{Node:kme,NodeSubscription:Hme}=pf(),{broadcast:Gme}=st(),{setNode:qme}=(_f(),v(Ef)),yFe=fe(),RFe=(G(),v(j)),$me="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",Vme="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Kme=_P.get(sy.CONFIG_PARAMS.CLUSTERING_NODENAME);PY.exports=Yme;async function Yme(e,t=!1){if(ny.trace("addNode called with:",e),_P.get(sy.CONFIG_PARAMS.REPLICATION_URL)||_P.get(sy.CONFIG_PARAMS.REPLICATION_HOSTNAME))return qme(e);Mh.checkClusteringEnabled();let r=xme(e);if(r)throw ty(r,r.message,ry.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let f=await Mh.getNodeRecord(n);if(!Bme.isEmptyOrZeroLength(f))throw ty(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,ry.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await Fme(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=$me,o;let c=Mh.buildNodePayloads(s,Kme,sy.OPERATIONS_ENUM.ADD_NODE,await Mh.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 Hme(p.schema,p.table,p.publish,p.subscribe))}ny.trace("addNode sending remote payload:",c);let u;try{u=await vh.request(`${n}.${OY.REQUEST_SUFFIX}`,c)}catch(f){ny.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 ty(new Error,m,ry.INTERNAL_SERVER_ERROR,"error",m)}if(u.status===OY.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let f=`Error returned from remote node ${n}: ${u.message}`;throw ty(new Error,f,ry.INTERNAL_SERVER_ERROR,"error",f)}ny.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 kme(n,l,u.system_info);return await Mh.upsertNodeRecord(d),Gme({type:"nats_update"}),i.length>0?o.message=Vme:o.message=`Successfully added '${n}' to manifest`,o}a(Yme,"addNode")});var yP=M((wFe,DY)=>{"use strict";var{handleHDBError:gP,hdbErrors:Wme}=Ee(),{HTTP_STATUS_CODES:SP}=Wme,{addUpdateNodeValidator:jme}=QT(),Uh=Q(),oy=(G(),v(j)),LY=Lt(),IFe=ae(),xh=Sr(),Bh=da(),TP=fe(),{cloneDeep:zme}=require("lodash"),Jme=pP(),{Node:Qme,NodeSubscription:Xme}=pf(),{broadcast:Zme}=st(),{setNode:epe}=(_f(),v(Ef)),tpe="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",rpe="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",npe=TP.get(oy.CONFIG_PARAMS.CLUSTERING_NODENAME);DY.exports=spe;async function spe(e){if(Uh.trace("updateNode called with:",e),TP.get(oy.CONFIG_PARAMS.REPLICATION_URL)??TP.get(oy.CONFIG_PARAMS.REPLICATION_HOSTNAME))return epe(e);Bh.checkClusteringEnabled();let t=jme(e);if(t)throw gP(t,t.message,SP.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Bh.getNodeRecord(r);s.length>0&&(n=zme(s));let{added:i,skipped:o}=await Jme(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=tpe,c;let l=Bh.buildNodePayloads(i,npe,oy.OPERATIONS_ENUM.UPDATE_NODE,await Bh.getSystemInfo());for(let d=0,f=i.length;d<f;d++){let m=i[d];Uh.trace(`updateNode updating work stream for node: ${r} subscription:`,m),i[d].start_time===void 0&&delete i[d].start_time}Uh.trace("updateNode sending remote payload:",l);let u;try{u=await xh.request(`${r}.${LY.REQUEST_SUFFIX}`,l)}catch(d){Uh.error(`updateNode received error from request: ${d}`);let f=xh.requestErrorHandler(d,"update_node",r);throw gP(new Error,f,SP.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===LY.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${r}: ${u.message}`;throw gP(new Error,d,SP.INTERNAL_SERVER_ERROR,"error",d)}Uh.trace(u);for(let d=0,f=i.length;d<f;d++){let m=i[d];await xh.updateRemoteConsumer(m,r),m.subscribe===!0?await xh.updateConsumerIterator(m.schema,m.table,r,"start"):await xh.updateConsumerIterator(m.schema,m.table,r,"stop")}return n||(n=[new Qme(r,[],u.system_info)]),await ipe(n[0],i,u.system_info),o.length>0?c.message=rpe:c.message=`Successfully updated '${r}'`,c}a(spe,"updateNode");async function ipe(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 Xme(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Bh.upsertNodeRecord(n),Zme({type:"nats_update"})}a(ipe,"updateNodeTable")});var BY=M((CFe,xY)=>{"use strict";var UY=require("joi"),{string:vY}=UY.types(),ope=pt(),MY=(G(),v(j)),ape=fe(),cpe=Lt();xY.exports=lpe;function lpe(e){let t=vY.invalid(ape.get(MY.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(cpe.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=UY.object({operation:vY.valid(MY.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return ope.validateBySchema(e,r)}a(lpe,"removeNodeValidator")});var ay=M((PFe,qY)=>{"use strict";var{handleHDBError:FY,hdbErrors:upe}=Ee(),{HTTP_STATUS_CODES:kY}=upe,dpe=BY(),Fh=Q(),HY=da(),fpe=ae(),gf=(G(),v(j)),GY=Lt(),RP=Sr(),bP=fe(),{RemotePayloadObject:mpe}=Ph(),{NodeSubscription:ppe}=pf(),hpe=Ep(),Epe=Dl(),{broadcast:_pe}=st(),{setNode:gpe}=(_f(),v(Ef)),Spe=bP.get(gf.CONFIG_PARAMS.CLUSTERING_NODENAME);qY.exports=Tpe;async function Tpe(e){if(Fh.trace("removeNode called with:",e),bP.get(gf.CONFIG_PARAMS.REPLICATION_URL)??bP.get(gf.CONFIG_PARAMS.REPLICATION_HOSTNAME))return gpe(e);HY.checkClusteringEnabled();let t=dpe(e);if(t)throw FY(t,t.message,kY.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await HY.getNodeRecord(r);if(fpe.isEmptyOrZeroLength(n))throw FY(new Error,`Node '${r}' was not found.`,kY.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new mpe(gf.OPERATIONS_ENUM.REMOVE_NODE,Spe,[]),i,o=!1;for(let l=0,u=n.subscriptions.length;l<u;l++){let d=n.subscriptions[l];d.subscribe===!0&&await RP.updateConsumerIterator(d.schema,d.table,r,"stop");try{await RP.updateRemoteConsumer(new ppe(d.schema,d.table,!1,!1),r)}catch(f){Fh.error(f)}}try{i=await RP.request(`${r}.${GY.REQUEST_SUFFIX}`,s),Fh.trace("Remove node reply from remote node:",r,i)}catch(l){Fh.error("removeNode received error from request:",l),o=!0}let c=new hpe(gf.SYSTEM_SCHEMA_NAME,gf.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await Epe.deleteRecord(c),_pe({type:"nats_update"}),i?.status===GY.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Fh.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(Tpe,"removeNode")});var KY=M((DFe,VY)=>{"use strict";var $Y=require("joi"),{string:ype,array:Rpe}=$Y.types(),bpe=pt(),Ape=QT();VY.exports=Ipe;function Ipe(e){let t=$Y.object({operation:ype.valid("configure_cluster").required(),connections:Rpe.items(Ape.validationSchema).required()});return bpe.validateBySchema(e,t)}a(Ipe,"configureClusterValidator")});var AP=M((MFe,JY)=>{"use strict";var YY=(G(),v(j)),cy=Q(),wpe=ae(),Npe=fe(),Cpe=ay(),Ope=iy(),Ppe=da(),Lpe=KY(),{handleHDBError:WY,hdbErrors:Dpe}=Ee(),{HTTP_STATUS_CODES:jY}=Dpe,vpe="Configure cluster complete.",Mpe="Failed to configure the cluster. Check the logs for more details.",Upe="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";JY.exports=xpe;async function xpe(e){cy.trace("configure cluster called with:",e);let t=Lpe(e);if(t)throw WY(t,t.message,jY.BAD_REQUEST,void 0,void 0,!0);let r=await Ppe.getAllNodeRecords(),n=[];if(Npe.get(YY.CONFIG_PARAMS.CLUSTERING_ENABLED)){for(let d=0,f=r.length;d<f;d++){let m=await zY(Cpe,{operation:YY.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[d].name},r[d].name);n.push(m)}cy.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 zY(Ope,f,f.node_name);s.push(m)}cy.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"&&(cy.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(wpe.isEmptyOrZeroLength(o))return{message:vpe,connections:c};if(l)return{message:Upe,failed_nodes:o,connections:c};throw WY(new Error,Mpe,jY.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(xpe,"configureCluster");async function zY(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(zY,"functionWrapper")});var eW=M((xFe,ZY)=>{"use strict";var kh=require("joi"),Bpe=pt(),{validateSchemaExists:QY,validateTableExists:Fpe,validateSchemaName:XY}=Ji(),kpe=kh.object({operation:kh.string().valid("purge_stream"),schema:kh.string().custom(QY).custom(XY).optional(),database:kh.string().custom(QY).custom(XY).optional(),table:kh.string().custom(Fpe).required()});function Hpe(e){return Bpe.validateBySchema(e,kpe)}a(Hpe,"purgeStreamValidator");ZY.exports=Hpe});var IP=M((FFe,tW)=>{"use strict";var{handleHDBError:Gpe,hdbErrors:qpe}=Ee(),{HTTP_STATUS_CODES:$pe}=qpe,Vpe=eW(),Kpe=Sr(),Ype=da();tW.exports=Wpe;async function Wpe(e){e.schema=e.schema??e.database;let t=Vpe(e);if(t)throw Gpe(t,t.message,$pe.BAD_REQUEST,void 0,void 0,!0);Ype.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await Kpe.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(Wpe,"purgeStream")});var CP=M((HFe,lW)=>{"use strict";var NP=da(),jpe=Sr(),uy=fe(),Sf=(G(),v(j)),Xl=Lt(),zpe=ae(),wP=Q(),{RemotePayloadObject:Jpe}=Ph(),{ErrorCode:rW}=require("nats"),{parentPort:nW}=require("worker_threads"),{onMessageByType:Qpe}=st(),{getThisNodeName:Xpe}=(Ss(),v(oa)),{requestClusterStatus:Zpe}=(gh(),v(QV)),{getReplicationSharedStatus:ehe,getHDBNodeTable:the}=(Qd(),v(VV)),{CONFIRMATION_STATUS_POSITION:rhe,RECEIVED_VERSION_POSITION:sW,RECEIVED_TIME_POSITION:nhe,SENDING_TIME_POSITION:she,RECEIVING_STATUS_POSITION:ihe,RECEIVING_STATUS_RECEIVING:ohe,BACK_PRESSURE_RATIO_POSITION:ahe}=(SO(),v(G1)),iW=uy.get(Sf.CONFIG_PARAMS.CLUSTERING_ENABLED),oW=uy.get(Sf.CONFIG_PARAMS.CLUSTERING_NODENAME);lW.exports={clusterStatus:che,buildNodeStatus:cW};var aW;Qpe("cluster-status",async e=>{aW(e)});async function che(){if(uy.get(Sf.CONFIG_PARAMS.REPLICATION_URL)||uy.get(Sf.CONFIG_PARAMS.REPLICATION_HOSTNAME)){let n;nW?(nW.postMessage({type:"request-cluster-status"}),n=await new Promise(i=>{aW=i})):n=Zpe();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=ehe(u,l,o);c.lastCommitConfirmed=ly(d[rhe]),c.lastReceivedRemoteTime=ly(d[sW]),c.lastReceivedLocalTime=ly(d[nhe]),c.lastReceivedVersion=d[sW],c.sendingMessage=ly(d[she]),c.backPressurePercent=d[ahe]*100,c.lastReceivedStatus=d[ihe]===ohe?"Receiving":"Waiting"}}n.node_name=Xpe();let s=the().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:oW,is_enabled:iW,connections:[]};if(!iW)return e;let t=await NP.getAllNodeRecords();if(zpe.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(cW(t[n],e.connections));return await Promise.allSettled(r),e}a(che,"clusterStatus");function ly(e){return e?e===1?"Copying":new Date(e).toUTCString():void 0}a(ly,"asDate");async function cW(e,t){let r=e.name,n=new Jpe(Sf.OPERATIONS_ENUM.CLUSTER_STATUS,oW,void 0,await NP.getSystemInfo()),s,i,o=Xl.CLUSTER_STATUS_STATUSES.OPEN;try{let l=Date.now();s=await jpe.request(Xl.REQUEST_SUBJECT(r),n),i=Date.now()-l,s.status===Xl.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=Xl.CLUSTER_STATUS_STATUSES.CLOSED,wP.error(`Error getting node status from ${r} `,s))}catch(l){wP.warn(`Error getting node status from ${r}`,l),l.code===rW.NoResponders?o=Xl.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:l.code===rW.Timeout?o=Xl.CLUSTER_STATUS_STATUSES.TIMEOUT:o=Xl.CLUSTER_STATUS_STATUSES.CLOSED}let c=new lhe(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!==Sf.PRE_4_0_0_VERSION&&await NP.upsertNodeRecord(l)}catch(l){wP.error("Cluster status encountered an error updating system info for node:",r,l)}t.push(c)}a(cW,"buildNodeStatus");function lhe(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(lhe,"NodeStatusObject")});var PP=M((qFe,uW)=>{"use strict";var{handleHDBError:uhe,hdbErrors:dhe}=Ee(),{HTTP_STATUS_CODES:fhe}=dhe,mhe=Sr(),phe=da(),OP=ae(),dy=require("joi"),hhe=pt(),Ehe=2e3,_he=dy.object({timeout:dy.number().min(1),connected_nodes:dy.boolean(),routes:dy.boolean()});uW.exports=ghe;async function ghe(e){phe.checkClusteringEnabled();let t=hhe.validateBySchema(e,_he);if(t)throw uhe(t,t.message,fhe.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||OP.autoCastBoolean(n),o=s===void 0||OP.autoCastBoolean(s),c={nodes:[]},l=await mhe.getServerList(r??Ehe),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:OP.autoCast(E.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(ghe,"clusterNetwork")});var pW=M((VFe,mW)=>{"use strict";var LP=require("joi"),dW=pt(),{routeConstraints:fW}=_N();mW.exports={setRoutesValidator:She,deleteRoutesValidator:The};function She(e){let t=LP.object({server:LP.valid("hub","leaf"),routes:fW.required()});return dW.validateBySchema(e,t)}a(She,"setRoutesValidator");function The(e){let t=LP.object({routes:fW.required()});return dW.validateBySchema(e,t)}a(The,"deleteRoutesValidator")});var fy=M((YFe,yW)=>{"use strict";var ma=gt(),DP=ae(),Ws=(G(),v(j)),Tf=fe(),hW=pW(),{handleHDBError:EW,hdbErrors:yhe}=Ee(),{HTTP_STATUS_CODES:_W}=yhe,gW="cluster routes successfully set",SW="cluster routes successfully deleted";yW.exports={setRoutes:bhe,getRoutes:Ahe,deleteRoutes:Ihe};function Rhe(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=DP.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(Ws.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,r):ma.updateConfigValue(Ws.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,r),{message:gW,set:i,skipped:s}}a(Rhe,"setRoutesNats");function bhe(e){let t=hW.setRoutesValidator(e);if(t)throw EW(t,t.message,_W.BAD_REQUEST,void 0,void 0,!0);if(Tf.get(Ws.CONFIG_PARAMS.CLUSTERING_ENABLED))return Rhe(e);let r=[],n=[],s=Tf.get(Ws.CONFIG_PARAMS.REPLICATION_ROUTES)??[];return e.routes.forEach(i=>{TW(s,i)?n.push(i):(s.push(i),r.push(i))}),ma.updateConfigValue(Ws.CONFIG_PARAMS.REPLICATION_ROUTES,s),{message:gW,set:r,skipped:n}}a(bhe,"setRoutes");function TW(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(TW,"existsInArray");function Ahe(){if(Tf.get(Ws.CONFIG_PARAMS.CLUSTERING_ENABLED)){let e=ma.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}else return Tf.get(Ws.CONFIG_PARAMS.REPLICATION_ROUTES)??[]}a(Ahe,"getRoutes");function Ihe(e){let t=hW.deleteRoutesValidator(e);if(t)throw EW(t,t.message,_W.BAD_REQUEST,void 0,void 0,!0);if(Tf.get(Ws.CONFIG_PARAMS.CLUSTERING_ENABLED))return whe(e);let r=[],n=[],s=Tf.get(Ws.CONFIG_PARAMS.REPLICATION_ROUTES)??[],i=[];return s.forEach(o=>{TW(e.routes,o)?r.push(o):(i.push(o),n.push(o))}),ma.updateConfigValue(Ws.CONFIG_PARAMS.REPLICATION_ROUTES,i),{message:SW,deleted:r,skipped:n}}a(Ihe,"deleteRoutes");function whe(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=DP.isEmptyOrZeroLength(r)?null:r,ma.updateConfigValue(Ws.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,r)),c&&(n=DP.isEmptyOrZeroLength(n)?null:n,ma.updateConfigValue(Ws.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:SW,deleted:s,skipped:i}}a(whe,"deleteRoutesNats")});var bW=M((jFe,RW)=>{"use strict";var Nhe=Lt(),vP=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+Nhe.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"}};RW.exports=vP});var wW=M((JFe,IW)=>{"use strict";var AW=Lt(),MP=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+AW.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+AW.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"}};IW.exports=MP});var CW=M((XFe,NW)=>{"use strict";var UP=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};NW.exports=UP});var PW=M((eke,OW)=>{"use strict";var Che=Lt(),xP=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+Che.SERVER_SUFFIX.ADMIN,this.password=r}};OW.exports=xP});var Ey=M((rke,vW)=>{"use strict";var Zl=require("path"),eu=require("fs-extra"),Ohe=bW(),Phe=wW(),Lhe=CW(),Dhe=PW(),BP=(Es(),v(ao)),Rf=ae(),jn=gt(),py=(G(),v(j)),Hh=Lt(),{CONFIG_PARAMS:cr}=py,bf=Q(),Gh=fe(),LW=no(),FP=Sr(),vhe=ys(),yf="clustering",Mhe=1e4,DW=50;vW.exports={generateNatsConfig:xhe,removeNatsConfig:Bhe,getHubConfigPath:Uhe};function Uhe(){let e=Gh.get(cr.ROOTPATH);return Zl.join(e,yf,Hh.NATS_CONFIG_FILES.HUB_SERVER)}a(Uhe,"getHubConfigPath");async function xhe(e=!1,t=void 0){console.error("Warning: NATS replication is deprecated and will be removed in version 5.0 of Harper");let r=Gh.get(cr.ROOTPATH);eu.ensureDirSync(Zl.join(r,"clustering","leaf")),Gh.initSync();let n=jn.getConfigFromFile(cr.CLUSTERING_TLS_CERT_AUTH),s=jn.getConfigFromFile(cr.CLUSTERING_TLS_PRIVATEKEY),i=jn.getConfigFromFile(cr.CLUSTERING_TLS_CERTIFICATE);!await eu.exists(i)&&!await eu.exists(!n)&&await vhe.createNatsCerts();let o=Zl.join(r,yf,Hh.PID_FILES.HUB),c=Zl.join(r,yf,Hh.PID_FILES.LEAF),l=jn.getConfigFromFile(cr.CLUSTERING_LEAFSERVER_STREAMS_PATH),u=Zl.join(r,yf,Hh.NATS_CONFIG_FILES.HUB_SERVER),d=Zl.join(r,yf,Hh.NATS_CONFIG_FILES.LEAF_SERVER),f=jn.getConfigFromFile(cr.CLUSTERING_TLS_INSECURE),m=jn.getConfigFromFile(cr.CLUSTERING_TLS_VERIFY),p=jn.getConfigFromFile(cr.CLUSTERING_NODENAME),h=jn.getConfigFromFile(cr.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await FP.checkNATSServerInstalled()||hy("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let E=await BP.listUsers(),_=jn.getConfigFromFile(cr.CLUSTERING_USER),R=await BP.getClusterUser();(Rf.isEmpty(R)||R.active!==!0)&&hy(`Invalid cluster user '${_}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await my(cr.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await my(cr.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await my(cr.CLUSTERING_HUBSERVER_NETWORK_PORT),await my(cr.CLUSTERING_LEAFSERVER_NETWORK_PORT));let S=[],y=[];for(let[z,Y]of E.entries())Y.role?.role===py.ROLE_TYPES_ENUM.CLUSTER_USER&&Y.active&&(S.push(new Dhe(Y.username,LW.decrypt(Y.hash))),y.push(new Lhe(Y.username,LW.decrypt(Y.hash))));let w=[],{hub_routes:I}=jn.getClusteringRoutes();if(!Rf.isEmptyOrZeroLength(I))for(let z of I)w.push(`tls://${R.sys_name_encoded}:${R.uri_encoded_d_hash}@${z.host}:${z.port}`);let H=new Ohe(jn.getConfigFromFile(cr.CLUSTERING_HUBSERVER_NETWORK_PORT),p,o,i,s,n,f,m,h,jn.getConfigFromFile(cr.CLUSTERING_HUBSERVER_CLUSTER_NAME),jn.getConfigFromFile(cr.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),w,S,y);n==null&&(delete H.tls.ca_file,delete H.leafnodes.tls.ca_file),t=Rf.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===py.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await eu.writeJson(u,H),bf.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 Phe(jn.getConfigFromFile(cr.CLUSTERING_LEAFSERVER_NETWORK_PORT),p,c,l,[X],[q],S,y,i,s,n,f);n==null&&delete k.tls.ca_file,(t===void 0||t===py.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await eu.writeJson(d,k),bf.trace(`Leaf server config written to ${d}`))}a(xhe,"generateNatsConfig");async function my(e){let t=Gh.get(e);return Rf.isEmpty(t)&&hy(`port undefined for '${e}'`),await Rf.isPortTaken(t)&&hy(`'${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(my,"isPortAvailable");function hy(e){let t=`Error generating clustering config: ${e}`;bf.error(t),console.error(t),process.exit(1)}a(hy,"generateNatsConfigError");async function Bhe(e){let{port:t,config_file:r}=FP.getServerConfig(e),{username:n,decrypt_hash:s}=await BP.getClusterUser(),i=0,o=2e3;for(;i<DW;){try{let d=await FP.createConnection(t,n,s,!1);if(d.protocol.connected===!0){d.close();break}}catch(d){bf.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${d}`)}if(i++,i>=DW)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&&bf.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await Rf.asyncSetTimeout(u)}let c="0".repeat(Mhe),l=Zl.join(Gh.get(cr.ROOTPATH),yf,r);await eu.writeFile(l,c),await eu.remove(l),bf.notify(e,"started.")}a(Bhe,"removeNatsConfig")});var kW=M((ske,FW)=>{"use strict";var bs=fe(),et=(G(),v(j)),qh=Lt(),pa=require("path"),{PACKAGE_ROOT:gy}=Rt(),MW=fe(),_y=ae(),Af="/dev/null",Fhe=pa.join(gy,"launchServiceScripts"),UW=pa.join(gy,"utility/scripts"),khe=pa.join(UW,et.HDB_RESTART_SCRIPT),xW=pa.resolve(gy,"dependencies",`${process.platform}-${process.arch}`,qh.NATS_BINARY_NAME);function BW(){let e={[et.PROCESS_NAME_ENV_PROP]:et.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0,...process.env};return _y.noBootFile()&&(e[et.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=_y.getEnvCliRootPath()),{name:et.PROCESS_DESCRIPTORS.HDB,script:et.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:e,execArgv:process.execArgv,cwd:gy}}a(BW,"generateMainServerConfig");var Hhe=9930;function Ghe(){bs.initSync(!0);let e=bs.get(et.CONFIG_PARAMS.ROOTPATH),t=pa.join(e,"clustering",qh.NATS_CONFIG_FILES.HUB_SERVER),r=pa.join(bs.get(et.HDB_SETTINGS_NAMES.LOG_PATH_KEY),et.LOG_NAMES.HDB),n=MW.get(et.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=qh.LOG_LEVEL_FLAGS[bs.get(et.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:et.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==Hhe?"-"+n:""),binFile:xW,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=Af,i.error_file=Af),i}a(Ghe,"generateNatsHubServerConfig");var qhe=9940;function $he(){bs.initSync(!0);let e=bs.get(et.CONFIG_PARAMS.ROOTPATH),t=pa.join(e,"clustering",qh.NATS_CONFIG_FILES.LEAF_SERVER),r=pa.join(bs.get(et.HDB_SETTINGS_NAMES.LOG_PATH_KEY),et.LOG_NAMES.HDB),n=MW.get(et.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=qh.LOG_LEVEL_FLAGS[bs.get(et.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==qhe?"-"+n:""),binFile:xW,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=Af,i.error_file=Af),i}a($he,"generateNatsLeafServerConfig");function Vhe(){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:Fhe,autorestart:!1};return bs.get(et.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=Af,t.error_file=Af),t}a(Vhe,"generateClusteringUpgradeV4ServiceConfig");function Khe(){let e={[et.PROCESS_NAME_ENV_PROP]:et.PROCESS_DESCRIPTORS.RESTART_HDB};return _y.noBootFile()&&(e[et.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=_y.getEnvCliRootPath()),{...{name:et.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:UW},script:khe}}a(Khe,"generateRestart");function Yhe(){return{apps:[BW()]}}a(Yhe,"generateAllServiceConfigs");FW.exports={generateAllServiceConfigs:Yhe,generateMainServerConfig:BW,generateRestart:Khe,generateNatsHubServerConfig:Ghe,generateNatsLeafServerConfig:$he,generateClusteringUpgradeV4ServiceConfig:Vhe}});var If=M((ake,YW)=>{"use strict";var Lr=(G(),v(j)),oke=ae(),Ea=Ey(),Sy=Sr(),ha=Lt(),Oc=kW(),HP=fe(),Pc=Q(),Whe=da(),{startWorker:HW,onMessageFromWorkers:jhe}=st(),GW=require("fs"),zhe=require("node:path"),Jhe=(G(),v(j)),{setTimeout:Qhe}=require("node:timers/promises"),{execFile:Xhe,fork:Zhe}=require("node:child_process");YW.exports={start:Lc,restart:tEe,kill:iEe,startAllServices:oEe,startService:$W,restartHdb:rEe,startClusteringProcesses:VW,startClusteringThreads:KW,isHdbRestartRunning:nEe,getHdbPid:sEe,cleanupChildrenProcesses:$h,reloadClustering:cEe,expectedRestartOfChildren:qW};jhe(e=>{e.type==="restart"&&HP.initSync(!0)});var So=[],eEe=10,kP;function Lc(e,t=!1){let r=typeof e.args=="string"?e.args.split(" "):e.args;e.silent=!0,e.detached=!0;let n=e.script?Zhe(e.script,r,e):Xhe(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=So.indexOf(n);c>-1&&So.splice(c,1),!kP&&o!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<eEe&&(GW.existsSync(Ea.getHubConfigPath())?Lc(e):(await Ea.generateNatsConfig(!0),Lc(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=HP.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?Pc.OUTPUTS.STDERR:Pc.OUTPUTS.STDOUT;Pc.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?Pc.OUTPUTS.STDERR:Pc.OUTPUTS.STDOUT;Pc.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(),So.length===0&&(t||(process.on("exit",$h),process.on("SIGINT",$h),process.on("SIGQUIT",$h),process.on("SIGTERM",$h))),So.push(n)}a(Lc,"start");function $h(e=!0){if(!kP&&(kP=!0,So.length!==0))if(Pc.info("Killing child processes..."),So.map(t=>t.kill()),e)process.exit(0);else return Qhe(2e3)}a($h,"cleanupChildrenProcesses");function tEe(e){qW();for(let t of So)t.name===e&&t.kill()}a(tEe,"restart");function qW(){for(let e of So)e.config&&(e.config.restarts=0)}a(qW,"expectedRestartOfChildren");async function rEe(){await Lc(Oc.generateRestart())}a(rEe,"restartHdb");async function nEe(){let e=await list();for(let t in e)if(e[t].name===Lr.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(nEe,"isHdbRestartRunning");function sEe(){let e=HP.getHdbBasePath();if(!e)return;let t=zhe.join(e,Jhe.HDB_PID_FILE),r=lEe(t);if(!(!r||r===process.pid)&&uEe(r))return r}a(sEe,"getHdbPid");function iEe(){for(let e of So)e.kill();So=[]}a(iEe,"kill");async function oEe(){await VW(),await KW(),await Lc(Oc.generateAllServiceConfigs())}a(oEe,"startAllServices");async function $W(e,t=!1){let r;switch(e=e.toLowerCase(),e){case Lr.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Oc.generateMainServerConfig();break;case Lr.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Oc.generateNatsIngestServiceConfig();break;case Lr.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Oc.generateNatsReplyServiceConfig();break;case Lr.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Oc.generateNatsHubServerConfig(),await Lc(r,t),await Ea.removeNatsConfig(e);return;case Lr.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Oc.generateNatsLeafServerConfig(),await Lc(r,t),await Ea.removeNatsConfig(e);return;case Lr.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=Oc.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}Lc(r,t)}a($W,"startService");var aEe;async function VW(e=!1){for(let t in Lr.CLUSTERING_PROCESSES){let r=Lr.CLUSTERING_PROCESSES[t];await $W(r,e)}}a(VW,"startClusteringProcesses");async function KW(){aEe=HW(Lr.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Lr.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await Sy.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await Sy.updateLocalStreams();let e=await Whe.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Lr.PRE_4_0_0_VERSION){Pc.info("Starting clustering upgrade 4.0.0 process"),HW(Lr.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(KW,"startClusteringThreads");async function cEe(){await Ea.generateNatsConfig(!0),await Sy.reloadNATSHub(),await Sy.reloadNATSLeaf(),await Ea.removeNatsConfig(Lr.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Ea.removeNatsConfig(Lr.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(cEe,"reloadClustering");function lEe(e){try{return Number.parseInt(GW.readFileSync(e,"utf8"),10)}catch{return null}}a(lEe,"readPidFile");function uEe(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}a(uEe,"isProcessRunning")});var $P={};ye($P,{compactOnStart:()=>dEe,copyDb:()=>XW});async function dEe(){_a.notify("Running compact on start"),console.log("Running compact on start");let e=(0,GP.get)(x.ROOTPATH),t=new Map,r=lt();(0,qP.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,Ty.join)(e,"backup",n+".mdb"),o=(0,Ty.join)(e,Zc,n+"-copy.mdb"),c=0;try{c=await WW(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 XW(n,o),console.log("Backing up",n,"to",i);try{await(0,tu.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,tu.move)(o,s,{overwrite:!0}),await(0,tu.remove)((0,Ty.join)(e,Zc,`${n}-copy.mdb-lock`))}try{Md()}catch(n){_a.error("Error resetting databases after backup",n),console.error("Error resetting databases after backup",n)}try{Md()}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,qP.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,tu.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw Md(),n}for(let[n,{backupDest:s,recordCount:i}]of t){let o=await WW(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}.
18
18
  Total record count before compaction: ${i}, total after: ${o}.
19
19
  Database backup has not been removed and can be found here: ${s}`;_a.warn(c),console.warn(c)}(0,GP.get)(x.STORAGE_COMPACTONSTARTKEEPBACKUP)!==!0&&(console.log("Removing backup",s),await(0,tu.remove)(s))}}async function WW(e){let t=await(0,QW.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}function wf(){}async function XW(e,t){console.log(`Copying database ${e} to ${t}`);let r=lt()[e];if(!r)throw new Error(`Source database not found: ${e}`);let n;for(let f in r){let m=r[f];m.primaryStore.put=wf,m.primaryStore.remove=wf;for(let p in m.indices){let h=m.indices[p];h.put=wf,h.remove=wf}m.auditStore&&(m.auditStore.put=wf,m.auditStore.remove=wf),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,jW.open)(new zW.default(t)),c=o.openDB(yy.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,_=DS(),_?p.compression=_:delete p.compression,E?.dictionary?.toString()===_?.dictionary?.toString()&&(E=null,_=null)),c.put(m,p),!(h||p.indexed))continue;let R=new JW.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(yy.AUDIT_STORE_NAME,Vm);console.log("copying audit log for",e,"to",t),f(i,m,!1,d)}async function f(m,p,h,E){let _=0,R=0,S=0,y=1e7,w=null;for(;y-- >0;)try{for(let I of m.getKeys({start:w,transaction:E}))try{w=I;let{value:H,version:X}=m.getEntry(I,{transaction:E});if(H?.length<14&&h){S++;continue}l=p.put(I,H,h?X:void 0),_++,E.openTimer&&(E.openTimer=0),R+=(I?.length||10)+H.length,u++>5e3&&(await l,console.log("copied",_,"entries",S,"delete records,",R,"bytes"),u=0)}catch(H){console.error("Error copying record",typeof I=="symbol"?"symbol":I,"from",e,"to",t,H)}console.log("finish copying, copied",_,"entries",S,"delete records,",R,"bytes");return}catch{if(typeof w=="string"){if(w==="z")return console.error("Reached end of dbi",w,"for",e,"to",t);w=w.slice(0,-2)+"z"}else if(typeof w=="number")w++;else return console.error("Unknown key type",w,"for",e,"to",t)}}a(f,"copyDbi"),await l,console.log("copied database "+e+" to "+t)}finally{d.done(),o.close()}}var jW,Ty,tu,GP,zW,JW,yy,QW,qP,_a,VP=se(()=>{Oe();jW=require("lmdb"),Ty=require("path"),tu=require("fs-extra"),GP=b(fe()),zW=b(sp()),JW=b(np()),yy=b(Jt());G();qi();QW=b($l()),qP=b(gt()),_a=b(Q());a(dEe,"compactOnStart");a(WW,"getTotalDBRecordCount");a(wf,"noop");a(XW,"copyDb")});var YP=M((mke,ZW)=>{"use strict";var Vh=fe();Vh.initSync();var Nf=require("fs-extra"),KP=require("path"),Cf=(G(),v(j)),fEe=require("crypto"),mEe=require("uuid").v4;ZW.exports=pEe;function pEe(){if(Vh.getHdbBasePath()!==void 0){let e=KP.join(Vh.getHdbBasePath(),Cf.LICENSE_KEY_DIR_NAME,Cf.JWT_ENUM.JWT_PRIVATE_KEY_NAME),t=KP.join(Vh.getHdbBasePath(),Cf.LICENSE_KEY_DIR_NAME,Cf.JWT_ENUM.JWT_PUBLIC_KEY_NAME),r=KP.join(Vh.getHdbBasePath(),Cf.LICENSE_KEY_DIR_NAME,Cf.JWT_ENUM.JWT_PASSPHRASE_NAME);try{Nf.accessSync(r),Nf.accessSync(e),Nf.accessSync(t)}catch(n){if(n.code==="ENOENT"){let s=mEe(),i=fEe.generateKeyPairSync("rsa",{modulusLength:4096,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem",cipher:"aes-256-cbc",passphrase:s}});Nf.writeFileSync(r,s),Nf.writeFileSync(e,i.privateKey),Nf.writeFileSync(t,i.publicKey)}else throw n}}}a(pEe,"checkJWTTokenExist")});var tj=M((hke,ej)=>{"use strict";var WP=class{static{a(this,"HdbInfoInsertObject")}constructor(t,r,n){this.info_id=t,this.data_version_num=r,this.hdb_version_num=n}};ej.exports={HdbInfoInsertObject:WP}});var sj=M((_ke,nj)=>{"use strict";var rj=(G(),v(j)),jP=class{static{a(this,"UpgradeObject")}constructor(t,r){this[rj.UPGRADE_JSON_FIELD_NAMES_ENUM.DATA_VERSION]=t,this[rj.UPGRADE_JSON_FIELD_NAMES_ENUM.UPGRADE_VERSION]=r}};nj.exports={UpgradeObject:jP}});var Ry=M((Ske,oj)=>{"use strict";var js=require("prompt"),Of=require("chalk"),ij=Q(),Ri=require("os"),zP=el(),JP=["yes","y"];async function hEe(e){let t=`${Ri.EOL}`+Of.bold.green("Your current HarperDB version requires that we complete an update process.")+`${Ri.EOL}If a backup of your data has not been created, we recommend you cancel this process and backup before proceeding.${Ri.EOL}${Ri.EOL}You can read more about the changes in this upgrade at https://harperdb.io/developers/release-notes/${Ri.EOL}`;js.override=zP(["CONFIRM_UPGRADE"]),js.start(),js.message=t;let r={properties:{CONFIRM_UPGRADE:{description:Of.magenta(`${Ri.EOL}[CONFIRM_UPGRADE] Do you want to upgrade your HDB instance now? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"no",required:!0}}},n;try{n=await js.get([r])}catch(s){return ij.error("There was an error when prompting user about an upgrade."),ij.error(s),!1}return JP.includes(n.CONFIRM_UPGRADE)}a(hEe,"forceUpdatePrompt");async function EEe(e){let t=`${Ri.EOL}`+Of.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.${Ri.EOL}`);js.override=zP(["CONFIRM_DOWNGRADE"]),js.start(),js.message=t;let r={properties:{CONFIRM_DOWNGRADE:{description:Of.magenta(`${Ri.EOL}[CONFIRM_DOWNGRADE] Do you want to proceed with using your downgraded HDB instance now? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"no",required:!0}}},n=await js.get([r]);return JP.includes(n.CONFIRM_DOWNGRADE)}a(EEe,"forceDowngradePrompt");async function _Ee(){let e=`${Ri.EOL}`+Of.bold.green("We now require a Certifacte Authority certificate. HarperDB can generate all new certificates for you (your existing certificates will be backed up) or you can keep any existing certificates and add your own CA certificate. To add your own CA certificate set the <certificateAuthority> parameter in harperdb-config.yaml");js.override=zP(["GENERATE_CERTS"]),js.start(),js.message=e;let t={properties:{GENERATE_CERTS:{description:Of.magenta(`${Ri.EOL}[GENERATE_CERTS] Do you want HarperDB to generate all new certificates? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"yes",required:!0}}},r=await js.get([t]);return JP.includes(r.GENERATE_CERTS)}a(_Ee,"upgradeCertsPrompt");oj.exports={forceUpdatePrompt:hEe,forceDowngradePrompt:EEe,upgradeCertsPrompt:_Ee}});var by=M((yke,aj)=>{"use strict";var QP=class{static{a(this,"UpgradeDirective")}constructor(t){this.version=t,this.sync_functions=[],this.async_functions=[]}};aj.exports=QP});var lj=M((Nke,cj)=>{"use strict";var gEe=ae(),SEe=gt(),bke=Q(),Ake=require("path"),Ike=require("fs"),wke=(G(),v(j));cj.exports={getOldPropsValue:TEe};function TEe(e,t,r=!1){let n=t.getRaw(e);return gEe.isNotEmptyAndHasValue(n)?n:r?SEe.getDefaultConfig(e):""}a(TEe,"getOldPropsValue")});var mj=M((Oke,fj)=>{"use strict";var Dc=require("path"),vc=require("fs-extra"),yEe=require("properties-reader"),REe=by(),Tr=Q(),{getOldPropsValue:St}=lj(),{HDB_SETTINGS_NAMES:be,CONFIG_PARAMS:ru}=(G(),v(j)),nu=gt(),Ay=fe(),uj=ae(),To=(G(),v(j)),XP=new REe("3.1.0"),dj=[];function bEe(){let e=yEe(Ay.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.