harperdb 4.6.15 → 4.6.17

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.
@@ -14,9 +14,9 @@
14
14
  This can occur during early stages of install where the config file has not yet been created`);return}else throw dr.error(i),new Error(`Error reading HarperDB config file at ${r}`)}Rse(n,r),YI(n);let s=n.toJSON();if(fse.config=s,Bt=Ju(s),Bt.logging_rotation_rotate)for(let i in sH)Bt[i]&&dr.error(`Config ${sH[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);dr.trace(hse)}}o(gg,"initConfig");function Rse(e,t){let r=e.getIn(["rootPath"]),n=!1;if(e.hasIn(["storage","path"])||(e.setIn(["storage","path"],ts.join(r,"database")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],ts.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(dr.trace("Updating config file with missing config params"),e.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${e.errors}`);ln.writeFileSync(t,String(e))}}o(Rse,"checkForUpdatedConfig");function YI(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 Qu.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 Qu.CONFIG_VALIDATION("operationsApi.network.port and operationsApi.network.securePort cannot be the same value");let n=ase(r,t);if(n.error)throw Qu.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)}o(YI,"validateConfig");function yse(e,t){Bt===void 0&&(Bt={});let r=ui[e.toLowerCase()];if(r===void 0){dr.trace(`Unable to update config object because config param '${e}' does not exist`);return}Bt[r.toLowerCase()]=t}o(yse,"updateConfigObject");function dH(e,t,r=void 0,n=!1,s=!1,i=!1){Bt===void 0&&gg();let a=uH(ui.hdb_root),c=ts.join(a,ws.HDB_CONFIG_FILE),l=ka(c),u;if(r&&Bt){let m=!1;for(let h in r)if(r[h]!=Bt[h.toLowerCase()]){m=!0;break}if(!m){dr.trace("No changes detected in config parameters, skipping update");return}}if(r===void 0&&e.toLowerCase()===es.DATABASES)u=t;else if(r===void 0){let m;if(i)m=e;else if(m=ui[e.toLowerCase()],m===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let h=m.split("_"),p=KI(m,t);l.setIn([...h],p)}else for(let m in r){let h=ui[m.toLowerCase()];if(h===es.HTTP_SECUREPORT&&r[m]===Bt[es.HTTP_PORT]?.toString()&&l.setIn(["http","port"],null),h===es.OPERATIONSAPI_NETWORK_SECUREPORT&&r[m]===Bt[es.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&l.setIn(["operationsApi","network","port"],null),h===es.DATABASES){u=r[m];continue}if(h?.startsWith("threads_")){let p=l.getIn(["threads"]);p>=0&&(l.deleteIn(["threads"]),l.setIn(["threads","count"],p))}if(!h&&(m.endsWith("_package")||m.endsWith("_port"))&&(h=m),h!==void 0){let p=h.split("_"),_=ws.LEGACY_CONFIG_PARAMS[m.toUpperCase()];_&&_.startsWith("customFunctions")&&l.hasIn(_.split("_"))&&(h=_,p=_.split("_"));let g=KI(h,r[m]);h==="rootPath"&&g?.endsWith("/")&&(g=g.slice(0,-1));try{p.length>1&&typeof l.getIn(p.slice(0,-1))=="boolean"&&l.deleteIn(p.slice(0,-1)),l.setIn([...p],g)}catch(y){dr.error(y)}}}u&&lH(l,u),YI(l);let d=l.getIn(["rootPath"]),f=ts.join(d,ws.HDB_CONFIG_FILE);if(n===!0&&Ase(c,d),l.errors?.length>0)throw new Error(`Error parsing harperdb-config.yaml ${l.errors}`);ln.writeFileSync(f,String(l)),s&&(Bt=Ju(l.toJSON())),dr.trace(`Config parameter: ${e} updated with value: ${t}`)}o(dH,"updateConfigValue");function Ase(e,t){try{let r=ts.join(t,"backup",`${new Date(Date.now()).toISOString().replaceAll(":","-")}-${ws.HDB_CONFIG_FILE}.bak`);ln.copySync(e,r),dr.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){dr.error(pse),dr.error(r)}}o(Ase,"backupConfigFile");var bse=["databases"];function Ju(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}),_g=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])&&!bse.includes(i)){let a=r(n[i]);for(let c in a){if(!a.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let l=i+"_"+c;!es[l.toUpperCase()]&&ui[l]&&(s[ui[l].toLowerCase()]=a[c]),s[l]=a[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}o(r,"squashObj")}o(Ju,"flattenConfig");function KI(e,t){if(e===es.CLUSTERING_NODENAME||e===es.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(cse(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Ir.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 Ir.autoCast(t)}o(KI,"castConfigValue");function Ise(){let e=Ir.getPropsFilePath(),t=_l(e);return ka(t).toJSON()}o(Ise,"getConfiguration");async function Nse(e){let{operation:t,hdb_user:r,hdbAuthHeader:n,...s}=e;try{return dH(void 0,void 0,s,!0),gse}catch(i){throw typeof i=="string"||i instanceof String?use(i,i,dse.BAD_REQUEST,void 0,void 0,!0):i}}o(Nse,"setConfiguration");function WI(){let e=Ir.getPropsFilePath();try{ln.accessSync(e,ln.constants.F_OK|ln.constants.R_OK)}catch(n){if(!Ir.noBootFile())throw dr.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=_l(e);return ka(t).toJSON()}o(WI,"readConfigFile");function ka(e){return iH.parseDocument(ln.readFileSync(e,"utf8"),{simpleKeys:!0})}o(ka,"parseYamlDoc");function wse(){let e=WI(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Ir.isEmptyOrZeroLength(t)?[]:t;let r=nH(t);if(r)throw Qu.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Ir.isEmptyOrZeroLength(n)?[]:n;let s=nH(n);if(s)throw Qu.CONFIG_VALIDATION(s.message);if(!Ir.isEmptyOrZeroLength(n)&&!Ir.isEmptyOrZeroLength(t)){let i=t.filter(a=>n.some(c=>c.host===a.host&&c.port===a.port));if(!Ir.isEmptyOrZeroLength(i)){let a=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw Qu.CONFIG_VALIDATION(a)}}return{hub_routes:t,leaf_routes:n}}o(wse,"getClusteringRoutes");function fH(e){let t=oH(e);Bt={};for(let r in ui){let n=t.get(r.toUpperCase());if(Ir.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=ui[r].toLowerCase();s===es.LOGGING_ROOT?Bt[s]=ts.dirname(n):Bt[s]=n}return Bt}o(fH,"initOldConfig");function Ose(e){let t=WI();return lse.get(t,e.replaceAll("_","."))}o(Ose,"getConfigFromFile");async function Cse(e,t){let r=ka(_l());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 ln.writeFile(_l(),String(r))}o(Cse,"addConfig");function Pse(e){let t=_l(Ir.getPropsFilePath()),r=ka(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=ts.join(n,ws.HDB_CONFIG_FILE);ln.writeFileSync(s,String(r))}o(Pse,"deleteConfigFromFile");function Lse(){return _g||(gg(),_g)}o(Lse,"getConfigObj");function Dse(){return Bt||gg(),Bt}o(Dse,"getFlatConfigObj")});var rs=M((XPe,Fr)=>{"use strict";var pH="username is required",EH="nothing to update, must supply active, role or password to update",_H="password cannot be an empty string",gH="If role is specified, it cannot be empty.",SH="active must be true or false";Fr.exports.addUser=Gse;Fr.exports.alterUser=qse;Fr.exports.dropUser=Vse;Fr.exports.getSuperUser=jse;Fr.exports.userInfo=Kse;Fr.exports.listUsers=Tg;Fr.exports.listUsersExternal=Yse;Fr.exports.setUsersWithRolesCache=gl;Fr.exports.findAndValidateUser=rN;Fr.exports.getClusterUser=Qse;Fr.exports.getUsersWithRolesCache=zse;Fr.exports.USERNAME_REQUIRED=pH;Fr.exports.ALTERUSER_NOTHING_TO_UPDATE=EH;Fr.exports.EMPTY_PASSWORD=_H;Fr.exports.EMPTY_ROLE=gH;Fr.exports.ACTIVE_BOOLEAN=SH;var TH=vn(),Mse=pl(),th=(hg(),v(mg)),RH=zF(),rh=on(),XI=Co(),Yi=ie(),yH=require("validate.js"),ZI=Q(),{promisify:vse}=require("util"),eN=Vi(),jI=(k(),v(W)),mH=It(),Use=bt(),xse=oe(),Bse=No(),{hdbErrors:Fse,ClientError:di}=ge(),{HTTP_STATUS_CODES:Mo,AUTHENTICATION_ERROR_MSGS:zI,HDB_ERROR_MSGS:Xu}=Fse,{UserEventMsg:tN}=oi(),QI=require("lodash"),{server:Sg}=(Mr(),v(Yf)),Hse=Q();Sg.getUser=(e,t)=>rN(e,t,t!=null);Sg.authenticateUser=(e,t)=>rN(e,t);var AH={username:!0,active:!0,role:!0,password:!0},hH=new Map,kse=vse(Mse.delete),JI=xse.get(jI.CONFIG_PARAMS.AUTHENTICATION_HASHFUNCTION)??th.HASH_FUNCTION.SHA256,Wi;async function Gse(e){let t=yH.cleanAttributes(e,AH),r=RH.addUserValidation(t);if(r)throw new di(r.message);let n=await rh.searchByValue({schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]});if(!n||n.length<1)throw new di(Xu.ROLE_NAME_NOT_FOUND(t.role),Mo.NOT_FOUND);if(n.length>1)throw new di(Xu.DUP_ROLES_FOUND(t.role),Mo.CONFLICT);n[0].permission.cluster_user===!0&&(t.hash=eN.encrypt(t.password)),t.password=await th.hash(t.password,JI),t.hash_function=JI,t.role=n[0].id;let s=await TH.insert({operation:"insert",schema:"system",table:"hdb_user",records:[t]});if(ZI.debug(s),await gl(),s.skipped_hashes.length===1)throw new di(Xu.USER_ALREADY_EXISTS(t.username),Mo.CONFLICT);return XI.signalUserChange(new tN(process.pid)),`${t.username} successfully added`}o(Gse,"addUser");async function qse(e){let t=yH.cleanAttributes(e,AH);if(Yi.isEmptyOrZeroLength(t.username))throw new Error(pH);if(Yi.isEmptyOrZeroLength(t.password)&&Yi.isEmptyOrZeroLength(t.role)&&Yi.isEmptyOrZeroLength(t.active))throw new Error(EH);if(!Yi.isEmpty(t.password)&&Yi.isEmptyOrZeroLength(t.password.trim()))throw new Error(_H);if(!Yi.isEmpty(t.active)&&!Yi.isBoolean(t.active))throw new Error(SH);if(!Yi.isEmpty(t.password)&&!Yi.isEmptyOrZeroLength(t.password.trim())&&($se(t.username)&&(t.hash=eN.encrypt(t.password)),t.password=await th.hash(t.password,JI)),t.role==="")throw new Error(gH);if(t.role){let n=await rh.searchByValue({schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["*"]});if(!n||n.length===0)throw new di(Xu.ALTER_USER_ROLE_NOT_FOUND(t.role),Mo.NOT_FOUND);if(n.length>1)throw new di(Xu.DUP_ROLES_FOUND(t.role),Mo.CONFLICT);t.role=n[0].id}let r=await TH.update({operation:"update",schema:"system",table:"hdb_user",records:[t]});return await gl(),XI.signalUserChange(new tN(process.pid)),r}o(qse,"alterUser");function $se(e){let t=!1,r=Wi.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}o($se,"isClusterUser");async function Vse(e){let t=RH.dropUserValidation(e);if(t)throw new di(t.message);if(Wi.get(e.username)===void 0)throw new di(Xu.USER_NOT_EXIST(e.username),Mo.NOT_FOUND);let r=await kse({table:"hdb_user",schema:"system",hash_values:[e.username]});return ZI.debug(r),await gl(),XI.signalUserChange(new tN(process.pid)),`${e.username} successfully deleted`}o(Vse,"dropUser");async function Kse(e){let t={};if(!e||!e.hdb_user)return"There was no user info in the body";t=QI.cloneDeep(e.hdb_user);let r=await rh.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}o(Kse,"userInfo");async function Yse(){let e=await Tg();return e.forEach(t=>{delete t.password,delete t.hash,delete t.refresh_token,delete t.hash_function}),[...e.values()]}o(Yse,"listUsersExternal");async function Tg(){let e=await rh.searchByValue({schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]}),t={};for(let s of e)t[s.id]=QI.cloneDeep(s);if(Object.keys(t).length===0)return null;let r=await rh.searchByValue({schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]}),n=new Map;for(let s of r)s=QI.cloneDeep(s),s.role=t[s.role],Wse(s.role),n.set(s.username,s);return n}o(Tg,"listUsers");function Wse(e){if(!e){ZI.error("invalid user role found.");return}e.permission.system||(e.permission.system={}),e.permission.system.tables||(e.permission.system.tables={});for(let t of Object.keys(Bse)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}o(Wse,"appendSystemTablesToRole");async function gl(e=void 0){e?Wi=e:Wi=await Tg()}o(gl,"setUsersWithRolesCache");async function zse(){return Wi||await gl(),Wi}o(zse,"getUsersWithRolesCache");async function rN(e,t,r=!0){Wi||await gl();let n=Wi.get(e);if(!n){if(!r)return{username:e};throw new di(zI.GENERIC_AUTH_FAIL,Mo.UNAUTHORIZED)}if(n&&!n.active)throw new di(zI.USER_INACTIVE,Mo.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(hH.get(t)===n.password)return s;{let i=th.validate(n.password,t,n.hash_function||th.HASH_FUNCTION.MD5);if(i?.then&&(i=await i),i===!0)hH.set(t,n.password);else throw new di(zI.GENERIC_AUTH_FAIL,Mo.UNAUTHORIZED)}}return s}o(rN,"findAndValidateUser");async function jse(){Wi||await gl();for(let[,e]of Wi)if(e.role.role==="super_user")return e}o(jse,"getSuperUser");async function Qse(){let e=await Tg(),t=Use.getConfigFromFile(jI.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!(r==null||r?.role?.role!==jI.ROLE_TYPES_ENUM.CLUSTER_USER))return r.decrypt_hash=eN.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+mH.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+mH.SERVER_SUFFIX.ADMIN,r}o(Qse,"getClusterUser");var bH=[];Sg.invalidateUser=function(e){for(let t of bH)try{t(e)}catch(r){Hse.error("Error invalidating user",r)}};Sg.onInvalidatedUser=function(e){bH.push(e)}});var sh=M((rLe,OH)=>{"use strict";var Sl=Q(),ns=(k(),v(W)),Jse=QU(),eLe=ii(),tLe=xa(),Xse=rs(),{validateEvent:IH}=oi(),nh=Xn(),Zse=require("process"),{resetDatabases:eie}=(De(),v(mt)),tie={[ns.ITC_EVENT_TYPES.SCHEMA]:rie,[ns.ITC_EVENT_TYPES.USER]:wH};async function rie(e){let t=IH(e);if(t){Sl.error(t);return}Sl.trace("ITC schemaHandler received schema event:",e),await Jse(e.message),await nie(e.message)}o(rie,"schemaHandler");async function nie(e){try{nh.resetReadTxn(ns.SYSTEM_SCHEMA_NAME,ns.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),nh.resetReadTxn(ns.SYSTEM_SCHEMA_NAME,ns.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),nh.resetReadTxn(ns.SYSTEM_SCHEMA_NAME,ns.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=eie();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Sl.error(t)}}o(nie,"syncSchemaMetadata");var NH=[];async function wH(e){try{try{nh.resetReadTxn(ns.SYSTEM_SCHEMA_NAME,ns.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),nh.resetReadTxn(ns.SYSTEM_SCHEMA_NAME,ns.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Sl.warn(r)}let t=IH(e);if(t){Sl.error(t);return}Sl.trace(`ITC userHandler ${ns.HDB_ITC_CLIENT_PREFIX}${Zse.pid} received user event:`,e),await Xse.setUsersWithRolesCache();for(let r of NH)r()}catch(t){Sl.error(t)}}o(wH,"userHandler");wH.addListener=function(e){NH.push(e)};OH.exports=tie});var oi=M((cLe,PH)=>{"use strict";var sLe=Q(),nN=ie(),sie=(k(),v(W)),{ITC_ERRORS:ih}=rn(),{parentPort:iLe,threadId:iie,isMainThread:oie,workerData:oLe}=require("worker_threads"),{onMessageFromWorkers:aie,broadcast:aLe,broadcastWithAcknowledgement:cie}=nt();PH.exports={sendItcEvent:lie,validateEvent:CH,SchemaEventMsg:uie,UserEventMsg:die};var Rg;aie(async(e,t)=>{Rg=Rg||sh(),CH(e),Rg[e.type]&&await Rg[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function lie(e){return!oie&&e.message&&(e.message.originator=iie),cie(e)}o(lie,"sendItcEvent");function CH(e){if(typeof e!="object")return ih.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||nN.isEmpty(e.type))return ih.MISSING_TYPE;if(!e.hasOwnProperty("message")||nN.isEmpty(e.message))return ih.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||nN.isEmpty(e.message.originator))return ih.MISSING_ORIGIN;if(sie.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return ih.INVALID_EVENT(e.type)}o(CH,"validateEvent");function uie(e,t,r,n=void 0,s=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=n,this.attribute=s}o(uie,"SchemaEventMsg");function die(e){this.originator=e}o(die,"UserEventMsg")});var Co=M((dLe,vH)=>{"use strict";var LH=(k(),v(W)),uLe=ie(),yg=Q(),DH=DU(),Zu,{sendItcEvent:MH}=oi();function fie(e){try{yg.info("signalSchemaChange called with message:",e),Zu=Zu||sh();let t=new DH(LH.ITC_EVENT_TYPES.SCHEMA,e);return Zu.schema(t),MH(t)}catch(t){yg.error(t)}}o(fie,"signalSchemaChange");function mie(e){try{yg.trace("signalUserChange called with message:",e),Zu=Zu||sh();let t=new DH(LH.ITC_EVENT_TYPES.USER,e);return Zu.user(t),MH(t)}catch(t){yg.error(t)}}o(mie,"signalUserChange");vH.exports={signalSchemaChange:fie,signalUserChange:mie}});function Ag(){return sN||(sN=ze({table:"hdb_analytics_hostname",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"hostname"}]})),sN}function pie(e){return e=e.replace(hie,t=>{let[r,n,s,i]=t.split(".").map(a=>parseInt(a));return(r<<8|n).toString(16)+":"+(s<<8|i).toString(16)}),e=e.replace("::",":".repeat(10-e.split(":").length)),e.toLowerCase().split(":").map(t=>t.padStart(4,"0")).join(":")}function Eie(e){if(e.length!==4)throw new Error(`nodeHash must be exactly 4 bytes (32 bits); got ${e.length} bytes`);return e[0]<<24|e[1]<<16|e[2]<<8|e[3]}function oN(e){let t=UH.default.createHash("shake128",{outputLength:4}),r;return(0,xH.isIPv6)(e)?r=pie(e):r=e.toLowerCase(),Eie(Uint8Array.from(t.update(r).digest()))}var UH,xH,iN,sN,hie,aN=ue(()=>{De();UH=w(require("crypto")),xH=require("node:net"),iN=new Map;o(Ag,"getAnalyticsHostnameTable");hie=/(\d{1,3}\.){3}\d{1,3}$/;o(pie,"normalizeIPv6");o(Eie,"nodeHashToNumber");o(oN,"stableNodeId")});var vo,cN=ue(()=>{vo={TABLE_SIZE:"table-size",DATABASE_SIZE:"database-size",STORAGE_VOLUME:"storage-volume",MAIN_THREAD_UTILIZATION:"main-thread-utilization",RESOURCE_USAGE:"resource-usage",UTILIZATION:"utilization"}});var Og={};Oe(Og,{addAnalyticsListener:()=>ch,calculateCPUUtilization:()=>ZH,diffResourceUsage:()=>ek,recordAction:()=>it,recordActionBinary:()=>zr,recordHostname:()=>dN,setAnalyticsEnabled:()=>_ie});function _ie(e){zH=e}function gie(e,t){if(typeof e=="number"){let r=t.values,n=r.index++;if(n>=r.length){let s=r;t.values=r=new Float32Array(n*2),r.set(s),r.index=n+1}r[n]=e,t.total+=e}else if(typeof e=="boolean")e&&t.total++,t.count++;else if(typeof e=="function")t.count++;else throw new TypeError("Invalid metric value type "+typeof e)}function Sie(e,t,r,n,s,i){let a={};if(typeof t=="number")a.total=t,a.values=new Float32Array(4),a.values.index=1,a.values[0]=t,a.total=t;else if(typeof t=="boolean")a.total=t?1:0,a.count=1;else if(typeof t=="function")a.count=1,a.callback=t;else throw new TypeError("Invalid metric value type "+typeof t);a.description={metric:r,path:n,method:s,type:i},Ng.set(e,a)}function it(e,t,r,n,s){if(!zH)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let a=Ng.get(i);a?gie(e,a):Sie(i,e,t,r,n,s),Ig||Tie()}function zr(e,t,r,n,s){it(!!e,t,r,n,s)}function ch(e){JH.push(e)}function Tie(){Ig=performance.now(),setTimeout(async()=>{let e=performance.now()-Ig;Ig=0;let t=[],r={time:Date.now(),period:e,threadId:Tl.threadId,metrics:t};for(let[s,i]of Ng){if(i.values){let a=i.values.subarray(0,i.values.index);a.sort();let c=a.length,l=0,u=[],d;for(let f of XH){let m=Math.floor(c*f),h=a[m-1];if(m>l){let p=m-l;if(h===d){let _=u[u.length-1];typeof _=="number"?u[u.length-1]={value:_,count:1+p}:_.count+=p}else u.push(p>1?{value:h,count:p}:h),d=h;l=m}}t.push(Object.assign(i.description,{mean:i.total/c,distribution:u,count:c}))}else i.callback?t.push(Object.assign(i.description,i.callback(i))):t.push(Object.assign(i.description,{total:i.total,count:i.count}));await tk()}let n=process.memoryUsage();t.push({metric:"memory",threadId:Tl.threadId,byThread:!0,...n});for(let s of JH)s(t);Ng=new Map,Tl.parentPort?Tl.parentPort.postMessage({type:QH,report:r}):sk({report:r})},jH).unref()}async function dN(){let e=Le.hostname;Wr.trace?.("recordHostname server.hostname:",e);let t=oN(e);Wr.trace?.("recordHostname nodeId:",t);let r=Ag();if(!await r.get(t)){let s={id:t,hostname:e};Wr.trace?.(`recordHostname storing hostname: ${JSON.stringify(s)}`),r.put(s.id,s)}}function ed(e,t){let r=Le.hostname,n=iN.get(r);n?Wr.trace?.("storeMetric cached nodeId:",n):(n=oN(r),Wr.trace?.("storeMetric new nodeId:",n),iN.set(r,n));let s={id:[(0,uN.getNextMonotonicTime)(),n],...t};Wr.trace?.(`storing metric ${JSON.stringify(s)}`),e.put(s.id,s)}function ZH(e,t){let r=e.userCPUTime+e.systemCPUTime;return Wr.trace?.(`calculateCPUUtilization cpuTime: ${r} period: ${t}`),Math.round(r/t*100)/100}function ek(e,t){return{userCPUTime:t.userCPUTime-(e?.userCPUTime??0),systemCPUTime:t.systemCPUTime-(e?.systemCPUTime??0),minorPageFault:t.minorPageFault-(e?.minorPageFault??0),majorPageFault:t.majorPageFault-(e?.majorPageFault??0),fsRead:t.fsRead-(e?.fsRead??0),fsWrite:t.fsWrite-(e?.fsWrite??0),voluntaryContextSwitches:t.voluntaryContextSwitches-(e?.voluntaryContextSwitches??0),involuntaryContextSwitches:t.involuntaryContextSwitches-(e?.involuntaryContextSwitches??0)}}function Rie(e,t,r){let n=0;for(let[s,i]of Object.entries(r)){let a=`${t}.${s}`,c=i.getSize(),l={metric:vo.TABLE_SIZE,database:t,table:s,size:c};Wr.trace?.(`table ${a} size metric: ${JSON.stringify(l)}`),ed(e,l),n+=c}return n}function BH(e,t){for(let[r,n]of Object.entries(t))try{let[s]=Object.values(n),i=s?.getAuditSize();if(!i)return;let a=WH.statSync(s.primaryStore.env.path).size,c=Rie(e,r,n),l=a-c,u={metric:vo.DATABASE_SIZE,database:r,size:a,used:c,free:l,audit:i};ed(e,u),Wr.trace?.(`database ${r} size metric: ${JSON.stringify(u)}`)}catch(s){Wr.warn?.("Error getting DB size metrics",s)}}function FH(e,t){for(let[r,n]of Object.entries(t))try{let[s]=Object.values(n),i=s?.getStorageStats();if(!i)return;let a={metric:vo.STORAGE_VOLUME,database:r,...i};ed(e,a),Wr.trace?.(`db ${r} storage volume metrics: ${JSON.stringify(a)}`)}catch(s){Wr.warn?.("Error getting DB volume metrics",s)}}async function yie(e,t=6e4){let r=fN(),n=rk(),s=new Promise(R=>{let N=performance.now();setImmediate(()=>{let O=performance.now();O-N>5e3&&Wr.warn?.("Unusually high event queue latency on the main thread of "+Math.round(O-N)+"ms"),N=performance.now()}),n.primaryStore.prefetch([1],()=>{let O=performance.now();O-N>5e3&&Wr.warn?.("Unusually high task queue latency on the main thread of "+Math.round(O-N)+"ms"),R(O-N)})}),i;for(let R of n.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(R.value?.time){i=R.value.time;break}if(Date.now()-t<i)return;let a,c=new Map,l=new Map,u=[],d;for(let{key:R,value:N}of r.primaryStore.getRange({start:i||!1,exclusiveStart:!0,end:1/0})){if(!N)continue;if(a){if(R>a+t)break}else a=R;d=R;let{metrics:O,threadId:F}=N;for(let Z of O||[]){let{path:G,method:Y,type:q,metric:K,count:ce,total:le,distribution:se,threads:pe,...Ne}=Z;ce||(ce=1);let Ue=K+(G?"-"+G:"");Y!==void 0&&(Ue+="-"+Y),q!==void 0&&(Ue+="-"+q);let xe=c.get(Ue);if(xe){if(xe.threads){let Jt=xe.threads[F];if(Jt)xe=Jt;else{xe.threads[F]={...Ne};continue}}xe.count||(xe.count=1);let Rr=xe.count;for(let Jt in Ne){let kt=Ne[Jt];typeof kt=="number"&&(xe[Jt]=(xe[Jt]*Rr+kt*ce)/(Rr+ce))}xe.count+=ce,le>=0&&(xe.total+=le,xe.ratio=xe.total/xe.count)}else xe={period:t,...Z},delete xe.distribution,c.set(Ue,xe),xe.byThread&&(xe.threads=[],xe.threads[F]={...Ne},u.push(xe));if(se){se=se.map(Jt=>typeof Jt=="number"?{value:Jt,count:1}:Jt);let Rr=l.get(Ue);Rr?Rr.push(...se):l.set(Ue,se)}}await tk()}for(let R of u){let{path:N,method:O,type:F,metric:Z,count:G,total:Y,distribution:q,threads:K,...ce}=R;K=K.filter(le=>le);for(let le in ce){if(typeof R[le]!="number")continue;let se=0;for(let pe of K){let Ne=pe[le];typeof Ne=="number"&&(se+=Ne)}R[le]=se}R.count=K.length,delete R.threads,delete R.byThread}for(let[R,N]of l){let O=c.get(R);N.sort((Jt,kt)=>Jt.value>kt.value?1:-1);let F=O.count-1,Z=[],G=0,Y=0,q;for(let Jt of XH){let kt=F*Jt;for(;G<kt;)q=N[Y++],G+=q.count,Y===1&&G--;let Xt=N[Y>1?Y-2:0];q||(q=N[0]),Z.push(q.value-(q.value-Xt.value)*(G-kt)/q.count)}let[K,ce,le,se,pe,Ne,Ue,xe,Rr]=Z;Object.assign(O,{p1:K,p10:ce,p25:le,median:se,p75:pe,p90:Ne,p95:Ue,p99:xe,p999:Rr})}let f;for(let[,R]of c)R.time=d,ed(n,R),f=!0;let m=Date.now(),{idle:h,active:p}=performance.eventLoopUtilization();if(f||p*10>h){let R={metric:vo.MAIN_THREAD_UTILIZATION,idle:h-HH,active:p-kH,taskQueueLatency:await s,time:m,...process.memoryUsage()};ed(n,R)}HH=h,kH=p;let _=process.resourceUsage();_.time=m,_.userCPUTime=_.userCPUTime/1e3,_.systemCPUTime=_.systemCPUTime/1e3,Wr.trace?.(`process.resourceUsage: ${JSON.stringify(_)}`);let g=ek(bg,_);Wr.trace?.(`diffed resourceUsage: ${JSON.stringify(g)}`),g.time=m,g.period=bg.time?m-bg.time:t,g.cpuUtilization=ZH(g,g.period);let y={metric:vo.RESOURCE_USAGE,...g};ed(n,y),bg=_;let T=st();BH(n,T),BH(n,{system:T.system}),FH(n,T),FH(n,{system:T.system})}async function GH(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function fN(){return qH||(qH=ze({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function rk(){return $H||($H=ze({table:"hdb_analytics",database:"system",audit:!0,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function Iie(){nk=!0;let e=(0,ah.get)(U.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await yie(jH,e),await GH(fN(),Aie),await GH(rk(),bie)},Math.min(e/2,2147483647)).unref()}function sk(e,t){let r=e.report;r.threadId=t?.threadId||Tl.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(VH+=n.mean*n.count);r.totalBytesProcessed=VH,t&&(r.metrics.push({metric:vo.UTILIZATION,...t.performance.eventLoopUtilization(KH.get(t))}),KH.set(t,t.performance.eventLoopUtilization())),r.id=(0,uN.getNextMonotonicTime)(),fN().primaryStore.put(r.id,r),nk||Iie(),Nie&&(ik=Oie(r))}async function Oie(e){if(await ik,!Ga){let r=(0,oh.dirname)((0,wg.getLogFilePath)());try{Ga=await(0,lN.open)((0,oh.join)(r,"analytics.log"),"r+")}catch{Ga=await(0,lN.open)((0,oh.join)(r,"analytics.log"),"w+")}}let t=(await Ga.stat()).size;if(t>wie){let r=Buffer.alloc(t);await Ga.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await Ga.write(r,{position:0}),await Ga.truncate(r.length),t=r.length}await Ga.write(JSON.stringify(e)+`
15
15
  `,t)}var Tl,YH,wg,oh,lN,uN,ah,WH,Wr,Ng,zH,Ig,jH,QH,JH,XH,HH,kH,bg,tk,Aie,bie,qH,$H,nk,VH,KH,Nie,ik,Ga,wie,zi=ue(()=>{Tl=require("worker_threads"),YH=w(nt());De();wg=w(Q()),oh=require("path"),lN=require("fs/promises"),uN=w(bn()),ah=w(oe());k();Mr();WH=w(require("node:fs"));aN();cN();Wr=(0,wg.forComponent)("analytics").conditional;(0,ah.initSync)();Ng=new Map,zH=(0,ah.get)(U.ANALYTICS_AGGREGATEPERIOD)>-1;o(_ie,"setAnalyticsEnabled");o(gie,"recordExistingAction");o(Sie,"recordNewAction");o(it,"recordAction");Le.recordAnalytics=it;o(zr,"recordActionBinary");Ig=0,jH=1e3,QH="analytics-report",JH=[];o(ch,"addAnalyticsListener");XH=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];o(Tie,"sendAnalytics");o(dN,"recordHostname");o(ed,"storeMetric");o(ZH,"calculateCPUUtilization");o(ek,"diffResourceUsage");o(Rie,"storeTableSizeMetrics");o(BH,"storeDBSizeMetrics");o(FH,"storeVolumeMetrics");o(yie,"aggregation");HH=0,kH=0,bg={userCPUTime:0,systemCPUTime:0},tk=o(()=>new Promise(setImmediate),"rest");o(GH,"cleanup");Aie=36e5,bie=31536e6;o(fN,"getRawAnalyticsTable");o(rk,"getAnalyticsTable");(0,YH.setChildListenerByType)(QH,sk);o(Iie,"startScheduledTasks");VH=0,KH=new Map,Nie=!1;o(sk,"recordAnalytics");wie=1e6;o(Oie,"logAnalytics")});function lh(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 ok(e,t){(typeof e.set!="function"||typeof e.has!="function")&&(e=new Os(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 Os,uh=ue(()=>{Os=class extends Map{static{o(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 a=i[1];if(n)r=(typeof a=="string"?a:a.join(", "))+", "+r;else if(typeof a=="string")r=[a,r];else{a.push(r);return}}return super.set(s,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}};o(lh,"appendHeader");o(ok,"mergeHeaders")});function Cg(e,t,r=Pie){let n;return function(...i){return n?n.length*mN>r?t(...i):new Promise((a,c)=>{n.push({args:i,fn(){try{let l=e(...i);a(l)}catch(l){c(l)}}})}):(n=[],s(performance.now(),i),e(...i))};function s(i,a){setImmediate(()=>{let c=performance.now();mN=(mN*4+c-i)/5;let l=n.shift();if(l){let{args:u,fn:d}=l;d(),s(c,u)}else n=null})}}var lk,Cie,Pie,ak,Lie,hN,ck,mN,pN=ue(()=>{lk=w(ei()),Cie=3e3,Pie=2e4,ak=0,Lie=3e4,hN=3e3,ck=performance.now()+hN,mN=0;o(Cg,"throttle");setInterval(()=>{let e=performance.now();e-ck-hN>Cie&&ak+Lie<e&&(lk.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"),ak=e),ck=e},hN).unref()});var Sk={};Oe(Sk,{EVICTED:()=>Jc,INVALIDATED:()=>wn,coerceType:()=>Lg,makeTable:()=>Mg});function Mg(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:a,databaseName:c,auditStore:l,schemaDefined:u,dbisDB:d,sealed:f,splitSegments:m,replicate:h}=e,{expirationMS:p,evictionMS:_,audit:g,trackDeletes:y}=e;_??=0;let{attributes:T}=e;T||(T=[]);let R=VA(i,n,l),N,O,F={},Z=Promise.resolve(),G,Y,q;for(let V of T)(V.assignCreatedTime||V.name==="__createdtime__")&&(G=V),(V.assignUpdatedTime||V.name==="__updatedtime__")&&(Y=V),V.expiresAt&&(q=V),V.isPrimaryKey&&(F=V);let K,ce=[],le=[],se=1,pe=2,Ne={},Ue={},xe=864e5,Rr=0,Jt,kt,Xt,Mf=!1,Cc,Gt,vf,Uf=yl.get(U.REPLICATION_DATABASES);if(Array.isArray(Uf)){for(let V of Uf)if(V.name===c&&V.replicateTo>=0){vf=V.replicateTo;break}}let bE=i.getRange({start:!1,end:!1}).constructor,IE=10,My=6;g&&Hf(),mm(i.env.path,V=>{if(O)return Ta(V)});class xf extends al{static{o(this,"Updatable")}getUpdatedTime(){return Ca.get(this.getRecord())?.version}getExpiresAt(){return Ca.get(this.getRecord())?.expiresAt}addTo(E,S){if(typeof S=="number"||typeof S=="bigint")this.set(E,new Vm(S));else throw new Error("Can not add or subtract a non-numeric value")}subtractFrom(E,S){return this.addTo(E,-S)}}class Pe extends xr{#e;#t;#r;#n;#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=g;static databasePath=a;static databaseName=c;static attributes=T;static replicate=h;static sealed=f;static splitSegments=m??!0;static createdTimeProperty=G;static updatedTimeProperty=Y;static propertyResolvers;static userResolvers={};static sources=[];static getResidencyById;static get expirationMS(){return p}static dbisDB=d;static schemaDefined=u;static sourcedFrom(E,S){if(S&&(this.sourceOptions=S,(S.expiration||S.eviction||S.scanInterval)&&this.setTTLExpiration(S)),S?.intermediateSource)E.intermediateSource=!0,this.sources.unshift(E);else{if(this.sources.some(L=>!L.intermediateSource)){if(this.sources.some(L=>L.name===E.name))return;throw new Error("Can not have multiple canonical (non-intermediate) sources")}this.sources.push(E)}O=O||E.get&&(!E.get.reliesOnPrototype||E.prototype.get),N=N||E.load;let A=o(L=>{let D=this.sources;if(D=D.filter(H=>H.intermediateSource&&H[L]&&(!H[L].reliesOnPrototype||H.prototype[L])),D.length>0)if(D.length===1){let H=D[0];return(C,x,z)=>{if(C?.source!==H)return H[L](x,z,C)}}else return(H,C,x)=>{let z=[];for(let ne of D){if(H?.source===ne)break;z.push(ne[L](C,x,H))}return Promise.all(z)}},"getApplyToIntermediateSource"),b=this.sources[this.sources.length-1];b.intermediateSource&&(b={});let I=o(L=>{if(b[L]&&(!b[L].reliesOnPrototype||b.prototype[L]))return(D,H,C)=>{if(!D?.source)return b[L](H,C,D)}},"getApplyToCanonicalSource");Ne={put:I("put"),patch:I("patch"),delete:I("delete"),publish:I("publish")},Ue={put:A("put"),patch:A("patch"),delete:A("delete"),publish:A("publish"),invalidate:A("invalidate")};let P=b.shouldRevalidateEvents;return(async()=>{let L=!1,D,H=o(async(C,x)=>{let z=C.value,ne=C.table?ke[c][C.table]:Pe;if(c===Vf&&(C.table===_u.ROLE_TABLE_NAME||C.table===_u.USER_TABLE_NAME)&&(L=!0),C.id===void 0&&(C.id=z[ne.primaryKey],C.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(C));C.source=E;let re={residencyId:Dc(C.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:C.nodeId,async:!0},B=C.id,de=await ne.getResource(B,x,re);switch(C.finished&&await C.finished,C.type){case"put":return P?de._writeInvalidate(B,z,re):de._writeUpdate(B,z,!0,re);case"patch":return P?de._writeInvalidate(B,z,re):de._writeUpdate(B,z,!1,re);case"delete":return de._writeDelete(B,re);case"publish":case"message":return de._writePublish(B,z,re);case"invalidate":return de._writeInvalidate(B,z,re);case"relocate":return de._writeRelocate(B,re);default:Me.default.error?.("Unknown operation",C.type,C.id)}},"writeUpdate");try{let C=E.subscribe;C&&y==null&&(y=!0);let x={crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0},z=E.subscribeOnThisThread?E.subscribeOnThisThread((0,Rl.getWorkerIndex)(),x):(0,Rl.getWorkerIndex)()===0,ne=C&&z&&await E.subscribe?.(x);if(ne){let re;for await(let B of ne)try{if(!(B.type==="transaction"?B.writes[0]:B)){Me.default.error?.("Bad subscription event",B);continue}if(B.source=E,B.type==="end_txn"){if(re?.resolve(),B.localTime&&D!==B.localTime){if(B.remoteNodeIds?.length>0){let Se=[Symbol.for("seq"),B.remoteNodeIds[0]],ee=d.get(Se),j=ee?.nodes;j||(j=[]);for(let Te of B.remoteNodeIds.slice(1)){let fe=j.find(We=>We.id===Te);j=j.filter(We=>We.id!==Te||We===fe),fe||(fe={id:Te,seqId:0},j.push(fe)),fe.seqId=Math.max(ee?.seqId??1,B.localTime),Te===re?.nodeId&&(fe.lastTxnTime=B.timestamp)}let he=Math.max(ee?.seqId??1,B.localTime);Me.default.trace?.("Received txn",c,he,new Date(he),B.localTime,new Date(B.localTime),B.remoteNodeIds),d.put(Se,{seqId:he,nodes:j})}D=B.localTime}B.onCommit&&re?.committed.then(B.onCommit);continue}if(re)if(B.beginTxn)re.resolve();else{re.write_promises.push(H(B,re));continue}!B.timestamp&&B.version&&(B.timestamp=B.version);let me=Ut(B,()=>{if(B.type==="transaction"){let Se=[];for(let ee of B.writes)try{Se.push(H(ee,B))}catch(j){throw j.message+=" writing "+JSON.stringify(ee)+" of event "+JSON.stringify(B),j}return Promise.all(Se)}else if(B.type==="define_schema"){let Se=this.attributes.slice(0),ee=!1;for(let j of B.attributes)Se.find(he=>he.name===j.name)||(Se.push(j),ee=!0);ee&&(ze({table:s,database:c,attributes:Se,origin:"cluster"}),fh.signalSchemaChange(new mh.SchemaEventMsg(process.pid,$.CREATE_TABLE,c,s)))}else return B.beginTxn?(re=B,re.write_promises=[H(B,B)],new Promise(Se=>{re.resolve=()=>Se(Promise.all(re.write_promises))})):H(B,B)});re&&(re.committed=me),L&&me&&!me?.waitingForUserChange&&(me.then(()=>fh.signalUserChange(new mh.UserEventMsg(process.pid))),me.waitingForUserChange=!0),B.onCommit&&(me?me.then(B.onCommit):B.onCommit())}catch(de){Me.default.error?.("error in subscription handler",de)}}}catch(C){Me.default.error?.(C)}})(),this}static get isCaching(){return O}static get shouldRevalidateEvents(){return this.prototype.get!==Pe.prototype.get}static getResource(E,S,A){let b=super.getResource(E,S,A);if(this.loadAsInstance===!1&&(S._freezeRecords=!0),E!=null&&this.loadAsInstance!==!1){Lr(E);try{if(b.getRecord?.())return b;if(typeof E=="object"&&E&&!Array.isArray(E))throw new Error(`Invalid id ${JSON.stringify(E)}`);let I=!A?.async||i.cache?.get?.(E),P=Dr(S),L=P.getReadTxn();if(L?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Ea(E,S,{transaction:L,ensureLoaded:A?.ensureLoaded},I,D=>{if(D?Pe._updateResource(b,D):b.#e=null,S.onlyIfCached){if(!b.doesExist())throw new ot.ServerError("Entry is not cached",504)}else if(A?.ensureLoaded){let H=Pc(E,D,S,b);if(H)return P?.disregardReadTxn(),b.#i=!0,S.loadedFromSource=!0,Cs(H,C=>(Pe._updateResource(b,C),b))}return b})}catch(I){throw I.message.includes("Unable to serialize object")&&(I.message+=": "+JSON.stringify(E)),I}}return b}static _updateResource(E,S){E.#n=S,E.#e=S?.value??null,E.#r=S?.version}ensureLoaded(){let E=Pc(this.getId(),this.#n,this.getContext());if(E)return this.#i=!0,this.getContext().loadedFromSource=!0,Cs(E,S=>{this.#n=S,this.#e=S.value,this.#r=S.version})}static getNewId(){let E=F?.type;if(E==="String"||E==="ID")return super.getNewId();if(!Gt){let I=i.getEntry(Symbol.for("id_allocation")),P=I?.value,L;if(P&&P.nodeName===server.hostname&&(!qie(i)||P.pid===process.pid)){let D=P.start,H=P.end;L=D;for(let C of i.getKeys({start:H,end:D,limit:1,reverse:!0}))L=C}else P=b(I?.version??null),L=P.start;Gt=new BigInt64Array([BigInt(L)+1n]),Gt=new BigInt64Array(i.getUserSharedBuffer("id",Gt.buffer)),Gt.maxSafeId=P.end}let S=Number(Atomics.add(Gt,0,1n)),A=E==="Int"?512:1048576;if(S+A>=Gt.maxSafeId){let I=o(P=>{Gt.maxSafeId=S+(E==="Int"?1023:4194303);let L=(E==="Int"?Math.pow(2,31):Math.pow(2,49))-1,D=P?void 0:i.useReadTransaction(),H=Number(Gt[0]);for(let z of i.getKeys({start:H+1,end:L,limit:1,transaction:D}))L=z;D?.done();let{value:C,version:x}=i.getEntry(Symbol.for("id_allocation"));if(Gt.maxSafeId<L){if(C.end>Gt.maxSafeId-100)return;Me.default.info?.("New id allocation",S,Gt.maxSafeId,x),i.put(Symbol.for("id_allocation"),{start:C.start,end:Gt.maxSafeId,nodeName:server.hostname,pid:process.pid},Date.now(),x)}else{Me.default.warn?.(`Id conflict detected, starting new id allocation range, attempting to allocate to ${Gt.maxSafeId}, but id of ${L} detected`);let z=b(x);z.alreadyUpdated||Atomics.store(Gt,0,BigInt(z.start+1)),Gt.maxSafeId=z.end}},"updateEnd");S+A===Gt.maxSafeId?setImmediate(I):S+100>=Gt.maxSafeId&&(Me.default.warn?.(`Synchronous id allocation required on table ${s}${E=="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`),i.transactionSync(()=>I(!0)))}return S;function b(I){let P=(E==="Int"?Math.pow(2,31):Math.pow(2,49))-1,L=P/4,D,H,C=!1,x,z;do{x=Math.floor(Math.random()*P),z={start:x,end:x+(E==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},D=0;for(let ne of i.getKeys({start:x,limit:1,reverse:!0}))D=ne;H=P;for(let ne of i.getKeys({start:x+1,end:P,limit:1}))H=ne;L*=.875,L<1e3&&!C&&(C=!0,Me.default.error?.(`Id allocation in table ${s} is very dense, limited safe range of numbers to allocate ids in${E==="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`,x,D,H,L))}while(!(L<H-x&&(L<x-D||D===0)));return i.transactionSync(()=>{let ne=i.getEntry(Symbol.for("id_allocation"));return(ne?.version??null)==I?(Me.default.info?.("Allocated new id range",z),i.put(Symbol.for("id_allocation"),z,Date.now()),z):(Me.default.debug?.("Looks like ids were already allocated"),{alreadyUpdated:!0,...ne.value})})}}static setTTLExpiration(E){if(typeof E=="number")p=E*1e3,_||(_=0);else if(E&&typeof E=="object")p=E.expiration*1e3,_=(E.eviction||0)*1e3,xe=E.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(p<0)throw new Error("Expiration can not be negative");xe=xe||(p+_)/4,Ta()}static getResidencyRecord(E){return d.get([Symbol.for("residency_by_id"),E])}static setResidency(E){Pe.getResidency=E&&((S,A)=>{try{return E(S,A)}catch(b){throw b.message+=` in residency function for table ${s}`,b}})}static setResidencyById(E){Pe.getResidencyById=E&&(S=>{try{return E(S)}catch(A){throw A.message+=` in residency function for table ${s}`,A}})}static getResidency(E,S){if(Pe.getResidencyById)return Pe.getResidencyById(E[t]);let A=vf;if(S.replicateTo!=null){if(Array.isArray(S.replicateTo))return S.replicateTo.includes(server.hostname)?S.replicateTo:[server.hostname,...S.replicateTo];S.replicateTo>=0&&(A=S.replicateTo)}if(A>=0&&server.nodes){let b=[server.hostname];if(S.previousResidency)b.push(...S.previousResidency.slice(0,A));else{let I=server.nodes.map(D=>D.name),P=Math.floor(I.length*Math.random());b.push(...I.slice(P,P+A));let L=P+A-I.length;L>0&&b.push(...I.slice(0,L))}return b}}static enableAuditing(E=!0){g=E,E&&Hf(),Pe.audit=E}static coerceId(E){return E===""?null:Lg(E,F)}static async dropTable(){delete ke[c][s];for(let E of i.getRange({versions:!0,snapshot:!1,lazy:!0}))E.metadataFlags&Vr&&E.value&&wa(E.value);if(c===a){for(let E of T)d.remove(Pe.tableName+"/"+E.name),r[E.name]?.drop();d.remove(Pe.tableName+"/"),i.drop(),await d.committed}else console.log("legacy dropTable"),await i.close(),_N.default.unlinkSync(i.env.path);fh.signalSchemaChange(new mh.SchemaEventMsg(process.pid,$.DROP_TABLE,c,s))}get(E){let S=this.constructor;if(typeof E=="string"&&S.loadAsInstance!==!1)return this.getProperty(E);if(Ff(E))return this.search(E);if(E&&E.id===void 0&&!E.toString()){let A={records:"./",name:s,database:c,auditSize:l?.getStats().entryCount,attributes:T,recordCount:void 0,estimatedRecordRange:void 0};return this.getContext()?.includeExpensiveRecordCountEstimates?Pe.getRecordCount().then(b=>(A.recordCount=b.recordCount,A.estimatedRecordRange=b.estimatedRange,A)):A}if(E!==void 0&&S.loadAsInstance===!1){let A=this.getContext(),b=Dr(A),I=b.getReadTxn();if(I?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");let P=yr(E);Lr(P);let L=!0;return E.checkPermission&&(L=this.allowRead(A.user,E)),Cs(Cs(L,D=>{if(!D)throw new ot.AccessViolation(A.user);let H=!0;return Ea(P,A,{transaction:I,ensureLoaded:H},!1,C=>{if(A.onlyIfCached){if(!C?.value)throw new ot.ServerError("Entry is not cached",504)}else if(H){let x=Pc(P,C,A);if(x)return b?.disregardReadTxn(),A.loadedFromSource=!0,x.then(z=>z?.value)}return C?.value})}),D=>{let H=E?.select;return H&&D!=null?Uu(H,this.constructor)(D):D})}if(E?.property)return this.getProperty(E.property);if(this.doesExist()||E?.ensureLoaded===!1||this.getContext()?.returnNonexistent)return this}allowRead(E,S){let A=_a(E,S);if(A?.read){if(A.isSuperUser)return!0;let b=A.attribute_permissions,I=S?.select;if(b?.length>0||Mf&&I){if(S||(S={}),I){let P=Array.isArray(I)?I:[I],L=b?.length>0&&EN(b,"read");S.select=P.map(D=>{let H=D.name||D;if(!L||L[H]){let C=Xt[H]?.definition?.tableClass;if(C){if(D.name||(D={name:D}),!D.checkPermission&&S.checkPermission&&(D.checkPermission=S.checkPermission),!C.prototype.allowRead.call(null,E,D))return!1;if(!D.select)return D.name}return D}}).filter(Boolean)}else S.select=b.filter(P=>P.read&&!Xt[P.attribute_name]).map(P=>P.attribute_name);return S}else return!0}}allowUpdate(E,S,A){let b=_a(E,A);if(b?.update){let I=b.attribute_permissions;if(I?.length>0){let P=EN(I,"update");for(let L in S)if(!P[L])return!1;for(let L of I){let D=L.attribute_name;!L.update&&!(D in S)&&(S[D]=this.getProperty(D))}}return Sa(this.getContext())}}allowCreate(E,S,A){if(this.isCollection){let b=_a(E,A);if(b?.insert){let I=b.attribute_permissions;if(I?.length>0){let P=EN(I,"insert");for(let L in S)if(!P[L])return!1;return Sa(this.getContext())}else return Sa(this.getContext())}}else return this.allowUpdate(E,{})}allowDelete(E,S){return _a(E,S)?.delete&&Sa(this.getContext())}update(E,S){let A,b=typeof S=="boolean"||S===void 0&&(E==null||typeof E=="object"&&!(E instanceof URLSearchParams)),I=!1;b?(I=S,S=E,A=this.getId()):A=yr(E);let P=this.getContext();if(!Dr(P))throw new Error("Can not update a table resource outside of a transaction");if(S===!1)return this;if(typeof S=="object"&&S)if(I)Object.isFrozen(S)&&(S={...S}),this.#e={},this.#t=S;else if(b){let D=this.#t;D&&(S=Object.assign(D,S)),this.#t=S}else{let D=!0;if(E==null)throw new TypeError("Can not put a record without a target");return E.checkPermission&&(D=this.allowUpdate(P.user,S,E)),Cs(D,H=>{if(!H)throw new ot.AccessViolation(P.user);return Cs(i.get(yr(E)),C=>{let x=new xf(C);return x._setChanges(S),this._writeUpdate(A,x.getChanges(),!1),x})})}return this._writeUpdate(A,this.#t,I),this}addTo(E,S){if(typeof S=="number"||typeof S=="bigint")this.#s===dk?this.set(E,(+this.getProperty(E)||0)+S):(this.#s||this.update(),this.set(E,new Vm(S)));else throw new Error("Can not add a non-numeric value")}subtractFrom(E,S){if(typeof S=="number")return this.addTo(E,-S);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this.#n}getRecord(){return this.#e}getChanges(){return this.#t}_setChanges(E){this.#t=E}setRecord(E){this.#e=E}invalidate(E){let S=!0,A=this.getContext();return E?.checkPermission&&(S=this.allowDelete(A.user,E,A)),Cs(S,b=>{if(!b)throw new ot.AccessViolation(A.user);this._writeInvalidate(E?yr(E):this.getId())})}_writeInvalidate(E,S,A){let b=this.getContext();Lr(E),Dr(this.getContext()).addWrite({key:E,store:i,invalidated:!0,entry:this.#n,before:Ne.invalidate?.bind(this,b,E),beforeIntermediate:Ra(S,Ue.invalidate?.bind(this,b,E)),commit:o((P,L)=>{if(!(ga(P,L,A?.nodeId)<=0)){S??=null;for(let D in r)S||(S={}),S[D]===void 0&&(S[D]=this.getProperty(D));Me.default.trace?.(`Invalidating entry in ${s} id: ${E}, timestamp: ${new Date(P).toISOString()}`),R(E,S,L,P,wn,g,{user:b?.user,residencyId:A?.residencyId,nodeId:A?.nodeId},"invalidate")}},"commit")})}_writeRelocate(E,S){let A=this.getContext();Lr(E),Dr(this.getContext()).addWrite({key:E,store:i,invalidated:!0,entry:this.#n,before:Ne.relocate?.bind(this,A,E),beforeIntermediate:Ue.relocate?.bind(this,A,E),commit:o((I,P)=>{if(ga(I,P,S?.nodeId)<=0)return;let L=Pe.getResidencyRecord(S.residencyId),D=0,H=null,C=P?.value;if(L&&!L.includes(server.hostname)){for(let x in r)H||(H={}),H[x]=C[x];D=wn}else H=C;Me.default.trace?.(`Relocating entry id: ${E}, timestamp: ${new Date(I).toISOString()}`),R(E,H,P,I,D,g,{user:A.user,residencyId:S.residencyId,nodeId:S.nodeId,expiresAt:S.expiresAt},"relocate",!1,null)},"commit")})}static _recordRelocate(E,S){if(this.getResidencyById)return!1;let A={previousResidency:this.getResidencyRecord(E.residencyId),isRelocation:!0},b=Lc(this.getResidency(S.value,A)),I;if(b){if(!b.includes(server.hostname))return!1;I=Dc(b)}let P=0;Me.default.debug?.("Performing a relocate of an entry",existing_entry.key,S.value,b);let L=R(E.key,S.value,E,E.version,P,!0,{residencyId:I,expiresAt:S.expiresAt},"relocate",!1,null);return!0}static evict(E,S,A){let b=this.Source,I;if(!((O||g)&&(!S||(I=i.getEntry(E),!I||!S)||I.version!==A))){if(O){if(i.hasLock(E,I.version))return;let P;for(let L in r)P||(P={}),P[L]=S[L];if(P)return R(E,P,I,A,Jc,null,null,null,!0)}return i.ifVersion(E,A,()=>{po(E,S,null)}),Qc(i,I??i.getEntry(E),A)}}lock(){throw new Error("Not yet implemented")}static operation(E,S){return E.table||=s,E.schema||=c,global.operation(E,S)}put(E,S){if(S===void 0||S instanceof URLSearchParams)this.update(E,!0);else{let A=!0;if(E==null)throw new TypeError("Can not put a record without a target");let b=this.getContext();return E.checkPermission&&(A=this.allowUpdate(b.user,S,E)),Cs(A,I=>{if(!I)throw new ot.AccessViolation(b.user);if(Array.isArray(S))for(let P of S){let L=P[t];this._writeUpdate(L,P,!0)}else{let P=yr(E);this._writeUpdate(P,S,!0)}})}}create(E,S){let A=!0,b=this.getContext();if(!S&&!(E instanceof URLSearchParams)&&(S=E,E=void 0),!S||typeof S!="object"||Array.isArray(S))throw new TypeError("Can not create a record without an object");return E?.checkPermission&&(A=this.allowCreate(b.user,S,E)),Cs(A,I=>{if(!I)throw new ot.AccessViolation(b.user);let P=yr(E)??S[t];if(P===void 0)P=this.constructor.getNewId();else if(i.get(P))throw new ot.ClientError("Record already exists",409);return this._writeUpdate(P,S,!0),S})}patch(E,S){if(S===void 0||S instanceof URLSearchParams)this.update(E,!1);else{let A=this.update(E,S);if(A?.then)return A.then(()=>{})}}_writeUpdate(E,S,A,b){let I=this.getContext(),P=Dr(I);Lr(E);let L=this.#n??i.getEntry(E);this.#s=A?dk:Fie;let D=o(C=>A?C.put?()=>C.put(I,E,S):null:C.patch?()=>C.patch(I,E,S):C.put?()=>C.put(I,E,cl(this)):null,"writeToSources"),H={key:E,store:i,entry:L,nodeName:I?.nodeName,validate:o(C=>{S||(S=this.#t),A||S&&X_(this.#t===S?this:S)?I?.source||(P.checkOverloaded(),this.validate(S,!A),Y&&(S[Y.name]=Y.type==="Date"?new Date(C):Y.type==="String"?new Date(C).toISOString():C),A&&(t&&S[t]!==E&&(S[t]=E),G&&(L?.value?S[G.name]=L?.value[G.name]:S[G.name]=G.type==="Date"?new Date(C):G.type==="String"?new Date(C).toISOString():C),S=cl(S))):P.removeWrite(H)},"validate"),before:D(Ne),beforeIntermediate:Ra(S,D(Ue)),commit:o((C,x,z)=>{if(z){if(I&&x?.version>(I.lastModified||0)&&(I.lastModified=x.version),this.#n=x,x?.value&&x.value.getRecord)throw new Error("Can not assign a record to a record, check for circular references");A||(this.#e=x?.value??null)}this.#t=void 0,this.#r=C;let ne=x?.value,re=S;this.#s=0;let B=!1,de=ga(C,x,b?.nodeId),me,Se=A?"put":"patch",ee;b?.residencyId!=null&&(ee=b.residencyId);let j=I?.expiresAt??(p?p+Date.now():-1);if(de<=0){if(g){let fe=x.localTime,We=x.version;Me.default.trace?.("Applying CRDT update to record with id: ",E,"txn time",new Date(C),"applying later update from:",new Date(We),"local recorded time",new Date(fe));let Et=[];for(;fe>C||We>=C&&fe>0;){let dt=l.get(fe);if(!dt)break;let Ee=At(dt);if(We=Ee.version,We>=C){if(We===C){if(de=ga(C,{version:We,localTime:fe},b?.nodeId),de===0)return Te(!1);if(de>0)continue}if(Ee.type==="patch")Et.push(Ee),me=S;else if(Ee.type==="put"||Ee.type==="delete")return Te(!1)}fe=Ee.previousLocalTime}fe||Me.default.debug?.("No further audit history, applying incremental updates based on available history",E,"existing version preserved",x),Et.sort((dt,Ee)=>dt.version-Ee.version);for(let dt of Et){let Ee=dt.getValue(i);if(Me.default.debug?.("Rebuilding update with future patch:",new Date(dt.version),Ee,dt),re=zE(re,Ee,A),!re)return Te(!1)}}else{if(A)return Te(!1);re=zE(re,ne,A),Me.default.debug?.("Rebuilding update without audit:",re)}Me.default.trace?.("Rebuilt record to save:",re," is full update:",A)}let he;if(A?he=re:this.constructor.loadAsInstance===!1?he=cl(ne,re):(this.#e=ne,he=cl(this,re)),this.#e=he,he&&he.getRecord)throw new Error("Can not assign a record to a record, check for circular references");if(ee==null){L?.residencyId&&(I.previousResidency=Pe.getResidencyRecord(L.residencyId));let fe=Lc(Pe.getResidency(he,I));if(fe&&!fe.includes(server.hostname))if(me??=he,B=!0,Pe.getResidencyById)he=void 0;else{he=null;for(let We in r)he||(he={}),he[We]=me[We]}ee=Dc(fe)}A||(me=S),Me.default.trace?.(`Saving record with id: ${E}, timestamp: ${new Date(C).toISOString()}${j?", expires at: "+new Date(j).toISOString():""}${x?", replaces entry from: "+new Date(x.version).toISOString():", new entry"}`,(()=>{try{return JSON.stringify(he).slice(0,100)}catch{return""}})()),po(E,ne,he),Te(!0),I.expiresAt&&Ta();function Te(fe){R(E,fe?he:void 0,fe?x:{...x,value:void 0},C,B?wn:0,g,{omitLocalRecord:B,user:I?.user,residencyId:ee,expiresAt:j,nodeId:b?.nodeId,originatingOperation:I?.originatingOperation},Se,!1,fe?me:me??S)}o(Te,"writeCommit")},"commit")};P.addWrite(H)}async delete(E){if(Ff(E)){E.select=["$id"];for await(let S of this.search(E))this._writeDelete(S.$id);return!0}if(E){let S=!0,A=this.getContext();return E.checkPermission&&(S=this.allowDelete(A.user,E,A)),Cs(S,b=>{if(!b)throw new ot.AccessViolation(A.user);let I=yr(E);return this._writeDelete(I),!0})}return this._writeDelete(this.getId()),!!this.#e}_writeDelete(E,S){let A=Dr(this.getContext());Lr(E);let b=this.getContext();return A.addWrite({key:E,store:i,entry:this.#n,nodeName:b?.nodeName,before:Ne.delete?.bind(this,b,E),beforeIntermediate:Ue.delete?.bind(this,b,E),commit:o((I,P,L)=>{let D=P?.value;L&&(b&&P?.version>(b.lastModified||0)&&(b.lastModified=P.version),Pe._updateResource(this,P)),!(ga(I,P,S?.nodeId)<=0)&&(po(this.getId(),D),Me.default.trace?.(`Deleting record with id: ${E}, txn timestamp: ${new Date(I).toISOString()}`),g||y?(R(E,null,P,I,0,g,{user:b?.user,nodeId:S?.nodeId},"delete"),g||Ta()):Qc(i,P))},"commit")}),!0}search(E){let S=this.getContext(),A=Dr(S);if(!E)throw new Error("No query provided");if(E.parseError)throw E.parseError;if(E.checkPermission&&!this.allowRead(S.user,E))throw new ot.AccessViolation(S.user);let b=E.conditions;b?b.length===void 0&&(b=b[Symbol.iterator]?Array.from(b):[b]):b=Array.isArray(E)?E:E[Symbol.iterator]?Array.from(E):[];let I=E.id??this.getId();I&&(b=[{attribute:null,comparator:Array.isArray(I)?"prefix":"starts_with",value:I}].concat(b));let P,L={};function D(j,he){let Te;switch(he){case"and":case void 0:if(j.length<1)throw new Error('An "and" operator requires at least one condition');Te=!0;break;case"or":if(j.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+he)}for(let fe of j){if(fe.conditions){fe.conditions=D(fe.conditions,fe.operator);continue}let We=fe[0]??fe.attribute,Et=We==null?F:Bi(T,We);if(Et)(Et.type||YA[fe.comparator])&&(fe[1]===void 0?fe.value=C(fe.value,Et):fe[1]=C(fe[1],Et));else if(We!=null&&!E.allowConditionsOnDynamicAttributes)throw(0,ot.handleHDBError)(new Error,`${We} is not a defined attribute`,404);if(fe.chainedConditions)if(fe.chainedConditions.length===1&&(!fe.operator||fe.operator=="and")){let dt=fe.chainedConditions[0],Ee,tt;if(dt.comparator==="gt"||dt.comparator==="greater_than"||dt.comparator==="ge"||dt.comparator==="greater_than_equal"?(Ee=fe,tt=dt):(Ee=dt,tt=fe),Ee.comparator!=="lt"&&Ee.comparator!=="less_than"&&Ee.comparator!=="le"&&Ee.comparator!=="less_than_equal")throw new Error("Invalid chained condition, only less than and greater than conditions can be chained together");let rt=tt.comparator==="ge"||tt.comparator==="greater_than_equal",cr=Ee.comparator==="le"||Ee.comparator==="less_than_equal";fe.comparator=(rt?"ge":"gt")+(cr?"le":"lt"),fe.value=[tt.value,Ee.value]}else throw new Error("Multiple chained conditions are not currently supported")}return j}o(D,"prepareConditions");function H(j,he){if(E.enforceExecutionOrder)return j;for(let Te of j)Te.conditions&&(Te.conditions=H(Te.conditions,Te.operator));return j.length>1&&he!=="or"?Die(j,I_(Pe)):j}o(H,"orderConditions");function C(j,he){return Array.isArray(j)?j.map(Te=>Lg(Te,he)):Lg(j,he)}o(C,"coerceTypedValues");let x=E.operator;(b.length>0||x)&&(b=D(b,x));let z=typeof E.sort=="object"&&E.sort,ne;if(z&&x!=="or"){let j=z.attribute;if(j==null)throw new ot.ClientError("Sort requires an attribute");if(P=b.find(he=>Du(he.attribute)===Du(j)),!P){let he=Bi(T,j);if(!he)throw(0,ot.handleHDBError)(new Error,`${Array.isArray(j)?j.join("."):j} is not a defined attribute`,404);if(he.indexed)P={...z,comparator:"sort"},b.push(P);else if(b.length===0&&!E.allowFullScan)throw(0,ot.handleHDBError)(new Error,`${Array.isArray(j)?j.join("."):j} is not indexed and not combined with any other conditions`,404)}P&&(P.descending=!!z.descending)}b=H(b,x),z&&(P&&b[0]===P?z.next&&(ne={dbOrderedAttribute:z.attribute,attribute:z.next.attribute,descending:z.next.descending,next:z.next.next}):(P&&b.splice(b.indexOf(P),1),ne=z));let re=E.select;if(b.length===0&&(b=[{attribute:t,comparator:"greater_than",value:!0}]),E.explain)return{conditions:b,operator:x,postOrdering:ne,selectApplied:!!re};let B=A.useReadTxn(),de=WA(b,x,Pe,B,E,S,(j,he)=>hu(j,re,S,B,he),L),me=E.ensureLoaded!==!1,Se=Pe.transformEntryForSelect(re,S,B,L,me,!0),ee=Pe.transformToOrderedSelect(de,re,ne,S,B,Se);return(E.offset||E.limit!==void 0)&&(ee=ee.slice(E.offset,E.limit!==void 0?(E.offset||0)+E.limit:void 0)),ee.onDone=()=>{ee.onDone=null,A.doneReadTxn()},ee.selectApplied=!0,ee.getColumns=()=>{if(re){let j=[];for(let he of re)he==="*"?j.push(...T.map(Te=>Te.name)):j.push(he.name||he);return j}return T.filter(j=>!j.computed&&!j.relationship).map(j=>j.name)},ee}static transformToOrderedSelect(E,S,A,b,I,P){let L=new bE;if(A){E=hu(E,S,b,I,null);let D;L.iterate=function(){let C,x=E[Symbol.asyncIterator]?E[Symbol.asyncIterator]():E[Symbol.iterator](),z,ne=A.dbOrderedAttribute,re,B,de=!0;function me(ee){let j=ee.next&&me(ee.next),he=ee.descending;return b.sort=ee,(Te,fe)=>{let We=mu(Te,ee.attribute,b),Et=mu(fe,ee.attribute,b),dt=he?(0,Al.compareKeys)(Et,We):(0,Al.compareKeys)(We,Et);return dt===0?j?.(Te,fe)||0:dt}}o(me,"createComparator");let Se=me(A);return{async next(){let ee;if(C)if(ee=C.next(),ee.done){if(z)return L.onDone&&L.onDone(),ee}else return{value:await P.call(this,ee.value)};D=[],re&&D.push(re);do if(ee=await x.next(),ee.done){if(z=!0,D.length)break;return L.onDone&&L.onDone(),ee}else{let j=ee.value;if(j?.then&&(j=await j),ne){let he=mu(j,ne,b);if(de)de=!1,B=he;else if(he!==B){B=he,re=j;break}}D.push(j)}while(!0);return A.isGrouped,D.sort(Se),C=D[Symbol.iterator](),ee=C.next(),ee.done?(L.onDone&&L.onDone(),ee):{value:await P.call(this,ee.value)}},return(){L.onDone&&L.onDone(),x.return()},throw(){L.onDone&&L.onDone(),x.throw()}}};let H=o(C=>{if(typeof S=="object"&&Array.isArray(C.attribute))for(let x=0;x<S.length;x++){let z=S[x],ne;if(z.name===C.attribute[0]){for(ne=z.sort||(z.sort={});ne.next;)ne=ne.next;ne.attribute=C.attribute.slice(1),ne.descending=C.descending}else z===C.attribute[0]&&(S[x]=ne={name:z,sort:{attribute:C.attribute.slice(1),descending:C.descending}})}C.next&&H(C.next)},"applySortingOnSelect");H(A)}else L.iterate=(E[Symbol.asyncIterator]||E[Symbol.iterator]).bind(E),L=L.map(function(D){try{let H=P.call(this,D);return typeof H?.catch=="function"?H.catch(C=>{throw C.partialObject={[t]:D.key},C}):H}catch(H){throw H.partialObject={[t]:D.key},H}});return L}static transformEntryForSelect(E,S,A,b,I,P){let L;I&&O&&!(typeof E=="string"?[E]:E)?.every(C=>{let x;return typeof C=="object"?x=C.name:x=C,r[x]||x===t})&&(L=!0);let D,H=o(function(C){let x;if(S?.transaction?.stale&&(S.transaction.stale=!1),C!=null){if(x=C.deref?C.deref():C.value,!x&&(C.key===void 0||C.deref)||C.metadataFlags&wn){if(C.metadataFlags&wn&&S.replicateFrom===!1&&P&&C.residencyId)return $a.SKIP;if(C=Ea(C.key??C,S,{transaction:A,lazy:E?.length<4,ensureLoaded:I},this?.isSync,z=>z),C?.then)return C.then(H.bind(this));x=C?.value}if(L&&C?.metadataFlags&(wn|Jc)||C?.expiresAt!=null&&C?.expiresAt<Date.now()){if(S.onlyIfCached)return{[t]:C.key,message:"This entry has expired"};let z=Pc(C.key??C,C,S);if(z?.then)return z.then(H)}}if(x==null)return P?$a.SKIP:x;if(E&&!(E[0]==="*"&&E.length===1)){let z,ne=o((B,de)=>{let me;typeof B=="object"?me=B.name:me=B;let Se=Xt?.[me],ee;if(Se){let j=b?.[me];if(j)if(j.hasMappings){let Te=Se.from?x[Se.from]:Du(C.key);ee=j.get(Te),ee||(ee=[])}else ee=j.fromRecord?.(x);else ee=Se(x,S,C,!0);let he=o(Te=>{if(Se.directReturn)return de(Te,me);if(Te&&typeof Te=="object"){let fe=Se.definition?.tableClass||Pe;D||(D={});let We=D[me]||(D[me]=fe.transformEntryForSelect(me===B?null:B.select||(Array.isArray(B)?B:null),S,A,j,I));if(Array.isArray(Te)){let Et=[],dt=fe.transformToOrderedSelect(Te,B.select,typeof B.sort=="object"&&B.sort,S,A,We)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),Ee=o(rt=>{for(;!rt.done;){if(rt?.then)return rt.then(Ee);Et.push(rt.value),rt=dt.next()}de(Et,me)},"nextValue"),tt=Ee(dt.next());tt&&(z||(z=[]),z.push(tt));return}else if(Te=We.call(this,Te),Te?.then){z||(z=[]),z.push(Te.then(Et=>de(Et,me)));return}}de(Te,me)},"handleResolvedValue");ee?.then?(z||(z=[]),z.push(ee.then(he))):he(ee);return}else ee=x[me],ee&&typeof ee=="object"&&me!==B&&(ee=Pe.transformEntryForSelect(B.select||B,S,A,null)({value:ee}));de(ee,me)},"selectAttribute"),re;if(typeof E=="string")ne(E,B=>{re=B});else if(Array.isArray(E))if(E.asArray)re=[],E.forEach((B,de)=>{B==="*"?E[de]=x:ne(B,me=>re[de]=me)});else{re={};let B=E.forceNulls;for(let de of E)if(de==="*")for(let me in x)re[me]=x[me];else ne(de,(me,Se)=>{me===void 0&&B&&(me=null),re[Se]=me})}else throw new ot.ClientError("Invalid select"+E);return z?Promise.all(z).then(()=>re):re}return x},"transform");return H}async subscribe(E){if(!l)throw new Error("Can not subscribe to a table without an audit log");g||ze({table:s,database:c,schemaDefined:u,attributes:T,audit:!0}),E||(E={});let S=!E.rawEvents,A=[],b=this,I=ZA(Pe,this.getId()??null,function(L,D,H,C){try{let x=D.getValue?.(i,S),z=D.type;if(!x&&z==="patch"&&S){let re=i.getEntry(L);re?.version===D.version?x=re.value:x=D.getValue?.(i,!0,H),z="put"}let ne={id:L,localTime:H,value:x,version:D.version,type:z,beginTxn:C};A?A.push(ne):this.send(ne)}catch(x){Me.default.error?.(x)}},E.startTime||0,E),P=(async()=>{this.isCollection&&(I.includeDescendants=!0,E.onlyChildren&&(I.onlyChildren=!0)),E.supportsTransactions&&(I.supportsTransactions=!0);let L=this.getId(),D=E.previousCount;D>1e3&&(D=1e3);let H=E.startTime;if(this.isCollection){if(H){if(D)throw new ot.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:C,value:x}of l.getRange({start:H,exclusiveStart:!0,snapshot:!1})){let z=At(x);if(z.tableId!==n)continue;let ne=z.recordId;if(L==null||pk(L,ne)){let re=z.getValue(i,S,C);if(I.send({id:ne,localTime:C,value:re,version:z.version,type:z.type}),I.queue?.length>mk&&await I.waitForDrain()===!1)return}I.startTime=C}}else if(D){let C=[];for(let{key:x,value:z}of l.getRange({start:"z",end:!1,reverse:!0}))try{let ne=At(z);if(ne.tableId!==n)continue;let re=ne.recordId;if(L==null||pk(L,re)){let B=ne.getValue(i,S,x);if(C.push({id:re,localTime:x,value:B,version:ne.version,type:ne.type}),--D<=0)break}}catch(ne){Me.default.error("Error getting history entry",x,ne)}for(let x=C.length;x>0;)I.send(C[--x]);C[0]&&(I.startTime=C[0].localTime)}else if(!E.omitCurrent){for(let{key:C,value:x,version:z,localTime:ne}of i.getRange({start:L??!1,end:L==null?void 0:[L,Al.MAXIMUM_KEY],versions:!0,snapshot:!1}))if(x&&(I.send({id:C,localTime:ne,value:x,version:z,type:"put"}),I.queue?.length>mk&&await I.waitForDrain()===!1))return}}else{D&&!H&&(H=0);let C=this.#n?.localTime;if(C===$A&&(i.cache?.delete(L),this.#n=i.getEntry(L),Me.default.trace?.("re-retrieved record",C,this.#n?.localTime),C=this.#n?.localTime),Me.default.trace?.("Subscription from",H,"from",L,C),H<C){let x=[],z=C;do{let ne=l.get(z);if(ne){E.omitCurrent=!0;let re=At(ne),B=re.getValue(i,S,z);S&&(re.type="put"),x.push({id:L,value:B,localTime:z,...re}),z=re.previousLocalTime}else break;D&&D--}while(z>H&&D!==0);for(let ne=x.length;ne>0;)I.send(x[--ne]);I.startTime=C}!E.omitCurrent&&this.doesExist()&&I.send({id:L,localTime:C,value:this.#e,version:this.#r,type:"put"})}for(let C of A)I.send(C);A=null})();return E.listener&&I.on("data",E.listener),I}static subscribeOnThisThread(E,S){return E===0||S?.crossThreads===!1}doesExist(){return!!(this.#e||this.#s)}publish(E,S,A){if(S===void 0||S instanceof URLSearchParams)this._writePublish(this.getId(),E,S);else{let b=!0,I=this.getContext();return E.checkPermission&&(b=this.allowCreate(I.user,E,I)),Cs(b,P=>{if(!P)throw new ot.AccessViolation(I.user);let L=yr(E);this._writePublish(L,S,A)})}}_writePublish(E,S,A){let b=Dr(this.getContext());E??=null,E!==null&&Lr(E);let I=this.getContext();b.addWrite({key:E,store:i,entry:this.#n,nodeName:I?.nodeName,validate:o(()=>{I?.source||(b.checkOverloaded(),this.validate(S))},"validate"),before:Ne.publish?.bind(this,I,E,S),beforeIntermediate:Ra(S,Ue.publish?.bind(this,I,E,S)),commit:o((P,L,D)=>{L===void 0&&y&&!g&&Ta(),Me.default.trace?.(`Publishing message to id: ${E}, timestamp: ${new Date(P).toISOString()}`),R(E,L?.value??null,L,L?.version||P,0,!0,{user:I?.user,residencyId:A?.residencyId,expiresAt:I?.expiresAt,nodeId:A?.nodeId},"message",!1,S)},"commit")})}validate(E,S){let A,b=o((I,P,L)=>{if(P.type&&I!=null)if(S&&I.__op__&&(I=I.value),P.properties){typeof I!="object"&&(A||(A=[])).push(`Value ${Ps(I)} in property ${L} must be an object${P.type?" ("+P.type+")":""}`);let D=P.properties;for(let H=0,C=D.length;H<C;H++){let x=D[H];if(x.relationship||x.computed){E.hasOwnProperty(x.name)&&(A||(A=[])).push(`Computed property ${L}.${x.name} may not be directly assigned a value`);continue}let z=b(I[x.name],x,L+"."+x.name);z&&(I[x.name]=z)}if(P.sealed&&I!=null&&typeof I=="object")for(let H in I)D.find(C=>C.name===H)||(A||(A=[])).push(`Property ${H} is not allowed within object in property ${L}`)}else switch(P.type){case"Int":(typeof I!="number"||I>>0!==I)&&(A||(A=[])).push(`Value ${Ps(I)} in property ${L} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof I!="number"||!(Math.floor(I)===I&&Math.abs(I)<=9007199254740992))&&(A||(A=[])).push(`Value ${Ps(I)} in property ${L} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof I!="number"&&(A||(A=[])).push(`Value ${Ps(I)} in property ${L} must be a number`);break;case"ID":typeof I=="string"||I?.length>0&&I.every?.(D=>typeof D=="string")||(A||(A=[])).push(`Value ${Ps(I)} in property ${L} must be a string, or an array of strings`);break;case"String":typeof I!="string"&&(A||(A=[])).push(`Value ${Ps(I)} in property ${L} must be a string`);break;case"Boolean":typeof I!="boolean"&&(A||(A=[])).push(`Value ${Ps(I)} in property ${L} must be a boolean`);break;case"Date":if(!(I instanceof Date)){if(typeof I=="string"||typeof I=="number")return new Date(I);(A||(A=[])).push(`Value ${Ps(I)} in property ${L} must be a Date`)}break;case"BigInt":if(typeof I!="bigint"){if(typeof I=="string"||typeof I=="number")return BigInt(I);(A||(A=[])).push(`Value ${Ps(I)} in property ${L} must be a bigint`)}break;case"Bytes":if(!(I instanceof Uint8Array)){if(typeof I=="string")return Buffer.from(I);(A||(A=[])).push(`Value ${Ps(I)} in property ${L} must be a Buffer or Uint8Array`)}break;case"Blob":if(!(I instanceof Rs)){if(typeof I=="string"&&(I=Buffer.from(I)),I instanceof Buffer)return createBlob(I,{type:"text/plain"});(A||(A=[])).push(`Value ${Ps(I)} in property ${L} must be a Blob`)}break;case"array":if(Array.isArray(I)){if(P.elements)for(let D=0,H=I.length;D<H;D++){let C=I[D],x=b(C,P.elements,L+"[*]");x&&(I[D]=x)}}else(A||(A=[])).push(`Value ${Ps(I)} in property ${L} must be an Array`);break}P.nullable===!1&&I==null&&(A||(A=[])).push(`Property ${L} is required (and not does not allow null values)`)},"validateValue");for(let I=0,P=T.length;I<P;I++){let L=T[I];if(L.relationship||L.computed){Object.hasOwn(E,L.name)&&(A||(A=[])).push(`Computed property ${L.name} may not be directly assigned a value`);continue}if(!S||L.name in E){let D=b(E[L.name],L,L.name);D!==void 0&&(E[L.name]=D)}}if(f)for(let I in E)T.find(P=>P.name===I)||(A||(A=[])).push(`Property ${I} is not allowed`);if(A)throw new ot.ClientError(A.join(". "))}getUpdatedTime(){return this.#r}wasLoadedFromSource(){return O?!!this.#i:void 0}static async addAttributes(E){let S=T.slice(0);for(let A of E){if(!A.name)throw new ot.ClientError("Attribute name is required");if(A.name.match(/[`/]/))throw new ot.ClientError("Attribute names cannot include backticks or forward slashes");Mie(A.name),S.push(A)}return ze({table:s,database:c,schemaDefined:u,attributes:S}),Pe.indexingOperation}static async removeAttributes(E){let S=T.filter(A=>!E.includes(A.name));return ze({table:s,database:c,schemaDefined:u,attributes:S}),Pe.indexingOperation}static getSize(){let E=i.getStats();return(E.treeBranchPageCount+E.treeLeafPageCount+E.overflowPages)*E.pageSize}static getAuditSize(){let E=l?.getStats();return E&&(E.treeBranchPageCount+E.treeLeafPageCount+E.overflowPages)*E.pageSize}static getStorageStats(){let E=i.env.path,S=_N.default.statfsSync?.(E)??{};return{available:S.bavail*S.bsize,free:S.bfree*S.bsize,size:S.blocks*S.bsize}}static async getRecordCount(E){let S=i.getStats().entryCount,A=1e3/2,b=performance.now(),I=Math.floor(S/2),P=E?.exactCount,L=0,D=0,H;for(let{value:C}of i.getRange({start:!0,lazy:!0,snapshot:!1}))if(C!=null&&L++,D++,await qa(),!P&&D<I&&performance.now()-b>A){H=D;break}if(H){let C=L;L=0;for(let{value:ee}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:H,snapshot:!1}))ee!=null&&L++,await qa();let x=H*2,z=(L+C)/x,ne=Math.pow((L-C+1)/H/2,2)+z*(1-z)/x,re=Math.max(Math.sqrt(ne)*S,1),B=Math.round(z*S),de=Math.max(B-1.96*re,L+C),me=Math.min(B+1.96*re,S),Se=Math.pow(10,Math.round(Math.log10(re)));return Se>B&&(Se=Se/10),L=Math.round(B/Se)*Se,{recordCount:L,estimatedRange:[Math.round(de),Math.round(me)]}}return{recordCount:L}}static updatedAttributes(){Xt=this.propertyResolvers={$id:o((E,S,A)=>({value:A.key}),"$id"),$updatedtime:o((E,S,A)=>A.version,"$updatedtime"),$updatedTime:o((E,S,A)=>A.version,"$updatedTime"),$expiresAt:o((E,S,A)=>A.expiresAt,"$expiresAt"),$record:o((E,S,A)=>A?{value:E}:E,"$record"),$distance:o((E,S,A)=>A&&(A.distance??S?.vectorDistances?.get(A)),"$distance")};for(let E of this.attributes){E.isPrimaryKey&&(F=E),E.resolve=null;let S=E.relationship,A=E.computed;if(S)if(E.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),A&&console.error("A relationship property is already computed and can not be combined with a computed function (the relationship will be given precedence)"),Mf=!0,S.to)E.elements?.definition?(Xt[E.name]=E.resolve=(b,I,P,L)=>{let D=b[S.from?S.from:t],H=E.elements.definition.tableClass;return L?Lu({attribute:S.to,value:D},Dr(I).getReadTxn(),!1,H,!1).map(C=>C&&C.key!==void 0?C:H.primaryStore.getEntry(C,{transaction:Dr(I).getReadTxn()})).asArray:H.search([{attribute:S.to,value:D}],I).asArray},E.set=()=>{},E.resolve.definition=E.elements.definition,E.resolve.to=S.to,S.from&&(E.resolve.from=S.from)):console.error(`The one-to-many/many-to-many relationship property "${E.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(S.from){let b=E.definition||E.elements?.definition;b?(Xt[E.name]=E.resolve=(I,P,L,D)=>{let H=I[S.from];if(H===void 0)return;if(E.elements){let x,z=H?.map(ne=>{let re=b.tableClass.primaryStore[D?"getEntry":"get"](ne,{transaction:Dr(P).getReadTxn()});return re?.then&&(x=!0),Pe.loadAsInstance===!1&&Object.freeze(D?re?.value:re),re});return S.filterMissing?x?Promise.all(z).then(ne=>ne.filter(Ek)):z.filter(Ek):x?Promise.all(z):z}let C=b.tableClass.primaryStore[D?"getEntry":"get"](H,{transaction:Dr(P).getReadTxn()});return Pe.loadAsInstance===!1&&Object.freeze(D?C?.value:C),C},E.set=(I,P)=>{if(Array.isArray(P)){let L=P.map(D=>D.getId?.()||D[b.tableClass.primaryKey]);I[S.from]=L}else{let L=P.getId?.()||P[b.tableClass.primaryKey];I[S.from]=L}},E.resolve.definition=E.definition||E.elements?.definition,E.resolve.from=S.from):console.error(`The relationship property "${E.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${E.name}" in table "${s}" must use either "from" or "to" arguments`);else if(A)typeof A.from=="function"&&this.setComputedAttribute(E.name,A.from),Xt[E.name]=E.resolve=(b,I,P)=>{let L=typeof A.from=="string"?b[A.from]:b,D=this.userResolvers[E.name];if(D)return D(L,I,P);Me.default.warn(`Computed attribute "${E.name}" does not have a function assigned to it. Please use setComputedAttribute('${E.name}', resolver) to assign a resolver function.`),this.userResolvers[E.name]=()=>{}},E.resolve.directReturn=!0;else if(r[E.name]?.customIndex?.propertyResolver){let b=r[E.name].customIndex;Xt[E.name]=(I,P,L)=>{let D=I[E.name];return b.propertyResolver(D,P,L)},Xt[E.name].directReturn=!0}}Km(this,this),Km(xf,this,!0);for(let E of T){let S=E.name;E.resolve&&Object.defineProperty(i.encoder.structPrototype,S,{get(){return E.resolve(this,vu.getStore())},set(A){return E.set(this,A)},configurable:!0})}}static setComputedAttribute(E,S){let A=Bi(T,E);if(!A){console.error(`The attribute "${E}" does not exist in the table "${s}"`);return}if(!A.computed){console.error(`The attribute "${E}" is not defined as computed in the table "${s}"`);return}this.userResolvers[E]=S}static async deleteHistory(E=0,S=!1){let A;for(let{key:b,value:I}of l.getRange({start:0,end:E}))await qa(),At(I).tableId===n&&(A=p_(l,b,I));if(S)for(let b of i.getRange({start:0,versions:!0})){let{key:I,value:P,localTime:L}=b;await qa(),P===null&&L<E&&(A=Qc(i,b))}await A}static async*getHistory(E=0,S=1/0){for(let{key:A,value:b}of l.getRange({start:E||1,end:S})){await qa();let I=At(b);I.tableId===n&&(yield{id:I.recordId,localTime:A,version:I.version,type:I.type,value:I.getValue(i,!0,A),user:I.user,operation:I.originatingOperation})}}static async getHistoryOfRecord(E){let S=[];if(E==null)throw new Error("An id is required");let A=i.getEntry(E);if(!A)return S;let b=A.localTime;if(!b)throw new Error("The entry does not have a local audit time");let I=0;do{await qa();let P=l.get(b);if(P){let L=At(P);S.push({id:L.recordId,localTime:b,version:L.version,type:L.type,value:L.getValue(i,!0,b),user:L.user}),b=L.previousLocalTime}else break}while(I<1e3&&b);return S.reverse()}static cleanup(){K?.remove()}}let NE=Cg(async(V,E,S)=>{for(let A of Pe.sources)if(A.get&&(!A.get.reliesOnPrototype||A.prototype.get)){if(A.available?.(S)===!1)continue;E.source=A;let b=await A.get(V,E);if(b)return b}},()=>{throw new ot.ServerError("Service unavailable, exceeded request queue limit for resolving cache record",503)});Pe.updatedAttributes();let Bf=Pe.prototype;return p&&Pe.setTTLExpiration(p/1e3),q&&pu(),Pe;function po(V,E,S){let A;for(let b in r){let I=r[b],P=I.isIndexing,L=Xt[b],D=S&&(L?L(S):S[b]),H=E&&(L?L(E):E[b]);if(D===H&&!P)continue;if(I.customIndex){I.customIndex.index(V,D,H);continue}A=!0;let C=I.indexNulls,x=(0,dh.getIndexedValues)(D,C),z=(0,dh.getIndexedValues)(H,C);if(s==="OrganizationRole"&&Me.default.error?.({tableName:s,id:V,key:b,valuesToAdd:x,valuesToRemove:z}),z?.length>0){let ne=new Set(z);if(x=x?x.filter(re=>{if(ne.has(re))ne.delete(re);else return!0}):[],z=Array.from(ne),(z.length>0||x.length>0)&&uk){let re=z.concat(x).map(B=>({key:B,value:V}));I.prefetch(re,hk)}for(let re=0,B=z.length;re<B;re++)I.remove(z[re],V)}else x?.length>0&&uk&&I.prefetch(x.map(ne=>({key:ne,value:V})),hk);if(x)for(let ne=0,re=x.length;ne<re;ne++)I.put(x[ne],V)}return A}o(po,"updateIndices");function Lr(V){switch(typeof V){case"number":return!0;case"string":if(V.length<659)return!0;if(V.length>fk)throw new Error("Primary key size is too large: "+V.length);break;case"object":if(V===null)throw new Error("Invalid primary key of null");break;case"bigint":if(V<2n**64n&&V>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof V)}if((0,Al.writeKey)(V,Hie,0)>fk)throw new Error("Primary key size is too large: "+V.length);return!0}o(Lr,"checkValidId");function yr(V){return typeof V=="object"&&V?V.id:V}o(yr,"requestTargetToId");function Ff(V){return typeof V=="object"&&V&&V.isCollection}o(Ff,"isSearchTarget");function Ss(V){}o(Ss,"isRequestTarget");function Ea(V,E,S,A,b){if(Pe.getResidencyById&&S.ensureLoaded&&E?.replicateFrom!==!1){let P=Lc(Pe.getResidencyById(V));if(P&&!P.includes(server.hostname)&&N)return N({key:V,residency:P}).then(b)}let I=o(()=>{if(E?.transaction?.stale&&(E.transaction.stale=!1),S.transaction?.isDone)return b(null,V);let P=i.getEntry(V,S);return E?._freezeRecords&&Object.freeze(P?.value),P?.residencyId&&P.metadataFlags&wn&&N&&S.ensureLoaded&&E?.replicateFrom!==!1?N(P).then(L=>b(L,V),L=>(Me.default.error?.("Error loading remote record",V,P,S,L),b(null,V))):(P&&E&&(P?.version>(E.lastModified||0)&&(E.lastModified=P.version),P?.localTime&&!E.lastRefreshed&&(E.lastRefreshed=P.localTime)),b(P,V))},"whenPrefetched");return A?I():se>0?(se--,I()):new Promise((P,L)=>{se===0?(se--,i.prefetch([V],()=>{D(),H()})):(ce.push(V),le.push(H),ce.length>My&&(se--,D()));function D(){if(ce.length>0){let C=le;i.prefetch(ce,()=>{se===-1?D():se++;for(let x of C)x()}),ce=[],le=[],pe>2&&pe--}else se=pe,pe<IE&&pe++}o(D,"prefetch");function H(){try{P(I())}catch(C){L(C)}}o(H,"load")})}o(Ea,"loadLocalRecord");function _a(V,E){let S=E?.checkPermission;if(typeof S!="object"){if(!V?.role)return;S=V.role.permission}if(S.super_user)return kie;let A=S[c],b,I=A?.tables;if(I)return I[s];if(c==="data"&&(b=S[s])&&!b.tables)return b}o(_a,"getTablePermissions");function Pc(V,E,S,A){if(O){let b=!1;if(S.noCache?b=!0:(E?(!E.value||E.metadataFlags&(wn|Jc)||E.expiresAt!=null&&E.expiresAt<Date.now())&&(b=!0):b=!0,zr(!b,"cache-hit",s)),b){let I=wE(V,E,S).then(P=>(P?.value&&P?.value.getRecord?.()&&Me.default.error?.("Can not assign a record that is already a resource"),S&&(P?.version>(S.lastModified||0)&&(S.lastModified=P.version),S.lastRefreshed=Date.now()),P));if(S?.onlyIfCached||E?.value&&A?.allowStaleWhileRevalidate?.(E,V)){if(I.catch(P=>Me.default.warn?.(P)),S?.onlyIfCached&&!A.doesExist())throw new ot.ServerError("Entry is not cached",504);return}else return I}}else if(E?.value&&E.expiresAt!=null&&E.expiresAt<Date.now())return Pe.evict(E.key,E.value,E.version),E.value=null,{then(b){return b(E)}}}o(Pc,"ensureLoadedFromSource");function Dr(V){let E=V?.transaction;if(E){if(!E.lmdbDb)return E.lmdbDb=i,E;do{if(E.lmdbDb?.path===i.path)return E;let S=E.next;if(!S)return E=E.next=new _o,E.lmdbDb=i,E;E=S}while(!0)}else return new YE}o(Dr,"txnForContext");function mu(V,E,S){if(!V)return;let A=(V.deref?V.deref():V.value)??i.getEntry(V.key)?.value;if(typeof E=="object"){let I=Xt,P=A;for(let L=0,D=E.length;L<D;L++){let H=E[L],C=I?.[H];P=C&&P?C(P,S,V):P?.[H],V=null,I=C?.definition?.tableClass?.propertyResolvers}return P}let b=Xt[E];return b?b(A,S,V):A[E]}o(mu,"getAttributeValue");function hu(V,E,S,A,b){let I=b?.length,P={transaction:A,lazy:I>0||typeof E=="string"||E?.length<4,alwaysPrefetch:!0},L;function D(H,C){let x=H?.value;if(!x)return $a.SKIP;for(let z=0;z<I;z++)if(!L?.includes(z)&&!b[z](x,H))return $a.SKIP;return C!==void 0&&(H.key=C),H}if(o(D,"processEntry"),I>0||!V.hasEntries){let H=V.map(C=>{if(L=null,typeof C=="object"&&C?.key!==void 0)return I>0?D(C):C;if(C==null)return $a.SKIP;for(let x=0;x<I;x++){let ne=b[x].idFilter;if(ne){if(!ne(C))return $a.SKIP;L||(L=[]),L.push(x)}}return Ea(C,S,P,!1,D)});return Array.isArray(V)&&(H=H.filter(C=>C!==$a.SKIP)),H.hasEntries=!0,H}return V}o(hu,"transformToEntries");function ga(V,E,S=server.replication?.getThisNodeId(l)){if(V<=E?.version){if(E?.version===V&&S!==void 0){let A=server.replication?.exportIdMapping(l),b=E.localTime,I=b&&l.get(b);if(I){let P,L,D=At(I);for(let H in A)A[H]===S&&(P=H),A[H]===D.nodeId&&(L=H);if(P>L)return 1;if(P===L)return 0}}return-1}return 1}o(ga,"precedesExistingVersion");async function wE(V,E,S){let A=E?.metadataFlags,b=E?.version,I,P;if(!i.attemptLock(V,b,()=>{clearTimeout(P);let C=i.getEntry(V);!C||!C.value||C.metadataFlags&(wn|Jc)?I(wE(V,i.getEntry(V),S)):I(C)}))return new Promise(C=>{I=C,P=setTimeout(()=>{i.unlock(V,b)},Bie)});let L=E?.value,D={requestContext:S,replacingRecord:L,replacingEntry:E,replacingVersion:b,noCacheStore:!1,source:null,resourceCache:S?.resourceCache,transaction:void 0,expiresAt:void 0,lastModified:void 0},H=S?.responseHeaders;return new Promise((C,x)=>{let z;Cs(Ut(D,async ne=>{let re=performance.now(),B,de,me;try{B=await NE(V,D,E),me=A&wn;let ee=D.lastModified||me&&b;ee||(ee=(0,dh.getNextMonotonicTime)()),de=me||ee>b||!L;let j=performance.now()-re;if(it(j,"cache-resolution",s,null,"success"),H&&lh(H,"Server-Timing",`cache-resolve;dur=${j.toFixed(2)}`,!0),ne.timestamp=ee,p&&D.expiresAt==null&&(D.expiresAt=Date.now()+p),B){if(typeof B!="object")throw new Error("Only objects can be cached and stored in tables");if(B.status>0&&B.headers)if(B.status>=300)if(B.status===304)B=L,ee=b;else throw new ot.ServerError(B.body||"Error from source",B.status);else B=B.body;typeof B.toJSON=="function"&&(B=B.toJSON()),t&&B[t]!==V&&(B[t]=V)}z=!0,C({key:V,version:ee,value:B})}catch(ee){ee.message+=` while resolving record ${V} for ${s}`,L&&((ee.code==="ECONNRESET"||ee.code==="ECONNREFUSED"||ee.code==="EAI_AGAIN")&&!S?.mustRevalidate||S?.staleIfError&&(ee.statusCode===500||ee.statusCode===502||ee.statusCode===503||ee.statusCode===504))?(C({key:V,version:b,value:L}),Me.default.trace?.(ee.message,"(returned stale record)")):x(ee);let j=performance.now()-re;it(j,"cache-resolution",s,null,"fail"),H&&lh(H,"Server-Timing",`cache-resolve;dur=${j.toFixed(2)}`,!0),D.transaction.abort();return}if(S?.noCacheStore||D.noCacheStore){D.transaction.abort();return}Dr(D).addWrite({key:V,store:i,entry:E,nodeName:"source",before:Ra(B),commit:o((ee,j)=>{if(j?.version!==b)return;let he=po(V,L,B);if(B){Ue.put?.(D,V,B),j&&(S.previousResidency=Pe.getResidencyRecord(j.residencyId));let Te,fe=!1,We,Et=Lc(Pe.getResidency(B,S));if(Et){if(!Et.includes(server.hostname))if(Te=B,fe=!0,Pe.getResidencyById)B=void 0;else{B=null;for(let dt in r)B||(B={}),B[dt]=Te[dt]}We=Dc(Et)}Me.default.trace?.(`Writing resolved record from source with id: ${V}, timestamp: ${new Date(ee).toISOString()}`),R(V,B,j,ee,fe?wn:0,g&&(de||fe)||null,{user:D?.user,expiresAt:D.expiresAt,residencyId:We},"put",!!me,Te)}else j&&(Ue.delete?.(D,V),Me.default.trace?.(`Deleting resolved record from source with id: ${V}, timestamp: ${new Date(ee).toISOString()}`),g||y?R(V,null,j,ee,0,g&&de||null,{user:D?.user},"delete",!!me):Qc(i,j,b))},"commit")})}),()=>{i.unlock(V,b)},ne=>{i.unlock(V,b),z&&Me.default.error?.("Error committing cache update",ne)})})}o(wE,"getFromSource");function Sa(V){if(!V||V.user?.role?.permission?.super_user)return!0;if(V.replicateTo)throw new ot.ClientError("Can not specify replication parameters without super user permissions",403);if(V.replicatedConfirmation)throw new ot.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}o(Sa,"checkContextPermissions");function Ta(V){let E=!1;if(V&&(V-Rr>1&&(E=!0),Rr=V),!(xe===Jt&&!E)&&(Jt=xe,(0,Rl.getWorkerIndex)()===(0,Rl.getWorkerCount)()-1))return kt&&clearTimeout(kt),xe?new Promise(S=>{let A=new Date;A.setMonth(0),A.setDate(1),A.setHours(0),A.setMinutes(0),A.setSeconds(0);let b=xe/(1+Rr),I=E?Date.now():Math.ceil((Date.now()-A.getTime())/b)*b+A.getTime(),P=o(L=>{Me.default.trace?.(`Scheduled next cleanup scan at ${new Date(L)}`),kt=setTimeout(()=>Z=Z.then(async()=>{if(P(Math.max(L+xe,Date.now())),i.rootStore.status!=="open"){clearTimeout(kt);return}let D=50,H=new Array(D),C=0,x=Math.pow(Rr,8)*(yl.get(U.STORAGE_RECLAMATION_EVICTIONFACTOR)??1e5),z=_/Math.pow(Math.max(Rr,1),4);Me.default.info?.(`Starting cleanup scan for ${s}, evict threshold ${x}, adjusted eviction ${z}ms`);function ne(re,B,de,me){let Se=re+z-Date.now();if(Se<0)return!0;if(Rr){let ee=i.lastSize;return de&Vr&&kc(me,j=>{j.size&&(ee+=j.size)}),Me.default.trace?.(`shouldEvict adjusted ${Se} ${ee}, ${Se*(re-B)/ee} < ${x}`),Se*(re-B)/ee<x}return!1}o(ne,"shouldEvict");try{let re=0;for(let B of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let{key:de,value:me,version:Se,expiresAt:ee,metadataFlags:j}=B,he;me===null&&!g&&Se+xie<Date.now()?he=Qc(i,B,Se):ee!=null&&ne(ee,Se,j,me)&&(he=Pe.evict(de,me,Se),re++),he&&(await H[C],H[C]=he.catch(Te=>{Me.default.error?.("Cleanup error",Te)}),++C>=D&&(C=0)),await qa()}Me.default.info?.(`Finished cleanup scan for ${s}, evicted ${re} entries`)}catch(re){Me.default.warn?.(`Error in cleanup scan for ${s}:`,re)}S(void 0),Rr=0}),Math.min(L-Date.now(),2147483647)).unref()},"startNextTimer");P(I)}):void 0}o(Ta,"scheduleCleanup");function Hf(){K=l?.addDeleteRemovalCallback(n,i,(V,E)=>{i.remove(V,E)})}o(Hf,"addDeleteRemoval");function pu(){(0,Rl.getWorkerIndex)()===0&&setInterval(async()=>{if(!Cc){Cc=!0;try{let V=q.name,E=r[V];if(!E)throw new Error(`expiresAt attribute ${q} must be indexed`);for(let S of E.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let A of E.getValues(S)){let b=i.getEntry(A);b?.value?b.value[V]<Date.now()&&Pe.evict(A,b.value,b.version):i.ifVersion(A,b?.version,()=>E.remove(S,A))}await qa()}}catch(V){Me.default.error?.("Error in evicting old records",V)}finally{Cc=!1}}},Uie).unref()}o(pu,"runRecordExpirationEviction");function Lc(V){if(V!=null){if(Array.isArray(V))return V;if(typeof V=="number"){if(V>=65536)throw new Error(`Shard id ${V} must be below 65536`);let E=server.shards?.get?.(V);if(E)return Me.default.trace?.(`Shard ${V} mapped to ${E.map(S=>S.name).join(", ")}`),E.map(S=>S.name);throw new Error(`Shard ${V} is not defined`)}throw new Error(`Shard or residency list ${V} is not a valid type, must be a shard number or residency list of node hostnames`)}}o(Lc,"residencyFromFunction");function Dc(V){if(V){let E=V.join(","),S=d.get([Symbol.for("residency_by_set"),E]);return S||(d.put([Symbol.for("residency_by_set"),E],S=Math.floor(Math.random()*2147418112)+65535),d.put([Symbol.for("residency_by_id"),S],V),S)}}o(Dc,"getResidencyId");function Ra(V,E){let S=wA(V,i.rootStore);if(S){let A=E;return A?async()=>{await A(),await S}:()=>S}return E}o(Ra,"preCommitBlobsForRecordBefore")}function EN(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 hk(){}function Lg(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 Pg(parseInt(e.slice(1),36));if(e==="null")return null;if(!/^-?[0-9]+$/.test(e)&&!(e instanceof Date))throw new SyntaxError;return Pg(+e);case"Float":return e==="null"?null:Pg(+e);case"BigInt":return e==="null"?null:BigInt(e);case"Boolean":return e==="true"?!0:e==="false"?!1:e;case"Date":if(isNaN(e)){if(e==="null")return null;Gie.test(e)||(e+="Z");let n=new Date(e);return Pg(n.getTime()),n}return new Date(+e);case void 0:case"Any":return(0,Dg.autoCast)(e);default:return e}}catch(n){throw n.message=`Invalid value for attribute ${t.name}: "${e}", expecting ${r}`,n.statusCode=400,n}}function Pg(e){if(isNaN(e))throw new SyntaxError;return e}function pk(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 Cs(e,t,r){return e?.then?e.then(t,r):t(e)}function Ek(e){return e!=null}function Ps(e){try{return JSON.stringify(e)}catch{return e}}function qie(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var $a,dh,_k,gk,yl,ot,fh,mh,Me,Al,Rl,Dg,_N,Die,Mie,vie,Uie,xie,uk,Bie,dk,Fie,wn,Jc,Hie,fk,mk,kie,VLe,Gie,qa,O_=ue(()=>{k();$a=require("lmdb"),dh=w(bn()),_k=w(require("lodash")),gk=w(em());La();rm();yl=w(oe());eb();ot=w(ge()),fh=w(Co()),mh=w(oi());De();w_();Me=w(ei());mI();xc();Al=require("ordered-binary"),Rl=w(nt());Di();Dg=w(ie());Wc();zi();jE();uh();_N=w(require("node:fs"));Yn();d_();pN();({sortBy:Die}=_k.default),{validateAttribute:Mie}=gk.default,vie=new Uint8Array(9);vie[8]=192;Uie=6e4,xie=864e5;yl.initSync();uk=yl.get(U.STORAGE_PREFETCHWRITES),Bie=1e4,dk=1,Fie=2,wn=1,Jc=8,Hie=Buffer.allocUnsafeSlow(8192),fk=1978,mk=100,kie={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},VLe=(0,Dg.convertToMS)(yl.get(U.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;o(Mg,"makeTable");o(EN,"attributesAsObject");o(hk,"noop");Gie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;o(Lg,"coerceType");o(Pg,"rejectNaN");o(pk,"isDescendantId");qa=o(()=>new Promise(setImmediate),"rest");o(Cs,"when");o(Ek,"exists");o(Ps,"stringify");o(qie,"hasOtherProcesses")});function vg(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,a=t[s]||0,c=i-a;r+=c*c}return r}function Ug(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 a=0;a<i;a++){let c=e[a]||0,l=t[a]||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 Tk=ue(()=>{o(vg,"euclideanDistance");o(Ug,"cosineDistance")});var Rk,yk,rd,ji,td,$ie,Vie,xg,Ak=ue(()=>{Tk();Rk=require("msgpackr"),yk=w(ei()),rd=w(ge()),ji=(0,yk.loggerWithTag)("HNSW"),td=Symbol.for("entryPoint"),$ie=Symbol.for("key"),Vie=10,xg=class{static{o(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=Rk.FLOAT32_OPTIONS.ALWAYS),this.distance=r?.distance==="euclidean"?vg:Ug,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"?[$ie,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 a=new Map,c,l=this.indexStore.get(td);if(n?c={...this.indexStore.get(i)}:c={},r){let f=l&&this.indexStore.get(l);if(f===void 0){let _=Math.floor(-Math.log(Math.random())*this.mL),g={vector:r,level:_,primaryKey:t};for(let y=0;y<=_;y++)g[y]=[];if(this.indexStore.put(i,g),typeof i!="number")throw new Error("Invalid nodeId: "+i);ji.debug?.("setting entry point to",i),this.indexStore.put(td,i);return}let m=c.level??Math.min(Math.floor(-Math.log(Math.random())*this.mL),Vie),h=f.level;if(m>=h){if(typeof i!="number")throw new Error("Invalid nodeId: "+i);ji.debug?.("setting entry point to",i),this.indexStore.put(td,i)}for(;h>m;){let _=this.searchLayer(r,l,f,this.efConstruction,h);_.length>0&&(l=_[0].id,f=_[0].node),h--}let p=new Array(m+1);for(let _=0;_<=m;_++)p[_]=[];for(let _=Math.min(m,h);_>=0;_--){let g=this.searchLayer(r,l,f,this.efConstruction,_);g=g.slice(0,this.M<<1),g.length===0&&_===0&&ji.info?.("should not have zero connections for",l);let y=p[_];for(let T=0;T<g.length;T++){let{id:R,distance:N,node:O}=g[T];if(R===i)continue;let F=[];if(this.optimizeRouting){let Y=!1,q=O[_],K=1+this.optimizeRouting*(1+.5*T/this.M);for(let ce=0;ce<q.length;ce++){let{id:le,distance:se}=q[ce],pe=1+this.optimizeRouting*(1+.5*ce/this.M);for(let Ne=0;Ne<y.length;Ne++){let{id:Ue,distance:xe}=y[Ne];if(Ue===le){N*K>xe+se?Y=!0:se*pe>N+xe&&(F.push({fromId:Ue,toId:R}),F.push({fromId:R,toId:Ue}));break}}if(Y)break}if(Y)continue}else if(T>=(_>0?this.M:this.M<<1))continue;y.push({id:R,distance:N});for(let{fromId:Y,toId:q}of F){let K=d(Y);K||(K=d(Y,this.indexStore.get(Y)));for(let ce=0;ce<K[_].length;ce++)if(K[_][ce].id===q){Object.isFrozen(K[_])&&(K[_]=K[_].slice()),K[_].splice(ce,1);break}}let Z=c[_],G=Z?.find(({id:Y})=>Y===R);if(G){let Y=Z?.indexOf(G);Z.copied||(Z=[...Z],Z.copied=!0,c[_]=Z),Z.splice(Y,1)}else this.addConnection(R,d(R,O),i,_,N,d)}}this.indexStore.put(i,{vector:r,level:m,primaryKey:t,...p})}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:h,value:p}of this.indexStore.getRange({start:0,end:1/0}))if(p.level>m){if(l=h,p.level===f)break;m=p.level}}if(l===void 0)this.indexStore.remove(td);else{if(typeof l!="number")throw new Error("Invalid nodeId: "+l);ji.debug?.("setting entry point to",l),this.indexStore.put(td,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:h}of m){let p=d(h,this.indexStore.get(h));for(let _=0;_<=f;_++)p[_]=p[_]?.filter(({id:g})=>g!==i),p[_].length===0&&(ji.info?.("node was left orphaned, will reindex",h),u.set(p.primaryKey,p.vector))}}function d(f,m){let h=a.get(f);return!h&&m&&(h={...m},a.set(f,h)),h}o(d,"updateNode");for(let[f,m]of a)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(td);if(t===void 0)return;let r=this.indexStore.get(t);return{id:t,...r}}searchLayer(t,r,n,s,i,a=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((h,p)=>h.distance-p.distance);let d=l.shift(),f=u[u.length-1].distance;if(d.distance>f)break;let m=d.node;for(let{id:h}of m[i]||[]){if(c.has(h)||h===void 0)continue;c.add(h);let p=this.indexStore.get(h);if(!p)continue;this.nodesVisitedCount++;let _=a(t,p.vector);if(_<f||u.length<s){let g={id:h,distance:_,node:p};l.push(g),u.push(g)}}u.sort((h,p)=>h.distance-p.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 a=0;switch(i){case"lt":case"le":a=r;case"sort":break;default:throw new rd.ClientError(`Can not use "${i}" comparator with HNSW`)}if(n)throw new rd.ClientError("Can not use descending sort order with HNSW");let c;if(s==="cosine")c=Ug;else if(s==="euclidean")c=vg;else{if(s)throw new rd.ClientError("Unknown distance function");c=this.distance}if(!t)throw new rd.ClientError("A target vector must be provided for an HNSW query");if(!Array.isArray(t))throw new rd.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 a&&(d=d.filter(f=>f.distance<a)),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 a=this.indexStore.get(i);if(!a){ji.info?.("could not find neighbor node",a);continue}a[n]?.find(({id:l})=>l==t)||ji.info?.("asymmetry detected",a[n])}n++}}addConnection(t,r,n,s,i,a){r[s]||(r[s]=[]);let c=s===0?this.M<<1:this.M;if(this.optimizeRouting&&(c<<=2),r[s].length>=c+(c>>2)){ji.warn?.("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=a(f.id)??this.indexStore.get(f.id);m&&m[s]&&(m=a(f.id,m),m[s]=m[s].filter(({id:h})=>h!==t),s===0&&m[s].length===0&&ji.info?.("should not remove last connection",t,n))}}r[s].find(({id:l})=>l===n)?ji.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 a=s.shift(),c=this.indexStore.get(a);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 a=this.distance;s.type&&(a=s.distance==="euclidean"?vg:Ug);let c=a(s.target,t);return i.set(n,c),c}return t}}});var gN,bk=ue(()=>{Ak();gN={HNSW:xg}});var mt={};Oe(mt,{database:()=>Yu,databaseEnvs:()=>Uo,databases:()=>ke,dropDatabase:()=>gI,dropTableMeta:()=>jie,getDatabases:()=>st,getDefaultCompression:()=>qg,getTables:()=>Kie,onRemovedDB:()=>Sh,onUpdatedTable:()=>bl,readMetaDb:()=>hh,resetDatabases:()=>cd,table:()=>ze,tables:()=>un});function Kie(){return kg||st(),un||{}}function st(){if(kg)return ke;kg=!0,id=new Map;let e=(0,Vt.getHdbBasePath)()&&(0,Ft.join)((0,Vt.getHdbBasePath)(),vc),t=(0,Vt.get)(U.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Vt.get)(U.STORAGE_PATH)||e&&((0,ss.existsSync)(e)?e:(0,Ft.join)((0,Vt.getHdbBasePath)(),DE)),!e)return;if((0,ss.existsSync)(e))for(let n of(0,ss.readdirSync)(e,{withFileTypes:!0})){let s=(0,Ft.basename)(n.name,".mdb");n.isFile()&&(0,Ft.extname)(n.name).toLowerCase()===".mdb"&&!t[s]?.path&&hh((0,Ft.join)(e,n.name),null,s)}if((0,ss.existsSync)((0,sd.getBaseSchemaPath)())){for(let n of(0,ss.readdirSync)((0,sd.getBaseSchemaPath)(),{withFileTypes:!0}))if(!n.isFile()){let s=(0,Ft.join)((0,sd.getBaseSchemaPath)(),n.name),i=(0,Ft.join)((0,sd.getTransactionAuditStoreBasePath)(),n.name);for(let a of(0,ss.readdirSync)(s,{withFileTypes:!0}))if(a.isFile()&&(0,Ft.extname)(a.name).toLowerCase()===".mdb"){let c=(0,Ft.join)(i,a.name);hh((0,Ft.join)(s,a.name),(0,Ft.basename)(a.name,".mdb"),n.name,c,!0)}}}if(t)for(let n in t){let s=t[n],i=s.path;if((0,ss.existsSync)(i))for(let c of(0,ss.readdirSync)(i,{withFileTypes:!0}))c.isFile()&&(0,Ft.extname)(c.name).toLowerCase()===".mdb"&&hh((0,Ft.join)(i,c.name),(0,Ft.basename)(c.name,".mdb"),n);let a=s.tables;if(a)for(let c in a){let l=a[c],u=(0,Ft.join)(l.path,(0,Ft.basename)(c+".mdb"));(0,ss.existsSync)(u)&&hh(u,c,n,null,!0)}}for(let n in ke){let s=id.get(n);if(s){let i=ke[n];n.includes("delete")&&Nr.trace(`defined tables ${Array.from(s.keys())}`);for(let a in i)s.has(a)||(Nr.trace(`delete table class ${a}`),delete i[a])}else if(delete ke[n],n==="data"){for(let i in un)delete un[i];delete un[Gg]}}let r=["hdb_temp","hdb_certificate","hdb_raw_analytics","hdb_session_will","hdb_job","hdb_license","hdb_info"];if((0,Vt.get)(U.ANALYTICS_REPLICATE)===!1?r.push("hdb_analytics"):(ke.system?.hdb_analytics?.enableAuditing(),ke.system?.hdb_analytics_hostname?.enableAuditing()),ke.system)for(let n of r)ke.system[n]&&(ke.system[n].replicate=!1);return id=null,ke}function cd(){kg=!1;for(let[,e]of Uo)e.needsDeletion=!0;st();for(let[e,t]of Uo)if(t.needsDeletion&&!e.endsWith("system.mdb")){t.close(),Uo.delete(e);let r=ke[t.databaseName];for(let n in r)if(r[n].primaryStore.path===e){delete ke[t.databaseName],Eh.forEach(i=>i(t.databaseName));break}}return ke}function hh(e,t,r=RN,n,s){let i=new SN.default(e,!1);try{let a=Uo.get(e);a?a.needsDeletion=!1:(a=(0,od.open)(i),Uo.set(e,a));let c=new ad.default(!1),l=a.dbisDb||(a.dbisDb=a.openDB(Bg.INTERNAL_DBIS_NAME,c)),u=a.auditStore;u||(n?(0,ss.existsSync)(n)&&(i.path=n,u=(0,od.open)(i),u.isLegacy=!0):u=h_(a));let d=Ck(r),f=d[Gg],m=new Map;for(let{key:h,value:p}of l.getRange({start:!1})){let[_,g]=h.toString().split("/");g===""?g=p.name:g||(g=_,_=t,p.name||(p.name=g,p.indexed=!p.is_hash_attribute)),f?.add(_);let y=m.get(_);y||m.set(_,y={attributes:[]}),(g==null||p.is_hash_attribute)&&(y.primary=p),g!=null&&y.attributes.push(p),Object.defineProperty(p,"key",{value:h,configurable:!0})}for(let[h,p]of m){let{attributes:_,primary:g}=p;if(!g){for(let se of _)if(se.is_hash_attribute||se.isPrimaryKey){g=se;break}if(!g){Nr.warn(`Unable to find a primary key attribute on table ${h}, with attributes: ${JSON.stringify(_)}`);continue}}let y=d[h],T={},R=[],N,O,F=typeof g.audit=="boolean"?g.audit:(0,Vt.get)(U.LOGGING_AUDITLOG),Z=g.trackDeletes,G=g.expiration,Y=g.eviction,q=g.sealed,K=g.splitSegments,ce=g.replicate;if(y)T=y.indices,R=y.attributes,y.schemaVersion++;else{N=g.tableId,N?N>=(l.get(nd)||0)&&(l.putSync(nd,N+1),Nr.info(`Updating next table id (it was out of sync) to ${N+1} for ${h}`)):(g.tableId=N=l.get(nd),N||(N=1),Nr.debug("Table {tableName} missing an id, assigning {tableId}"),l.putSync(nd,N+1),l.putSync(g.key,g));let se=new ad.default(!g.is_hash_attribute,g.is_hash_attribute);if(se.compression=g.compression,se.compression){let pe=(0,Vt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||Ok;se.compression.threshold=pe}O=A_(a.openDB(g.key,se),a),a.databaseName=r,O.tableId=N}let le;for(let se of _){se.attribute=se.name;try{if(!se.is_hash_attribute&&(se.indexed||se.attribute&&!se.name)){if(!T[se.name]){let Ne=Lk(se.key,a,se);T[se.name]=Ne,T[se.name].indexNulls=se.indexNulls}let pe=R.find(Ne=>Ne.name===se.name);pe?R.splice(R.indexOf(pe),1,se):R.push(se),le=!0}}catch(pe){Nr.error("Error trying to update attribute",se,R,T,pe)}}for(let se of R)if(!_.find(Ne=>Ne.name===se.name)){if(se.is_hash_attribute){Nr.error("Unable to remove existing primary key attribute",se);continue}se.indexed&&(R.splice(R.indexOf(se),1),le=!0)}if(y)le&&(y.schemaVersion++,y.updatedAttributes());else{y=Pk(d,h,Mg({primaryStore:O,auditStore:u,audit:F,sealed:q,splitSegments:K,replicate:ce,expirationMS:G&&G*1e3,evictionMS:Y&&Y*1e3,trackDeletes:Z,tableName:h,tableId:N,primaryKey:g.name,databasePath:s?r+"/"+h:r,databaseName:r,indices:T,attributes:_,schemaDefined:g.schemaDefined,dbisDB:l})),y.schemaVersion=1;for(let se of ph)se(y)}}return a}catch(a){throw a.message+=` opening database ${e}`,a}}function Ck(e){let t=ke[e];if(t||(e==="data"?t=ke[e]=un:e==="system"?Object.defineProperty(ke,"system",{value:t=Object.create(null),configurable:!0}):t=ke[e]=Object.create(null)),id&&!id.has(e)){let r=new Set;t[Gg]=r,id.set(e,r)}return t}function Pk(e,t,r){return e[t]=r,r}function Yu({database:e,table:t}){e||(e=RN),st();let r=Ck(e),n=(0,Ft.join)((0,Vt.getHdbBasePath)(),vc),s=(0,Vt.get)(U.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,Vt.get)(U.STORAGE_PATH)||((0,ss.existsSync)(n)?n:(0,Ft.join)((0,Vt.getHdbBasePath)(),DE));let a=(0,Ft.join)(n,(i?t:e)+".mdb"),c=Uo.get(a);if(!c||c.status==="closed"){let l=new SN.default(a,!1);c=(0,od.open)(l),Uo.set(a,c)}return c.auditStore||(c.auditStore=h_(c)),c}async function gI(e){if(!ke[e])throw new Error("Schema does not exist");let t=ke[e],r;for(let n in t)r=t[n].primaryStore.rootStore,Uo.delete(r.path),r.status==="open"&&(await r.close(),await _h.remove(r.path));if(r||(r=Yu({database:e,table:null}),r.status==="open"&&(await r.close(),await _h.remove(r.path))),e==="data"){for(let n in un)delete un[n];delete un[Gg]}delete ke[e],Eh.forEach(n=>n(e)),await NA(r)}function Lk(e,t,r){let n=r.is_hash_attribute||r.indexed.type&&gN[r.indexed.type]?.useObjectStore,s=new ad.default(!n,n),i=t.openDB(e,s);if(r.indexed.type){let a=gN[r.indexed.type];a?i.customIndex=new a(i,r.indexed):Nr.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:a,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,schemaDefined:m,origin:h}=e;r||(r=RN);let p=Yu({database:r,table:t}),_=ke[r];Nr.trace(`Defining ${t} in ${r}`);let g=_?.[t];if(p.status==="closed")throw new Error(`Can not use a closed data store for ${t}`);let y,T,R;m==null&&(m=!0);let N=new ad.default(!1);for(let K of a)K.attribute&&!K.name?(K.name=K.attribute,K.indexed=!0):K.attribute=K.name,K.expiresAt&&(K.indexed=!0);let O,F;if(g){if(y=g.primaryKey,g.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${t} class`);u==null&&(u=g.splitSegments),g.attributes.splice(0,g.attributes.length,...a)}else{let K=p.auditStore;T=a.find(pe=>pe.isPrimaryKey)||{},y=T.name,T.is_hash_attribute=T.isPrimaryKey=!0,T.schemaDefined=m,T.compression=qg(),f&&(T.trackDeletes=!0),c=T.audit=typeof c=="boolean"?c:(0,Vt.get)(U.LOGGING_AUDITLOG),n&&(T.expiration=n),s&&(T.eviction=s),u??=!1,T.splitSegments=u,typeof l=="boolean"&&(T.sealed=l),typeof d=="boolean"&&(T.replicate=d),h&&(T.origins?T.origins.includes(h)||T.origins.push(h):T.origins=[h]),Nr.trace(`${t} table loading, opening primary store`);let ce=new ad.default(!1,!0);ce.compression=T.compression;let le=t+"/";if(R=p.dbisDb=p.openDB(Bg.INTERNAL_DBIS_NAME,N),q(),R.get(le))return F&&F(),cd(),ze(e);let se=A_(p.openDB(le,ce),p);p.databaseName=r,se.tableId=R.get(nd),Nr.trace(`Assigning new table id ${se.tableId} for ${t}`),se.tableId||(se.tableId=1),R.put(nd,se.tableId+1),T.tableId=se.tableId,g=Pk(_,t,Mg({primaryStore:se,auditStore:K,audit:c,sealed:l,splitSegments:u,replicate:d,trackDeletes:f,expirationMS:n&&n*1e3,evictionMS:s&&s*1e3,primaryKey:y,tableName:t,tableId:se.tableId,databasePath:r,databaseName:r,indices:{},attributes:a,schemaDefined:m,dbisDB:R})),g.schemaVersion=1,O=!0,R.put(le,T)}let Z=g.indices;R=R||(p.dbisDb=p.openDB(Bg.INTERNAL_DBIS_NAME,N)),g.dbisDB=R;let G=[];for(let{key:K,value:ce}of R.getRange({start:!0})){let[le,se]=K.toString().split("/");if(se===""&&(se=ce.name),se){if(le!==t)continue}else continue;let pe=a.find(Ue=>Ue.name===se),Ne=!pe?.indexed&&ce.indexed&&!ce.isPrimaryKey;if((!pe||Ne)&&(q(),O=!0,pe||R.remove(K),Ne)){let Ue=g.indices[le];Ue&&G.push(Ue)}}let Y=[];try{for(let K of a||[]){if((K.relationship||K.computed)&&(O=!0,K.relationship))continue;let ce=t+"/"+(K.name||"");Object.defineProperty(K,"key",{value:ce,configurable:!0});let le=R.get(ce);if(K.isPrimaryKey){if(le=le||R.get(ce=t+"/")||{},c!==void 0&&c!==g.audit||l!==void 0&&l!==g.sealed||d!==void 0&&d!==g.replicate||(+n||void 0)!==(+le.expiration||void 0)||(+s||void 0)!==(+le.eviction||void 0)||K.type!==le.type){let pe={...le};typeof c=="boolean"&&(c&&g.enableAuditing(c),pe.audit=c),n&&(pe.expiration=+n),s&&(pe.eviction=+s),l!==void 0&&(pe.sealed=l),d!==void 0&&(pe.replicate=d),K.type&&(pe.type=K.type),O=!0,q(),R.put(ce,pe)}continue}le?.attribute&&!le.name&&(le.indexed=!0);let se=!le||le.type!==K.type||JSON.stringify(le.indexed)!==JSON.stringify(K.indexed)||le.nullable!==K.nullable||le.version!==K.version||JSON.stringify(le.properties)!==JSON.stringify(K.properties)||JSON.stringify(le.elements)!==JSON.stringify(K.elements);if(K.indexed){let pe=Lk(ce,p,K);(se||le.indexingPID&&le.indexingPID!==process.pid||le.restartNumber<gh.workerData?.restartNumber)&&(O=!0,q(),le=R.get(ce),(se||le.indexingPID&&le.indexingPID!==process.pid||le.restartNumber<gh.workerData?.restartNumber)&&(O=!0,K.indexNulls===void 0&&(K.indexNulls=!0),g.primaryStore.getStats().entryCount>0&&(K.lastIndexedKey=le?.lastIndexedKey??void 0,K.indexingPID=process.pid,pe.isIndexing=!0,Object.defineProperty(K,"dbi",{value:pe}),Y.push(K))),R.put(ce,K)),le?.indexNulls&&K.indexNulls===void 0&&(K.indexNulls=!0),pe.indexNulls=K.indexNulls,Z[K.name]=pe}else se&&(O=!0,q(),R.put(ce,K))}}finally{F&&F()}if(O&&(g.schemaVersion++,g.updatedAttributes()),Nr.trace(`${t} table loading, running index`),Y.length>0||G.length>0?g.indexingOperation=zie(g,Y,G):O&&Fg.signalSchemaChange(new Hg.SchemaEventMsg(process.pid,"schema-change",g.databaseName,g.tableName)),g.origin=h,O)for(let K of ph)K(g,h!=="cluster");return(n||s||i)&&g.setTTLExpiration({expiration:n,eviction:s,scanInterval:i}),Nr.trace(`${t} table loaded`),g;function q(){F||p.transactionSync(()=>({then(K){F=K}}))}o(q,"startTxn")}async function zie(e,t,r){try{Nr.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await Fg.signalSchemaChange(new Hg.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,a={},c=0,l=t.length;if(await new Promise(u=>setImmediate(u)),l>0){let u;for(let f of t)(0,od.compareKeys)(f.lastIndexedKey,u)<0&&(u=f.lastIndexedKey),f.lastIndexedKey==null&&f.dbi.clearAsync();let d=0;for(let{key:f,value:m,version:h}of e.primaryStore.getRange({start:u,lazy:l<4,versions:!0,snapshot:!1}))if(m){if(d++,s=e.primaryStore.ifVersion(f,h,()=>{for(let p=0;p<l;p++){let _=t[p],g=_.name,y=_.dbi;try{let T=_.resolve,R=m&&(T?T(m):m[g]);if(y.customIndex){y.customIndex.index(f,R);continue}let N=(0,Ik.getIndexedValues)(R);if(N)for(let O=0,F=N.length;O<F;O++)y.put(N[O],f)}catch(T){a[g]||(a[g]=!0,Nr.error(`Error indexing attribute ${g}`,T))}}}),s.then(()=>d--,p=>{d--,Nr.error(p)}),gh.workerData&&gh.workerData.restartNumber!==wk.restartNumber&&(i=!0),++c%100===0||i){for(let p of t)p.lastIndexedKey=f,e.dbisDB.put(p.key,p);if(i)return}d>Yie?await s:d>Wie&&await new Promise(p=>setImmediate(p))}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 Fg.signalSchemaChange(new Hg.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),Nr.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){Nr.error("Error in indexing",n)}}function jie({table:e,database:t}){let r=Yu({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 bl(e){return ph.push(e),{remove(){let t=ph.indexOf(e);t>-1&&ph.splice(t,1)}}}function Sh(e){return Eh.push(e),{remove(){let t=Eh.indexOf(e);t>-1&&Eh.splice(t,1)}}}function qg(){let e=(0,Vt.get)(U.STORAGE_COMPRESSION),t=(0,Vt.get)(U.STORAGE_COMPRESSION_DICTIONARY),r=(0,Vt.get)(U.STORAGE_COMPRESSION_THRESHOLD)||Ok,n={startingOffset:32};return t&&(n.dictionary=_h.readFileSync(t)),r&&(n.threshold=r),e&&n}var Vt,Bg,od,Ft,ss,sd,ad,SN,_h,TN,Ik,Fg,Hg,gh,Nk,wk,Nr,RN,Gg,Ok,un,ke,nd,ph,Eh,kg,Uo,id,Yie,Wie,De=ue(()=>{Vt=w(oe()),Bg=w(qt()),od=require("lmdb"),Ft=require("path"),ss=require("fs"),sd=w(yt());O_();ad=w(Im()),SN=w(Nm());k();_h=w(require("fs-extra")),TN=w(Zs()),Ik=w(bn()),Fg=w(Co()),Hg=w(oi()),gh=require("worker_threads"),Nk=w(Q()),wk=w(nt());Di();Wc();Yn();bk();Nr=(0,Nk.forComponent)("storage"),RN="data",Gg=Symbol("defined-tables"),Ok=((0,Vt.get)(U.STORAGE_PAGESIZE)||4096)-60;(0,Vt.initSync)();un=Object.create(null),ke=Object.create(null);(0,TN._assignPackageExport)("databases",ke);(0,TN._assignPackageExport)("tables",un);nd=Symbol.for("next-table-id"),ph=[],Eh=[],Uo=new Map;o(Kie,"getTables");o(st,"getDatabases");o(cd,"resetDatabases");o(hh,"readMetaDb");o(Ck,"ensureDB");o(Pk,"setTable");o(Yu,"database");o(gI,"dropDatabase");o(Lk,"openIndex");o(ze,"table");Yie=1e3,Wie=10;o(zie,"runIndexing");o(jie,"dropTableMeta");o(bl,"onUpdatedTable");o(Sh,"onRemovedDB");o(qg,"getDefaultCompression")});var bN={};Oe(bN,{loadGQLSchema:()=>Xie,start:()=>AN,startOnMainThread:()=>Jie});function AN({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:a,Source:c,Kind:l,NamedTypeNode:u,StringValueNode:d}=await import("graphql"),f=a(new c(r.toString(),s)),m=new Map,h=[],p;for(let y of f.definitions)switch(y.kind){case l.OBJECT_TYPE_DEFINITION:let F=function(G){if(G.kind==="NonNullType"){let K=F(G.type);return K.nullable=!1,K}if(G.kind==="ListType")return{type:"array",elements:F(G.type)};let q={type:G.name?.value};return Object.defineProperty(q,"location",{value:G.loc.startToken}),q};o(F,"getProperty");let T=y.name.value,R=[],N={table:null,database:null,properties:R};m.set(T,N);for(let G of y.directives){if(G.name.value==="table"){for(let q of G.arguments)N[q.name.value]=q.value.value;N.schema&&(N.database=N.schema),N.table||(N.table=T),N.audit&&(N.audit=N.audit!=="false"),N.attributes=N.properties,h.push(N)}if(G.name.value==="sealed"&&(N.sealed=!0),G.name.value==="splitSegments"&&(N.splitSegments=!0),G.name.value==="replicate"&&(N.replicate=!0),G.name.value==="export"){N.export=!0;for(let q of G.arguments)typeof N.export!="object"&&(N.export={}),N.export[q.name.value]=q.value.value}}let O=!1,Z={};for(let G of y.fields){let Y=F(G.type);Y.name=G.name.value,R.push(Y),Z[Y.name]=void 0;for(let q of G.directives){let K=q.name.value;if(K==="primaryKey")O?console.warn("Can not define two attributes as a primary key at",q.loc):(Y.isPrimaryKey=!0,O=!0);else if(K==="indexed"){let ce={};for(let le of q.arguments||[])ce[le.name.value]=le.value.value;Y.indexed=ce}else if(K==="computed"){for(let ce of q.arguments||[])if(ce.name.value==="from"){let le=ce.value.value;Y.computed={from:g(le,ce,Z)},Y.version==null&&(Y.version=le)}else ce.name.value==="version"&&(Y.version=ce.value.value);Y.computed=Y.computed||!0}else if(K==="relationship"){let ce={};for(let le of q.arguments)ce[le.name.value]=le.value.value;Y.relationship=ce}else if(K==="createdTime")Y.assignCreatedTime=!0;else if(K==="updatedTime")Y.assignUpdatedTime=!0;else if(K==="expiresAt")Y.expiresAt=!0;else if(K==="allow"){let ce=Y.authorizedRoles=[];for(let le of q.arguments)le.name.value==="role"&&ce.push(le.value.value)}else server.knownGraphQLDirectives.includes(K)&&console.warn(`@${K} is an unknown directive, at`,q.loc)}}N.type=T,T==="Query"&&(p=N)}function _(y){let T=m.get(y.type);T?(Object.defineProperty(y,"properties",{value:T.properties}),Object.defineProperty(y,"definition",{value:T})):y.type==="array"?_(y.elements):Qie.includes(y.type)||(0,Mk.getWorkerIndex)()===0&&console.error(`The type ${y.type} is unknown at line ${y.location.line}, column ${y.location.column}, in ${s}`)}o(_,"connectPropertyType");for(let y of m.values())for(let T of y.properties)_(T);for(let y of h)y.tableClass=e(y),y.export&&(y.export.name===""?i.set((0,yN.dirname)(n),y.tableClass):i.set((0,yN.dirname)(n)+"/"+(y.export.name||y.type),y.tableClass,y.export));function g(y,T,R){return new Dk.Script(`function computed(attributes) { return function(record) { with(attributes) { with (record) { return ${y}; } } } } computed;`,{filename:s,lineOffset:T.loc.startToken.line-1,columnOffset:T.loc.startToken.column}).runInThisContext()(R)}o(g,"createComputedFrom")}}var yN,Dk,Mk,Qie,Jie,Xie,vk=ue(()=>{yN=require("path"),Dk=require("node:vm");De();Mk=w(nt()),Qie=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt","Blob"];server.knownGraphQLDirectives&&(server.knownGraphQLDirectives=["table","sealed","export","primaryKey","indexed","computed","relationship","createdTime","updatedTime","expiresAt","allow"]);o(AN,"start");Jie=AN,Xie=AN({ensureTable:ze}).handleFile});var NN={};Oe(NN,{start:()=>aoe});function Zie(e){if(e.kind!==Be.Kind.OPERATION_DEFINITION&&e.kind!==Be.Kind.FRAGMENT_DEFINITION)throw new Hr(`Unexpected non-executable definition type ${e.kind}.`)}function Uk(e){if(typeof e!="object"||e===null)throw new Qi("Request body must be an object.");if(!("query"in e))throw new Qi("Request body must contain a `query` field.");if(typeof e.query!="string")throw new Qi("Request body `query` field must be a string.");if("variables"in e&&(typeof e.variables!="object"||e.variables===null))throw new Qi("Request body `variables` field must be an object.");if("operationName"in e&&typeof e.operationName!="string")throw new Qi("Request body `operationName` field must be a string.")}function IN(e){return parseInt(e.value,10)}function Bk(e){return parseFloat(e.value)}function Fk(e,t,r){let n=r.get(e.name.value);return Hk(n)?kk(n,t):{attribute:t,value:n}}function Hk(e){return typeof e=="object"&&e!=null&&!Array.isArray(e)}function kk(e,t){return t=typeof t=="string"?[t]:t,Object.entries(e).flatMap(([r,n])=>(t=[...t,r],Hk(n)?kk(n,t):{attribute:t,value:n}))}function eoe(e,t,r){switch(t=[...t,e.name.value],e.value.kind){case Be.Kind.NULL:return{attribute:t,value:null};case Be.Kind.INT:return{attribute:t,value:IN(e.value)};case Be.Kind.FLOAT:return{attribute:t,value:Bk(e.value)};case Be.Kind.BOOLEAN:case Be.Kind.STRING:return{attribute:t,value:e.value.value};case Be.Kind.VARIABLE:return Fk(e.value,t,r);case Be.Kind.OBJECT:return Gk(e.value,t,r);case Be.Kind.LIST:case Be.Kind.ENUM:default:throw new Hr(`Value type, ${e.value.kind}, is not supported.`)}}function Gk(e,t,r){return e.fields.flatMap(n=>eoe(n,t,r))}function toe(e,t){switch(e.value.kind){case Be.Kind.NULL:return{attribute:e.name.value,value:null};case Be.Kind.INT:return{attribute:e.name.value,value:IN(e.value)};case Be.Kind.FLOAT:return{attribute:e.name.value,value:Bk(e.value)};case Be.Kind.BOOLEAN:case Be.Kind.STRING:return{attribute:e.name.value,value:e.value.value};case Be.Kind.VARIABLE:return Fk(e.value,e.name.value,t);case Be.Kind.OBJECT:return Gk(e.value,[e.name.value],t);case Be.Kind.LIST:case Be.Kind.ENUM:default:throw new Hr(`Argument type, ${e.value.kind}, is not supported.`)}}function roe(e,t){return e.flatMap(r=>toe(r,t))}function $g(e,t){return e.selections.flatMap(r=>{switch(r.kind){case Be.Kind.FIELD:return r;case Be.Kind.FRAGMENT_SPREAD:{let n=r.name.value,s=t.get(n);if(s==null)throw new Hr(`Fragment \`${n}\` not found.`);return $g(s.selectionSet,t)}case Be.Kind.INLINE_FRAGMENT:return $g(r.selectionSet,t)}})}function qk(e,t){return $g(e,t).map(r=>r.selectionSet?.selections.length>0?{name:r.name.value,select:qk(r.selectionSet,t)}:r.name.value)}async function noe(e,t,r,n){let s=bs.getMatch(e.name.value,"graphql");if(s===void 0)throw new Hr(`Resource \`${e.name.value}\` not found.`);let i=s.Resource,a={select:qk(e.selectionSet,r),conditions:roe(e.arguments,t)},c=[];n.authorize=!0;for await(let l of i.search(a,n))c.push(l);return[e.name.value,c]}function $k(e){switch(e.kind){case Be.Kind.NULL:return null;case Be.Kind.INT:return IN(e);case Be.Kind.FLOAT:return parseFloat(e.value);case Be.Kind.STRING:case Be.Kind.BOOLEAN:return e.value;case Be.Kind.OBJECT:return e.fields.reduce((t,r)=>({[r.name.value]:$k(r.value),...t}),{});case Be.Kind.LIST:case Be.Kind.ENUM:default:throw new Hr(`Value type, ${e.kind}, is not supported.`)}}function soe(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=$k(n.defaultValue)),n.type.kind===Be.Kind.NON_NULL_TYPE&&!(s in t)&&i===void 0)throw new Hr(`Variable $${s} is required, but not provided.`);r.set(n.variable.name.value,i??null)}return r}async function ioe(e,t,r,n){if(e.operation===Be.OperationTypeNode.SUBSCRIPTION)throw new Hr("Subscriptions are not supported.");if(e.operation===Be.OperationTypeNode.MUTATION)throw new Hr("Mutations are not supported yet.");let s=soe(e.variableDefinitions,t),i=await Promise.all($g(e.selectionSet,r).map(c=>noe(c,s,r,n))),a={data:{}};for(let[c,l]of i)a.data[c]=l;return a}async function xk({query:e,variables:t={},operationName:r},n){let s=Be.parse(e),i=new Map,a=new Map;for(let u of s.definitions)if(Zie(u),u.kind===Be.Kind.FRAGMENT_DEFINITION)a.set(u.name.value,u);else{if(u.name===void 0&&s.definitions.length>1)throw new Hr("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 Hr(`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 Hr("Operation name is required when there are multiple operations in the document.");else if(c=i.get(r),c==null)throw new Hr(`Operation \`${r}\` not found.`);let l=await ioe(c,t,a,n);return{status:200,headers:{"Content-Type":"application/graphql-response+json; charset=utf-8"},body:JSON.stringify(l)}}async function ooe(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 Uk(r),xk(r,e)}case"POST":{let r=await To(e.headers.get("content-type"),!0)(e._nodeRequest);return Uk(r),xk(r,e)}default:throw new Qi("Method Not Allowed",405,{Allow:"GET, POST"})}}function aoe(e){e.server.http(async(t,r)=>{if(!t.url.startsWith("/graphql"))return r(t);try{return await ooe(t)}catch(n){logger.error(n);let s=t.headers.get("accept")??"application/graphql-response+json";switch(s){case"application/json":{if(n instanceof Qi)return{status:n.statusCode,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/json",...n.headers}};if(n instanceof Be.GraphQLError)return{status:200,body:JSON.stringify({errors:[n]}),headers:{"Content-Type":"application/json"}};if(n instanceof Hr)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 Qi)return{status:n.statusCode,body:JSON.stringify({errors:[{message:n.message}]}),headers:{"Content-Type":"application/graphql-response+json",...n.headers}};if(n instanceof Be.GraphQLError)return{status:400,body:JSON.stringify({errors:[n]}),headers:{"Content-Type":"application/graphql-response+json"}};if(n instanceof Hr)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 Be,Hr,Qi,Vk=ue(()=>{Be=w(require("graphql"));Ro();Bu();o(Zie,"assertExecutableDefinitionNode");o(Uk,"assertRequestParams");o(IN,"processIntValueNode");o(Bk,"processFloatValueNode");o(Fk,"processVariableNode");o(Hk,"isObject");o(kk,"transformObjectIntoQueryCondition");o(eoe,"processObjectFieldNode");o(Gk,"processObjectValueNode");o(toe,"processArgumentNode");o(roe,"buildConditionsQuery");o($g,"fillInFragments");o(qk,"buildSelectQuery");o(noe,"processFieldNode");o($k,"processConstValueNode");o(soe,"resolveVariables");o(ioe,"executeOperation");o(xk,"resolver");Hr=class extends Error{static{o(this,"GraphQLQueryingError")}},Qi=class extends Error{static{o(this,"HTTPError")}statusCode;headers;constructor(t,r=400,n={}){super(t),this.statusCode=r,this.headers=n}};o(ooe,"graphqlQueryingHandler");o(aoe,"start")});var Qk=M((mDe,jk)=>{var ld=require("validate.js"),Yk=ut(),ud=(k(),v(W)),{handleHDBError:coe,hdbErrors:loe}=ge(),{HDB_ERROR_MSGS:tr,HTTP_STATUS_CODES:uoe}=loe,wN=o(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),doe={STRUCTURE_USER:"structure_user"},Kk=Object.values(ud.ROLE_TYPES_ENUM),foe="attribute_permissions",moe="attribute_name",{PERMS_CRUD_ENUM:dd}=ud,hoe=[foe,...Object.values(dd)],Wk=[dd.READ,dd.INSERT,dd.UPDATE],poe=[moe,...Wk];function Eoe(e){let t=wN();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,zk(e,t)}o(Eoe,"addRoleValidation");function _oe(e){let t=wN();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,zk(e,t)}o(_oe,"alterRoleValidation");function goe(e){let t=wN();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,Yk.validateObject(e,t)}o(goe,"dropRoleValidation");var Soe=["operation","role","id","permission","hdb_user","access"];function zk(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let a=0,c=n.length;a<c;a++)Soe.includes(n[a])||s.push(n[a]);s.length>0&&fr(tr.INVALID_ROLE_JSON_KEYS(s),r);let i=Yk.validateObject(e,t);if(i&&i.message.split(",").forEach(a=>{fr(a,r)}),e.permission){let a=Toe(e);a&&fr(a,r),Kk.forEach(c=>{e.permission[c]&&!ld.isBoolean(e.permission[c])&&fr(tr.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let a in e.permission)if(Kk.indexOf(a)<0){if(a===doe.STRUCTURE_USER){let l=e.permission[a];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]||fr(tr.SCHEMA_NOT_FOUND(f),r)}continue}fr(tr.STRUCTURE_USER_ROLE_TYPE_ERROR(a),r);continue}let c=e.permission[a];if(!a||!global.hdb_schema[a]){fr(tr.SCHEMA_NOT_FOUND(a),r);continue}if(c.tables)for(let l in c.tables){let u=c.tables[l];if(!l||!global.hdb_schema[a][l]){fr(tr.TABLE_NOT_FOUND(a,l),r);continue}if(Object.keys(u).forEach(d=>{hoe.includes(d)||fr(tr.INVALID_PERM_KEY(d),r,a,l)}),Object.values(dd).forEach(d=>{ld.isDefined(u[d])?ld.isBoolean(u[d])||fr(tr.TABLE_PERM_NOT_BOOLEAN(d),r,a,l):fr(tr.TABLE_PERM_MISSING(d),r,a,l)}),u.attribute_permissions===void 0){fr(tr.ATTR_PERMS_ARRAY_MISSING,r,a,l);continue}else if(!(Array.isArray(u.attribute_permissions)||u.attribute_permissions===null)){fr(tr.ATTR_PERMS_NOT_ARRAY,r,a,l);continue}if(u.attribute_permissions){let d=global.hdb_schema[a][l].attributes.map(({attribute:m})=>m),f={read:!1,insert:!1,update:!1};for(let m in u.attribute_permissions){let h=u.attribute_permissions[m];if(Object.keys(h).forEach(_=>{!poe.includes(_)&&_!==dd.DELETE&&fr(tr.INVALID_ATTR_PERM_KEY(_),r,a,l)}),!ld.isDefined(h.attribute_name)){fr(tr.ATTR_PERM_MISSING_NAME,r,a,l);continue}let p=h.attribute_name;if(!d.includes(p)){fr(tr.INVALID_ATTRIBUTE_IN_PERMS(p),r,a,l);continue}Wk.forEach(_=>{ld.isDefined(h[_])?ld.isBoolean(h[_])||fr(tr.ATTR_PERM_NOT_BOOLEAN(_,p),r,a,l):fr(tr.ATTR_PERM_MISSING(_,p),r,a,l)}),!f.read&&h.read===!0&&(f.read=!0),!f.insert&&h.insert===!0&&(f.insert=!0),!f.update&&h.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=`${a}.${l}`;fr(tr.MISMATCHED_TABLE_ATTR_PERMS(m),r,a,l)}}}}return Roe(r)}o(zk,"customValidate");jk.exports={addRoleValidation:Eoe,alterRoleValidation:_oe,dropRoleValidation:goe};function Toe(e){let{operation:t,permission:r}=e;if(t===ud.OPERATIONS_ENUM.ADD_ROLE||t===ud.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 tr.SU_CU_ROLE_COMBINED_ERROR;{let a=r.super_user?ud.ROLE_TYPES_ENUM.SUPER_USER:ud.ROLE_TYPES_ENUM.CLUSTER_USER;return tr.SU_CU_ROLE_NO_PERMS_ALLOWED(a)}}}return null}o(Toe,"validateNoSUPerms");function Roe(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:tr.ROLE_PERMS_ERROR,...e};return coe(new Error,n,uoe.BAD_REQUEST)}else return null}o(Roe,"generateRolePermResponse");function fr(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]}}o(fr,"addPermError")});var Rh=M((EDe,eG)=>{"use strict";var Jk=vn(),Xk=on(),yoe=pl(),CN=Qk(),PN=Co(),pDe=require("uuid").v4,Aoe=require("util"),Vg=(k(),v(W)),boe=ie(),LN=Xk.searchByValue,Ioe=Xk.searchByHash,Noe=Aoe.promisify(yoe.delete),woe=ai(),Ooe=Vu(),{hdbErrors:Coe,handleHDBError:Il}=ge(),{HDB_ERROR_MSGS:Zk,HTTP_STATUS_CODES:Th}=Coe,{UserEventMsg:DN}=oi();eG.exports={addRole:Poe,alterRole:Loe,dropRole:Doe,listRoles:Moe};function ON(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}o(ON,"scrubRoleDetails");async function Poe(e){let t=CN.addRoleValidation(e);if(t)throw t;e=ON(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await LN(r)||[])}catch(i){throw Il(i)}if(n&&n.length>0)throw Il(new Error,Zk.ROLE_ALREADY_EXISTS(e.role),Th.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 Jk.insert(s),PN.signalUserChange(new DN(process.pid)),e=ON(e),e}o(Poe,"addRole");async function Loe(e){let t=CN.alterRoleValidation(e);if(t)throw t;e=ON(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await Jk.update(r)}catch(s){throw Il(s)}if(n&&n?.message==="updated 0 of 1 records")throw Il(new Error,"Invalid role id",Th.BAD_REQUEST,void 0,void 0,!0);return await PN.signalUserChange(new DN(process.pid)),e}o(Loe,"alterRole");async function Doe(e){let t=CN.dropRoleValidation(e);if(t)throw Il(new Error,t,Th.BAD_REQUEST,void 0,void 0,!0);let r=new Ooe(Vg.SYSTEM_SCHEMA_NAME,Vg.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await Ioe(r));if(n.length===0)throw Il(new Error,Zk.ROLE_NOT_FOUND,Th.NOT_FOUND,void 0,void 0,!0);let s=new woe(Vg.SYSTEM_SCHEMA_NAME,Vg.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await LN(s)),a=!1;if(boe.isEmptyOrZeroLength(i)===!1){for(let l=0;l<i.length;l++)if(i[l].active===!0){a=!0;break}}if(a===!0)throw Il(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,Th.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await Noe(c),PN.signalUserChange(new DN(process.pid)),`${n[0].role} successfully deleted`}o(Doe,"dropRole");async function Moe(){return LN({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}o(Moe,"listRoles")});var MN={};Oe(MN,{start:()=>nG,startOnMainThread:()=>xoe});function nG({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r){let n=(0,tG.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 a in i.permission){if(voe.includes(a))continue;let c=i.permission[a];c.tables||(i.permission[a]=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 Uoe(i)}}}async function Uoe(e){let t=st().system.hdb_role;for await(let r of t.search([{attribute:"role",value:e.role}])){let{__createdtime__:n,__updatedtime__:s,...i}=r;return(0,rG.isEqual)(i,e)?void 0:(e.id=r.id,(0,Kg.alterRole)(e))}return(0,Kg.addRole)(e)}var Kg,tG,rG,voe,xoe,sG=ue(()=>{De();Kg=w(Rh()),tG=require("yaml"),rG=require("lodash"),voe=["super_user","cluster_user","structure_user"];o(nG,"start");o(Uoe,"ensureRole");xoe=nG});async function Yg(e){let t=(0,aG.pathToFileURL)(e).toString();if(Boe)return yh||(yh=Foe(koe)),(await(await yh).import(t)).namespace;try{return await import(t)}catch(r){try{(await import("internal/util")).default.decorateErrorStack(r)}catch{}throw r}}async function Foe(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),yh=new Compartment({console,Math,Date,fetch:Hoe,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,oG.extname)(r)||(r+=".js"),r)},importHook:o(async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){s.Resource=xr,s.tables=un,s.databases=ke}};let n=await(0,iG.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)},"importHook")}),yh}function Hoe(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 koe(){return{Resource:xr,tables:un}}var iG,oG,aG,Boe,yh,vN=ue(()=>{La();De();iG=require("fs/promises"),oG=require("path"),aG=require("url"),Boe=!1;o(Yg,"secureImport");o(Foe,"getCompartment");o(Hoe,"secureOnlyFetch");o(koe,"getGlobalVars")});var UN={};Oe(UN,{handleApplication:()=>Goe,suppressHandleApplicationWarning:()=>qoe});function lG(e){return typeof e=="function"&&("get"in e||"put"in e||"post"in e||"delete"in e)}async function Goe(e){e.handleEntry(t=>{if(t.entryType!=="file"){e.logger.warn(`jsResource plugin cannot handle entry type ${t.entryType}. Modify the 'files' option in ${e.configFilePath} to only include files.`);return}if(t.eventType!=="add"){e.requestRestart();return}Yg(t.absolutePath).then(r=>{let n=(0,cG.dirname)(t.urlPath).replace(/\\/g,"/").replace(/^\/$/,"");lG(r.default)&&(e.resources.set(n,r.default),e.logger.debug(`Registered root resource: ${n}`)),uG(e,r,n)}).catch(r=>{e.logger.error(`Failed to load resource module ${t.absolutePath}: ${r}`),e.requestRestart()})})}function uG(e,t,r){for(let n in t){let s=t[n],i=`${r}/${n}`;lG(s)?(e.resources.set(i,s),e.logger.debug(`Registered resource: ${i}`)):typeof s=="object"&&uG(e,s,i)}}var cG,qoe,dG=ue(()=>{vN();cG=require("path");o(lG,"isResource");o(Goe,"handleApplication");o(uG,"recurseForResources");qoe=!0});var BN={};Oe(BN,{start:()=>$oe});function $oe({resources:e}){e.set("login",xN),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var xN,fG=ue(()=>{La();o($oe,"start");xN=class extends xr{static{o(this,"Login")}static async get(t,r,n){}static async post(t,r,n){let{username:s,password:i,redirect:a}=r;return{data:await n.login(s,i)}}}});function _G(e){let t={openapi:Voe,info:{title:"HarperDB HTTP REST interface",version:EG.packageJson.version},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,n]of e){if(!n.path||n.Resource.isError)continue;let{path:s}=n,i=s.split("/").slice(-1),{attributes:a,primaryKey:c,prototype:l}=n.Resource;if(c=c??"id",!c)continue;let u={},d=[];if(a)for(let{type:R,name:N,elements:O,relationship:F,definition:Z}of a){if(F)R==="array"?u[N]={type:"array",items:{$ref:Va+O.type}}:u[N]={$ref:Va+R};else{let G=Z??O?.definition;if(G){if(!t.components.schemas[G.type]){let Y={};G.properties.forEach(q=>{Y[q.name]=new GN(FN[q.type],q.type)}),t.components.schemas[G.type]=new pG(Y)}R==="array"?u[N]={type:"array",items:{$ref:Va+G.type}}:u[N]={$ref:Va+G.type}}else R==="array"?O.type==="Any"||O.type=="ID"?u[N]={type:"array",items:{format:O.type}}:u[N]={type:"array",items:new GN(FN[O.type],O.type)}:R==="Any"||R=="ID"?u[N]={format:R}:u[N]=new GN(FN[R],R)}d.push(new qN(N,"query",u[N]))}let f=Object.keys(u),m=new qN(c,"path",{format:"ID"});m.required=!0,m.description="primary key of record";let h=new qN("property","path",{enum:f});h.required=!0,t.components.schemas[i]=new pG(u);let p=l.post!==Resource.prototype.post||l.update,_=typeof l.put=="function",g=typeof l.get=="function",y=typeof l.delete=="function",T="/"+s+"/";p&&(t.paths[T]={},t.paths[T].post=new Koe(i,r,"create a new record auto-assigning a primary key")),g&&(t.paths[T]||(t.paths[T]={}),t.paths[T].get=new HN(d,r,{200:new kN({$ref:Va+i})},"search for records by the specified property name and value pairs")),y&&(t.paths[T]||(t.paths[T]={}),t.paths[T].delete=new hG(d,r,"delete all the records that match the provided query",{204:new mG})),T="/"+s+"/{"+c+"}",g&&(t.paths[T]={},t.paths[T].get=new HN([m],r,{200:new kN({$ref:Va+i})},"retrieve a record by its primary key")),_&&(t.paths[T]||(t.paths[T]={}),t.paths[T].put=new Yoe([m],r,i,"create or update the record with the URL path that maps to the record's primary key")),y&&(t.paths[T]||(t.paths[T]={}),t.paths[T].delete=new hG([m],r,"delete a record with the given primary key",{204:new mG})),g&&h.schema.enum.length>0&&(T="/"+s+"/{"+c+"}.{property}",t.paths[T]={},t.paths[T].get=new HN([m,h],r,{200:new kN({enum:f})},"used to retrieve the specified property of the specified record"))}return t}function Koe(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Va+e}}}},this.security=t,this.responses={200:{description:$N,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function HN(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function kN(e){this.description=$N,this.content={"application/json":{schema:e}}}function mG(){this.description="successfully processed request, no content returned to client"}function Yoe(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Va+r}}}},this.responses={200:{description:$N}}}function hG(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function pG(e){this.type="object",this.properties=e}function GN(e,t){this.type=e,this.format=t}function qN(e,t,r){this.name=e,this.in=t,this.schema=r}var EG,Voe,FN,Va,$N,gG=ue(()=>{EG=w(Rt()),Voe="3.0.3",FN={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Va="#/components/schemas/",$N="successful operation";o(_G,"generateJsonApi");o(Koe,"Post");o(HN,"Get");o(kN,"Response200");o(mG,"Response204");o(Yoe,"Put");o(hG,"Delete");o(pG,"ResourceSchema");o(GN,"Type");o(qN,"Parameter")});var TG={};Oe(TG,{Request:()=>Ka,createReuseportFd:()=>Wg});var SG,Ka,VN,KN,Wg,Ah=ue(()=>{SG=require("os"),Ka=class{static{o(this,"Request")}#e;constructor(t,r){this.method=t.method;let n=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=n,this.headers=new KN(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._nodeRequest.socket.getPeerCertificate()}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new VN(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get httpVersion(){return this._nodeRequest.httpVersion}get isAborted(){return!1}sendEarlyHints(t,r={}){r.link=t,this._nodeResponse.writeEarlyHints(r)}},VN=class{static{o(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)}},KN=class{constructor(t){this.asObject=t}static{o(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(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,SG.platform)()!="win32"&&(Wg=require("node-unix-socket").createReuseportFd)});var jg={};Oe(jg,{parseHeaderValue:()=>WN,start:()=>joe});async function zoe(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream",s=n?"CONNECT":e.method;e.search&&N_(e);let i=new Os;try{e.responseHeaders=i;let a=e.url.slice(1),c,l;if(a!==RG){let g=zg.getMatch(a,n?"sse":"rest");if(!g)return t(e);e.handlerPath=g.path,c=new ri(g.relativeURL),c.async=!0,l=g.Resource}if(l?.isCaching){let g=r["cache-control"];if(g){let y=WN(g);for(let T of y)switch(T.name){case"max-age":e.expiresAt=T.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 g=WN(u).map(y=>(y.next?.name==="confirm"&&y.next.value>=0&&(e.replicatedConfirmation=+y.next.value),y.name));e.replicateTo=g.length===1&&+g[0]>=0?+g[0]:g[0]==="*"?void 0:g}r["x-replicate-from"]==="none"&&(e.replicateFrom=!1);let f=await Ut(e,()=>{if(r["content-length"]||r["transfer-encoding"])try{e.data=To(r["content-type"],!0)(e.body,e.headers)}catch(g){throw new fd.ClientError(g,400)}if(e.authorize=!0,a===RG&&s==="GET"){if(e?.user?.role?.permission?.super_user)return _G(zg);throw new fd.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 fd.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new fd.ServerError(`Method ${s} is not recognized`,501)}}),m=200,h;if(f==null)m=s==="GET"||s==="HEAD"?404:204,YN.lastModified&&e.lastModified&&i.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(f.status>0&&f.headers){let g=ok(f.headers,i);return f.headers!==g&&(f.headers=g),f.data!==void 0&&(f.body=cm(f.data,e,f)),f}else if(h=e.lastModified){Woe[0]=h;let g=String.fromCharCode(34,(jr[0]&63)+62,(jr[0]>>6)+(jr[1]<<2&63)+62,(jr[1]>>4)+(jr[2]<<4&63)+62,(jr[2]>>2)+62,(jr[3]&63)+62,(jr[3]>>6)+(jr[4]<<2&63)+62,(jr[4]>>4)+(jr[5]<<4&63)+62,(jr[5]>>2)+62,(jr[6]&63)+62,(jr[6]>>6)+(jr[7]<<2&63)+62,34),y=r["if-none-match"];y&&g==y?(f?.onDone&&f.onDone(),m=304,f=void 0):i.setIfNone("ETag",g),YN.lastModified&&i.setIfNone("Last-Modified",new Date(h).toUTCString())}e.createdResource&&(m=201),e.newLocation&&i.setIfNone("Location",e.newLocation);let p={status:m,headers:i,body:void 0},_=e.loadedFromSource??f?.wasLoadedFromSource?.();return _!==void 0&&(p.wasCacheMiss=_,!_&&h&&i.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||h))/1e3))),f!==void 0&&(p.body=cm(f,e,p),s==="HEAD"&&(p.body=void 0)),p}catch(a){a.statusCode?a.statusCode===500?fi.warn(a):fi.info(a):fi.error(a),a.statusCode===405&&(a.method&&(a.message+=` to handle HTTP method ${a.method.toUpperCase()||""}`),a.allow&&(a.allow.push("trace","head","options"),i.setIfNone("Allow",a.allow.map(l=>l.toUpperCase()).join(", "))));let c={status:a.statusCode||500,headers:i,body:void 0};return c.body=cm(a.contentType?a:bG(a),e,c),c}}function joe(e){YN=e,e.includeExpensiveRecordCountEstimates&&(Ka.prototype.includeExpensiveRecordCountEstimates=!0),!yG&&(yG=!0,zg=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return zoe(t,r)},e),e.webSocket!==!1&&e.server.ws(async(t,r,n)=>{bh++;let s=new Kn;AG||(AG=!0,ch(l=>{bh>0&&l.push({metric:"ws-connections",connections:bh,byThread:!0})}));let i;t.on("error",l=>{i=!0,fi.warn(l)});let a;t.on("message",o(function(u){a||(a=To(r.requestedContentType??r.headers.asObject["content-type"],!1));let d=a(u);it(u.length,"bytes-received",r.handlerPath,"message","ws"),s.push(d)},"message"));let c;t.on("close",()=>{bh--,zr(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()});try{await n;let l=r.url.slice(1),u=zg.getMatch(l,"ws");if(zr(!!u,"connection","ws","connect"),u){r.handlerPath=u.path,it(p=>({count:p.count,total:bh}),"connections",r.handlerPath,"connect","ws"),r.authorize=!0;let d=new ri(u.relativeURL);d.checkPermission=r.user?.role?.permission??{};let f=u.Resource;c=(await Ut(r,()=>f.connect(d,s,r)))[Symbol.asyncIterator]();let h;for(;!(h=await c.next()).done;){let p=await Ia(h.value,r);t.send(p),it(p.length,"bytes-sent",r.handlerPath,"message","ws"),t._socket.writableNeedDrain&&await new Promise(_=>t._socket.once("drain",_))}}else return t.close(1011,`No resource was found to handle ${r.pathname}`)}catch(l){l.statusCode?l.statusCode===500?fi.warn(l):fi.info(l):fi.error(l),t.close(Qoe[l.statusCode]||1011,bG(l))}t.close()},e))}function WN(e){return e.trim().split(",").map(t=>{let r,n=t.trim().split(";"),s;for(;s=n.pop();)if(s.includes("=")){let[i,a]=s.trim().split("=");i=i.trim(),a&&(a=a.trim()),r={name:i.toLowerCase(),value:a,next:r}}else r={name:s.toLowerCase(),next:r};return r})}var fi,fd,bG,jr,Woe,YN,RG,yG,zg,AG,bh,Qoe,IG=ue(()=>{Ro();zi();fi=w(Q()),fd=w(ge());w_();Tu();xc();uh();gG();Ah();C_();({errorToString:bG}=fi),jr=new Uint8Array(8),Woe=new Float64Array(jr.buffer,0,1),YN={},RG="openapi";o(zoe,"http");bh=0;o(joe,"start");Qoe={401:3e3,403:3003};o(WN,"parseHeaderValue")});var zN=M((qDe,wG)=>{var{recordAction:Qg,recordActionBinary:NG}=(zi(),v(Og)),Joe=require("fastify-plugin"),Xoe=200;wG.exports=Joe(function(e,t,r){e.addHook("onResponse",async(n,s)=>{let i=s.elapsedTime}),e.addHook("onSend",async(n,s,i)=>{let a=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),Qg(a,"duration",u,f,d),NG(s.raw.statusCode<400,"success",u,f,d),NG(1,"response_"+s.raw.statusCode,u,f,d);let m=Xoe;i?.pipe?(i.on("data",g=>{m+=g.length}),i.on("end",()=>{Qg(performance.now()-c,"transfer",u,f,d),Qg(m,"bytes-sent",u,f,d)})):(m+=i?.length||0,Qg(m,"bytes-sent",u,f,d));let h=a.toFixed(3),p=s.getHeader("Server-Timing"),_=`db;dur=${h}`;s.header("Server-Timing",p?`${p}, ${_}`:_)}),r()},{name:"hdb-request-time"})});var CG=M(($De,OG)=>{var Zoe=ut(),eae={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};OG.exports=function(e){return Zoe.validateObject(e,eae)}});var Jg=M((VDe,PG)=>{"use strict";var tae=(k(),v(W)).OPERATIONS_ENUM,jN=class{static{o(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=tae.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};PG.exports=jN});var wh={};Oe(wh,{createTokens:()=>XN,getJWTRSAKeys:()=>rS,refreshOperationToken:()=>ZN,validateOperationToken:()=>ew,validateRefreshToken:()=>nS});async function rS(){if(Xg)return Xg;try{let e=Ih.default.join(Nh.default.getHdbBasePath(),$y),t=await Zg.default.readFile(Ih.default.join(e,Kf.JWT_PASSPHRASE_NAME),"utf8"),r=await Zg.default.readFile(Ih.default.join(e,Kf.JWT_PRIVATE_KEY_NAME),"utf8");return Xg={publicKey:await Zg.default.readFile(Ih.default.join(e,Kf.JWT_PUBLIC_KEY_NAME),"utf8"),privateKey:r,passphrase:t},Xg}catch(e){throw tS.default.error(e),new mi.ClientError(hd.NO_ENCRYPTION_KEYS,md.INTERNAL_SERVER_ERROR)}}async function XN(e){let t=(0,QN.validateBySchema)(e,Ji.default.object({username:Ji.default.string().optional(),password:Ji.default.string().optional(),role:Ji.default.string().optional(),expires_in:Ji.default.alternatives(Ji.default.string(),Ji.default.number()).optional()}));if(t)throw new mi.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(0,JN.findAndValidateUser)(e.username,e.password,f)}catch(f){throw tS.default.error(f),new mi.ClientError(hd.INVALID_CREDENTIALS,md.UNAUTHORIZED)}if(!r)throw new mi.ClientError(hd.INVALID_CREDENTIALS,md.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 a=await rS(),c=await pd.default.sign(i,{key:a.privateKey,passphrase:a.passphrase},{expiresIn:e.expires_in??UG,algorithm:eS,subject:Ed.OPERATION}),l=await pd.default.sign(i,{key:a.privateKey,passphrase:a.passphrase},{expiresIn:rae,algorithm:eS,subject:Ed.REFRESH}),u=BI(l,Br.SHA256);if((await(0,LG.update)(new DG.default(Vf,_u.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]))).skipped_hashes.length>0)throw new mi.ClientError(hd.REFRESH_TOKEN_SAVE_FAILED,md.INTERNAL_SERVER_ERROR);return MG.default.signalUserChange(new vG.UserEventMsg(process.pid)),{operation_token:c,refresh_token:l}}async function ZN(e){let t=(0,QN.validateBySchema)(e,Ji.default.object({refresh_token:Ji.default.string().required()}).required());if(t)throw new mi.ClientError(t.message);let{refresh_token:r}=e;await nS(r);let n=await rS(),s=await pd.default.decode(r);return{operation_token:await pd.default.sign({username:s.username,super_user:s.super_user,cluster_user:s.cluster_user},{key:n.privateKey,passphrase:n.passphrase},{expiresIn:UG,algorithm:eS,subject:Ed.OPERATION})}}async function ew(e){return xG(e,Ed.OPERATION)}async function nS(e){return xG(e,Ed.REFRESH)}async function xG(e,t){try{let r=await rS(),n=await pd.default.verify(e,r.publicKey,{algorithms:eS,subject:t});if(n.role)throw new Error("Invalid token");let s=await(0,JN.findAndValidateUser)(n.username,void 0,!1);if(t===Ed.REFRESH&&!FI(s.refresh_token,e))throw new Error("Invalid token");return s}catch(r){throw tS.default.warn(r),r?.name==="TokenExpiredError"?new mi.ClientError(hd.TOKEN_EXPIRED,md.FORBIDDEN):new mi.ClientError(hd.INVALID_TOKEN,md.UNAUTHORIZED)}}var pd,Zg,Ih,Ji,QN,mi,tS,JN,LG,DG,MG,vG,Nh,md,hd,UG,rae,eS,Ed,Xg,_d=ue(()=>{pd=w(require("jsonwebtoken")),Zg=w(require("fs-extra")),Ih=w(require("node:path")),Ji=w(require("joi")),QN=w(ut());k();mi=w(ge()),tS=w(Q());hg();JN=w(rs()),LG=w(vn()),DG=w(Jg()),MG=w(Co()),vG=w(oi()),Nh=w(oe()),{HTTP_STATUS_CODES:md,AUTHENTICATION_ERROR_MSGS:hd}=mi.hdbErrors;Nh.default.initSync();UG=Nh.default.get(U.AUTHENTICATION_OPERATIONTOKENTIMEOUT)||"1d",rae=Nh.default.get(U.AUTHENTICATION_REFRESHTOKENTIMEOUT)||"30d",eS="RS256",Ed={OPERATION:"operation",REFRESH:"refresh"};o(rS,"getJWTRSAKeys");o(XN,"createTokens");o(ZN,"refreshOperationToken");o(ew,"validateOperationToken");o(nS,"validateRefreshToken");o(xG,"validateToken")});var tw=M((jDe,HG)=>{"use strict";var nae=CG(),gd=require("passport"),sae=require("passport-local").Strategy,iae=require("passport-http").BasicStrategy,oae=require("util"),aae=rs(),FG=oae.callbackify(aae.findAndValidateUser),zDe=rn(),cae=(k(),v(W)),BG=(_d(),v(wh));gd.use(new sae(function(e,t,r){FG(e,t,r)}));gd.use(new iae(function(e,t,r){FG(e,t,r)}));gd.serializeUser(function(e,t){t(null,e)});gd.deserializeUser(function(e,t){t(null,e)});function lae(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let n,s;if(e.headers?.authorization){let a=e.headers.authorization.split(" ");n=a[0],s=a[1]}function i(a,c){return a?r(a):c?r(null,c):r("Must login")}switch(o(i,"handleResponse"),n){case"Basic":gd.authenticate("basic",{session:!1},(a,c)=>{i(a,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===cae.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?BG.validateRefreshToken(s).then(a=>{e.body.refresh_token=s,r(null,a)}).catch(a=>{r(a)}):BG.validateOperationToken(s).then(a=>{r(null,a)}).catch(a=>{r(a)});break;default:gd.authenticate("local",{session:!1},function(a,c){i(a,c)})(e,t,r);break}}o(lae,"authorize");function uae(e,t){let r=nae(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 a=i[e.schema].tables[e.table].attribute_permissions;for(let c in a)e.attributes.indexOf(a[c].attribute_name)>-1&&!a[c][e.operation]&&(n.authorized=!1,n.messages.push(`Not authorized to ${e.operation} ${a[c].attribute_name} `))}return t(null,n)}o(uae,"checkPermissions");HG.exports={authorize:lae,checkPermissions:uae}});var sS=M((JDe,kG)=>{"use strict";var dae=Xn();kG.exports={writeTransaction:fae};function fae(e,t,r){return dae.writeTransaction(e,t,r)}o(fae,"writeTransaction")});var VG=M((eMe,$G)=>{"use strict";var mae=on(),hae=ii(),GG=Q(),pae=vn(),ZDe=sS(),Eae=require("clone"),nw=require("alasql"),_ae=ng(),qG=require("util"),gae=qG.promisify(hae.getTableSchema),Sae=qG.promisify(mae.search),Tae=(k(),v(W)),rw=ie();_ae(nw);$G.exports={update:yae};var Rae="There was a problem performing this update. Please check the logs and try again.";async function yae({statement:e,hdb_user:t}){let r=await gae(e.table.databaseid,e.table.tableid),n=Aae(e.columns);rw.backtickASTSchemaItems(e);let{table:s,where:i}=e,a=Eae(s),c=rw.isEmpty(i)?"":` WHERE ${i.toString()}`,l=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,u=nw.parse(l).statements[0],d=await Sae(u),f=bae(n,d);return Iae(a,f,t)}o(yae,"update");function Aae(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=nw.compile(`SELECT ${r.expression.toString()} AS [${Tae.FUNC_VAL}] FROM ?`)}),t}catch(t){throw GG.error(t),new Error(Rae)}}o(Aae,"createUpdateRecord");function bae(e,t){return rw.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}o(bae,"buildUpdateRecords");async function Iae(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await pae.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){GG.error(`Error delete new_attributes from update response: ${i}`)}return s}o(Iae,"updateRecords")});var YG=M((sMe,KG)=>{var Nae=require("alasql"),wae=on(),Oae=Q(),Cae=Xn(),iw=require("util"),sw=ie(),Pae=(k(),v(W)),Lae=ii(),rMe=sS(),nMe=vn(),Dae="record",Mae="successfully deleted",vae=iw.callbackify(Fae),Uae=iw.promisify(wae.search),xae=iw.promisify(Lae.getTableSchema);KG.exports={convertDelete:vae};function Bae(e){return`${e.deleted_hashes.length} ${Dae}${e.deleted_hashes.length===1?"":"s"} ${Mae}`}o(Bae,"generateReturnMessage");async function Fae({statement:e,hdb_user:t}){let r=await xae(e.table.databaseid,e.table.tableid);sw.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=sw.isEmpty(s)?"":` WHERE ${s.toString()}`,a=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=Nae.parse(a).statements[0],l={operation:Pae.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{l.records=await Uae(c);let u=await Cae.deleteRecords(l);return sw.isEmptyOrZeroLength(u.message)&&(u.message=Bae(u)),delete u.txn_time,u}catch(u){throw Oae.error(u),u.hdb_code?u.message:u}}o(Fae,"convertDelete")});var JG=M((oMe,QG)=>{"use strict";var Hae=xa(),{hdbErrors:WG}=ge(),{getDatabases:zG}=(De(),v(mt));QG.exports={checkSchemaExists:jG,checkSchemaTableExists:kae,schemaDescribe:Hae};async function jG(e){if(!zG()[e])return WG.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}o(jG,"checkSchemaExists");async function kae(e,t){let r=await jG(e);if(r)return r;if(!zG()[e][t])return WG.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}o(kae,"checkSchemaTableExists")});function ow(e){let t=e.get(iS),r=t?(0,Sd.unpack)(t):null;r||(r={remoteNameToId:{}});let n=Ze(),s=!1;r.nodeName=Ze();let i=r.remoteNameToId;if(i[n]!==0){let a=0,c;for(let l in i){let u=i[l];u===0?c=l:u>a&&(a=u)}if(c){a++,i[c]=a;let l=[Symbol.for("seq"),a];e.rootStore.dbisDb.transactionSync(()=>{e.rootStore.dbisDb.get(l)||e.rootStore.dbisDb.putSync(l,{seqId:Ch(e)??1,nodes:[]})})}i[n]=0,e.putSync(iS,(0,Sd.pack)(r))}return r}function Oh(e){return ow(e).remoteNameToId}function ZG(e,t){let r=ow(t),n=r.remoteNameToId,s=new Map,i=!1;for(let a in e){let c=e[a],l=n[a];if(l==null){let u=0;for(let d in n){let f=n[d];f>u&&(u=f)}l=u+1,n[a]=l,i=!0}s.set(c,l)}return i&&t.putSync(iS,(0,Sd.pack)(r)),s}function oS(e,t){let r=ow(t),n=r.remoteNameToId,s=n[e];if(s==null){let i=0;for(let a in n){let c=n[a];c>i&&(i=c)}s=i+1,n[e]=s,t.putSync(iS,(0,Sd.pack)(r))}return XG.trace?.("The remote node name map",e,n,s),s}var XG,Sd,iS,aw=ue(()=>{XG=w(ei());is();Sd=require("msgpackr"),iS=Symbol.for("remote-ids");o(ow,"getIdMappingRecord");o(Oh,"exportIdMapping");o(ZG,"remoteToLocalNodeId");o(oS,"getIdOfRemoteNode")});var cw={};Oe(cw,{commitsAwaitingReplication:()=>Td,getHDBNodeTable:()=>Kt,getReplicationSharedStatus:()=>Rd,iterateRoutes:()=>Lh,shouldReplicateToNode:()=>Ph,subscribeToNodeUpdates:()=>yd});function Kt(){return eq||(eq=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 Rd(e,t,r,n){return new Float64Array(e.getUserSharedBuffer(["replicated",t,r],new ArrayBuffer(48),n&&{callback:n}))}function yd(e){Kt().subscribe({}).then(async t=>{for await(let r of t){let n=r?.value?.name;sq.debug?.("adding node",n,"on node",Ze()," on process",process.pid),server.nodes=server.nodes.filter(i=>i.name!==n),r.type==="put"&&n!==Ze()&&(r.value?server.nodes.push(r.value):console.error("Invalid node update event",r));let s=new Map;for await(let i of Kt().search({}))if(i.shard!=null){let a=s.get(i.shard);a||s.set(i.shard,a=[]),a.push(i)}server.shards=s,(r.type==="put"||r.type==="delete")&&e(r.value,r.id)}})}function Ph(e,t){let r=Ya.default.get(U.REPLICATION_DATABASES);return(e.replicates===!0||e.replicates?.sends)&&databases[t]&&(r==="*"||r?.find?.(n=>n.name===t&&(!n.sharded||e.shard===Ya.default.get(U.REPLICATION_SHARD))))&&Kt().primaryStore.get(Ze())?.replicates||e.subscriptions?.some(n=>(n.database||n.schema)===t&&n.subscribe)}function Gae(){yd(e=>{Wa({},(t,r)=>{let n=e.name,s=tq.get(n);if(s||tq.set(n,s=new Map),s.has(r))return;let i;for(let a in t)if(i=t[a].auditStore,i)break;if(i){let a=Rd(i,r,n,()=>{let c=a[0],l=a.lastTime;for(let{txnTime:u,onConfirm:d}of Td.get(r)||[])u>l&&u<=c&&d();a.lastTime=c});a.lastTime=0,s.set(r,a)}})})}function*Lh(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=Ya.default.get(U.REPLICATION_SECUREPORT)??(!Ya.default.get(U.REPLICATION_PORT)&&Ya.default.get(U.OPERATIONSAPI_NETWORK_SECUREPORT)),i;(i=n.match(/:(\d+)$/)?.[1])?n=n.slice(0,-i[0].length-1):t.port?i=t.port:i=s||Ya.default.get(U.REPLICATION_PORT)||Ya.default.get(U.OPERATIONSAPI_NETWORK_PORT);let a=i?.lastIndexOf?.(":");a>0&&(i=+i.slice(a+1).replace(/[\[\]]/g,"")),r=(s?"wss://":"ws://")+n+":"+i}if(!r){rq.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 rq,nq,Ya,sq,eq,tq,Td,Nl=ue(()=>{De();is();rm();rq=require("worker_threads"),nq=w(ge()),Ya=w(oe());k();sq=w(ei());server.nodes=[];o(Kt,"getHDBNodeTable");o(Rd,"getReplicationSharedStatus");o(yd,"subscribeToNodeUpdates");o(Ph,"shouldReplicateToNode");tq=new Map;fv((e,t,r)=>{if(r>server.nodes.length)throw new nq.ClientError(`Cannot confirm replication to more nodes (${r}) than are in the network (${server.nodes.length})`);Td||(Td=new Map,Gae());let n=Td.get(e);return n||(n=[],Td.set(e,n)),new Promise(s=>{let i=0;n.push({txnTime:t,onConfirm:o(()=>{++i===r&&s()},"onConfirm")})})});o(Gae,"startSubscriptionToReplications");o(Lh,"iterateRoutes")});var aq={};Oe(aq,{connectedToNode:()=>wl,disconnectedFromNode:()=>bd,ensureNode:()=>xo,requestClusterStatus:()=>oq,startOnMainThread:()=>dw});async function dw(e){let t=0,r=st();for(let i of Object.getOwnPropertyNames(r)){let a=r[i];for(let c in a){let l=a[c];if(l.auditStore){aS.set(i,Ch(l.auditStore));break}}}Zi.whenThreadsStarted.then(async()=>{let i=[];for await(let l of r.system.hdb_nodes?.search([])||[])i.push(l);let a=Ze();function c(){let l=Kt().primaryStore.get(a);if(l!==null){let u=e.url??za();if(l===void 0||l.url!==u||l.shard!==e.shard)return xo(a,{name:a,url:u,shard:e.shard,replicates:!0})}}o(c,"ensureThisNode"),Kt().primaryStore.get(a)&&c();for(let l of Lh(e))try{let u=!l.subscriptions;if(u&&await c(),u&&l.replicates==null&&(l.replicates=!0),i.find(d=>d.url===l.url))continue;s(l)}catch(u){console.error(u)}yd(s)});let n;function s(i,a=i?.name){let c=Ze()&&a===Ze()||za()&&i?.url===za();if(c){let f=!!i?.replicates;if(n!==void 0&&n!==f)for(let m of Kt().search([]))m.replicates&&m.name!==a&&s(m,m.name);n=f}if(at.trace("Setting up node replication for",i),!i){for(let[f,m]of Xi){let h;for(let[p,{worker:_,nodes:g}]of m){let y=g[0];if(y&&y.name==a){h=!0;for(let[T,{worker:R}]of m)m.delete(T),at.warn("Node was deleted, unsubscribing from node",a,T,f),R?.postMessage({type:"unsubscribe-from-node",node:a,database:T,url:f});break}}if(h){Xi.get(f).iterator.remove(),Xi.delete(f);return}}return}if(c)return;if(!i.url){at.info(`Node ${i.name} is missing url`);return}let l=Xi.get(i.url);if(l&&l.iterator.remove(),!(i.replicates===!0||i.replicates?.sends)&&!i.subscriptions?.length&&!l)return;if(at.info(`Added node ${i.name} at ${i.url} for process ${Ze()}`),i.replicates&&i.subscriptions&&(i={...i,subscriptions:null}),i.name){for(let[f,m]of Ad)if(i.url===m.url){Ad.delete(f);break}Ad.set(i.name,i)}let u=st();if(l||(l=new Map,Xi.set(i.url,l)),l.iterator=Wa(e,(f,m,h)=>{h?d(m,!0):d(m,!1)}),i.subscriptions)for(let f of i.subscriptions){let m=f.database||f.schema;u[m]||(at.warn(`Database ${m} not found for node ${i.name}, making a subscription anyway`),d(m,!1))}function d(f,m){at.trace("Setting up replication for database",f,"on node",i.name);let h=l.get(f),p,_=[{replicateByDefault:m,...i}];aS.has(f)&&(_.push({replicateByDefault:m,name:Ze(),startTime:aS.get(f),endTime:Date.now(),replicates:!0}),aS.delete(f));let g=Ph(i,f),y=Zi.workers.filter(T=>T.name==="http");if(h?(p=h.worker,h.nodes=_):g&&(t=t%y.length,p=y[t++],l.set(f,{worker:p,nodes:_,url:i.url}),p?.on("exit",()=>{l.get(f)?.worker===p&&(l.delete(f),d(f,m))})),g)setTimeout(()=>{let T={type:"subscribe-to-node",database:f,nodes:_};p?p.postMessage(T):Dh(T)},qae);else{at.info("Node no longer should be used, unsubscribing from node",{replicates:i.replicates,databaseName:f,node:i,subscriptions:i.subscriptions,hasDatabase:!!u[f],thisReplicates:Kt().primaryStore.get(Ze())?.replicates}),Kt().primaryStore.get(Ze())?.replicates||(n=!1,at.info("Disabling replication, this node name",Ze(),Kt().primaryStore.get(Ze()),f));let T={type:"unsubscribe-from-node",database:f,url:i.url,name:i.name};p?p.postMessage(T):lS(T)}}o(d,"onDatabase")}o(s,"onNodeUpdate"),bd=o(function(i){try{at.info("Disconnected from node",i.name,i.url,"finished",!!i.finished);let a=Array.from(Ad.keys()),c=a.sort(),l=c.indexOf(i.name||hi(i.url));if(l===-1){at.warn("Disconnected node not found in node map",i.name,a);return}let u=Xi.get(i.url),d=u?.get(i.database);if(!d){at.warn("Disconnected node not found in replication map",i.database,u);return}if(d.connected=!1,i.finished||!uw.default.get(U.REPLICATION_FAILOVER))return;let f=d.nodes[0];if(!(f.replicates===!0||f.replicates?.sends||f.subscriptions?.length))return;let m=f.shard,h=(l+1)%c.length;for(;l!==h;){let p=c[h],_=Ad.get(p);u=Xi.get(_.url);let g=u?.get(i.database);if(!g||g.connected===!1||g.nodes[0].shard!==m){h=(h+1)%c.length;continue}let{worker:y,nodes:T}=g,R=!1;for(let N of d.nodes){if(T.some(O=>O.name===N.name)){at.info(`Disconnected node is already failing over to ${p} for ${i.database}`);continue}N.endTime<Date.now()||(T.push(N),R=!0)}if(d.nodes=[d.nodes[0]],!R){at.info(`Disconnected node ${i.name} has no nodes to fail over to ${p}`);return}at.info(`Failing over ${i.database} from ${i.name} to ${p}`),y?y.postMessage({type:"subscribe-to-node",database:i.database,nodes:T}):Dh({database:i.database,nodes:T});return}at.warn("Unable to find any other node to fail over to",i.name,i.url)}catch(a){at.error("Error failing over node",a)}},"disconnectedFromNode"),wl=o(function(i){let a=Xi.get(i.url),c=a?.get(i.database);if(!c){at.warn("Connected node not found in replication map, this may be because the node is being removed",i.database,a);return}c.connected=!0,c.latency=i.latency;let l=c.nodes[0];if(!l){at.warn("Newly connected node has no node subscriptions",i.database,c);return}if(!l.name){at.debug("Connected node is not named yet",i.database,c);return}c.nodes=[l];let u=!1;for(let d of Xi.values()){let f=d.get(i.database);if(!f||f==c)continue;let{worker:m,nodes:h,connected:p}=f;if(h)if(p===!1&&h[0].shard===l.shard)u=!0,c.nodes.push(h[0]);else{let _=h.filter(g=>g&&g.name!==l.name);_.length<h.length&&(f.nodes=_,m.postMessage({type:"subscribe-to-node",database:i.database,nodes:h}))}}u&&c.worker&&c.worker.postMessage({type:"subscribe-to-node",database:i.database,nodes:c.nodes})},"connectedToNode"),(0,Zi.onMessageByType)("disconnected-from-node",bd),(0,Zi.onMessageByType)("connected-to-node",wl),(0,Zi.onMessageByType)("request-cluster-status",oq)}function oq(e,t){let r=[];for(let[n,s]of Ad)try{let i=Xi.get(s.url);at.info("Getting cluster status for",n,s.url,"has dbs",i?.size);let a=[];if(i){for(let[l,{worker:u,connected:d,nodes:f,latency:m}]of i)a.push({database:l,connected:d,latency:m,threadId:u?.threadId,nodes:f.filter(h=>!(h.endTime<Date.now())).map(h=>h.name)});let c=(0,lw.cloneDeep)(s);c.database_sockets=a,delete c.ca,delete c.node_name,delete c.__updatedtime__,delete c.__createdtime__,r.push(c)}}catch(i){at.warn("Error getting cluster status for",s?.url,i)}return t?.postMessage({type:"cluster-status",connections:r}),{connections:r}}async function xo(e,t){let r=Kt();e=e??hi(t.url),t.name=e;try{if(t.ca){let s=new iq.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){at.error("Error parsing replication CA info for hdb_nodes table",s.message)}let n=r.primaryStore.get(e);if(at.debug(`Ensuring node ${e} at ${t.url}, existing record:`,n,"new record:",t),!n)await r.patch(t);else{t.replicates&&!uw.default.get(U.CLUSTERING_ENABLED)&&(t.subscriptions=null);for(let s in t)if(n[s]!==t[s]&&s==="subscriptions"&&t[s]&&n[s]){let i=[],a=(0,lw.cloneDeep)(n[s]);for(let c of t[s]){let l=!1;for(let u of a)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=[...a,...i];break}if(Array.isArray(t.revoked_certificates)){let s=n.revoked_certificates||[];t.revoked_certificates=[...new Set([...s,...t.revoked_certificates])]}at.info(`Updating node ${e} at ${t.url}`),await r.patch(t)}}var Zi,cS,at,lw,uw,iq,qae,Xi,bd,wl,Ad,aS,Mh=ue(()=>{De();Zi=w(nt());is();cS=require("worker_threads");Nl();at=w(Q()),lw=require("lodash"),uw=w(oe());k();iq=require("crypto"),qae=200,Xi=new Map,Ad=new Map,aS=new Map;o(dw,"startOnMainThread");o(oq,"requestClusterStatus");cS.parentPort&&(bd=o(e=>{cS.parentPort.postMessage({type:"disconnected-from-node",...e})},"disconnectedFromNode"),wl=o(e=>{cS.parentPort.postMessage({type:"connected-to-node",...e})},"connectedToNode"),(0,Zi.onMessageByType)("subscribe-to-node",e=>{Dh(e)}),(0,Zi.onMessageByType)("unsubscribe-from-node",e=>{lS(e)}));o(xo,"ensureNode")});var as=M(Yt=>{"use strict";var mr=require("path"),{watch:$ae}=require("chokidar"),xn=require("fs-extra"),Id=require("node-forge"),mq=require("net"),{generateKeyPair:fw,X509Certificate:Bo,createPrivateKey:hq}=require("crypto"),Vae=require("util");fw=Vae.promisify(fw);var wt=Id.pki,pi=require("joi"),{v4:pq}=require("uuid"),{validateBySchema:Ew}=ut(),{forComponent:Kae}=Q(),os=oe(),Ls=(k(),v(W)),{CONFIG_PARAMS:Cl}=Ls,Ei=GI(),{ClientError:Qa}=ge(),dS=require("node:tls"),{relative:Eq,join:Yae}=require("node:path"),{CERT_PREFERENCE_APP:AMe,CERTIFICATE_VALUES:cq}=Ei,Wae=Uc(),mw=bt(),{table:zae,getDatabases:jae,databases:uS}=(De(),v(mt)),{getJWTRSAKeys:lq}=(_d(),v(wh)),ht=Kae("tls");Yt.generateKeys=Sw;Yt.updateConfigCert=bq;Yt.createCsr=rce;Yt.signCertificate=nce;Yt.setCertTable=Nd;Yt.loadCertificates=Rq;Yt.reviewSelfSignedCert=Rw;Yt.createTLSSelector=Nq;Yt.listCertificates=Oq;Yt.addCertificate=lce;Yt.removeCertificate=dce;Yt.createNatsCerts=oce;Yt.generateCertsKeys=ice;Yt.getReplicationCert=Uh;Yt.getReplicationCertAuth=tce;Yt.renewSelfSigned=ace;Yt.hostnamesFromCert=Aw;Yt.getKey=fce;Yt.getHostnamesFromCertificate=mce;Yt.getPrimaryHostName=yw;var{urlToNodeName:_q,getThisNodeUrl:Qae,getThisNodeName:mS,clearThisNodeName:Jae}=(is(),v(Fo)),{readFileSync:Xae,statSync:gq}=require("node:fs"),bMe=oe(),{getTicketKeys:Zae,onMessageFromWorkers:ece}=nt(),ja=Q(),{isMainThread:Sq}=require("worker_threads"),{TLSSocket:Tq,createSecureContext:IMe}=require("node:tls"),_w=3650,vh=["127.0.0.1","localhost","::1"],gw=[{name:"countryName",value:"USA"},{name:"stateOrProvinceName",value:"Colorado"},{name:"localityName",value:"Denver"},{name:"organizationName",value:"HarperDB, Inc."}];ece(async e=>{e.type===Ls.ITC_EVENT_TYPES.RESTART&&(os.initSync(!0),await Rw())});var Qr;function Xa(){return Qr||(Qr=jae().system.hdb_certificate,Qr||(Qr=zae({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__"}]}))),Qr}o(Xa,"getCertTable");async function Uh(){let e=Nq("operations-api"),t={secureContexts:null,setSecureContext:o(s=>{},"setSecureContext")};await e.initialize(t);let r=t.secureContexts.get(mS());if(!r)return;let n=new Bo(r.options.cert);return r.cert_parsed=n,r.issuer=n.issuer,r}o(Uh,"getReplicationCert");async function tce(){Xa();let e=(await Uh()).options.cert,r=new Bo(e).issuer.match(/CN=(.*)/)?.[1];return Qr.get(r)}o(tce,"getReplicationCertAuth");var uq,Ja=new Map;function Rq(){if(uq)return;uq=!0;let e=[{configKey:Cl.TLS},{configKey:Cl.OPERATIONSAPI_TLS}];Xa();let t=mr.dirname(mw.getConfigFilePath()),r;for(let{configKey:n}of e){let s=mw.getConfigFromFile(n);if(s){Array.isArray(s)||(s=[s]);for(let i of s){let a=i.privateKey,c=a&&Eq(Yae(t,"keys"),a);c&&dq(a,l=>{Ja.set(c,l)},"private key");for(let l of[!1,!0]){let u=i[l?"certificateAuthority":"certificate"];if(u&&Sq){let d;dq(u,f=>{if(cq.cert===f)return;let m=i.hostname??i.hostnames??i.host??i.hosts;m&&!Array.isArray(m)&&(m=[m]);let h=Iq(u),p=new Bo(h),_;try{_=yw(p)}catch(R){ht.error("error extracting host name from certificate",R);return}if(_==null){ht.error("No host name found on certificate");return}if(p.checkIssued(new Bo(cq.cert)))return;let g=Qr.primaryStore.get(_),y=gq(u).mtimeMs,T=!g||g.is_self_signed?1:g.file_timestamp??g.__updatedtime__;if(g&&y<=T){y<T&&ht.info(`Certificate ${_} at ${u} is older (${new Date(y)}) than the certificate in the database (${T>1?new Date(T):"only self signed certificate available"})`);return}r=Qr.put({name:_,uses:["https",...n.includes("operations")?["operations"]:[]],ciphers:i.ciphers,certificate:h,private_key_name:c,is_authority:l,hostnames:m,fileTimestamp:y,details:{issuer:p.issuer.replace(/\n/g," "),subject:p.subject?.replace(/\n/g," "),subject_alt_name:p.subjectAltName,serial_number:p.serialNumber,valid_from:p.validFrom,valid_to:p.validTo}})},l?"certificate authority":"certificate")}}}}}return r}o(Rq,"loadCertificates");function dq(e,t,r){let n,s=o((i,a)=>{try{let c=a.mtimeMs;c&&c!==n&&(n&&Sq&&ht.warn(`Reloading ${r}:`,i),n=c,t(Iq(i)))}catch(c){ht.error(`Error loading ${r}:`,i,c)}},"loadFile");xn.existsSync(e)?s(e,gq(e)):ht.error(`${r} file not found:`,e),$ae(e,{persistent:!1}).on("change",s)}o(dq,"loadAndWatch");function hw(){let e=Qae();if(e==null){let t=vh[0];return ht.info("replication url is missing from harperdb-config.yaml, using default host"+t),t}return _q(e)}o(hw,"getHost");function fS(){let e=mS();if(e==null){let t=vh[0];return ht.info("replication url is missing from harperdb-config.yaml, using default host"+t),t}return e}o(fS,"getCommonName");async function rce(){let e=await Uh(),t=wt.certificateFromPem(e.options.cert),r=wt.privateKeyFromPem(e.options.key);ht.info("Creating CSR with cert named:",e.name);let n=wt.createCertificationRequest();n.publicKey=t.publicKey;let s=[{name:"commonName",value:fS()},...gw];ht.info("Creating CSR with subject",s),n.setSubject(s);let i=[{name:"unstructuredName",value:"HarperDB, Inc."},{name:"extensionRequest",extensions:yq()}];return ht.info("Creating CSR with attributes",i),n.setAttributes(i),n.sign(r),Id.pki.certificationRequestToPem(n)}o(rce,"createCsr");function yq(){let e=vh.includes(fS())?vh:[...vh,fS()];return e.includes(hw())||e.push(hw()),[{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=>mq.isIP(t)?{type:7,ip:t}:{type:2,value:t})}]}o(yq,"certExtensions");async function nce(e){let t={},r=mr.join(os.getHdbBasePath(),Ls.LICENSE_KEY_DIR_NAME);if(e.csr){let n,s;Xa();for await(let d of Qr.search([]))if(d.is_authority&&!d.details.issuer.includes("HarperDB-Certificate-Authority")){if(Ja.has(d.private_key_name)){n=Ja.get(d.private_key_name),s=d;break}else if(d.private_key_name&&await xn.exists(mr.join(r,d.private_key_name))){n=xn.readFile(mr.join(r,d.private_key_name)),s=d;break}}if(!n){let d=await pw();s=d.ca,n=d.private_key}n=wt.privateKeyFromPem(n),t.signingCA=s.certificate;let i=wt.certificateFromPem(s.certificate);ht.info("Signing CSR with cert named",s.name);let a=wt.certificationRequestFromPem(e.csr);try{a.verify()}catch(d){return ht.error(d),new Error("Error verifying CSR: "+d.message)}let c=Id.pki.createCertificate();c.serialNumber="0"+Math.random().toString().slice(2,9),c.validity.notBefore=new Date;let l=new Date;c.validity.notAfter=l,c.validity.notAfter.setDate(l.getDate()+_w),ht.info("sign cert setting validity:",c.validity),ht.info("sign cert setting subject from CSR:",a.subject.attributes),c.setSubject(a.subject.attributes),ht.info("sign cert setting issuer:",i.subject.attributes),c.setIssuer(i.subject.attributes);let u=a.getAttribute({name:"extensionRequest"}).extensions;ht.info("sign cert adding extensions from CSR:",u),c.setExtensions(u),c.publicKey=a.publicKey,c.sign(n,Id.md.sha256.create()),t.certificate=wt.certificateToPem(c)}else ht.info("Sign cert did not receive a CSR from:",e.url,"only the CA will be returned");return t}o(nce,"signCertificate");async function sce(e,t){await Nd({name:mS(),uses:["https","wss"],certificate:e,private_key_name:"privateKey.pem",is_authority:!1,is_self_signed:!0}),await Nd({name:t.subject.getField("CN").value,uses:["https","wss"],certificate:wt.certificateToPem(t),private_key_name:"privateKey.pem",is_authority:!0,is_self_signed:!0})}o(sce,"createCertificateTable");async function Nd(e){let t=new Bo(e.certificate);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},Xa(),await Qr.patch(e)}o(Nd,"setCertTable");async function Sw(){let e=await fw("rsa",{modulusLength:4096,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKey:wt.publicKeyFromPem(e.publicKey),privateKey:wt.privateKeyFromPem(e.privateKey)}}o(Sw,"generateKeys");async function Tw(e,t,r){let n=wt.createCertificate();if(!t){let a=await Uh();t=wt.certificateFromPem(a.options.cert).publicKey}n.publicKey=t,n.serialNumber="0"+Math.random().toString().slice(2,9),n.validity.notBefore=new Date;let s=new Date;n.validity.notAfter=s,n.validity.notAfter.setDate(s.getDate()+_w);let i=[{name:"commonName",value:fS()},...gw];return n.setSubject(i),n.setIssuer(r.subject.attributes),n.setExtensions(yq()),n.sign(e,Id.md.sha256.create()),wt.certificateToPem(n)}o(Tw,"generateCertificates");async function pw(){let e=await Oq(),t;for(let r of e){if(!r.is_authority)continue;let n=await wq(r.private_key_name);if(r.private_key_name&&n&&new Bo(r.certificate).checkPrivateKey(hq(n))){ht.trace(`CA named: ${r.name} found with matching private key`),t={ca:r,private_key:n};break}}if(t)return t;ht.trace("No CA found with matching private key")}o(pw,"getCertAuthority");async function Aq(e,t,r=!0){let n=wt.createCertificate();n.publicKey=t,n.serialNumber="0"+Math.random().toString().slice(2,9),n.validity.notBefore=new Date;let s=new Date;n.validity.notAfter=s,n.validity.notAfter.setDate(s.getDate()+_w);let i=[{name:"commonName",value:`HarperDB-Certificate-Authority-${os.get(Cl.REPLICATION_HOSTNAME)??_q(os.get(Cl.REPLICATION_URL))??pq().split("-")[0]}`},...gw];n.setSubject(i),n.setIssuer(i),n.setExtensions([{name:"basicConstraints",cA:!0,critical:!0},{name:"keyUsage",keyCertSign:!0,critical:!0}]),n.sign(e,Id.md.sha256.create());let a=mr.join(os.getHdbBasePath(),Ls.LICENSE_KEY_DIR_NAME),c=mr.join(a,Ei.PRIVATEKEY_PEM_NAME);return r&&await xn.writeFile(c,wt.privateKeyToPem(e)),n}o(Aq,"generateCertAuthority");async function ice(){let{privateKey:e,publicKey:t}=await Sw(),r=await Aq(e,t),n=await Tw(e,t,r);await sce(n,r),bq()}o(ice,"generateCertsKeys");async function oce(){let e=await Tw(wt.privateKeyFromPem(Ei.CERTIFICATE_VALUES.key),void 0,wt.certificateFromPem(Ei.CERTIFICATE_VALUES.cert)),t=mr.join(os.getHdbBasePath(),Ls.LICENSE_KEY_DIR_NAME),r=mr.join(t,Ei.NATS_CERTIFICATE_PEM_NAME);await xn.exists(r)||await xn.writeFile(r,e);let n=mr.join(t,Ei.NATS_CA_PEM_NAME);await xn.exists(n)||await xn.writeFile(n,Ei.CERTIFICATE_VALUES.cert)}o(oce,"createNatsCerts");async function ace(){Xa();for await(let e of Qr.search([{attribute:"is_self_signed",value:!0}]))await Qr.delete(e.name);await Rw()}o(ace,"renewSelfSigned");async function Rw(){Jae(),await Rq(),Xa();let e=await pw();if(!e){ht.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=o(u=>{try{return{key:wt.privateKeyFromPem(xn.readFileSync(u)),keyPath:u}}catch(d){return ht.warn(`Failed to parse private key from ${u}:`,d.message),{key:null,keyPath:u}}},"tryToParseKey"),n=os.get(Cl.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=os.get(Cl.TLS_PRIVATEKEY),d=r(u);s=d.key,i=d.keyPath}let a=mr.join(os.getHdbBasePath(),Ls.LICENSE_KEY_DIR_NAME),c=Eq(a,i);s||(ht.warn("Unable to parse the TLS key",i,"A new key will be generated and used to create Certificate Authority"),{privateKey:s}=await Sw(),xn.existsSync(mr.join(a,Ei.PRIVATEKEY_PEM_NAME))&&(c=`privateKey${pq().split("-")[0]}.pem`),await xn.writeFile(mr.join(a,c),wt.privateKeyToPem(s)));let l=await Aq(s,wt.setRsaPublicKey(s.n,s.e),!1);await Nd({name:l.subject.getField("CN").value,uses:["https"],certificate:wt.certificateToPem(l),private_key_name:c,is_authority:!0,is_self_signed:!0})}if(!await Uh()){let r=mS();ht.notify(`A suitable replication certificate was not found, creating new self singed cert named: ${r}`),e=e??await pw();let n=wt.certificateFromPem(e.ca.certificate),s=n.publicKey,i=await Tw(wt.privateKeyFromPem(e.private_key),s,n);await Nd({name:r,uses:["https","operations","wss"],certificate:i,is_authority:!1,private_key_name:e.ca.private_key_name,is_self_signed:!0})}}o(Rw,"reviewSelfSignedCert");function bq(){let e=Wae(Object.keys(Ls.CONFIG_PARAM_MAP),!0),t=mr.join(os.getHdbBasePath(),Ls.LICENSE_KEY_DIR_NAME),r=mr.join(t,Ei.PRIVATEKEY_PEM_NAME),n=mr.join(t,Ei.NATS_CERTIFICATE_PEM_NAME),s=mr.join(t,Ei.NATS_CA_PEM_NAME),i=Ls.CONFIG_PARAMS,a={[i.TLS_PRIVATEKEY]:e[i.TLS_PRIVATEKEY.toLowerCase()]?e[i.TLS_PRIVATEKEY.toLowerCase()]:r};e[i.TLS_CERTIFICATE.toLowerCase()]&&(a[i.TLS_CERTIFICATE]=e[i.TLS_CERTIFICATE.toLowerCase()]),e[i.TLS_CERTIFICATEAUTHORITY.toLowerCase()]&&(a[i.TLS_CERTIFICATEAUTHORITY]=e[i.TLS_CERTIFICATEAUTHORITY.toLowerCase()]),e[i.OPERATIONSAPI_TLS_CERTIFICATE.toLowerCase()]&&(a[i.OPERATIONSAPI_TLS_CERTIFICATE]=e[i.OPERATIONSAPI_TLS_CERTIFICATE.toLowerCase()]),e[i.OPERATIONSAPI_TLS_PRIVATEKEY.toLowerCase()]&&(a[i.OPERATIONSAPI_TLS_PRIVATEKEY]=e[i.OPERATIONSAPI_TLS_PRIVATEKEY.toLowerCase()]),e[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY.toLowerCase()]&&(a[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY]=e[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY.toLowerCase()]),(e[i.CLUSTERING_ENABLED.toLowerCase()]||e.clustering)&&(a[i.CLUSTERING_TLS_CERTIFICATE]=e[i.CLUSTERING_TLS_CERTIFICATE.toLowerCase()]??n,a[i.CLUSTERING_TLS_CERT_AUTH]=e[i.CLUSTERING_TLS_CERT_AUTH.toLowerCase()]??s,a[i.CLUSTERING_TLS_PRIVATEKEY]=e[i.CLUSTERING_TLS_PRIVATEKEY.toLowerCase()]??r),mw.updateConfigValue(void 0,void 0,a,!1,!0)}o(bq,"updateConfigCert");function Iq(e){return e.startsWith("-----BEGIN")?e:Xae(e,"utf8")}o(Iq,"readPEM");var fq=dS.createSecureContext;dS.createSecureContext=function(e){if(!e.cert||!e.key)return fq(e);let t={...e};delete t.key,delete t.cert;let r=fq(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};var cce=Tq.prototype._init;Tq.prototype._init=function(e,t){cce.call(this,e,t);let r=this;this._handle.oncertcb=function(n){let s=n.servername;r._SNICallback(s,(i,a)=>{this.sni_context=a?.context||a,this.certCbDone()})}};var Ol=new Map;function Nq(e,t){let r=new Map,n,s=!1;return i.initialize=a=>i.ready?i.ready:(a&&(a.secureContexts=r,a.secureContextsListeners=[]),i.ready=new Promise((c,l)=>{async function u(){try{r.clear(),Ol.clear();let d=0;if(uS===void 0){c();return}for await(let f of uS.system.hdb_certificate.search([])){let m=f.certificate,h=new Bo(m);f.is_authority&&(h.asString=m,Ol.set(h.subject,m))}for await(let f of uS.system.hdb_certificate.search([]))try{if(f.is_authority)continue;let m=e==="operations-api",h=f.is_self_signed?1:2;m&&f.uses?.includes?.("operations")&&(h+=1);let p=await wq(f.private_key_name),_=f.certificate,g=new Bo(_);if(Ol.has(g.issuer)&&(_+=`
16
16
  `+Ol.get(g.issuer)),!p||!_)throw new Error("Missing private key or certificate for secure server");let y={ciphers:f.ciphers,ticketKeys:Zae(),availableCAs:Ol,ca:t&&Array.from(Ol.values()),cert:_,key:p,key_file:f.private_key_name,is_self_signed:f.is_self_signed};a&&(y.sessionIdContext=a.sessionIdContext);let T=dS.createSecureContext(y);T.name=f.name,T.options=y,T.quality=h,T.certificateAuthorities=Array.from(Ol),T.certStart=_.toString().slice(0,100);let R=f.hostnames??Aw(g);Array.isArray(R)||(R=[R]);let N;for(let O of R)if(O){O[0]==="*"&&(s=!0,O=O.slice(1)),O===hw()&&(h+=2),mq.isIP(O)&&(N=!0);let F=r.get(O)?.quality??0;h>F&&r.set(O,T)}else ja.error("No hostname found for certificate at",dS.certificate);ja.trace("Adding TLS",T.name,"for",a.ports||"client","cert named",f.name,"hostnames",R,"quality",h,"best quality",d),h>d&&(i.defaultContext=n=T,d=h,a&&(a.defaultContext=T))}catch(m){ja.error("Error applying TLS for",f.name,m)}a?.secureContextsListeners.forEach(f=>f()),c(n)}catch(d){l(d)}}o(u,"updateTLS"),uS?.system.hdb_certificate.subscribe({listener:o(()=>setTimeout(()=>u(),1500).unref(),"listener"),omitCurrent:!0}),u()})),i;function i(a,c){ja.info("TLS requested for",a||"(no SNI)");let l=a;for(;;){let d=r.get(l);if(d)return ja.debug("Found certificate for",a,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}a?ja.debug("No certificate found to match",a,"using the default certificate"):ja.debug("No SNI, using the default certificate",n?.name);let u=n;u?u.updatedContext&&(u=u.updatedContext):ja.info("No default certificate found"),c(null,u)}o(i,"SNICallback")}o(Nq,"createTLSSelector");async function wq(e){let t=Ja.get(e);return!t&&e?await xn.readFile(mr.join(os.get(Cl.ROOTPATH),Ls.LICENSE_KEY_DIR_NAME,e),"utf8"):t}o(wq,"getPrivateKeyByName");async function Oq(){Xa();let e=[];for await(let t of Qr.search([]))e.push(t);return e}o(Oq,"listCertificates");async function lce(e){let t=Ew(e,pi.object({name:pi.string().required(),certificate:pi.string().required(),is_authority:pi.boolean().required(),private_key:pi.string(),hosts:pi.array(),uses:pi.array()}));if(t)throw new Qa(t.message);let{name:r,certificate:n,private_key:s,is_authority:i}=e,a=new Bo(n),c=!1,l=!1,u;for(let[h,p]of Ja)!s&&!c&&a.checkPrivateKey(hq(p))&&(c=!0,u=h),s&&s===p&&(l=!0,u=h);if(!i&&!s&&!c)throw new Qa("A suitable private key was not found for this certificate");let d;if(!r){try{d=yw(a)}catch(h){ht.error(h)}if(d==null)throw new Qa("Error extracting certificate host name, please provide a name parameter")}let f=uce(r??d);s&&!c&&!l&&(await xn.writeFile(mr.join(os.getHdbBasePath(),Ls.LICENSE_KEY_DIR_NAME,f+".pem"),s),Ja.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 Nd(m),"Successfully added certificate: "+f}o(lce,"addCertificate");function uce(e){return e.replace(/[^a-z0-9\.]/gi,"-")}o(uce,"sanitizeName");async function dce(e){let t=Ew(e,pi.object({name:pi.string().required()}));if(t)throw new Qa(t.message);let{name:r}=e;Xa();let n=await Qr.get(r);if(!n)throw new Qa(r+" not found");let{private_key_name:s}=n;if(s){let i=Array.from(await Qr.search([{attribute:"private_key_name",value:s}]));i.length===1&&i[0].name===r&&(ht.info("Removing private key named",s),await xn.remove(mr.join(os.getHdbBasePath(),Ls.LICENSE_KEY_DIR_NAME,s)))}return await Qr.delete(r),"Successfully removed "+r}o(dce,"removeCertificate");function yw(e){let t=e.subject?.match(/CN=(.*)/)?.[1];return t||Aw(e)[0]}o(yw,"getPrimaryHostName");function Aw(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=certObj.subject?.match(/CN=(.*)/)?.[1];return t?[t]:[]}o(Aw,"hostnamesFromCert");async function fce(e){if(e.bypass_auth!==!0)throw new Qa("Unauthorized","401");let t=Ew(e,pi.object({name:pi.string().required()}));if(t)throw new Qa(t.message);let{name:r}=e;if(r===".jwtPrivate")return(await lq()).privateKey;if(r===".jwtPublic")return(await lq()).publicKey;if(Ja.get(r))return Ja.get(e.name);throw new Qa("Key not found")}o(fce,"getKey");function mce(e){return[e.subject?.CN,...e.subjectaltname.split(",").filter(t=>t.trim().startsWith("DNS:")).map(t=>t.trim().substring(4))]}o(mce,"getHostnamesFromCertificate")});var Jq={};Oe(Jq,{CONFIRMATION_STATUS_POSITION:()=>zq,LATENCY_POSITION:()=>TS,NodeReplicationConnection:()=>Cd,OPERATION_REQUEST:()=>ww,RECEIVED_TIME_POSITION:()=>Cw,RECEIVED_VERSION_POSITION:()=>Ow,RECEIVING_STATUS_POSITION:()=>Pw,RECEIVING_STATUS_RECEIVING:()=>Qq,RECEIVING_STATUS_WAITING:()=>jq,SENDING_TIME_POSITION:()=>xh,createWebSocket:()=>RS,databaseSubscriptions:()=>ec,replicateOverWS:()=>Bh,tableUpdateListeners:()=>Dw});async function RS(e,t){let{authorization:r,rejectUnauthorized:n}=t||{},s=Ze(),i;if(e==null)throw new TypeError(`Invalid URL: Expected a string URL for node "${s}" but received ${e}`);if(e.includes("wss://")){if(!Iw){let l=(0,$q.createTLSSelector)("operations-api"),u={secureContexts:null};await l.initialize(u),Iw=u.secureContexts}if(i=Iw.get(s),i&&ae.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 a={};r&&(a.Authorization=r);let c={headers:a,localAddress:s?.startsWith("127.0")?s:void 0,servername:(0,Kq.isIP)(t?.serverName)?void 0:t?.serverName,noDelay:!0,highWaterMark:128*1024,rejectUnauthorized:n!==!1,secureContext:void 0};return i&&(SS?.caCount!==Ho.size&&(SS=Vq.createSecureContext({...i.options,ca:[...Ho,...i.options.availableCAs.values()]}),SS.caCount=Ho.size),c.secureContext=SS),new Gq.WebSocket(e,"harperdb-replication-v1",c)}function Bh(e,t,r){let n=t.port||t.securePort,s=Pl.pid%1e3+"-"+qq.threadId+(n?"s:"+n:"c:"+t.url?.slice(-4))+" "+Math.random().toString().slice(2,3);ae.debug?.(s,"Initializing replication connection",r);let i=0,a=Buffer.allocUnsafeSlow(1024),c=0,l=new DataView(a.buffer,0,1024),u=t.database,d=t.databaseSubscriptions||ec,f,m,h=!1,p=t.subscription;p?.then&&p.then(E=>{p=E,p.auditStore&&(f=p.auditStore)});let _=t.tables||u&&st()[u],g;if(!r){ae.error?.(s,"No authorization provided"),Ss(1008,"Unauthorized");return}let y=new Map,T=[];g=r.name,g&&t.connection&&(t.connection.nodeName=g);let R,N,O,F,Z,G,Y,q=6e4,K,ce=0,le=0,se=0,pe=kq.default.get(U.REPLICATION_BLOBTIMEOUT)??12e4,Ne=new Map,Ue=[],xe=0,Rr;if(t.url){let E=o(()=>{Z&&le===e._socket?.bytesRead&&se===e._socket?.bytesWritten?e.terminate():(Z=performance.now(),e.ping(),le=e._socket?.bytesRead,se=e._socket?.bytesWritten)},"sendPing");O=setInterval(E,Fq).unref(),E()}else Jt();e._socket?.setMaxListeners(200);function Jt(){clearTimeout(F),le=e._socket?.bytesRead,se=e._socket?.bytesWritten,F=setTimeout(()=>{le===e._socket?.bytesRead&&se===e._socket?.bytesWritten&&(ae.warn?.(`Timeout waiting for ping from ${g}, terminating connection and reconnecting`),e.terminate())},Fq*2).unref()}o(Jt,"resetPingTimer");function kt(){if(!(!g||!u))return m||(m=Rd(f,u,g)),m}o(kt,"getSharedStatus"),u&&ga(u);let Xt,Mf,Cc=[],Gt=[],vf,Uf=[],bE=[],IE=[],My=150,xf=25,Pe=0,NE=0,Bf=!1,po,Lr,yr,Ff;e.on("message",E=>{ce=performance.now();try{let S=E.dataView=new $c(E.buffer,E.byteOffset,E.byteLength);if(E[0]>127){let P=(0,et.decode)(E),[L,D,H]=P;switch(L){case Pq:{if(D){if(g){if(g!==D){ae.error?.(s,`Node name mismatch, expecting to connect to ${g}, but peer reported name as ${D}, disconnecting`),e.send((0,et.encode)([wd])),Ss(1008,"Node name mismatch");return}}else if(g=D,t.connection?.tentativeNode){let B=t.connection.tentativeNode;B.name=g,t.connection.tentativeNode=null,xo(g,B)}if(t.connection&&(t.connection.nodeName=g),ae.debug?.(s,"received node name:",g,"db:",u??P[2]),!u)try{ga(u=P[2]),u==="system"&&(Xt=Wa(t,(B,de)=>{hu(de)&&Sa(de)}),e.on("close",()=>{Xt?.remove()}))}catch(B){ae.warn?.(s,"Error setting database",B),e.send((0,et.encode)([wd])),Ss(1008,B.message);return}Dr()}break}case xq:{ae.debug?.(s,"Received table definitions for",D.map(B=>B.table));for(let B of D){let de=P[2];B.database=de;let me;hu(de)&&(de==="system"?ke[de]?.[B.table]||(me=V(B,ke[de]?.[B.table])):me=V(B,ke[de]?.[B.table]),f||(f=me?.auditStore),_||(_=st()?.[de]))}break}case wd:Ss();break;case ww:try{let B=r?.replicates||r?.subscribers||r?.name;ae.debug?.("Received operation request",D,"from",g),server.operation(D,{user:r},!B).then(de=>{Array.isArray(de)&&(de={results:de}),de.requestId=D.requestId,e.send((0,et.encode)([pS,de]))},de=>{e.send((0,et.encode)([pS,{requestId:D.requestId,error:(0,Od.errorToString)(de)}]))})}catch(B){e.send((0,et.encode)([pS,{requestId:D.requestId,error:(0,Od.errorToString)(B)}]))}break;case pS:let{resolve:C,reject:x}=y.get(D.requestId);D.error?x(new Error(D.error)):C(D),y.delete(D.requestId);break;case bw:let z=P[3];if(!_){u?ae.error?.(s,"No database found for",u):ae.error?.(s,"Database name never received"),Ss();return}let ne=_[z];ne=V({table:z,database:u,attributes:D.attributes,schemaDefined:D.schemaDefined},ne),Cc[H]={name:z,decoder:new et.Packr({useBigIntExtension:!0,randomAccessStructure:!0,freezeData:!0,typedStructs:D.typedStructs,structures:D.structures}),getEntry(B){return ne.primaryStore.getEntry(B)},rootStore:ne.primaryStore.rootStore};break;case Lq:Ff=f?ZG(D,f):new Map,vf=P[2],ae.debug?.(s,`Acknowledged subscription request, receiving messages for nodes: ${vf}`);break;case Dq:let re=H;IE[re]=D;break;case Uq:kt()[zq]=D,ae.trace?.(s,"received and broadcasting committed update",D),kt().buffer.notify();break;case vq:R=D,p.send({type:"end_txn",localTime:R,remoteNodeIds:T});break;case ES:{let B=P[1],{fileId:de,size:me,finished:Se,error:ee}=B,j=Ne.get(de);ae.debug?.("Received blob",de,"has stream",!!j,"connectedToBlob",!!j?.connectedToBlob,"length",P[2].length,"finished",Se),j||(j=new Nw.PassThrough,j.expectedSize=me,Ne.set(de,j)),j.lastChunk=Date.now();let he=P[2];it(he.byteLength,"bytes-received",`${g}.${u}`,"replication","blob");try{Se?(ee?(j.on("error",()=>{}),j.destroy(new Error("Blob error: "+ee+" for record "+(j.recordId??"unknown")+" from "+g))):j.end(he),j.connectedToBlob&&Ne.delete(de)):j.write(he)}catch(Te){ae.error?.(`Error receiving blob for ${j.recordId} from ${g} and streaming to storage`,Te),Ne.delete(de)}break}case Mq:{let B=D,de;try{let me=P[3],Se=Gt[H]||(Gt[H]=_[P[4]]);if(!Se)return ae.warn?.("Unknown table id trying to handle record request",H);let ee=Se.primaryStore.getBinaryFast(Symbol.for("structures")),j=ee?.length??0;if(j>0&&j!==NE){NE=j;let Te=(0,et.decode)(ee);e.send((0,et.encode)([bw,{typedStructs:Te.typed,structures:Te.named},H,Se.tableName]))}let he=Se.primaryStore.getBinaryFast(me);if(he){let Te=Se.primaryStore.decoder.decode(he,{valueAsBuffer:!0}),fe=lt||{};fe.version=(0,Yq.getLastVersion)(),lt&&lt[wu]&Vr&&(Te=Buffer.from(Te),fm(()=>Se.primaryStore.decoder.decode(he),We=>_a(We,me),Se.primaryStore.rootStore)),de=(0,et.encode)([hS,B,{value:Te,expiresAt:fe.expiresAt,version:fe.version,residencyId:fe.residencyId,nodeId:fe.nodeId,user:fe.user}])}else de=(0,et.encode)([hS,B])}catch(me){de=(0,et.encode)([hS,B,{error:me.message}])}e.send(de);break}case hS:{let{resolve:B,reject:de,tableId:me,key:Se}=y.get(P[1]),ee=P[2];if(ee?.error)de(new Error(ee.error));else if(ee){let j;o_(()=>{let he=Cc[me].decoder.decode(ee.value);ee.value=he,ee.key=Se,B(ee)||j&&setTimeout(()=>j.forEach(n_),6e4).unref()},f?.rootStore,he=>{let Te=Pc(he,Se);return j||(j=[]),j.push(Te),Te})}else B();y.delete(P[1]);break}case Cq:{yr=D;let B,de,me=!1;if(p){if(u!==p.databaseName&&!p.then){ae.error?.("Subscription request for wrong database",u,p.databaseName);return}}else p=d.get(u);if(ae.debug?.(s,"received subscription request for",u,"at",yr),!p){let Ee;p=new Promise(tt=>{ae.debug?.("Waiting for subscription to database "+u),Ee=tt}),p.ready=Ee,ec.set(u,p)}if(r.name)de=Kt().subscribe(r.name),de.then(async Ee=>{B=Ee;for await(let tt of B){let rt=tt.value;if(!(rt?.replicates===!0||rt?.replicates?.receives||rt?.subscriptions?.some(cr=>(cr.database||cr.schema)===u&&cr.publish!==!1))){me=!0,e.send((0,et.encode)([wd])),Ss(1008,`Unauthorized database subscription to ${u}`);return}}},Ee=>{ae.error?.(s,"Error subscribing to HDB nodes",Ee)});else if(!(r?.role?.permission?.super_user||r.replicates)){e.send((0,et.encode)([wd])),Ss(1008,`Unauthorized database subscription to ${u}`);return}if(Lr&&(ae.debug?.(s,"stopping previous subscription",u),Lr.emit("close")),yr.length===0)return;let Se=yr[0],ee=o(Ee=>{if(Ee&&(Se.replicateByDefault?!Se.tables.includes(Ee.tableName):Se.tables.includes(Ee.tableName)))return{table:Ee}},"tableToTableEntry"),j={txnTime:0},he,Te,fe=1/0,We,Et=o((Ee,tt)=>{if(Ee.type==="end_txn"){j.txnTime&&(a[i]!==66&&ae.error?.("Invalid encoding of message"),pu(9),pu(__),Dc(We=tt),dt()),i=c,j.txnTime=0;return}let rt=Ee.nodeId,cr=Ee.tableId,Mt=Te[cr];if(!Mt&&(Mt=Te[cr]=ee(p.tableById[cr]),!Mt))return ae.debug?.("Not subscribed to table",cr);let Ts=Mt.table,vt=Ts.primaryStore,Qs=vt.encoder;(Ee.extendedType&y_||!Qs.typedStructs)&&(Qs._mergeStructures(Qs.getStructures()),Qs.typedStructs&&(Qs.lastTypedStructuresLength=Qs.typedStructs.length));let Eu=he[rt];if(!(Eu&&Eu.startTime<tt&&(!Eu.endTime||Eu.endTime>tt)))return gS&&ae.trace?.(s,"skipping replication update",Ee.recordId,"to:",g,"from:",rt,"subscribed:",he),XD();gS&&ae.trace?.(s,"sending replication update",Ee.recordId,"to:",g,"from:",rt,"subscribed:",he);let vy=Ee.version;j.txnTime!==vy&&(j.txnTime&&(gS&&ae.trace?.(s,"new txn time, sending queued txn",j.txnTime),a[i]!==66&&ae.error?.("Invalid encoding of message"),dt()),j.txnTime=vy,i=c,Dc(vy));let Mc=Ee.residencyId,Uy=mu(Mc,Ts),OE;if(Uy&&!Uy.includes(g)){let Js=mu(Ee.previousResidencyId,Ts);if(Js&&!Js.includes(g)&&(Ee.type==="put"||Ee.type==="patch")||Ts.getResidencyById)return XD();let kf=Ee.recordId;ae.trace?.(s,"sending invalidation",kf,g,"from",rt);let Gf=0;Mc&&(Gf|=Vc),Ee.previousResidencyId&&(Gf|=Kc);let Fy,CE=null;for(let ZD in Ts.indices){if(!CE){if(Fy=Ee.getValue(vt,!0),!Fy)break;CE={}}CE[ZD]=Fy[ZD]}OE=Yc(Ee.version,cr,kf,null,rt,Ee.user,Ee.type==="put"||Ee.type==="patch"?"invalidate":Ee.type,Qs.encode(CE),Gf,Mc,Ee.previousResidencyId,Ee.expiresAt)}function XD(){return ae.trace?.(s,"skipping audit record",Ee.recordId),G||(G=setTimeout(()=>{G=null,(We||0)+Bq/2<fe&&(gS&&ae.trace?.(s,"sending skipped sequence update",fe),e.send((0,et.encode)([vq,fe])))},Bq).unref()),new Promise(setImmediate)}o(XD,"skipAuditRecord");let xy=Qs.typedStructs,By=Qs.structures;if((xy?.length!=Mt.typed_length||By?.length!=Mt.structure_length)&&(Mt.typed_length=xy?.length,Mt.structure_length=By.length,ae.debug?.(s,"send table struct",Mt.typed_length,Mt.structure_length),Mt.sentName||(Mt.sentName=!0),e.send((0,et.encode)([bw,{typedStructs:xy,structures:By,attributes:Ts.attributes,schemaDefined:Ts.schemaDefined},cr,Mt.table.tableName]))),Mc&&!bE[Mc]&&(e.send((0,et.encode)([Dq,Uy,Mc])),bE[Mc]=!0),OE)pu(OE.length),Lc(OE);else{let Js=Ee.encoded;Ee.extendedType&Vr&&fm(()=>Ee.getValue(vt),Gf=>_a(Gf,Ee.recordId),vt.rootStore);let kf=Js[0]===66?8:0;pu(Js.length-kf),Lc(Js,kf),ae.trace?.("wrote record",Ee.recordId,"length:",Js.length)}return e._socket.writableNeedDrain?new Promise(Js=>{ae.debug?.(`Waiting for remote node ${g} to allow more commits ${e._socket.writableNeedDrain?"due to network backlog":"due to requested flow directive"}`),e._socket.once("drain",Js)}):xe>xf?new Promise(Js=>{Rr=Js}):new Promise(setImmediate)},"sendAuditRecord"),dt=o(()=>{c-i>8?(e.send(a.subarray(i,c)),ae.debug?.(s,"Sent message, size:",c-i),it(c-i,"bytes-sent",`${g}.${u}`,"replication","egress")):ae.debug?.(s,"skipping empty transaction")},"sendQueuedData");Lr=new Lw.EventEmitter,Lr.once("close",()=>{me=!0,B?.end()});for(let{startTime:Ee}of yr)Ee<fe&&(fe=Ee);(de||Promise.resolve()).then(async()=>{p=await p,f=p.auditStore,Te=p.tableById.map(ee),he=[];for(let{name:tt,startTime:rt,endTime:cr}of yr){let Mt=oS(tt,f);ae.debug?.("subscription to",tt,"using local id",Mt,"starting",rt),he[Mt]={startTime:rt,endTime:cr}}Sa(u),Xt||(Xt=bl(tt=>{tt.databaseName===u&&Sa(u)}),Mf=Sh(tt=>{tt===u&&(e.send((0,et.encode)([wd])),Ss())}),e.on("close",()=>{Xt?.remove(),Mf?.remove()})),e.send((0,et.encode)([Lq,Oh(p.auditStore),yr.map(({name:tt})=>tt)]));let Ee=!0;do{isFinite(fe)||(ae.warn?.("Invalid sequence id "+fe),Ss(1008,"Invalid sequence id"+fe));let tt;if(Ee&&!me&&(Ee=!1,fe===0)){ae.info?.("Replicating all tables to",g);let rt=fe,cr=yS(f);for(let Mt in _){if(!ee(Mt))continue;let Ts=_[Mt];for(let vt of Ts.primaryStore.getRange({snapshot:!1,versions:!0})){if(me)return;if(vt.localTime>=fe){ae.trace?.(s,"Copying record from",u,Mt,vt.key,vt.localTime),rt=Math.max(vt.localTime,rt),tt=!0,kt()[xh]=1;let Qs=Yc(vt.version,Ts.tableId,vt.key,null,cr,null,"put",fm(()=>Ts.primaryStore.encoder.encode(vt.value),Eu=>_a(Eu,vt.key)),vt.metadataFlags&-256,vt.residencyId,null,vt.expiresAt);await Et({recordId:vt.key,tableId:Ts.tableId,type:"put",getValue(){return vt.value},encoded:Qs,version:vt.version,residencyId:vt.residencyId,nodeId:cr,extendedType:vt.metadataFlags},vt.localTime)}}}tt&&Et({type:"end_txn"},fe),kt()[xh]=0,fe=rt}for(let{key:rt,value:cr}of f.getRange({start:fe||1,exclusiveStart:!0,snapshot:!1})){if(me)return;let Mt=At(cr);ae.debug?.("sending audit record",new Date(rt)),kt()[xh]=rt,fe=rt,await Et(Mt,rt),Lr.startTime=rt,tt=!0}tt&&Et({type:"end_txn"},fe),kt()[xh]=0,await PU(f)}while(!me)}).catch(Ee=>{ae.error?.(s,"Error handling subscription to node",Ee),Ss(1008,"Error handling subscription to node")});break}}return}S.position=8;let A=!0,b,I;do{kt();let P=S.readInt();if(P===9&&S.getUint8(S.position)==__){S.position++,R=I=S.readFloat64(),m[Ow]=R,m[Cw]=Date.now(),m[Pw]=jq,ae.trace?.("received remote sequence update",R,u);break}let L=S.position,D=At(E,L,L+P),H=Cc[D.tableId];H||ae.error?.(`No table found with an id of ${D.tableId}`);let C;D.residencyId&&(C=IE[D.residencyId],ae.trace?.(s,"received residency list",C,D.type,D.recordId));try{let x=D.recordId;o_(()=>{b={table:H.name,id:D.recordId,type:D.type,nodeId:Ff.get(D.nodeId),residencyList:C,timestamp:D.version,value:D.getValue(H),user:D.user,beginTxn:A,expiresAt:D.expiresAt}},f?.rootStore,z=>Pc(z,x))}catch(x){throw x.message+="typed structures for current decoder"+JSON.stringify(H.decoder.typedStructs),x}A=!1,ae.trace?.(s,"received replication message",D.type,"id",b.id,"version",new Date(D.version),"nodeId",b.nodeId),m[Ow]=D.version,m[Cw]=Date.now(),m[Pw]=Qq,p.send(b),S.position=L+P}while(S.position<E.byteLength);Pe++,it(E.byteLength,"bytes-received",`${g}.${u}.${b?.table||"unknown_table"}`,"replication","ingest"),Pe>My&&!Bf&&(Bf=!0,e.pause(),ae.debug?.(`Commit backlog causing replication back-pressure, requesting that ${g} pause replication`)),p.send({type:"end_txn",localTime:R,remoteNodeIds:T,async onCommit(){if(b){let P=Date.now()-b.timestamp;it(P,"replication-latency",g+"."+u+"."+b.table,b.type,"ingest")}Pe--,Bf&&(Bf=!1,e.resume(),ae.debug?.(`Replication resuming ${g}`)),Ue.length>0&&await Promise.all(Ue),ae.trace?.("All blobs finished"),!N&&I&&(ae.trace?.(s,"queuing confirmation of a commit at",I),setTimeout(()=>{e.send((0,et.encode)([Uq,N])),ae.trace?.(s,"sent confirmation of a commit at",N),N=null},pce)),N=I,ae.debug?.("last sequence committed",new Date(I),u)}})}catch(S){ae.error?.(s,"Error handling incoming replication message",S)}}),e.on("ping",Jt),e.on("pong",()=>{if(t.connection){let E=performance.now()-Z;t.connection.latency=E,kt()&&(m[TS]=E),t.isSubscriptionConnection&&wl({name:g,database:u,url:t.url,latency:E})}Z=null}),e.on("close",(E,S)=>{clearInterval(O),clearTimeout(F),clearInterval(Y),Lr&&Lr.emit("close"),po&&po.end();for(let[A,{reject:b}]of y)b(new Error(`Connection closed ${S?.toString()} ${E}`));ae.debug?.(s,"closed",E,S?.toString())});function Ss(E,S){try{e.isFinished=!0,ae.debug?.(s,"closing",g,u,E,S),e.close(E,S),t.connection?.emit("finished")}catch(A){ae.error?.(s,"Error closing connection",A)}}o(Ss,"close");let Ea=new Set;async function _a(E,S){let A=s_(E);if(Ea.has(A)){ae.debug?.("Blob already being sent",A);return}Ea.add(A);try{let b;xe++;for await(let I of E.stream())b&&(ae.debug?.("Sending blob chunk",A,"length",b.length),e.send((0,et.encode)([ES,{fileId:A,size:E.size},b]))),b=I,e._socket.writableNeedDrain&&(ae.debug?.("draining",A),await new Promise(P=>e._socket.once("drain",P)),ae.debug?.("drained",A)),it(I.length,"bytes-sent",`${g}.${u}`,"replication","blob");ae.debug?.("Sending final blob chunk",A,"length",b.length),e.send((0,et.encode)([ES,{fileId:A,size:E.size,finished:!0},b]))}catch(b){ae.warn?.("Error sending blob",b,"blob id",A,"for record",S),e.send((0,et.encode)([ES,{fileId:A,finished:!0,error:(0,Od.errorToString)(b)},Buffer.alloc(0)]))}finally{Ea.delete(A),xe--,xe<xf&&Rr?.()}}o(_a,"sendBlobs");function Pc(E,S){let A=s_(E),b=Ne.get(A);ae.debug?.("Received transaction with blob",A,"has stream",!!b,"ended",!!b?.writableEnded),b?b.writableEnded&&Ne.delete(A):(b=new Nw.PassThrough,Ne.set(A,b)),b.connectedToBlob=!0,b.lastChunk=Date.now(),b.recordId=S,E.size===void 0&&b.expectedSize&&(E.size=b.expectedSize);let I=b.blob??createBlob(b,E);b.blob=I;let P=Ao(()=>dm(I).saving,p.auditStore?.rootStore);return P&&(P.blobId=A,Ue.push(P),P.finally(()=>{ae.debug?.(`Finished receiving blob stream ${A}`),Ue.splice(Ue.indexOf(P),1)})),I}o(Pc,"receiveBlobs");function Dr(){if(h||(h=!0,t.connection?.on("subscriptions-updated",Dr)),!f&&p&&(f=p.auditStore),t.connection?.isFinished)throw new Error("Can not make a subscription request on a connection that is already closed");let E=new Map;f||(f=p?.auditStore);try{for(let b of p?.dbisDB?.getRange({start:Symbol.for("seq"),end:[Symbol.for("seq"),Buffer.from([255])]})||[])for(let I of b.value.nodes||[])I.lastTxnTime>(E.get(I.id)??0)&&E.set(I.id,I.lastTxnTime)}catch(b){if(!b.message.includes("Can not re"))throw b}let S=t.connection?.nodeSubscriptions?.[0];T=[];let A=t.connection?.nodeSubscriptions.map((b,I)=>{let P=[],{replicateByDefault:L}=b;if(b.subscriptions){for(let x of b.subscriptions)if(x.subscribe&&(x.schema||x.database)===u){let z=x.table;_?.[z]?.replicate!==!1&&P.push(z)}L=!1}else for(let x in _)(L?_[x].replicate===!1:_[x].replicate)&&P.push(x);let D=f&&oS(b.name,f),H=p?.dbisDB?.get([Symbol.for("seq"),D])??1,C=Math.max(H?.seqId??1,(typeof b.startTime=="string"?new Date(b.startTime).getTime():b.startTime)??1);if(ae.debug?.("Starting time recorded in db",b.name,D,u,H?.seqId,"start time:",C,new Date(C)),S!==b){let x=f&&oS(S.name,f),z=p?.dbisDB?.get([Symbol.for("seq"),x])??1;for(let ne of z?.nodes||[])ne.name===b.name&&(C=ne.seqId,ae.debug?.("Using sequence id from proxy node",S.name,C))}if(D===void 0?ae.warn("Starting subscription request from node",b,"but no node id found"):T.push(D),E.get(D)>C&&(C=E.get(D),ae.debug?.("Updating start time from more recent txn recorded",S.name,C)),C===1&&_S)try{new URL(_S).hostname===b.name?(ae.warn?.(`Requesting full copy of database ${u} from ${_S}`),C=0):C=Date.now()-6e4}catch(x){ae.error?.("Error parsing leader URL",_S,x)}return ae.trace?.(s,"defining subscription request",b.name,u,new Date(C)),{name:b.name,replicateByDefault:L,tables:P,startTime:C,endTime:b.endTime}});if(A)if(ae.debug?.(s,"sending subscription request",A,p?.dbisDB?.path),clearTimeout(K),A.length>0)e.send((0,et.encode)([Cq,A]));else{let b=o(()=>{let I=performance.now();K=setTimeout(()=>{ce<=I?Ss(1008,"Connection has no subscriptions and is no longer used"):b()},q).unref()},"scheduleClose");b()}}o(Dr,"sendSubscriptionRequestUpdate");function mu(E,S){if(!E)return;let A=Uf[E];return A||(A=S.getResidencyRecord(E),Uf[E]=A),A}o(mu,"getResidence");function hu(E){return!(Za&&Za!="*"&&!Za[E]&&!Za.includes?.(E)&&!Za.some?.(S=>S.name===E))}o(hu,"checkDatabaseAccess");function ga(E){if(p=p||d.get(E),!hu(E))throw new Error(`Access to database "${E}" is not permitted`);p||ae.warn?.(`No database named "${E}" was declared and registered`),f=p?.auditStore,_||(_=st()?.[E]);let S=Ze();if(S===g)throw S?new Error("Should not connect to self",S):new Error("Node name not defined");return wE(S,E),!0}o(ga,"setDatabase");function wE(E,S){let A=st()?.[S],b=[];for(let I in A){let P=A[I];b.push({table:I,schemaDefined:P.schemaDefined,attributes:P.attributes.map(L=>({name:L.name,type:L.type,isPrimaryKey:L.isPrimaryKey}))})}ae.trace?.("Sending database info for node",E,"database name",S),e.send((0,et.encode)([Pq,E,S,b]))}o(wE,"sendNodeDBName");function Sa(E){let S=st()?.[E],A=[];for(let b in S){if(yr&&!yr.some(P=>P.replicateByDefault?!P.tables.includes(b):P.tables.includes(b)))continue;let I=S[b];A.push({table:b,schemaDefined:I.schemaDefined,attributes:I.attributes.map(P=>({name:P.name,type:P.type,isPrimaryKey:P.isPrimaryKey}))})}e.send((0,et.encode)([xq,A,E]))}o(Sa,"sendDBSchema"),Y=setInterval(()=>{for(let[E,S]of Ne)S.lastChunk+pe<Date.now()&&(ae.warn?.(`Timeout waiting for blob stream to finish ${E} for record ${S.recordId??"unknown"} from ${g}`),Ne.delete(E),S.end())},pe).unref();let Ta=1,Hf=[];return{end(){po&&po.end(),Lr&&Lr.emit("close")},getRecord(E){let S=Ta++;return new Promise((A,b)=>{let I=[Mq,S,E.table.tableId,E.id];Hf[E.table.tableId]||(I.push(E.table.tableName),Hf[E.table.tableId]=!0),e.send((0,et.encode)(I)),ce=performance.now(),y.set(S,{tableId:E.table.tableId,key:E.id,resolve(P){let{table:L,entry:D}=E;if(A(P),P)return L._recordRelocate(D,P)},reject:b})})},sendOperation(E){let S=Ta++;return E.requestId=S,e.send((0,et.encode)([ww,E])),new Promise((A,b)=>{y.set(S,{resolve:A,reject:b})})}};function pu(E){Ra(5),E<128?a[c++]=E:E<16384?(l.setUint16(c,E|32768),c+=2):E<1056964608?(l.setUint32(c,E|3221225472),c+=4):(a[c]=255,l.setUint32(c+1,E),c+=5)}function Lc(E,S=0,A=E.length){let b=A-S;Ra(b),E.copy(a,c,S,A),c+=b}function Dc(E){Ra(8),l.setFloat64(c,E),c+=8}function Ra(E){if(E+16>a.length-c){let S=Buffer.allocUnsafeSlow(c+E-i+65536>>10<<11);a.copy(S,0,i,c),c=c-i,i=0,a=S,l=new DataView(a.buffer,0,a.length)}}function V(E,S){let A=E.database??"data";if(A!=="data"&&!ke[A]){ae.warn?.("Database not found",E.database);return}S||(S={});let b=S.schemaDefined,I=!1,P=E.schemaDefined,L=S.attributes||[];for(let D=0;D<E.attributes?.length;D++){let H=E.attributes[D],C=L.find(x=>x.name===H.name);(!C||C.type!==H.type)&&(b?ae.error?.(`Schema for '${u}.${E.table}' is defined locally, but attribute '${H.name}: ${H.type}' from '${g}' does not match local attribute ${C?"'"+C.name+": "+C.type+"'":"which does not exist"}`):(I=!0,P||(H.indexed=!0),C?L[L.indexOf(C)]=H:L.push(H)))}return I?(ae.debug?.("(Re)creating",E),ze({table:E.table,database:E.database,schemaDefined:E.schemaDefined,attributes:L,...S})):S}}var kq,et,Gq,qq,Od,Lw,$q,Vq,Pl,Kq,Nw,Yq,Wq,ae,Cq,Pq,Lq,wd,Dq,bw,Mq,hS,ww,pS,vq,Uq,xq,ES,zq,Ow,Cw,xh,TS,Pw,jq,Qq,hce,_S,Dw,ec,gS,Bq,pce,Fq,Iw,SS,Hq,Cd,Mw=ue(()=>{De();Di();aw();eb();is();kq=w(oe());k();Wc();et=require("msgpackr"),Gq=require("ws"),qq=require("worker_threads"),Od=w(Q());Mh();Lw=require("events"),$q=w(as()),Vq=w(require("node:tls"));Nl();Pl=w(require("node:process")),Kq=require("node:net");zi();Yn();Nw=require("node:stream"),Yq=require("lmdb"),Wq=w(require("minimist")),ae=(0,Od.forComponent)("replication").conditional,Cq=129,Pq=140,Lq=141,wd=142,Dq=130,bw=132,Mq=133,hS=134,ww=136,pS=137,vq=143,Uq=144,xq=145,ES=146,zq=0,Ow=1,Cw=2,xh=3,TS=4,Pw=5,jq=0,Qq=1,hce=(0,Wq.default)(Pl.argv),_S=hce.HDB_LEADER_URL??Pl.env.HDB_LEADER_URL,Dw=new Map,ec=new Map,gS=!0,Bq=300,pce=2,Fq=3e4;o(RS,"createWebSocket");Hq=500,Cd=class extends Lw.EventEmitter{static{o(this,"NodeReplicationConnection")}socket;startTime;retryTime=Hq;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??hi(t)}async connect(){this.session||this.resetSession();let t=[];this.socket=await RS(this.url,{serverName:this.nodeName,authorization:this.authorization});let r;ae.debug?.(`Connecting to ${this.url}, db: ${this.databaseName}, process ${Pl.pid}`),this.socket.on("open",()=>{this.socket._socket.unref(),ae[this.isConnected?"info":"warn"]?.(`Connected to ${this.url}, db: ${this.databaseName}`),this.retries=0,this.retryTime=Hq,this.nodeSubscriptions&&wl({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"?(ae.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"?ae.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`):ae.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&&bd({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();ae.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))}};o(Bh,"replicateOverWS")});var Fo={};Oe(Fo,{clearThisNodeName:()=>bce,disableReplication:()=>Sce,enabledDatabases:()=>Za,forEachReplicatedDatabase:()=>Wa,getThisNodeId:()=>yS,getThisNodeName:()=>Ze,getThisNodeUrl:()=>za,hostnameToUrl:()=>wS,lastTimeInAuditStore:()=>Ch,monitorNodeCAs:()=>o$,replicateOperation:()=>Nce,replicationCertificateAuthorities:()=>Ho,sendOperationToNode:()=>Fh,servers:()=>_ce,setReplicator:()=>c$,start:()=>gce,startOnMainThread:()=>dw,subscribeToNode:()=>Dh,unsubscribeFromNode:()=>lS,urlToNodeName:()=>hi});function gce(e){if(!e.port&&!e.securePort&&(e.port=Ds.default.get(U.OPERATIONSAPI_NETWORK_PORT),e.securePort=Ds.default.get(U.OPERATIONSAPI_NETWORK_SECUREPORT)),!Ze())throw new Error("Can not load replication without a url (see replication.url in the config)");let t=new Map;for(let s of Lh(e))t.set(hi(s.url),s);Tce(e),e={mtls:!0,isOperationsServer:!0,maxPayload:10*1024*1024*1024,...e};let r=Le.ws(async(s,i,a,c)=>{if(Ot.debug("Incoming WS connection received "+i.url),i.headers.get("sec-websocket-protocol")!=="harperdb-replication-v1")return c(s,i,a);await a,s._socket.unref(),Bh(s,e,i?.user),s.on("error",l=>{l.code!=="ECONNREFUSED"&&Ot.error("Error in connection to "+this.url,l.message)})},e);e.runFirst=!0,Le.http((s,i)=>{if(s.isWebSocket&&s.headers.get("Sec-WebSocket-Protocol")==="harperdb-replication-v1"){Ot.debug("Incoming replication WS connection received, authorized: "+s.authorized),!s.authorized&&s._nodeRequest.socket.authorizationError&&Ot.error(`Incoming client connection from ${s.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`,s._nodeRequest.socket.authorizationError);let a=Kt().primaryStore;if(s.authorized&&s.peerCertificate.subjectaltname){let c=(0,s$.getHostnamesFromCertificate)(s.peerCertificate),l;for(let u of c)if(l=u&&(a.get(u)||t.get(u)),l)break;if(l)if(l?.revoked_certificates?.includes(s.peerCertificate.serialNumber)){Ot.warn("Revoked certificate used in attempt to connect to node",l.name,"certificate serial number",s.peerCertificate.serialNumber);return}else s.user=l;else Ot.warn(`No node found for certificate common name/SANs: ${c}, available nodes are ${Array.from(a.getRange({}).filter(({value:u})=>u).map(({key:u})=>u)).join(", ")} and routes ${Array.from(t.keys()).join(", ")}, connection will require credentials.`)}else{let c=a.get(s.ip)||t.get(s.ip);c?s.user=c:Ot.warn(`No node found for IP address ${s.ip}, available nodes are ${Array.from(new Set([...a.getKeys(),...t.keys()])).join(", ")}, connection will require credentials.`)}}return i(s)},e);let n=[];for(let s of r)if(s.secureContexts){let i=o(()=>{let a=new Set(s.secureContexts.values());s.defaultContext&&a.add(s.defaultContext);for(let c of a)try{let l=Array.from(Ho);c.options.availableCAs&&l.push(...c.options.availableCAs.values());let u={...c.options,ca:l};c.updatedContext=NS.createSecureContext(u)}catch(l){Ot.error("Error creating replication TLS config",l)}},"updateContexts");s.secureContextsListeners.push(i),n.push(i),Ds.default.get(U.REPLICATION_ENABLEROOTCAS)!==!1&&i()}o$(()=>{for(let s of n)s()})}function o$(e){let t=0;yd(r=>{r?.ca&&(Ho.add(r.ca),Ho.size!==t&&(t=Ho.size,e?.()))})}function Sce(e=!0){i$=e}function Tce(e){i$||(st(),Za=e.databases,Wa(e,(t,r)=>{if(!t){let n=e.databaseSubscriptions||ec;for(let[s,i]of bS){let a=i.get(r);a&&(a.subscribe([],!1),i.delete(r))}n.delete(r);return}for(let n in t){let s=t[n];c$(r,s,e),Dw.get(s)?.forEach(i=>i(s))}}))}function c$(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 a$ extends xr{static{o(this,"Replicator")}static connection;static subscription;static async subscribe(){let i=r.databaseSubscriptions||ec,a=i.get(e),c=a?.tableById||[];c[t.tableId]=t;let l=a?.ready;if(Ot.trace("Setting up replicator subscription to database",e),!a?.auditStore)return this.subscription=a=new Kn,i.set(e,a),a.tableById=c,a.auditStore=t.auditStore,a.dbisDB=t.dbisDB,a.databaseName=e,l&&l(a),a;this.subscription=a}static subscribeOnThisThread(i,a){return!0}static async load(i){if(i){let a=i.residencyId,c=i.residency||t.dbisDB.get([Symbol.for("residency_by_id"),a]);if(c){let l,u=new Set;do{let d,f="",m=1/0;for(let p of c){if(u.has(p)||p===Le.hostname)continue;let _=yce(p,a$.subscription,e);if(_?.isConnected){let g=Rd(t.auditStore,e,p)[TS];(!d||g<m)&&(d=_,f=p,m=g)}}if(!d)throw l||new r$.ServerError(`No connection to any other nodes are available: ${c}`,502);let h={requestId:Ece++,table:t,entry:i,id:i.key};u.add(f);try{return await d.getRecord(h)}catch(p){if(d.isConnected)throw p;Ot.warn("Error in load from node",IS,p),l||(l=p)}}while(!0)}}}static isReplicator=!0},{intermediateSource:!0})}function Rce(e,t,r,n,s){let i=bS.get(e);i||bS.set(e,i=new Map);let a=i.get(r);if(a)return a;if(t)return i.set(r,a=new Cd(e,t,r,n,s)),a.connect(),a.once("finished",()=>i.delete(r)),a}function yce(e,t,r){let n=Xq.get(e);n||(n=new Map,Xq.set(e,n));let s=n.get(r);if(s)return s;let i=Kt().primaryStore.get(e);return i?.url&&(s=new Cd(i.url,t,r,e,i.authorization),n.set(r,s),s.connect(),s.once("finished",()=>n.delete(r))),s}async function Fh(e,t,r){r||(r={}),r.serverName=e.name;let n=await RS(e.url,r),s=Bh(n,{},{});return new Promise((i,a)=>{n.on("open",()=>{Ot.debug("Sending operation connection to "+e.url+" opened",t),i(s.sendOperation(t))}),n.on("error",c=>{a(c)}),n.on("close",c=>{Ot.info("Sending operation connection to "+e.url+" closed",c)})}).finally(()=>{n.close()})}function Dh(e){try{n$.isMainThread&&Ot.trace("Subscribing on main thread (should not happen in multi-threaded instance)",e.nodes[0].url,e.database);let t=ec.get(e.database);if(!t){let n;t=new Promise(s=>{Ot.info("Waiting for subscription to database "+e.database),n=s}),t.ready=n,ec.set(e.database,t)}let r=Rce(e.nodes[0].url,t,e.database,e.nodes[0].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){Ot.error("Error in subscription to node",e.nodes[0]?.url,t)}}async function lS({name:e,url:t,database:r}){Ot.trace("Unsubscribing from node",e,t,r,"nodes",Array.from(Kt().primaryStore.getRange({})));let n=bS.get(t);if(n){let s=n.get(r);s&&(s.unsubscribe(),n.delete(r))}}function Ace(){if(vw!==void 0)return vw;let e=Ds.default.get(U.OPERATIONSAPI_TLS_CERTIFICATE)||Ds.default.get(U.TLS_CERTIFICATE);if(e)return vw=new e$.X509Certificate((0,t$.readFileSync)(e)).subject?.match(/CN=(.*)/)?.[1]??null}function Ze(){return IS||(IS=Ds.default.get("replication_hostname")??hi(Ds.default.get("replication_url"))??Ace()??Zq("operationsapi_network_secureport")??Zq("operationsapi_network_port")??"127.0.0.1")}function bce(){IS=void 0}function Zq(e){let t=Ds.default.get(e),r=t?.lastIndexOf?.(":");if(r>0)return t.slice(0,r)}function AS(e){let t=Ds.default.get(e),r=t?.lastIndexOf?.(":");return r>0?+t.slice(r+1).replace(/[\[\]]/g,""):+t}function yS(e){return Oh(e)?.[Ze()]}function za(){let e=Ds.default.get("replication_url");return e||wS(Ze())}function wS(e){let t=AS("replication_port");if(t)return`ws://${e}:${t}`;if(t=AS("replication_secureport"),t)return`wss://${e}:${t}`;if(t=AS("operationsapi_network_port"),t)return`ws://${e}:${t}`;if(t=AS("operationsapi_network_secureport"),t)return`wss://${e}:${t}`}function hi(e){if(e)return new URL(e).hostname}function Wa(e,t){for(let n of Object.getOwnPropertyNames(ke))r(n);return Sh(n=>{r(n)}),bl((n,s)=>{r(n.databaseName)});function r(n){let s=ke[n];Ot.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):Ice(n)&&t(s,n,!1)}o(r,"forDatabase")}function Ice(e){let t=ke[e];for(let r in t)if(t[r].replicate)return!0}function Ch(e){for(let t of e.getKeys({limit:1,reverse:!0}))return t}async function Nce(e){let t={message:""};if(e.replicated){e.replicated=!1,Ot.trace?.("Replicating operation",e.operation,"to nodes",Le.nodes.map(n=>n.name));let r=await Promise.allSettled(Le.nodes.map(n=>Fh(n,e)));t.replicated=r.map((n,s)=>{let i=n.status==="rejected"?{status:"failed",reason:n.reason.toString()}:n.value;return i.node=Le.nodes[s]?.name,i})}return t}var Ds,Ot,e$,t$,NS,r$,n$,s$,i$,Ece,_ce,Ho,Za,bS,Xq,vw,IS,is=ue(()=>{De();La();Tu();Mw();Mr();Ds=w(oe()),Ot=w(Q()),e$=require("crypto"),t$=require("fs");Mh();Nl();k();aw();NS=w(require("node:tls")),r$=w(ge()),n$=require("worker_threads"),s$=w(as()),Ece=1,_ce=[],Ho=Ds.default.get(U.REPLICATION_ENABLEROOTCAS)!==!1?new Set(NS.rootCertificates):new Set;o(gce,"start");o(o$,"monitorNodeCAs");o(Sce,"disableReplication");o(Tce,"assignReplicationSource");o(c$,"setReplicator");bS=new Map;o(Rce,"getSubscriptionConnection");Xq=new Map;o(yce,"getRetrievalConnectionByName");o(Fh,"sendOperationToNode");o(Dh,"subscribeToNode");o(lS,"unsubscribeFromNode");o(Ace,"getCommonNameFromCert");o(Ze,"getThisNodeName");o(bce,"clearThisNodeName");Object.defineProperty(Le,"hostname",{get(){return Ze()}});o(Zq,"getHostFromListeningPort");o(AS,"getPortFromListeningPort");o(yS,"getThisNodeId");Le.replication={getThisNodeId:yS,exportIdMapping:Oh};o(za,"getThisNodeUrl");o(wS,"hostnameToUrl");o(hi,"urlToNodeName");o(Wa,"forEachReplicatedDatabase");o(Ice,"hasExplicitlyReplicatedTable");o(Ch,"lastTimeInAuditStore");o(Nce,"replicateOperation")});var kh=M((JMe,m$)=>{"use strict";var Pd=JG(),{validateBySchema:Hh}=ut(),{commonValidators:Ld,schemaRegex:Uw}=ki(),hr=require("joi"),wce=Q(),Oce=require("uuid").v4,PS=Co(),Dd=(k(),v(W)),Cce=require("util"),tc=Xn(),{handleHDBError:ko,hdbErrors:Pce,ClientError:Ll}=ge(),{HDB_ERROR_MSGS:OS,HTTP_STATUS_CODES:Go}=Pce,{SchemaEventMsg:LS}=oi(),l$=pr(),{getDatabases:Lce}=(De(),v(mt)),{transformReq:Md}=ie(),{replicateOperation:u$}=(is(),v(Fo)),{cleanupOrphans:Dce}=(Yn(),v(a_)),CS=hr.string().min(1).max(Ld.schema_length.maximum).pattern(Uw).messages({"string.pattern.base":"{:#label} "+Ld.schema_format.message}),Mce=hr.string().min(1).max(Ld.schema_length.maximum).pattern(Uw).messages({"string.pattern.base":"{:#label} "+Ld.schema_format.message}).required(),vce=hr.string().min(1).max(Ld.schema_length.maximum).pattern(Uw).messages({"string.pattern.base":"{:#label} "+Ld.schema_format.message,"any.required":"'primary_key' is required","string.base":"'primary_key' must be a string"}).required();m$.exports={createSchema:Uce,createSchemaStructure:d$,createTable:xce,createTableStructure:f$,createAttribute:Gce,dropSchema:Bce,dropTable:Fce,dropAttribute:Hce,getBackup:qce,cleanupOrphanBlobs:$ce};async function Uce(e){let t=await d$(e);return PS.signalSchemaChange(new LS(process.pid,e.operation,e.schema)),t}o(Uce,"createSchema");async function d$(e){let t=Hh(e,hr.object({database:CS,schema:CS}));if(t)throw new Ll(t.message);if(Md(e),!await Pd.checkSchemaExists(e.schema))throw ko(new Error,OS.SCHEMA_EXISTS_ERR(e.schema),Go.BAD_REQUEST,Dd.LOG_LEVELS.ERROR,OS.SCHEMA_EXISTS_ERR(e.schema),!0);return await tc.createSchema(e),`database '${e.schema}' successfully created`}o(d$,"createSchemaStructure");async function xce(e){return Md(e),e.hash_attribute=e.primary_key??e.hash_attribute,await f$(e)}o(xce,"createTable");async function f$(e){let t=Hh(e,hr.object({database:CS,schema:CS,table:Mce,residence:hr.array().items(hr.string().min(1)).optional(),hash_attribute:vce}));if(t)throw new Ll(t.message);if(!await Pd.checkSchemaTableExists(e.schema,e.table))throw ko(new Error,OS.TABLE_EXISTS_ERR(e.schema,e.table),Go.BAD_REQUEST,Dd.LOG_LEVELS.ERROR,OS.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:Oce(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await tc.createTable(n,e);else throw ko(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",Go.BAD_REQUEST);else await tc.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}o(f$,"createTableStructure");async function Bce(e){let t=Hh(e,hr.object({database:hr.string(),schema:hr.string()}).or("database","schema").messages({"object.missing":"'database' is required"}));if(t)throw new Ll(t.message);Md(e);let r=await Pd.checkSchemaExists(e.schema);if(r)throw ko(new Error,r,Go.NOT_FOUND,Dd.LOG_LEVELS.ERROR,r,!0);let n=await Pd.schemaDescribe.describeSchema({schema:e.schema}),s=Object.keys(global.hdb_schema[e.schema]);await tc.dropSchema(e),PS.signalSchemaChange(new LS(process.pid,e.operation,e.schema)),await l$.purgeSchemaTableStreams(e.schema,s);let i=await u$(e);return i.message=`successfully deleted '${e.schema}'`,i}o(Bce,"dropSchema");async function Fce(e){let t=Hh(e,hr.object({database:hr.string(),schema:hr.string(),table:hr.string().required()}));if(t)throw new Ll(t.message);Md(e);let r=await Pd.checkSchemaTableExists(e.schema,e.table);if(r)throw ko(new Error,r,Go.NOT_FOUND,Dd.LOG_LEVELS.ERROR,r,!0);await tc.dropTable(e),await l$.purgeTableStream(e.schema,e.table);let n=await u$(e);return n.message=`successfully deleted table '${e.schema}.${e.table}'`,n}o(Fce,"dropTable");async function Hce(e){let t=Hh(e,hr.object({database:hr.string(),schema:hr.string(),table:hr.string().required(),attribute:hr.string().required()}));if(t)throw new Ll(t.message);Md(e);let r=await Pd.checkSchemaTableExists(e.schema,e.table);if(r)throw ko(new Error,r,Go.NOT_FOUND,Dd.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw ko(new Error,"You cannot drop a hash attribute",Go.BAD_REQUEST,void 0,void 0,!0);if(Dd.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw ko(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,Go.BAD_REQUEST,void 0,void 0,!0);try{return await tc.dropAttribute(e),kce(e),PS.signalSchemaChange(new LS(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw wce.error(`Got an error deleting attribute ${Cce.inspect(e)}.`),n}}o(Hce,"dropAttribute");function kce(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)}o(kce,"dropAttributeFromGlobal");async function Gce(e){Md(e);let t=Lce()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw ko(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,Go.BAD_REQUEST,void 0,void 0,!0);return await tc.createAttribute(e),PS.signalSchemaChange(new LS(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}o(Gce,"createAttribute");function qce(e){return tc.getBackup(e)}o(qce,"getBackup");function $ce(e){if(!e.database)throw new Ll('Must provide "database" name for search for orphaned blobs');if(!databases[e.database])throw new Ll(`Unknown database '${e.database}'`);return Dce(databases[e.database],e.database),{message:"Orphaned blobs cleanup started, check logs for progress"}}o($ce,"cleanupOrphanBlobs")});var p$=M((ZMe,h$)=>{"use strict";var{OPERATIONS_ENUM:Vce}=(k(),v(W)),xw=class{static{o(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=Vce.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};h$.exports=xw});var Bw=M((rve,T$)=>{"use strict";var Kce=Xn(),tve=p$(),DS=ie(),MS=(k(),v(W)),Yce=oe(),{handleHDBError:E$,hdbErrors:Wce}=ge(),{HDB_ERROR_MSGS:_$,HTTP_STATUS_CODES:g$}=Wce,zce=Object.values(MS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),S$="To use this operation audit log must be enabled in harperdb-config.yaml";T$.exports=jce;async function jce(e){if(DS.isEmpty(e.schema))throw new Error(_$.SCHEMA_REQUIRED_ERR);if(DS.isEmpty(e.table))throw new Error(_$.TABLE_REQUIRED_ERR);if(!Yce.get(MS.CONFIG_PARAMS.LOGGING_AUDITLOG))throw E$(new Error,S$,g$.BAD_REQUEST,MS.LOG_LEVELS.ERROR,S$,!0);let t=DS.checkSchemaTableExist(e.schema,e.table);if(t)throw E$(new Error,t,g$.NOT_FOUND,MS.LOG_LEVELS.ERROR,t,!0);if(!DS.isEmpty(e.search_type)&&zce.indexOf(e.search_type)<0)throw new Error(`Invalid searchType '${read_audit_log_object.search_type}'`);return await Kce.readAuditLog(e)}o(jce,"readAuditLog")});var y$=M((sve,R$)=>{"use strict";var{OPERATIONS_ENUM:Qce}=(k(),v(W)),Fw=class{static{o(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=Qce.GET_BACKUP,this.schema=t,this.table=r}};R$.exports=Fw});var I$=M((cve,b$)=>{"use strict";var Jce=Xn(),ove=y$(),Hw=ie(),Xce=(k(),v(W)),ave=oe(),{handleHDBError:Zce,hdbErrors:ele}=ge(),{HDB_ERROR_MSGS:A$,HTTP_STATUS_CODES:tle}=ele;b$.exports=rle;async function rle(e){if(Hw.isEmpty(e.schema))throw new Error(A$.SCHEMA_REQUIRED_ERR);if(Hw.isEmpty(e.table))throw new Error(A$.TABLE_REQUIRED_ERR);let t=Hw.checkSchemaTableExist(e.schema,e.table);if(t)throw Zce(new Error,t,tle.NOT_FOUND,Xce.LOG_LEVELS.ERROR,t,!0);return await Jce.getBackup(readAuditLogObject)}o(rle,"getBackup")});var C$=M((uve,O$)=>{"use strict";var nle=oe(),rc=require("joi"),sle=ut(),N$=require("moment"),ile=require("fs-extra"),kw=require("path"),ole=require("lodash"),Gh=(k(),v(W)),{LOG_LEVELS:Dl}=(k(),v(W)),ale="YYYY-MM-DD hh:mm:ss",cle=kw.resolve(__dirname,"../logs");O$.exports=function(e){return sle.validateBySchema(e,lle)};var lle=rc.object({from:rc.custom(w$),until:rc.custom(w$),level:rc.valid(Dl.NOTIFY,Dl.FATAL,Dl.ERROR,Dl.WARN,Dl.INFO,Dl.DEBUG,Dl.TRACE),order:rc.valid("asc","desc"),limit:rc.number().min(1),start:rc.number().min(0),log_name:rc.custom(ule)});function w$(e,t){if(N$(e,N$.ISO_8601).format(ale)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}o(w$,"validateDatetime");function ule(e,t){if(ole.invert(Gh.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=nle.get(Gh.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?Gh.LOG_NAMES.HDB:e,i=s===Gh.LOG_NAMES.INSTALL?kw.join(cle,Gh.LOG_NAMES.INSTALL):kw.join(n,s);return ile.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}o(ule,"validateReadLogPath")});var qw=M((fve,L$)=>{"use strict";var vS=(k(),v(W)),dle=Q(),fle=oe(),mle=C$(),Gw=require("path"),P$=require("fs-extra"),{once:hle}=require("events"),{handleHDBError:ple,hdbErrors:Ele}=ge(),{PACKAGE_ROOT:_le}=Rt(),{replicateOperation:gle}=(is(),v(Fo)),Sle=Gw.join(_le,"logs"),Tle=1e3,Rle=200;L$.exports=yle;async function yle(e){let t=mle(e);if(t)throw ple(t,t.message,Ele.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=gle(e),n=fle.get(vS.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?vS.LOG_NAMES.HDB:e.log_name,i=s===vS.LOG_NAMES.INSTALL?Gw.join(Sle,vS.LOG_NAMES.INSTALL):Gw.join(n,s),a=e.level!==void 0,c=a?e.level:void 0,l=e.from!==void 0,u=l?new Date(e.from):void 0,d=e.until!==void 0,f=d?new Date(e.until):void 0,m=e.limit===void 0?Tle:e.limit,h=e.order===void 0?void 0:e.order,p=e.start===void 0?0:e.start,_=p+m,g=0;h==="desc"&&!u&&!f&&(g=Math.max(P$.statSync(i).size-(_+5)*Rle,0));let y=P$.createReadStream(i,{start:g});y.on("error",G=>{dle.error(G)});let T=0,R=[],N="",O;y.on("data",G=>{let Y=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;G=N+G;let q=0,K;for(;(K=Y.exec(G))&&!y.destroyed;){O&&(O.message=G.slice(q,K.index),F(O));let[ce,le,se]=K,pe=se.split("] ["),Ne=pe[0],Ue=pe[1];pe.splice(0,2),O={timestamp:le,thread:Ne,level:Ue,tags:pe,message:""},q=K.index+ce.length}N=G.slice(q)}),y.on("end",G=>{y.destroyed||O&&(O.message=N.trim(),F(O))}),y.resume();function F(G){let Y,q,K;switch(!0){case(a&&l&&d):Y=new Date(G.timestamp),q=new Date(u),K=new Date(f),G.level===c&&Y>=q&&Y<=K&&T<p?T++:G.level===c&&Y>=q&&Y<=K&&(eo(G,h,R),T++,T===_&&y.destroy());break;case(a&&l):Y=new Date(G.timestamp),q=new Date(u),G.level===c&&Y>=q&&T<p?T++:G.level===c&&Y>=q&&(eo(G,h,R),T++,T===_&&y.destroy());break;case(a&&d):Y=new Date(G.timestamp),K=new Date(f),G.level===c&&Y<=K&&T<p?T++:G.level===c&&Y<=K&&(eo(G,h,R),T++,T===_&&y.destroy());break;case(l&&d):Y=new Date(G.timestamp),q=new Date(u),K=new Date(f),Y>=q&&Y<=K&&T<p?T++:Y>=q&&Y<=K&&(eo(G,h,R),T++,T===_&&y.destroy());break;case a:G.level===c&&T<p?T++:G.level===c&&(eo(G,h,R),T++,T===_&&y.destroy());break;case l:Y=new Date(G.timestamp),q=new Date(u),Y>=q&&T<p?T++:Y>=q&&T>=p&&(eo(G,h,R),T++,T===_&&y.destroy());break;case d:Y=new Date(G.timestamp),K=new Date(f),Y<=K&&T<p?T++:Y<=K&&T>=p&&(eo(G,h,R),T++,T===_&&y.destroy());break;default:T<p?T++:(eo(G,h,R),T++,T===_&&y.destroy())}}o(F,"onLogMessage"),await hle(y,"close");let Z=await r;if(Z.replicated){for(let G of R)G.node=server.hostname;for(let G of Z.replicated){let Y=G.node;if(G.status==="failed")eo({timestamp:new Date().toISOString(),level:"error",node:Y,message:`Error retrieving logs: ${G.reason}`},h,R);else for(let q of G.results)q.node=Y,eo(q,h,R)}}return R}o(yle,"readLog");function eo(e,t,r){t==="desc"?Ale(e,r):t==="asc"?ble(e,r):r.push(e)}o(eo,"pushLineToResult");function Ale(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)}o(Ale,"insertDescending");function ble(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)}o(ble,"insertAscending")});var US=M((gve,U$)=>{"use strict";var $w=require("joi"),{string:vd,boolean:D$,date:Ile}=$w.types(),Nle=ut(),{validateSchemaExists:hve,validateTableExists:pve,validateSchemaName:Eve}=ki(),wle=(k(),v(W)),Ole=It(),M$=oe();M$.initSync();var _ve=vd.invalid(M$.get(wle.CONFIG_PARAMS.CLUSTERING_NODENAME)??"node_name").pattern(Ole.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),v$={operation:vd.valid("add_node","update_node","set_node_replication"),node_name:vd.optional(),subscriptions:$w.array().items({table:vd.optional(),schema:vd.optional(),database:vd.optional(),subscribe:D$.required(),publish:D$.required().custom(Ple),start_time:Ile.iso()})};function Cle(e){return Nle.validateBySchema(e,$w.object(v$))}o(Cle,"addUpdateNodeValidator");function Ple(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`)}o(Ple,"checkForFalsy");U$.exports={addUpdateNodeValidator:Cle,validationSchema:v$}});var Ud=M((Tve,x$)=>{"use strict";var Vw=class{static{o(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},Kw=class{static{o(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};x$.exports={Node:Vw,NodeSubscription:Kw}});var F$=M((yve,B$)=>{"use strict";var Lle=(k(),v(W)).OPERATIONS_ENUM,Yw=class{static{o(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=Lle.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};B$.exports=Yw});var qh=M((bve,H$)=>{"use strict";var Ww=class{static{o(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},zw=class{static{o(this,"RemotePayloadSubscription")}constructor(t,r,n,s,i,a,c){this.schema=t,this.table=r,this.hash_attribute=n,this.publish=s,this.subscribe=i,this.start_time=a,c!==void 0&&(this.attributes=c)}};H$.exports={RemotePayloadObject:Ww,RemotePayloadSubscription:zw}});var G$=M((Nve,k$)=>{"use strict";var jw=class{static{o(this,"TableSizeObject")}constructor(t,r,n=0,s=0,i=0,a=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=a}};k$.exports=jw});var $$=M((Dve,q$)=>{"use strict";var Dle=G$(),Ove=qt(),Cve=_t(),Mle=Q(),{getSchemaPath:Pve,getTransactionAuditStorePath:Lve}=yt(),{getDatabases:vle}=(De(),v(mt));q$.exports=Ule;async function Ule(e){let t=new Dle;try{let r=vle()[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){Mle.warn(`unable to stat table dbi due to ${r}`)}return t}o(Ule,"lmdbGetTableSize")});var K$=M((vve,V$)=>{"use strict";var Qw=class{static{o(this,"SystemInformationObject")}constructor(t,r,n,s,i,a,c){this.system=t,this.time=r,this.cpu=n,this.memory=s,this.disk=i,this.network=a,this.harperdb_processes=c}};V$.exports=Qw});var Bd=M((kve,j$)=>{"use strict";var xle=require("fs-extra"),Ble=require("path"),dn=require("systeminformation"),nc=Q(),Y$=pr(),xve=It(),xd=(k(),v(W)),Fle=$$(),Hle=xa(),{getThreadInfo:W$}=nt(),$h=oe();$h.initSync();var kle=K$(),{openEnvironment:Bve}=_t(),{getSchemaPath:Fve}=yt(),{database:Hve,databases:Jw}=(De(),v(mt)),xS;j$.exports={getHDBProcessInfo:tO,getNetworkInfo:nO,getDiskInfo:rO,getMemoryInfo:eO,getCPUInfo:Zw,getTimeInfo:Xw,getSystemInformation:sO,systemInformation:Gle,getTableSize:iO,getMetrics:oO};function Xw(){return dn.time()}o(Xw,"getTimeInfo");async function Zw(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:a,governor:c,socket:l,cache:u,...d}=await dn.cpu();d.cpu_speed=await dn.cpuCurrentSpeed();let{rawCurrentload:f,rawCurrentloadIdle:m,rawCurrentloadIrq:h,rawCurrentloadNice:p,rawCurrentloadSystem:_,rawCurrentloadUser:g,cpus:y,...T}=await dn.currentLoad();return T.cpus=[],y.forEach(R=>{let{rawLoad:N,rawLoadIdle:O,rawLoadIrq:F,rawLoadNice:Z,rawLoadSystem:G,rawLoadUser:Y,...q}=R;T.cpus.push(q)}),d.current_load=T,d}catch(e){return nc.error(`error in getCPUInfo: ${e}`),{}}}o(Zw,"getCPUInfo");async function eO(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await dn.mem();return Object.assign(s,process.memoryUsage())}catch(e){return nc.error(`error in getMemoryInfo: ${e}`),{}}}o(eO,"getMemoryInfo");async function tO(){let e={core:[],clustering:[]};try{let t=await dn.processes(),r;try{r=Number.parseInt(await xle.readFile(Ble.join($h.get(xd.CONFIG_PARAMS.ROOTPATH),xd.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===xd.NODE_ERROR_CODES.ENOENT)nc.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 nc.error(`error in getHDBProcessInfo: ${t}`),e}}o(tO,"getHDBProcessInfo");async function rO(){let e={};try{if(!$h.get(xd.CONFIG_PARAMS.OPERATIONSAPI_SYSINFO_DISK))return e;let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await dn.disksIO();e.io=i;let{rxSec:a,txSec:c,wxSec:l,...u}=await dn.fsStats();return e.read_write=u,e.size=await dn.fsSize(),e}catch(t){return nc.error(`error in getDiskInfo: ${t}`),e}}o(rO,"getDiskInfo");async function nO(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return $h.get(xd.CONFIG_PARAMS.OPERATIONSAPI_SYSINFO_NETWORK)&&(e.default_interface=await dn.networkInterfaceDefault(),e.latency=await dn.inetChecksite("google.com"),(await dn.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:a,dhcp:c,dnsSuffix:l,ieee8021xAuth:u,ieee8021xState:d,carrierChanges:f,...m}=n;e.interfaces.push(m)}),(await dn.networkStats()).forEach(n=>{let{rxSec:s,txSec:i,ms:a,...c}=n;e.stats.push(c)})),e}catch(t){return nc.error(`error in getNetworkInfo: ${t}`),e}}o(nO,"getNetworkInfo");async function sO(){if(xS!==void 0)return xS;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:a,...c}=await dn.osInfo();e=c;let l=await dn.versions("node, npm");return e.node_version=l.node,e.npm_version=l.npm,xS=e,xS}catch(t){return nc.error(`error in getSystemInformation: ${t}`),e}}o(sO,"getSystemInformation");async function iO(){let e=[],t=await Hle.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await Fle(n));return e}o(iO,"getTableSize");async function oO(){let e={};for(let t in Jw){let r=e[t]={},n=r.tables={};for(let s in Jw[t])try{let i=Jw[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 a=i.primaryStore.getStats(),c={};for(let l of["treeDepth","treeBranchPageCount","treeLeafPageCount","entryCount","overflowPages"])c[l]=a[l];n[s]=c}catch(i){nc.notify(`Error getting stats for table ${s}: ${i}`)}}return e}o(oO,"getMetrics");async function z$(){if($h.get(xd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await Y$.getNATSReferences(),t=await Y$.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 a={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(a)}return r}}o(z$,"getNatsStreamInfo");async function Gle(e){let t=new kle;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await sO(),t.time=Xw(),t.cpu=await Zw(),t.memory=await eO(),t.disk=await rO(),t.network=await nO(),t.harperdb_processes=await tO(),t.table_size=await iO(),t.metrics=await oO(),t.threads=await W$(),t.replication=await z$(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await sO();break;case"time":t.time=Xw();break;case"cpu":t.cpu=await Zw();break;case"memory":t.memory=await eO();break;case"disk":t.disk=await rO();break;case"network":t.network=await nO();break;case"harperdb_processes":t.harperdb_processes=await tO();break;case"table_size":t.table_size=await iO();break;case"database_metrics":case"metrics":t.metrics=await oO();break;case"threads":t.threads=await W$();break;case"replication":t.replication=await z$();break;default:break}return t}o(Gle,"systemInformation")});var qo=M((Kve,Z$)=>{"use strict";var qle=vn(),aO=ie(),$le=require("util"),Ml=(k(),v(W)),Q$=oe();Q$.initSync();var Vle=tw(),J$=on(),{Node:qve,NodeSubscription:$ve}=Ud(),Kle=Vu(),Yle=F$(),{RemotePayloadObject:Wle,RemotePayloadSubscription:zle}=qh(),{handleHDBError:jle,hdbErrors:Qle}=ge(),{HTTP_STATUS_CODES:Jle,HDB_ERROR_MSGS:Xle}=Qle,Zle=ai(),eue=Bd(),{packageJson:tue}=Rt(),{getDatabases:rue}=(De(),v(mt)),Vve=$le.promisify(Vle.authorize),nue=J$.searchByHash,sue=J$.searchByValue;Z$.exports={isEmpty:iue,getNodeRecord:oue,upsertNodeRecord:aue,buildNodePayloads:cue,checkClusteringEnabled:lue,getAllNodeRecords:uue,getSystemInfo:due,reverseSubscription:X$};function iue(e){return e==null}o(iue,"isEmpty");async function oue(e){let t=new Kle(Ml.SYSTEM_SCHEMA_NAME,Ml.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return nue(t)}o(oue,"getNodeRecord");async function aue(e){let t=new Yle(Ml.SYSTEM_SCHEMA_NAME,Ml.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return qle.upsert(t)}o(aue,"upsertNodeRecord");function X$(e){if(aO.isEmpty(e.subscribe)||aO.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}o(X$,"reverseSubscription");function cue(e,t,r,n){let s=[];for(let i=0,a=e.length;i<a;i++){let c=e[i],{schema:l,table:u}=c,d=aO.getTableHashAttribute(l,u),{subscribe:f,publish:m}=X$(c),h=rue()[l]?.[u],p=new zle(l,u,d,m,f,c.start_time,h.schemaDefined?h.attributes:void 0);s.push(p)}return new Wle(r,t,s,n)}o(cue,"buildNodePayloads");function lue(){if(!Q$.get(Ml.CONFIG_PARAMS.CLUSTERING_ENABLED))throw jle(new Error,Xle.CLUSTERING_NOT_ENABLED,Jle.BAD_REQUEST,void 0,void 0,!0)}o(lue,"checkClusteringEnabled");async function uue(){let e=new Zle(Ml.SYSTEM_SCHEMA_NAME,Ml.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await sue(e))}o(uue,"getAllNodeRecords");async function due(){let e=await eue.getSystemInformation();return{hdb_version:tue.version,node_version:e.node_version,platform:e.platform}}o(due,"getSystemInfo")});var cO=M((Wve,aV)=>{"use strict";var BS=pr(),eV=ie(),tV=It(),rV=(k(),v(W)),FS=Q(),nV=kh(),fue=km(),{RemotePayloadObject:mue}=qh(),{handleHDBError:sV,hdbErrors:hue}=ge(),{HTTP_STATUS_CODES:iV}=hue,{NodeSubscription:oV}=Ud();aV.exports=pue;async function pue(e,t){let r;try{r=await BS.request(`${t}.${tV.REQUEST_SUFFIX}`,new mue(rV.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),FS.trace("Response from remote describe all request:",r)}catch(a){FS.error(`addNode received error from describe all request to remote node: ${a}`);let c=BS.requestErrorHandler(a,"add_node",t);throw sV(new Error,c,iV.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===tV.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let a=`Error returned from remote node ${t}: ${r.message}`;throw sV(new Error,a,iV.INTERNAL_SERVER_ERROR,"error",a)}let n=r.message,s=[],i=[];for(let a of e){let{table:c}=a,l=a.database??a.schema??"data";if(l===rV.SYSTEM_SCHEMA_NAME){await BS.createLocalTableStream(l,c);let p=new oV(l,c,a.publish,a.subscribe);p.start_time=a.start_time,i.push(p);continue}let u=eV.doesSchemaExist(l),d=n[l]!==void 0,f=c?eV.doesTableExist(l,c):!0,m=c?n?.[l]?.[c]!==void 0:!0;if(!u&&!d||!f&&!m){s.push(a);continue}if(!u&&d&&(FS.trace(`addNode creating schema: ${l}`),await nV.createSchema({operation:"create_schema",schema:l})),!f&&m){FS.trace(`addNode creating table: ${c} in schema: ${l} with attributes ${JSON.stringify(n[l][c].attributes)}`);let p=new fue(l,c,n[l][c].hash_attribute);n[l][c].attributes&&(p.attributes=n[l][c].attributes),await nV.createTable(p)}await BS.createLocalTableStream(l,c);let h=new oV(l,c,a.publish,a.subscribe);h.start_time=a.start_time,i.push(h)}return{added:i,skipped:s}}o(pue,"reviewSubscriptions")});var Fd={};Oe(Fd,{addNodeBack:()=>lO,removeNodeBack:()=>uO,setNode:()=>Sue});async function Sue(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=hi(t)):t=wS(r);let n=(0,lV.validateBySchema)(e,gue);if(n)throw(0,$o.handleHDBError)(n,n.message,_ue.BAD_REQUEST,void 0,void 0,!0);if(e.operation==="remove_node"){if(!t&&!r)throw new $o.ClientError("url or hostname is required for remove_node operation");let h=r,p=Kt(),_=await p.get(h);if(!_)throw new $o.ClientError(h+" does not exist");try{await Fh({url:_.url},{operation:$.REMOVE_NODE_BACK,name:_?.subscriptions?.length>0?Ze():h},void 0)}catch(g){cs.warn(`Error removing node from target node ${h}, if it is offline and we be online in the future, you may need to clean up this node manually, or retry:`,g)}return await p.delete(h),`Successfully removed '${h}' from cluster`}if(!t)throw new $o.ClientError("url required for this operation");let s=za();if(s==null)throw new $o.ClientError("replication url is missing from harperdb-config.yaml");let i,a,c;if(t?.startsWith("wss:")){i=await(0,Ms.getReplicationCert)();let h=await(0,Ms.getReplicationCertAuth)();if(!i)throw new Error("Unable to find a certificate to use for replication");i.options.is_self_signed?(a=await(0,Ms.createCsr)(),cs.info("Sending CSR to target node:",t)):h&&(c=h.certificate,cs.info("Sending CA named",h.name,"to target node",t))}let l={operation:$.ADD_NODE_BACK,hostname:(0,ic.get)(U.REPLICATION_HOSTNAME),target_hostname:r,url:s,csr:a,cert_auth:c,authorization:e.retain_authorization?e.authorization:null};if((0,ic.get)(U.REPLICATION_SHARD)!==void 0&&(l.shard=(0,ic.get)(U.REPLICATION_SHARD)),e.subscriptions?l.subscriptions=e.subscriptions.map(cV):l.subscriptions=null,e.hasOwnProperty("subscribe")||e.hasOwnProperty("publish")){let h=cV(e);l.subscribe=h.subscribe,l.publish=h.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 Fh({url:t},l,e)}catch(h){h.message=`Error returned from ${t}: `+h.message,cs.warn("Error adding node:",t,"to cluster:",h),d=h}if(a&&(!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)}`);a&&(cs.info("CSR response received from node:",t,"saving certificate and CA in hdb_certificate"),await(0,Ms.setCertTable)({name:Eue.certificateFromPem(u.signingCA).issuer.getField("CN").value,certificate:u.signingCA,is_authority:!0}),u.certificate&&await(0,Ms.setCertTable)({name:Ze(),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 h={url:s,ca:c,replicates:!0,subscriptions:null};(0,ic.get)(U.REPLICATION_SHARD)!==void 0&&(h.shard=(0,ic.get)(U.REPLICATION_SHARD)),e.retain_authorization&&(h.authorization=e.authorization),e.start_time&&(h.start_time=e.start_time),await xo(Ze(),h)}await xo(u?u.nodeName:f.name??hi(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 lO(e){cs.trace("addNodeBack received request:",e);let t=await(0,Ms.signCertificate)(e),r;e.csr?(r=t.signingCA,cs.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,cs.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,Ms.getReplicationCertAuth)();if(n.replicates){let i={url:za(),ca:s?.certificate,replicates:!0,subscriptions:null};(0,ic.get)(U.REPLICATION_SHARD)!==void 0&&(i.shard=(0,ic.get)(U.REPLICATION_SHARD),t.shard=i.shard),e.start_time&&(i.start_time=e.start_time),e.authorization&&(i.authorization=e.authorization),await xo(Ze(),i)}return await xo(e.hostname,n),t.nodeName=Ze(),t.usingCA=s?.certificate,cs.info("addNodeBack responding to:",e.url,"with CA named:",s?.name),t}async function uO(e){cs.trace("removeNodeBack received request:",e),await Kt().delete(e.name)}function cV(e){let{subscribe:t,publish:r}=e;return{...e,subscribe:r,publish:t}}var Ms,lV,sc,ic,cs,$o,Eue,_ue,gue,Hd=ue(()=>{Ms=w(as()),lV=w(ut()),sc=w(require("joi")),ic=w(oe());k();Mh();Nl();is();cs=w(Q()),$o=w(ge()),{pki:Eue}=require("node-forge"),{HTTP_STATUS_CODES:_ue}=$o.hdbErrors,gue=sc.default.object({hostname:sc.default.string(),verify_tls:sc.default.boolean(),replicates:sc.default.boolean(),subscriptions:sc.default.array(),revoked_certificates:sc.default.array(),shard:sc.default.number()});o(Sue,"setNode");o(lO,"addNodeBack");o(uO,"removeNodeBack");o(cV,"reverseSubscription")});var $S=M((rUe,dV)=>{"use strict";var{handleHDBError:HS,hdbErrors:Tue}=ge(),{HTTP_STATUS_CODES:kS}=Tue,{addUpdateNodeValidator:Rue}=US(),GS=Q(),qS=(k(),v(W)),uV=It(),yue=ie(),Vh=pr(),Kh=qo(),dO=oe(),Aue=cO(),{Node:bue,NodeSubscription:Iue}=Ud(),{broadcast:Nue}=nt(),{setNode:wue}=(Hd(),v(Fd)),eUe=oe(),tUe=(k(),v(W)),Oue="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",Cue="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Pue=dO.get(qS.CONFIG_PARAMS.CLUSTERING_NODENAME);dV.exports=Lue;async function Lue(e,t=!1){if(GS.trace("addNode called with:",e),dO.get(qS.CONFIG_PARAMS.REPLICATION_URL)||dO.get(qS.CONFIG_PARAMS.REPLICATION_HOSTNAME))return wue(e);Kh.checkClusteringEnabled();let r=Rue(e);if(r)throw HS(r,r.message,kS.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let f=await Kh.getNodeRecord(n);if(!yue.isEmptyOrZeroLength(f))throw HS(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,kS.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await Aue(e.subscriptions,n),a={message:void 0,added:s,skipped:i};if(s.length===0)return a.message=Oue,a;let c=Kh.buildNodePayloads(s,Pue,qS.OPERATIONS_ENUM.ADD_NODE,await Kh.getSystemInfo()),l=[];for(let f=0,m=s.length;f<m;f++){let h=s[f];s[f].start_time===void 0&&delete s[f].start_time,l.push(new Iue(h.schema,h.table,h.publish,h.subscribe))}GS.trace("addNode sending remote payload:",c);let u;try{u=await Vh.request(`${n}.${uV.REQUEST_SUFFIX}`,c)}catch(f){GS.error(`addNode received error from request: ${f}`);for(let h=0,p=s.length;h<p;h++){let _=s[h];_.publish=!1,_.subscribe=!1,await Vh.updateRemoteConsumer(_,n)}let m=Vh.requestErrorHandler(f,"add_node",n);throw HS(new Error,m,kS.INTERNAL_SERVER_ERROR,"error",m)}if(u.status===uV.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let f=`Error returned from remote node ${n}: ${u.message}`;throw HS(new Error,f,kS.INTERNAL_SERVER_ERROR,"error",f)}GS.trace(u);for(let f=0,m=s.length;f<m;f++){let h=s[f];await Vh.updateRemoteConsumer(h,n),h.subscribe===!0&&await Vh.updateConsumerIterator(h.schema,h.table,n,"start")}let d=new bue(n,l,u.system_info);return await Kh.upsertNodeRecord(d),Nue({type:"nats_update"}),i.length>0?a.message=Cue:a.message=`Successfully added '${n}' to manifest`,a}o(Lue,"addNode")});var pO=M((iUe,mV)=>{"use strict";var{handleHDBError:fO,hdbErrors:Due}=ge(),{HTTP_STATUS_CODES:mO}=Due,{addUpdateNodeValidator:Mue}=US(),Yh=Q(),VS=(k(),v(W)),fV=It(),sUe=ie(),Wh=pr(),zh=qo(),hO=oe(),{cloneDeep:vue}=require("lodash"),Uue=cO(),{Node:xue,NodeSubscription:Bue}=Ud(),{broadcast:Fue}=nt(),{setNode:Hue}=(Hd(),v(Fd)),kue="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",Gue="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",que=hO.get(VS.CONFIG_PARAMS.CLUSTERING_NODENAME);mV.exports=$ue;async function $ue(e){if(Yh.trace("updateNode called with:",e),hO.get(VS.CONFIG_PARAMS.REPLICATION_URL)??hO.get(VS.CONFIG_PARAMS.REPLICATION_HOSTNAME))return Hue(e);zh.checkClusteringEnabled();let t=Mue(e);if(t)throw fO(t,t.message,mO.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await zh.getNodeRecord(r);s.length>0&&(n=vue(s));let{added:i,skipped:a}=await Uue(e.subscriptions,r),c={message:void 0,updated:i,skipped:a};if(i.length===0)return c.message=kue,c;let l=zh.buildNodePayloads(i,que,VS.OPERATIONS_ENUM.UPDATE_NODE,await zh.getSystemInfo());for(let d=0,f=i.length;d<f;d++){let m=i[d];Yh.trace(`updateNode updating work stream for node: ${r} subscription:`,m),i[d].start_time===void 0&&delete i[d].start_time}Yh.trace("updateNode sending remote payload:",l);let u;try{u=await Wh.request(`${r}.${fV.REQUEST_SUFFIX}`,l)}catch(d){Yh.error(`updateNode received error from request: ${d}`);let f=Wh.requestErrorHandler(d,"update_node",r);throw fO(new Error,f,mO.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===fV.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${r}: ${u.message}`;throw fO(new Error,d,mO.INTERNAL_SERVER_ERROR,"error",d)}Yh.trace(u);for(let d=0,f=i.length;d<f;d++){let m=i[d];await Wh.updateRemoteConsumer(m,r),m.subscribe===!0?await Wh.updateConsumerIterator(m.schema,m.table,r,"start"):await Wh.updateConsumerIterator(m.schema,m.table,r,"stop")}return n||(n=[new xue(r,[],u.system_info)]),await Vue(n[0],i,u.system_info),a.length>0?c.message=Gue:c.message=`Successfully updated '${r}'`,c}o($ue,"updateNode");async function Vue(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let a=t[s],c=!1;for(let l=0,u=e.subscriptions.length;l<u;l++){let d=n.subscriptions[l];if(d.schema===a.schema&&d.table===a.table){d.publish=a.publish,d.subscribe=a.subscribe,c=!0;break}}c||n.subscriptions.push(new Bue(a.schema,a.table,a.publish,a.subscribe))}n.system_info=r,await zh.upsertNodeRecord(n),Fue({type:"nats_update"})}o(Vue,"updateNodeTable")});var gV=M((aUe,_V)=>{"use strict";var EV=require("joi"),{string:hV}=EV.types(),Kue=ut(),pV=(k(),v(W)),Yue=oe(),Wue=It();_V.exports=zue;function zue(e){let t=hV.invalid(Yue.get(pV.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(Wue.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=EV.object({operation:hV.valid(pV.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return Kue.validateBySchema(e,r)}o(zue,"removeNodeValidator")});var KS=M((lUe,AV)=>{"use strict";var{handleHDBError:SV,hdbErrors:jue}=ge(),{HTTP_STATUS_CODES:TV}=jue,Que=gV(),jh=Q(),RV=qo(),Jue=ie(),kd=(k(),v(W)),yV=It(),EO=pr(),_O=oe(),{RemotePayloadObject:Xue}=qh(),{NodeSubscription:Zue}=Ud(),ede=Hm(),tde=pl(),{broadcast:rde}=nt(),{setNode:nde}=(Hd(),v(Fd)),sde=_O.get(kd.CONFIG_PARAMS.CLUSTERING_NODENAME);AV.exports=ide;async function ide(e){if(jh.trace("removeNode called with:",e),_O.get(kd.CONFIG_PARAMS.REPLICATION_URL)??_O.get(kd.CONFIG_PARAMS.REPLICATION_HOSTNAME))return nde(e);RV.checkClusteringEnabled();let t=Que(e);if(t)throw SV(t,t.message,TV.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await RV.getNodeRecord(r);if(Jue.isEmptyOrZeroLength(n))throw SV(new Error,`Node '${r}' was not found.`,TV.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new Xue(kd.OPERATIONS_ENUM.REMOVE_NODE,sde,[]),i,a=!1;for(let l=0,u=n.subscriptions.length;l<u;l++){let d=n.subscriptions[l];d.subscribe===!0&&await EO.updateConsumerIterator(d.schema,d.table,r,"stop");try{await EO.updateRemoteConsumer(new Zue(d.schema,d.table,!1,!1),r)}catch(f){jh.error(f)}}try{i=await EO.request(`${r}.${yV.REQUEST_SUFFIX}`,s),jh.trace("Remove node reply from remote node:",r,i)}catch(l){jh.error("removeNode received error from request:",l),a=!0}let c=new ede(kd.SYSTEM_SCHEMA_NAME,kd.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await tde.deleteRecord(c),rde({type:"nats_update"}),i?.status===yV.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||a?(jh.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`}o(ide,"removeNode")});var NV=M((dUe,IV)=>{"use strict";var bV=require("joi"),{string:ode,array:ade}=bV.types(),cde=ut(),lde=US();IV.exports=ude;function ude(e){let t=bV.object({operation:ode.valid("configure_cluster").required(),connections:ade.items(lde.validationSchema).required()});return cde.validateBySchema(e,t)}o(ude,"configureClusterValidator")});var gO=M((mUe,LV)=>{"use strict";var wV=(k(),v(W)),YS=Q(),dde=ie(),fde=oe(),mde=KS(),hde=$S(),pde=qo(),Ede=NV(),{handleHDBError:OV,hdbErrors:_de}=ge(),{HTTP_STATUS_CODES:CV}=_de,gde="Configure cluster complete.",Sde="Failed to configure the cluster. Check the logs for more details.",Tde="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";LV.exports=Rde;async function Rde(e){YS.trace("configure cluster called with:",e);let t=Ede(e);if(t)throw OV(t,t.message,CV.BAD_REQUEST,void 0,void 0,!0);let r=await pde.getAllNodeRecords(),n=[];if(fde.get(wV.CONFIG_PARAMS.CLUSTERING_ENABLED)){for(let d=0,f=r.length;d<f;d++){let m=await PV(mde,{operation:wV.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[d].name},r[d].name);n.push(m)}YS.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 PV(hde,f,f.node_name);s.push(m)}YS.trace("All results from configure_cluster add node:",s);let a=[],c=[],l=!1,u=n.concat(s);for(let d=0,f=u.length;d<f;d++){let m=u[d];m.status==="rejected"&&(YS.error(m.node_name,m?.error?.message,m?.error?.stack),a.includes(m.node_name)||a.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(dde.isEmptyOrZeroLength(a))return{message:gde,connections:c};if(l)return{message:Tde,failed_nodes:a,connections:c};throw OV(new Error,Sde,CV.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}o(Rde,"configureCluster");async function PV(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}o(PV,"functionWrapper")});var UV=M((pUe,vV)=>{"use strict";var Qh=require("joi"),yde=ut(),{validateSchemaExists:DV,validateTableExists:Ade,validateSchemaName:MV}=ki(),bde=Qh.object({operation:Qh.string().valid("purge_stream"),schema:Qh.string().custom(DV).custom(MV).optional(),database:Qh.string().custom(DV).custom(MV).optional(),table:Qh.string().custom(Ade).required()});function Ide(e){return yde.validateBySchema(e,bde)}o(Ide,"purgeStreamValidator");vV.exports=Ide});var SO=M((_Ue,xV)=>{"use strict";var{handleHDBError:Nde,hdbErrors:wde}=ge(),{HTTP_STATUS_CODES:Ode}=wde,Cde=UV(),Pde=pr(),Lde=qo();xV.exports=Dde;async function Dde(e){e.schema=e.schema??e.database;let t=Cde(e);if(t)throw Nde(t,t.message,Ode.BAD_REQUEST,void 0,void 0,!0);Lde.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await Pde.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}o(Dde,"purgeStream")});var yO=M((SUe,$V)=>{"use strict";var RO=qo(),Mde=pr(),zS=oe(),Gd=(k(),v(W)),vl=It(),vde=ie(),TO=Q(),{RemotePayloadObject:Ude}=qh(),{ErrorCode:BV}=require("nats"),{parentPort:FV}=require("worker_threads"),{onMessageByType:xde}=nt(),{getThisNodeName:Bde}=(is(),v(Fo)),{requestClusterStatus:Fde}=(Mh(),v(aq)),{getReplicationSharedStatus:Hde,getHDBNodeTable:kde}=(Nl(),v(cw)),{CONFIRMATION_STATUS_POSITION:Gde,RECEIVED_VERSION_POSITION:qde,RECEIVED_TIME_POSITION:$de,SENDING_TIME_POSITION:Vde,RECEIVING_STATUS_POSITION:Kde,RECEIVING_STATUS_RECEIVING:Yde}=(Mw(),v(Jq)),HV=zS.get(Gd.CONFIG_PARAMS.CLUSTERING_ENABLED),kV=zS.get(Gd.CONFIG_PARAMS.CLUSTERING_NODENAME);$V.exports={clusterStatus:Wde,buildNodeStatus:qV};var GV;xde("cluster-status",async e=>{GV(e)});async function Wde(){if(zS.get(Gd.CONFIG_PARAMS.REPLICATION_URL)||zS.get(Gd.CONFIG_PARAMS.REPLICATION_HOSTNAME)){let n;if(FV){FV.postMessage({type:"request-cluster-status"}),n=await new Promise(i=>{GV=i});for(let i of n.connections){let a=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=Hde(u,l,a);c.lastCommitConfirmed=WS(d[Gde]),c.lastReceivedRemoteTime=WS(d[qde]),c.lastReceivedLocalTime=WS(d[$de]),c.sendingMessage=WS(d[Vde]),c.lastReceivedStatus=d[Kde]===Yde?"Receiving":"Waiting"}}}else n=Fde();n.node_name=Bde();let s=kde().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:kV,is_enabled:HV,connections:[]};if(!HV)return e;let t=await RO.getAllNodeRecords();if(vde.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(qV(t[n],e.connections));return await Promise.allSettled(r),e}o(Wde,"clusterStatus");function WS(e){return e?e===1?"Copying":new Date(e).toUTCString():void 0}o(WS,"asDate");async function qV(e,t){let r=e.name,n=new Ude(Gd.OPERATIONS_ENUM.CLUSTER_STATUS,kV,void 0,await RO.getSystemInfo()),s,i,a=vl.CLUSTER_STATUS_STATUSES.OPEN;try{let l=Date.now();s=await Mde.request(vl.REQUEST_SUBJECT(r),n),i=Date.now()-l,s.status===vl.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(a=vl.CLUSTER_STATUS_STATUSES.CLOSED,TO.error(`Error getting node status from ${r} `,s))}catch(l){TO.warn(`Error getting node status from ${r}`,l),l.code===BV.NoResponders?a=vl.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:l.code===BV.Timeout?a=vl.CLUSTER_STATUS_STATUSES.TIMEOUT:a=vl.CLUSTER_STATUS_STATUSES.CLOSED}let c=new zde(r,a,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!==Gd.PRE_4_0_0_VERSION&&await RO.upsertNodeRecord(l)}catch(l){TO.error("Cluster status encountered an error updating system info for node:",r,l)}t.push(c)}o(qV,"buildNodeStatus");function zde(e,t,r,n,s,i,a,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:n},this.latency_ms=s,this.uptime=i,this.subscriptions=a,this.system_info=c}o(zde,"NodeStatusObject")});var bO=M((RUe,VV)=>{"use strict";var{handleHDBError:jde,hdbErrors:Qde}=ge(),{HTTP_STATUS_CODES:Jde}=Qde,Xde=pr(),Zde=qo(),AO=ie(),jS=require("joi"),efe=ut(),tfe=2e3,rfe=jS.object({timeout:jS.number().min(1),connected_nodes:jS.boolean(),routes:jS.boolean()});VV.exports=nfe;async function nfe(e){Zde.checkClusteringEnabled();let t=efe.validateBySchema(e,rfe);if(t)throw jde(t,t.message,Jde.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||AO.autoCastBoolean(n),a=s===void 0||AO.autoCastBoolean(s),c={nodes:[]},l=await Xde.getServerList(r??tfe),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,h=l[d].data;if(m.name.endsWith("-hub")){let p={name:m.name.slice(0,-4),response_time:l[d].response_time};i&&(p.connected_nodes=[],u[m.name]&&u[m.name].forEach(_=>{p.connected_nodes.includes(_.name.slice(0,-4))||p.connected_nodes.push(_.name.slice(0,-4))})),a&&(p.routes=h.cluster?.urls?h.cluster?.urls.map(_=>({host:_.split(":")[0],port:AO.autoCast(_.split(":")[1])})):[]),c.nodes.push(p)}}return c}o(nfe,"clusterNetwork")});var zV=M((AUe,WV)=>{"use strict";var IO=require("joi"),KV=ut(),{routeConstraints:YV}=$I();WV.exports={setRoutesValidator:sfe,deleteRoutesValidator:ife};function sfe(e){let t=IO.object({server:IO.valid("hub","leaf"),routes:YV.required()});return KV.validateBySchema(e,t)}o(sfe,"setRoutesValidator");function ife(e){let t=IO.object({routes:YV.required()});return KV.validateBySchema(e,t)}o(ife,"deleteRoutesValidator")});var QS=M((IUe,t1)=>{"use strict";var Vo=bt(),NO=ie(),vs=(k(),v(W)),qd=oe(),jV=zV(),{handleHDBError:QV,hdbErrors:ofe}=ge(),{HTTP_STATUS_CODES:JV}=ofe,XV="cluster routes successfully set",ZV="cluster routes successfully deleted";t1.exports={setRoutes:cfe,getRoutes:lfe,deleteRoutes:ufe};function afe(e){let t=Vo.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 a=0,c=e.routes.length;a<c;a++){let l=e.routes[a];l.port=NO.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"?Vo.updateConfigValue(vs.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,r):Vo.updateConfigValue(vs.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,r),{message:XV,set:i,skipped:s}}o(afe,"setRoutesNats");function cfe(e){let t=jV.setRoutesValidator(e);if(t)throw QV(t,t.message,JV.BAD_REQUEST,void 0,void 0,!0);if(qd.get(vs.CONFIG_PARAMS.CLUSTERING_ENABLED))return afe(e);let r=[],n=[],s=qd.get(vs.CONFIG_PARAMS.REPLICATION_ROUTES)??[];return e.routes.forEach(i=>{e1(s,i)?n.push(i):(s.push(i),r.push(i))}),Vo.updateConfigValue(vs.CONFIG_PARAMS.REPLICATION_ROUTES,s),{message:XV,set:r,skipped:n}}o(cfe,"setRoutes");function e1(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}o(e1,"existsInArray");function lfe(){if(qd.get(vs.CONFIG_PARAMS.CLUSTERING_ENABLED)){let e=Vo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}else return qd.get(vs.CONFIG_PARAMS.REPLICATION_ROUTES)??[]}o(lfe,"getRoutes");function ufe(e){let t=jV.deleteRoutesValidator(e);if(t)throw QV(t,t.message,JV.BAD_REQUEST,void 0,void 0,!0);if(qd.get(vs.CONFIG_PARAMS.CLUSTERING_ENABLED))return dfe(e);let r=[],n=[],s=qd.get(vs.CONFIG_PARAMS.REPLICATION_ROUTES)??[],i=[];return s.forEach(a=>{e1(e.routes,a)?r.push(a):(i.push(a),n.push(a))}),Vo.updateConfigValue(vs.CONFIG_PARAMS.REPLICATION_ROUTES,i),{message:ZV,deleted:r,skipped:n}}o(ufe,"deleteRoutes");function dfe(e){let t=Vo.getClusteringRoutes(),r=t.hub_routes,n=t.leaf_routes,s=[],i=[],a=!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,h=r.length;m<h;m++){let p=r[m];if(d.host===p.host&&d.port===p.port){r.splice(m,1),f=!0,a=!0,s.push(d);break}}if(!f){let m=!0;for(let h=0,p=n.length;h<p;h++){let _=n[h];if(d.host===_.host&&d.port===_.port){n.splice(h,1),c=!0,m=!1,s.push(d);break}}m&&i.push(d)}}return a&&(r=NO.isEmptyOrZeroLength(r)?null:r,Vo.updateConfigValue(vs.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,r)),c&&(n=NO.isEmptyOrZeroLength(n)?null:n,Vo.updateConfigValue(vs.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:ZV,deleted:s,skipped:i}}o(dfe,"deleteRoutesNats")});var n1=M((wUe,r1)=>{"use strict";var Jh=require("alasql"),Ul=require("recursive-iterator"),_i=Q(),ffe=ie(),Xh=(k(),v(W)),wO=class{static{o(this,"sqlStatementBucket")}constructor(t){this.ast=t,this.affected_attributes=new Map,this.table_lookup=new Map,this.schema_lookup=new Map,this.table_to_schema_lookup=new Map,hfe(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(s=>Xh.SEARCH_WILDCARDS.includes(s.columnid));if(r.length===0)return this.ast;let n=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(s=>!Xh.SEARCH_WILDCARDS.includes(s.columnid)),r.forEach(s=>{let i=this.table_to_schema_lookup.has(s.tableid)?this.table_to_schema_lookup.get(s.tableid):n,a=this.table_lookup.has(s.tableid)?this.table_lookup.get(s.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[a]&&t[i].tables[a][Xh.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[a].attribute_permissions.length>0?c=mfe(t[i].tables[a].attribute_permissions):c=global.hdb_schema[i][a].attributes.map(u=>({attribute_name:u.attribute}));let l=this.affected_attributes.get(i).get(a).filter(u=>!Xh.SEARCH_WILDCARDS.includes(u));c.forEach(({attribute_name:u})=>{let d=new Jh.yy.Column({columnid:u});s.tableid&&(d.tableid=s.tableid),this.ast.columns.push(d),l.includes(u)||l.push(u)}),this.affected_attributes.get(i).set(a,l)}}),this.ast}};function mfe(e){return e.filter(t=>t[Xh.PERMS_CRUD_ENUM.READ])}o(mfe,"filterReadRestrictedAttrs");function hfe(e,t,r,n,s){pfe(e,t,r,n,s)}o(hfe,"interpretAST");function Zh(e,t,r,n,s){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),n&&!n.has(e.as)&&n.set(e.as,e.databaseid)),s)){let i=e.databaseid,a=e.tableid;e.as&&(a=e.as),s.set(a,i)}}o(Zh,"addSchemaTableToMap");function pfe(e,t,r,n,s){if(!e){_i.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Jh.yy.Insert?Sfe(e,t,r):e instanceof Jh.yy.Select?Efe(e,t,r,n,s):e instanceof Jh.yy.Update?_fe(e,t,r):e instanceof Jh.yy.Delete?gfe(e,t,r):_i.error("AST in getRecordAttributesAST() is not a valid SQL type.")}o(pfe,"getRecordAttributesAST");function Efe(e,t,r,n,s){if(!e){_i.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(ffe.isEmptyOrZeroLength(i)){_i.error("No schema specified");return}e.from.forEach(c=>{Zh(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),Zh(c.table,t,r,n,s)});let a=new Ul(e.columns);for(let{node:c}of a)if(c&&c.columnid){let l=c.tableid,u=n.has(l)?n.get(l):i;if(l||(l=e.from[0].tableid),!t.get(u).has(l))if(r.has(l))l=r.get(l);else{_i.info(`table specified as ${l} not found.`);return}t.get(u).get(l).indexOf(c.columnid)<0&&t.get(u).get(l).push(c.columnid)}if(e.where){let c=new Ul(e.where),l=e.from[0].tableid;for(let{node:u}of c)if(u&&u.columnid){let d=u.tableid?u.tableid:l;if(!t.get(i).has(d))if(r.has(d))d=r.get(d);else{_i.info(`table specified as ${d} not found.`);continue}t.get(i).get(d).indexOf(u.columnid)<0&&t.get(i).get(d).push(u.columnid)}}if(e.joins&&e.joins.forEach(c=>{let l=new Ul(c.on);for(let{node:u}of l)if(u&&u.columnid){let d=u.tableid,f=s.get(d);if(!t.get(f).has(d))if(r.has(d))d=r.get(d);else{_i.info(`table specified as ${d} not found.`);continue}t.get(f).get(d).indexOf(u.columnid)<0&&t.get(f).get(d).push(u.columnid)}}),e.order){let c=new Ul(e.order);for(let{node:l}of c)if(l&&l.columnid){let u=l.tableid,d=n.has(u)?n.get(u):i;if(u||(u=e.from[0].tableid),!t.get(d).has(u))if(r.has(u))u=r.get(u);else{_i.info(`table specified as ${u} not found.`);return}t.get(d).get(u).indexOf(l.columnid)<0&&t.get(d).get(u).push(l.columnid)}}}o(Efe,"getSelectAttributes");function _fe(e,t,r){if(!e){_i.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new Ul(e.columns),s=e.table.databaseid;Zh(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&OO(e.table.tableid,s,i.columnid,t,r)}o(_fe,"getUpdateAttributes");function gfe(e,t,r){if(!e){_i.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new Ul(e.where),s=e.table.databaseid;Zh(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&OO(e.table.tableid,s,i.columnid,t,r)}o(gfe,"getDeleteAttributes");function Sfe(e,t,r){if(!e){_i.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new Ul(e.columns),s=e.into.databaseid;Zh(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&OO(e.into.tableid,s,i.columnid,t,r)}o(Sfe,"getInsertAttributes");function OO(e,t,r,n,s){if(!n.get(t))return;let i=e;n.get(t).has(i)||(i=s.get(i)),n.get(t).get(i).push(r)}o(OO,"pushAttribute");r1.exports=wO});var i1=M((CUe,s1)=>{"use strict";var JS=(k(),v(W)),XS=class{static{o(this,"BaseLicense")}constructor(t=0,r=JS.RAM_ALLOCATION_ENUM.DEFAULT,n=JS.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},CO=class extends XS{static{o(this,"ExtendedLicense")}constructor(t=0,r=JS.RAM_ALLOCATION_ENUM.DEFAULT,n=JS.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};s1.exports={BaseLicense:XS,ExtendedLicense:CO}});var Kd=M((LUe,d1)=>{"use strict";var Vd=require("fs-extra"),ZS=(hg(),v(mg)),a1=require("crypto"),Tfe=require("moment"),Rfe=require("uuid").v4,fn=Q(),LO=require("path"),yfe=ie(),xl=(k(),v(W)),{totalmem:o1}=require("os"),Afe=i1().ExtendedLicense,$d="invalid license key format",bfe="061183",Ife="mofi25",Nfe="aes-256-cbc",wfe=16,Ofe=32,c1=oe(),{resolvePath:l1}=bt();c1.initSync();var PO;d1.exports={validateLicense:u1,generateFingerPrint:Pfe,licenseSearch:vO,getLicense:Mfe,checkMemoryLimit:vfe};function DO(){return LO.join(c1.getHdbBasePath(),xl.LICENSE_KEY_DIR_NAME,xl.LICENSE_FILE_NAME)}o(DO,"getLicenseDirPath");function Cfe(){let e=DO();return l1(LO.join(e,xl.LICENSE_FILE_NAME))}o(Cfe,"getLicenseFilePath");function MO(){let e=DO();return l1(LO.join(e,xl.REG_KEY_FILE_NAME))}o(MO,"getFingerPrintFilePath");async function Pfe(){let e=MO();try{return await Vd.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await Lfe();throw fn.error(`Error writing fingerprint file to ${e}`),fn.error(t),new Error("There was an error generating the fingerprint")}}o(Pfe,"generateFingerPrint");async function Lfe(){let e=Rfe(),t=ZS.hash(e,ZS.HASH_FUNCTION.MD5),r=MO();try{await Vd.mkdirp(DO()),await Vd.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw fn.error(`Error writing fingerprint file to ${r}`),fn.error(n),new Error("There was an error generating the fingerprint")}return t}o(Lfe,"writeFingerprint");function u1(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:xl.RAM_ALLOCATION_ENUM.DEFAULT,version:xl.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return fn.error("empty license key passed to validate."),r;let n=MO(),s=!1;try{s=Vd.statSync(n)}catch(i){fn.error(i)}if(s){let i;try{i=Vd.readFileSync(n,"utf8")}catch{fn.error("error validating this machine in the license"),r.valid_machine=!1;return}let a=e.split(Ife),c=a[1];c=Buffer.concat([Buffer.from(c)],wfe);let l=Buffer.concat([Buffer.from(i)],Ofe),u=a1.createDecipheriv(Nfe,l,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let d=null;try{d=u.update(a[0],"hex","utf8"),d.trim(),d+=u.final("utf8")}catch{let h=Dfe(a[0],i);if(h)d=h;else throw r.valid_license=!1,r.valid_machine=!1,console.error($d),fn.error($d),new Error($d)}let f;if(isNaN(d))try{f=JSON.parse(d),r.version=f.version,r.exp_date=f.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),f.ram_allocation&&(r.ram_allocation=f.ram_allocation)}catch{throw console.error($d),fn.error($d),new Error($d)}else r.exp_date=d;r.exp_date<Tfe().valueOf()&&(r.valid_date=!1),ZS.validate(a[1],`${bfe}${i}${t}`,ZS.HASH_FUNCTION.MD5)||(r.valid_license=!1)}else r.valid_license=!1,r.valid_machine=!1;return r.valid_license&&r.valid_machine&&r.valid_date||fn.error("Invalid licence"),r}o(u1,"validateLicense");function Dfe(e,t){try{let r=a1.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{fn.warn("Check old license failed")}}o(Dfe,"checkOldLicense");function vO(){let e=new Afe,t=[];try{t=Vd.readFileSync(Cfe(),"utf-8").split(`\r
17
- `)}catch(r){r.code==="ENOENT"?fn.debug("no license file found"):fn.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(yfe.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=u1(s.license_key,s.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(s){fn.error("There was an error parsing the license string."),fn.error(s),e.ram_allocation=xl.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return PO=e,e}o(vO,"licenseSearch");async function Mfe(){return PO||await vO(),PO}o(Mfe,"getLicense");function vfe(){let e=vO().ram_allocation,t=process.constrainedMemory?.()||o1();if(t=Math.round(Math.min(t,o1())/2**20),t>e)return`This server has more memory (${t}MB) than HarperDB is licensed for (${e}MB), this should only be used for educational and development purposes.`}o(vfe,"checkMemoryLimit")});var BO=M((MUe,p1)=>{var eT=Kd(),f1=require("chalk"),ls=Q(),m1=require("prompt"),{promisify:Ufe}=require("util"),UO=(k(),v(W)),xfe=require("fs-extra"),Bfe=require("path"),Ffe=ie(),{packageJson:Hfe}=Rt(),h1=oe();h1.initSync();var kfe=require("moment"),Gfe=Ufe(m1.get),qfe=Bfe.join(h1.getHdbBasePath(),UO.LICENSE_KEY_DIR_NAME,UO.LICENSE_FILE_NAME,UO.LICENSE_FILE_NAME);p1.exports={getFingerprint:Vfe,setLicense:$fe,parseLicense:xO,register:Kfe,getRegistrationInfo:Wfe};async function $fe(e){if(e&&e.key&&e.company){try{ls.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await xO(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw ls.error(r),ls.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}o($fe,"setLicense");async function Vfe(){let e={};try{e=await eT.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw ls.error(r),ls.error(t),new Error(r)}return e}o(Vfe,"getFingerprint");async function xO(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");ls.info("Validating license input...");let r=eT.validateLicense(e,t);if(ls.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(ls.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(ls.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{ls.info("writing license to disk"),await xfe.writeFile(qfe,JSON.stringify({license_key:e,company:t}))}catch(n){throw ls.error("Failed to write License"),n}return"Registration successful."}o(xO,"parseLicense");async function Kfe(){let e=await Yfe();return xO(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}o(Kfe,"register");async function Yfe(){let e=await eT.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:f1.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:f1.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{m1.start()}catch(n){ls.error(n)}let r;try{r=await Gfe(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}o(Yfe,"promptForRegistration");async function Wfe(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await eT.getLicense()}catch(r){throw ls.error(`There was an error when searching licenses due to: ${r.message}`),r}if(Ffe.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=Hfe.version,e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=kfe.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}o(Wfe,"getRegistrationInfo")});var _1=M((UUe,E1)=>{"use strict";var zfe=It(),FO=class{static{o(this,"HubConfigObject")}constructor(t,r,n,s,i,a,c,l,u,d,f,m,h,p){this.port=t,a===null&&(a=void 0),this.server_name=r+zfe.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:a,insecure:c,verify:l},this.leafnodes={port:u,tls:{cert_file:s,key_file:i,ca_file:a,insecure:c}},this.cluster={name:d,port:f,routes:m,tls:{cert_file:s,key_file:i,ca_file:a,insecure:c,verify:l}},this.accounts={SYS:{users:h},HDB:{users:p}},this.system_account="SYS"}};E1.exports=FO});var T1=M((BUe,S1)=>{"use strict";var g1=It(),HO=class{static{o(this,"LeafConfigObject")}constructor(t,r,n,s,i,a,c,l,u,d,f){this.port=t,f===null&&(f=void 0),this.server_name=r+g1.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+g1.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:a,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:l,jetstream:"enabled"}},this.system_account="SYS"}};S1.exports=HO});var y1=M((HUe,R1)=>{"use strict";var kO=class{static{o(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};R1.exports=kO});var b1=M((GUe,A1)=>{"use strict";var jfe=It(),GO=class{static{o(this,"SysUserObject")}constructor(t,r){this.user=t+jfe.SERVER_SUFFIX.ADMIN,this.password=r}};A1.exports=GO});var sT=M(($Ue,w1)=>{"use strict";var Bl=require("path"),Fl=require("fs-extra"),Qfe=_1(),Jfe=T1(),Xfe=y1(),Zfe=b1(),qO=rs(),Wd=ie(),Bn=bt(),rT=(k(),v(W)),ep=It(),{CONFIG_PARAMS:rr}=rT,zd=Q(),tp=oe(),I1=Vi(),$O=pr(),eme=as(),Yd="clustering",tme=1e4,N1=50;w1.exports={generateNatsConfig:nme,removeNatsConfig:sme,getHubConfigPath:rme};function rme(){let e=tp.get(rr.ROOTPATH);return Bl.join(e,Yd,ep.NATS_CONFIG_FILES.HUB_SERVER)}o(rme,"getHubConfigPath");async function nme(e=!1,t=void 0){console.error("Warning: NATS replication is deprecated and will be removed in version 5.0 of Harper");let r=tp.get(rr.ROOTPATH);Fl.ensureDirSync(Bl.join(r,"clustering","leaf")),tp.initSync();let n=Bn.getConfigFromFile(rr.CLUSTERING_TLS_CERT_AUTH),s=Bn.getConfigFromFile(rr.CLUSTERING_TLS_PRIVATEKEY),i=Bn.getConfigFromFile(rr.CLUSTERING_TLS_CERTIFICATE);!await Fl.exists(i)&&!await Fl.exists(!n)&&await eme.createNatsCerts();let a=Bl.join(r,Yd,ep.PID_FILES.HUB),c=Bl.join(r,Yd,ep.PID_FILES.LEAF),l=Bn.getConfigFromFile(rr.CLUSTERING_LEAFSERVER_STREAMS_PATH),u=Bl.join(r,Yd,ep.NATS_CONFIG_FILES.HUB_SERVER),d=Bl.join(r,Yd,ep.NATS_CONFIG_FILES.LEAF_SERVER),f=Bn.getConfigFromFile(rr.CLUSTERING_TLS_INSECURE),m=Bn.getConfigFromFile(rr.CLUSTERING_TLS_VERIFY),h=Bn.getConfigFromFile(rr.CLUSTERING_NODENAME),p=Bn.getConfigFromFile(rr.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await $O.checkNATSServerInstalled()||nT("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let _=await qO.listUsers(),g=Bn.getConfigFromFile(rr.CLUSTERING_USER),y=await qO.getClusterUser();(Wd.isEmpty(y)||y.active!==!0)&&nT(`Invalid cluster user '${cluster_username}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await tT(rr.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await tT(rr.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await tT(rr.CLUSTERING_HUBSERVER_NETWORK_PORT),await tT(rr.CLUSTERING_LEAFSERVER_NETWORK_PORT));let T=[],R=[];for(let[q,K]of _.entries())K.role?.role===rT.ROLE_TYPES_ENUM.CLUSTER_USER&&K.active&&(T.push(new Zfe(K.username,I1.decrypt(K.hash))),R.push(new Xfe(K.username,I1.decrypt(K.hash))));let N=[],{hub_routes:O}=Bn.getClusteringRoutes();if(!Wd.isEmptyOrZeroLength(O))for(let q of O)N.push(`tls://${y.sys_name_encoded}:${y.uri_encoded_d_hash}@${q.host}:${q.port}`);let F=new Qfe(Bn.getConfigFromFile(rr.CLUSTERING_HUBSERVER_NETWORK_PORT),h,a,i,s,n,f,m,p,Bn.getConfigFromFile(rr.CLUSTERING_HUBSERVER_CLUSTER_NAME),Bn.getConfigFromFile(rr.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),N,T,R);n==null&&(delete F.tls.ca_file,delete F.leafnodes.tls.ca_file),t=Wd.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===rT.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await Fl.writeJson(u,F),zd.trace(`Hub server config written to ${u}`));let Z=`tls://${y.sys_name_encoded}:${y.uri_encoded_d_hash}@0.0.0.0:${p}`,G=`tls://${y.uri_encoded_name}:${y.uri_encoded_d_hash}@0.0.0.0:${p}`,Y=new Jfe(Bn.getConfigFromFile(rr.CLUSTERING_LEAFSERVER_NETWORK_PORT),h,c,l,[Z],[G],T,R,i,s,n,f);n==null&&delete Y.tls.ca_file,(t===void 0||t===rT.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await Fl.writeJson(d,Y),zd.trace(`Leaf server config written to ${d}`))}o(nme,"generateNatsConfig");async function tT(e){let t=tp.get(e);return Wd.isEmpty(t)&&nT(`port undefined for '${e}'`),await Wd.isPortTaken(t)&&nT(`'${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}o(tT,"isPortAvailable");function nT(e){let t=`Error generating clustering config: ${e}`;zd.error(t),console.error(t),process.exit(1)}o(nT,"generateNatsConfigError");async function sme(e){let{port:t,config_file:r}=$O.getServerConfig(e),{username:n,decrypt_hash:s}=await qO.getClusterUser(),i=0,a=2e3;for(;i<N1;){try{let d=await $O.createConnection(t,n,s,!1);if(d.protocol.connected===!0){d.close();break}}catch(d){zd.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${d}`)}if(i++,i>=N1)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=a*(i*2);u>3e4&&zd.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await Wd.asyncSetTimeout(u)}let c="0".repeat(tme),l=Bl.join(tp.get(rr.ROOTPATH),Yd,r);await Fl.writeFile(l,c),await Fl.remove(l),zd.notify(e,"started.")}o(sme,"removeNatsConfig")});var M1=M((KUe,D1)=>{"use strict";var us=oe(),ime=Kd(),Ke=(k(),v(W)),rp=It(),Ko=require("path"),{PACKAGE_ROOT:oT}=Rt(),O1=oe(),iT=ie(),jd="/dev/null",ome=Ko.join(oT,"launchServiceScripts"),C1=Ko.join(oT,"utility/scripts"),ame=Ko.join(C1,Ke.HDB_RESTART_SCRIPT),P1=Ko.resolve(oT,"dependencies",`${process.platform}-${process.arch}`,rp.NATS_BINARY_NAME);function L1(){let t=ime.licenseSearch().ram_allocation||Ke.RAM_ALLOCATION_ENUM.DEFAULT,r=Ke.MEM_SETTING_KEY+t,n={[Ke.PROCESS_NAME_ENV_PROP]:Ke.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return iT.noBootFile()&&(n[Ke.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=iT.getEnvCliRootPath()),{name:Ke.PROCESS_DESCRIPTORS.HDB,script:Ke.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:oT}}o(L1,"generateMainServerConfig");var cme=9930;function lme(){us.initSync(!0);let e=us.get(Ke.CONFIG_PARAMS.ROOTPATH),t=Ko.join(e,"clustering",rp.NATS_CONFIG_FILES.HUB_SERVER),r=Ko.join(us.get(Ke.HDB_SETTINGS_NAMES.LOG_PATH_KEY),Ke.LOG_NAMES.HDB),n=O1.get(Ke.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=rp.LOG_LEVEL_FLAGS[us.get(Ke.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:Ke.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==cme?"-"+n:""),script:P1,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[Ke.PROCESS_NAME_ENV_PROP]:Ke.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return us.get(Ke.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=jd,i.error_file=jd),i}o(lme,"generateNatsHubServerConfig");var ume=9940;function dme(){us.initSync(!0);let e=us.get(Ke.CONFIG_PARAMS.ROOTPATH),t=Ko.join(e,"clustering",rp.NATS_CONFIG_FILES.LEAF_SERVER),r=Ko.join(us.get(Ke.HDB_SETTINGS_NAMES.LOG_PATH_KEY),Ke.LOG_NAMES.HDB),n=O1.get(Ke.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=rp.LOG_LEVEL_FLAGS[us.get(Ke.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:Ke.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==ume?"-"+n:""),script:P1,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[Ke.PROCESS_NAME_ENV_PROP]:Ke.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return us.get(Ke.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=jd,i.error_file=jd),i}o(dme,"generateNatsLeafServerConfig");function fme(){us.initSync();let e=Ko.join(us.get(Ke.CONFIG_PARAMS.LOGGING_ROOT),Ke.LOG_NAMES.HDB),t={name:Ke.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:Ke.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[Ke.PROCESS_NAME_ENV_PROP]:Ke.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:ome,autorestart:!1};return us.get(Ke.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=jd,t.error_file=jd),t}o(fme,"generateClusteringUpgradeV4ServiceConfig");function mme(){let e={[Ke.PROCESS_NAME_ENV_PROP]:Ke.PROCESS_DESCRIPTORS.RESTART_HDB};return iT.noBootFile()&&(e[Ke.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=iT.getEnvCliRootPath()),{...{name:Ke.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:C1},script:ame}}o(mme,"generateRestart");function hme(){return{apps:[L1()]}}o(hme,"generateAllServiceConfigs");D1.exports={generateAllServiceConfigs:hme,generateMainServerConfig:L1,generateRestart:mme,generateNatsHubServerConfig:lme,generateNatsLeafServerConfig:dme,generateClusteringUpgradeV4ServiceConfig:fme}});var sp=M((zUe,W1)=>{"use strict";var ct=(k(),v(W)),pme=ie(),Wo=sT(),aT=pr(),Yo=It(),oc=M1(),cT=oe(),Hl=Q(),Eme=qo(),{startWorker:v1,onMessageFromWorkers:_me}=nt(),gme=Bd(),WUe=require("util"),Sme=require("child_process"),Tme=require("fs"),{execFile:Rme}=Sme,je;W1.exports={enterPM2Mode:yme,start:ac,stop:VO,reload:x1,restart:B1,list:KO,describe:k1,connect:zo,kill:wme,startAllServices:Ome,startService:YO,getUniqueServicesList:G1,restartAllServices:Cme,isServiceRegistered:q1,reloadStopStart:$1,restartHdb:H1,deleteProcess:Ime,startClusteringProcesses:K1,startClusteringThreads:Y1,isHdbRestartRunning:Nme,isClusteringRunning:Lme,stopClustering:Pme,reloadClustering:Dme,expectedRestartOfChildren:F1};var np=!1;_me(e=>{e.type==="restart"&&cT.initSync(!0)});function yme(){np=!0}o(yme,"enterPM2Mode");function zo(){return je||(je=require("pm2")),new Promise((e,t)=>{je.connect((r,n)=>{r&&t(r),e(n)})})}o(zo,"connect");var mn,Ame=10,U1;function ac(e,t=!1){if(np)return bme(e);let r=Rme(e.script,e.args.split(" "),e);r.name=e.name,r.config=e,r.on("exit",async i=>{let a=mn.indexOf(r);a>-1&&mn.splice(a,1),!U1&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<Ame&&(Tme.existsSync(Wo.getHubConfigPath())?ac(e):(await Wo.generateNatsConfig(!0),ac(e),await new Promise(c=>setTimeout(c,3e3)),await Wo.removeNatsConfig(ct.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Wo.removeNatsConfig(ct.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let a=cT.get(ct.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,l,u=0,d;for(;l=c.exec(i);){if(l.index&&Yo.LOG_LEVEL_HIERARCHY[a]>=Yo.LOG_LEVEL_HIERARCHY[d||"info"]){let h=d===Yo.LOG_LEVELS.ERR||d===Yo.LOG_LEVELS.WRN?Hl.OUTPUTS.STDERR:Hl.OUTPUTS.STDOUT;Hl.logCustomLevel(d||"info",h,n,i.slice(u,l.index).trim())}let[f,m]=l;u=l.index+f.length,d=Yo.LOG_LEVELS[m]}if(Yo.LOG_LEVEL_HIERARCHY[a]>=Yo.LOG_LEVEL_HIERARCHY[d||"info"]){let f=d===Yo.LOG_LEVELS.ERR||d===Yo.LOG_LEVELS.WRN?Hl.OUTPUTS.STDERR:Hl.OUTPUTS.STDOUT;Hl.logCustomLevel(d||"info",f,n,i.slice(u).trim())}}if(o(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),!mn&&(mn=[],!t)){let i=o(()=>{U1=!0,mn&&(mn.map(a=>a.kill()),process.exit(0))},"killChildren");process.on("exit",i),process.on("SIGINT",i),process.on("SIGQUIT",i),process.on("SIGTERM",i)}mn.push(r)}o(ac,"start");function bme(e){return new Promise(async(t,r)=>{try{await zo()}catch(n){r(n)}je.start(e,(n,s)=>{n&&(je.disconnect(),r(n)),je.disconnect(),t(s)})})}o(bme,"startWithPM2");function VO(e){if(!np){for(let t of mn||[])t.name===e&&(mn.splice(mn.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await zo()}catch(n){r(n)}je.stop(e,async(n,s)=>{n&&(je.disconnect(),r(n)),je.delete(e,(i,a)=>{i&&(je.disconnect(),r(n)),je.disconnect(),t(a)})})})}o(VO,"stop");function x1(e){return new Promise(async(t,r)=>{try{await zo()}catch(n){r(n)}je.reload(e,(n,s)=>{n&&(je.disconnect(),r(n)),je.disconnect(),t(s)})})}o(x1,"reload");function B1(e){if(!np){F1();for(let t of mn||[])t.name===e&&t.kill()}return new Promise(async(t,r)=>{try{await zo()}catch(n){r(n)}je.restart(e,(n,s)=>{je.disconnect(),t(s)})})}o(B1,"restart");function F1(){for(let e of mn||[])e.config&&(e.config.restarts=0)}o(F1,"expectedRestartOfChildren");function Ime(e){return new Promise(async(t,r)=>{try{await zo()}catch(n){r(n)}je.delete(e,(n,s)=>{n&&(je.disconnect(),r(n)),je.disconnect(),t(s)})})}o(Ime,"deleteProcess");async function H1(){await ac(oc.generateRestart())}o(H1,"restartHdb");async function Nme(){let e=await KO();for(let t in e)if(e[t].name===ct.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}o(Nme,"isHdbRestartRunning");function KO(){return new Promise(async(e,t)=>{try{await zo()}catch(r){t(r)}je.list((r,n)=>{r&&(je.disconnect(),t(r)),je.disconnect(),e(n)})})}o(KO,"list");function k1(e){return new Promise(async(t,r)=>{try{await zo()}catch(n){r(n)}je.describe(e,(n,s)=>{n&&(je.disconnect(),r(n)),je.disconnect(),t(s)})})}o(k1,"describe");function wme(){if(!np){for(let e of mn||[])e.kill();mn=[];return}return new Promise(async(e,t)=>{try{await zo()}catch(r){t(r)}je.killDaemon((r,n)=>{r&&(je.disconnect(),t(r)),je.disconnect(),e(n)})})}o(wme,"kill");async function Ome(){try{await K1(),await Y1(),await ac(oc.generateAllServiceConfigs())}catch(e){throw je?.disconnect(),e}}o(Ome,"startAllServices");async function YO(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case ct.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=oc.generateMainServerConfig();break;case ct.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=oc.generateNatsIngestServiceConfig();break;case ct.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=oc.generateNatsReplyServiceConfig();break;case ct.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=oc.generateNatsHubServerConfig(),await ac(r,t),await Wo.removeNatsConfig(e);return;case ct.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=oc.generateNatsLeafServerConfig(),await ac(r,t),await Wo.removeNatsConfig(e);return;case ct.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=oc.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await ac(r)}catch(r){throw je?.disconnect(),r}}o(YO,"startService");async function G1(){try{let e=await KO(),t={};for(let r=0,n=e.length;r<n;r++){let s=e[r];t[s.name]===void 0&&(t[s.name]={name:s.name,exec_mode:s.pm2_env.exec_mode})}return t}catch(e){throw je?.disconnect(),e}}o(G1,"getUniqueServicesList");async function Cme(e=[]){try{let t=!1,r=await G1();for(let n=0,s=Object.values(r).length;n<s;n++){let a=Object.values(r)[n].name;e.includes(a)||(a===ct.PROCESS_DESCRIPTORS.HDB?t=!0:await B1(a))}t&&await $1(ct.PROCESS_DESCRIPTORS.HDB)}catch(t){throw je?.disconnect(),t}}o(Cme,"restartAllServices");async function q1(e){if(mn?.find(r=>r.name===e))return!0;let t=await gme.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}o(q1,"isServiceRegistered");async function $1(e){let t=cT.get(ct.CONFIG_PARAMS.THREADS_COUNT)??cT.get(ct.CONFIG_PARAMS.THREADS),r=await k1(e),n=pme.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await VO(e),await YO(e)):e===ct.PROCESS_DESCRIPTORS.HDB?await H1():await x1(e)}o($1,"reloadStopStart");var V1;async function K1(e=!1){for(let t in ct.CLUSTERING_PROCESSES){let r=ct.CLUSTERING_PROCESSES[t];await YO(r,e)}}o(K1,"startClusteringProcesses");async function Y1(){V1=v1(ct.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:ct.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await aT.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await aT.updateLocalStreams();let e=await Eme.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===ct.PRE_4_0_0_VERSION){Hl.info("Starting clustering upgrade 4.0.0 process"),v1(ct.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}o(Y1,"startClusteringThreads");async function Pme(){for(let e in ct.CLUSTERING_PROCESSES)if(e!==ct.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===ct.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await V1.terminate();else{let t=ct.CLUSTERING_PROCESSES[e];await VO(t)}}o(Pme,"stopClustering");async function Lme(){for(let e in ct.CLUSTERING_PROCESSES){let t=ct.CLUSTERING_PROCESSES[e];if(await q1(t)===!1)return!1}return!0}o(Lme,"isClusteringRunning");async function Dme(){await Wo.generateNatsConfig(!0),await aT.reloadNATSHub(),await aT.reloadNATSLeaf(),await Wo.removeNatsConfig(ct.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Wo.removeNatsConfig(ct.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}o(Dme,"reloadClustering")});var jO={};Oe(jO,{compactOnStart:()=>Mme,copyDb:()=>Z1});async function Mme(){cc.notify("Running compact on start"),console.log("Running compact on start");let e=(0,WO.get)(U.ROOTPATH),t=new Map,r=st();(0,zO.updateConfigValue)(U.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,lT.join)(e,"backup",n+".mdb"),a=(0,lT.join)(e,vc,n+"-copy.mdb"),c=0;try{c=await z1(n),console.log("Database",n,"before compact has a total record count of",c)}catch(l){cc.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:a,backupDest:i,recordCount:c}),await Z1(n,a),console.log("Backing up",n,"to",i);try{await(0,kl.move)(s,i,{overwrite:!0})}catch(l){console.log("Error moving database",s,"to",i,l)}}try{cd()}catch(n){cc.error("Error resetting databases after backup",n),console.error("Error resetting databases after backup",n)}for(let[n,{dbPath:s,copyDest:i}]of t)console.log("Moving copy compacted",n,"to",s),await(0,kl.move)(i,s,{overwrite:!0}),await(0,kl.remove)((0,lT.join)(e,vc,`${n}-copy.mdb-lock`));try{cd()}catch(n){cc.error("Error resetting databases after backup",n),console.error("Error resetting databases after backup",n),process.exit(0)}}catch(n){cc.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,zO.updateConfigValue)(U.STORAGE_COMPACTONSTART,!1);for(let[s,{dbPath:i,backupDest:a}]of t){console.error("Moving backup database",a,"back to",i);try{await(0,kl.move)(a,i,{overwrite:!0})}catch(c){console.error(c)}}throw cd(),n}for(let[n,{backupDest:s,recordCount:i}]of t){let a=!0,c=await z1(n);if(console.log("Database",n,"after compact has a total record count of",c),i!==c){a=!1;let l=`There is a discrepancy between pre and post compact record count for database ${n}.
18
- Total record count before compaction: ${i}, total after: ${c}.
19
- Database backup has not been removed and can be found here: ${s}`;cc.error(l),console.error(l)}(0,WO.get)(U.STORAGE_COMPACTONSTARTKEEPBACKUP)===!0||a===!1||(console.log("Removing backup",s),await(0,kl.remove)(s))}}async function z1(e){let t=await(0,X1.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}function Qd(){}async function Z1(e,t){console.log(`Copying database ${e} to ${t}`);let r=st()[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=Qd,m.primaryStore.remove=Qd;for(let h in m.indices){let p=m.indices[h];p.put=Qd,p.remove=Qd}m.auditStore&&(m.auditStore.put=Qd,m.auditStore.remove=Qd),n=m.primaryStore.rootStore}if(!n)throw new Error(`Source database does not have any tables: ${e}`);let s=n.dbisDb,i=n.auditStore,a=(0,j1.open)(new Q1.default(t)),c=a.openDB(uT.INTERNAL_DBIS_NAME),l,u=0,d=s.useReadTransaction();try{for(let{key:m,value:h}of s.getRange({transaction:d})){let p=h.is_hash_attribute||h.isPrimaryKey,_,g;if(p&&(_=h.compression,g=qg(),g?h.compression=g:delete h.compression,_?.dictionary?.toString()===g?.dictionary?.toString()&&(_=null,g=null)),c.put(m,h),!(p||h.indexed))continue;let y=new J1.default(!p,p);y.encoding="binary",y.compression=_;let T=n.openDB(m,y);T.decoder=null,T.decoderCopies=!1,T.encoding="binary",y.compression=g;let R=a.openDB(m,y);R.encoder=null,console.log("copying",m,"from",e,"to",t),await f(T,R,p,d)}if(i){let m=n.openDB(uT.AUDIT_STORE_NAME,Em);console.log("copying audit log for",e,"to",t),f(i,m,!1,d)}async function f(m,h,p,_){let g=0,y=0,T=0,R=1e7,N=null;for(;R-- >0;)try{for(let O of m.getKeys({start:N,transaction:_}))try{N=O;let{value:F,version:Z}=m.getEntry(O,{transaction:_});if(F?.length<14&&p){T++;continue}l=h.put(O,F,p?Z:void 0),g++,_.openTimer&&(_.openTimer=0),y+=(O?.length||10)+F.length,u++>5e3&&(await l,console.log("copied",g,"entries",T,"delete records,",y,"bytes"),u=0)}catch(F){console.error("Error copying record",typeof O=="symbol"?"symbol":O,"from",e,"to",t,F)}console.log("finish copying, copied",g,"entries",T,"delete records,",y,"bytes");return}catch{if(typeof N=="string"){if(N==="z")return console.error("Reached end of dbi",N,"for",e,"to",t);N=N.slice(0,-2)+"z"}else if(typeof N=="number")N++;else return console.error("Unknown key type",N,"for",e,"to",t)}}o(f,"copyDbi"),await l,console.log("copied database "+e+" to "+t)}finally{d.done(),a.close()}}var j1,lT,kl,WO,Q1,J1,uT,X1,zO,cc,QO=ue(()=>{De();j1=require("lmdb"),lT=require("path"),kl=require("fs-extra"),WO=w(oe()),Q1=w(Nm()),J1=w(Im()),uT=w(qt());k();Di();X1=w(xa()),zO=w(bt()),cc=w(Q());o(Mme,"compactOnStart");o(z1,"getTotalDBRecordCount");o(Qd,"noop");o(Z1,"copyDb")});var Xd=M((n0e,oK)=>{"use strict";var vme=require("minimist"),{isMainThread:XO,parentPort:op,threadId:e0e}=require("worker_threads"),ft=(k(),v(W)),to=Q(),ZO=ie(),fT=sT(),dT=pr(),t0e=It(),nK=bt(),gi=sp(),eK=Bd(),{compactOnStart:Ume}=(QO(),v(jO)),xme=Uc(),{restartWorkers:mT,onMessageByType:Bme}=nt(),{handleHDBError:Fme,hdbErrors:Hme}=ge(),{HTTP_STATUS_CODES:kme}=Hme,ap=oe(),{sendOperationToNode:tK,getThisNodeName:Gme,monitorNodeCAs:qme}=(is(),v(Fo)),{getHDBNodeTable:r0e}=(Nl(),v(cw));ap.initSync();var ip=`Restarting HarperDB. This may take up to ${ft.RESTART_TIMEOUT_MS/1e3} seconds.`,$me="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",rK="Clustering is not enabled so cannot be restarted",Vme="Invalid service",Jd,Us;oK.exports={restart:sK,restartService:eC};XO&&Bme(ft.ITC_EVENT_TYPES.RESTART,async(e,t)=>{e.workerType?await eC({service:e.workerType}):sK({operation:"restart"}),t.postMessage({type:"restart-complete"})});async function sK(e){Us=Object.keys(e).length===0,Jd=await gi.isServiceRegistered(ft.PROCESS_DESCRIPTORS.HDB);let t=vme(process.argv);if(t.service){await eC(t);return}if(Us&&!Jd){console.error($me);return}if(Us&&console.log(ip),Jd){gi.enterPM2Mode(),to.notify(ip);let r=xme(Object.keys(ft.CONFIG_PARAM_MAP),!0);return ZO.isEmptyOrZeroLength(Object.keys(r))||nK.updateConfigValue(void 0,void 0,r,!0,!0),Kme(),ip}return XO?(to.notify(ip),ap.get(ft.CONFIG_PARAMS.STORAGE_COMPACTONSTART)&&await Ume(),process.env.HARPER_EXIT_ON_RESTART&&process.exit(0),setTimeout(()=>{mT()},50)):op.postMessage({type:ft.ITC_EVENT_TYPES.RESTART}),ip}o(sK,"restart");async function eC(e){let{service:t}=e;if(ft.HDB_PROCESS_SERVICES[t]===void 0)throw Fme(new Error,Vme,kme.BAD_REQUEST,void 0,void 0,!0);if(gi.expectedRestartOfChildren(),Jd=await gi.isServiceRegistered(ft.PROCESS_DESCRIPTORS.HDB),!XO){e.replicated&&qme(),op.postMessage({type:ft.ITC_EVENT_TYPES.RESTART,workerType:t}),op.ref(),await new Promise(s=>{op.on("message",i=>{i.type==="restart-complete"&&(s(),op.unref())})});let n;if(e.replicated){e.replicated=!1,n=[];for(let s of server.nodes){if(s.name===Gme())continue;let i;try{({job_id:i}=await tK(s,e))}catch(a){n.push({node:s.name,message:a.message});continue}n.push(await new Promise((a,c)=>{let u=2400,d=setInterval(async()=>{if(u--<=0){clearInterval(d);let h=new Error("Timed out waiting for restart job to complete");h.replicated=n,c(h)}let m=(await tK(s,{operation:"get_job",id:i})).results[0];if(m.status==="COMPLETE"&&(clearInterval(d),a({node:s.name,message:m.message})),m.status==="ERROR"){clearInterval(d);let h=new Error(m.message);h.replicated=n,c(h)}},250)}))}return{replicated:n}}return}let r;switch(t){case ft.HDB_PROCESS_SERVICES.clustering:if(!ap.get(ft.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=rK;break}Us&&console.log("Restarting clustering"),to.notify("Restarting clustering"),await iK();break;case ft.HDB_PROCESS_SERVICES.clustering_config:case ft.HDB_PROCESS_SERVICES["clustering config"]:if(!ap.get(ft.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=rK;break}Us&&console.log("Restarting clusteringConfig"),to.notify("Restarting clustering_config"),await gi.reloadClustering();break;case"custom_functions":case"custom functions":case ft.HDB_PROCESS_SERVICES.harperdb:case ft.HDB_PROCESS_SERVICES.http_workers:case ft.HDB_PROCESS_SERVICES.http:if(Us&&!Jd){r=`Restart ${t} is not available from the CLI when running in non-pm2 mode. Either call restart ${t} from the API or stop and start HarperDB.`;break}Us&&console.log("Restarting httpWorkers"),to.notify("Restarting http_workers"),Us?await gi.restart(ft.PROCESS_DESCRIPTORS.HDB):await mT("http");break;default:r=`Unrecognized service: ${t}`;break}return r?(to.error(r),Us&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}o(eC,"restartService");async function Kme(){await iK(),await gi.restart(ft.PROCESS_DESCRIPTORS.HDB),await ZO.asyncSetTimeout(2e3),ap.get(ft.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await JO(),Us&&(await dT.closeConnection(),process.exit(0))}o(Kme,"restartPM2Mode");async function iK(){if(!nK.getConfigFromFile(ft.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await eK.getHDBProcessInfo()).clustering.length===0)to.trace("Clustering not running, restart will start clustering services"),await fT.generateNatsConfig(!0),await gi.startClusteringProcesses(),await gi.startClusteringThreads(),await JO(),Us&&await dT.closeConnection();else{await fT.generateNatsConfig(!0),Jd?(to.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await gi.restart(ft.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await gi.restart(ft.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await eK.getHDBProcessInfo()).clustering.forEach(s=>{to.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await ZO.asyncSetTimeout(3e3),await JO(),await dT.updateLocalStreams(),Us&&await dT.closeConnection(),to.trace("Restart clustering restarting ingest and reply service threads");let t=mT(ft.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=mT(ft.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}o(iK,"restartClustering");async function JO(){await fT.removeNatsConfig(ft.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await fT.removeNatsConfig(ft.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}o(JO,"removeNatsConfig")});var _K=M((o0e,EK)=>{"use strict";var i0e=require("lodash"),Fn=(k(),v(W)),{handleHDBError:aK,hdbErrors:Yme}=ge(),{HDB_ERROR_MSGS:Wme,HTTP_STATUS_CODES:zme}=Yme,tC=Q();EK.exports={getRolePermissions:Qme};var Gl=Object.create(null),jme=o(e=>({key:e,perms:{}}),"permsTemplateObj"),dK=o((e=!1)=>({describe:e,tables:{}}),"schemaPermsTemplate"),fK=o((e=!1,t=!1,r=!1,n=!1)=>({[Fn.PERMS_CRUD_ENUM.READ]:e,[Fn.PERMS_CRUD_ENUM.INSERT]:t,[Fn.PERMS_CRUD_ENUM.UPDATE]:r,[Fn.PERMS_CRUD_ENUM.DELETE]:n}),"permissionsTemplate"),rC=o((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...fK(t,r,n,s)}),"tablePermsTemplate"),cK=o((e,t=fK())=>({attribute_name:e,describe:pK(t),[cp]:t[cp],[nC]:t[nC],[sC]:t[sC]}),"attrPermsTemplate"),lK=o((e,t=!1)=>({attribute_name:e,describe:t,[cp]:t}),"timestampAttrPermsTemplate"),{READ:cp,INSERT:nC,UPDATE:sC}=Fn.PERMS_CRUD_ENUM,mK=Object.values(Fn.PERMS_CRUD_ENUM),hK=[cp,nC,sC];function Qme(e){let t;try{if(e.permission.super_user||e.permission.cluster_user)return e.permission;let r={...global.hdb_schema};delete r[Fn.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(Gl[t]&&Gl[t].key===n)return Gl[t].perms;let s=Jme(e,r);return Gl[t]?Gl[t].key=n:Gl[t]=jme(n),Gl[t].perms=s,s}catch(r){if(!e[Fn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[Fn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<Fn.PERMS_UPDATE_RELEASE_TIMESTAMP){let n=`Role permissions for role '${role_name}' must be updated to align with new structure from the 2.2.0 release.`;throw tC.error(n),tC.debug(r),aK(new Error,Wme.OUTDATED_PERMS_TRANSLATION_ERROR,zme.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
17
+ `)}catch(r){r.code==="ENOENT"?fn.debug("no license file found"):fn.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(yfe.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=u1(s.license_key,s.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(s){fn.error("There was an error parsing the license string."),fn.error(s),e.ram_allocation=xl.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return PO=e,e}o(vO,"licenseSearch");async function Mfe(){return PO||await vO(),PO}o(Mfe,"getLicense");function vfe(){let e=vO().ram_allocation,t=process.constrainedMemory?.()||o1();if(t=Math.round(Math.min(t,o1())/2**20),t>e)return`This server has more memory (${t}MB) than HarperDB is licensed for (${e}MB), this should only be used for educational and development purposes.`}o(vfe,"checkMemoryLimit")});var BO=M((MUe,p1)=>{var eT=Kd(),f1=require("chalk"),ls=Q(),m1=require("prompt"),{promisify:Ufe}=require("util"),UO=(k(),v(W)),xfe=require("fs-extra"),Bfe=require("path"),Ffe=ie(),{packageJson:Hfe}=Rt(),h1=oe();h1.initSync();var kfe=require("moment"),Gfe=Ufe(m1.get),qfe=Bfe.join(h1.getHdbBasePath(),UO.LICENSE_KEY_DIR_NAME,UO.LICENSE_FILE_NAME,UO.LICENSE_FILE_NAME);p1.exports={getFingerprint:Vfe,setLicense:$fe,parseLicense:xO,register:Kfe,getRegistrationInfo:Wfe};async function $fe(e){if(e&&e.key&&e.company){try{ls.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await xO(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw ls.error(r),ls.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}o($fe,"setLicense");async function Vfe(){let e={};try{e=await eT.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw ls.error(r),ls.error(t),new Error(r)}return e}o(Vfe,"getFingerprint");async function xO(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");ls.info("Validating license input...");let r=eT.validateLicense(e,t);if(ls.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(ls.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(ls.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{ls.info("writing license to disk"),await xfe.writeFile(qfe,JSON.stringify({license_key:e,company:t}))}catch(n){throw ls.error("Failed to write License"),n}return"Registration successful."}o(xO,"parseLicense");async function Kfe(){let e=await Yfe();return xO(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}o(Kfe,"register");async function Yfe(){let e=await eT.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:f1.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:f1.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{m1.start()}catch(n){ls.error(n)}let r;try{r=await Gfe(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}o(Yfe,"promptForRegistration");async function Wfe(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await eT.getLicense()}catch(r){throw ls.error(`There was an error when searching licenses due to: ${r.message}`),r}if(Ffe.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=Hfe.version,e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=kfe.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}o(Wfe,"getRegistrationInfo")});var _1=M((UUe,E1)=>{"use strict";var zfe=It(),FO=class{static{o(this,"HubConfigObject")}constructor(t,r,n,s,i,a,c,l,u,d,f,m,h,p){this.port=t,a===null&&(a=void 0),this.server_name=r+zfe.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:a,insecure:c,verify:l},this.leafnodes={port:u,tls:{cert_file:s,key_file:i,ca_file:a,insecure:c}},this.cluster={name:d,port:f,routes:m,tls:{cert_file:s,key_file:i,ca_file:a,insecure:c,verify:l}},this.accounts={SYS:{users:h},HDB:{users:p}},this.system_account="SYS"}};E1.exports=FO});var T1=M((BUe,S1)=>{"use strict";var g1=It(),HO=class{static{o(this,"LeafConfigObject")}constructor(t,r,n,s,i,a,c,l,u,d,f){this.port=t,f===null&&(f=void 0),this.server_name=r+g1.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+g1.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:a,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:l,jetstream:"enabled"}},this.system_account="SYS"}};S1.exports=HO});var y1=M((HUe,R1)=>{"use strict";var kO=class{static{o(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};R1.exports=kO});var b1=M((GUe,A1)=>{"use strict";var jfe=It(),GO=class{static{o(this,"SysUserObject")}constructor(t,r){this.user=t+jfe.SERVER_SUFFIX.ADMIN,this.password=r}};A1.exports=GO});var sT=M(($Ue,w1)=>{"use strict";var Bl=require("path"),Fl=require("fs-extra"),Qfe=_1(),Jfe=T1(),Xfe=y1(),Zfe=b1(),qO=rs(),Wd=ie(),Bn=bt(),rT=(k(),v(W)),ep=It(),{CONFIG_PARAMS:rr}=rT,zd=Q(),tp=oe(),I1=Vi(),$O=pr(),eme=as(),Yd="clustering",tme=1e4,N1=50;w1.exports={generateNatsConfig:nme,removeNatsConfig:sme,getHubConfigPath:rme};function rme(){let e=tp.get(rr.ROOTPATH);return Bl.join(e,Yd,ep.NATS_CONFIG_FILES.HUB_SERVER)}o(rme,"getHubConfigPath");async function nme(e=!1,t=void 0){console.error("Warning: NATS replication is deprecated and will be removed in version 5.0 of Harper");let r=tp.get(rr.ROOTPATH);Fl.ensureDirSync(Bl.join(r,"clustering","leaf")),tp.initSync();let n=Bn.getConfigFromFile(rr.CLUSTERING_TLS_CERT_AUTH),s=Bn.getConfigFromFile(rr.CLUSTERING_TLS_PRIVATEKEY),i=Bn.getConfigFromFile(rr.CLUSTERING_TLS_CERTIFICATE);!await Fl.exists(i)&&!await Fl.exists(!n)&&await eme.createNatsCerts();let a=Bl.join(r,Yd,ep.PID_FILES.HUB),c=Bl.join(r,Yd,ep.PID_FILES.LEAF),l=Bn.getConfigFromFile(rr.CLUSTERING_LEAFSERVER_STREAMS_PATH),u=Bl.join(r,Yd,ep.NATS_CONFIG_FILES.HUB_SERVER),d=Bl.join(r,Yd,ep.NATS_CONFIG_FILES.LEAF_SERVER),f=Bn.getConfigFromFile(rr.CLUSTERING_TLS_INSECURE),m=Bn.getConfigFromFile(rr.CLUSTERING_TLS_VERIFY),h=Bn.getConfigFromFile(rr.CLUSTERING_NODENAME),p=Bn.getConfigFromFile(rr.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await $O.checkNATSServerInstalled()||nT("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let _=await qO.listUsers(),g=Bn.getConfigFromFile(rr.CLUSTERING_USER),y=await qO.getClusterUser();(Wd.isEmpty(y)||y.active!==!0)&&nT(`Invalid cluster user '${cluster_username}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await tT(rr.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await tT(rr.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await tT(rr.CLUSTERING_HUBSERVER_NETWORK_PORT),await tT(rr.CLUSTERING_LEAFSERVER_NETWORK_PORT));let T=[],R=[];for(let[q,K]of _.entries())K.role?.role===rT.ROLE_TYPES_ENUM.CLUSTER_USER&&K.active&&(T.push(new Zfe(K.username,I1.decrypt(K.hash))),R.push(new Xfe(K.username,I1.decrypt(K.hash))));let N=[],{hub_routes:O}=Bn.getClusteringRoutes();if(!Wd.isEmptyOrZeroLength(O))for(let q of O)N.push(`tls://${y.sys_name_encoded}:${y.uri_encoded_d_hash}@${q.host}:${q.port}`);let F=new Qfe(Bn.getConfigFromFile(rr.CLUSTERING_HUBSERVER_NETWORK_PORT),h,a,i,s,n,f,m,p,Bn.getConfigFromFile(rr.CLUSTERING_HUBSERVER_CLUSTER_NAME),Bn.getConfigFromFile(rr.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),N,T,R);n==null&&(delete F.tls.ca_file,delete F.leafnodes.tls.ca_file),t=Wd.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===rT.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await Fl.writeJson(u,F),zd.trace(`Hub server config written to ${u}`));let Z=`tls://${y.sys_name_encoded}:${y.uri_encoded_d_hash}@0.0.0.0:${p}`,G=`tls://${y.uri_encoded_name}:${y.uri_encoded_d_hash}@0.0.0.0:${p}`,Y=new Jfe(Bn.getConfigFromFile(rr.CLUSTERING_LEAFSERVER_NETWORK_PORT),h,c,l,[Z],[G],T,R,i,s,n,f);n==null&&delete Y.tls.ca_file,(t===void 0||t===rT.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await Fl.writeJson(d,Y),zd.trace(`Leaf server config written to ${d}`))}o(nme,"generateNatsConfig");async function tT(e){let t=tp.get(e);return Wd.isEmpty(t)&&nT(`port undefined for '${e}'`),await Wd.isPortTaken(t)&&nT(`'${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}o(tT,"isPortAvailable");function nT(e){let t=`Error generating clustering config: ${e}`;zd.error(t),console.error(t),process.exit(1)}o(nT,"generateNatsConfigError");async function sme(e){let{port:t,config_file:r}=$O.getServerConfig(e),{username:n,decrypt_hash:s}=await qO.getClusterUser(),i=0,a=2e3;for(;i<N1;){try{let d=await $O.createConnection(t,n,s,!1);if(d.protocol.connected===!0){d.close();break}}catch(d){zd.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${d}`)}if(i++,i>=N1)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=a*(i*2);u>3e4&&zd.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await Wd.asyncSetTimeout(u)}let c="0".repeat(tme),l=Bl.join(tp.get(rr.ROOTPATH),Yd,r);await Fl.writeFile(l,c),await Fl.remove(l),zd.notify(e,"started.")}o(sme,"removeNatsConfig")});var M1=M((KUe,D1)=>{"use strict";var us=oe(),ime=Kd(),Ke=(k(),v(W)),rp=It(),Ko=require("path"),{PACKAGE_ROOT:oT}=Rt(),O1=oe(),iT=ie(),jd="/dev/null",ome=Ko.join(oT,"launchServiceScripts"),C1=Ko.join(oT,"utility/scripts"),ame=Ko.join(C1,Ke.HDB_RESTART_SCRIPT),P1=Ko.resolve(oT,"dependencies",`${process.platform}-${process.arch}`,rp.NATS_BINARY_NAME);function L1(){let t=ime.licenseSearch().ram_allocation||Ke.RAM_ALLOCATION_ENUM.DEFAULT,r=Ke.MEM_SETTING_KEY+t,n={[Ke.PROCESS_NAME_ENV_PROP]:Ke.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return iT.noBootFile()&&(n[Ke.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=iT.getEnvCliRootPath()),{name:Ke.PROCESS_DESCRIPTORS.HDB,script:Ke.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:oT}}o(L1,"generateMainServerConfig");var cme=9930;function lme(){us.initSync(!0);let e=us.get(Ke.CONFIG_PARAMS.ROOTPATH),t=Ko.join(e,"clustering",rp.NATS_CONFIG_FILES.HUB_SERVER),r=Ko.join(us.get(Ke.HDB_SETTINGS_NAMES.LOG_PATH_KEY),Ke.LOG_NAMES.HDB),n=O1.get(Ke.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=rp.LOG_LEVEL_FLAGS[us.get(Ke.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:Ke.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==cme?"-"+n:""),script:P1,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[Ke.PROCESS_NAME_ENV_PROP]:Ke.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return us.get(Ke.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=jd,i.error_file=jd),i}o(lme,"generateNatsHubServerConfig");var ume=9940;function dme(){us.initSync(!0);let e=us.get(Ke.CONFIG_PARAMS.ROOTPATH),t=Ko.join(e,"clustering",rp.NATS_CONFIG_FILES.LEAF_SERVER),r=Ko.join(us.get(Ke.HDB_SETTINGS_NAMES.LOG_PATH_KEY),Ke.LOG_NAMES.HDB),n=O1.get(Ke.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=rp.LOG_LEVEL_FLAGS[us.get(Ke.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:Ke.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==ume?"-"+n:""),script:P1,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[Ke.PROCESS_NAME_ENV_PROP]:Ke.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return us.get(Ke.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=jd,i.error_file=jd),i}o(dme,"generateNatsLeafServerConfig");function fme(){us.initSync();let e=Ko.join(us.get(Ke.CONFIG_PARAMS.LOGGING_ROOT),Ke.LOG_NAMES.HDB),t={name:Ke.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:Ke.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[Ke.PROCESS_NAME_ENV_PROP]:Ke.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:ome,autorestart:!1};return us.get(Ke.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=jd,t.error_file=jd),t}o(fme,"generateClusteringUpgradeV4ServiceConfig");function mme(){let e={[Ke.PROCESS_NAME_ENV_PROP]:Ke.PROCESS_DESCRIPTORS.RESTART_HDB};return iT.noBootFile()&&(e[Ke.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=iT.getEnvCliRootPath()),{...{name:Ke.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:C1},script:ame}}o(mme,"generateRestart");function hme(){return{apps:[L1()]}}o(hme,"generateAllServiceConfigs");D1.exports={generateAllServiceConfigs:hme,generateMainServerConfig:L1,generateRestart:mme,generateNatsHubServerConfig:lme,generateNatsLeafServerConfig:dme,generateClusteringUpgradeV4ServiceConfig:fme}});var sp=M((zUe,W1)=>{"use strict";var ct=(k(),v(W)),pme=ie(),Wo=sT(),aT=pr(),Yo=It(),oc=M1(),cT=oe(),Hl=Q(),Eme=qo(),{startWorker:v1,onMessageFromWorkers:_me}=nt(),gme=Bd(),WUe=require("util"),Sme=require("child_process"),Tme=require("fs"),{execFile:Rme}=Sme,je;W1.exports={enterPM2Mode:yme,start:ac,stop:VO,reload:x1,restart:B1,list:KO,describe:k1,connect:zo,kill:wme,startAllServices:Ome,startService:YO,getUniqueServicesList:G1,restartAllServices:Cme,isServiceRegistered:q1,reloadStopStart:$1,restartHdb:H1,deleteProcess:Ime,startClusteringProcesses:K1,startClusteringThreads:Y1,isHdbRestartRunning:Nme,isClusteringRunning:Lme,stopClustering:Pme,reloadClustering:Dme,expectedRestartOfChildren:F1};var np=!1;_me(e=>{e.type==="restart"&&cT.initSync(!0)});function yme(){np=!0}o(yme,"enterPM2Mode");function zo(){return je||(je=require("pm2")),new Promise((e,t)=>{je.connect((r,n)=>{r&&t(r),e(n)})})}o(zo,"connect");var mn,Ame=10,U1;function ac(e,t=!1){if(np)return bme(e);let r=Rme(e.script,e.args.split(" "),e);r.name=e.name,r.config=e,r.on("exit",async i=>{let a=mn.indexOf(r);a>-1&&mn.splice(a,1),!U1&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<Ame&&(Tme.existsSync(Wo.getHubConfigPath())?ac(e):(await Wo.generateNatsConfig(!0),ac(e),await new Promise(c=>setTimeout(c,3e3)),await Wo.removeNatsConfig(ct.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Wo.removeNatsConfig(ct.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let a=cT.get(ct.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,l,u=0,d;for(;l=c.exec(i);){if(l.index&&Yo.LOG_LEVEL_HIERARCHY[a]>=Yo.LOG_LEVEL_HIERARCHY[d||"info"]){let h=d===Yo.LOG_LEVELS.ERR||d===Yo.LOG_LEVELS.WRN?Hl.OUTPUTS.STDERR:Hl.OUTPUTS.STDOUT;Hl.logCustomLevel(d||"info",h,n,i.slice(u,l.index).trim())}let[f,m]=l;u=l.index+f.length,d=Yo.LOG_LEVELS[m]}if(Yo.LOG_LEVEL_HIERARCHY[a]>=Yo.LOG_LEVEL_HIERARCHY[d||"info"]){let f=d===Yo.LOG_LEVELS.ERR||d===Yo.LOG_LEVELS.WRN?Hl.OUTPUTS.STDERR:Hl.OUTPUTS.STDOUT;Hl.logCustomLevel(d||"info",f,n,i.slice(u).trim())}}if(o(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),!mn&&(mn=[],!t)){let i=o(()=>{U1=!0,mn&&(mn.map(a=>a.kill()),process.exit(0))},"killChildren");process.on("exit",i),process.on("SIGINT",i),process.on("SIGQUIT",i),process.on("SIGTERM",i)}mn.push(r)}o(ac,"start");function bme(e){return new Promise(async(t,r)=>{try{await zo()}catch(n){r(n)}je.start(e,(n,s)=>{n&&(je.disconnect(),r(n)),je.disconnect(),t(s)})})}o(bme,"startWithPM2");function VO(e){if(!np){for(let t of mn||[])t.name===e&&(mn.splice(mn.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await zo()}catch(n){r(n)}je.stop(e,async(n,s)=>{n&&(je.disconnect(),r(n)),je.delete(e,(i,a)=>{i&&(je.disconnect(),r(n)),je.disconnect(),t(a)})})})}o(VO,"stop");function x1(e){return new Promise(async(t,r)=>{try{await zo()}catch(n){r(n)}je.reload(e,(n,s)=>{n&&(je.disconnect(),r(n)),je.disconnect(),t(s)})})}o(x1,"reload");function B1(e){if(!np){F1();for(let t of mn||[])t.name===e&&t.kill()}return new Promise(async(t,r)=>{try{await zo()}catch(n){r(n)}je.restart(e,(n,s)=>{je.disconnect(),t(s)})})}o(B1,"restart");function F1(){for(let e of mn||[])e.config&&(e.config.restarts=0)}o(F1,"expectedRestartOfChildren");function Ime(e){return new Promise(async(t,r)=>{try{await zo()}catch(n){r(n)}je.delete(e,(n,s)=>{n&&(je.disconnect(),r(n)),je.disconnect(),t(s)})})}o(Ime,"deleteProcess");async function H1(){await ac(oc.generateRestart())}o(H1,"restartHdb");async function Nme(){let e=await KO();for(let t in e)if(e[t].name===ct.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}o(Nme,"isHdbRestartRunning");function KO(){return new Promise(async(e,t)=>{try{await zo()}catch(r){t(r)}je.list((r,n)=>{r&&(je.disconnect(),t(r)),je.disconnect(),e(n)})})}o(KO,"list");function k1(e){return new Promise(async(t,r)=>{try{await zo()}catch(n){r(n)}je.describe(e,(n,s)=>{n&&(je.disconnect(),r(n)),je.disconnect(),t(s)})})}o(k1,"describe");function wme(){if(!np){for(let e of mn||[])e.kill();mn=[];return}return new Promise(async(e,t)=>{try{await zo()}catch(r){t(r)}je.killDaemon((r,n)=>{r&&(je.disconnect(),t(r)),je.disconnect(),e(n)})})}o(wme,"kill");async function Ome(){try{await K1(),await Y1(),await ac(oc.generateAllServiceConfigs())}catch(e){throw je?.disconnect(),e}}o(Ome,"startAllServices");async function YO(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case ct.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=oc.generateMainServerConfig();break;case ct.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=oc.generateNatsIngestServiceConfig();break;case ct.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=oc.generateNatsReplyServiceConfig();break;case ct.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=oc.generateNatsHubServerConfig(),await ac(r,t),await Wo.removeNatsConfig(e);return;case ct.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=oc.generateNatsLeafServerConfig(),await ac(r,t),await Wo.removeNatsConfig(e);return;case ct.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=oc.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await ac(r)}catch(r){throw je?.disconnect(),r}}o(YO,"startService");async function G1(){try{let e=await KO(),t={};for(let r=0,n=e.length;r<n;r++){let s=e[r];t[s.name]===void 0&&(t[s.name]={name:s.name,exec_mode:s.pm2_env.exec_mode})}return t}catch(e){throw je?.disconnect(),e}}o(G1,"getUniqueServicesList");async function Cme(e=[]){try{let t=!1,r=await G1();for(let n=0,s=Object.values(r).length;n<s;n++){let a=Object.values(r)[n].name;e.includes(a)||(a===ct.PROCESS_DESCRIPTORS.HDB?t=!0:await B1(a))}t&&await $1(ct.PROCESS_DESCRIPTORS.HDB)}catch(t){throw je?.disconnect(),t}}o(Cme,"restartAllServices");async function q1(e){if(mn?.find(r=>r.name===e))return!0;let t=await gme.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}o(q1,"isServiceRegistered");async function $1(e){let t=cT.get(ct.CONFIG_PARAMS.THREADS_COUNT)??cT.get(ct.CONFIG_PARAMS.THREADS),r=await k1(e),n=pme.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await VO(e),await YO(e)):e===ct.PROCESS_DESCRIPTORS.HDB?await H1():await x1(e)}o($1,"reloadStopStart");var V1;async function K1(e=!1){for(let t in ct.CLUSTERING_PROCESSES){let r=ct.CLUSTERING_PROCESSES[t];await YO(r,e)}}o(K1,"startClusteringProcesses");async function Y1(){V1=v1(ct.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:ct.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await aT.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await aT.updateLocalStreams();let e=await Eme.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===ct.PRE_4_0_0_VERSION){Hl.info("Starting clustering upgrade 4.0.0 process"),v1(ct.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}o(Y1,"startClusteringThreads");async function Pme(){for(let e in ct.CLUSTERING_PROCESSES)if(e!==ct.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===ct.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await V1.terminate();else{let t=ct.CLUSTERING_PROCESSES[e];await VO(t)}}o(Pme,"stopClustering");async function Lme(){for(let e in ct.CLUSTERING_PROCESSES){let t=ct.CLUSTERING_PROCESSES[e];if(await q1(t)===!1)return!1}return!0}o(Lme,"isClusteringRunning");async function Dme(){await Wo.generateNatsConfig(!0),await aT.reloadNATSHub(),await aT.reloadNATSLeaf(),await Wo.removeNatsConfig(ct.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Wo.removeNatsConfig(ct.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}o(Dme,"reloadClustering")});var jO={};Oe(jO,{compactOnStart:()=>Mme,copyDb:()=>Z1});async function Mme(){cc.notify("Running compact on start"),console.log("Running compact on start");let e=(0,WO.get)(U.ROOTPATH),t=new Map,r=st();(0,zO.updateConfigValue)(U.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,lT.join)(e,"backup",n+".mdb"),a=(0,lT.join)(e,vc,n+"-copy.mdb"),c=0;try{c=await z1(n),console.log("Database",n,"before compact has a total record count of",c)}catch(l){cc.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:a,backupDest:i,recordCount:c}),await Z1(n,a),console.log("Backing up",n,"to",i);try{await(0,kl.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,kl.move)(a,s,{overwrite:!0}),await(0,kl.remove)((0,lT.join)(e,vc,`${n}-copy.mdb-lock`))}try{cd()}catch(n){cc.error("Error resetting databases after backup",n),console.error("Error resetting databases after backup",n)}try{cd()}catch(n){cc.error("Error resetting databases after backup",n),console.error("Error resetting databases after backup",n),process.exit(0)}}catch(n){cc.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,zO.updateConfigValue)(U.STORAGE_COMPACTONSTART,!1);for(let[s,{dbPath:i,backupDest:a}]of t){console.error("Moving backup database",a,"back to",i);try{await(0,kl.move)(a,i,{overwrite:!0})}catch(c){console.error(c)}}throw cd(),n}for(let[n,{backupDest:s,recordCount:i}]of t){let a=await z1(n);if(console.log("Database",n,"after compact has a total record count of",a),i!==a){let c=`There is a discrepancy between pre and post compact record count for database ${n}.
18
+ Total record count before compaction: ${i}, total after: ${a}.
19
+ Database backup has not been removed and can be found here: ${s}`;cc.error(c),console.error(c)}(0,WO.get)(U.STORAGE_COMPACTONSTARTKEEPBACKUP)!==!0&&(console.log("Removing backup",s),await(0,kl.remove)(s))}}async function z1(e){let t=await(0,X1.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}function Qd(){}async function Z1(e,t){console.log(`Copying database ${e} to ${t}`);let r=st()[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=Qd,m.primaryStore.remove=Qd;for(let h in m.indices){let p=m.indices[h];p.put=Qd,p.remove=Qd}m.auditStore&&(m.auditStore.put=Qd,m.auditStore.remove=Qd),n=m.primaryStore.rootStore}if(!n)throw new Error(`Source database does not have any tables: ${e}`);let s=n.dbisDb,i=n.auditStore,a=(0,j1.open)(new Q1.default(t)),c=a.openDB(uT.INTERNAL_DBIS_NAME),l,u=0,d=s.useReadTransaction();try{for(let{key:m,value:h}of s.getRange({transaction:d})){let p=h.is_hash_attribute||h.isPrimaryKey,_,g;if(p&&(_=h.compression,g=qg(),g?h.compression=g:delete h.compression,_?.dictionary?.toString()===g?.dictionary?.toString()&&(_=null,g=null)),c.put(m,h),!(p||h.indexed))continue;let y=new J1.default(!p,p);y.encoding="binary",y.compression=_;let T=n.openDB(m,y);T.decoder=null,T.decoderCopies=!1,T.encoding="binary",y.compression=g;let R=a.openDB(m,y);R.encoder=null,console.log("copying",m,"from",e,"to",t),await f(T,R,p,d)}if(i){let m=n.openDB(uT.AUDIT_STORE_NAME,Em);console.log("copying audit log for",e,"to",t),f(i,m,!1,d)}async function f(m,h,p,_){let g=0,y=0,T=0,R=1e7,N=null;for(;R-- >0;)try{for(let O of m.getKeys({start:N,transaction:_}))try{N=O;let{value:F,version:Z}=m.getEntry(O,{transaction:_});if(F?.length<14&&p){T++;continue}l=h.put(O,F,p?Z:void 0),g++,_.openTimer&&(_.openTimer=0),y+=(O?.length||10)+F.length,u++>5e3&&(await l,console.log("copied",g,"entries",T,"delete records,",y,"bytes"),u=0)}catch(F){console.error("Error copying record",typeof O=="symbol"?"symbol":O,"from",e,"to",t,F)}console.log("finish copying, copied",g,"entries",T,"delete records,",y,"bytes");return}catch{if(typeof N=="string"){if(N==="z")return console.error("Reached end of dbi",N,"for",e,"to",t);N=N.slice(0,-2)+"z"}else if(typeof N=="number")N++;else return console.error("Unknown key type",N,"for",e,"to",t)}}o(f,"copyDbi"),await l,console.log("copied database "+e+" to "+t)}finally{d.done(),a.close()}}var j1,lT,kl,WO,Q1,J1,uT,X1,zO,cc,QO=ue(()=>{De();j1=require("lmdb"),lT=require("path"),kl=require("fs-extra"),WO=w(oe()),Q1=w(Nm()),J1=w(Im()),uT=w(qt());k();Di();X1=w(xa()),zO=w(bt()),cc=w(Q());o(Mme,"compactOnStart");o(z1,"getTotalDBRecordCount");o(Qd,"noop");o(Z1,"copyDb")});var Xd=M((n0e,oK)=>{"use strict";var vme=require("minimist"),{isMainThread:XO,parentPort:op,threadId:e0e}=require("worker_threads"),ft=(k(),v(W)),to=Q(),ZO=ie(),fT=sT(),dT=pr(),t0e=It(),nK=bt(),gi=sp(),eK=Bd(),{compactOnStart:Ume}=(QO(),v(jO)),xme=Uc(),{restartWorkers:mT,onMessageByType:Bme}=nt(),{handleHDBError:Fme,hdbErrors:Hme}=ge(),{HTTP_STATUS_CODES:kme}=Hme,ap=oe(),{sendOperationToNode:tK,getThisNodeName:Gme,monitorNodeCAs:qme}=(is(),v(Fo)),{getHDBNodeTable:r0e}=(Nl(),v(cw));ap.initSync();var ip=`Restarting HarperDB. This may take up to ${ft.RESTART_TIMEOUT_MS/1e3} seconds.`,$me="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",rK="Clustering is not enabled so cannot be restarted",Vme="Invalid service",Jd,Us;oK.exports={restart:sK,restartService:eC};XO&&Bme(ft.ITC_EVENT_TYPES.RESTART,async(e,t)=>{e.workerType?await eC({service:e.workerType}):sK({operation:"restart"}),t.postMessage({type:"restart-complete"})});async function sK(e){Us=Object.keys(e).length===0,Jd=await gi.isServiceRegistered(ft.PROCESS_DESCRIPTORS.HDB);let t=vme(process.argv);if(t.service){await eC(t);return}if(Us&&!Jd){console.error($me);return}if(Us&&console.log(ip),Jd){gi.enterPM2Mode(),to.notify(ip);let r=xme(Object.keys(ft.CONFIG_PARAM_MAP),!0);return ZO.isEmptyOrZeroLength(Object.keys(r))||nK.updateConfigValue(void 0,void 0,r,!0,!0),Kme(),ip}return XO?(to.notify(ip),ap.get(ft.CONFIG_PARAMS.STORAGE_COMPACTONSTART)&&await Ume(),process.env.HARPER_EXIT_ON_RESTART&&process.exit(0),setTimeout(()=>{mT()},50)):op.postMessage({type:ft.ITC_EVENT_TYPES.RESTART}),ip}o(sK,"restart");async function eC(e){let{service:t}=e;if(ft.HDB_PROCESS_SERVICES[t]===void 0)throw Fme(new Error,Vme,kme.BAD_REQUEST,void 0,void 0,!0);if(gi.expectedRestartOfChildren(),Jd=await gi.isServiceRegistered(ft.PROCESS_DESCRIPTORS.HDB),!XO){e.replicated&&qme(),op.postMessage({type:ft.ITC_EVENT_TYPES.RESTART,workerType:t}),op.ref(),await new Promise(s=>{op.on("message",i=>{i.type==="restart-complete"&&(s(),op.unref())})});let n;if(e.replicated){e.replicated=!1,n=[];for(let s of server.nodes){if(s.name===Gme())continue;let i;try{({job_id:i}=await tK(s,e))}catch(a){n.push({node:s.name,message:a.message});continue}n.push(await new Promise((a,c)=>{let u=2400,d=setInterval(async()=>{if(u--<=0){clearInterval(d);let h=new Error("Timed out waiting for restart job to complete");h.replicated=n,c(h)}let m=(await tK(s,{operation:"get_job",id:i})).results[0];if(m.status==="COMPLETE"&&(clearInterval(d),a({node:s.name,message:m.message})),m.status==="ERROR"){clearInterval(d);let h=new Error(m.message);h.replicated=n,c(h)}},250)}))}return{replicated:n}}return}let r;switch(t){case ft.HDB_PROCESS_SERVICES.clustering:if(!ap.get(ft.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=rK;break}Us&&console.log("Restarting clustering"),to.notify("Restarting clustering"),await iK();break;case ft.HDB_PROCESS_SERVICES.clustering_config:case ft.HDB_PROCESS_SERVICES["clustering config"]:if(!ap.get(ft.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=rK;break}Us&&console.log("Restarting clusteringConfig"),to.notify("Restarting clustering_config"),await gi.reloadClustering();break;case"custom_functions":case"custom functions":case ft.HDB_PROCESS_SERVICES.harperdb:case ft.HDB_PROCESS_SERVICES.http_workers:case ft.HDB_PROCESS_SERVICES.http:if(Us&&!Jd){r=`Restart ${t} is not available from the CLI when running in non-pm2 mode. Either call restart ${t} from the API or stop and start HarperDB.`;break}Us&&console.log("Restarting httpWorkers"),to.notify("Restarting http_workers"),Us?await gi.restart(ft.PROCESS_DESCRIPTORS.HDB):await mT("http");break;default:r=`Unrecognized service: ${t}`;break}return r?(to.error(r),Us&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}o(eC,"restartService");async function Kme(){await iK(),await gi.restart(ft.PROCESS_DESCRIPTORS.HDB),await ZO.asyncSetTimeout(2e3),ap.get(ft.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await JO(),Us&&(await dT.closeConnection(),process.exit(0))}o(Kme,"restartPM2Mode");async function iK(){if(!nK.getConfigFromFile(ft.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await eK.getHDBProcessInfo()).clustering.length===0)to.trace("Clustering not running, restart will start clustering services"),await fT.generateNatsConfig(!0),await gi.startClusteringProcesses(),await gi.startClusteringThreads(),await JO(),Us&&await dT.closeConnection();else{await fT.generateNatsConfig(!0),Jd?(to.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await gi.restart(ft.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await gi.restart(ft.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await eK.getHDBProcessInfo()).clustering.forEach(s=>{to.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await ZO.asyncSetTimeout(3e3),await JO(),await dT.updateLocalStreams(),Us&&await dT.closeConnection(),to.trace("Restart clustering restarting ingest and reply service threads");let t=mT(ft.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=mT(ft.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}o(iK,"restartClustering");async function JO(){await fT.removeNatsConfig(ft.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await fT.removeNatsConfig(ft.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}o(JO,"removeNatsConfig")});var _K=M((o0e,EK)=>{"use strict";var i0e=require("lodash"),Fn=(k(),v(W)),{handleHDBError:aK,hdbErrors:Yme}=ge(),{HDB_ERROR_MSGS:Wme,HTTP_STATUS_CODES:zme}=Yme,tC=Q();EK.exports={getRolePermissions:Qme};var Gl=Object.create(null),jme=o(e=>({key:e,perms:{}}),"permsTemplateObj"),dK=o((e=!1)=>({describe:e,tables:{}}),"schemaPermsTemplate"),fK=o((e=!1,t=!1,r=!1,n=!1)=>({[Fn.PERMS_CRUD_ENUM.READ]:e,[Fn.PERMS_CRUD_ENUM.INSERT]:t,[Fn.PERMS_CRUD_ENUM.UPDATE]:r,[Fn.PERMS_CRUD_ENUM.DELETE]:n}),"permissionsTemplate"),rC=o((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...fK(t,r,n,s)}),"tablePermsTemplate"),cK=o((e,t=fK())=>({attribute_name:e,describe:pK(t),[cp]:t[cp],[nC]:t[nC],[sC]:t[sC]}),"attrPermsTemplate"),lK=o((e,t=!1)=>({attribute_name:e,describe:t,[cp]:t}),"timestampAttrPermsTemplate"),{READ:cp,INSERT:nC,UPDATE:sC}=Fn.PERMS_CRUD_ENUM,mK=Object.values(Fn.PERMS_CRUD_ENUM),hK=[cp,nC,sC];function Qme(e){let t;try{if(e.permission.super_user||e.permission.cluster_user)return e.permission;let r={...global.hdb_schema};delete r[Fn.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(Gl[t]&&Gl[t].key===n)return Gl[t].perms;let s=Jme(e,r);return Gl[t]?Gl[t].key=n:Gl[t]=jme(n),Gl[t].perms=s,s}catch(r){if(!e[Fn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[Fn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<Fn.PERMS_UPDATE_RELEASE_TIMESTAMP){let n=`Role permissions for role '${role_name}' must be updated to align with new structure from the 2.2.0 release.`;throw tC.error(n),tC.debug(r),aK(new Error,Wme.OUTDATED_PERMS_TRANSLATION_ERROR,zme.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
20
20
  ${r.stack}`;throw tC.error(n),aK(new Error)}}}o(Qme,"getRolePermissions");function Jme(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[Fn.SYSTEM_SCHEMA_NAME]=n[Fn.SYSTEM_SCHEMA_NAME],r.structure_user=n.structure_user;let s=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(s===!0||s.indexOf(i)>-1){r[i]=Xme(t[i]);return}r[i]=dK(),n[i]?(n[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(a=>{if(n[i].tables[a]){let c=n[i].tables[a],l=t[i][a],u=Zme(c,l);r[i].describe||mK.forEach(d=>{u[d]&&(r[i].describe=!0)}),r[i].tables[a]=u}else r[i].tables[a]=rC()})):Object.keys(t[i]).forEach(a=>{r[i].tables[a]=rC()})}),r}o(Jme,"translateRolePermissions");function Xme(e){let t=dK(!0);return Object.keys(e).forEach(r=>{t.tables[r]=rC(!0,!0,!0,!0,!0)}),t}o(Xme,"createStructureUserPermissions");function Zme(e,t){let{attribute_permissions:r}=e;if(r?.length>0){let s={...e};s.attribute_permissions=[];let i=r.reduce((u,d)=>{let{attribute_name:f}=d,m=d;return Fn.TIME_STAMP_NAMES.includes(f)&&(m=lK(f,d[cp])),u[f]=m,u},{}),a=t.primaryKey||t.hash_attribute,c=!!i[a],l=cK(a);return t.attributes.forEach(({attribute:u})=>{if(i[u]){let d=i[u];d.describe=pK(d),s.attribute_permissions.push(d),c||ehe(d,l)}else if(u!==a){let d;Fn.TIME_STAMP_NAMES.includes(u)?d=lK(u):d=cK(u),s.attribute_permissions.push(d)}}),c||s.attribute_permissions.push(l),s.describe=uK(s),s}else return e.describe=uK(e),e}o(Zme,"getTableAttrPerms");function uK(e){return mK.filter(t=>e[t]).length>0}o(uK,"getSchemaTableDescribePerm");function pK(e){return hK.filter(t=>e[t]).length>0}o(pK,"getAttributeDescribePerm");function ehe(e,t){hK.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}o(ehe,"checkForHashPerms")});var lp={};Oe(lp,{authentication:()=>IK,bypassAuth:()=>lhe,login:()=>aC,logout:()=>cC,start:()=>uhe});function lhe(){bK=!0}async function IK(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,a=[];try{if(i){let h=e.isOperationsServer?ihe?she:[]:nhe?rhe:[];if(h.includes(i)||h.includes("*")){if(e.method==="OPTIONS"){let p=hn.get(U.HTTP_CORSACCESSCONTROLALLOWHEADERS)??"Accept, Content-Type, Authorization",_=new Os([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers",p],["Access-Control-Allow-Origin",i]]);return hT&&_.set("Access-Control-Allow-Credentials","true"),{status:200,headers:_}}a.push("Access-Control-Allow-Origin",i),hT&&a.push("Access-Control-Allow-Credentials","true")}}let l,u;if(hT){i||(i=r.host);let h=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",p=s?.split(/;\s+/)||[];for(let _ of p)if(_.startsWith(h)){let g=_.indexOf(";");l=_.slice(h.length,g===-1?_.length:g),u=await gK.get(l);break}e.session=u||(u={})}let d=o((h,p,_)=>{let g=new pT.AuthAuditLog(h,p,ya.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);g.auth_strategy=_,l&&(g.session_id=l),r.referer&&(g.referer=r.referer),r.origin&&(g.origin=r.origin),p===Xs.SUCCESS?iC.notify(g):iC.error(g)},"authAuditLog");if(!e.authorized&&e.mtlsConfig&&e.peerCertificate.subject&&e?._nodeRequest?.socket?.authorizationError&&iC.error("Authorization error:",e._nodeRequest.socket.authorizationError),e.mtlsConfig&&e.authorized&&e.peerCertificate.subject){let h=e.mtlsConfig.user;h!==null?((h===void 0||h==="Common Name"||h==="CN")&&(h=e.peerCertificate.subject.CN),e.user=await Le.getUser(h,null,e),d(h,Xs.SUCCESS,"mTLS")):the("HTTPS/WSS mTLS authorized connection (mTLS did not authorize a user)","from",e.ip)}let f;if(!e.user)if(n){if(f=ql.get(n),!f){let h=n.indexOf(" "),p=n.slice(0,h),_=n.slice(h+1),g,y;try{switch(p){case"Basic":let T=atob(_),R=T.indexOf(":");g=T.slice(0,R),y=T.slice(R+1),f=g||y?await Le.getUser(g,y,e):null;break;case"Bearer":try{f=await ew(_)}catch(N){if(N.message==="invalid token")try{return await nS(_),c({status:-1})}catch{throw N}}break}}catch(T){return ahe&&(ql.get(_)||(ql.set(_,_),d(g,Xs.FAILURE,p))),c({status:401,body:Ia({error:T.message},e)})}ql.set(n,f),ohe&&d(f.username,Xs.SUCCESS,p)}e.user=f}else u?.user?e.user=await Le.getUser(u.user,null,e):(bK&&(e.ip?.includes("127.0.0.")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,TK.getSuperUser)());hT&&(e.session.update=function(h){let p=hn.get(U.AUTHENTICATION_COOKIE_EXPIRES),_=e.protocol==="https"||r.host?.startsWith("localhost:")||r.host?.startsWith("127.0.0.1:")||r.host?.startsWith("::1");if(!l){l=(0,RK.v4)();let g=hn.get(U.AUTHENTICATION_COOKIE_DOMAINS),y=p?new Date(Date.now()+(0,oC.convertToMS)(p)).toUTCString():che,T=g?.find(O=>r.host?.endsWith(O)),N=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${l}; Path=/; Expires=${y}; HttpOnly`;T&&(N+=`; Domain=${T}`),_&&(N+="; SameSite=None; Secure"),a?a.push("Set-Cookie",N):m?.headers?.set&&m.headers.set("Set-Cookie",N)}return _&&(a?(i&&a.push("Access-Control-Expose-Headers","X-Hdb-Session"),a.push("X-Hdb-Session","Secure")):m?.headers?.set&&(i&&m.headers.set("Access-Control-Expose-Headers","X-Hdb-Session"),m.headers.set("X-Hdb-Session","Secure"))),h.id=l,gK.put(h,{expiresAt:p?Date.now()+(0,oC.convertToMS)(p):void 0})},e.login=async function(h,p){let _=e.user=await Le.authenticateUser(h,p,e);e.session.update({user:_&&(_.getId?.()??_.username)})});let m=await t(e);return m&&(m.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&bs.loginPath?(m.status=302,m.headers.set("Location",bs.loginPath(e))):m.headers.set("WWW-Authenticate","Basic")),c(m))}catch(l){throw c(l)}function c(l){let u=a.length;if(u>0){let d=l.headers;d||(l.headers=d=new Os);for(let f=0;f<u;){let m=a[f++];d.set(m,a[f++])}}return a=null,l}o(c,"applyResponseHeaders")}function uhe({server:e,port:t,securePort:r}){e.http(IK,t||r?{port:t,securePort:r}:{port:"all"}),SK||(SK=!0,setInterval(()=>{ql=new Map},hn.get(U.AUTHENTICATION_CACHETTL)).unref(),yK.user.addListener(()=>{ql=new Map}))}async function aC(e){if(!e.baseRequest?.login)throw new Error("No session for login");return e.baseResponse.headers.set=(t,r)=>{e.fastifyResponse.header(t,r)},await e.baseRequest.login(e.username,e.password??""),"Login successful"}async function cC(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var TK,RK,hn,pT,yK,oC,AK,the,iC,rhe,nhe,she,ihe,gK,hT,bK,ohe,ahe,che,ql,SK,ET=ue(()=>{TK=w(rs());Mr();Bu();_d();De();RK=require("uuid"),hn=w(oe());k();pT=w(Q()),yK=w(sh());uh();oC=w(ie());Ro();AK=(0,pT.forComponent)("authentication"),{debug:the}=AK,iC=AK.withTag("auth-event");hn.initSync();rhe=hn.get(U.HTTP_CORSACCESSLIST),nhe=hn.get(U.HTTP_CORS),she=hn.get(U.OPERATIONSAPI_NETWORK_CORSACCESSLIST),ihe=hn.get(U.OPERATIONSAPI_NETWORK_CORS),gK=ze({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),hT=hn.get(U.AUTHENTICATION_ENABLESESSIONS)??!0,bK=process.env.AUTHENTICATION_AUTHORIZELOCAL??hn.get(U.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,ohe=hn.get(U.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,ahe=hn.get(U.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,che="Tue, 01 Oct 8307 19:33:20 GMT",ql=new Map;Le.onInvalidatedUser(()=>{ql=new Map});o(lhe,"bypassAuth");o(IK,"authentication");o(uhe,"start");o(aC,"login");o(cC,"logout")});var DK=M((E0e,LK)=>{"use strict";var we=require("joi"),NK=require("fs-extra"),wK=require("path"),ds=ut(),OK=oe(),CK=(k(),v(W)),PK=Q(),{hdbErrors:dhe}=ge(),{HDB_ERROR_MSGS:pn}=dhe,jo=/^[a-zA-Z0-9-_]+$/,fhe=/^[a-zA-Z0-9-_]+$/;LK.exports={getDropCustomFunctionValidator:hhe,setCustomFunctionValidator:phe,addComponentValidator:She,dropCustomFunctionProjectValidator:The,packageComponentValidator:Rhe,deployComponentValidator:yhe,setComponentFileValidator:Ehe,getComponentFileValidator:ghe,dropComponentFileValidator:_he,addSSHKeyValidator:Ahe,updateSSHKeyValidator:bhe,deleteSSHKeyValidator:Ihe,setSSHKnownHostsValidator:Nhe};function _T(e,t,r){try{let n=OK.get(CK.CONFIG_PARAMS.COMPONENTSROOT),s=wK.join(n,t);return NK.existsSync(s)?e?t:r.message(pn.PROJECT_EXISTS):e?r.message(pn.NO_PROJECT):t}catch(n){return PK.error(n),r.message(pn.VALIDATION_ERR)}}o(_T,"checkProjectExists");function up(e,t){return e.includes("..")?t.message("Invalid file path"):e}o(up,"checkFilePath");function mhe(e,t,r,n){try{let s=OK.get(CK.CONFIG_PARAMS.COMPONENTSROOT),i=wK.join(s,e,t,r+".js");return NK.existsSync(i)?r:n.message(pn.NO_FILE)}catch(s){return PK.error(s),n.message(pn.VALIDATION_ERR)}}o(mhe,"checkFileExists");function hhe(e){let t=we.object({project:we.string().pattern(jo).custom(_T.bind(null,!0)).required().messages({"string.pattern.base":pn.BAD_PROJECT_NAME}),type:we.string().valid("helpers","routes").required(),file:we.string().pattern(jo).custom(mhe.bind(null,e.project,e.type)).custom(up).required().messages({"string.pattern.base":pn.BAD_FILE_NAME})});return ds.validateBySchema(e,t)}o(hhe,"getDropCustomFunctionValidator");function phe(e){let t=we.object({project:we.string().pattern(jo).custom(_T.bind(null,!0)).required().messages({"string.pattern.base":pn.BAD_PROJECT_NAME}),type:we.string().valid("helpers","routes").required(),file:we.string().custom(up).required(),function_content:we.string().required()});return ds.validateBySchema(e,t)}o(phe,"setCustomFunctionValidator");function Ehe(e){let t=we.object({project:we.string().pattern(jo).required().messages({"string.pattern.base":pn.BAD_PROJECT_NAME}),file:we.string().custom(up).required(),payload:we.string().allow("").optional(),encoding:we.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return ds.validateBySchema(e,t)}o(Ehe,"setComponentFileValidator");function _he(e){let t=we.object({project:we.string().pattern(jo).required().messages({"string.pattern.base":pn.BAD_PROJECT_NAME}),file:we.string().custom(up).optional()});return ds.validateBySchema(e,t)}o(_he,"dropComponentFileValidator");function ghe(e){let t=we.object({project:we.string().required(),file:we.string().custom(up).required(),encoding:we.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return ds.validateBySchema(e,t)}o(ghe,"getComponentFileValidator");function She(e){let t=we.object({project:we.string().pattern(jo).custom(_T.bind(null,!1)).required().messages({"string.pattern.base":pn.BAD_PROJECT_NAME})});return ds.validateBySchema(e,t)}o(She,"addComponentValidator");function The(e){let t=we.object({project:we.string().pattern(jo).custom(_T.bind(null,!0)).required().messages({"string.pattern.base":pn.BAD_PROJECT_NAME})});return ds.validateBySchema(e,t)}o(The,"dropCustomFunctionProjectValidator");function Rhe(e){let t=we.object({project:we.string().pattern(jo).required().messages({"string.pattern.base":pn.BAD_PROJECT_NAME}),skip_node_modules:we.boolean(),skip_symlinks:we.boolean()});return ds.validateBySchema(e,t)}o(Rhe,"packageComponentValidator");function yhe(e){let t=we.object({project:we.string().pattern(jo).required().messages({"string.pattern.base":pn.BAD_PROJECT_NAME}),package:we.string().optional(),restart:we.alternatives().try(we.boolean(),we.string().valid("rolling")).optional()});return ds.validateBySchema(e,t)}o(yhe,"deployComponentValidator");function Ahe(e){let t=we.object({name:we.string().pattern(fhe).required().messages({"string.pattern.base":pn.BAD_SSH_KEY_NAME}),key:we.string().required(),host:we.string().required(),hostname:we.string().required(),known_hosts:we.string().optional()});return ds.validateBySchema(e,t)}o(Ahe,"addSSHKeyValidator");function bhe(e){let t=we.object({name:we.string().required(),key:we.string().required()});return ds.validateBySchema(e,t)}o(bhe,"updateSSHKeyValidator");function Ihe(e){let t=we.object({name:we.string().required()});return ds.validateBySchema(e,t)}o(Ihe,"deleteSSHKeyValidator");function Nhe(e){let t=we.object({known_hosts:we.string().required()});return ds.validateBySchema(e,t)}o(Nhe,"setSSHKnownHostsValidator")});var mp=M((g0e,BK)=>{"use strict";var gT=require("joi"),lc=require("path"),Zd=require("fs-extra"),{exec:whe,spawn:Ohe}=require("child_process"),Che=require("util"),Phe=Che.promisify(whe),ef=(k(),v(W)),{PACKAGE_ROOT:Lhe}=Rt(),{handleHDBError:dp,hdbErrors:Dhe}=ge(),{HTTP_STATUS_CODES:fp}=Dhe,$l=oe(),Mhe=ut(),uc=Q(),{once:vhe}=require("events");$l.initSync();var lC=$l.get(ef.CONFIG_PARAMS.COMPONENTSROOT),MK="npm install --force --omit=dev --json",Uhe=`${MK} --dry-run`,xhe=$l.get(ef.CONFIG_PARAMS.ROOTPATH),ST=lc.join(xhe,"ssh");BK.exports={installModules:khe,auditModules:Ghe,installAllRootModules:Bhe,uninstallRootModule:Fhe,linkHarperdb:Hhe,runCommand:tf};async function Bhe(e=!1,t=$l.get(ef.CONFIG_PARAMS.ROOTPATH)){await TT();let r=!1,n=process.env;Zd.pathExistsSync(ST)&&Zd.readdirSync(ST).forEach(s=>{s.includes(".key")&&!r&&(n={GIT_SSH_COMMAND:"ssh -F "+lc.join(ST,"config")+" -o UserKnownHostsFile="+lc.join(ST,"known_hosts"),...process.env},r=!0)});try{let s=$l.get(ef.CONFIG_PARAMS.ROOTPATH),i=lc.join(s,"node_modules","harperdb");Zd.lstatSync(i).isSymbolicLink()&&Zd.unlinkSync(i)}catch(s){s.code!=="ENOENT"&&uc.error("Error removing symlink:",s)}await tf(e?"npm install --force --ignore-scripts":"npm install --force",t,n)}o(Bhe,"installAllRootModules");async function Fhe(e){await tf(`npm uninstall ${e}`,$l.get(ef.CONFIG_PARAMS.ROOTPATH))}o(Fhe,"uninstallRootModule");async function Hhe(){await TT(),await tf(`npm link ${Lhe}`,$l.get(ef.CONFIG_PARAMS.ROOTPATH))}o(Hhe,"linkHarperdb");async function tf(e,t=void 0,r=process.env){uc.debug({tagName:"npm_run_command"},`running command: \`${e}\``);let n=Ohe(e,{shell:!0,cwd:t,env:r,stdio:["ignore","pipe","pipe"]}),s="",i="";n.stdout.on("data",c=>{let l=c.toString();uc.debug({tagName:"npm_run_command:stdout"},l),s+=l}),n.stderr.on("data",c=>{let l=c.toString();uc.error({tagName:"npm_run_command:stderr"},l),i+=l});let[a]=await vhe(n,"close");if(a!==0)throw new Error(`Command \`${e}\` exited with code ${a}.${i===""?"":` Error: ${i}`}`);return s||void 0}o(tf,"runCommand");async function khe(e){let t="install_node_modules is deprecated. Dependencies are automatically installed on deploy, and install_node_modules can lead to inconsistent behavior";uc.warn(t,e.projects);let r=xK(e);if(r)throw dp(r,r.message,fp.BAD_REQUEST);let{projects:n,dryRun:s}=e,i=s===!0?Uhe:MK;await TT(),await UK(n);let a={};for(let c=0,l=n.length;c<l;c++){let u=n[c];a[u]={npm_output:null,npm_error:null};let d=lc.join(lC,u),f,m=null;try{let{stdout:h,stderr:p}=await Phe(i,{cwd:d});f=h?h.replace(`
21
21
  `,""):null,m=p?p.replace(`
22
22
  `,""):null}catch(h){h.stderr?a[u].npm_error=vK(h.stderr):a[u].npm_error=h.message;continue}try{a[u].npm_output=JSON.parse(f)}catch{a[u].npm_output=f}try{a[u].npm_error=JSON.parse(m)}catch{a[u].npm_error=m}}return uc.info(`finished installModules with response ${a}`),a.warning=t,a}o(khe,"installModules");function vK(e){let t='"error": {',r=e.indexOf('"error": {'),n=e.indexOf(`}