harperdb 4.2.0-alpha.12 → 4.2.0-alpha.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/harperdb.js +5 -5
- package/bin/lite.js +2 -2
- package/launchServiceScripts/launchInstallNATSServer.js +1 -1
- package/launchServiceScripts/launchNatsIngestService.js +2 -2
- package/launchServiceScripts/launchNatsReplyService.js +2 -2
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +2 -2
- package/package.json +1 -1
- package/server/jobs/jobProcess.js +2 -2
- package/server/threads/threadServer.js +3 -3
- package/utility/scripts/restartHdb.js +2 -2
package/bin/harperdb.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
"use strict";var xG=Object.create;var mc=Object.defineProperty;var kG=Object.getOwnPropertyDescriptor;var $G=Object.getOwnPropertyNames;var VG=Object.getPrototypeOf,YG=Object.prototype.hasOwnProperty;var a=(e,t)=>mc(e,"name",{value:t,configurable:!0});var Te=(e,t)=>()=>(e&&(t=e(e=0)),t);var m=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ke=(e,t)=>{for(var r in t)mc(e,r,{get:t[r],enumerable:!0})},mO=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of $G(t))!YG.call(e,n)&&n!==r&&mc(e,n,{get:()=>t[n],enumerable:!(s=kG(t,n))||s.enumerable});return e};var D=(e,t,r)=>(r=e!=null?xG(VG(e)):{},mO(t||!e||!e.__esModule?mc(r,"default",{value:e,enumerable:!0}):r,e)),re=e=>mO(mc({},"__esModule",{value:!0}),e);var TO=m((Ile,SO)=>{var KG=require("fast-glob"),{statSync:Hh,existsSync:qh,readFileSync:WG,writeFileSync:QG}=require("fs"),{spawnSync:zG,spawn:JG}=require("child_process"),{isMainThread:jG}=require("worker_threads"),{join:on,relative:pO}=require("path"),{PACKAGE_ROOT:qr}=R(),{tmpdir:XG}=require("os");require("source-map-support").install();var ZG=["resources","server","dataLayer"],pc="ts-build",Fh,ex=__filename.endsWith("tsBuild.js");if(ex){if(jG){let r;try{Hh(on(qr,pc)),r=!0}catch{}if(r)for(let s of KG.sync(ZG.map(n=>n+"/**/*.ts"),{cwd:qr})){let n=0,i=0;try{n=Hh(on(qr,s)).mtimeMs-5e3,i=Hh(on(qr,pc,s.replace(/.ts$/,".js"))).mtimeMs}catch{}if(n>i){console.warn(`TypeScript ${s} is not compiled`+(i?` (TS source file was modified at ${new Date(n)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),Fh=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),Fh=!0;if(Fh){let s=zG(process.argv[0],[on(qr,"node_modules/.bin/tsc")],{cwd:qr});if(s.stdout.length&&console.log(s.stdout.toString()),s.stderr.length&&console.log(s.stderr.toString()),r){let n=on(XG(),"harperdb-tsc.pid"),i;if(qh(n))try{process.kill(+WG(n,{encoding:"utf8"}),0),i=!0}catch{}if(!i){console.log("starting tsc background process");let o=JG(process.argv[0],[on(qr,"node_modules/.bin/tsc"),"--watch"],{cwd:qr,detached:!0,stdio:"ignore"});QG(n,o.pid.toString()),o.unref()}}}}let e=SO.constructor,t=e._findPath;e._findPath=function(r,s,n){if(r.startsWith(".")&&!n&&s.length===1&&s[0].startsWith(qr)&&!s[0].includes("node_modules")){let i=pO(qr,s[0]),o;i.startsWith(pc)?o=on(qr,pO(pc,i)):o=on(qr,pc,i);let c=on(o,r),u=c+".js";if(qh(u))return u;if(c.includes(".")&&qh(c))return c}return t(r,s,n)}}});var R=m((Lle,MO)=>{"use strict";var Fr=require("path"),tx=require("fs"),{relative:wle,join:Cle}=Fr,{existsSync:rx}=tx;function sx(){let e=__dirname;for(;!rx(Fr.join(e,"package.json"));){let t=Fr.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(sx,"getHDBPackageRoot");var Qn=sx(),gO="js",t_=gO,nx="harperdb-config.yaml",ix="defaultConfig.yaml",ox="hdb",RO=`harperdb.${t_}`,AO=`customFunctionsServer.${t_}`,ax=`restartHdb.${t_}`,xh="HarperDB",e_="Custom Functions",r_="Clustering Hub",s_="Clustering Leaf",cx="Clustering Ingest Service",ux="Clustering Reply Service",lx="foreground.pid",_x="hdb.pid",dx="data",Ex={HDB:xh,CLUSTERING_HUB:r_,CLUSTERING_LEAF:s_,CLUSTERING_INGEST_SERVICE:cx,CLUSTERING_REPLY_SERVICE:ux,CUSTOM_FUNCTIONS:e_,RESTART_HDB:"Restart HDB",INSTALL:"Install",RUN:"Run",STOP:"Stop",UPGRADE:"Upgrade",REGISTER:"Register",JOB:"Job",CLUSTERING_UPGRADE_4_0_0:"Upgrade-4-0-0"},fx={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},hx={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},mx={harperdb:xh,"clustering hub":r_,"clustering leaf":s_,"custom functions":e_,custom_functions:e_,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},px={CLUSTERING_HUB_PROC_DESCRIPTOR:r_,CLUSTERING_LEAF_PROC_DESCRIPTOR:s_},Gh={HDB:Fr.join(Qn,"server/harperdb"),CUSTOM_FUNCTIONS:Fr.join(Qn,"server/customFunctions"),CLUSTERING_HUB:Fr.join(Qn,"server/nats"),CLUSTERING_LEAF:Fr.join(Qn,"server/nats")},Sx={HDB:Fr.join(Gh.HDB,RO),CUSTOM_FUNCTIONS:Fr.join(Gh.CUSTOM_FUNCTIONS,AO)},Tx={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:Fr.join(Qn,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:Fr.join(Qn,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:Fr.join(Qn,"launchServiceScripts/launchUpdateNodes4-0-0.js")},gx={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},OO="support@harperdb.io",Rx="customer-success@harperdb.io",NO=1,Ax=4141,bO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",Ox="https://www.harperdb.io/product",Nx=`For support, please submit a request at ${bO} or contact ${OO}`,yO=`For license support, please contact ${Rx}`,bx="None of the specified records were found.",yx="hash attribute not found",Ix=`Your current license only supports ${NO} role. ${yO}`,wx="Your current license only supports 3 connections to a node.",Cx="127.0.0.1",Lx=1,Dx=/^\.$/,Ux=/^\.\.$/,Mx="U+002E",Px=/\//g,vx="U+002F",Bx=/U\+002F/g,Hx=/^U\+002E$/,qx=/^U\+002EU\+002E$/,Fx="d",Gx=999999,xx="*",kx="--max-old-space-size=",$x="system",Vx="__hdb_hash",Yx=".harperdb",Kx=".hdb",Wx="keys",Qx="hdb_boot_properties.file",zx=".updateConfig.json",Jx="SIGTSTP",jx=24,Xx=6e4,Zx=448,ek="blob",tk="trash",rk="database",sk="schema",nk="transactions",ik=".count",ok="id",ak="PROCESS_NAME",IO={SETTINGS_PATH_KEY:"settings_path"},wO=require("lodash"),ck={TC_AGREEMENT:"TC_AGREEMENT",CLUSTERING_USER:"CLUSTERING_USER",CLUSTERING_PASSWORD:"CLUSTERING_PASSWORD",HDB_ADMIN_USERNAME:"HDB_ADMIN_USERNAME",HDB_ADMIN_PASSWORD:"HDB_ADMIN_PASSWORD",OPERATIONSAPI_ROOT:"OPERATIONSAPI_ROOT",ROOTPATH:"ROOTPATH",OPERATIONSAPI_NETWORK_PORT:"OPERATIONSAPI_NETWORK_PORT",CLUSTERING_NODENAME:"CLUSTERING_NODENAME",CLUSTERING_ENABLED:"CLUSTERING_ENABLED",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},uk={HDB_PATH_KEY:"HDB_INTERNAL_PATH",HDB_AUTH_HEADER:"hdb_auth_header",HDB_USER_DATA_KEY:"hdb_user",CHUNK_SIZE:1e3,MAX_CHARACTER_SIZE:250},lk={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},_k={JOB_TABLE_NAME:"hdb_job",NODE_TABLE_NAME:"hdb_nodes",ATTRIBUTE_TABLE_NAME:"hdb_attribute",LICENSE_TABLE_NAME:"hdb_license",ROLE_TABLE_NAME:"hdb_role",SCHEMA_TABLE_NAME:"hdb_schema",TABLE_TABLE_NAME:"hdb_table",USER_TABLE_NAME:"hdb_user",INFO_TABLE_NAME:"hdb_info"},dk={JOB_TABLE_HASH_ATTRIBUTE:"id",NODE_TABLE_HASH_ATTRIBUTE:"name",ATTRIBUTE_TABLE_HASH_ATTRIBUTE:"id",LICENSE_TABLE_HASH_ATTRIBUTE:"license_key",ROLE_TABLE_HASH_ATTRIBUTE:"id",SCHEMA_TABLE_HASH_ATTRIBUTE:"name",TABLE_TABLE_HASH_ATTRIBUTE:"id",USER_TABLE_HASH_ATTRIBUTE:"username",INFO_TABLE_ATTRIBUTE:"info_id"},Tr="hdb_internal:",Ek={CREATE_SCHEMA:Tr+"create_schema",CREATE_TABLE:Tr+"create_table",CREATE_ATTRIBUTE:Tr+"create_attribute",ADD_USER:Tr+"add_user",ALTER_USER:Tr+"alter_user",DROP_USER:Tr+"drop_user",HDB_NODES:Tr+"hdb_nodes",HDB_USERS:Tr+"hdb_users",HDB_WORKERS:Tr+"hdb_workers",CATCHUP:Tr+"catchup",SCHEMA_CATCHUP:Tr+"schema_catchup",WORKER_ROOM:Tr+"cluster_workers"},fk={ATTR_ATTRIBUTE_KEY:"attribute",ATTR_CREATEDDATE_KEY:"createddate",ATTR_HASH_ATTRIBUTE_KEY:"hash_attribute",ATTR_ID_KEY:"id",ATTR_NAME_KEY:"name",ATTR_PASSWORD_KEY:"password",ATTR_RESIDENCE_KEY:"residence",ATTR_ROLE_KEY:"role",ATTR_SCHEMA_KEY:"schema",ATTR_SCHEMA_TABLE_KEY:"schema_table",ATTR_TABLE_KEY:"table",ATTR_USERNAME_KEY:"username"},hk="060493.ks",mk=".license",pk={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},W={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",SEARCH_BY_ID:"search_by_id",SEARCH_BY_VALUE:"search_by_value",SEARCH:"search",SQL:"sql",CSV_DATA_LOAD:"csv_data_load",CSV_FILE_LOAD:"csv_file_load",CSV_URL_LOAD:"csv_url_load",CREATE_SCHEMA:"create_schema",CREATE_DATABASE:"create_database",CREATE_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_DATABASE:"drop_database",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",DESCRIBE_DATABASE:"describe_database",DESCRIBE_TABLE:"describe_table",DESCRIBE_ALL:"describe_all",DELETE:"delete",ADD_USER:"add_user",ALTER_USER:"alter_user",DROP_USER:"drop_user",LIST_USERS:"list_users",LIST_ROLES:"list_roles",ADD_ROLE:"add_role",ALTER_ROLE:"alter_role",DROP_ROLE:"drop_role",USER_INFO:"user_info",READ_LOG:"read_log",ADD_NODE:"add_node",UPDATE_NODE:"update_node",EXPORT_TO_S3:"export_to_s3",IMPORT_FROM_S3:"import_from_s3",DELETE_FILES_BEFORE:"delete_files_before",DELETE_RECORDS_BEFORE:"delete_records_before",EXPORT_LOCAL:"export_local",SEARCH_JOBS_BY_START_DATE:"search_jobs_by_start_date",GET_JOB:"get_job",DELETE_JOB:"delete_job",UPDATE_JOB:"update_job",GET_FINGERPRINT:"get_fingerprint",SET_LICENSE:"set_license",GET_REGISTRATION_INFO:"registration_info",CONFIGURE_CLUSTER:"configure_cluster",SET_CONFIGURATION:"set_configuration",CLUSTER_STATUS:"cluster_status",CLUSTER_NETWORK:"cluster_network",DROP_ATTRIBUTE:"drop_attribute",REMOVE_NODE:"remove_node",RESTART:"restart",RESTART_SERVICE:"restart_service",CATCHUP:"catchup",SYSTEM_INFORMATION:"system_information",DELETE_AUDIT_LOGS_BEFORE:"delete_audit_logs_before",READ_AUDIT_LOG:"read_audit_log",CREATE_AUTHENTICATION_TOKENS:"create_authentication_tokens",LOGIN:"login",LOGOUT:"logout",REFRESH_OPERATION_TOKEN:"refresh_operation_token",GET_CONFIGURATION:"get_configuration",CUSTOM_FUNCTIONS_STATUS:"custom_functions_status",GET_CUSTOM_FUNCTIONS:"get_custom_functions",GET_CUSTOM_FUNCTION:"get_custom_function",SET_CUSTOM_FUNCTION:"set_custom_function",GET_COMPONENTS:"get_components",GET_COMPONENT_FILE:"get_component_file",SET_COMPONENT_FILE:"set_component_file",DROP_COMPONENT:"drop_component",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",ADD_COMPONENT:"add_component",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",PACKAGE_COMPONENT:"package_component",DEPLOY_COMPONENT:"deploy_component",CLUSTER_SET_ROUTES:"cluster_set_routes",CLUSTER_DELETE_ROUTES:"cluster_delete_routes",CLUSTER_GET_ROUTES:"cluster_get_routes",READ_TRANSACTION_LOG:"read_transaction_log",DELETE_TRANSACTION_LOGS_BEFORE:"delete_transaction_logs_before",INSTALL_NODE_MODULES:"install_node_modules",AUDIT_NODE_MODULES:"audit_node_modules",PURGE_STREAM:"purge_stream",GET_BACKUP:"get_backup"},Sk={CSV:".csv",JSON:".json"},Tk={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},gk={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Sc={};Sc[W.INSERT]=W.INSERT;Sc[W.UPDATE]=W.UPDATE;Sc[W.UPSERT]=W.UPSERT;Sc[W.DELETE]=W.DELETE;var Oe=Object.create(null);Oe[W.DESCRIBE_ALL]=W.DESCRIBE_ALL;Oe[W.DESCRIBE_TABLE]=W.DESCRIBE_TABLE;Oe[W.DESCRIBE_SCHEMA]=W.DESCRIBE_SCHEMA;Oe[W.READ_LOG]=W.READ_LOG;Oe[W.ADD_NODE]=W.ADD_NODE;Oe[W.LIST_USERS]=W.LIST_USERS;Oe[W.LIST_ROLES]=W.LIST_ROLES;Oe[W.USER_INFO]=W.USER_INFO;Oe[W.SQL]=W.SQL;Oe[W.GET_JOB]=W.GET_JOB;Oe[W.SEARCH_JOBS_BY_START_DATE]=W.SEARCH_JOBS_BY_START_DATE;Oe[W.DELETE_FILES_BEFORE]=W.DELETE_FILES_BEFORE;Oe[W.EXPORT_LOCAL]=W.EXPORT_LOCAL;Oe[W.EXPORT_TO_S3]=W.EXPORT_TO_S3;Oe[W.CLUSTER_STATUS]=W.CLUSTER_STATUS;Oe[W.REMOVE_NODE]=W.REMOVE_NODE;Oe[W.RESTART]=W.RESTART;Oe[W.CUSTOM_FUNCTIONS_STATUS]=W.CUSTOM_FUNCTIONS_STATUS;Oe[W.GET_CUSTOM_FUNCTIONS]=W.GET_CUSTOM_FUNCTIONS;Oe[W.GET_CUSTOM_FUNCTION]=W.GET_CUSTOM_FUNCTION;Oe[W.SET_CUSTOM_FUNCTION]=W.SET_CUSTOM_FUNCTION;Oe[W.DROP_CUSTOM_FUNCTION]=W.DROP_CUSTOM_FUNCTION;Oe[W.ADD_CUSTOM_FUNCTION_PROJECT]=W.ADD_CUSTOM_FUNCTION_PROJECT;Oe[W.DROP_CUSTOM_FUNCTION_PROJECT]=W.DROP_CUSTOM_FUNCTION_PROJECT;Oe[W.PACKAGE_CUSTOM_FUNCTION_PROJECT]=W.PACKAGE_CUSTOM_FUNCTION_PROJECT;Oe[W.DEPLOY_CUSTOM_FUNCTION_PROJECT]=W.DEPLOY_CUSTOM_FUNCTION_PROJECT;var Rk={DEBUG:"debug",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status"},Ak={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},CO={HDB_ROOT_KEY:"HDB_ROOT",SERVER_PORT_KEY:"SERVER_PORT",CERT_KEY:"CERTIFICATE",PRIVATE_KEY_KEY:"PRIVATE_KEY",HTTP_SECURE_ENABLED_KEY:"HTTPS_ON",CORS_ENABLED_KEY:"CORS_ON",CORS_WHITELIST_KEY:"CORS_WHITELIST",LOG_LEVEL_KEY:"LOG_LEVEL",LOGGER_KEY:"LOGGER",LOG_PATH_KEY:"LOG_PATH",LOG_ROTATE:"LOG_ROTATE",LOG_ROTATE_MAX_SIZE:"LOG_ROTATE_MAX_SIZE",LOG_ROTATE_RETAIN:"LOG_ROTATE_RETAIN",LOG_ROTATE_COMPRESS:"LOG_ROTATE_COMPRESS",LOG_ROTATE_DATE_FORMAT:"LOG_ROTATE_DATE_FORMAT",LOG_ROTATE_ROTATE_MODULE:"LOG_ROTATE_ROTATE_MODULE",LOG_ROTATE_WORKER_INTERVAL:"LOG_ROTATE_WORKER_INTERVAL",LOG_ROTATE_ROTATE_INTERVAL:"LOG_ROTATE_ROTATE_INTERVAL",LOG_ROTATE_TIMEZONE:"LOG_ROTATE_TIMEZONE",LOG_DAILY_ROTATE_KEY:"LOG_DAILY_ROTATE",LOG_MAX_DAILY_FILES_KEY:"LOG_MAX_DAILY_FILES",PROPS_ENV_KEY:"NODE_ENV",SETTINGS_PATH_KEY:"settings_path",CLUSTERING_PORT_KEY:"CLUSTERING_PORT",CLUSTERING_NODE_NAME_KEY:"NODE_NAME",CLUSTERING_ENABLED_KEY:"CLUSTERING",ALLOW_SELF_SIGNED_SSL_CERTS:"ALLOW_SELF_SIGNED_SSL_CERTS",MAX_HDB_PROCESSES:"MAX_HDB_PROCESSES",INSTALL_USER:"install_user",CLUSTERING_USER_KEY:"CLUSTERING_USER",MAX_CLUSTERING_PROCESSES:"MAX_CLUSTERING_PROCESSES",SERVER_TIMEOUT_KEY:"SERVER_TIMEOUT_MS",SERVER_KEEP_ALIVE_TIMEOUT_KEY:"SERVER_KEEP_ALIVE_TIMEOUT",SERVER_HEADERS_TIMEOUT_KEY:"SERVER_HEADERS_TIMEOUT",DISABLE_TRANSACTION_LOG_KEY:"DISABLE_TRANSACTION_LOG",OPERATION_TOKEN_TIMEOUT_KEY:"OPERATION_TOKEN_TIMEOUT",REFRESH_TOKEN_TIMEOUT_KEY:"REFRESH_TOKEN_TIMEOUT",CUSTOM_FUNCTIONS_ENABLED_KEY:"CUSTOM_FUNCTIONS",CUSTOM_FUNCTIONS_PORT_KEY:"CUSTOM_FUNCTIONS_PORT",CUSTOM_FUNCTIONS_DIRECTORY_KEY:"CUSTOM_FUNCTIONS_DIRECTORY",MAX_CUSTOM_FUNCTION_PROCESSES:"MAX_CUSTOM_FUNCTION_PROCESSES",LOG_TO_FILE:"LOG_TO_FILE",LOG_TO_STDSTREAMS:"LOG_TO_STDSTREAMS",RUN_IN_FOREGROUND:"RUN_IN_FOREGROUND",LOCAL_STUDIO_ON:"LOCAL_STUDIO_ON",STORAGE_WRITE_ASYNC:"STORAGE_WRITE_ASYNC"},Ok=wO.invert(CO),O={ANALYTICS_AGGREGATEPERIOD:"analytics_aggregatePeriod",AUTHENTICATION_AUTHORIZELOCAL:"authentication_authorizeLocal",AUTHENTICATION_CACHETTL:"authentication_cacheTTL",AUTHENTICATION_ENABLESESSIONS:"authentication_enableSessions",AUTHENTICATION_OPERATIONTOKENTIMEOUT:"authentication_operationTokenTimeout",AUTHENTICATION_REFRESHTOKENTIMEOUT:"authentication_refreshTokenTimeout",CLUSTERING_USER:"clustering_user",CLUSTERING_ENABLED:"clustering_enabled",CLUSTERING_HUBSERVER_CLUSTER_NAME:"clustering_hubServer_cluster_name",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT:"clustering_hubServer_cluster_network_port",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES:"clustering_hubServer_cluster_network_routes",CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT:"clustering_hubServer_leafNodes_network_port",CLUSTERING_HUBSERVER_NETWORK_PORT:"clustering_hubServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_PORT:"clustering_leafServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_ROUTES:"clustering_leafServer_network_routes",CLUSTERING_LEAFSERVER_STREAMS_MAXAGE:"clustering_leafServer_streams_maxAge",CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES:"clustering_leafServer_streams_maxBytes",CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS:"clustering_leafServer_streams_maxMsgs",CLUSTERING_LEAFSERVER_STREAMS_PATH:"clustering_leafServer_streams_path",CLUSTERING_NODENAME:"clustering_nodeName",CLUSTERING_TLS_CERTIFICATE:"clustering_tls_certificate",CLUSTERING_TLS_PRIVATEKEY:"clustering_tls_privateKey",CLUSTERING_TLS_CERT_AUTH:"clustering_tls_certificateAuthority",CLUSTERING_TLS_INSECURE:"clustering_tls_insecure",CLUSTERING_TLS_VERIFY:"clustering_tls_verify",CLUSTERING_LOGLEVEL:"clustering_logLevel",CLUSTERING_REPUBLISHMESSAGES:"clustering_republishMessages",CLUSTERING_DATABASELEVEL:"clustering_databaseLevel",CUSTOMFUNCTIONS_ENABLED:"customFunctions_enabled",CUSTOMFUNCTIONS_NETWORK_PORT:"customFunctions_network_port",CUSTOMFUNCTIONS_TLS_CERTIFICATE:"customFunctions_tls_certificate",CUSTOMFUNCTIONS_NETWORK_CORS:"customFunctions_network_cors",CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST:"customFunctions_network_corsAccessList",CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT:"customFunctions_network_headersTimeout",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT:"customFunctions_network_keepAliveTimeout",CUSTOMFUNCTIONS_TLS_PRIVATEKEY:"customFunctions_tls_privateKey",CUSTOMFUNCTIONS_TLS_CERT_AUTH:"customFunctions_tls_certificateAuthority",CUSTOMFUNCTIONS_NETWORK_TIMEOUT:"customFunctions_network_timeout",CUSTOMFUNCTIONS_NODEENV:"customFunctions_nodeEnv",CUSTOMFUNCTIONS_ROOT:"customFunctions_root",HTTP_THREADS:"http_threads",HTTP_SESSION_AFFINITY:"http_sessionAffinity",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_ROTATION_ENABLED:"logging_rotation_enabled",LOGGING_ROTATION_COMPRESS:"logging_rotation_compress",LOGGING_ROTATION_INTERVAL:"logging_rotation_interval",LOGGING_ROTATION_MAXSIZE:"logging_rotation_maxSize",LOGGING_ROTATION_PATH:"logging_rotation_path",LOGGING_STDSTREAMS:"logging_stdStreams",LOGGING_AUDITLOG:"logging_auditLog",LOGGING_AUDITRETENTION:"logging_auditRetention",LOGGING_AUDITAUTHEVENTS_LOGFAILED:"logging_auditAuthEvents_logFailed",LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL:"logging_auditAuthEvents_logSuccessful",OPERATIONSAPI_AUTHENTICATION_OPERATIONTOKENTIMEOUT:"operationsApi_authentication_operationTokenTimeout",OPERATIONSAPI_AUTHENTICATION_REFRESHTOKENTIMEOUT:"operationsApi_authentication_refreshTokenTimeout",OPERATIONSAPI_FOREGROUND:"operationsApi_foreground",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",OPERATIONSAPI_NETWORK_CORS:"operationsApi_network_cors",OPERATIONSAPI_NETWORK_CORSACCESSLIST:"operationsApi_network_corsAccessList",OPERATIONSAPI_NETWORK_HEADERSTIMEOUT:"operationsApi_network_headersTimeout",OPERATIONSAPI_NETWORK_HTTPS:"operationsApi_network_https",OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT:"operationsApi_network_keepAliveTimeout",OPERATIONSAPI_NETWORK_PORT:"operationsApi_network_port",OPERATIONSAPI_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERT_AUTH:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",OPERATIONSAPI_NODEENV:"operationsApi_nodeEnv",ROOTPATH:"rootPath",STORAGE_WRITEASYNC:"storage_writeAsync",STORAGE_OVERLAPPINGSYNC:"storage_overlappingSync",STORAGE_CACHING:"storage_caching",STORAGE_COMPRESSION:"storage_compression",STORAGE_NOREADAHEAD:"storage_noReadAhead",STORAGE_PREFETCHWRITES:"storage_prefetchWrites",STORAGE_ENCRYPTION:"storage_encryption",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",SCHEMAS:"schemas",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication"},LO={settings_path:IO.SETTINGS_PATH_KEY,hdb_root_key:O.ROOTPATH,hdb_root:O.ROOTPATH,server_port_key:O.OPERATIONSAPI_NETWORK_PORT,server_port:O.OPERATIONSAPI_NETWORK_PORT,cert_key:O.OPERATIONSAPI_TLS_CERTIFICATE,certificate:O.OPERATIONSAPI_TLS_CERTIFICATE,private_key_key:O.OPERATIONSAPI_TLS_PRIVATEKEY,private_key:O.OPERATIONSAPI_TLS_PRIVATEKEY,http_secure_enabled_key:O.OPERATIONSAPI_NETWORK_HTTPS,https_on:O.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:O.OPERATIONSAPI_NETWORK_CORS,cors_on:O.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:O.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:O.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:O.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:O.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:O.LOGGING_LEVEL,log_level:O.LOGGING_LEVEL,log_path_key:O.LOGGING_ROOT,log_path:O.LOGGING_ROOT,props_env_key:O.OPERATIONSAPI_NODEENV,node_env:O.OPERATIONSAPI_NODEENV,clustering_node_name_key:O.CLUSTERING_NODENAME,node_name:O.CLUSTERING_NODENAME,clustering_enabled_key:O.CLUSTERING_ENABLED,clustering:O.CLUSTERING_ENABLED,max_http_threads:O.HTTP_THREADS,max_hdb_processes:O.HTTP_THREADS,server_timeout_key:O.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:O.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:O.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:O.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:O.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:O.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:O.LOGGING_AUDITLOG,disable_transaction_log:O.LOGGING_AUDITLOG,operation_token_timeout_key:O.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:O.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:O.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:O.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_enabled_key:O.CUSTOMFUNCTIONS_ENABLED,custom_functions:O.CUSTOMFUNCTIONS_ENABLED,custom_functions_port_key:O.CUSTOMFUNCTIONS_NETWORK_PORT,custom_functions_port:O.CUSTOMFUNCTIONS_NETWORK_PORT,custom_functions_directory_key:O.CUSTOMFUNCTIONS_ROOT,custom_functions_directory:O.CUSTOMFUNCTIONS_ROOT,max_custom_function_processes:O.HTTP_THREADS,log_to_file:O.LOGGING_FILE,log_to_stdstreams:O.LOGGING_STDSTREAMS,run_in_foreground:O.OPERATIONSAPI_FOREGROUND,local_studio_on:O.LOCALSTUDIO_ENABLED,clustering_port:O.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:O.CLUSTERING_USER,clustering_enabled:O.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:O.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:O.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:O.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:O.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:O.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:O.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:O.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:O.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:O.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxmsgs:O.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:O.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:O.CLUSTERING_NODENAME,clustering_tls_certificate:O.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:O.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:O.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:O.CLUSTERING_TLS_INSECURE,clustering_tls_verify:O.CLUSTERING_TLS_VERIFY,clustering_loglevel:O.CLUSTERING_LOGLEVEL,clustering_republishmessages:O.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:O.CLUSTERING_DATABASELEVEL,customfunctions_enabled:O.CUSTOMFUNCTIONS_ENABLED,customfunctions_network_port:O.CUSTOMFUNCTIONS_NETWORK_PORT,customfunctions_tls_certificate:O.CUSTOMFUNCTIONS_TLS_CERTIFICATE,customfunctions_network_cors:O.CUSTOMFUNCTIONS_NETWORK_CORS,customfunctions_network_corsaccesslist:O.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,customfunctions_network_headerstimeout:O.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,customfunctions_network_https:O.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:O.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:O.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:O.CUSTOMFUNCTIONS_TLS_CERT_AUTH,customfunctions_network_timeout:O.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,customfunctions_nodeenv:O.CUSTOMFUNCTIONS_NODEENV,http_threads:O.HTTP_THREADS,http_session_affinity:O.HTTP_SESSION_AFFINITY,customfunctions_processes:O.HTTP_THREADS,customfunctions_root:O.CUSTOMFUNCTIONS_ROOT,localstudio_enabled:O.LOCALSTUDIO_ENABLED,logging_file:O.LOGGING_FILE,logging_level:O.LOGGING_LEVEL,logging_root:O.LOGGING_ROOT,logging_rotation_enabled:O.LOGGING_ROTATION_ENABLED,logging_rotation_compress:O.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:O.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:O.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:O.LOGGING_ROTATION_PATH,logging_stdstreams:O.LOGGING_STDSTREAMS,logging_auditlog:O.LOGGING_AUDITLOG,logging_auditretention:O.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:O.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:O.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:O.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:O.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_foreground:O.OPERATIONSAPI_FOREGROUND,operationsapi_tls_certificate:O.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_network_cors:O.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:O.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:O.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:O.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:O.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:O.OPERATIONSAPI_NETWORK_PORT,operationsapi_tls_privatekey:O.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:O.OPERATIONSAPI_TLS_CERT_AUTH,operationsapi_network_timeout:O.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_nodeenv:O.OPERATIONSAPI_NODEENV,operationsapi_root:O.ROOTPATH,schemas:O.SCHEMAS,storage_path:O.STORAGE_PATH,ignorescripts:O.IGNORE_SCRIPTS,mqtt_network_port:O.MQTT_NETWORK_PORT,mqtt_websocket:O.MQTT_WEBSOCKET,mqtt_network_secureport:O.MQTT_NETWORK_SECUREPORT,mqtt_requireauthentication:O.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:O.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:O.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:O.AUTHENTICATION_CACHETTL,authentication_enablesessions:O.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:O.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:O.AUTHENTICATION_REFRESHTOKENTIMEOUT};for(let e in O){let t=O[e];LO[t.toLowerCase()]=t}var Nk={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},bk={csv_file_load:"csv_file_load",csv_data_load:W.CSV_DATA_LOAD,csv_url_load:W.CSV_URL_LOAD,delete_files_before:"delete_files_before",delete_records_before:"delete_records_before",delete_audit_logs_before:"delete_audit_logs_before",delete_transaction_logs_before:"delete_transaction_logs_before",empty_trash:"empty_trash",export_local:"export_local",export_to_s3:"export_to_s3",import_from_s3:"import_from_s3"},yk={CLUSTERING_PAYLOAD:"clustering_payload",DELEGATE_THREAD_RESPONSE:"delegate_thread_response",CLUSTERING:"clustering",SCHEMA:"schema",CLUSTER_STATUS:"cluster_status",JOB:"job",CHILD_STARTED:"child_started",CHILD_STOPPED:"child_stopped",USER:"user",RESTART:"restart"},Ik={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},wk={VERSION_DEFAULT:"2.2.0"},Ck={DEVELOPMENT:8192,DEFAULT:512},Lk={IDENTIFY:"identify",AUTHENTICATE:"authenticate",AUTHENTICATE_OK:"authenticated",AUTHENTICATE_FAIL:"authenticate_fail",CONNECTION:"connection",CONNECT:"connect",CATCHUP_REQUEST:"catchup_request",CATCHUP_RESPONSE:"catchup",CONFIRM_MSG:"confirm_msg",ERROR:"error",DISCONNECT:"disconnect",SCHEMA_UPDATE_REQ:"schema_update_request",SCHEMA_UPDATE_RES:"schema_update_response",RECONNECT_ATTEMPT:"reconnect_attempt",CONNECT_ERROR:"connect_error",MESSAGE:"msg",VERSION_MISMATCH:"version_mismatch",DIRECTION_CHANGE:"direction_change"},Dk={1e3:"SUCCESSFUL_SHUTDOWN",1001:"CLOSE_GOING_AWAY",1002:"CLOSE_PROTOCOL_ERROR",1003:"CLOSE_UNSUPPORTED",1005:"CLOSE_NO_STATUS",1006:"CLOSE_ABNORMAL",1007:"UNSUPPORTED_PAYLOAD",1008:"POLICY_VIOLATION",1009:"CLOSE_TOO_LARGE",1010:"MANDATORY_EXTENSION",1011:"SERVER_ERROR",1012:"SERVICE_RESTART",1013:"SERVER_BUSY",1014:"BAD_GATEWAY",1015:"HANDSHAKE_FAIL",4141:"LICENSE_LIMIT_REACHED"},Uk={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},DO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},Mk=Symbol("metadata"),Pk="__clustering__",vk=Object.values(DO),Bk=15984864e5,UO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},Hk=wO.invert(UO),qk={GET_CLUSTER_STATUS:"GET_CLUSTER_STATUS",CLUSTER_STATUS_RESPONSE:"CLUSTER_STATUS_RESPONSE",ERROR_RESPONSE:"ERROR",ADD_USER:"ADD_USER",ALTER_USER:"ALTER_USER",DROP_USER:"DROP_USER",HDB_OPERATION:"HDB_OPERATION",ADD_NODE:"ADD_NODE",UPDATE_NODE:"UPDATE_NODE",REMOVE_NODE:"REMOVE_NODE",HDB_USERS_MSG:"HDB_USERS_MSG",HDB_WORKERS:"HDB_WORKERS",HDB_TRANSACTION:"HDB_TRANSACTION"},Fk=111,Gk=`\r
|
|
3
3
|
`,xk={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},kk=["*","%"],$k="unauthorized_access",Vk="func_val",Yk={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},Kk={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},Wk={SHUTDOWN:"shutdown",CHILD_STARTED:"child_started",CHILD_STOPPED:"child_stopped",SCHEMA:"schema",USER:"user",CLUSTER_STATUS_RESPONSE:"cluster_status_response",CLUSTER_STATUS_REQUEST:"cluster_status_request",METRICS:"metrics",GET_METRICS:"get_metrics",RESTART:"restart"},Qk={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},zk={HTTP:"http"},Jk={STOPPED:"stopped",ONLINE:"online"},jk="3.x.x",Xk={SUCCESS:"success",FAILURE:"failure"},Zk={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};MO.exports={LOCAL_HARPERDB_OPERATIONS:Oe,HDB_SUPPORT_ADDRESS:OO,HDB_SUPPORT_URL:bO,HDB_PRICING_URL:Ox,SUPPORT_HELP_MSG:Nx,LICENSE_HELP_MSG:yO,HDB_PROC_NAME:RO,HDB_PROC_DESCRIPTOR:xh,CLUSTERING_LEAF_PROC_DESCRIPTOR:s_,CLUSTERING_HUB_PROC_DESCRIPTOR:r_,SYSTEM_SCHEMA_NAME:$x,HASH_FOLDER_NAME:Vx,HDB_HOME_DIR_NAME:Yx,UPDATE_FILE_NAME:zx,LICENSE_KEY_DIR_NAME:Wx,BOOT_PROPS_FILE_NAME:Qx,JOB_TYPE_ENUM:bk,JOB_STATUS_ENUM:pk,SYSTEM_TABLE_NAMES:_k,SYSTEM_TABLE_HASH_ATTRIBUTES:dk,OPERATIONS_ENUM:W,VALID_S3_FILE_TYPES:Sk,S3_BUCKET_AUTH_KEYS:Tk,VALID_SQL_OPS_ENUM:gk,GEO_CONVERSION_ENUM:Ak,HDB_SETTINGS_NAMES:CO,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:Ok,SERVICE_ACTIONS_ENUM:Rk,CLUSTER_MESSAGE_TYPE_ENUM:yk,CLUSTER_CONNECTION_DIRECTION_ENUM:Ik,CLUSTER_EVENTS_DEFS_ENUM:Lk,PERIOD_REGEX:Dx,DOUBLE_PERIOD_REGEX:Ux,UNICODE_PERIOD:Mx,FORWARD_SLASH_REGEX:Px,UNICODE_FORWARD_SLASH:vx,ESCAPED_FORWARD_SLASH_REGEX:Bx,ESCAPED_PERIOD_REGEX:Hx,ESCAPED_DOUBLE_PERIOD_REGEX:qx,REG_KEY_FILE_NAME:hk,RESTART_TIMEOUT_MS:Xx,HDB_FILE_PERMISSIONS:Zx,DATABASES_DIR_NAME:rk,LEGACY_DATABASES_DIR_NAME:sk,TRANSACTIONS_DIR_NAME:nk,LIMIT_COUNT_NAME:ik,ID_ATTRIBUTE_STRING:ok,INSERT_MODULE_ENUM:uk,UPGRADE_JSON_FIELD_NAMES_ENUM:lk,RESTART_CODE:Jx,RESTART_CODE_NUM:jx,CLUSTER_OPERATIONS:Sc,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:fk,HDB_INTERNAL_SC_CHANNEL_PREFIX:Tr,INTERNAL_SC_CHANNELS:Ek,CLUSTERING_MESSAGE_TYPES:qk,HDB_FILE_SUFFIX:Kx,BLOB_FOLDER_NAME:ek,HDB_TRASH_DIR:tk,ORIGINATOR_SET_VALUE:Fk,LICENSE_VALUES:wk,RAM_ALLOCATION_ENUM:Ck,TIME_STAMP_NAMES_ENUM:DO,TIME_STAMP_NAMES:vk,PERMS_UPDATE_RELEASE_TIMESTAMP:Bk,SEARCH_NOT_FOUND_MESSAGE:bx,SEARCH_ATTRIBUTE_NOT_FOUND:yx,LICENSE_ROLE_DENIED_RESPONSE:Ix,LICENSE_MAX_CONNS_REACHED:wx,BASIC_LICENSE_MAX_NON_CU_ROLES:NO,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:Ax,VALUE_SEARCH_COMPARATORS:UO,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:Hk,LICENSE_FILE_NAME:mk,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:Dk,NEW_LINE:Gk,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:Lx,MOMENT_DAYS_TAG:Fx,API_TURNOVER_SEC:Gx,LOOPBACK:Cx,CODE_EXTENSION:t_,WILDCARD_SEARCH_VALUE:xx,NODE_ERROR_CODES:Uk,JAVASCRIPT_EXTENSION:gO,PERMS_CRUD_ENUM:xk,UNAUTHORIZED_PERMISSION_NAME:$k,SEARCH_WILDCARDS:kk,FUNC_VAL:Vk,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:Yk,JWT_ENUM:Kk,CLUSTERING_FLAG:Pk,ITC_EVENT_TYPES:Wk,CUSTOM_FUNCTION_PROC_NAME:AO,CUSTOM_FUNCTION_PROC_DESCRIPTOR:e_,SERVICES:Qk,THREAD_TYPES:zk,MEM_SETTING_KEY:kx,HDB_RESTART_SCRIPT:ax,PROCESS_DESCRIPTORS:Ex,SERVICE_SERVERS:Sx,SERVICE_SERVERS_CWD:Gh,PROCESS_DESCRIPTORS_VALIDATE:mx,LAUNCH_SERVICE_SCRIPTS:Tx,LOG_LEVELS:hx,PROCESS_NAME_ENV_PROP:ak,LOG_NAMES:fx,PM2_PROCESS_STATUSES:Jk,CONFIG_PARAM_MAP:LO,CONFIG_PARAMS:O,HDB_CONFIG_FILE:nx,HDB_DEFAULT_CONFIG_FILE:ix,ROLE_TYPES_ENUM:gx,BOOT_PROP_PARAMS:IO,INSTALL_PROMPTS:ck,HDB_ROOT_DIR_NAME:ox,CLUSTERING_PROCESSES:px,FOREGROUND_PID_FILE:lx,PACKAGE_ROOT:Qn,PRE_4_0_0_VERSION:jk,SCHEMAS_PARAM_CONFIG:Nk,METADATA_PROPERTY:Mk,AUTH_AUDIT_STATUS:Xk,AUTH_AUDIT_TYPES:Zk,HDB_PID_FILE:_x,DEFAULT_DATABASE_NAME:dx};TO()});var Gi=m((Ule,BO)=>{"use strict";var PO=require("minimist");BO.exports=e$;function e$(e=[],t=!1){if(!Array.isArray(e))return{};let r,s;t?(r=vO(process.env),s=vO(PO(process.argv))):(r=process.env,s=PO(process.argv));let n={};for(let i=0,o=e.length;i<o;i++){let c=e[i];s[c]!==void 0?n[c]=s[c].toString().trim():r[c]!==void 0&&(n[c]=r[c].toString().trim())}return n}a(e$,"assignCMDENVVariables");function vO(e){let t,r=Object.keys(e),s=r.length,n={};for(;s--;)t=r[s],n[t.toLowerCase()]=e[t];return n}a(vO,"objKeysToLowerCase")});var C=m((Ple,Qh)=>{"use strict";var xi=require("fs-extra"),{workerData:t$,threadId:r$}=require("worker_threads"),un=require("path"),FO=require("yaml"),GO=require("properties-reader"),dt=R(),HO=Gi(),s$=require("os"),{PACKAGE_ROOT:$h}=R(),{_assignPackageExport:n$}=require("../index"),gc={};for(let e in console)gc[e]||(gc[e]=console[e]);var Wt={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},xO={STDOUT:"stdOut",STDERR:"stdErr"},i$=un.join($h,"logs"),o$=un.join($h,"config/yaml/",dt.HDB_DEFAULT_CONFIG_FILE),a$=1e4,an,cn,Kt,n_,i_,Rc,Wo,Tc;Tc===void 0&&kO();Qh.exports={notify:YO,fatal:KO,error:Ac,warn:Wh,info:o_,debug:Kh,trace:Yh,setLogLevel:f$,log_level:Kt,loggerWithTag:c$,suppressLogging:u$,initLogSettings:kO,setupConsoleLogging:$O,logCustomLevel:d$,closeLogFile:Vh,getLogFilePath:()=>Rc,OUTPUTS:xO,AuthAuditLog:p$};n$("logger",Qh.exports);function kO(e=!1){try{if(Tc===void 0||e){Vh();let t=E$(),r=HO(["ROOTPATH"]);try{Tc=GO(t)}catch(s){if(!r.ROOTPATH||r.ROOTPATH&&!xi.pathExistsSync(un.join(r.ROOTPATH,dt.HDB_CONFIG_FILE)))throw s}({level:Kt,config_log_path:i_,to_file:an,to_stream:cn}=h$(r.ROOTPATH?un.join(r.ROOTPATH,dt.HDB_CONFIG_FILE):Tc.get("settings_path"))),n_=dt.LOG_NAMES.HDB,Rc=un.join(i_,n_)}}catch(t){if(Tc=void 0,t.code===dt.NODE_ERROR_CODES.ENOENT){let r=HO(Object.keys(dt.CONFIG_PARAM_MAP),!0);for(let o in r){let c=dt.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===dt.CONFIG_PARAMS.LOGGING_LEVEL){Kt=u;continue}if(c===dt.CONFIG_PARAMS.LOGGING_STDSTREAMS){cn=u;continue}c===dt.CONFIG_PARAMS.LOGGING_FILE&&(an=c)}let{default_level:s,default_to_file:n,default_to_stream:i}=m$();an=an===void 0?n:an,an=qO(an),cn=cn===void 0?i:cn,cn=qO(cn),Kt=Kt===void 0?s:Kt,i_=i$,n_=dt.LOG_NAMES.INSTALL,Rc=un.join(i_,n_);return}throw Ac("Error initializing log settings"),Ac(t),t}$O()}a(kO,"initLogSettings");var kh=!0;function $O(){Ko("error",Ac),Ko("warn",Wh),Ko("log",o_),Ko("info",o_),Ko("debug",Kh),Ko("trace",Yh)}a($O,"setupConsoleLogging");function Ko(e,t){console[e]=function(...r){if(kh&&t(...r),!/PM2 log:|App \[/.test(r[0]))return gc[e](...r)}}a(Ko,"logConsole");function c$(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(YO),fatal:r(KO),error:r(Ac),warn:r(Wh),info:r(o_),debug:r(Kh),trace:r(Yh)};function r(s){return function(...n){return s(t,...n)}}}a(c$,"loggerWithTag");function u$(e){try{kh=!1,e()}finally{kh=!0}}a(u$,"suppressLogging");var l$=t$?.name?.replace(/ /g,"-")||"main";function ln(e,t){let r=new Date(Date.now()).toISOString(),s="",n=t.length,i=n-1,o=[e],c=0,u;for(typeof t[0]=="object"&&(t[0]?.tagName?(o.push(t[0]?.tagName),c++):t[0]?.serviceName&&(u=t[0]?.serviceName,c++)),o.unshift(u||l$+"/"+r$);c<n;c++){let l=t[c];l instanceof Error&&l.stack?s+=l.stack:typeof l=="object"?s+=JSON.stringify(l):s+=l,c<i&&(s+=" ")}return`${r} [${o.join("] [")}]: ${s}
|
|
4
|
-
`}a(ln,"createLogRecord");function Oc(e){an&&VO(e),cn&&process.stdout.write(e)}a(Oc,"logStdOut");function a_(e){an&&VO(e),cn&&process.stderr.write(e)}a(a_,"logStdErr");function VO(e){_$(),Wo?xi.appendFileSync(Wo,e):gc.log(e)}a(VO,"logToFile");function Vh(){try{xi.closeSync(Wo)}catch{}Wo=null}a(Vh,"closeLogFile");function _$(){if(!Wo){try{if(!Rc)debugger;Wo=xi.openSync(Rc,"a")}catch(e){gc.error(e)}setTimeout(()=>{Vh()},a$).unref()}}a(_$,"openLogFile");function o_(...e){Wt[Kt]<=Wt.info&&Oc(ln("info",e))}a(o_,"info");function Yh(...e){Wt[Kt]<=Wt.trace&&Oc(ln("trace",e))}a(Yh,"trace");function Ac(...e){Wt[Kt]<=Wt.error&&a_(ln("error",e))}a(Ac,"error");function Kh(...e){Wt[Kt]<=Wt.debug&&Oc(ln("debug",e))}a(Kh,"debug");function YO(...e){Wt[Kt]<=Wt.notify&&Oc(ln("notify",e))}a(YO,"notify");function KO(...e){Wt[Kt]<=Wt.fatal&&a_(ln("fatal",e))}a(KO,"fatal");function Wh(...e){Wt[Kt]<=Wt.warn&&a_(ln("warn",e))}a(Wh,"warn");function d$(e,t,...r){t===xO.STDERR?a_(ln(e,r)):Oc(ln(e,r))}a(d$,"logCustomLevel");function E$(){let e;try{e=s$.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=un.join(e,dt.HDB_HOME_DIR_NAME,dt.BOOT_PROPS_FILE_NAME);return xi.existsSync(t)||(t=un.join($h,"utility/hdb_boot_properties.file")),t}a(E$,"getPropsFilePath");function f$(e){Kt=e}a(f$,"setLogLevel");function qO(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(qO,"autoCastBoolean");function h$(e){try{if(e.includes("config/settings.js")){let o=GO(e);return{level:o.get(dt.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:un.dirname(o.get(dt.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(dt.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(dt.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=FO.parseDocument(xi.readFileSync(e,"utf8")),r=t.getIn(["logging","level"]),s=t.getIn(["logging","root"]),n=t.getIn(["logging","file"]),i=t.getIn(["logging","stdStreams"]);return{level:r,config_log_path:s,to_file:n,to_stream:i}}catch(t){if(t.code===dt.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(h$,"getLogConfig");function m$(){try{let e=FO.parseDocument(xi.readFileSync(o$,"utf8")),t=e.getIn(["logging","level"]),r=e.getIn(["logging","file"]),s=e.getIn(["logging","stdStreams"]);return{default_level:t,default_to_file:r,default_to_stream:s}}catch(e){console.error("Error accessing default config file for logging"),console.error(e)}}a(m$,"getDefaultConfig");function p$(e,t,r,s,n,i){this.username=e,this.status=t,this.type=r,this.originating_ip=s,this.request_method=n,this.path=i}a(p$,"AuthAuditLog")});var ki=m((Ble,S$)=>{S$.exports={name:"harperdb",version:"4.2.0-alpha.12",description:"HarperDB is a distributed SQL & NoSQL data platform focused on speed, flexibility, and ease of use.",keywords:["database","sql","nosql","api","distributed","cloud","enterprise","Fastify","NATS"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{node:">=14.0.0","preferred-node":"18.15.0","go-lang":"1.19.12","nats-server":"2.9.21"},exports:{".":"./index.js"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"SEE LICENSE IN LICENSE",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/","cover:test":"rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:apitests && nyc --no-clean --reporter=lcovonly npm run test:logging && nyc --no-clean --reporter=lcovonly npm run test:upgrade && nyc --no-clean --reporter=lcovonly npm run test:nats && nyc --no-clean --reporter=lcovonly npm run test:cfserver && nyc --no-clean --reporter=lcovonly npm run test:hdbserver && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:main":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","test:lmdbbridge":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --config '../unitTests/.mocharc.json'","test:lmdbutility":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --config '../unitTests/.mocharc.json'","test:hdbserver":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --config '../unitTests/.mocharc.json'","test:cfserver":"npm run submodules && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/fastifyRoutes/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","test:nats":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","test:upgrade":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --config '../unitTests/.mocharc.json'","test:apitests":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/apiTests/**/*-test.mjs' --config '../unitTests/.mocharc.json'","test:logging":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/logging/*.js' --config '../unitTests/.mocharc.json'","test:ci":" cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --retries 3 --config '../unitTests/.mocharc-main.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter","hdb-check":"./utility/devops/hdb-check.sh","download-prebuilds":"node ./utility/devops/build/download-prebuilds.js",prebuild:"date",postinstall:"node ./launchServiceScripts/launchInstallNATSServer.js",build_nats_dependency:"node ./utility/devops/nats/builder.js",coverage:"nyc --reporter=lcov npm test"},dependencies:{"@aws-sdk/client-s3":"3.383.0","@aws-sdk/lib-storage":"3.383.0","@aws-sdk/abort-controller":"3.370.0","@endo/static-module-record":"^0.7.16","@fastify/autoload":"~5.7.1","@fastify/compress":"~6.4.0","@fastify/cors":"~8.3.0","@fastify/static":"~6.10.2","@turf/area":"6.5.0","@turf/boolean-contains":"6.5.0","@turf/boolean-disjoint":"6.5.0","@turf/boolean-equal":"6.5.0","@turf/circle":"6.5.0","@turf/difference":"6.5.0","@turf/distance":"6.5.0","@turf/helpers":"6.5.0","@turf/length":"6.5.0",alasql:"1.7.4","cbor-x":"1.5.4",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2",esbuild:"^0.18.0","fast-glob":"3.3.1",fastify:"~4.21.0","fastify-plugin":"~4.5.0","fs-extra":"11.1.1",graphql:"^16.6.0","human-readable-ids":"1.0.4",inquirer:"8.2.6","is-number":"7.0.0",joi:"17.9.2",json2csv:"5.0.7",jsonata:"1.8.6",jsonwebtoken:"9.0.1",lmdb:"2.8.4",lodash:"4.17.21",mathjs:"11.9.1",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.29.4","mqtt-packet":"~8.2.0",msgpackr:"1.9.7",nats:"2.16.0",needle:"3.2.0","node-stream-zip":"1.15.0","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.4.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.15.0",pm2:"5.3.0",prompt:"1.3.0","properties-reader":"2.2.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0",ses:"^0.18.1","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.18.11","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.0","validate.js":"0.13.1",ws:"^8.13.0",yaml:"2.3.1"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"0.27.2",chai:"4.3.7","chai-integer":"0.1.0",eslint:"8.22.0","eslint-config-prettier":"8.3.0","eslint-plugin-prettier":"3.4.1","eslint-plugin-radar":"0.2.1",eventsource:"^2.0.2","hook-std":"3.0.0","intercept-stdout":"0.1.2",mocha:"^10.2.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.7",newman:"5.3.2","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"^1.22.11","newman-reporter-teamcity":"^0.1.12","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.8.4",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0","source-map-support":"^0.5.21",typescript:"^4.9.4","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},"newman-reporter-html":{newman:"5.3.2"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var $i=m((Fle,WO)=>{"use strict";var Hle=require("fs-extra"),qle=C();WO.exports={version:T$,printVersion:R$,nodeVersion:g$};var zn=ki();function T$(){if(zn)return zn.version}a(T$,"version");function g$(){if(zn&&zn.engines&&zn.engines["preferred-node"])return zn.engines["preferred-node"]}a(g$,"nodeVersion");function R$(){zn&&console.log(`HarperDB Version ${zn.version}`)}a(R$,"printVersion")});var jO=m((xle,JO)=>{"use strict";var QO=require("semver/functions/major"),A$=require("semver/functions/satisfies"),zO=ki(),Nc=process.versions&&process.versions.node?process.versions.node:void 0;JO.exports=O$;function O$(){let e=zO.engines.node,t=zO.engines["preferred-node"];if(Nc){if(e&&!A$(Nc,e))return{error:`This version of HarperDB supports Node.js versions: ${e}, the currently installed Node.js version is: ${Nc}. Please install a version of Node.js that is withing the defined range.`};if(t&&QO(Nc)!==QO(t))return{warn:`This version of HarperDB is tested against Node.js version ${t}, the currently installed Node.js version is: ${Nc}. Some issues may occur with untested versions of Node.js.`}}}a(O$,"checkNodeVersion")});var zh=m(($le,XO)=>{"use strict";var N$=require("util"),b$=require("path"),y$=require("child_process"),I$=N$.promisify(y$.execFile),w$=1e3*1e3*10;XO.exports={findPs:C$};async function C$(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:s}=await I$("ps",["wwxo",`pid,${r}`],{maxBuffer:w$});for(let n of s.trim().split(`
|
|
4
|
+
`}a(ln,"createLogRecord");function Oc(e){an&&VO(e),cn&&process.stdout.write(e)}a(Oc,"logStdOut");function a_(e){an&&VO(e),cn&&process.stderr.write(e)}a(a_,"logStdErr");function VO(e){_$(),Wo?xi.appendFileSync(Wo,e):gc.log(e)}a(VO,"logToFile");function Vh(){try{xi.closeSync(Wo)}catch{}Wo=null}a(Vh,"closeLogFile");function _$(){if(!Wo){try{if(!Rc)debugger;Wo=xi.openSync(Rc,"a")}catch(e){gc.error(e)}setTimeout(()=>{Vh()},a$).unref()}}a(_$,"openLogFile");function o_(...e){Wt[Kt]<=Wt.info&&Oc(ln("info",e))}a(o_,"info");function Yh(...e){Wt[Kt]<=Wt.trace&&Oc(ln("trace",e))}a(Yh,"trace");function Ac(...e){Wt[Kt]<=Wt.error&&a_(ln("error",e))}a(Ac,"error");function Kh(...e){Wt[Kt]<=Wt.debug&&Oc(ln("debug",e))}a(Kh,"debug");function YO(...e){Wt[Kt]<=Wt.notify&&Oc(ln("notify",e))}a(YO,"notify");function KO(...e){Wt[Kt]<=Wt.fatal&&a_(ln("fatal",e))}a(KO,"fatal");function Wh(...e){Wt[Kt]<=Wt.warn&&a_(ln("warn",e))}a(Wh,"warn");function d$(e,t,...r){t===xO.STDERR?a_(ln(e,r)):Oc(ln(e,r))}a(d$,"logCustomLevel");function E$(){let e;try{e=s$.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=un.join(e,dt.HDB_HOME_DIR_NAME,dt.BOOT_PROPS_FILE_NAME);return xi.existsSync(t)||(t=un.join($h,"utility/hdb_boot_properties.file")),t}a(E$,"getPropsFilePath");function f$(e){Kt=e}a(f$,"setLogLevel");function qO(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(qO,"autoCastBoolean");function h$(e){try{if(e.includes("config/settings.js")){let o=GO(e);return{level:o.get(dt.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:un.dirname(o.get(dt.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(dt.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(dt.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=FO.parseDocument(xi.readFileSync(e,"utf8")),r=t.getIn(["logging","level"]),s=t.getIn(["logging","root"]),n=t.getIn(["logging","file"]),i=t.getIn(["logging","stdStreams"]);return{level:r,config_log_path:s,to_file:n,to_stream:i}}catch(t){if(t.code===dt.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(h$,"getLogConfig");function m$(){try{let e=FO.parseDocument(xi.readFileSync(o$,"utf8")),t=e.getIn(["logging","level"]),r=e.getIn(["logging","file"]),s=e.getIn(["logging","stdStreams"]);return{default_level:t,default_to_file:r,default_to_stream:s}}catch(e){console.error("Error accessing default config file for logging"),console.error(e)}}a(m$,"getDefaultConfig");function p$(e,t,r,s,n,i){this.username=e,this.status=t,this.type=r,this.originating_ip=s,this.request_method=n,this.path=i}a(p$,"AuthAuditLog")});var ki=m((Ble,S$)=>{S$.exports={name:"harperdb",version:"4.2.0-alpha.13",description:"HarperDB is a distributed SQL & NoSQL data platform focused on speed, flexibility, and ease of use.",keywords:["database","sql","nosql","api","distributed","cloud","enterprise","Fastify","NATS"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{node:">=14.0.0","preferred-node":"18.15.0","go-lang":"1.19.12","nats-server":"2.9.21"},exports:{".":"./index.js"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"SEE LICENSE IN LICENSE",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/","cover:test":"rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:apitests && nyc --no-clean --reporter=lcovonly npm run test:logging && nyc --no-clean --reporter=lcovonly npm run test:upgrade && nyc --no-clean --reporter=lcovonly npm run test:nats && nyc --no-clean --reporter=lcovonly npm run test:cfserver && nyc --no-clean --reporter=lcovonly npm run test:hdbserver && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:main":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","test:lmdbbridge":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --config '../unitTests/.mocharc.json'","test:lmdbutility":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --config '../unitTests/.mocharc.json'","test:hdbserver":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --config '../unitTests/.mocharc.json'","test:cfserver":"npm run submodules && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/fastifyRoutes/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","test:nats":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","test:upgrade":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --config '../unitTests/.mocharc.json'","test:apitests":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/apiTests/**/*-test.mjs' --config '../unitTests/.mocharc.json'","test:logging":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/logging/*.js' --config '../unitTests/.mocharc.json'","test:ci":" cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --retries 3 --config '../unitTests/.mocharc-main.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter","hdb-check":"./utility/devops/hdb-check.sh","download-prebuilds":"node ./utility/devops/build/download-prebuilds.js",prebuild:"date",postinstall:"node ./launchServiceScripts/launchInstallNATSServer.js",build_nats_dependency:"node ./utility/devops/nats/builder.js",coverage:"nyc --reporter=lcov npm test"},dependencies:{"@aws-sdk/client-s3":"3.383.0","@aws-sdk/lib-storage":"3.383.0","@aws-sdk/abort-controller":"3.370.0","@endo/static-module-record":"^0.7.16","@fastify/autoload":"~5.7.1","@fastify/compress":"~6.4.0","@fastify/cors":"~8.3.0","@fastify/static":"~6.10.2","@turf/area":"6.5.0","@turf/boolean-contains":"6.5.0","@turf/boolean-disjoint":"6.5.0","@turf/boolean-equal":"6.5.0","@turf/circle":"6.5.0","@turf/difference":"6.5.0","@turf/distance":"6.5.0","@turf/helpers":"6.5.0","@turf/length":"6.5.0",alasql:"1.7.4","cbor-x":"1.5.4",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2",esbuild:"^0.18.0","fast-glob":"3.3.1",fastify:"~4.21.0","fastify-plugin":"~4.5.0","fs-extra":"11.1.1",graphql:"^16.6.0","human-readable-ids":"1.0.4",inquirer:"8.2.6","is-number":"7.0.0",joi:"17.9.2",json2csv:"5.0.7",jsonata:"1.8.6",jsonwebtoken:"9.0.1",lmdb:"2.8.4",lodash:"4.17.21",mathjs:"11.9.1",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.29.4","mqtt-packet":"~8.2.0",msgpackr:"1.9.7",nats:"2.16.0",needle:"3.2.0","node-stream-zip":"1.15.0","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.4.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.15.0",pm2:"5.3.0",prompt:"1.3.0","properties-reader":"2.2.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0",ses:"^0.18.1","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.18.11","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.0","validate.js":"0.13.1",ws:"^8.13.0",yaml:"2.3.1"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"0.27.2",chai:"4.3.7","chai-integer":"0.1.0",eslint:"8.22.0","eslint-config-prettier":"8.3.0","eslint-plugin-prettier":"3.4.1","eslint-plugin-radar":"0.2.1",eventsource:"^2.0.2","hook-std":"3.0.0","intercept-stdout":"0.1.2",mocha:"^10.2.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.7",newman:"5.3.2","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"^1.22.11","newman-reporter-teamcity":"^0.1.12","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.8.4",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0","source-map-support":"^0.5.21",typescript:"^4.9.4","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},"newman-reporter-html":{newman:"5.3.2"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var $i=m((Fle,WO)=>{"use strict";var Hle=require("fs-extra"),qle=C();WO.exports={version:T$,printVersion:R$,nodeVersion:g$};var zn=ki();function T$(){if(zn)return zn.version}a(T$,"version");function g$(){if(zn&&zn.engines&&zn.engines["preferred-node"])return zn.engines["preferred-node"]}a(g$,"nodeVersion");function R$(){zn&&console.log(`HarperDB Version ${zn.version}`)}a(R$,"printVersion")});var jO=m((xle,JO)=>{"use strict";var QO=require("semver/functions/major"),A$=require("semver/functions/satisfies"),zO=ki(),Nc=process.versions&&process.versions.node?process.versions.node:void 0;JO.exports=O$;function O$(){let e=zO.engines.node,t=zO.engines["preferred-node"];if(Nc){if(e&&!A$(Nc,e))return{error:`This version of HarperDB supports Node.js versions: ${e}, the currently installed Node.js version is: ${Nc}. Please install a version of Node.js that is withing the defined range.`};if(t&&QO(Nc)!==QO(t))return{warn:`This version of HarperDB is tested against Node.js version ${t}, the currently installed Node.js version is: ${Nc}. Some issues may occur with untested versions of Node.js.`}}}a(O$,"checkNodeVersion")});var zh=m(($le,XO)=>{"use strict";var N$=require("util"),b$=require("path"),y$=require("child_process"),I$=N$.promisify(y$.execFile),w$=1e3*1e3*10;XO.exports={findPs:C$};async function C$(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:s}=await I$("ps",["wwxo",`pid,${r}`],{maxBuffer:w$});for(let n of s.trim().split(`
|
|
5
5
|
`).slice(1)){n=n.trim();let[i]=n.split(" ",1),o=n.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,s])=>({pid:Number.parseInt(r,10),name:b$.basename(s.comm),cmd:s.args,ppid:Number.parseInt(s.ppid,10),uid:Number.parseInt(s.uid,10),cpu:Number.parseFloat(s["%cpu"]),memory:Number.parseFloat(s["%mem"])}))}a(C$,"findPs")});var Ge=m((Yle,eN)=>{"use strict";var L$="__dbis__",D$="__txns__",U$="__environment_name__",M$="__dbi_defintion__",P$={EQUALS:"equals",STARTS_WITH:"startsWith",_STARTS_WITH:"starts_with",ENDS_WITH:"endsWith",_ENDS_WITH:"ends_with",CONTAINS:"contains",SEARCH_ALL:"searchAll",SEARCH_ALL_TO_MAP:"searchAllToMap",BATCH_SEARCH_BY_HASH:"batchSearchByHash",BATCH_SEARCH_BY_HASH_TO_MAP:"batchSearchByHashToMap",GREATER_THAN:"greaterThan",_GREATER_THAN:"greater_than",GREATER_THAN_EQUAL:"greaterThanEqual",_GREATER_THAN_EQUAL:"greater_than_equal",LESS_THAN:"lessThan",_LESS_THAN:"less_than",LESS_THAN_EQUAL:"lessThanEqual",_LESS_THAN_EQUAL:"less_than_equal",BETWEEN:"between"},v$=["__createdtime__","__updatedtime__"],B$="\uFFFF",ZO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},H$=Object.values(ZO);eN.exports={AUDIT_STORE_NAME:D$,INTERNAL_DBIS_NAME:L$,DBI_DEFINITION_NAME:M$,SEARCH_TYPES:P$,TIMESTAMP_NAMES:v$,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:U$,TRANSACTIONS_DBI_NAMES_ENUM:ZO,TRANSACTIONS_DBIS:H$,OVERFLOW_MARKER:B$}});var gr=m((Kle,uN)=>{"use strict";var tN=R(),rN=Ge(),sN={CONTINUE:100,OK:200,CREATED:201,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,REQUEST_TIMEOUT:408,CONFLICT:409,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,INSUFFICIENT_STORAGE:507,NETWORK_AUTHENTICATION_REQUIRED:511},nN=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),iN={500:nN("There was an error processing your request."),400:"Invalid request"},q$=iN[sN.INTERNAL_SERVER_ERROR],F$={OP_NOT_SUPPORTED_FOR_FS:e=>`${e} is not available for this instance because it uses the File System data store.`,MISSING_VALUE:e=>`${e} is missing.`,INVALID_VALUE:e=>`${e} is invalid.`,NOT_FOUND:e=>`${e} not found.`},G$={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},x$={DEFAULT_BULK_LOAD_ERR:"There was an error during your bulk load into HarperDB.",DOWNLOAD_FILE_ERR:e=>`There was an error downloading '${e}'.`,INSERT_JSON_ERR:"There was an error inserting the downloaded JSON data.",INSERT_CSV_ERR:"There was an error inserting the downloaded CSV data.",INVALID_ACTION_PARAM_ERR:e=>`Bulk load operation failed - ${e} is not a valid 'action' parameter`,INVALID_FILE_EXT_ERR:e=>`Error selecting correct parser - valid file type not found in json - ${e}`,MAX_FILE_SIZE_ERR:(e,t)=>`File size is ${e} bytes, which exceeded the maximum size allowed of: ${t} bytes`,PAPA_PARSE_ERR:"There was an error parsing the downloaded CSV data.",S3_DOWNLOAD_ERR:e=>`There was an error downloading '${e}' from AWS.`,WRITE_TEMP_FILE_ERR:"Error writing temporary file to storage"},k$={BASE_PATH_REQUIRED:"base_path is required",DESTINATION_PATH_REQUIRED:"destination_path is required",ENV_NAME_REQUIRED:"env_name is required",INVALID_BASE_PATH:"invalid base_path",INVALID_DESTINATION_PATH:"invalid destination_path",INVALID_ENVIRONMENT:"invalid environment",ENV_REQUIRED:"env is required",DBI_NAME_REQUIRED:"dbi_name is required",DBI_DOES_NOT_EXIST:"dbi does not exist",HASH_ATTRIBUTE_REQUIRED:"hash_attribute is required",ID_REQUIRED:"id is required",IDS_REQUIRED:"ids is required",IDS_MUST_BE_ITERABLE:"ids must be iterable",FETCH_ATTRIBUTES_REQUIRED:"fetch_attributes is required",FETCH_ATTRIBUTES_MUST_BE_ARRAY:"fetch_attributes must be an array",ATTRIBUTE_REQUIRED:"attribute is required",SEARCH_VALUE_REQUIRED:"search_value is required",SEARCH_VALUE_TOO_LARGE:"search_value is too long",WRITE_ATTRIBUTES_REQUIRED:"write_attributes is required",WRITE_ATTRIBUTES_MUST_BE_ARRAY:"write_attributes must be an array",RECORDS_REQUIRED:"records is required",RECORDS_MUST_BE_ARRAY:"records must be an array",CANNOT_CREATE_INTERNAL_DBIS_NAME:`cannot create a dbi named ${rN.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${rN.INTERNAL_DBIS_NAME}`,START_VALUE_REQUIRED:"start_value is required",END_VALUE_REQUIRED:"end_value is required",CANNOT_COMPARE_STRING_TO_NUMERIC_KEYS:"cannot compare a string to numeric keys",END_VALUE_MUST_BE_GREATER_THAN_START_VALUE:"end_value must be greater than or equal to start_value",UNKNOWN_SEARCH_TYPE:"unknown search type",CANNOT_DROP_TABLE_HASH_ATTRIBUTE:"cannot drop a table's hash attribute"},$$={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${tN.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE} bytes.`,ATTR_NAME_NULLISH_ERR:"transaction aborted due to record(s) with an attribute name that is null, undefined or empty string",HASH_VAL_LENGTH_ERR:`transaction aborted due to record(s) with a hash value that exceeds ${tN.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE} bytes, check log for more info`,INVALID_FORWARD_SLASH_IN_HASH_ERR:"transaction aborted due to record(s) with a hash value that contains a forward slash, check log for more info",RECORD_MISSING_HASH_ERR:"transaction aborted due to record(s) with no hash value, check log for more info"},oN={GENERIC_AUTH_FAIL:"Login failed",USER_INACTIVE:"Cannot complete request: User is inactive",INVALID_TOKEN:"invalid token",NO_ENCRYPTION_KEYS:"unable to generate JWT as there are no encryption keys. please contact your administrator",INVALID_CREDENTIALS:"invalid credentials",PASSWORD_REQUIRED:"password is required",USERNAME_REQUIRED:"username is required",REFRESH_TOKEN_REQUIRED:"refresh_token is required",INVALID_AUTH_OBJECT:"invalid auth_object",INVALID_BODY:"invalid body",TOKEN_EXPIRED:"token expired",REFRESH_TOKEN_SAVE_FAILED:"unable to store refresh_token"},V$={DEFAULT_INVALID_REQUEST:"Invalid request",OP_AUTH_PERMS_ERROR:"This operation is not authorized due to role restrictions and/or invalid database items",OP_IS_SU_ONLY:e=>`Operation '${e}' is restricted to 'super_user' roles`,OP_NOT_FOUND:e=>`Operation '${e}' not found`,SYSTEM_TIMESTAMP_PERMS_ERR:"Internal timestamp attributes - '__createdtime_' and '__updatedtime__' - cannot be inserted to or updated by HDB users.",UNKNOWN_OP_AUTH_ERROR:(e,t,r)=>`There was an error authorizing ${e} op on table '${t}.${r}'`,USER_HAS_NO_PERMS:e=>`User ${e} has no role or permissions. Please assign the user a valid role.`,DROP_SYSTEM:"The 'system' database, tables and records are used internally by HarperDB and cannot be updated or removed."},Y$={ATTR_PERM_MISSING:(e,t)=>`${e.toUpperCase()} attribute permission missing for '${t}'`,ATTR_PERM_MISSING_NAME:"Permission object in 'attribute_permission' missing an 'attribute_name'",ATTR_PERM_NOT_BOOLEAN:(e,t)=>`${e.toUpperCase()} attribute permission for '${t}' must be a boolean`,ATTR_PERMS_ARRAY_MISSING:"Missing 'attribute_permissions' array",ATTR_PERMS_NOT_ARRAY:"Value for 'attribute_permissions' must be an array",INVALID_ATTRIBUTE_IN_PERMS:e=>`Invalid attribute '${e}' in 'attribute_permissions'`,INVALID_PERM_KEY:e=>`Invalid table permission key value '${e}'`,INVALID_ATTR_PERM_KEY:e=>`Invalid attribute permission key value '${e}'`,INVALID_ROLE_JSON_KEYS:e=>`Invalid ${e.length>1?"keys":"key"} in JSON body - '${e.join("', '")}'`,MISMATCHED_TABLE_ATTR_PERMS:e=>`You have a conflict with TABLE permissions for '${e}' being false and ATTRIBUTE permissions being true`,OUTDATED_PERMS_TRANSLATION_ERROR:"This instance was recently upgraded and uses our new role permissions structure. Please login to this instance in HarperDB Studio, go to 'Roles', and click 'Update Role Permission' for all standard roles to migrate them to the new structure.",ROLE_ALREADY_EXISTS:e=>`A role with name '${e}' already exists`,ROLE_NOT_FOUND:"Role not found",ROLE_PERMS_ERROR:"Errors in the role permissions JSON provided",SCHEMA_PERM_ERROR:e=>`Your role does not have permission to view database metadata for '${e}'`,SCHEMA_TABLE_PERM_ERROR:(e,t)=>`Your role does not have permission to view database.table metadata for '${e}.${t}'`,SU_ROLE_MISSING_ERROR:"Missing 'super_user' key/value in permission set",SU_CU_ROLE_BOOLEAN_ERROR:e=>`Value for '${e}' permission must be a boolean`,STRUCTURE_USER_ROLE_TYPE_ERROR:e=>`Value for '${e}' permission must be a boolean or Array`,SU_CU_ROLE_NO_PERMS_ALLOWED:e=>`Roles with '${e}' set to true cannot have other permissions set.`,SU_CU_ROLE_COMBINED_ERROR:"Roles cannot have both 'super_user' and 'cluster_user' values included in their permissions set.",TABLE_PERM_MISSING:e=>`Missing table ${e.toUpperCase()} permission`,TABLE_PERM_NOT_BOOLEAN:e=>`Table ${e.toUpperCase()} permission must be a boolean`},K$={ATTR_NOT_FOUND:(e,t,r)=>`Attribute '${r}' does not exist on '${e}.${t}'`,ATTR_EXISTS_ERR:(e,t,r)=>`Attribute '${r}' already exists in ${e}.${t}'`,DESCRIBE_ALL_ERR:"There was an error during describeAll. Please check the logs and try again.",INVALID_TABLE_ERR:e=>`Invalid table ${JSON.stringify(e)}`,SCHEMA_NOT_FOUND:e=>`database '${e}' does not exist`,SCHEMA_EXISTS_ERR:e=>`database '${e}' already exists`,TABLE_EXISTS_ERR:(e,t)=>`Table '${t}' already exists in '${e}'`,SCHEMA_REQUIRED_ERR:"database is required",TABLE_NOT_FOUND:(e,t)=>`Table '${e}.${t}' does not exist`,TABLE_REQUIRED_ERR:"table is required"},W$={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},Q$={ALTER_USER_DUP_ROLES:e=>`Update failed. There are duplicates for the '${e}' role which is not allowed. Update your roles and try again.`,ALTER_USER_ROLE_NOT_FOUND:e=>`Update failed. Requested '${e}' role not found.`,DUP_ROLES_FOUND:e=>`Multiple ${e} roles found. Roles must have unique 'role' value. Please update and try again.`,ROLE_NAME_NOT_FOUND:e=>`${e} role not found`,USER_ALREADY_EXISTS:e=>`User ${e} already exists`,USER_NOT_EXIST:e=>`User ${e} does not exist`},aN={INVALID_DATE:"Invalid date, must be in ISO-8601 format (YYYY-MM-DD).",SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE:e=>`invalid sort attribute '${e}', the attribute must either be the table's hash attribute or an attribute used in conditions.`},cN={INVALID_ITC_DATA_TYPE:"Invalid ITC event data type, must be an object",MISSING_TYPE:"ITC event missing 'type'",MISSING_MSG:"ITC event missing 'message'",MISSING_ORIGIN:"ITC event message missing 'originator' property",INVALID_EVENT:e=>`ITC server received invalid event type: ${e}`},z$={FUNCTION_STATUS:"Error getting custom function status, check the log for more details",GET_FUNCTIONS:"Error getting custom functions, check the log for more details",GET_FUNCTION:"Error getting custom function, check the log for more details",SET_FUNCTION:"Error setting custom function, check the log for more details",NO_PROJECT:"Project does not exist. Create one using 'add_custom_function_project'",PROJECT_EXISTS:"Project already exists",VALIDATION_ERR:"Error validating request, check the log for more details",NO_FILE:"File does not exist",BAD_FILE_NAME:"File name can only contain alphanumeric, dash and underscore characters",BAD_PROJECT_NAME:"Project name can only contain alphanumeric, dash and underscores characters",BAD_PACKAGE:"Packaged project must be base64-encoded tar file of project directory",DROP_FUNCTION:"Error dropping custom function, check the log for more details",ADD_FUNCTION:"Error adding custom function project, check the log for more details",DROP_FUNCTION_PROJECT:"Error dropping custom function project, check the log for more details",BAD_FILE_PATH:"Filepath must be valid, and contain the name of the tarball you wish to write",NOT_ENABLED:"Custom functions is not enabled, to enable set fastifyRoutes enabled to true in hdb/harperdb-config.yaml file."},J$={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},j$={...oN,...x$,...F$,...V$,...Y$,...K$,...W$,...Q$,...$$,...aN,...cN,...z$,...J$,...G$};uN.exports={CHECK_LOGS_WRAPPER:nN,HDB_ERROR_MSGS:j$,DEFAULT_ERROR_MSGS:iN,DEFAULT_ERROR_RESP:q$,HTTP_STATUS_CODES:sN,LMDB_ERRORS_ENUM:k$,AUTHENTICATION_ERROR_MSGS:oN,VALIDATION_ERROR_MSGS:aN,ITC_ERRORS:cN}});var z=m((Qle,dN)=>{"use strict";var Qo=gr(),X$=C(),Z$=R(),c_=class extends Error{static{a(this,"HdbError")}constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,lN),this.statusCode=s||Qo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Qo.DEFAULT_ERROR_MSGS[s]?Qo.DEFAULT_ERROR_MSGS[s]:Qo.DEFAULT_ERROR_MSGS[Qo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,n&&(this.logLevel=n),typeof this.message!="string"&&(this.stack=t.stack),i&&X$[n](i)}},Jh=class extends Error{static{a(this,"ClientError")}constructor(t,r){if(t instanceof Error)return t.statusCode=r||400,t;super(t),this.statusCode=r||400}},jh=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function lN(e,t,r,s=Z$.LOG_LEVELS.ERROR,n=null,i=!1){if(_N(e))return e;let o=new c_(e,t,r,s,n);return i&&delete o.stack,o}a(lN,"handleHDBError");function _N(e){return e.__proto__.constructor.name===c_.name}a(_N,"isHDBError");dN.exports={isHDBError:_N,handleHDBError:lN,ClientError:Jh,ServerError:jh,hdb_errors:Qo}});var De=m((Jle,TN)=>{"use strict";var Cc=R(),eV=F(),Qt=Y(),Lc=require("path"),tV=require("minimist"),EN=require("fs-extra"),fN=require("lodash");Qt.initSync();var{CONFIG_PARAMS:Jn,SCHEMAS_PARAM_CONFIG:bc,SYSTEM_SCHEMA_NAME:u_}=Cc,yc,Ic,wc;function hN(){if(yc!==void 0)return yc;if(Qt.getHdbBasePath()!==void 0)return yc=Qt.get(Jn.STORAGE_PATH)||Lc.join(Qt.getHdbBasePath(),Cc.DATABASES_DIR_NAME),yc}a(hN,"getBaseSchemaPath");function mN(){if(Ic!==void 0)return Ic;if(Qt.getHdbBasePath()!==void 0)return Ic=SN(u_),Ic}a(mN,"getSystemSchemaPath");function pN(){if(wc!==void 0)return wc;if(Qt.getHdbBasePath()!==void 0)return wc=Qt.get(Cc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||Lc.join(Qt.getHdbBasePath(),Cc.TRANSACTIONS_DIR_NAME),wc}a(pN,"getTransactionAuditStoreBasePath");function rV(e,t){let r=Qt.get(Jn.SCHEMAS)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||Lc.join(pN(),e.toString())}a(rV,"getTransactionAuditStorePath");function SN(e,t){e=e.toString(),t=t&&t.toString();let r=Qt.get(Cc.CONFIG_PARAMS.SCHEMAS)?.[e];return t&&r?.tables?.[t]?.path||r?.path||Lc.join(hN(),e)}a(SN,"getSchemaPath");function sV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,tV(process.argv));let s=r[Jn.SCHEMAS.toUpperCase()];if(s){let i;try{i=JSON.parse(s)}catch(o){if(!eV.isObject(s))throw o;i=s}for(let o of i){let c=o[u_];if(!c)continue;let u=Qt.get(Jn.SCHEMAS);u=u??{};let l=c?.tables?.[t]?.[bc.PATH];if(l)return fN.set(u,[u_,bc.TABLES,t,bc.PATH],l),Qt.setProperty(Jn.SCHEMAS,u),l;let _=c?.[bc.PATH];if(_)return fN.set(u,[u_,bc.PATH],_),Qt.setProperty(Jn.SCHEMAS,u),_}}let n=r[Jn.STORAGE_PATH.toUpperCase()];if(n){if(!EN.pathExistsSync(n))throw new Error(n+" does not exist");let i=Lc.join(n,e);return EN.mkdirsSync(i),Qt.setProperty(Jn.STORAGE_PATH,n),i}return mN()}a(sV,"initSystemSchemaPaths");function nV(){yc=void 0,Ic=void 0,wc=void 0}a(nV,"resetPaths");TN.exports={getBaseSchemaPath:hN,getSystemSchemaPath:mN,getTransactionAuditStorePath:rV,getTransactionAuditStoreBasePath:pN,getSchemaPath:SN,initSystemSchemaPaths:sV,resetPaths:nV}});var Ht=m((e_e,NN)=>{"use strict";var iV=gr().LMDB_ERRORS_ENUM,Xle=require("lmdb"),oV=Ge(),Zle=require("buffer").Buffer,{OVERFLOW_MARKER:gN,MAX_SEARCH_KEY_LENGTH:l_}=oV,RN=["number","string","symbol","boolean","bigint"];function aV(e){if(e=e?.primaryStore||e,!e)throw new Error(iV.ENV_REQUIRED)}a(aV,"validateEnv");function cV(e){if(e==null)return null;let t;try{t=typeof e=="object"?JSON.stringify(e):e.toString()}catch{t=e.toString()}return t}a(cV,"stringifyData");function uV(e){return e instanceof Date?e.valueOf():e}a(uV,"convertKeyValueToWrite");function lV(e){if(e==null)return;if(RN.includes(typeof e))return e.length>l_?[e.slice(0,l_)+gN]:[e];let t;if(Array.isArray(e)){t=[];for(let r=0,s=e.length;r<s;r++){let n=e[r];if(RN.includes(typeof n))n.length>l_?t.push(n.slice(0,l_)+gN):t.push(n);else if(n instanceof Date)return t.push(n.getTime())}}else if(e instanceof Date)return[e.getTime()];return t}a(lV,"getIndexedValues");var __=0,AN=0;function ON(){AN=Date.now()-performance.now()}a(ON,"adjustStartTime");ON();var _V=6e4;setInterval(ON,_V).unref();function dV(){let e=performance.now()+AN;return e>__?(__=e,e):(__+=488e-6,__)}a(dV,"getNextMonotonicTime");NN.exports={validateEnv:aV,stringifyData:cV,convertKeyValueToWrite:uV,getNextMonotonicTime:dV,getIndexedValues:lV}});var bN,ys,Xh,Dc=Te(()=>{bN=require("events"),ys=class extends bN.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new Xh;return t.queue=this,t}push(t){this.send(t)}send(t){this.resolveNext?(this.resolveNext({value:t}),this.resolveNext=null):this.hasDataListeners?this.emit("data",t):(this.queue||(this.queue=[]),this.queue.push(t))}getNextMessage(){return this.queue?.shift()}on(t,r){if(t==="data"&&!this.hasDataListeners)for(this.hasDataListeners=!0;this.queue?.length>0;)r(this.queue.shift());return super.on(t,r)}},Xh=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});function Uc(e){return e[Nt]||(e[Nt]=Object.create(null))}function m_(e,t){let r=e.prototype,s={},n=t.attributes||t.properties||[];for(let o of n){let c=o.name,u={get(){let l=this[Nt];if(l&&c in l)return l[c];let _=this[le]?.[c];if(_&&typeof _=="object"){let d=yN(_,o);if(d)return l||(l=this[Nt]=Object.create(null)),l[c]=d}return _},set(l){Uc(this)[c]=l},enumerable:!0,configurable:!0};switch(u.get.isAttribute=!0,o.type){case"String":u.set=function(l){if(typeof l!="string")throw(0,d_.ClientError)(`${c} must be a string, attempt to assign ${l}`);Uc(this)[c]=l};break;case"Int":u.set=function(l){if(typeof l!="number")throw(0,d_.ClientError)(`${c} must be a string, attempt to assign ${l}`);Uc(this)[c]=l};break}s[c]=u,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,u)}i("getProperty",function(o){let c=s[o];if(c)return c.get.call(this);let u=this[Nt];return u?.[o]!==void 0?u[o]:this[le]?.[o]}),i("set",function(o,c){let u=s[o];if(u)return u.set.call(this,c);if(t.sealed)throw new d_.ClientError("Can not add a property to a sealed table schema");Uc(this)[o]=c}),i("deleteProperty",function(o){Uc(this)[o]=void 0}),i("toJSON",function(){let o=this[Nt],c;for(let l in o)c||(c=Object.assign({},this[le])),c[l]=o[l];return Object.keys(this).length>0&&(c||(c=Object.assign({},this[le])),Object.assign(c,this)),c||this[le]}),r.get||i("get",r.getProperty),r.delete||i("delete",r.deleteProperty);function i(o,c){Object.defineProperty(r,o,{value:c,configurable:!0})}a(i,"setMethod")}function yN(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(n){this[le]=n}},m_(r,t)),new r(e)):new E_(e);case Array:let s=new h_(e.length);s[le]=e;for(let n=0,i=e.length;n<i;n++){let o=e[n];o&&typeof o=="object"&&(o=yN(o,t?.elements)),s[n]=o}return s}}function p_(e){let t=e[Nt],r;for(let n in t){r||(r=Object.assign({},e[le]));let i=t[n];i&&typeof i=="object"&&(i=p_(i)),r[n]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[le])),Object.assign(r,e)),r||e[le]}function Mc(e){let t;if(e[le]&&e.constructor===Array&&!Object.isFrozen(e)){t=e;for(let s=0,n=e.length;s<n;s++){let i=e[s];if(i&&typeof i=="object"){let o=Mc(i);o!==i&&t===e&&(t=e.slice(0)),i=o}t[s]=i}return Object.freeze(t)}let r=e[Nt];for(let s in r){t||(t=Object.assign({},e[le]));let n=r[s];n&&typeof n=="object"&&(n=Mc(n)),t[s]=n}return t?Object.freeze(t):e[le]||Object.freeze(e)}function f_(e){let t=e[le];if(!t)return!0;if(e.constructor===Array){if(e[Vi]||e.length!==t.length)return!0;for(let r=0,s=e.length;r<s;r++){let n=t[r],i=e[r];if(n&&i?.[le]===n){if(f_(i))return!0}else return!0}}else{let r=e[Nt];for(let s in r){let n=r[s];if(n&&typeof n=="object"){let i=t[s];if(i&&n[le]===i){if(f_(n))return!0}else return!0}else return!0}}return!1}var d_,Nt,E_,Vi,h_,S_=Te(()=>{Is();d_=D(z()),Nt=Symbol("own-data");a(Uc,"getChanges");a(m_,"assignTrackedAccessors");a(yN,"trackObject");E_=class{static{a(this,"GenericTrackedObject")}constructor(t){this[le]=t}};m_(E_,{});a(p_,"collapseData");a(Mc,"deepFreeze");a(f_,"hasChanges");Vi=Symbol.for("has-array-changes"),h_=class extends Array{static{a(this,"TrackedArray")}[Vi];constructor(t){super(t)}splice(...t){return this[Vi]=!0,super.splice(...t)}push(...t){return this[Vi]=!0,super.push(...t)}pop(){return this[Vi]=!0,super.pop()}unshift(...t){return this[Vi]=!0,super.unshift(...t)}shift(){return this[Vi]=!0,super.shift()}};h_.prototype.constructor=Array});function Xe(e,t){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let r=e.transaction=new Zh;e.timestamp&&(r.timestamp=e.timestamp),r[Ne]=e,e.resourceCache=[];let s;try{if(s=t(r),s?.then)return s.then(n,i)}catch(o){i(o)}return n(s);function n(o){let c=r.commit();return c.then?c.then(()=>(e.transaction=null,o)):(e.transaction=null,o)}function i(o){throw r.abort(),e.transaction=null,o}}var IN,wN,Zh,Yi=Te(()=>{IN=D(Ht()),wN=require("../index");Is();a(Xe,"transaction");(0,wN._assignPackageExport)("transaction",Xe);Xe.commit=function(e){let t=(e[Ne]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Xe.abort=function(e){let t=(e[Ne]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()};Zh=class extends Array{static{a(this,"TransactionSet")}commit(t=!0){let r=[],s=this.length;for(let n=0;n<s;n++)this[n].validate?.();this.timestamp||(this.timestamp=(0,IN.getNextMonotonicTime)());for(let n=0;n<s;n++){let o=this[n].commit(this.timestamp,t);o?.then&&r.push(o)}return r.length>0?Promise.all(r).then(()=>(this.splice(0,s),this.commit(t))):this.length>s?(this.splice(0,s),this.commit(t)):(this.length=0,{txnTime:this.timestamp})}abort(){for(let t of this)t.abort?.()}doneReading(){for(let t of this)t.doneReading?.()}}});function rm(e,t,r,s,n){let i=e[0]??e.attribute,o,c,u,l,_=e[1]??e.value;_ instanceof Date&&(_=_.getTime());let d=e.comparator,E;switch(fV[d]||d){case"lt":o=!0,c=_;break;case"le":o=!0,c=_,u=!0;break;case"gt":o=_,l=!0;break;case"ge":o=_;break;case"prefix":o=_,c=_.slice(0),c[c.length-1]=Cs.MAXIMUM_KEY;break;case"starts_with":o=_.toString(),c=_+String.fromCharCode(65535);break;case"between":o=_[0],o instanceof Date&&(o=o.getTime()),c=_[1],c instanceof Date&&(c=c.getTime()),u=!0;break;case Rt.SEARCH_TYPES.EQUALS:case void 0:o=_,c=_,u=!0;break;case"ne":case"contains":case"ends_with":E=!0;break}if(r){let T=o;o=c,c=T,T=!l,l=!u,u=T}let f=i===s.primaryKey||i==null,h=f?s.primaryStore:s.indices[i];if(!h||h.isIndexing||E){if(!n)throw new em.ClientError(`"${i}" is not indexed${h?.isIndexing?" yet":""}, can not search for this attribute`,404);let T=sm(e);if(!T)throw new em.ClientError(`Unknown search operator ${e.comparator}`);return s.primaryStore.getRange({start:!0,transaction:t,reverse:r}).map(({key:A,value:g})=>new Promise(x=>setImmediate(()=>x(T(g)?A:LN.SKIP))))}let S={start:o,end:c,inclusiveEnd:u,exclusiveStart:l,values:!f,transaction:t,reverse:r};return f?h.getRange(S):h.getRange(S).map(({value:T})=>T)}function sm(e){let t=e.comparator,r=e[0]??e.attribute,s=e[1]??e.value;switch(s instanceof Date&&(s=s.getTime()),t){case Rt.SEARCH_TYPES.EQUALS:case void 0:return ws(r,n=>n===s);case Rt.SEARCH_TYPES.CONTAINS:return ws(r,n=>n?.toString().includes(s));case Rt.SEARCH_TYPES.ENDS_WITH:case Rt.SEARCH_TYPES._ENDS_WITH:return ws(r,n=>n?.toString().endsWith(s));case Rt.SEARCH_TYPES.STARTS_WITH:case Rt.SEARCH_TYPES._STARTS_WITH:return ws(r,n=>typeof n=="string"&&n.startsWith(s));case Rt.SEARCH_TYPES.BETWEEN:return s[0]instanceof Date&&(s[0]=s[0].getTime()),s[1]instanceof Date&&(s[1]=s[1].getTime()),ws(r,n=>(0,Cs.compareKeys)(n,s[0])>=0&&(0,Cs.compareKeys)(n,s[1])<=0);case"gt":case Rt.SEARCH_TYPES.GREATER_THAN:case Rt.SEARCH_TYPES._GREATER_THAN:return ws(r,n=>(0,Cs.compareKeys)(n,s)>0);case"ge":case Rt.SEARCH_TYPES.GREATER_THAN_EQUAL:case Rt.SEARCH_TYPES._GREATER_THAN_EQUAL:return ws(r,n=>(0,Cs.compareKeys)(n,s)>=0);case Rt.SEARCH_TYPES.LESS_THAN:case"lt":case Rt.SEARCH_TYPES._LESS_THAN:return ws(r,n=>(0,Cs.compareKeys)(n,s)<0);case"le":case Rt.SEARCH_TYPES.LESS_THAN_EQUAL:case Rt.SEARCH_TYPES._LESS_THAN_EQUAL:return ws(r,n=>(0,Cs.compareKeys)(n,s)<=0);case"ne":return ws(r,n=>(0,Cs.compareKeys)(n,s)!==0);default:return}}function ws(e,t){return r=>{let s=r[e];return typeof s!="object"||!s?t(s):Array.isArray(s)?s.some(t):s instanceof Date?t(s.getTime()):!1}}function T_(e){if(!e)return;let t=new tm,r,s,n,i,o;for(;r=CN.exec(e);){i=CN.lastIndex;let[,c,u]=r;switch(u){case")":switch(o){case"limit":if(c.indexOf(",")>-1){let[l,_]=c.split(",");t.offset=+l,t.limit=_-t.offset}else t.limit=+c;break;case"select":if(c[0]==="["){if(c[c.length-1]!=="]")throw new Error("Unmatched brackets");t.select=c.slice(1,-1).split(","),t.select.asArray=!0}else c.indexOf(",")>-1?t.select=(c.endsWith(",")?c.slice(0,-1):c).split(","):t.select=c;break;case"group-by":throw new Error("Group by is not implemented yet");case"sort":t.sort=c.split(",").map(l=>{switch(l[0]){case"-":return{attribute:l.slice(1),descending:!0};case"+":return{attribute:l.slice(1),descending:!1};default:return{attribute:l,descending:!1}}});break;default:throw new Error(`Unknown query function call ${o}`)}break;case"(":o=c;break;case"=":s?c.length<=2&&(n=c):(n="equals",s=decodeURIComponent(c));break;case"!=":case"<":case"<=":case">":case">=":n=EV[u],s=decodeURIComponent(c);break;case"=*":n="ends_with",s=decodeURIComponent(c);break;case"*":case"*&":t.conditions.push({comparator:n==="ends_with"?"contains":"starts_with",attribute:s,value:decodeURIComponent(c)}),s=null;break;case"":case void 0:case"&":case"|":if(!s)throw new Error(`Unable to parse query, no part before ${u} at ${i} in ${e}`);t.conditions.push({comparator:n,attribute:s,value:decodeURIComponent(c)}),s=void 0;break;default:throw new Error(`Unknown operator ${u} in query ${e}`)}}if(i!==e.length)throw new Error(`Unable to parse query, unexpected end in ${e}`);return t}var em,Rt,Cs,LN,CN,EV,fV,tm,g_=Te(()=>{em=D(z()),Rt=D(Ge()),Cs=require("ordered-binary"),LN=require("lmdb"),CN=/([^?&|=<>!()*]+)([&|=<>!()*]*)/g,EV={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne"};a(rm,"idsForCondition");fV={greater_than:"gt",greater_than_equal:"ge",less_than:"lt",less_than_equal:"le",not_equal:"ne",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(sm,"filterByType");a(ws,"attributeComparator");a(T_,"parseQuery");tm=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let s=this.conditions[r];if(s.attribute===t)return s.value}}}});var om={};Ke(om,{CONTEXT:()=>Ne,ID_PROPERTY:()=>ue,IS_COLLECTION:()=>_n,RECORD_PROPERTY:()=>le,Resource:()=>bt,SAVE_UPDATES_PROPERTY:()=>BN,snake_case:()=>mV});function mV(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function DN(e,t){if(e=e.slice(1),e.indexOf("/")===-1)return e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e));let r=e.split("/"),s=new im(r.length);for(let n=0;n<r.length;n++)s[n]=t.coerceId(decodeURIComponent(r[n]));return s}function Gr(e,t){s.reliesOnPrototype=!0;let r=t.hasContent;return s;function s(n,i,o){let c,u,l;if(r?o?(l=i,o=o[Ne]||o):i?typeof n=="object"&&n&&(!Array.isArray(n)||typeof n[0]=="object")?(l=n,c=l[this.primaryKey]??null,o=i[Ne]||i):l=i:(l=n,c=l[ue]??l[this.primaryKey]??null):i?o=i[Ne]||i:n&&typeof n=="object"&&!Array.isArray(n)&&(o=n),c===void 0)if(typeof n=="string")c=n;else if(typeof n=="object"&&n)if(u=n,n[Symbol.iterator]){c=[];for(let E of n){if(typeof E=="object"&&E)break;c.push(E)}c.length===0?c=null:(c.length===1&&(c=c[0]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null)))}else{if(typeof(c=n.url)=="string"){let E=c.indexOf("?");if(E>-1){let h=this.parseQuery(c.slice(E+1));u?u=Object.assign(h,u):u=h,c=c.slice(0,E)}let f=this.parsePath(c,o,u);f?.query?(u=f.query,c=f.id):c=f}c===void 0&&(c=n.id??null)}else c=n??null;o||(o={});let _;if(u?.allowInvalidated?(_=Object.assign({},t),_.allowInvalidated=!0):_=t,o.transaction){let E=this.getResource(c,o,_);return E.then?E.then(d):d(E)}else return Xe(o,()=>{let E=this.getResource(c,o,_);return E.then?E.then(d):d(E)});function d(E){if(t.type==="read"&&(E[BN]=!1),o.authorize){o.authorize=!1;let f=t.type==="read"?E.allowRead(o.user,o):t.type==="update"?E.doesExist?.()===!1?E.allowCreate(o.user,o):E.allowUpdate(o.user,o):t.type==="create"?E.allowCreate(o.user,o):E.allowDelete(o.user,o);if(f?.then)return f.then(h=>{if(!h)throw new R_(o.user);return typeof l?.then=="function"?l.then(S=>e(E,u,o,S)):e(E,u,o,l)});if(!f)throw new R_(o.user)}return typeof l?.then=="function"?l.then(f=>e(E,u,o,f)):e(E,u,o,l)}a(d,"authorizeActionOnResource")}}function xr(e,t){let r=new vN.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let s of["get","put","post","delete","query","move","copy"])typeof e[s]=="function"&&r.allow.push(s);throw r}function nm(e){let t=e[le];if(t){let r=e[Nt];return s=>{let n;return e.hasOwnProperty(s)&&typeof(n=e[s])!="function"?n:r&&s in r?r[s]:t[s]}}else return r=>e[r]}function UN(e){if(typeof e=="string")return t=>nm(t)(e);if(typeof e=="object"){if(e.asArray)return r=>{let s=[],n=nm(r);for(let i of e)s.push(n(i));return s};let t=e.forceNulls;return r=>{let s={},n=nm(r);for(let i of e){let o=n(i);o===void 0&&t&&(o=null),s[i]=o}return s}}else throw new Error("Invalid select argument type "+typeof e)}var MN,PN,vN,Ne,ue,_n,BN,le,hV,bt,R_,im,Is=Te(()=>{MN=require("crypto");Dc();PN=require("../index"),vN=D(z());S_();Yi();g_();Ne=Symbol.for("context"),ue=Symbol.for("primary-key"),_n=Symbol("is-collection"),BN=Symbol("save-updates"),le=Symbol("stored-record"),hV={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},bt=class{static{a(this,"Resource")}[Ne];[ue];static transactions;constructor(t,r){this[ue]=t;let s=r?.[Ne];this[Ne]=s!==void 0?s:r||null}updateModificationTime(t=Date.now()){t>this[LAST_MODIFICATION_PROPERTY]&&(this[LAST_MODIFICATION_PROPERTY]=t)}static get=Gr(function(t,r,s,n){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null){let l=UN(u);return typeof c?.map=="function"?c.map(l):l(c)}return c}},{type:"read"});static put=Gr(function(t,r,s,n){if(Array.isArray(n)&&t[_n]){let i=[],o=s.authorize;for(let c of n)o&&(s.authorize=!0),i.push(this.put(t,r,s,c));return i}return t.put?t.put(n,r):xr(t,"put")},{hasContent:!0,type:"update"});static delete=Gr(function(t,r,s,n){return t.delete?t.delete(r):xr(t,"delete")},{hasContent:!1,type:"delete",allowInvalidated:!0});static getNewId(){return(0,MN.randomUUID)()}static create(t,r,s){let n;return t==null?n=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?n=[...t,this.getNewId()]:typeof t!="object"?n=[t,this.getNewId()]:(n=this.getNewId(),s=r,r=t),Xe(s,()=>{let i=new this(n,s),o=i.put?i.put(r):xr(i,"put");return s.newLocation=n,s.createdResource=!0,o?.then?o.then(()=>n):n})}static invalidate=Gr(function(t,r,s,n){return t.invalidate?t.invalidate(r):xr(t,"delete")},{hasContent:!1,type:"update",allowInvalidated:!0});static post=Gr(function(t,r,s,n){return t[ue]!=null&&t.update(),t.post(n,r)},{hasContent:!0,type:"create"});static connect=Gr(function(t,r,s,n){return t.connect?t.connect(r):xr(t,"connect")},{type:"read"});static subscribe=Gr(function(t,r,s,n){return t.subscribe?t.subscribe(r):xr(t,"subscribe")},{type:"read"});static publish=Gr(function(t,r,s,n){return t[ue]!=null&&t.update(),t.publish?t.publish(n,r):xr(t,"publish")},{hasContent:!0,type:"create"});static search=Gr(function(t,r,s,n){let i=t.search?t.search(s):xr(t,"search"),o=s.select;if(o&&s.hasOwnProperty("select")&&i!=null){let c=UN(o);return i.map(c)}return i},{type:"read"});static query=Gr(function(t,r,s,n){return t.search?t.search(n,r):xr(t,"search")},{hasContent:!0,type:"read"});static copy=Gr(function(t,r,s,n){return t.copy?t.copy(s.headers?.destination,r):xr(t,"copy")},{type:"create"});static move=Gr(function(t,r,s,n){return t.move?t.move(s.headers?.destination,r):xr(t,"move")},{type:"delete"});post(t){if(this[_n])return this.constructor.create(this[ue],t,this[Ne]);xr(this,"post")}static isCollection(t){return t?.[_n]}static coerceId(t){return t}static parseQuery(t){return T_(t)}static parsePath(t,r,s){let n=t.indexOf(".");if(n>-1){let i=t.slice(n+1);t=t.slice(0,n);let o=r?.headers&&hV[i];if(o)r.headers.accept=o;else if(s)s.property=i;else return{query:{property:i},id:DN(t,this)}}return DN(t,this)}static getResource(t,r,s){let n,i=r[Ne],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=t==null||Array.isArray(t)&&t[t.length-1]==null;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let l=u.asMap.get(t);if(n=l?.find(_=>_.constructor===c),n)return n;l||u.asMap.set(t,l=[]),l.push(n=new c(t,i))}else{if(n=u.find(l=>l[ue]===t&&l.constructor===c),n)return n;if(u.push(n=new c(t,i)),u.length>10){let l=new Map;for(let _ of u){let d=_[ue],E=l.get(d);E?E.push(_):l.set(d,[_])}i.resourceCache.length=0,i.resourceCache.asMap=l}}}else n=new c(t,i);return o&&(n[_n]=!0),n}connect(t){let r=new ys;if(t?.subscribe!==!1){let s={listener:i=>{r.send(i)}},n=this.subscribe?.(s);r.on("close",()=>n?.end())}return r}update(t){throw new Error("Not implemented")}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this[ue]}getContext(){return this[Ne]}};bt.prototype[Ne]=null;(0,PN._assignPackageExport)("Resource",bt);a(mV,"snake_case");R_=class extends Error{static{a(this,"AccessError")}constructor(t){t?(super("Unauthorized access to resource"),this.statusCode=403):(super("Must login"),this.statusCode=401)}};a(DN,"pathToId");im=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(Gr,"transactional");a(xr,"missingMethod");a(nm,"selectFromObject");a(UN,"transformForSelect")});var Pc={};Ke(Pc,{server:()=>Et});var HN,Et,rs=Te(()=>{HN=require("../index"),Et={};(0,HN._assignPackageExport)("server",Et)});var um={};Ke(um,{loadGQLSchema:()=>SV,start:()=>cm,startOnMainThread:()=>pV});function cm({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,s,n,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:l,StringValueNode:_}=await import("graphql"),d=o(new c(r.toString(),n)),E=new Map,f=[],h;for(let S of d.definitions)switch(S.kind){case u.OBJECT_TYPE_DEFINITION:let V=function(I){if(I.kind==="NonNullType"){let M=V(I.type);return M.nullable=!0,M}return I.kind==="ListType"?{type:"array",elements:V(I.type)}:{type:I.name?.value}};a(V,"getProperty");let T=S.name.value,A=[],g={table:null,database:null,properties:A};E.set(T,g);for(let I of S.directives){if(I.name.value==="table"){for(let b of I.arguments)g[b.name.value]=b.value.value;g.schema&&(g.database=g.schema),g.table||(g.table=T),g.audit&&(g.audit=g.audit!=="false"),g.attributes=g.properties,f.push(g)}if(I.name.value==="sealed"&&(g.sealed=!0),I.name.value==="export"){g.export=!0;for(let b of I.arguments)b.name.value==="name"&&(g.export={name:b.value.value})}}let x=!1;for(let I of S.fields){let b=V(I.type);b.name=I.name.value,A.push(b);for(let M of I.directives)if(M.name.value==="primaryKey")x?console.warn("Can not define two attributes as a primary key"):(b.isPrimaryKey=!0,x=!0);else if(M.name.value==="indexed")b.indexed=!0;else if(M.name.value==="createdTime")b.assignCreatedTime=!0;else if(M.name.value==="updatedTime")b.assignUpdatedTime=!0;else if(M.name.value==="expiresAt")b.expiresAt=!0;else if(M.name.value==="allow"){let J=b.authorizedRoles=[];for(let B of M.arguments)B.name.value==="role"&&J.push(B.value.value)}}g.typeName=T,T==="Query"&&(h=g)}for(let[S,T]of E)for(let A of T.properties){let g=E.get(A.type);g&&(A.properties=g.properties)}for(let S of f)S.tableClass=e(S),S.export&&i.set((0,am.dirname)(s)+"/"+(S.export.name||S.typeName),S.tableClass);if(h)for(let S of h.properties){let T=E.get(S.type);if(!T)throw new Error(`${S.type} was not found as a Query export`);i.set((0,am.dirname)(s)+"/"+S.name,T.tableClass)}}}var am,pV,SV,qN=Te(()=>{am=require("path");_e();a(cm,"start");pV=cm,SV=cm({ensureTable:ft}).handleFile});async function A_(e){return TV?(vc||(vc=gV(AV)),(await(await vc).import(e)).namespace):import(e)}async function gV(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),vc=new Compartment({console,Math,Date,fetch:RV,...e()},{},{name:"h-dapp",resolveHook(r,s){return r==="harperdb"?"harperdb":(r=new URL(r,s).toString(),(0,GN.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(n){Object.assign(n,{Resource:bt,tables:Rr,databases:xe})}};let s=await(0,FN.readFile)(new URL(r),{encoding:"utf-8"});return new t(s,r)}}),vc}function RV(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 AV(){return{Resource:bt,tables:Rr}}var FN,GN,TV,vc,lm=Te(()=>{Is();_e();FN=require("fs/promises"),GN=require("path"),TV=!1;a(A_,"secureImport");a(gV,"getCompartment");a(RV,"secureOnlyFetch");a(AV,"getGlobalVars")});var dm={};Ke(dm,{handleFile:()=>OV});async function OV(e,t,r,s){let n=new Map,i=(0,xN.pathToFileURL)(r).toString(),o=await A_(i);u(o.default)&&s.set((0,_m.dirname)(t),o.default),c(o,(0,_m.dirname)(t));function c(l,_){for(let d in l){let E=l[d];u(E)?s.set(_+"/"+d,E):typeof E=="object"&&c(E,_+"/"+d)}}a(c,"recurseForResources");function u(l){return typeof l=="function"&&(l.get||l.put||l.post||l.delete)}return a(u,"isResource"),n}var xN,_m,kN=Te(()=>{xN=require("url");lm();_m=require("path");a(OV,"handleFile")});var fm={};Ke(fm,{start:()=>NV});function NV({resources:e}){e.set("login",Em),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Em,$N=Te(()=>{Is();a(NV,"start");Em=class extends bt{static{a(this,"Login")}static async get(t,r,s){}static async post(t,r,s){let{username:n,password:i,redirect:o}=r;return{data:await s.login(n,i)}}}});var mm=m((w_e,KN)=>{"use strict";var{Readable:bV}=require("stream"),yV=1e4;KN.exports={streamAsJSON(e){return new hm({value:e})}};var hm=class extends bV{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0)}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],s=t[Symbol.iterator];if((s||r)&&!t.then){yield"[";let n=!0;if((r||s)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator](),o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){yield"]";return}else n?n=!1:yield",",yield*this.serialize(o.value)}for(let i of t)n?n=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(n=>this.serialize(n),VN)}catch(n){yield VN(n)}else yield JSON.stringify(t)}else yield JSON.stringify(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);YN(this.readIterator(this.iterator),t=>{t?(this.done=!0,this.push(null)):this._amReading=!1},t=>{console.error(t),this.done=!0,this.push(t.toString()),this.push(null)})}}push(t){return t===null||t instanceof Buffer?(this.bufferSize>0&&this.flush(),super.push(t)):(this.bufferSize+=t.length||t.toString().length,this.buffer.push(t),this.bufferSize>yV?this.flush():!0)}flush(){let t=super.push(this.buffer.join(""));return this.buffer=[],this.bufferSize=0,t}readIterator(t){try{let r;if(t.childIterator)return YN(this.readIterator(t.childIterator),s=>{if(s)return t.childIterator=null,this.readIterator(t)});do{let s=t.next();if(s.done)return!0;if(r=s.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(n=>{if(n&&typeof n.return=="function")return t.childIterator=n,this.readIterator(t);if(this.push(n+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}};function VN(e){return console.error(e),JSON.stringify(e.toString())}a(VN,"handleError");function YN(e,t,r){return e&&e.then?r?e.then(t,r):e.then(t):t(e)}a(YN,"when")});var ib=m((D_e,nb)=>{"use strict";var pm=require("recursive-iterator"),IV=require("alasql"),Sm=require("clone"),WN=F(),{handleHDBError:QN,hdb_errors:wV}=z(),{HDB_ERROR_MSGS:zN,HTTP_STATUS_CODES:JN}=wV,{getDatabases:CV}=(_e(),re(be)),LV=["DISTINCT_ARRAY"],jN=Symbol("validateTables"),Tm=Symbol("validateTable"),L_e=Symbol("getAllColumns"),XN=Symbol("validateAllColumns"),O_=Symbol("findColumn"),ZN=Symbol("validateOrderBy"),Bc=Symbol("validateSegment"),gm=Symbol("validateColumn"),eb=Symbol("setColumnsForTable"),tb=Symbol("checkColumnsForAsterisk"),rb=Symbol("validateGroupBy"),sb=Symbol("hasColumns"),Rm=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[jN](),this[tb](),this[XN]()}[jN](){if(this[sb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[Tm](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[Tm](t.table)})}}[sb](){let t=!1,r=new pm(this.statement);for(let{node:s,path:n}of r)if(s&&s.columnid){t=!0;break}return t}[Tm](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=CV();if(!r[t.databaseid])throw QN(new Error,zN.SCHEMA_NOT_FOUND(t.databaseid),JN.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw QN(new Error,zN.TABLE_NOT_FOUND(t.databaseid,t.tableid),JN.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(n=>{let i=Sm(n);i.table=Sm(t),this.attributes.push(i)})}[O_](t){return this.attributes.filter(r=>t.tableid?(r.table.as===t.tableid||r.table.tableid===t.tableid)&&r.attribute===t.columnid:r.attribute===t.columnid)}[tb](){let t=new pm(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[eb](r.tableid)}[eb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&this.statement.columns.push(new IV.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[XN](){this[Bc](this.statement.columns,!1),this[Bc](this.statement.joins,!1),this[Bc](this.statement.where,!1),this[rb](this.statement.group,!1),this[Bc](this.statement.order,!0)}[Bc](t,r){if(!t)return;let s=new pm(t),n=[];for(let{node:i,path:o}of s)!WN.isEmpty(i)&&!WN.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[ZN](i):n.push(this[gm](i)));return n}[rb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&LV.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=Sm(s);delete n.as,r.push(n)}else if(s.columnid){let n=this[O_](s)[0];n&&r.push(n)}}}),this.statement.group.forEach(s=>{let n=null;if(!s.columnid)r.forEach((i,o)=>{if(i.toString()===s.toString()){n=i,r.splice(o,1);return}});else{let i=this[O_](s);if(!i||i.length===0)throw`unknown column '${s.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${s.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){n=o,r.splice(c,1);return}})}if(!n)throw`group by column '${s.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[ZN](t){let r=this.statement.columns.filter(s=>s.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[gm](t)}[gm](t){let r=this[O_](t),s=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${s}`;if(r.length>1)throw`ambiguous column reference ${s}`;return r[0]}};nb.exports=Rm});var ab=m((M_e,ob)=>{"use strict";var Am=class{static{a(this,"BridgeMethods")}createSchema(){throw new Error("createSchema bridge method is not defined")}dropSchema(){throw new Error("dropSchema bridge method is not defined")}createTable(){throw new Error("createTable bridge method is not defined")}dropTable(){throw new Error("dropTable bridge method is not defined")}createRecords(){throw new Error("createRecords bridge method is not defined")}updateRecords(){throw new Error("updateRecords bridge method is not defined")}async upsertRecords(){throw new Error("upsertRecords bridge method is not defined")}deleteRecords(){throw new Error("deleteRecords bridge method is not defined")}createAttribute(){throw new Error("createAttribute bridge method is not defined")}dropAttribute(){throw new Error("dropAttribute bridge method is not defined")}searchByConditions(){throw new Error("searchByConditions bridge method is not defined")}searchByHash(){throw new Error("searchByHash bridge method is not defined")}searchByValue(){throw new Error("searchByValue bridge method is not defined")}getDataByHash(){throw new Error("getDataByHash bridge method is not defined")}getDataByValue(){throw new Error("getDataByValue bridge method is not defined")}deleteRecordsBefore(){throw new Error("deleteRecordsBefore bridge method is not defined")}deleteAuditLogsBefore(){throw new Error("deleteAuditLogsBefore bridge method is not defined")}async readAuditLog(){throw new Error("readAuditLog bridge method is not defined")}};ob.exports=Am});var ub=m((v_e,cb)=>{"use strict";var Om=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};cb.exports=Om});var N_=m((H_e,lb)=>{"use strict";var bm=Y(),ym=R();bm.initSync();var DV=bm.get(ym.CONFIG_PARAMS.STORAGE_COMPRESSION),UV=bm.get(ym.CONFIG_PARAMS.STORAGE_CACHING)!==!1,MV=ym.UPDATES_PROPERTY,Nm=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.compression=DV&&r,this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=UV&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.alwaysLazyProperty=s=>s===MV)}};lb.exports=Nm});var y_=m((F_e,db)=>{"use strict";var zo=Y(),Hc=R();zo.initSync();var PV=zo.get(Hc.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||zo.get(Hc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||zo.get(Hc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",_b=zo.get(Hc.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC),vV=zo.get(Hc.CONFIG_PARAMS.STORAGE_NOREADAHEAD),b_=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=1e3,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.noSync=PV,this.noFSAccess=!0,_b!==void 0&&(this.overlappingSync=_b),this.noReadAhead=vV}};db.exports=b_;b_.MAX_DBS=1e4});var we=m((x_e,Ab)=>{"use strict";var wm=require("lmdb"),ss=require("fs-extra"),Ar=require("path"),I_=Ht(),hb=C(),zt=gr().LMDB_ERRORS_ENUM,w_=ub(),Cm=N_(),mb=y_(),jn=Ge(),Eb=R(),{table:BV,resetDatabases:HV}=(_e(),re(be)),fb=Y(),ns=jn.INTERNAL_DBIS_NAME,pb=jn.DBI_DEFINITION_NAME,qV="data.mdb",FV="lock.mdb",qc=".mdb",GV="-lock",Im=class{static{a(this,"TransactionCursor")}constructor(t,r,s=!1){this.dbi=kr(t,r),this.key_type=this.dbi[jn.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[jn.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:s===!1}),this.cursor=new wm.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function C_(e,t){if(e===void 0)throw new Error(zt.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(zt.ENV_NAME_REQUIRED)}a(C_,"pathEnvNameValidation");async function Lm(e,t,r=!0){try{await ss.access(e)}catch(s){throw s.code==="ENOENT"?new Error(zt.INVALID_BASE_PATH):s}try{let s=Ar.join(e,t+qc);return await ss.access(s,ss.constants.R_OK|ss.constants.F_OK),s}catch(s){if(s.code==="ENOENT")if(r)try{return await ss.access(Ar.join(e,t,qV),ss.constants.R_OK|ss.constants.F_OK),Ar.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(zt.INVALID_ENVIRONMENT)}else throw new Error(zt.INVALID_ENVIRONMENT);throw s}}a(Lm,"validateEnvironmentPath");function L_(e,t){if(I_.validateEnv(e),t===void 0)throw new Error(zt.DBI_NAME_REQUIRED)}a(L_,"validateEnvDBIName");async function xV(e,t,r=!1,s=!1){C_(e,t);let n=Ar.basename(e);t=t.toString();let i=fb.get(Eb.CONFIG_PARAMS.SCHEMAS);i||fb.setProperty(Eb.CONFIG_PARAMS.SCHEMAS,i={}),i[n]||(i[n]={}),i[n].path=e;try{return await Lm(e,t,s),Sb(e,t,r)}catch(o){if(o.message===zt.INVALID_ENVIRONMENT){let c=Ar.join(e,t);await ss.mkdirp(s?c:e);let u=new mb(s?c:c+qc,!1),l=wm.open(u);l.dbis=Object.create(null);let _=new Cm(!1);l.openDB(ns,_),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=Dm(e,t,r);return l[jn.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=l,l}throw o}}a(xV,"createEnvironment");async function kV(e,t,r,s=!0){C_(e,t),t=t.toString();let n=Ar.join(e,t);return BV({table:t,database:Ar.parse(e).name,path:n,attributes:[{name:"id",isPrimaryKey:!0}]})}a(kV,"copyEnvironment");async function Sb(e,t,r=!1){C_(e,t),t=t.toString();let s=Dm(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[s]!==void 0)return global.lmdb_map[s];let n=await Lm(e,t),i=Ar.join(e,t+qc),o=n!=i,c=new mb(n,o),u=wm.open(c);u.dbis=Object.create(null);let l=gb(u);for(let _=0;_<l.length;_++)kr(u,l[_]);return u[jn.ENVIRONMENT_NAME_KEY]=s,global.lmdb_map[s]=u,u}a(Sb,"openEnvironment");async function $V(e,t,r=!1){C_(e,t),t=t.toString();let s=Ar.join(e,t+qc),n=await Lm(e,t);if(global.lmdb_map!==void 0){let i=Dm(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await Tb(o),delete global.lmdb_map[i]}}await ss.remove(n),await ss.remove(n===s?n+GV:Ar.join(Ar.dirname(n),FV))}a($V,"deleteEnvironment");async function Tb(e){I_.validateEnv(e);let t=e[jn.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(Tb,"closeEnvironment");function Dm(e,t,r=!1){let n=`${Ar.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}a(Dm,"getCachedEnvironmentName");function VV(e){I_.validateEnv(e);let t=Object.create(null),r=kr(e,ns);for(let{key:s,value:n}of r.getRange({start:!1}))if(s!==ns)try{t[s]=Object.assign(new w_,n)}catch{hb.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}a(VV,"listDBIDefinitions");function gb(e){I_.validateEnv(e);let t=[],r=kr(e,ns);for(let{key:s}of r.getRange({start:!1}))s!==ns&&t.push(s);return t}a(gb,"listDBIs");function YV(e,t){let s=kr(e,ns).getEntry(t),n=new w_;if(s!==void 0){try{n=Object.assign(n,s.value)}catch{hb.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return n}}a(YV,"getDBIDefinition");function Rb(e,t,r,s=!r){if(L_(e,t),t=t.toString(),t===ns)throw new Error(zt.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return kr(e,t)}catch(n){if(n.message===zt.DBI_DOES_NOT_EXIST){let i=new Cm(r,s===!0),o=e.openDB(t,i),c=new w_(r===!0,s);return o[pb]=c,kr(e,ns).putSync(t,c),e.dbis[t]=o,o}throw n}}a(Rb,"createDBI");function kr(e,t){if(L_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==ns?r=YV(e,t):r=new w_,r===void 0)throw new Error(zt.DBI_DOES_NOT_EXIST);let s;try{let n=new Cm(r.dup_sort,r.useVersions);if(s=e.openDB(t,n),s.db===void 0)throw new Error("MDB_NOTFOUND")}catch(n){throw n.message.includes("MDB_NOTFOUND")===!0?new Error(zt.DBI_DOES_NOT_EXIST):n}return s[pb]=r,e.dbis[t]=s,s}a(kr,"openDBI");function KV(e,t){L_(e,t),t=t.toString();let r=kr(e,t),s=r.getStats();return r[jn.DBI_DEFINITION_NAME].is_hash_attribute&&s.entryCount>0&&s.entryCount--,s}a(KV,"statDBI");async function WV(e,t){try{let r=Ar.join(e,t+qc);return(await ss.stat(r)).size}catch{throw new Error(zt.INVALID_ENVIRONMENT)}}a(WV,"environmentDataSize");function QV(e,t){if(L_(e,t),t=t.toString(),t===ns)throw new Error(zt.CANNOT_DROP_INTERNAL_DBIS_NAME);kr(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],kr(e,ns).removeSync(t)}a(QV,"dropDBI");function zV(e,t,r){let s;for(let n=0;n<r.length;n++){let i=r[n];if(!e.dbis[i])try{kr(e,i)}catch(o){if(o.message===zt.DBI_DOES_NOT_EXIST)Rb(e,i,i!==t,i===t),s=!0;else throw o}}s&&HV()}a(zV,"initializeDBIs");Ab.exports={openDBI:kr,openEnvironment:Sb,createEnvironment:xV,listDBIs:gb,listDBIDefinitions:VV,createDBI:Rb,dropDBI:QV,statDBI:KV,deleteEnvironment:$V,initializeDBIs:zV,TransactionCursor:Im,environmentDataSize:WV,copyEnvironment:kV,closeEnvironment:Tb}});var Nb=m(($_e,Ob)=>{"use strict";var Um=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};Ob.exports=Um});var yb=m((Y_e,bb)=>{"use strict";var Mm=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],s=void 0,n=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s,this.original_records=n}};bb.exports=Mm});var wb=m((W_e,Ib)=>{"use strict";var Pm=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};Ib.exports=Pm});var Wi=m((X_e,Db)=>{"use strict";var JV=we(),jV=Nb(),XV=yb(),ZV=wb(),Ls=Ht(),Fc=gr().LMDB_ERRORS_ENUM,eY=Ge(),dn=R(),tY=F(),rY=require("uuid"),z_e=require("lmdb"),{handleHDBError:sY,hdb_errors:nY}=z(),{OVERFLOW_MARKER:J_e,MAX_SEARCH_KEY_LENGTH:j_e}=eY,Cb=Y();Cb.initSync();var D_=Cb.get(dn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),vm=dn.TIME_STAMP_NAMES_ENUM.CREATED_TIME,Ki=dn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function iY(e,t,r,s,n=Ls.getNextMonotonicTime()){Fm(e,t,r,s),Bm(e,t,r);let i=new jV,o=[],c=[];for(let u=0;u<s.length;u++){let l=s[u];Lb(l,!0,n);let _=oY(e,t,r,l),d=l[t];o.push(_),c.push(d)}return Hm(o,c,s,i,n)}a(iY,"insertRecords");function oY(e,t,r,s){let n=s[t];return e.dbis[t].ifNoExists(n,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||s.hasOwnProperty(o)===!1)continue;let c=s[o];if(typeof c=="function"){let _=c([[{}]]);Array.isArray(_)&&(c=_[0][dn.FUNC_VAL],s[o]=c)}let u=Ls.getIndexedValues(c),l=e.dbis[o];if(u){D_&&l.prefetch(u.map(_=>({key:_,value:n})),U_);for(let _=0,d=u.length;_<d;_++)l.put(u[_],n)}}D_&&e.dbis[t].prefetch([n],U_),e.dbis[t].put(n,s,s[Ki])})}a(oY,"insertRecord");function aY(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(aY,"removeSkippedRecords");function Lb(e,t,r){let s=r>0;(s||!Number.isInteger(e[Ki]))&&(e[Ki]=r||(r=Ls.getNextMonotonicTime())),t===!0?(s||!Number.isInteger(e[vm]))&&(e[vm]=r||Ls.getNextMonotonicTime()):delete e[vm]}a(Lb,"setTimestamps");function Bm(e,t,r){r.indexOf(dn.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(dn.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(dn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(dn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),JV.initializeDBIs(e,t,r)}a(Bm,"initializeTransaction");async function cY(e,t,r,s,n=Ls.getNextMonotonicTime()){Fm(e,t,r,s),Bm(e,t,r);let i=new XV,o=[],c=[],u=[];for(let l=0;l<s.length;l++){let _=s[l],d=_[t],E;try{E=qm(e,t,_,d,i,!0,n)}catch{i.skipped_hashes.push(d),o.push(l);continue}c.push(E),u.push(d)}return Hm(c,u,s,i,n,o)}a(cY,"updateRecords");async function uY(e,t,r,s,n=Ls.getNextMonotonicTime()){try{Fm(e,t,r,s)}catch(u){throw sY(u,u.message,nY.HTTP_STATUS_CODES.BAD_REQUEST)}Bm(e,t,r);let i=new ZV,o=[],c=[];for(let u=0;u<s.length;u++){let l=s[u],_;tY.isEmpty(l[t])?(_=rY.v4(),l[t]=_):_=l[t];let d=qm(e,t,l,_,i,!1,n);o.push(d),c.push(_)}return Hm(o,c,s,i,n)}a(uY,"upsertRecords");async function Hm(e,t,r,s,n,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?s.written_hashes.push(t[c]):(s.skipped_hashes.push(t[c]),i.push(c));return s.txn_time=n||Ls.getNextMonotonicTime(),aY(r,i),s}a(Hm,"finalizeWrite");function qm(e,t,r,s,n,i=!1,o){let c=e.dbis[t],u=c.getEntry(s),l=u?.value,_=l;if(!l){if(i)return!1;l={}}if(Lb(r,!_,o),Number.isInteger(r[Ki])&&l[Ki]>r[Ki])return!1;_&&n.original_records.push(l);let d,E=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let S=r[h],T=e.dbis[h];if(T===void 0)continue;let A=l[h];if(typeof S=="function"){let x=S([[l]]);Array.isArray(x)&&(S=x[0][dn.FUNC_VAL],r[h]=S)}if(S===A)continue;let g=Ls.getIndexedValues(A);if(g){D_&&T.prefetch(g.map(x=>({key:x,value:s})),U_);for(let x=0,V=g.length;x<V;x++)T.remove(g[x],s)}if(g=Ls.getIndexedValues(S),g){D_&&T.prefetch(g.map(x=>({key:x,value:s})),U_);for(let x=0,V=g.length;x<V;x++)T.put(g[x],s)}}let f=Object.assign({},l,r);c.put(s,f,f[Ki])},"do_put");return u?d=c.ifVersion(s,u.version,E):d=c.ifNoExists(s,E),d.then(f=>f?!0:qm(e,t,r,s,n,i,o))}a(qm,"updateUpsertRecord");function lY(e,t,r){if(Ls.validateEnv(e),t===void 0)throw new Error(Fc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Fc.WRITE_ATTRIBUTES_REQUIRED):new Error(Fc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(lY,"validateBasic");function Fm(e,t,r,s){if(lY(e,t,r),!Array.isArray(s))throw s===void 0?new Error(Fc.RECORDS_REQUIRED):new Error(Fc.RECORDS_MUST_BE_ARRAY)}a(Fm,"validateWrite");function U_(){}a(U_,"noop");Db.exports={insertRecords:iY,updateRecords:cY,upsertRecords:uY}});var En=m((ede,_Y)=>{_Y.exports={hdb_table:{hash_attribute:"id",name:"hdb_table",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"name"},{attribute:"hash_attribute"},{attribute:"schema"},{attribute:"residence"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_attribute:{hash_attribute:"id",name:"hdb_attribute",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"schema"},{attribute:"table"},{attribute:"attribute"},{attribute:"schema_table"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_schema:{hash_attribute:"name",name:"hdb_schema",schema:"system",residence:["*"],attributes:[{attribute:"name"},{attribute:"createddate"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_user:{hash_attribute:"username",name:"hdb_user",schema:"system",residence:["*"],attributes:[{attribute:"username"},{attribute:"password"},{attribute:"role"},{attribute:"active"},{attribute:"hash"},{attribute:"refresh_token"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_role:{hash_attribute:"id",name:"hdb_role",schema:"system",attributes:[{attribute:"id"},{attribute:"role"},{attribute:"permission"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}],residence:["*"]},hdb_job:{hash_attribute:"id",name:"hdb_job",schema:"system",attributes:[{attribute:"id"},{attribute:"user"},{attribute:"type"},{attribute:"status"},{attribute:"start_datetime"},{attribute:"end_datetime"},{attribute:"message"},{attribute:"created_datetime"},{attribute:"request"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_license:{hash_attribute:"license_key",name:"hdb_license",schema:"system",attributes:[{attribute:"license_key"},{attribute:"company"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_info:{hash_attribute:"info_id",name:"hdb_info",schema:"system",attributes:[{attribute:"info_id"},{attribute:"data_version_num"},{attribute:"hdb_version_num"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_nodes:{hash_attribute:"name",name:"hdb_nodes",schema:"system",attributes:[{attribute:"name"},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_analytics:{hash_attribute:"id",name:"hdb_analytics",schema:"system",attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]}}});var Ds=m((tde,Pb)=>{"use strict";var Mb=F(),Ub=R(),Jo=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,fn=require("joi"),Xn={schema_format:{pattern:Jo,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},dY=fn.alternatives(fn.string().min(1).max(Xn.schema_length.maximum).pattern(Jo).messages({"string.pattern.base":"{:#label} "+Xn.schema_format.message}),fn.number()).required(),EY=fn.alternatives(fn.string().min(1).max(Xn.schema_length.maximum).pattern(Jo).messages({"string.pattern.base":"{:#label} "+Xn.schema_format.message}),fn.number()),fY=fn.alternatives(fn.string().min(1).max(Xn.schema_length.maximum).pattern(Jo).messages({"string.pattern.base":"{:#label} "+Xn.schema_format.message}),fn.number()).required();function hY(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>Xn.schema_length.maximum?`'${e}' maximum of 250 characters`:Jo.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(hY,"checkValidTable");function mY(e,t){return Mb.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(mY,"validateSchemaExists");function pY(e,t){let r=t.state.ancestors[0].schema;return Mb.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(pY,"validateTableExists");function SY(e,t){return e.toLowerCase()===Ub.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${Ub.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(SY,"validateSchemaName");Pb.exports={common_validators:Xn,schema_regex:Jo,hdb_schema_table:dY,validateSchemaExists:mY,validateTableExists:pY,validateSchemaName:SY,checkValidTable:hY,hdb_database:EY,hdb_table:fY}});var He=m((sde,vb)=>{"use strict";var Jt=require("validate.js");Jt.validators.type=function(e,t,r,s){return e===null||typeof e>"u"||Jt.validators.type.checks[t](e)?null:` must be a '${t}' value`};Jt.validators.type.checks={Object:function(e){return Jt.isObject(e)&&!Jt.isArray(e)},Array:Jt.isArray,Integer:Jt.isInteger,Number:Jt.isNumber,String:Jt.isString,Date:Jt.isDate,Boolean:function(e){return typeof e=="boolean"}};Jt.validators.hasValidFileExt=function(e,t){return Jt.isString(e)?e===""?"can't be blank":t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`:null};vb.exports={validateObject:TY,validateObjectAsync:gY,validateBySchema:RY};function TY(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=Jt(e,t,{format:"flat"});return r?new Error(r):null}a(TY,"validateObject");async function gY(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await Jt.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}a(gY,"validateObjectAsync");function RY(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(RY,"validateBySchema")});var M_=m((ide,Bb)=>{var{common_validators:Us}=Ds(),xc=He(),Gc="is required",Ze={database:{presence:!1,format:Us.schema_format,length:Us.schema_length},schema:{presence:!1,format:Us.schema_format,length:Us.schema_length},table:{presence:!0,format:Us.schema_format,length:Us.schema_length},attribute:{presence:!0,format:Us.schema_format,length:Us.schema_length},hash_attribute:{presence:!0,format:Us.schema_format,length:Us.schema_length}};function kc(e){for(let t in e)e[t]=e[t]===null||e[t]===void 0||typeof e[t]=="object"?e[t]:e[t].toString();return e}a(kc,"makeAttributesStrings");function AY(e){return e=kc(e),Ze.table.presence=!1,Ze.attribute.presence=!1,Ze.hash_attribute.presence=!1,xc.validateObject(e,Ze)}a(AY,"schema_object");function OY(e){return e=kc(e),Ze.table.presence={message:Gc},Ze.attribute.presence=!1,Ze.hash_attribute.presence=!1,xc.validateObject(e,Ze)}a(OY,"table_object");function NY(e){return e=kc(e),Ze.table.presence={message:Gc},Ze.attribute.presence=!1,xc.validateObject(e,Ze)}a(NY,"create_table_object");function bY(e){return e=kc(e),Ze.table.presence={message:Gc},Ze.attribute.presence={message:Gc},Ze.hash_attribute.presence=!1,xc.validateObject(e,Ze)}a(bY,"attribute_object");function yY(e){return e=kc(e),Ze.table.presence={message:Gc},Ze.attribute.presence=!1,Ze.hash_attribute.presence=!1,xc.validateObject(e,Ze)}a(yY,"describe_table");function IY(e){if(e){if(!Array.isArray(e))throw new Error("residence must be a string array");if(e.length===0)throw new Error("residence cannot be an empty array");for(let t=0;t<e.length;t++)if(typeof e[t]!="string")throw new Error(`residence must be a string array, item '${e[t]}' is not a string`)}}a(IY,"validateTableResidence");Bb.exports={schema_object:AY,create_table_object:NY,table_object:OY,attribute_object:bY,describe_table:yY,validateTableResidence:IY}});var qb=m((ade,Hb)=>{"use strict";var wY=require("uuid"),Gm=class{static{a(this,"CreateAttributeObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||wY.v4(),this.schema_table=`${this.schema}.${this.table}`}};Hb.exports=Gm});var P_=m((ude,Fb)=>{"use strict";var CY=qb(),xm=class extends CY{static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,s,n,i=!0,o=!1){super(t,r,s,n),this.dup_sort=i,this.is_hash_attribute=o}};Fb.exports=xm});var xb=m((_de,Gb)=>{"use strict";Gb.exports=DY;var LY="inserted";function DY(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===LY?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(DY,"returnObject")});var v_=m((Ede,Kb)=>{"use strict";var UY=R(),km=we(),MY=Wi(),{getSystemSchemaPath:PY,getSchemaPath:vY}=De(),BY=En(),HY=M_(),qY=P_(),FY=xb(),{handleHDBError:kb,hdb_errors:Vb}=z(),$b=F(),{HTTP_STATUS_CODES:GY}=Vb,$m=BY.hdb_attribute,Yb=[];for(let e=0;e<$m.attributes.length;e++)Yb.push($m.attributes[e].attribute);var xY="inserted";Kb.exports=kY;async function kY(e){let t=HY.attribute_object(e);if(t)throw kb(new Error,t.message,Vb.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&$b.checkGlobalSchemaTable(e.schema,e.table);if(r)throw kb(new Error,r,GY.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=$b.isEmpty(e.dup_sort)||e.dup_sort=="true";let s=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(s=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(s)&&s.length>0){for(let i of s)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let n=new qY(e.schema,e.table,e.attribute,e.id);try{let i=await km.openEnvironment(vY(e.schema,e.table),e.table);if(i.dbis[e.attribute]!==void 0)throw new Error(`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`);km.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await km.openEnvironment(PY(),UY.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await MY.insertRecords(o,$m.hash_attribute,Yb,[n]);return FY(xY,c,{records:[n]},u)}catch(i){throw i}}a(kY,"lmdbCreateAttribute")});var Ym=m((hde,Qb)=>{var{hdb_table:$Y,hdb_database:Wb}=Ds(),VY=He(),Vm=require("joi"),YY={undefined:"undefined",null:"null"},KY=a((e,t)=>{let r=Object.keys(e),s=r.length,n;for(let i=0;i<s;i++){let o=r[i];(!o||o.length===0||YY[o]!==void 0)&&(n===void 0?n=`Invalid attribute name: '${o}'`:n+=`. Invalid attribute name: '${o}'`)}return n?t.message(n):e},"custom_records_val"),WY=Vm.object({database:Wb,schema:Wb,table:$Y,records:Vm.array().items(Vm.object().custom(KY)).required()});Qb.exports=function(e){return VY.validateBySchema(e,WY)}});var $c=m((Sde,Jb)=>{"use strict";var hn=F(),zb=C(),pde=Ym(),{getDatabases:QY}=(_e(),re(be)),{ClientError:Qi}=z();Jb.exports=zY;function zY(e){if(hn.isEmpty(e))throw new Qi("invalid update parameters defined.");if(hn.isEmptyOrZeroLength(e.schema))throw new Qi("invalid schema specified.");if(hn.isEmptyOrZeroLength(e.table))throw new Qi("invalid table specified.");if(!Array.isArray(e.records))throw new Qi("records must be an array");let t=QY()[e.schema]?.[e.table];if(hn.isEmpty(t))throw new Qi(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,s=new Set,n={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&hn.isEmptyOrZeroLength(o[r]))throw zb.error("a valid hash attribute must be provided with update record:",o),new Qi("a valid hash attribute must be provided with update record, check log for more info");if(!hn.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw zb.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Qi(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!hn.isEmpty(o[r])&&o[r]!==""&&s.has(hn.autoCast(o[r]))&&(o.skip=!0),s.add(hn.autoCast(o[r]));for(let c in o)n[c]=1}),n[r]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(n)}}a(zY,"insertUpdateValidate")});var Vc=m((gde,jb)=>{"use strict";var JY=R().OPERATIONS_ENUM,Km=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i=void 0){this.operation=JY.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};jb.exports=Km});var Qc=m((Ode,Xb)=>{"use strict";var Ade=Vc(),B_=R(),Qm=F(),Wm=C(),jY=require("uuid"),{handleHDBError:Yc,hdb_errors:XY}=z(),{HDB_ERROR_MSGS:Kc,HTTP_STATUS_CODES:Wc}=XY;Xb.exports=ZY;function ZY(e,t,r){for(let n=0;n<t.length;n++)eK(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];tK(i,r,e.operation)}}a(ZY,"processRows");function eK(e){if(Buffer.byteLength(String(e))>B_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Yc(new Error,Kc.ATTR_NAME_LENGTH_ERR(e),Wc.BAD_REQUEST,void 0,void 0,!0);if(Qm.isEmptyOrZeroLength(e)||Qm.isEmpty(e.trim()))throw Yc(new Error,Kc.ATTR_NAME_NULLISH_ERR,Wc.BAD_REQUEST,void 0,void 0,!0)}a(eK,"validateAttribute");function tK(e,t,r){if(!e.hasOwnProperty(t)||Qm.isEmptyOrZeroLength(e[t])){if(r===B_.OPERATIONS_ENUM.INSERT||r===B_.OPERATIONS_ENUM.UPSERT){e[t]=jY.v4();return}throw Wm.error("Update transaction aborted due to record with no hash value:",e),Yc(new Error,Kc.RECORD_MISSING_HASH_ERR,Wc.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>B_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Wm.error(e),Yc(new Error,Kc.HASH_VAL_LENGTH_ERR,Wc.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw Wm.error(e),Yc(new Error,Kc.INVALID_FORWARD_SLASH_IN_HASH_ERR,Wc.BAD_REQUEST,void 0,void 0,!0)}a(tK,"validateHash")});var ey=m((bde,Zb)=>{"use strict";var zm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};Zb.exports=zm});var sy=m((Ide,ry)=>{"use strict";var Jm=we(),rK=C(),ty=gr().LMDB_ERRORS_ENUM;ry.exports=sK;async function sK(e){try{if(global.lmdb_map!==void 0&&e.operation!==void 0){let t=Object.keys(global.lmdb_map),r;switch(e.operation){case"drop_schema":for(let i=0;i<t.length;i++){let o=t[i];if(o.startsWith(`${e.schema}.`)||o.startsWith(`txn.${e.schema}.`))try{await Jm.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==ty.ENV_REQUIRED)throw c}}break;case"drop_table":let s=`${e.schema}.${e.table}`,n=`txn.${s}`;try{await Jm.closeEnvironment(global.lmdb_map[s]),await Jm.closeEnvironment(global.lmdb_map[n])}catch(i){if(i.message!==ty.ENV_REQUIRED)throw i}break;case"drop_attribute":r=global.lmdb_map[`${e.schema}.${e.table}`],r!==void 0&&typeof r.dbis=="object"&&r.dbis[`${e.attribute}`]!==void 0&&delete r.dbis[`${e.attribute}`];break;default:break}}}catch(t){rK.error(t)}}a(sK,"cleanLMDBMap")});var mn=m((Cde,ay)=>{"use strict";var zc=require("crypto"),nK=Y(),{CONFIG_PARAMS:iK}=R(),iy="aes-256-cbc",oK=32,aK=16,jm=64,oy=32,cK=jm+oy,ny=new Map;ay.exports={encrypt:uK,decrypt:lK,createNatsTableStreamName:_K};function uK(e){let t=zc.randomBytes(oK),r=zc.randomBytes(aK),s=zc.createCipheriv(iy,Buffer.from(t),r),n=s.update(e);n=Buffer.concat([n,s.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=n.toString("hex");return i+o+c}a(uK,"encrypt");function lK(e){let t=e.substr(0,jm),r=e.substr(jm,oy),s=e.substr(cK,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),o=zc.createDecipheriv(iy,Buffer.from(t,"hex"),n),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(lK,"decrypt");function _K(e,t){let r=nK.get(iK.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,s=ny.get(r);return s||(s=zc.createHash("md5").update(r).digest("hex"),ny.set(r,s)),s}a(_K,"createNatsTableStreamName")});var Zn=m((Ude,uy)=>{"use strict";var Dde=jt(),H_=C(),cy=M_(),dK=mn(),q_=F(),{handleHDBError:F_,hdb_errors:EK}=z(),{HDB_ERROR_MSGS:G_,HTTP_STATUS_CODES:Xm}=EK,fK=Y();fK.initSync();var{getDatabases:Zm}=(_e(),re(be));uy.exports={describeAll:hK,describeTable:x_,describeSchema:mK};async function hK(e){try{let t=q_.isEmptyOrZeroLength(e),r,s;t||(r=e.hdb_user.role.permission,s=r.super_user||r.cluster_user);let n=Zm(),i={},o={},c=[];for(let l in n){i[l]=!0,!t&&!s&&(o[l]=e.hdb_user.role.permission[l].describe);let _=n[l];for(let d in _)try{let E;if(t||s)E=await x_({schema:l,table:d});else if(r&&r[l].describe&&r[l].tables[d].describe){let f=r[l].tables[d].attribute_permissions;E=await x_({schema:l,table:d},f)}E&&c.push(E)}catch(E){H_.error(E)}}let u={};for(let l in c)t||s?(u[c[l].schema]==null&&(u[c[l].schema]={}),u[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(u[c[l].schema]==null&&(u[c[l].schema]={}),u[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||s?u[l]={}:o[l]&&(u[l]={});return u}catch(t){return H_.error("Got an error in describeAll"),H_.error(t),F_(new Error,G_.DESCRIBE_ALL_ERR)}}a(hK,"describeAll");async function x_(e,t){q_.transformReq(e);let{schema:r,table:s}=e;r=r?.toString(),s=s?.toString();let n=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(n=e.hdb_user.role.permission[r].tables[s].attribute_permissions);let i=cy.describe_table(e);if(i)throw i;let c=Zm()[r];if(!c)throw F_(new Error,G_.SCHEMA_NOT_FOUND(e.schema),Xm.NOT_FOUND);let u=c[s];if(!u)throw F_(new Error,G_.TABLE_NOT_FOUND(e.schema,e.table),Xm.NOT_FOUND);let l=[];if(n){let d={};n.forEach(E=>{E.describe&&(d[E.attribute_name]=!0)}),u.attributes.forEach(E=>{d[E.name]&&l.push(E)})}else l=u.attributes;let _={schema:r,name:u.tableName,attributes:l,hash_attribute:u.attributes.find(d=>d.isPrimaryKey||d.is_hash_attribute)?.name};_.clustering_stream_name=dK.createNatsTableStreamName(_.schema,_.name);try{_.record_count=u.getRecordCount();let d=u.auditStore;if(d)for(let E of d.getKeys({reverse:!0,limit:1}))_.last_updated_record=E[0];if(!_.last_updated_record&&u.indices.__updatedtime__)for(let E of u.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))_.last_updated_record=E}catch(d){H_.warn(`unable to stat table dbi due to ${d}`)}return _}a(x_,"descTable");async function mK(e){q_.transformReq(e);let t=cy.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let s=e.schema.toString(),i=Zm()[s];if(!i)throw F_(new Error,G_.SCHEMA_NOT_FOUND(e.schema),Xm.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),q_.isEmpty(u)||u.describe){let l=await x_({schema:e.schema,table:c},u?u.attribute_permissions:null);l&&(o[l.name]=l)}}return o}a(mK,"describeSchema")});var $r=m((Bde,fy)=>{var pK=En(),{callbackify:_y,promisify:SK}=require("util"),{getDatabases:dy}=(_e(),re(be));fy.exports={setSchemaDataToGlobal:ly,getTableSchema:TK,getSystemSchema:gK,setSchemaDataToGlobalAsync:SK(ly)};var Ey=Zn(),Pde=_y(Ey.describeAll),vde=_y(Ey.describeTable);function ly(e){global.hdb_schema=dy(),e&&e()}a(ly,"setSchemaDataToGlobal");function TK(e,t,r){let s=dy()[e];if(!s)return r(`schema ${e} does not exist`);let n=s[t];return n?r(null,{schema:e,name:t,hash_attribute:n.primaryKey}):r(`table ${e}.${t} does not exist`)}a(TK,"getTableSchema");function gK(){return pK}a(gK,"getSystemSchema")});var Xt=m((qde,Sy)=>{"use strict";var $_=Ym(),yt=F(),RK=require("util"),V_=Vr(),AK=$r(),hy=C(),{handleHDBError:zi,hdb_errors:OK}=z(),{HTTP_STATUS_CODES:Ji}=OK,NK=RK.promisify(AK.getTableSchema),bK="updated",my="inserted",py="upserted";Sy.exports={insert:IK,update:wK,upsert:CK,validation:yK,flush:LK};async function yK(e){if(yt.isEmpty(e))throw new Error("invalid update parameters defined.");if(yt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(yt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await NK(e.schema,e.table),r=$_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let s=t.hash_attribute,n=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&yt.isEmptyOrZeroLength(c[s]))throw hy.error("a valid hash attribute must be provided with update record:",c),new Error("a valid hash attribute must be provided with update record");if(!yt.isEmptyOrZeroLength(c[s])&&(c[s]==="null"||c[s]==="undefined"))throw hy.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[s]}" is not a valid hash attribute value`);!yt.isEmpty(c[s])&&c[s]!==""&&n.has(yt.autoCast(c[s]))&&(c.skip=!0),n.add(yt.autoCast(c[s]));for(let u in c)i[u]=1}),i[s]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(i)}}a(yK,"validation");async function IK(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=$_(e);if(t)throw zi(new Error,t.message,Ji.BAD_REQUEST);yt.transformReq(e);let r=yt.checkSchemaTableExist(e.schema,e.table);if(r)throw zi(new Error,r,Ji.BAD_REQUEST);let s=await V_.createRecords(e);return k_(my,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}a(IK,"insertData");async function wK(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=$_(e);if(t)throw zi(new Error,t.message,Ji.BAD_REQUEST);yt.transformReq(e);let r=yt.checkSchemaTableExist(e.schema,e.table);if(r)throw zi(new Error,r,Ji.BAD_REQUEST);let s=await V_.updateRecords(e);return yt.isEmpty(s.existing_rows)?k_(bK,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time):k_(s.update_action,[],e,s.hashes,void 0,s.txn_time)}a(wK,"updateData");async function CK(e){if(e.operation!=="upsert")throw zi(new Error,"invalid operation, must be upsert",Ji.INTERNAL_SERVER_ERROR);let t=$_(e);if(t)throw zi(new Error,t.message,Ji.BAD_REQUEST);yt.transformReq(e);let r=yt.checkSchemaTableExist(e.schema,e.table);if(r)throw zi(new Error,r,Ji.BAD_REQUEST);let s=await V_.upsertRecords(e);return k_(py,s.written_hashes,e,[],s.new_attributes,s.txn_time)}a(CK,"upsertData");function k_(e,t,r,s,n,i){let o={message:`${e} ${t.length} of ${t.length+s.length} records`,new_attributes:n,txn_time:i};return e===my?(o.inserted_hashes=t,o.skipped_hashes=s,o):e===py?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=s,o)}a(k_,"returnObject");function LK(e){return yt.transformReq(e),V_.flush(e.schema,e.table)}a(LK,"flush")});var tp=m((Gde,Ry)=>{var DK=He(),ep=require("joi"),{hdb_table:UK,hdb_database:Ty}=Ds(),gy={schema:Ty,database:Ty,table:UK},MK={date:ep.date().iso().required()},PK={timestamp:ep.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};Ry.exports=function(e,t){let r=t==="timestamp"?{...gy,...PK}:{...gy,...MK},s=ep.object(r);return DK.validateBySchema(e,s)}});var Ny=m((xde,Oy)=>{var vK=He(),rp=require("joi"),{hdb_table:BK,hdb_database:Ay}=Ds(),HK=rp.object({schema:Ay,database:Ay,table:BK,hash_values:rp.array().required(),ids:rp.array()});Oy.exports=function(e){return vK.validateBySchema(e,HK)}});var op=m((kde,by)=>{"use strict";var sp=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i){this.operation=t,this.schema=r,this.table=s,this.hash_attribute=n,this.records=i}},np=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,s,n,i,o){this.schema=t,this.table=r,this.search_attribute=s,this.hash_attribute=n,this.get_attributes=i,this.search_value=o}},ip=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};by.exports={InsertObject:sp,NoSQLSeachObject:np,DeleteResponseObject:ip}});var Zi=m((Vde,Ly)=>{"use strict";var Iy=tp(),qK=Ny(),ji=F(),yy=require("moment"),wy=C(),{promisify:FK,callbackify:GK}=require("util"),Xi=R(),xK=$r(),ap=FK(xK.getTableSchema),cp=Vr(),{DeleteResponseObject:kK}=op(),{handleHDBError:ei,hdb_errors:$K}=z(),{HDB_ERROR_MSGS:Y_,HTTP_STATUS_CODES:ti}=$K,VK="records successfully deleted",YK=GK(Cy);Ly.exports={delete:YK,deleteRecord:Cy,deleteFilesBefore:KK,deleteAuditLogsBefore:WK};async function KK(e){let t=Iy(e,"date");if(t)throw ei(t,t.message,ti.BAD_REQUEST,void 0,void 0,!0);if(ji.transformReq(e),!yy(e.date,yy.ISO_8601).isValid())throw ei(new Error,Y_.INVALID_DATE,ti.BAD_REQUEST,Xi.LOG_LEVELS.ERROR,Y_.INVALID_DATE,!0);let s=ji.checkSchemaTableExist(e.schema,e.table);if(s)throw ei(new Error,s,ti.NOT_FOUND,Xi.LOG_LEVELS.ERROR,s,!0);let n=await cp.deleteRecordsBefore(e);if(await ap(e.schema,e.table),wy.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}a(KK,"deleteFilesBefore");async function WK(e){let t=Iy(e,"timestamp");if(t)throw ei(t,t.message,ti.BAD_REQUEST,void 0,void 0,!0);if(ji.transformReq(e),isNaN(e.timestamp))throw ei(new Error,Y_.INVALID_VALUE("Timestamp"),ti.BAD_REQUEST,Xi.LOG_LEVELS.ERROR,Y_.INVALID_VALUE("Timestamp"),!0);let r=ji.checkSchemaTableExist(e.schema,e.table);if(r)throw ei(new Error,r,ti.NOT_FOUND,Xi.LOG_LEVELS.ERROR,r,!0);let s=await cp.deleteAuditLogsBefore(e);return await ap(e.schema,e.table),wy.info(`Finished deleting audit logs before ${e.timestamp}`),s}a(WK,"deleteAuditLogsBefore");async function Cy(e){e.ids&&(e.hash_values=e.ids);let t=qK(e);if(t)throw ei(t,t.message,ti.BAD_REQUEST,void 0,void 0,!0);ji.transformReq(e);let r=ji.checkSchemaTableExist(e.schema,e.table);if(r)throw ei(new Error,r,ti.NOT_FOUND,Xi.LOG_LEVELS.ERROR,r,!0);try{await ap(e.schema,e.table);let s=await cp.deleteRecords(e);return ji.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${VK}`),s}catch(s){if(s.message===Xi.SEARCH_NOT_FOUND_MESSAGE){let n=new kK;return n.message=Xi.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}a(Cy,"deleteRecord")});var K_=m((Kde,My)=>{var QK=require("crypto"),Dy=9;function zK(e){let t=jK(Dy),r=Uy(e+t);return t+r}a(zK,"createHash");function JK(e,t){let r=e.substr(0,Dy),s=r+Uy(t+r);return e===s}a(JK,"validateHash");function jK(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,s="";for(let n=0;n<e;n++){let i=Math.floor(Math.random()*r);s+=t[i]}return s}a(jK,"generateSalt");function Uy(e){return QK.createHash("md5").update(e).digest("hex")}a(Uy,"md5");My.exports={hash:zK,validate:JK}});var vy=m((Qde,Py)=>{var up=He(),qt={username:{presence:!0,format:"[\\w\\-\\_]+",exclusion:{within:["system"],message:"You cannot create tables within the system schema"}},password:{presence:!0},role:{presence:!0,format:"[\\w\\-\\_]+"},active:{presence:!0,inclusion:{within:[!0,!1],message:"must be a boolean"}}};function XK(e){return qt.password.presence=!0,qt.username.presence=!0,qt.role.presence=!0,qt.active.presence=!0,up.validateObject(e,qt)}a(XK,"addUserValidation");function ZK(e){return qt.password.presence=!1,qt.username.presence=!0,qt.role.presence=!1,qt.active.presence=!1,up.validateObject(e,qt)}a(ZK,"alterUserValidation");function e1(e){return qt.password.presence=!1,qt.username.presence=!0,qt.role.presence=!1,qt.active.presence=!1,up.validateObject(e,qt)}a(e1,"dropUserValidation");Py.exports={addUserValidation:XK,alterUserValidation:ZK,dropUserValidation:e1}});var Me=m((jde,Hy)=>{"use strict";var{platform:Jde}=require("os"),t1="nats-server.zip",lp="nats-server",r1=process.platform==="win32"?`${lp}.exe`:lp,_p="HDB",s1=/^[^\s.,*>]+$/,By="__request__",n1=a(e=>`${e}.${By}`,"REQUEST_SUBJECT"),i1={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin"},o1={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},a1={HUB:"hub.pid",LEAF:"leaf.pid"},c1={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},u1={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:_p,deliver_subject:"__HDB__.WORKQUEUE"},l1={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:_p,deliver_subject:"HDB.SCHEMAQUEUE"},_1={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:_p,deliver_subject:"HDB.USERQUEUE"},d1={SUCCESS:"success",ERROR:"error"},E1={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},f1={TXN:"txn",MSGID:"msgid"},jo={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},h1={[jo.ERR]:1,[jo.WRN]:2,[jo.INF]:3,[jo.DBG]:4,[jo.TRC]:5},m1={debug:"-D",trace:"-DVV"};Hy.exports={NATS_SERVER_ZIP:t1,NATS_SERVER_NAME:lp,NATS_BINARY_NAME:r1,PID_FILES:a1,NATS_CONFIG_FILES:o1,SERVER_SUFFIX:c1,WORK_QUEUE_CONSUMER_NAMES:u1,SCHEMA_QUEUE_CONSUMER_NAMES:l1,USER_QUEUE_CONSUMER_NAMES:_1,NATS_TERM_CONSTRAINTS_RX:s1,REQUEST_SUFFIX:By,UPDATE_REMOTE_RESPONSE_STATUSES:d1,CLUSTER_STATUS_STATUSES:E1,REQUEST_SUBJECT:n1,SUBJECT_PREFIXES:f1,MSG_HEADERS:i1,LOG_LEVELS:jo,LOG_LEVEL_FLAGS:m1,LOG_LEVEL_HIERARCHY:h1}});var dp=m((Zde,qy)=>{"use strict";var p1={key:"-----BEGIN RSA PRIVATE KEY-----\rMIIEowIBAAKCAQEArBFJQRfFiJku/KwhV1Ssp7cX61vvuKmd4Rp6A9jB2QLgx8nj\r/+Xhp2hPRkISnOA8BuAxr4dMD9syGJwX4kNy9mbZ5Q0fWZCiEGBpVcU1J+k+N5K4\rSuZ2SqgxeN2IN2RLzt3GyQY4imcdHgNv7aHoXUrEwBx0MeYEw3IIDXtrYKCR2D8I\rvWBfwMUgWa24G8lpWILWA5hd9srRz9NxlAiHSjhbgT7B0xruEpHRCHSyKjvaIJVt\rWBR+amejYsAKVrD/hgrqjsA1123Y6++YqvU6vwg64xhS2kz5r3dkNKhvwbWgpZdI\rIaRvsiB77f4kLGo0vi8RFgJ1ZRjGg3RRK2w1LQIDAQABAoIBAQCEOmh78EOpnGZC\rYBjjHrvrysVD5gvLcfVUtl8Ls7gMB60re1eOIF+PoZZCHKZnDd6zPfiQtj1adg0C\rYnnsM/8VoaZS4gm0b3RLd3ubIQifWhuo40RissY2yxfxlPSH9LhZCY8ojnJG0cTL\resK579E8WCfopjUY33XLqEbN7Ylv39J+DSqInjqV3efJZUa+HqUJ98VxxzodcKMD\rP3bwUU4gHoSSp4pAsOFH5sQhaIWH1IcNjrAwpee2cJQuh4G157RRIuuUpagtaEG/\rXJIiAyBguJyu3JQFnIBQF01N5+omJgXYJ1L0m54543/iIRThmF3zDCDgCyUzmOk+\rH6As9fv1AoGBANOpOtOZLSAScjGsgJamT3ceJ2wCa86g2j8Oxu8lJUmUp5s3tA0v\rBFW5O3S4KR1EXwkLMBUMrfFM8YvzHWxsXBI6XV8azGLvyqPHxr65OhmpGYkGZMXu\rn9okgjkqlewnY2I073gvyK7ppX51UL5y9fF1vlsk+UlW+Rgx/vMHbdcjAoGBANAc\rxRUsxs4QJpbS4zD3JOkHjr24a97TrS3kCybAHUMpR2NrEHPZw9zex0/aphOJUHfL\rIMkOZdpfDqMfxWy4FAEmqBEMkO2SB+h0Wp4P+qp81ax4vGFiB0cD3wtixr11U1tt\rlZ/ZTdv4VDpDFNK1KaplhTDeyuCjeYfS3/GJia9vAoGAcOsAgjBevZR5rXx84WH6\rVO8WUu37u7FenXNxt9VWTinrPMh72uixZFY8nOk+rely1e1NCn3IMko9Ns9NbDFm\r8SaH95vhXArXTYbfxZIlp9jp0YtCqcHDL+p4Oq04bFMbFyJseu7rHj1x18QYfnHw\rOY/6LL/N6k1m+Hx7qgXVmIcCgYB/w0nTCBw84XlvWqSTqQaF8VfWbWP79mP5KmkW\rLxdH5g2noVEGbohqDnK6OXd/wusdwByukiJBf94Skyy25AOT+VFwthA7aU1ljhkb\rtJ+lDuJ28eBkwLPLCzthWBC+u0qjdJFJAzVjd/7tjcU43nNn4s90AzL12iaAFhvZ\rwyA+DQKBgGc/4cdyGJ3YkcA8150gQBawgJZ7q8V1JND87ggWA8wnK3cHn7rMZQl2\r3emDp9HEFXFex5dbGDDqZFAoesZCDxjknIn9oNfW4PvaWS8q7b6ZKLZG1p03Pu7/\rtYaD0kPbo0kysfFT/co+NgHbdykvIyboomfGdNLTUjYuy6lpwpvs\r-----END RSA PRIVATE KEY-----\r".replace(/\r/g,String.fromCharCode(13,10)),cert:"-----BEGIN CERTIFICATE-----\rMIIDXDCCAkSgAwIBAgIFNTE4MzQwDQYJKoZIhvcNAQELBQAwXTEXMBUGA1UEAxMO\rSGFycGVyREIsIEluYy4xCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UE\rBxMGRGVudmVyMRcwFQYDVQQKEw5IYXJwZXJEQiwgSW5jLjAeFw0yMjAzMTEyMzAz\rNDlaFw0yNzAzMTAyMzAzNDlaMF0xFzAVBgNVBAMTDkhhcnBlckRCLCBJbmMuMQsw\rCQYDVQQGEwJVUzELMAkGA1UECBMCQ08xDzANBgNVBAcTBkRlbnZlcjEXMBUGA1UE\rChMOSGFycGVyREIsIEluYy4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\rAQCsEUlBF8WImS78rCFXVKyntxfrW++4qZ3hGnoD2MHZAuDHyeP/5eGnaE9GQhKc\r4DwG4DGvh0wP2zIYnBfiQ3L2ZtnlDR9ZkKIQYGlVxTUn6T43krhK5nZKqDF43Yg3\rZEvO3cbJBjiKZx0eA2/toehdSsTAHHQx5gTDcggNe2tgoJHYPwi9YF/AxSBZrbgb\ryWlYgtYDmF32ytHP03GUCIdKOFuBPsHTGu4SkdEIdLIqO9oglW1YFH5qZ6NiwApW\rsP+GCuqOwDXXbdjr75iq9Tq/CDrjGFLaTPmvd2Q0qG/BtaCll0ghpG+yIHvt/iQs\rajS+LxEWAnVlGMaDdFErbDUtAgMBAAGjIzAhMA8GA1UdEwEB/wQFMAMBAf8wDgYD\rVR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4IBAQASR4YW/rPK7PNArHVe9zzM\rb0rKNX/2T9/0nybRhmE/+hdlSgliTAeebmwkUS2APckmekYt/q2ZY2NS65Fo/jjp\rG8TJrtcF4h+ylVqUp0ZXQLFtIsr7r2JZA7hJ6njW6G4DHSZ0gxtECLi4CBlTjzm5\rNmnmIDObvGRTuqmcdAZmXeObbta/He2XIzietukPAYX062pNM+G5XT5UM1eG/Vlp\rN86vjhpyI+ffKy+C60SJqxmKM3ydgN7oLscE7+2wLPN25XqN4W99OwGsp5dTdu/f\r5lPtFayXdJ55e/sNQKmGN+UGLrL05c2MWgjb8U/LFilnupUianceoeSERZmVjzKX\r-----END CERTIFICATE-----\r".replace(/\r/g,String.fromCharCode(13,10))},S1="certificate.pem",T1="privateKey.pem",g1="ca.pem";qy.exports={CERTIFICATE_VALUES:p1,CERTIFICATE_PEM_NAME:S1,PRIVATEKEY_PEM_NAME:T1,CA_PEM_NAME:g1}});var fp=m((tEe,Vy)=>{"use strict";var ky=require("fs-extra"),se=require("joi"),R1=require("os"),{boolean:ge,string:Sn,number:Or,array:Ep}=se.types(),{totalmem:Fy}=require("os"),Xo=require("path"),A1=C(),Q_=F(),eEe=dp(),Gy=R(),O1=He(),xy="log",N1="components",b1="Invalid logging.rotation.maxSize unit. Available units are G, M or K",y1="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",I1="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",w1="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",C1="rootPath config parameter is undefined",L1="clustering.enabled config parameter is undefined",pn=Or.min(0).required(),z_=Ep.items({host:Sn.required(),port:pn}).empty(null),Tn;Vy.exports={configValidator:D1,routesValidator:H1,route_constraints:z_};function D1(e){if(Tn=e.rootPath,Q_.isEmpty(Tn))throw C1;let t=ge.required(),r=se.valid("production","development").required(),s=Or.min(0).max(1e3).empty(null).default(B1),n=Sn.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(W_),i=se.custom(U1).messages({"any.custom":"{:#label} {:#error}"}),o=Sn.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=se.string().empty(null).default(W_),u=se.custom(M1).empty(null).default(W_),l=e.clustering?.enabled;if(Q_.isEmpty(l))throw L1;let _;return l===!0?_=se.object({enabled:t,hubServer:se.object({cluster:se.object({name:se.required().empty(null),network:se.object({port:pn,routes:z_}).required()}).required(),leafNodes:se.object({network:se.object({port:pn}).required()}).required(),network:se.object({port:pn}).required()}).required(),leafServer:se.object({network:se.object({port:pn,routes:z_}).required(),streams:se.object({maxAge:Or.min(120).allow(null).optional(),maxBytes:Or.min(1).allow(null).optional(),maxMsgs:Or.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:se.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:ge.optional(),databaseLevel:ge.optional(),tls:se.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:ge.required(),verify:ge.optional()}),user:Sn.optional().empty(null)}).required():_=se.object({enabled:t,tls:se.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:ge.required()})}).required(),se.object({authentication:se.object({authorizeLocal:ge,cacheTTL:Or.required(),enableSessions:ge,operationTokenTimeout:se.required(),refreshTokenTimeout:se.required()}),analytics:se.object({aggregatePeriod:Or}),clustering:_,customFunctions:se.object({enabled:t,network:se.object({cors:ge.required(),corsAccessList:Ep.required(),headersTimeout:Or.min(1).required(),https:ge.required(),keepAliveTimeout:Or.min(1).required(),port:pn,timeout:Or.min(1).required()}),nodeEnv:r,root:n,tls:se.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),localStudio:se.object({enabled:t}).required(),logging:se.object({auditAuthEvents:se.object({logFailed:ge,logSuccessful:ge}),file:ge.required(),level:se.valid("notify","fatal","error","warn","info","debug","trace"),rotation:se.object({enabled:ge.optional(),compress:ge.optional(),interval:Sn.custom(v1).optional().empty(null),maxSize:Sn.custom(P1).optional().empty(null),path:Sn.optional().empty(null).default(W_)}).required(),root:n,stdStreams:ge.required(),auditLog:ge.required()}).required(),operationsApi:se.object({foreground:ge.required(),network:se.object({cors:ge.required(),corsAccessList:Ep.required(),headersTimeout:Or.min(1).required(),https:ge.required(),keepAliveTimeout:Or.min(1).required(),port:pn,timeout:Or.min(1).required()}).required(),nodeEnv:r,tls:se.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),rootPath:Sn.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:se.object({network:se.object({port:pn,securePort:pn}).required(),webSocket:ge.optional(),requireAuthentication:ge.optional()}),http:se.object({threads:s}).required(),storage:se.object({writeAsync:ge.required(),overlappingSync:ge.optional(),caching:ge.optional(),compression:ge.optional(),noReadAhead:ge.optional(),path:u,prefetchWrites:ge.optional()}).required(),ignoreScripts:ge.optional()}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(D1,"configValidator");function $y(e){return ky.existsSync(e)?null:`Specified path ${e} does not exist.`}a($y,"doesPathExist");function U1(e,t){if(e===null)return;let r=$y(e);return r?t.message(r):e}a(U1,"validatePemFile");function M1(e,t){se.assert(e,Sn.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=$y(e);if(r)return t.message(r)}a(M1,"validatePath");function P1(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(b1);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(I1):e}a(P1,"validateRotationMaxSize");function v1(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(y1);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(w1):e}a(v1,"validateRotationInterval");function B1(e,t){let r=t.state.path.join("."),s=R1.cpus().length,n=s-1;n<=2&&(n=2);let i=process.constrainedMemory?.()||Fy();return i=Math.round(Math.min(i,Fy())/1e6),n=Math.max(Math.min(n,Math.round((i-750)/300)),1),A1.info(`Detected ${s} cores and ${i}MB on this machine, defaulting ${r} to ${n}`),n}a(B1,"setDefaultThreads");function W_(e,t){if(!Q_.isEmpty(t.original))return t.original;let r=t.state.path.join(".");if(Q_.isEmpty(Tn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"customFunctions.root":return Xo.join(Tn,N1);case"logging.root":return Xo.join(Tn,xy);case"clustering.leafServer.streams.path":return Xo.join(Tn,"clustering","leaf");case"storage.path":let s=Xo.join(Tn,Gy.LEGACY_DATABASES_DIR_NAME);return ky.existsSync(s)?s:Xo.join(Tn,Gy.DATABASES_DIR_NAME);case"logging.rotation.path":return Xo.join(Tn,xy);default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(W_,"setDefaultRoot");function H1(e){let t=se.object({routes:z_});return O1.validateBySchema({routes:e},t)}a(H1,"routesValidator")});var et=m((nEe,eI)=>{"use strict";var Yr=R(),At=F(),ht=C(),{configValidator:q1,routesValidator:Yy}=fp(),Zt=require("fs-extra"),F1=require("yaml"),is=require("path"),G1=require("is-number"),Wy=require("properties-reader"),x1=require("lodash"),{handleHDBError:k1}=z(),{HTTP_STATUS_CODES:$1,HDB_ERROR_MSGS:J_}=gr(),sEe=require("minimist"),{server:V1}=(rs(),re(Pc)),{SCHEMAS_PARAM_CONFIG:Jc,CONFIG_PARAMS:ri,CONFIG_PARAM_MAP:gn}=Yr,Y1="Unable to get config value because config is uninitialized",K1="Config successfully initialized",W1="Error backing up config file",Q1="Empty parameter sent to getConfigValue",Qy=is.join(Yr.PACKAGE_ROOT,"config","yaml",Yr.HDB_DEFAULT_CONFIG_FILE),z1="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",Ky={logging_rotation_retain:"logging.rotation.retain",logging_rotation_rotate:"logging.rotation.rotate",logging_rotation_rotateinterval:"logging.rotation.rotateInterval",logging_rotation_rotatemodule:"logging.rotation.rotateModule",logging_rotation_timezone:"logging.rotation.timezone",logging_rotation_workerinterval:"logging.rotation.workerInterval"},j_,It;eI.exports={createConfigFile:J1,getDefaultConfig:j1,getConfigValue:Jy,initConfig:jy,flattenConfig:to,updateConfigValue:Xy,updateConfigObject:Z1,getConfiguration:rW,setConfiguration:sW,readConfigFile:pp,getClusteringRoutes:nW,initOldConfig:Zy,getConfigFromFile:iW,getConfigFilePath:eo,addConfig:oW,deleteConfigFromFile:aW};function J1(e){let t=si(Qy);j_=to(t.toJSON());let r;for(let o in e){let c=gn[o.toLowerCase()];if(c===ri.SCHEMAS){r=e[o];continue}if(c!==void 0){let u=c.split("_"),l=hp(c,e[o]);c==="rootPath"&&l?.endsWith("/")&&(l=l.slice(0,-1));try{t.setIn([...u],l)}catch(_){ht.error(_)}}}r&&zy(t,r),mp(t);let s=t.toJSON();It=to(s);let n=t.getIn(["rootPath"]),i=is.join(n,Yr.HDB_CONFIG_FILE);Zt.createFileSync(i),Zt.writeFileSync(i,String(t)),ht.trace(`Config file written to ${i}`)}a(J1,"createConfigFile");function zy(e,t){let r;try{try{r=JSON.parse(t)}catch(s){if(!At.isObject(t))throw s;r=t}for(let s of r){let n=Object.keys(s)[0];if(s[n].hasOwnProperty(Jc.TABLES))for(let i in s[n][Jc.TABLES])for(let o in s[n][Jc.TABLES][i]){let c=s[n][Jc.TABLES][i][o],u=[ri.SCHEMAS,n,Jc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in s[n]){let o=s[n][i],c=[ri.SCHEMAS,n,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(s){ht.error("Error parsing schemas CLI/env config arguments",s)}}a(zy,"setSchemasConfig");function j1(e){if(j_===void 0){let r=si(Qy);j_=to(r.toJSON())}let t=gn[e.toLowerCase()];if(t!==void 0)return j_[t.toLowerCase()]}a(j1,"getDefaultConfig");function Jy(e){if(e==null){ht.error(Q1);return}if(It===void 0){ht.trace(Y1);return}let t=gn[e.toLowerCase()];if(t!==void 0)return It[t.toLowerCase()]}a(Jy,"getConfigValue");function eo(e=At.getPropsFilePath()){let t=At.getEnvCliRootPath();return t?is.join(t,Yr.HDB_CONFIG_FILE):Wy(e).get(Yr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(eo,"getConfigFilePath");function jy(e=!1){if(It===void 0||e){let t;if(!At.noBootFile()){t=At.getPropsFilePath();try{Zt.accessSync(t,Zt.constants.F_OK|Zt.constants.R_OK)}catch(i){throw ht.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=eo(t),s;if(r.includes("config/settings.js"))try{Zy(r);return}catch(i){if(i.code!==Yr.NODE_ERROR_CODES.ENOENT)throw i}try{s=si(r)}catch(i){if(i.code===Yr.NODE_ERROR_CODES.ENOENT){ht.trace(`HarperDB config file not found at ${r}.
|
|
6
6
|
This can occur during early stages of install where the config file has not yet been created`);return}else throw ht.error(i),new Error(`Error reading HarperDB config file at ${r}`)}X1(s,r),mp(s);let n=s.toJSON();if(V1.config=n,It=to(n),It.logging_rotation_rotate)for(let i in Ky)It[i]&&ht.error(`Config ${Ky[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);ht.trace(K1)}}a(jy,"initConfig");function X1(e,t){let r=e.getIn(["rootPath"]),s=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],is.join(r,"database")),s=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],is.join(r,"clustering","leaf")),s=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],is.join(r,"log")),s=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),s=!0),s&&(ht.trace("Updating config file with missing config params"),Zt.writeFileSync(t,String(e)))}a(X1,"checkForUpdatedConfig");function mp(e){let t=e.toJSON(),r=q1(t);if(r.error)throw J_.CONFIG_VALIDATION(r.error.message);e.setIn(["http","threads"],r.value.http.threads),e.setIn(["customFunctions","root"],r.value.customFunctions.root),e.setIn(["logging","root"],r.value.logging.root),e.setIn(["storage","path"],r.value.storage.path),e.setIn(["logging","rotation","path"],r.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],r.value.clustering.leafServer.streams?.path)}a(mp,"validateConfig");function Z1(e,t){It===void 0&&(It={});let r=gn[e.toLowerCase()];if(r===void 0){ht.trace(`Unable to update config object because config param '${e}' does not exist`);return}It[r.toLowerCase()]=t}a(Z1,"updateConfigObject");function Xy(e,t,r=void 0,s=!1,n=!1,i=!1){It===void 0&&jy();let o=Jy(gn.hdb_root),c=is.join(o,Yr.HDB_CONFIG_FILE),u=si(c),l;if(r===void 0&&e.toLowerCase()===ri.SCHEMAS)l=t;else if(r===void 0){let E;if(i)E=e;else if(E=gn[e.toLowerCase()],E===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let f=E.split("_"),h=hp(E,t);u.setIn([...f],h)}else for(let E in r){let f=gn[E.toLowerCase()];if(f===ri.SCHEMAS){l=r[E];continue}if(f!==void 0){let h=f.split("_"),S=hp(f,r[E]);f==="rootPath"&&S?.endsWith("/")&&(S=S.slice(0,-1));try{u.setIn([...h],S)}catch(T){ht.error(T)}}}l&&zy(u,l),mp(u);let _=u.getIn(["rootPath"]),d=is.join(_,Yr.HDB_CONFIG_FILE);s===!0&&eW(c,_),Zt.writeFileSync(d,String(u)),n&&(It=to(u.toJSON())),ht.trace(`Config parameter: ${e} updated with value: ${t}`)}a(Xy,"updateConfigValue");function eW(e,t){try{let r=is.join(t,"backup",`${Yr.HDB_CONFIG_FILE}.bak`);Zt.copySync(e,r),ht.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){ht.error(W1),ht.error(r)}}a(eW,"backupConfigFile");var tW=["schemas"];function to(e){let t={};for(let r in e)if(e.hasOwnProperty(r))if(typeof e[r]=="object"&&e[r]!==null&&!Array.isArray(e[r])&&!tW.includes(r)){let s=to(e[r]);for(let n in s)s.hasOwnProperty(n)&&(t[r.toLowerCase()+"_"+n]=s[n])}else t[r.toLowerCase()]=e[r];return t}a(to,"flattenConfig");function hp(e,t){if(e===ri.CLUSTERING_NODENAME||e===ri.CLUSTERING_USER){if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(G1(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||At.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 At.autoCast(t)}a(hp,"castConfigValue");function rW(){let e=At.getPropsFilePath(),t=eo(e);return si(t).toJSON()}a(rW,"getConfiguration");async function sW(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return Xy(void 0,void 0,n,!0),z1}catch(i){throw typeof i=="string"||i instanceof String?k1(i,i,$1.BAD_REQUEST,void 0,void 0,!0):i}}a(sW,"setConfiguration");function pp(){let e=At.getPropsFilePath();try{Zt.accessSync(e,Zt.constants.F_OK|Zt.constants.R_OK)}catch(s){if(!At.noBootFile())throw ht.error(s),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=eo(e);return si(t).toJSON()}a(pp,"readConfigFile");function si(e){return F1.parseDocument(Zt.readFileSync(e,"utf8"),{simpleKeys:!0})}a(si,"parseYamlDoc");function nW(){let e=pp(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=At.isEmptyOrZeroLength(t)?[]:t;let r=Yy(t);if(r)throw J_.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=At.isEmptyOrZeroLength(s)?[]:s;let n=Yy(s);if(n)throw J_.CONFIG_VALIDATION(n.message);if(!At.isEmptyOrZeroLength(s)&&!At.isEmptyOrZeroLength(t)){let i=t.filter(o=>s.some(c=>c.host===o.host&&c.port===o.port));if(!At.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw J_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:s}}a(nW,"getClusteringRoutes");function Zy(e){let t=Wy(e);It={};for(let r in gn){let s=t.get(r.toUpperCase());if(At.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=gn[r].toLowerCase();n===ri.LOGGING_ROOT?It[n]=is.dirname(s):It[n]=s}return It}a(Zy,"initOldConfig");function iW(e){let t=pp();return x1.get(t,e.replaceAll("_","."))}a(iW,"getConfigFromFile");async function oW(e,t){let r=si(eo());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await Zt.writeFile(eo(),String(r))}a(oW,"addConfig");function aW(e){let t=eo(At.getPropsFilePath()),r=si(t);r.deleteIn(e);let s=r.getIn(["rootPath"]),n=is.join(s,Yr.HDB_CONFIG_FILE);Zt.writeFileSync(n,String(r))}a(aW,"deleteConfigFromFile")});var rI=m((oEe,tI)=>{"use strict";var X_=R(),Z_=class{static{a(this,"BaseLicense")}constructor(t=0,r=X_.RAM_ALLOCATION_ENUM.DEFAULT,s=X_.LICENSE_VALUES.VERSION_DEFAULT,n){this.exp_date=t,this.ram_allocation=r,this.version=s,this.fingerprint=n}},Sp=class extends Z_{static{a(this,"ExtendedLicense")}constructor(t=0,r=X_.RAM_ALLOCATION_ENUM.DEFAULT,s=X_.LICENSE_VALUES.VERSION_DEFAULT,n,i=!1){super(t,r,s,n),this.enterprise=i}};tI.exports={BaseLicense:Z_,ExtendedLicense:Sp}});var jc=m((cEe,cI)=>{"use strict";var ea=require("fs-extra"),sI=K_(),nI=require("crypto"),cW=require("moment"),uW=require("uuid").v4,Ft=C(),gp=require("path"),lW=F(),ni=R(),_W=rI().ExtendedLicense,Zo="invalid license key format",dW="061183",EW="mofi25",fW="aes-256-cbc",hW=16,mW=32,iI=Y();iI.initSync();var Tp;cI.exports={validateLicense:oI,generateFingerPrint:SW,licenseSearch:aI,getLicense:RW};function Rp(){return gp.join(iI.getHdbBasePath(),ni.LICENSE_KEY_DIR_NAME,ni.LICENSE_FILE_NAME)}a(Rp,"getLicenseDirPath");function pW(){let e=Rp();return gp.join(e,ni.LICENSE_FILE_NAME)}a(pW,"getLicenseFilePath");function Ap(){let e=Rp();return gp.join(e,ni.REG_KEY_FILE_NAME)}a(Ap,"getFingerPrintFilePath");async function SW(){let e=Ap();try{return await ea.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await TW();throw Ft.error(`Error writing fingerprint file to ${e}`),Ft.error(t),new Error("There was an error generating the fingerprint")}}a(SW,"generateFingerPrint");async function TW(){let e=uW(),t=sI.hash(e),r=Ap();try{await ea.mkdirp(Rp()),await ea.writeFile(r,t)}catch(s){if(s.code==="EEXIST")return t;throw Ft.error(`Error writing fingerprint file to ${r}`),Ft.error(s),new Error("There was an error generating the fingerprint")}return t}a(TW,"writeFingerprint");function oI(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:ni.RAM_ALLOCATION_ENUM.DEFAULT,version:ni.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Ft.error("empty license key passed to validate."),r;let s=Ap(),n=!1;try{n=ea.statSync(s)}catch(i){Ft.error(i)}if(n){let i;try{i=ea.readFileSync(s,"utf8")}catch{Ft.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(EW),c=o[1];c=Buffer.concat([Buffer.from(c)],hW);let u=Buffer.concat([Buffer.from(i)],mW),l=nI.createDecipheriv(fW,u,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let _=null;try{_=l.update(o[0],"hex","utf8"),_.trim(),_+=l.final("utf8")}catch{let f=gW(o[0],i);if(f)_=f;else throw r.valid_license=!1,r.valid_machine=!1,console.error(Zo),Ft.error(Zo),new Error(Zo)}let d;if(isNaN(_))try{d=JSON.parse(_),r.version=d.version,r.exp_date=d.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),d.ram_allocation&&(r.ram_allocation=d.ram_allocation)}catch{throw console.error(Zo),Ft.error(Zo),new Error(Zo)}else r.exp_date=_;r.exp_date<cW().valueOf()&&(r.valid_date=!1),sI.validate(o[1],`${dW}${i}${t}`)||(r.valid_license=!1)}else r.valid_license=!1,r.valid_machine=!1;return r.valid_license&&r.valid_machine&&r.valid_date||Ft.error("Invalid licence"),r}a(oI,"validateLicense");function gW(e,t){try{let r=nI.createDecipher("aes192",t),s=r.update(e,"hex","utf8");return s.trim(),s+=r.final("utf8"),s}catch{Ft.warn("Check old license failed")}}a(gW,"checkOldLicense");function aI(){let e=new _W,t=[];try{t=ea.readFileSync(pW(),"utf-8").split(ni.NEW_LINE)}catch(r){r.code==="ENOENT"?Ft.info("no license file found"):Ft.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let s=t[r];try{if(lW.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=oI(n.license_key,n.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(n){Ft.error("There was an error parsing the license string."),Ft.error(n),e.ram_allocation=ni.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return Tp=e,e}a(aI,"licenseSearch");async function RW(){return Tp||await aI(),Tp}a(RW,"getLicense")});var er=m((EEe,NI)=>{"use strict";var EI="username is required",fI="nothing to update, must supply active, role or password to update",hI="password cannot be an empty string",mI="If role is specified, it cannot be empty.",pI="active must be true or false";NI.exports={addUser:LW,alterUser:DW,dropUser:MW,getSuperUser:HW,userInfo:PW,listUsers:td,listUsersExternal:vW,setUsersToGlobal:ra,findAndValidateUser:OI,getClusterUser:qW,USERNAME_REQUIRED:EI,ALTERUSER_NOTHING_TO_UPDATE:fI,EMPTY_PASSWORD:hI,EMPTY_ROLE:mI,ACTIVE_BOOLEAN:pI};var SI=Xt(),AW=Zi(),Np=K_(),TI=vy(),gI=jt(),bp=Rn(),Nr=F(),RI=require("validate.js"),de=C(),{promisify:OW}=require("util"),yp=mn(),uI=R(),lI=Me(),NW=et(),lEe=Y(),_Ee=jc(),bW=En(),{table:dEe}=(_e(),re(be)),{handleHDBError:Ms,hdb_errors:yW}=z(),{HTTP_STATUS_CODES:Ps,AUTHENTICATION_ERROR_MSGS:Op,HDB_ERROR_MSGS:ta}=yW,{UserEventMsg:Ip}=os(),_I=require("lodash"),{_assignPackageExport:IW}=require("../index");IW("getUser",OI);var AI={username:!0,active:!0,role:!0,password:!0},dI=new Map,ed=gI.searchByValue,wW=gI.searchByHash,CW=OW(AW.delete);async function LW(e){let t=RI.cleanAttributes(e,AI),r=TI.addUserValidation(t);if(r)throw Ms(new Error,r.message,Ps.BAD_REQUEST,void 0,void 0,!0);let s={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},n;try{n=await ed(s),n=n&&Array.from(n)}catch(u){throw de.error("There was an error searching for a role in add user"),de.error(u),u}if(!n||n.length<1)throw Ms(new Error,ta.ROLE_NAME_NOT_FOUND(t.role),Ps.NOT_FOUND,void 0,void 0,!0);if(n.length>1)throw Ms(new Error,ta.DUP_ROLES_FOUND(t.role),Ps.CONFLICT,void 0,void 0,!0);n[0].permission.cluster_user===!0&&(t.hash=yp.encrypt(t.password)),t.password=Np.hash(t.password),t.role=n[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await SI.insert(i)}catch(u){throw de.error("There was an error searching for a user."),de.error(u),u}de.debug(o);try{await ra()}catch(u){throw de.error("Got an error setting users to global"),de.error(u),u}if(o.skipped_hashes.length===1)throw Ms(new Error,ta.USER_ALREADY_EXISTS(t.username),Ps.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=n[0],bp.signalUserChange(new Ip(process.pid)),`${c.username} successfully added`}a(LW,"addUser");async function DW(e){let t=RI.cleanAttributes(e,AI);if(Nr.isEmptyOrZeroLength(t.username))throw new Error(EI);if(Nr.isEmptyOrZeroLength(t.password)&&Nr.isEmptyOrZeroLength(t.role)&&Nr.isEmptyOrZeroLength(t.active))throw new Error(fI);if(!Nr.isEmpty(t.password)&&Nr.isEmptyOrZeroLength(t.password.trim()))throw new Error(hI);if(!Nr.isEmpty(t.active)&&!Nr.isBoolean(t.active))throw new Error(pI);let r=UW(t.username);if(!Nr.isEmpty(t.password)&&!Nr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=yp.encrypt(t.password)),t.password=Np.hash(t.password)),t.role==="")throw new Error(mI);if(t.role){let i={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["*"]},o;try{o=Array.from(await ed(i)||[])}catch(c){throw de.error("Got an error searching for a role."),de.error(c),c}if(!o||o.length===0){let c=ta.ALTER_USER_ROLE_NOT_FOUND(t.role);throw de.error(c),Ms(new Error,c,Ps.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=ta.ALTER_USER_DUP_ROLES(t.role);throw de.error(c),Ms(new Error,c,Ps.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let s={operation:"update",schema:"system",table:"hdb_user",records:[t]},n;try{n=await SI.update(s)}catch(i){throw de.error("Error during update."),de.error(i),i}try{await ra()}catch(i){throw de.error("Got an error setting users to global"),de.error(i),i}return bp.signalUserChange(new Ip(process.pid)),n}a(DW,"alterUser");function UW(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(UW,"isClusterUser");async function MW(e){try{let t=TI.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Nr.isEmpty(global.hdb_users.get(e.username)))throw Ms(new Error,ta.USER_NOT_EXIST(e.username),Ps.NOT_FOUND,void 0,void 0,!0);let s;try{s=await CW(r)}catch(n){throw de.error("Got an error deleting a user."),de.error(n),n}de.debug(s);try{await ra()}catch(n){throw de.error("Got an error setting users to global."),de.error(n),n}return bp.signalUserChange(new Ip(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(MW,"dropUser");async function PW(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=e.hdb_user;let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},s;try{s=await wW(r)}catch(n){throw de.error("Got an error searching for a role."),de.error(n),n}t.role=s[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw de.error(r),r}return t}a(PW,"userInfo");async function vW(){let e;try{e=await td()}catch(t){throw de.error("Got an error listing users."),de.error(t),t}try{e.forEach(t=>{delete t.password,delete t.hash,delete t.refresh_token})}catch{throw new Error("there was an error massaging the user data")}return[...e.values()]}a(vW,"listUsersExternal");async function td(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await ed(e)}catch(o){throw de.error("Got an error searching for roles."),de.error(o),o}let r={};for(let o of t)r[o.id]=_I.cloneDeep(o);if(Object.keys(r).length===0)return null;let s={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},n;try{n=await ed(s)}catch(o){throw de.error("Got an error searching for users."),de.error(o),o}let i=new Map;for(let o of n)o=_I.cloneDeep(o),o.role=r[o.role],BW(o.role),i.set(o.username,o);return i}catch(e){throw de.error("got an error listing users"),de.error(e),Nr.errorizeMessage(e)}return null}a(td,"listUsers");function BW(e){try{if(!e){de.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(bW)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){de.error("Got an error trying to set system permissions."),de.error(t)}}a(BW,"appendSystemTablesToRole");async function ra(){try{let e=await td();global.hdb_users=e}catch(e){throw de.error(e),e}}a(ra,"setUsersToGlobal");async function OI(e,t,r=!0){global.hdb_users||await ra();let s=global.hdb_users.get(e);if(!s)throw Ms(new Error,Op.GENERIC_AUTH_FAIL,Ps.UNAUTHORIZED,void 0,void 0,!0);if(s&&!s.active)throw Ms(new Error,Op.USER_INACTIVE,Ps.UNAUTHORIZED,void 0,void 0,!0);let n={active:s.active,username:s.username};if(s.refresh_token&&(n.refresh_token=s.refresh_token),s.role&&(n.role=s.role),r===!0){if(dI.get(t)===s.password)return n;if(Np.validate(s.password,t))dI.set(t,s.password);else throw Ms(new Error,Op.GENERIC_AUTH_FAIL,Ps.UNAUTHORIZED,void 0,void 0,!0)}return n}a(OI,"findAndValidateUser");async function HW(){global.hdb_users||await ra();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(HW,"getSuperUser");async function qW(){let e=await td(),t=NW.getConfigFromFile(uI.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Nr.isEmpty(r)&&r?.role?.role===uI.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=yp.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+lI.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+lI.SERVER_SUFFIX.ADMIN,r}a(qW,"getClusterUser")});var Zc=m((pEe,wI)=>{"use strict";var ro=C(),br=R(),FW=sy(),hEe=$r(),mEe=Zn(),GW=er(),{validateEvent:bI}=os(),Xc=Vr(),xW=require("process"),{resetDatabases:kW}=(_e(),re(be)),$W={[br.ITC_EVENT_TYPES.SCHEMA]:VW,[br.ITC_EVENT_TYPES.USER]:II};async function VW(e){let t=bI(e);if(t){ro.error(t);return}ro.trace("ITC schemaHandler received schema event:",e),await FW(e.message),await YW(e.message)}a(VW,"schemaHandler");async function YW(e){try{Xc.resetReadTxn(br.SYSTEM_SCHEMA_NAME,br.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Xc.resetReadTxn(br.SYSTEM_SCHEMA_NAME,br.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Xc.resetReadTxn(br.SYSTEM_SCHEMA_NAME,br.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=kW();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){ro.error(t)}}a(YW,"syncSchemaMetadata");var yI=[];async function II(e){try{try{Xc.resetReadTxn(br.SYSTEM_SCHEMA_NAME,br.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Xc.resetReadTxn(br.SYSTEM_SCHEMA_NAME,br.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){ro.warn(r)}let t=bI(e);if(t){ro.error(t);return}ro.trace(`ITC userHandler ${br.HDB_ITC_CLIENT_PREFIX}${xW.pid} received user event:`,e),await GW.setUsersToGlobal();for(let r of yI)r()}catch(t){ro.error(t)}}a(II,"userHandler");II.addListener=function(e){yI.push(e)};wI.exports=$W});var os=m((OEe,LI)=>{"use strict";var TEe=C(),wp=F(),KW=R(),{ITC_ERRORS:eu}=gr(),{parentPort:gEe,threadId:WW,isMainThread:QW,workerData:REe}=require("worker_threads"),{onMessageFromWorkers:zW,broadcast:AEe,broadcastWithAcknowledgement:JW}=tt();LI.exports={sendItcEvent:jW,validateEvent:CI,SchemaEventMsg:XW,UserEventMsg:ZW};var rd;zW(async(e,t)=>{rd=rd||Zc(),CI(e),rd[e.type]&&await rd[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function jW(e){return!QW&&e.message&&(e.message.originator=WW),JW(e)}a(jW,"sendItcEvent");function CI(e){if(typeof e!="object")return eu.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||wp.isEmpty(e.type))return eu.MISSING_TYPE;if(!e.hasOwnProperty("message")||wp.isEmpty(e.message))return eu.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||wp.isEmpty(e.message.originator))return eu.MISSING_ORIGIN;if(KW.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return eu.INVALID_EVENT(e.type)}a(CI,"validateEvent");function XW(e,t,r,s=void 0,n=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=s,this.attribute=n}a(XW,"SchemaEventMsg");function ZW(e){this.originator=e}a(ZW,"UserEventMsg")});var Rn=m((yEe,PI)=>{"use strict";var DI=R(),bEe=F(),sd=C(),UI=ey(),sa,{sendItcEvent:MI}=os();function eQ(e){try{sd.trace("signalSchemaChange called with message:",e),sa=sa||Zc();let t=new UI(DI.ITC_EVENT_TYPES.SCHEMA,e);return sa.schema(t),MI(t)}catch(t){sd.error(t)}}a(eQ,"signalSchemaChange");function tQ(e){try{sd.trace("signalUserChange called with message:",e),sa=sa||Zc();let t=new UI(DI.ITC_EVENT_TYPES.USER,e);return sa.user(t),MI(t)}catch(t){sd.error(t)}}a(tQ,"signalUserChange");PI.exports={signalSchemaChange:eQ,signalUserChange:tQ}});var nd=m((wEe,BI)=>{"use strict";var vI=F(),rQ=R(),sQ=C(),nQ=v_(),iQ=P_(),oQ=Rn(),{SchemaEventMsg:aQ}=os(),cQ="already exists in";BI.exports=uQ;async function uQ(e,t,r){if(vI.isEmptyOrZeroLength(r))return r;let s=[];vI.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{s.push(i.attribute)});let n=r.filter(i=>s.indexOf(i)<0);return n.length===0||await Promise.all(n.map(async i=>{await lQ(e,t.schema,t.name,i)})),n}a(uQ,"lmdbCheckForNewAttributes");async function lQ(e,t,r,s){let n=new iQ(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await _Q(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(cQ))sQ.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(lQ,"createNewAttribute");async function _Q(e){let t;return t=await nQ(e),oQ.signalSchemaChange(new aQ(process.pid,rQ.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(_Q,"createAttribute")});var na=m((LEe,HI)=>{"use strict";var Cp=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,s,n,i=void 0){this.operation=t,this.user_name=r,this.timestamp=s,this.hash_values=n,this.origin=i}};HI.exports=Cp});var FI=m((UEe,qI)=>{"use strict";var dQ=na(),EQ=R().OPERATIONS_ENUM,Lp=class extends dQ{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,s,n,i=void 0){super(EQ.INSERT,r,s,n,i),this.records=t}};qI.exports=Lp});var xI=m((PEe,GI)=>{"use strict";var fQ=na(),hQ=R().OPERATIONS_ENUM,Dp=class extends fQ{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(hQ.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};GI.exports=Dp});var $I=m((BEe,kI)=>{"use strict";var mQ=na(),pQ=R().OPERATIONS_ENUM,Up=class extends mQ{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(pQ.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};kI.exports=Up});var YI=m((qEe,VI)=>{"use strict";var SQ=na(),TQ=R().OPERATIONS_ENUM,Mp=class extends SQ{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,s,n,i=void 0){super(TQ.DELETE,s,n,t,i),this.original_records=r}};VI.exports=Mp});var tu=m((xEe,zI)=>{"use strict";var GEe=require("path"),KI=we(),gQ=FI(),RQ=xI(),AQ=$I(),OQ=YI(),ia=Ge(),WI=F(),{CONFIG_PARAMS:NQ}=R(),QI=Y();QI.initSync();var id=R().OPERATIONS_ENUM,{getTransactionAuditStorePath:bQ}=De();zI.exports=yQ;async function yQ(e,t){if(QI.get(NQ.LOGGING_AUDITLOG)===!1)return;let r=bQ(e.schema,e.table),s=await KI.openEnvironment(r,e.table,!0),n=IQ(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){KI.initializeDBIs(s,ia.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,ia.TRANSACTIONS_DBIS);let i=n.timestamp;return await s.dbis[ia.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{s.dbis[ia.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,n),WI.isEmpty(n.user_name)||s.dbis[ia.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(n.user_name,i);for(let o=0;o<n.hash_values.length;o++)s.dbis[ia.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(n.hash_values[o],i)})}}a(yQ,"writeTransaction");function IQ(e,t){let r=WI.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===id.INSERT)return new gQ(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===id.UPDATE)return new RQ(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===id.UPSERT)return new AQ(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===id.DELETE)return new OQ(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(IQ,"createTransactionObject")});var Pp=m((VEe,JI)=>{"use strict";var wQ=$c(),$Ee=Vc(),ru=R(),CQ=Qc(),LQ=Wi().insertRecords,DQ=we(),UQ=C(),MQ=nd(),{getSchemaPath:PQ}=De(),vQ=tu();JI.exports=BQ;async function BQ(e){try{let{schema_table:t,attributes:r}=wQ(e);CQ(e,r,t.hash_attribute),e.schema!==ru.SYSTEM_SCHEMA_NAME&&(r.includes(ru.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(ru.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(ru.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(ru.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await MQ(e.hdb_auth_header,t,r),n=PQ(e.schema,e.table),i=await DQ.openEnvironment(n,e.table),o=await LQ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await vQ(e,o)}catch(c){UQ.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:s,txn_time:o.txn_time}}catch(t){throw t}}a(BQ,"lmdbCreateRecords")});var ZI=m((KEe,XI)=>{"use strict";var jI=R(),HQ=Pp(),qQ=Vc(),FQ=require("fs-extra"),{getSchemaPath:GQ}=De();XI.exports=xQ;async function xQ(e){let t=[{name:e.schema,createddate:Date.now()}],r=new qQ(jI.SYSTEM_SCHEMA_NAME,jI.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await HQ(r),await FQ.mkdirp(GQ(e.schema))}a(xQ,"lmdbCreateSchema")});var tw=m((QEe,ew)=>{"use strict";var vp=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],s=void 0,n=[]){this.deleted=t,this.skipped=r,this.txn_time=s,this.original_records=n}};ew.exports=vp});var iw=m((ZEe,nw)=>{"use strict";var rw=we(),Bp=Ht(),Hp=gr().LMDB_ERRORS_ENUM,kQ=Ge(),sw=C(),JEe=F(),$Q=require("lmdb"),VQ=tw(),YQ=R(),{OVERFLOW_MARKER:jEe,MAX_SEARCH_KEY_LENGTH:XEe}=kQ,KQ=YQ.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function WQ(e,t,r,s){if(Bp.validateEnv(e),t===void 0)throw new Error(Hp.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Hp.IDS_REQUIRED):new Error(Hp.IDS_MUST_BE_ITERABLE);try{let n=rw.listDBIs(e);rw.initializeDBIs(e,t,n);let i=new VQ,o,c=[],u=[];for(let E=0,f=r.length;E<f;E++)try{o=r[E];let h=e.dbis[t].get(o);if(!h||s&&h[KQ]>s){i.skipped.push(o);continue}let S=e.dbis[t].ifVersion(o,$Q.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let T=0;T<n.length;T++){let A=n[T];if(!h.hasOwnProperty(A)||A===t)continue;let g=e.dbis[A],x=h[A];if(x!=null)try{let V=Bp.getIndexedValues(x);if(V)for(let I=0,b=V.length;I<b;I++)g.remove(V[I],o)}catch{sw.warn(`cannot delete from attribute: ${A}, ${x}:${o}`)}}});c.push(S),u.push(o),i.original_records.push(h)}catch(h){sw.warn(h),i.skipped.push(o)}let l=[],_=await Promise.all(c);for(let E=0,f=_.length;E<f;E++)_[E]===!0?i.deleted.push(u[E]):(i.skipped.push(u[E]),l.push(E));let d=0;for(let E=0;E<l.length;E++){let f=l[E];i.original_records.splice(f-d,1),d++}return i.txn_time=Bp.getNextMonotonicTime(),i}catch(n){throw n}}a(WQ,"deleteRecords");nw.exports={deleteRecords:WQ}});var su=m((tfe,aw)=>{"use strict";var oa=F(),QQ=iw(),zQ=we(),{getSchemaPath:JQ}=De(),jQ=tu(),XQ=C();aw.exports=ZQ;async function ZQ(e,t=!0){let s=global.hdb_schema[e.schema][e.table].hash_attribute;if(oa.isEmpty(s))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(oa.isEmptyOrZeroLength(e.hash_values)&&!oa.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][s];oa.isEmpty(u)||e.hash_values.push(u)}}if(oa.isEmptyOrZeroLength(e.hash_values))return ow([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(oa.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[s]:e.hash_values[c]}}let n=JQ(e.schema,e.table),i=await zQ.openEnvironment(n,e.table),o=await QQ.deleteRecords(i,s,e.hash_values,e.__origin?.timestamp);try{t===!0&&await jQ(e,o)}catch(c){XQ.error(`unable to write transaction due to ${c.message}`)}return ow(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(ZQ,"lmdbDeleteRecords");function ow(e,t,r){let s=e.length+t.length,n=s===1?"record":"records";return{message:`${e.length} of ${s} ${n} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(ow,"createDeleteResponse")});var Fp=m((nfe,cw)=>{"use strict";var ez=R(),sfe=Ht();function qp(e,t){let r=Object.create(null);if(t.length===1&&ez.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let s=0;s<t.length;s++){let n=t[s],i=e[n];r[n]=i===void 0?null:i}return r}a(qp,"parseRow");function tz(e,t,r,s){let n=qp(r,e);s.push(n)}a(tz,"searchAll");function rz(e,t,r,s){let n=qp(r,e);s[t]=n}a(rz,"searchAllToMap");function sz(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(sz,"iterateDBI");function so(e,t,r,s,n){let i=Object.create(null);i[n]=e;let o;s===n?o=e:(o=t,s!==void 0&&(i[s]=o)),r[0].push(o),r[1].push(i)}a(so,"pushResults");function nz(e,t,r,s,n,i){t.toString().endsWith(e)&&so(t,r,s,n,i)}a(nz,"endsWith");function iz(e,t,r,s,n,i){t.toString().includes(e)&&so(t,r,s,n,i)}a(iz,"contains");function oz(e,t,r,s,n,i){t>e&&so(t,r,s,n,i)}a(oz,"greaterThanCompare");function az(e,t,r,s,n,i){t>=e&&so(t,r,s,n,i)}a(az,"greaterThanEqualCompare");function cz(e,t,r,s,n,i){t<e&&so(t,r,s,n,i)}a(cz,"lessThanCompare");function uz(e,t,r,s,n,i){t<=e&&so(t,r,s,n,i)}a(uz,"lessThanEqualCompare");cw.exports={parseRow:qp,searchAll:tz,searchAllToMap:rz,iterateDBI:sz,endsWith:nz,contains:iz,greaterThanCompare:oz,greaterThanEqualCompare:az,lessThanCompare:cz,lessThanEqualCompare:uz,pushResults:so}});var aa=m((ufe,hw)=>{"use strict";var ii=we(),ofe=C(),yr=Ht(),od=Ge(),We=gr().LMDB_ERRORS_ENUM,afe=F(),lz=R(),ad=Fp(),{parseRow:_z}=ad,cfe=require("lmdb"),{OVERFLOW_MARKER:uw,MAX_SEARCH_KEY_LENGTH:dz}=od;function lw(e,t,r,s=!1,n=void 0,i=void 0){return no(e,t,r,(o,c)=>c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}))}a(lw,"iterateFullIndex");function nu(e,t,r,s,n,i=!1,o=void 0,c=void 0,u=!1,l=!1){return no(e,t,r,(_,d,E,f)=>{let g={transaction:_,start:i===!0?n:s,end:i===!0?s:n,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!l,exclusiveStart:i===!0?l:u};return f===r?(g.values=!1,d.getRange(g).map(x=>({value:x}))):d.getRange(g)})}a(nu,"iterateRangeBetween");function no(e,t,r,s){let n=e.database||e,i=ii.openDBI(n,r);i[od.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&ii.openDBI(n,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=s(o,i,n,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(no,"setupTransaction");function _w(e,t,r,s){let n;return function(i,o){if(typeof i=="string"&&i.endsWith(uw)){if(!n)if(r)n=ii.openDBI(e,r);else{let u=ii.listDBIs(e);for(let l=0,_=u.length;l<_&&(n=ii.openDBI(e,u[l]),!n[od.DBI_DEFINITION_NAME].is_hash_attribute);l++);}i=n.get(o,{transaction:t,lazy:!0})[s]}return i}}a(_w,"getOverflowCheck");function Ez(e,t,r,s=!1,n=void 0,i=void 0){if(yr.validateEnv(e),t===void 0)throw new Error(We.HASH_ATTRIBUTE_REQUIRED);return no(e,t,t,(o,c,u)=>(cd(r),r=iu(u,r),c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}).map(l=>_z(l.value,r))))}a(Ez,"searchAll");function fz(e,t,r,s=!1,n=void 0,i=void 0){if(yr.validateEnv(e),t===void 0)throw new Error(We.HASH_ATTRIBUTE_REQUIRED);cd(r),r=iu(e.database||e,r);let o=new Map;for(let{key:c,value:u}of lw(e,t,t,s,n,i))o.set(c,ad.parseRow(u,r));return o}a(fz,"searchAllToMap");function hz(e,t,r=!1,s=void 0,n=void 0){if(yr.validateEnv(e),t===void 0)throw new Error(We.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=lw(e,void 0,t,r,s,n),c=o.transaction,u=_w(c.database,c,void 0,t);for(let{key:l,value:_}of o){let d=u(l,_);i[d]===void 0&&(i[d]=[]),i[d].push(_)}return i}a(hz,"iterateDBI");function mz(e,t){if(yr.validateEnv(e),t===void 0)throw new Error(We.HASH_ATTRIBUTE_REQUIRED);return ii.statDBI(e,t).entryCount}a(mz,"countAll");function pz(e,t,r,s,n=!1,i=void 0,o=void 0){return oi(e,r,s),no(e,t,r,(c,u,l,_)=>(s=yr.convertKeyValueToWrite(s),_===r?u.get(s,{transaction:c,lazy:!0})===void 0?[]:[{key:s,value:s}]:u.getValues(s,{transaction:c,reverse:n,limit:i,offset:o}).map(d=>({key:s,value:d}))))}a(pz,"equals");function Sz(e,t,r){return oi(e,t,r),ii.openDBI(e,t).getValuesCount(r)}a(Sz,"count");function Tz(e,t,r,s,n=!1,i=void 0,o=void 0){return oi(e,r,s),no(e,null,r,(c,u)=>{s=yr.convertKeyValueToWrite(s);let l=!0;typeof s=="number"&&(l=!1);let _;if(n===!0){let d;for(let E of u.getKeys({transaction:c,start:s}))if(!E.startsWith(s)){d=E;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),_=u.getRange({transaction:c,start:d,end:void 0,reverse:n,limit:i,offset:o}).map(E=>{let{key:f}=E;if(f!==d){if(f.toString().startsWith(s))return E;if(l===!0)return _.DONE}}),_.filter(E=>E)}else return _=u.getRange({transaction:c,start:s,reverse:n,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(s))return d;if(l===!0)return _.DONE}),l?_:_.filter(d=>d)})}a(Tz,"startsWith");function gz(e,t,r,s,n=!1,i=void 0,o=void 0){return dw(e,t,r,s,n,i,o,!0)}a(gz,"endsWith");function dw(e,t,r,s,n=!1,i=void 0,o=void 0,c=!1){return oi(e,r,s),no(e,null,r,(u,l,_,d)=>{let E=_w(_,u,d,r);return o=Number.isInteger(o)?o:0,l.getKeys({transaction:u,end:n?!1:void 0,reverse:n}).flatMap(f=>{let h=f.toString();return h.endsWith(uw)?l.getValues(f,{transaction:u}).map(S=>{let T=E(f,S);if(c?T.endsWith(s):T.includes(s))return{key:T,value:S}}).filter(S=>S):(c?h.endsWith(s):h.includes(s))?l[od.DBI_DEFINITION_NAME].is_hash_attribute?{key:f,value:f}:l.getValues(f,{transaction:u}).map(S=>({key:f,value:S})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(dw,"contains");function Rz(e,t,r,s,n=!1,i=void 0,o=void 0){oi(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),nu(e,t,r,s,u,n,i,o,!0,!1)}a(Rz,"greaterThan");function Az(e,t,r,s,n=!1,i=void 0,o=void 0){oi(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),nu(e,t,r,s,u,n,i,o,!1,!1)}a(Az,"greaterThanEqual");function Oz(e,t,r,s,n=!1,i=void 0,o=void 0){oi(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),nu(e,t,r,u,s,n,i,o,!1,!0)}a(Oz,"lessThan");function Nz(e,t,r,s,n=!1,i=void 0,o=void 0){oi(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),nu(e,t,r,u,s,n,i,o,!1,!1)}a(Nz,"lessThanEqual");function bz(e,t,r,s,n,i=!1,o=void 0,c=void 0){if(yr.validateEnv(e),r===void 0)throw new Error(We.ATTRIBUTE_REQUIRED);if(s===void 0)throw new Error(We.START_VALUE_REQUIRED);if(n===void 0)throw new Error(We.END_VALUE_REQUIRED);if(s=yr.convertKeyValueToWrite(s),n=yr.convertKeyValueToWrite(n),s>n)throw new Error(We.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return nu(e,t,r,s,n,i,o,c)}a(bz,"between");function yz(e,t,r,s){yr.validateEnv(e);let n=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(We.HASH_ATTRIBUTE_REQUIRED);if(cd(r),r=iu(n,r),s===void 0)throw new Error(We.ID_REQUIRED);let o=null,c=n.dbis[t].get(s,{transaction:i,lazy:r.length<3});return c&&(o=ad.parseRow(c,r)),o}a(yz,"searchByHash");function Iz(e,t,r){yr.validateEnv(e);let s=e.database||e,n=e.database?e:null;if(t===void 0)throw new Error(We.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(We.ID_REQUIRED);let i=!0;return s.dbis[t].get(r,{transaction:n,lazy:!0})===void 0&&(i=!1),i}a(Iz,"checkHashExists");function wz(e,t,r,s,n=[]){return fw(e,t,r,s,n),Ew(e,t,r,s,n).map(i=>i[1])}a(wz,"batchSearchByHash");function Cz(e,t,r,s,n=[]){fw(e,t,r,s,n);let i=new Map;for(let[o,c]of Ew(e,t,r,s,n))i.set(o,c);return i}a(Cz,"batchSearchByHashToMap");function Ew(e,t,r,s,n=[]){return no(e,t,t,(i,o,c)=>{r=iu(c,r);let u=r.length<3;return s.map(l=>{let _=c.dbis[t].get(l,{transaction:i,lazy:u});if(_)return[l,ad.parseRow(_,r)];n.push(l)}).filter(l=>l)})}a(Ew,"batchHashSearch");function fw(e,t,r,s,n){if(yr.validateEnv(e),t===void 0)throw new Error(We.HASH_ATTRIBUTE_REQUIRED);if(cd(r),s==null)throw new Error(We.IDS_REQUIRED);if(!s[Symbol.iterator])throw new Error(We.IDS_MUST_BE_ITERABLE)}a(fw,"initializeBatchSearchByHash");function cd(e){if(!Array.isArray(e))throw e===void 0?new Error(We.FETCH_ATTRIBUTES_REQUIRED):new Error(We.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(cd,"validateFetchAttributes");function oi(e,t,r){if(yr.validateEnv(e),t===void 0)throw new Error(We.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(We.SEARCH_VALUE_REQUIRED);if(r?.length>dz)throw new Error(We.SEARCH_VALUE_TOO_LARGE)}a(oi,"validateComparisonFunctions");function iu(e,t){return t.length===1&&lz.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ii.listDBIs(e)),t}a(iu,"setGetWholeRowAttributes");hw.exports={searchAll:Ez,searchAllToMap:fz,count:Sz,countAll:mz,equals:pz,startsWith:Tz,endsWith:gz,contains:dw,searchByHash:yz,setGetWholeRowAttributes:iu,batchSearchByHash:wz,batchSearchByHashToMap:Cz,checkHashExists:Iz,iterateDBI:hz,greaterThan:Rz,greaterThanEqual:Az,lessThan:Oz,lessThanEqual:Nz,between:bz}});var ca=m((_fe,gw)=>{var mw=require("lodash"),pw=He(),Pe=require("joi"),Lz=F(),{hdb_schema_table:ud,checkValidTable:Sw,hdb_table:Tw,hdb_database:ld}=Ds(),{handleHDBError:Dz,hdb_errors:Uz}=z(),{getDatabases:Mz}=(_e(),re(be)),{HTTP_STATUS_CODES:Pz}=Uz,vz=Pe.object({database:ld,schema:ld,table:Tw,search_attribute:ud,search_value:Pe.any().required(),get_attributes:Pe.array().min(1).items(ud).optional(),desc:Pe.bool(),limit:Pe.number().integer().min(1),offset:Pe.number().integer().min(0)}),Bz=Pe.object({database:ld,schema:ld,table:Tw,operator:Pe.string().valid("and","or").default("and").lowercase(),offset:Pe.number().integer().min(0),limit:Pe.number().integer().min(1),get_attributes:Pe.array().min(1).items(ud).optional(),conditions:Pe.array().min(1).items(Pe.object({search_attribute:ud,search_type:Pe.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between").required(),search_value:Pe.when("search_type",{switch:[{is:"equals",then:Pe.any()},{is:"between",then:Pe.array().items(Pe.alternatives([Pe.string(),Pe.number()])).length(2)}],otherwise:Pe.alternatives(Pe.string(),Pe.number())}).required()})).required()});gw.exports=function(e,t){let r=null;switch(t){case"value":r=pw.validateBySchema(e,vz);break;case"hashes":let i=function(o){n?n+=". "+o:n=o};var s=i;a(i,"addError");let n;i(Sw("database",e.schema)),i(Sw("table",e.table)),e.hash_values?Array.isArray(e.hash_values)?e.hash_values.every(o=>typeof o=="string"||typeof o=="number")||i("'hash_values' must be strings or numbers"):i("'hash_values' must be an array"):i("'hash_values' is required"),e.get_attributes?Array.isArray(e.get_attributes)?e.get_attributes.length===0?i("'get_attributes' must contain at least 1 item"):e.get_attributes.every(o=>typeof o=="string"||typeof o=="number")||i("'get_attributes' must be strings or numbers"):i("'get_attributes' must be an array"):i("'get_attributes' is required"),n&&(r=new Error(n.trim()));break;case"conditions":r=pw.validateBySchema(e,Bz);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=Lz.checkGlobalSchemaTable(e.schema,e.table);if(n)return Dz(new Error,n,Pz.NOT_FOUND);let o=Mz()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];if(t==="value"&&c.push(e.search_attribute),t==="conditions")for(let l=0,_=e.conditions.length;l<_;l++){let d=e.conditions[l];c.push(d.search_attribute)}let u=mw.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!mw.some(o,_=>_===l||_.attribute===l||_.attribute===l.attribute));if(u&&u.length>0){let l=u.join(", ");return l=l.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${l}'`)}}return r}});var Gp=m((Efe,Rw)=>{"use strict";var Hz=we(),qz=ca(),{getSchemaPath:Fz}=De();Rw.exports=Gz;function Gz(e){let t=qz(e,"hashes");if(t)throw t;let r=Fz(e.schema,e.table);return Hz.openEnvironment(r,e.table)}a(Gz,"initialize")});var xp=m((hfe,Aw)=>{"use strict";var xz=aa(),kz=Gp();Aw.exports=$z;async function $z(e){let t=await kz(e),r=t.useReadTransaction();r.database=t;let s=global.hdb_schema[e.schema][e.table];try{return xz.batchSearchByHashToMap(r,s.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a($z,"lmdbGetDataByHash")});var ua=m((pfe,Ow)=>{"use strict";var kp=class{static{a(this,"SearchByHashObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};Ow.exports=kp});var bw=m((gfe,Nw)=>{"use strict";var Tfe=ua(),Vz=aa(),Yz=Gp();Nw.exports=Kz;async function Kz(e){let t=await Yz(e),r=global.hdb_schema[e.schema][e.table];return Vz.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(Kz,"lmdbSearchByHash")});var as=m((Afe,yw)=>{"use strict";var $p=class{static{a(this,"SearchObject")}constructor(t,r,s,n,i,o,c,u=!1,l=void 0,_=void 0){this.schema=t,this.table=r,this.search_attribute=s,this.search_value=n,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=l,this.offset=_}};yw.exports=$p});var _d=m((Nfe,Uw)=>{"use strict";var Gt=aa(),Wz=we(),Qz=F(),ae=Ge(),io=R(),zz=En(),Iw=gr().LMDB_ERRORS_ENUM,{getSchemaPath:Jz}=De(),An=io.SEARCH_WILDCARDS;async function jz(e,t,r){let s;e.schema===io.SYSTEM_SCHEMA_NAME?s=zz[e.table]:s=global.hdb_schema[e.schema][e.table];let n=Dw(e,s.hash_attribute,r,t);return Cw(e,n,s.hash_attribute,r)}a(jz,"prepSearch");async function Cw(e,t,r,s){let n=Jz(e.schema,e.table),i=await Wz.openEnvironment(n,e.table),o=Lw(i,e,t,r),c=o.transaction||i;if([ae.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,ae.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,ae.SEARCH_TYPES.SEARCH_ALL,ae.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(Xz(e,r)===!1){let _=e.search_attribute;if(_===r)return s?ww(o,()=>!0):o.map(E=>({[r]:E.key}));let d=a(E=>({[r]:E.value,[_]:E.key}),"toObject");return s?ww(o,d):o.map(d)}let l=e.search_attribute===r?o.map(_=>_.key):o.map(_=>_.value);return s===!0?Gt.batchSearchByHashToMap(c,r,e.get_attributes,l):Gt.batchSearchByHash(c,r,e.get_attributes,l)}a(Cw,"executeSearch");function Lw(e,t,r,s){let n,i=s;t.get_attributes.indexOf(s)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case ae.SEARCH_TYPES.EQUALS:n=Gt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case ae.SEARCH_TYPES.CONTAINS:n=Gt.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case ae.SEARCH_TYPES.ENDS_WITH:case ae.SEARCH_TYPES._ENDS_WITH:n=Gt.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case ae.SEARCH_TYPES.STARTS_WITH:case ae.SEARCH_TYPES._STARTS_WITH:n=Gt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case ae.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Gt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case ae.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Gt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case ae.SEARCH_TYPES.SEARCH_ALL:return Gt.searchAll(e,s,t.get_attributes,o,c,u);case ae.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Gt.searchAllToMap(e,s,t.get_attributes,o,c,u);case ae.SEARCH_TYPES.BETWEEN:n=Gt.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case ae.SEARCH_TYPES.GREATER_THAN:case ae.SEARCH_TYPES._GREATER_THAN:n=Gt.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case ae.SEARCH_TYPES.GREATER_THAN_EQUAL:case ae.SEARCH_TYPES._GREATER_THAN_EQUAL:n=Gt.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case ae.SEARCH_TYPES.LESS_THAN:case ae.SEARCH_TYPES._LESS_THAN:n=Gt.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case ae.SEARCH_TYPES.LESS_THAN_EQUAL:case ae.SEARCH_TYPES._LESS_THAN_EQUAL:n=Gt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return n}a(Lw,"searchByType");function ww(e,t){let r=new Map;for(let s of e)r.set(s.value,t(s));return r}a(ww,"createMapFromIterable");function Xz(e,t){if(e.get_attributes.length===1&&e.get_attributes[0]==="*")return!0;let r=[e.search_attribute];e.get_attributes.indexOf(t)>=0&&r.push(t);let s=!1;for(let n=0;n<e.get_attributes.length;n++)if(r.indexOf(e.get_attributes[n])<0){s=!0;break}return s}a(Xz,"checkToFetchMore");function Dw(e,t,r,s){if(Qz.isEmpty(s)){let n=e.search_value;typeof n=="object"?n=JSON.stringify(n):n=n.toString();let i=n.charAt(0),o=n.charAt(n.length-1),c=!1;if(e.search_attribute===t&&(c=!0),An.indexOf(n)>-1)return r===!0?ae.SEARCH_TYPES.SEARCH_ALL_TO_MAP:ae.SEARCH_TYPES.SEARCH_ALL;if(n.indexOf(An[0])<0&&n.indexOf(An[1])<0)return c===!0?r===!0?ae.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:ae.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:ae.SEARCH_TYPES.EQUALS;if(An.indexOf(i)>=0&&An.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),ae.SEARCH_TYPES.CONTAINS;if(An.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),ae.SEARCH_TYPES.ENDS_WITH;if(An.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),ae.SEARCH_TYPES.STARTS_WITH;if(n.includes(An[0])||n.includes(An[1]))return ae.SEARCH_TYPES.EQUALS;throw new Error(Iw.UNKNOWN_SEARCH_TYPE)}else switch(s){case io.VALUE_SEARCH_COMPARATORS.BETWEEN:return ae.SEARCH_TYPES.BETWEEN;case io.VALUE_SEARCH_COMPARATORS.GREATER:return ae.SEARCH_TYPES.GREATER_THAN;case io.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return ae.SEARCH_TYPES.GREATER_THAN_EQUAL;case io.VALUE_SEARCH_COMPARATORS.LESS:return ae.SEARCH_TYPES.LESS_THAN;case io.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return ae.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(Iw.UNKNOWN_SEARCH_TYPE)}}a(Dw,"createSearchTypeFromSearchObject");Uw.exports={executeSearch:Cw,createSearchTypeFromSearchObject:Dw,prepSearch:jz,searchByType:Lw}});var Pw=m((Ife,Mw)=>{"use strict";var yfe=as(),Zz=ca(),eJ=F(),tJ=R(),rJ=_d();Mw.exports=sJ;function sJ(e,t){if(!eJ.isEmpty(t)&&tJ.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=Zz(e,"value");if(s)throw s;let n=!0;return rJ.prepSearch(e,t,n)}a(sJ,"lmdbGetDataByValue")});var ou=m((Lfe,vw)=>{"use strict";var Cfe=as(),nJ=ca(),iJ=F(),oJ=R(),aJ=_d();vw.exports=cJ;async function cJ(e,t){if(!iJ.isEmpty(t)&&oJ.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=nJ(e,"value");if(s)throw s;return aJ.prepSearch(e,t,!1)}a(cJ,"lmdbSearchByValue")});var Hw=m((Mfe,Bw)=>{"use strict";var Ufe=Ge(),Vp=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,s,n,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=s,this.limit=i,this.offset=o,this.conditions=n,this.operator=c}},Yp=class{static{a(this,"SearchCondition")}constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}},Kp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};Bw.exports={SearchByConditionsObject:Vp,SearchCondition:Yp,SortAttribute:Kp}});var kw=m((Hfe,xw)=>{"use strict";var vfe=Hw().SearchByConditionsObject,uJ=as(),lJ=ca(),Wp=aa(),dd=Ge(),{Resource:Bfe}=(Is(),re(om)),Gw=_d(),_J=Fp(),dJ=require("lodash"),{getSchemaPath:EJ}=De(),qw=we(),{handleHDBError:fJ,hdb_errors:hJ}=z(),{HTTP_STATUS_CODES:mJ}=hJ,pJ=1e8;xw.exports=SJ;async function SJ(e){let t=lJ(e,"conditions");if(t)throw fJ(t,t.message,mJ.BAD_REQUEST,void 0,void 0,!0);e.operator=e.operator?e.operator.toLowerCase():void 0,e.offset=Number.isInteger(e.offset)?e.offset:0;let r=EJ(e.schema,e.table),s=await qw.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table];for(let l of e.conditions)qw.openDBI(s,l.search_attribute);let i=dJ.sortBy(e.conditions,l=>{if(l.estimated_count===void 0){let _=l.search_type;_===dd.SEARCH_TYPES.EQUALS?l.estimated_count=Wp.count(s,l.search_attribute,l.search_value):_===dd.SEARCH_TYPES.CONTAINS||_===dd.SEARCH_TYPES.ENDS_WITH?l.estimated_count=1/0:l.estimated_count=pJ}return l.estimated_count}),o=s.useReadTransaction();o.database=s;let c=await Fw(o,e,i[0],n.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let l=s.dbis[n.hash_attribute],_=i.slice(1).map(Gw.filterByType),d=_.length,E=Wp.setGetWholeRowAttributes(s,e.get_attributes);u=c.map(f=>l.get(f,{transaction:o,lazy:!0})),d>0&&(u=u.filter(f=>{for(let h=0;h<d;h++)if(!_[h](f))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(f=>_J.parseRow(f,E))}else{for(let d=1;d<i.length;d++){let E=i[d],f=await Fw(o,e,E,n.hash_attribute);c=c.concat(f)}let l=new Set,_=e.offset||0;c=c.filter(d=>l.has(d)?!1:(l.add(d),!0)).slice(_,e.limit&&e.limit+_),u=Wp.batchSearchByHash(o,n.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(SJ,"lmdbSearchByConditions");async function Fw(e,t,r,s){let n=new uJ(t.schema,t.table,void 0,void 0,s,t.get_attributes),i=r.search_type;return n.search_attribute=r.search_attribute,i===dd.SEARCH_TYPES.BETWEEN?(n.search_value=r.search_value[0],n.end_value=r.search_value[1]):n.search_value=r.search_value,Gw.searchByType(e,n,i,s).map(o=>o.value)}a(Fw,"executeConditionSearch")});var au=m((Ffe,$w)=>{"use strict";var TJ=R().OPERATIONS_ENUM,Qp=class{static{a(this,"DeleteObject")}constructor(t,r,s,n=void 0){this.operation=TJ.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};$w.exports=Qp});var zp=m((xfe,jw)=>{"use strict";var Ww=as(),Qw=au(),zw=ou(),Jw=su(),tr=R(),Vw=F(),Yw=we(),{getTransactionAuditStorePath:gJ,getSchemaPath:RJ}=De(),Kw=C();jw.exports=AJ;async function AJ(e){try{if(Vw.isEmpty(global.hdb_schema[e.schema])||Vw.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await OJ(e),await NJ(e);let t=RJ(e.schema,e.table);try{await Yw.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")Kw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=gJ(e.schema,e.table);await Yw.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")Kw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(AJ,"lmdbDropTable");async function OJ(e){let t=new Ww(tr.SYSTEM_SCHEMA_NAME,tr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await zw(t)),s=[];for(let i=0;i<r.length;i++){let o=r[i];s.push(o.id)}if(s.length===0)return;let n=new Qw(tr.SYSTEM_SCHEMA_NAME,tr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await Jw(n)}a(OJ,"deleteAttributesFromSystem");async function NJ(e){let t=new Ww(tr.SYSTEM_SCHEMA_NAME,tr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,s;try{r=Array.from(await zw(t))}catch(i){throw i}for(let i=0;i<r.length;i++){let o=r[i];o.name===e.table&&o.schema===e.schema&&(s=o)}if(!s)throw new Error(`${e.schema}.${e.table} was not found`);let n=new Qw(tr.SYSTEM_SCHEMA_NAME,tr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await Jw(n)}catch(i){throw i}}a(NJ,"dropTableFromSystem")});var Zw=m(($fe,Xw)=>{"use strict";var bJ=require("fs-extra"),yJ=as(),IJ=ua(),wJ=au(),CJ=zp(),LJ=su(),DJ=xp(),UJ=ou(),On=R(),{getSchemaPath:MJ}=De(),{handleHDBError:PJ,hdb_errors:vJ}=z(),{HDB_ERROR_MSGS:BJ,HTTP_STATUS_CODES:HJ}=vJ;Xw.exports=qJ;async function qJ(e){let t;try{t=await FJ(e.schema);let r=new yJ(On.SYSTEM_SCHEMA_NAME,On.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,On.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[On.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),s=Array.from(await UJ(r));for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await CJ(c)}catch(u){if(u.message!=="invalid environment")throw u}}let n=new wJ(On.SYSTEM_SCHEMA_NAME,On.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await LJ(n);let i=MJ(t);await bJ.remove(i)}catch(r){throw r}}a(qJ,"lmdbDropSchema");async function FJ(e){let t=new IJ(On.SYSTEM_SCHEMA_NAME,On.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[On.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,s;try{r=Array.from(await DJ(t))}catch(n){throw n}for(let[,n]of r)n.name===e&&(s=e);if(!s)throw PJ(new Error,BJ.SCHEMA_NOT_FOUND(e),HJ.NOT_FOUND,void 0,void 0,!0);return s}a(FJ,"validateDropSchema")});var cu=m((Yfe,eC)=>{"use strict";var Jp=class{static{a(this,"CreateTableObject")}constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};eC.exports=Jp});var Xp=m((Qfe,tC)=>{"use strict";var GJ=require("fs-extra"),Ed=we(),{getTransactionAuditStorePath:xJ}=De(),jp=Ge(),Wfe=cu();tC.exports=kJ;async function kJ(e){let t;try{let r=xJ(e.schema,e.table);await GJ.mkdirp(r),t=await Ed.createEnvironment(r,e.table,!0)}catch(r){throw r.message=`unable to create transactions audit environment for ${e.schema}.${e.table} due to: ${r.message}`,r}try{Ed.createDBI(t,jp.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),Ed.createDBI(t,jp.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),Ed.createDBI(t,jp.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME,!0,!1)}catch(r){throw r.message=`unable to create dbi for ${e.schema}.${e.table} due to: ${r.message}`,r}return t}a(kJ,"createTransactionsAuditEnvironment")});var iC=m((Jfe,nC)=>{"use strict";var Zp=R(),rC=we(),$J=Wi(),{getSystemSchemaPath:VJ,getSchemaPath:YJ}=De(),KJ=En(),WJ=v_(),eS=P_(),QJ=C(),zJ=Xp(),rS=KJ.hdb_table,sC=[];for(let e=0;e<rS.attributes.length;e++)sC.push(rS.attributes[e].attribute);nC.exports=JJ;async function JJ(e,t){let r=YJ(t.schema,t.table),s=new eS(t.schema,t.table,Zp.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=new eS(t.schema,t.table,Zp.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new eS(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await rC.createEnvironment(r,t.table),e!==void 0){let o=await rC.openEnvironment(VJ(),Zp.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await $J.insertRecords(o,rS.hash_attribute,sC,[e]),s.skip_table_check=!0,n.skip_table_check=!0,i.skip_table_check=!0,await tS(s),await tS(n),await tS(i)}await zJ(t)}catch(o){throw o}}a(JJ,"lmdbCreateTable");async function tS(e){try{await WJ(e)}catch(t){QJ.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(tS,"createAttribute")});var aC=m((Xfe,oC)=>{"use strict";var jJ=$c(),XJ=Qc(),ZJ=nd(),uu=R(),ej=Wi().updateRecords,tj=we(),{getSchemaPath:rj}=De(),sj=tu(),nj=C();oC.exports=ij;async function ij(e){try{let{schema_table:t,attributes:r}=jJ(e);XJ(e,r,t.hash_attribute),e.schema!==uu.SYSTEM_SCHEMA_NAME&&(r.includes(uu.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(uu.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(uu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(uu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await ZJ(e.hdb_auth_header,t,r),n=rj(e.schema,e.table),i=await tj.openEnvironment(n,e.table),o=await ej(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await sj(e,o)}catch(c){nj.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:s,txn_time:o.txn_time}}catch(t){throw t}}a(ij,"lmdbUpdateRecords")});var uC=m((ehe,cC)=>{"use strict";var oj=R().OPERATIONS_ENUM,sS=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=oj.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};cC.exports=sS});var _C=m((she,lC)=>{"use strict";var rhe=uC(),aj=$c(),cj=Qc(),uj=nd(),lu=R(),lj=Wi().upsertRecords,_j=we(),{getSchemaPath:dj}=De(),Ej=tu(),fj=C(),{handleHDBError:hj,hdb_errors:mj}=z();lC.exports=pj;async function pj(e){let t;try{t=aj(e)}catch(u){throw hj(u,u.message,mj.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;cj(e,s,r.hash_attribute),e.schema!==lu.SYSTEM_SCHEMA_NAME&&(s.includes(lu.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||s.push(lu.TIME_STAMP_NAMES_ENUM.CREATED_TIME),s.includes(lu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||s.push(lu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await uj(e.hdb_auth_header,r,s),i=dj(e.schema,e.table),o=await _j.openEnvironment(i,e.table),c=await lj(o,r.hash_attribute,s,e.records,e.__origin?.timestamp);try{await Ej(e,c)}catch(u){fj.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:n,txn_time:c.txn_time}}a(pj,"lmdbUpsertRecords")});var EC=m((ihe,dC)=>{"use strict";var nS=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};dC.exports=nS});var hC=m((ahe,fC)=>{"use strict";var iS=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,s=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=s}};fC.exports=iS});var SC=m((lhe,pC)=>{"use strict";var oS=we(),{getTransactionAuditStorePath:Sj}=De(),uhe=EC(),_u=Ge(),Tj=F(),mC=hC(),gj=require("util").promisify,Rj=gj(setTimeout),Aj=1e4,Oj=100;pC.exports=Nj;async function Nj(e){let t=Sj(e.schema,e.table),r=await oS.openEnvironment(t,e.table,!0),s=oS.listDBIs(r);oS.initializeDBIs(r,_u.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new mC;do n=await bj(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=n.start_timestamp),n.end_timestamp!==void 0&&(i.end_timestamp=n.end_timestamp),i.transactions_deleted+=n.transactions_deleted,await Rj(Oj);while(n.transactions_deleted>0);return i}a(Nj,"deleteAuditLogsBefore");async function bj(e,t){let r=new mC;try{let s=e.dbis[_u.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let{key:i,value:o}of s.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),n=s.remove(i);let c=o[_u.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];Tj.isEmpty(c)||(n=e.dbis[_u.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)n=e.dbis[_u.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>Aj)break}return await n,r}catch(s){throw s}}a(bj,"deleteTransactions")});var gC=m((dhe,TC)=>{"use strict";var aS=class{static{a(this,"DropAttributeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};TC.exports=aS});var AC=m((hhe,RC)=>{"use strict";var yj=as(),Ij=au(),fhe=gC(),vs=R(),wj=F(),cS=we(),Cj=En(),Lj=ou(),Dj=su(),{getSchemaPath:Uj}=De();RC.exports=Mj;async function Mj(e,t=!0){let r;e.schema===vs.SYSTEM_SCHEMA_NAME?r=Cj[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await vj(e),n=Uj(e.schema,e.table),i=await cS.openEnvironment(n,e.table);return t===!0&&await Pj(e,i,r.hash_attribute),cS.dropDBI(i,e.attribute),s}a(Mj,"lmdbDropAttribute");async function Pj(e,t,r){let s=cS.openDBI(t,r),n,i=e.attribute;for(let{key:o,value:c,version:u}of s.getRange({start:!1,versions:!0})){let l={};for(let _ in c)_!==i&&(l[_]=c[_]);n=t.dbis[r].put(o,l,u)}await n}a(Pj,"removeAttributeFromAllObjects");async function vj(e){let t=new yj(vs.SYSTEM_SCHEMA_NAME,vs.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,vs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[vs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,vs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),s=Array.from(await Lj(t)).filter(o=>o[vs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(wj.isEmptyOrZeroLength(s))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let n=s.map(o=>o[vs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new Ij(vs.SYSTEM_SCHEMA_NAME,vs.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return Dj(i)}a(vj,"dropAttributeFromSystem")});var wC=m((She,IC)=>{"use strict";var uS=we(),la=Ge(),phe=Ht(),lS=R(),OC=F(),{getTransactionAuditStorePath:Bj}=De(),Hj=aa(),fd=na(),qj=C();IC.exports=Fj;async function Fj(e){let t=Bj(e.schema,e.table),r=await uS.openEnvironment(t,e.table,!0),s=uS.listDBIs(r);uS.initializeDBIs(r,la.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;switch(e.search_type){case lS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return NC(r,e.search_values);case lS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return n=global.hdb_schema[e.schema][e.table].hash_attribute,xj(r,e.search_values,n);case lS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return Gj(r,e.search_values);default:return NC(r)}}a(Fj,"readAuditLog");function NC(e,t=[0,Date.now()]){OC.isEmpty(t[0])&&(t[0]=0),OC.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[la.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let n of r.getKeys({start:t[1]}))if(n!==t[1]){s=n;break}return r.getRange({start:t[0],end:s}).map(({value:n})=>Object.assign(new fd,n))}a(NC,"searchTransactionsByTimestamp");function Gj(e,t=[]){let r=new Map;for(let s=0;s<t.length;s++){let n=t[s],i=[];for(let o of e.dbis[la.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(n))i.push(o);r.set(n,yC(e,i))}return Object.fromEntries(r)}a(Gj,"searchTransactionsByUsername");function xj(e,t,r){let s=new Map;for(let c=0,u=t.length;c<u;c++){let l=t[c],_=Hj.equals(e,la.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,la.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,l);for(let{value:d}of _){let E=Number(d);s.has(E)?s.get(E).push(l.toString()):s.set(E,[l.toString()])}}let n=Array.from(s.keys()),i=yC(e,n),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],l=u.timestamp,_=s.get(l);bC(u,"records",r,_,o),bC(u,"original_records",r,_,o)}return Object.fromEntries(o)}a(xj,"searchTransactionsByHashValues");function bC(e,t,r,s,n){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],u=c[r].toString();if(s.indexOf(u)>=0)if(n.has(u)){let l=n.get(u),_=l[l.length-1];if(_.timestamp===i)_[t]=[c];else{let d=new fd(e.operation,e.user_name,i,void 0);d[t]=[c],l.push(d)}}else{let l=new fd(e.operation,e.user_name,i,void 0);l[t]=[c],n.set(u,[l])}}}a(bC,"loopRecords");function yC(e,t){let r=[];try{let s=e.dbis[la.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let n=0;n<t.length;n++)try{let i=s.get(t[n]);if(i){let o=Object.assign(new fd,i);r.push(o)}}catch(i){qj.warn(i)}return r}catch(s){throw s}}a(yC,"batchSearchTransactions")});var LC=m((Ahe,CC)=>{"use strict";var{getSchemaPath:ghe}=De(),Rhe=we(),{database:kj}=(_e(),re(be));CC.exports={writeTransaction:$j};async function $j(e,t,r){return kj({database:e,table:t}).transaction(r)}a($j,"writeTransaction")});var PC=m((Nhe,MC)=>{"use strict";var{getSchemaPath:DC}=De(),UC=we();MC.exports={flush:Vj,resetReadTxn:Yj};async function Vj(e,t){return(await UC.openEnvironment(DC(e,t),t.toString())).flushed}a(Vj,"flush");async function Yj(e,t){try{(await UC.openEnvironment(DC(e,t),t.toString())).resetReadTxn()}catch{}}a(Yj,"resetReadTxn")});var qC=m((yhe,HC)=>{"use strict";var{Readable:Kj}=require("stream"),{getDatabases:Wj}=(_e(),re(be)),{readSync:Qj,openSync:zj,createReadStream:vC}=require("fs"),{open:Jj}=require("lmdb"),BC=N_(),jj=y_(),{INTERNAL_DBIS_NAME:Xj}=Ge();HC.exports=e2;var _S=32768,Zj=100;async function e2(e){let t=e.database||e.schema||"data",r=Wj()[t],s=new Date().toISOString(),n=e.tables||e.table&&[e.table];if(n){let l=r[n[0]];if(!l)throw new Error(`Can not find table ${n[0]}`);let _=l.dbisDB,d=Jj({noSync:!0,maxDbs:jj.MAX_DBS}),E,f=d.openDB(Xj,new BC(!1)),h=_.useReadTransaction(),S=0;for(let{key:A,value:g}of _.getRange({transaction:h,start:!1}))if(n.some(x=>A.startsWith?.(x+"/"))){f.put(A,g);let[,x]=A.split("/"),V=!x,I=new BC(!V,V);I.encoding="binary";let b=d.openDB(A,I),M=_.openDB(A,I);for(let{key:J,version:B,value:Ie}of M.getRange({transaction:h,versions:V}))E=b.put(J,Ie,B),S++%Zj===0&&await new Promise(_t=>setTimeout(_t,20))}await E;let T=vC(d.path);return T.headers=u(),T.on("close",()=>{h.done(),d.close()}),T}let o=r[Object.keys(r)[0]].primaryStore,c=zj(o.path);return o.transaction(()=>{let l=Buffer.alloc(_S);Qj(c,l,0,_S);let _=o.useReadTransaction(),d=vC(null,{fd:c,start:_S}),E=new Kj.from(async function*(){yield l;for await(let f of d)yield f;_.done()}());return E.headers=u(),E});function u(){let l=new Map;return l.set("content-type","application/octet-stream"),l.set("content-disposition",`attachment; filename="${t}"`),l.set("date",s),l}}a(e2,"getBackup")});var xC=m((whe,GC)=>{"use strict";var t2=C(),{handleHDBError:r2}=z(),s2=ab(),n2=v_(),i2=Pp(),o2=ZI(),a2=su(),c2=xp(),u2=bw(),l2=Pw(),_2=ou(),d2=kw(),E2=Zw(),f2=iC(),h2=aC(),m2=_C(),p2=SC(),S2=zp(),T2=AC(),g2=wC(),R2=LC(),FC=PC(),A2=qC(),dS=class extends s2{static{a(this,"LMDBBridge")}async searchByConditions(t){return d2(t)}async getDataByHash(t){return await c2(t)}async searchByHash(t){return await u2(t)}async getDataByValue(t,r){return await l2(t,r)}async searchByValue(t){return await _2(t)}async createSchema(t){return await o2(t)}async dropSchema(t){return await E2(t)}async createTable(t,r){return await f2(t,r)}async dropTable(t){return await S2(t)}async createAttribute(t){return await n2(t)}async createRecords(t){return await i2(t)}async updateRecords(t){return await h2(t)}async upsertRecords(t){try{return await m2(t)}catch(r){throw r2(r,null,null,t2.ERR,r)}}async deleteRecords(t){return await a2(t)}async dropAttribute(t){return await T2(t)}async deleteAuditLogsBefore(t){return await p2(t)}async readAuditLog(t){return await g2(t)}writeTransaction(t,r,s){return R2.writeTransaction(t,r,s)}flush(t,r){return FC.flush(t,r)}resetReadTxn(t,r){return FC.resetReadTxn(t,r)}getBackup(t){return A2(t)}};GC.exports=dS});var JC={};Ke(JC,{ResourceBridge:()=>hS});function mS({get_attributes:e},t){if(e){if(e[0]==="*"){if(t.schemaDefined)return;e=t.attributes.map(r=>r.name)}return e.forceNulls=!0,e}}function $C(e,t){let r=Bs(e),s=mS(e,r);if(!r)throw new cs.ClientError(`Table ${e.table} not found`);let n;s&&r.attributes.length-s.length>2&&s.length<5&&(n=!0);let i={user:e.hdb_user};return Xe(i,async function*(o){for(let c of e.hash_values){let u=await r.get({id:c,lazy:n,select:s},i);u=u&&p_(u),t?yield{key:c,value:u}:yield u}})}function Bs(e){let t=e.database||e.schema||N2,r=us()[t];if(!r)throw(0,cs.handleHDBError)(new Error,O2.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function VC(e,t,r){let s=e.length+t.length,n=s===1?"record":"records";return{message:`${e.length} of ${s} ${n} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*YC(e,t,r){let s;for await(let n of e.getHistory(t,r)){let i=n.type;i==="put"&&(i="upsert");let{id:o,timestamp:c,value:u}=n;s?.timestamp===c?(s.hash_values.push(o),s.records.push(u)):(s&&(yield s),s={operation:i,user_name:n.user,timestamp:c,hash_values:[o],records:[u]})}s&&(yield s)}var KC,hd,cs,WC,QC,ls,ES,fS,zC,O2,N2,b2,y2,kC,hS,jC=Te(()=>{"use strict";KC=D(xC()),hd=D(ca()),cs=D(z());_e();WC=D($c()),QC=D(Qc()),ls=D(R()),ES=D(Rn()),fS=D(os()),zC=D(F());Yi();S_();({HDB_ERROR_MSGS:O2}=cs.hdb_errors),N2="data",b2=1e4,y2=10,hS=class extends KC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),kC=this}async searchByConditions(t){let r=(0,hd.default)(t,"conditions");if(r)throw(0,cs.handleHDBError)(r,r.message,400,void 0,void 0,!0);let s=Bs(t);if(!s)throw new cs.ClientError(`Table ${t.table} not found`);let n=t.conditions.map(i=>({attribute:i.search_attribute,comparator:i.search_type,value:i.search_value}));return s.search({conditions:n,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:mS(t,s),allowFullScan:!0})}async createTable(t,r){let s=r.attributes,n=!!s,i=r.primary_key||r.hash_attribute;if(s)for(let o of s)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new cs.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");s=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}ft({database:r.schema,table:r.table,attributes:s,schemaDefined:n,expiration:r.expiration})}async createAttribute(t){return await Bs(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=Bs(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let s=t.attribute,n,i=a((o,c,u)=>(c=Object.assign({},c),delete c[s],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(l=>{if(!l){let{value:_,version:d}=r.primaryStore.getEntry(o);return i(o,_,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))n=i(o,c,u),await new Promise(l=>setImmediate(l));await n}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){Bs(t).dropTable()}createSchema(t){return du({database:t.schema,table:null}),ES.signalSchemaChange(new fS.SchemaEventMsg(process.pid,ls.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await pS(t.schema),ES.signalSchemaChange(new fS.SchemaEventMsg(process.pid,ls.OPERATIONS_ENUM.DROP_SCHEMA,t.schema))}async updateRecords(t){return t.requires_existing=!0,this.upsertRecords(t)}async createRecords(t){return t.requires_no_existing=!0,kC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:s}=(0,WC.default)(t);(0,QC.default)(t,s,r.primaryKey);let n,i=us()[t.schema][t.table],o={user:t.hdb_user};return Xe(o,async c=>{if(!i.schemaDefined){n=[];for(let _ of s)i.attributes.find(E=>E.name==_)||n.push(_);n.length>0&&await i.addAttributes(n.map(_=>({name:_,indexed:!0})))}let u=[],l=[];for(let _ of t.records){let d=await i.get(_[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){l.push(_[i.primaryKey]);continue}d&&(d=p_(d));for(let E in _)if(Object.prototype.hasOwnProperty.call(_,E)){let f=_[E];if(typeof f=="function")try{let h=f([[d]]);Array.isArray(h)&&(f=h[0].func_val,_[E]=f)}catch(h){throw h.message+="Trying to set key "+E+" on object"+JSON.stringify(_),h}}if(d)for(let E in d)Object.prototype.hasOwnProperty.call(_,E)||(_[E]=d[E]);await i.put(_,o),u.push(_[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:n,skipped_hashes:l}})}async deleteRecords(t){let r=us()[t.schema][t.table],s={user:t.hdb_user};return Xe(s,async n=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,s)?o.push(u):c.push(u);return VC(o,c,n.timestamp)})}async deleteRecordsBefore(t){let r=us()[t.schema][t.table];if(!r.createdTimeProperty)throw new cs.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let s=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:ls.VALUE_SEARCH_COMPARATORS.LESS}]}),n=!1,i=[],o=[],c=0,u=[],l=a(async()=>{let _=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(..._.deleted_hashes),o.push(..._.skipped_hashes),await(0,zC.async_set_timeout)(y2),u=[],n=!0},"chunkDelete");for await(let _ of s)u.push(_[r.primaryKey]),c++,c%b2===0&&await l();return u.length>0&&await l(),n?VC(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){let r=(0,hd.default)(t,"hashes");if(r)throw r;return $C(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:s,value:n}of $C(t,!0))r.set(s,n);return r}searchByValue(t,r){if(r&&ls.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);let s=(0,hd.default)(t,"value");if(s)throw s;let n=Bs(t);if(!n)throw new cs.ClientError(`Table ${t.table} not found`);let i=t.search_value;i.includes?.("*")&&(i.startsWith("*")?i.endsWith("*")?i!=="*"&&(r="contains",i=i.slice(1,-1)):(r="ends_with",i=i.slice(1)):i.endsWith("*")&&(r="starts_with",i=i.slice(0,-1))),r===ls.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return n.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:mS(t,n)})}async getDataByValue(t,r){let s=new Map,n=Bs(t);t.get_attributes&&!t.get_attributes.includes(n.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(n.primaryKey);for await(let i of this.searchByValue(t,r))s.set(i[n.primaryKey],i);return s}resetReadTxn(t,r){Bs({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return Bs(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=Bs(t),s={};switch(t.search_type){case ls.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)s[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,user_name:o.user,hash_values:[i],records:[o.value]}});return s;case ls.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let n=t.search_values;for await(let i of YC(r))n.includes(i.user_name)&&(s[i.user_name]||(s[i.user_name]=[])).push(i);return s;default:return YC(r,t.search_values?.[0],t.search_values?.[1])}}};a(mS,"getSelect");a($C,"getRecords");a(Bs,"getTable");a(VC,"createDeleteResponse");a(YC,"groupRecordsInHistory")});var Vr=m((Phe,XC)=>{"use strict";var{ResourceBridge:I2}=(jC(),re(JC)),w2=Y();w2.initSync();var md;function C2(){return md||(md=new I2,md)}a(C2,"getBridge");XC.exports=C2()});var rL=m((Bhe,tL)=>{"use strict";var ZC=require("lodash"),Eu=require("mathjs"),L2=require("jsonata"),eL=F();tL.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?ZC.uniqWith(e,ZC.isEqual):e,searchJSON:D2,mad:fu.bind(null,Eu.mad),mean:fu.bind(null,Eu.mean),mode:fu.bind(null,Eu.mode),prod:fu.bind(null,Eu.prod),median:fu.bind(null,Eu.median)};function fu(e,t,r,s){return s===1?t==null?[]:[t]:s===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a(fu,"aggregateFunction");function D2(e,t){if(typeof e!="string"||e.length===0)throw new Error("search json expression must be a non-empty string");let r="__"+e+"__";if(eL.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),eL.isEmpty(this.__ala__.res[r])){let s=L2(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(D2,"searchJSON")});var nL=m((qhe,sL)=>{"use strict";var rt=require("moment"),SS="YYYY-MM-DDTHH:mm:ss.SSSZZ";rt.suppressDeprecationWarnings=!0;sL.exports={current_date:()=>rt().utc().format("YYYY-MM-DD"),current_time:()=>rt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return rt(e).utc().format("YYYY");case"month":return rt(e).utc().format("MM");case"day":return rt(e).utc().format("DD");case"hour":return rt(e).utc().format("HH");case"minute":return rt(e).utc().format("mm");case"second":return rt(e).utc().format("ss");case"millisecond":return rt(e).utc().format("SSS");default:break}},date:e=>rt(e).utc().format(SS),date_format:(e,t)=>rt(e).utc().format(t),date_add:(e,t,r)=>rt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>rt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let s=rt(e).utc(),n=rt(t).utc();return r?s.diff(n,r,!0):s.diff(n)},now:()=>rt().utc().valueOf(),get_server_time:()=>rt().format(SS),offset_utc:(e,t)=>rt(e).utc().utcOffset(t).format(SS)}});var cL=m((Fhe,aL)=>{"use strict";var U2=require("@turf/area"),M2=require("@turf/length"),P2=require("@turf/circle"),v2=require("@turf/difference"),B2=require("@turf/distance"),H2=require("@turf/boolean-contains"),q2=require("@turf/boolean-equal"),F2=require("@turf/boolean-disjoint"),G2=require("@turf/helpers"),iL=R(),Ee=F();aL.exports={geoArea:x2,geoLength:k2,geoCircle:$2,geoDifference:V2,geoDistance:oL,geoNear:Y2,geoContains:K2,geoEqual:W2,geoCrosses:Q2,geoConvert:z2};var TS="geo1 is required",gS="geo2 is required";function x2(e){if(Ee.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=Ee.autoCastJSON(e)),U2.default(e)}a(x2,"geoArea");function k2(e,t){if(Ee.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=Ee.autoCastJSON(e)),M2.default(e,{units:t||"kilometers"})}a(k2,"geoLength");function $2(e,t,r){if(Ee.isEmpty(e))throw new Error("point is required");if(Ee.isEmpty(t))throw new Error("radius is required");return typeof e=="string"&&(e=Ee.autoCastJSON(e)),P2.default(e,t,{units:r||"kilometers"})}a($2,"geoCircle");function V2(e,t){if(Ee.isEmpty(e))throw new Error("poly1 is required");if(Ee.isEmpty(t))throw new Error("poly2 is required");return typeof e=="string"&&(e=Ee.autoCastJSON(e)),typeof t=="string"&&(t=Ee.autoCastJSON(t)),v2(e,t)}a(V2,"geoDifference");function oL(e,t,r){if(Ee.isEmpty(e))throw new Error("point1 is required");if(Ee.isEmpty(t))throw new Error("point2 is required");return typeof e=="string"&&(e=Ee.autoCastJSON(e)),typeof t=="string"&&(t=Ee.autoCastJSON(t)),B2.default(e,t,{units:r||"kilometers"})}a(oL,"geoDistance");function Y2(e,t,r,s){if(Ee.isEmpty(e))throw new Error("point1 is required");if(Ee.isEmpty(t))throw new Error("point2 is required");if(Ee.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=Ee.autoCastJSON(e)),typeof t=="string"&&(t=Ee.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");return oL(e,t,s)<=r}a(Y2,"geoNear");function K2(e,t){if(Ee.isEmpty(e))throw new Error(TS);if(Ee.isEmpty(e))throw new Error(gS);return typeof e=="string"&&(e=Ee.autoCastJSON(e)),typeof t=="string"&&(t=Ee.autoCastJSON(t)),H2.default(e,t)}a(K2,"geoContains");function W2(e,t){if(Ee.isEmpty(e))throw new Error(TS);if(Ee.isEmpty(e))throw new Error(gS);return typeof e=="string"&&(e=Ee.autoCastJSON(e)),typeof t=="string"&&(t=Ee.autoCastJSON(t)),q2.default(e,t)}a(W2,"geoEqual");function Q2(e,t){if(Ee.isEmpty(e))throw new Error(TS);if(Ee.isEmpty(e))throw new Error(gS);return typeof e=="string"&&(e=Ee.autoCastJSON(e)),typeof t=="string"&&(t=Ee.autoCastJSON(t)),!F2.default(e,t)}a(Q2,"geoCrosses");function z2(e,t,r){if(Ee.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(Ee.isEmpty(t))throw new Error("geo_type is required");if(Ee.isEmpty(iL.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(iL.GEO_CONVERSION_ENUM).join(",")}`);return G2[t](e,r)}a(z2,"geoConvert")});var pd=m((xhe,uL)=>{var oo=rL(),Ir=nL(),Hs=cL();uL.exports=e=>{e.aggr.mad=e.aggr.MAD=oo.mad,e.aggr.mean=e.aggr.MEAN=oo.mean,e.aggr.mode=e.aggr.MODE=oo.mode,e.aggr.prod=e.aggr.PROD=oo.prod,e.aggr.median=e.aggr.MEDIAN=oo.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=oo.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=oo.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=Ir.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Ir.current_time,e.fn.extract=e.fn.EXTRACT=Ir.extract,e.fn.date=e.fn.DATE=Ir.date,e.fn.date_format=e.fn.DATE_FORMAT=Ir.date_format,e.fn.date_add=e.fn.DATE_ADD=Ir.date_add,e.fn.date_sub=e.fn.DATE_SUB=Ir.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Ir.date_diff,e.fn.now=e.fn.NOW=Ir.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Ir.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Ir.get_server_time,e.fn.getdate=e.fn.GETDATE=Ir.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Ir.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=Hs.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=Hs.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=Hs.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=Hs.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=Hs.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=Hs.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=Hs.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=Hs.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=Hs.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=Hs.geoNear}});var EL=m((khe,dL)=>{"use strict";var hu=require("lodash"),wt=require("alasql");wt.options.cache=!1;var J2=pd(),lL=require("clone"),Sd=require("recursive-iterator"),ie=C(),oe=F(),_a=Vr(),j2=R(),{hdb_errors:X2}=z(),{getDatabases:_L}=(_e(),re(be)),Z2="IS NULL",_s="There was a problem performing this search. Please check the logs and try again.";J2(wt);var RS=class{static{a(this,"SQLSearch")}constructor(t,r){if(oe.isEmpty(t))throw ie.error("AST statement for SQL select process cannot be empty"),"statement cannot be null";this.statement=t,this.columns={},this.all_table_attributes=r,this.fetch_attributes=[],this.exact_search_values={},this.comparator_search_values={},this.tables=[],this.data={},this.has_aggregator=!1,this.has_ordinal=!1,this.has_outer_join=!1,this._getColumns(),this._getTables(),this._conditionsToFetchAttributeValues(),this._setAliasesForColumns(),oe.backtickASTSchemaItems(this.statement)}async search(){let t;try{let s=await this._checkEmptySQL();if(!oe.isEmptyOrZeroLength(s))return ie.trace("No results returned from checkEmptySQL SQLSearch method."),s}catch(s){throw ie.error("Error thrown from checkEmptySQL in SQLSearch class method search."),ie.error(s),new Error(_s)}try{let s=await this._getFetchAttributeValues();if(s)return s}catch(s){throw ie.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),ie.error(s),new Error(_s)}if(Object.keys(this.data).length===0)return ie.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(s){throw ie.error("Error thrown from processJoins in SQLSearch class method search."),ie.error(s),new Error(_s)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(s){throw ie.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),ie.error(s),new Error(_s)}try{return t=await this._finalSQL(),t}catch(s){throw ie.error("Error thrown from finalSQL in SQLSearch class method search."),ie.error(s),new Error(_s)}}_getColumns(){let t=new Sd(this.statement);for(let{node:r,path:s}of t)r&&r.columnid&&(this.columns[s[0]]||(this.columns[s[0]]=[]),this.columns[s[0]].push(lL(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=hu.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let s=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[s]={},this.data[s].__hash_name=_L()[r.databaseid][r.tableid].primaryKey,this.data[s].__merged_data={},this.data[s].__merged_attributes=[],this.data[s].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(oe.isEmpty(this.statement.where)){ie.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new Sd(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!oe.isEmpty(r)&&r.right)if(oe.isNotEmptyAndHasValue(r.right.value)){let s=oe.autoCast(r.right.value);[!0,!1].indexOf(s)>=0?r.right=new wt.yy.LogicValue({value:s}):r.right instanceof wt.yy.StringValue&&!oe.isEmpty(s)&&oe.autoCasterIsNumberCheck(s.toString())&&(r.right=new wt.yy.NumValue({value:s}))}else Array.isArray(r.right)&&r.right.forEach((s,n)=>{let i=oe.autoCast(s.value);[!0,!1].indexOf(i)>=0?r.right[n]=new wt.yy.LogicValue({value:i}):s instanceof wt.yy.StringValue&&oe.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new wt.yy.NumValue({value:i}))});if(t){ie.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new Sd(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let s=new Set,n=r.left.columnid?r.left:r.right,i=this._findColumn(n);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!oe.isEmpty(j2.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(oe.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(oe.isEmptyOrZeroLength(r.left.columnid)||oe.isEmptyOrZeroLength(r.right.value)){this.comparator_search_values[o].ignore=!0,this.comparator_search_values[o].comparators=[];continue}this.comparator_search_values[o].comparators.push({attribute:r.left.columnid,operation:r.op,search_value:r.right.value})}continue}if(oe.isEmpty(this.exact_search_values[o])&&(this.exact_search_values[o]={ignore:!1,values:new Set}),!this.exact_search_values[o].ignore){let c=!1;switch(r.op){case"=":!oe.isEmpty(r.right.value)||!oe.isEmpty(r.left.value)?s.add(oe.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let u=Array.isArray(r.right)?r.right:r.left;for(let l=0;l<u.length;l++)if(u[l].value)s.add(u[l].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...s])}}}_setAliasesForColumns(){if(oe.isEmptyOrZeroLength(this.all_table_attributes)&&oe.isEmptyOrZeroLength(this.statement.from)&&oe.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((s,n)=>{if(s.columnid==="*"){t.push(n);return}if(s.aggregatorid&&(this.has_aggregator=!0),!s.aggregatorid&&!s.funcid)if(s.as_orig=s.as?s.as:s.columnid,this.statement.joins)if(r[s.as_orig]>=0){let i=r[s.as_orig]+1;s.as=`[${s.as_orig+i}]`,r[s.as_orig]=i}else s.as=`[${s.as_orig}]`,r[s.as_orig]=0;else s.as=`[${s.as_orig}]`;!s.aggregatorid&&s.funcid&&s.args&&(s.as_orig=s.as?s.as:s.toString().replace(/'/g,'"'),s.as=`[${s.as_orig}]`),s.aggregatorid&&s.expression.columnid!=="*"&&(s.as_orig=s.as?s.as:s.expression.tableid?`${s.aggregatorid}(${s.expression.tableid}.${s.expression.columnid})`:`${s.aggregatorid}(${s.expression.columnid})`,s.as=`[${s.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&hu.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(s=>{if(t.columnid_orig&&t.tableid_orig)return(s.table.as===t.tableid_orig||s.table.tableid===t.tableid_orig)&&s.attribute===t.columnid_orig;if(t.tableid)return(s.table.as===t.tableid||s.table.tableid===t.tableid)&&s.attribute===t.columnid;let n=t.columnid_orig?t.columnid_orig:t.columnid;return s.attribute===n});if(oe.isEmptyOrZeroLength(r)){let s=this.columns.columns.filter(n=>n.as?t.columnid===n.as:!1);oe.isEmptyOrZeroLength(s)||(r=this.all_table_attributes.filter(n=>n.attribute===s[0].columnid&&s[0].tableid&&s[0].tableid===(n.table.as?n.table.as:n.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(oe.isEmptyOrZeroLength(this.all_table_attributes)&&!oe.isEmptyOrZeroLength(this.columns.columns))return t;if(oe.isEmptyOrZeroLength(this.all_table_attributes)&&oe.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await wt.promise(r)}catch(r){throw ie.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),ie.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let s=this._findColumn(r);s&&this.fetch_attributes.push(lL(s))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,s,n){let i=this.data[t].__merged_attr_map[s];this.data[t].__merged_data[r].splice(i,1,n)}async _getFetchAttributeValues(){if(oe.isEmptyOrZeroLength(Object.keys(this.columns)))return[];this._addFetchColumns(this.columns.joins);let t=null;try{t=this.statement.where?this.statement.where.toString():""}catch{throw new Error("Could not generate proper where clause")}this.columns.where&&this._addFetchColumns(this.columns.where);let r=this._isSimpleSelect();if(r?this._addFetchColumns(this.columns.columns):(!this.columns.where&&this.fetch_attributes.length===0)|t.indexOf(Z2)>-1&&this.tables.forEach(n=>{let i={columnid:_L()[n.databaseid][n.tableid].primaryKey,tableid:n.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=hu.uniqBy(this.fetch_attributes,n=>[n.table.databaseid,n.table.as?n.table.as:n.table.tableid,n.attribute].join()),r)return await this._simpleSQLQuery();let s=this.fetch_attributes.reduce((n,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return n[o]||(n[o]=[],n[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(n[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),n},{});for(let n of this.fetch_attributes){let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,o=this.data[i].__hash_name,c={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]},u=!1,l=[n.table.databaseid,n.table.tableid,n.attribute].join("/");if(n.attribute===o&&(u=!0),!oe.isEmpty(this.exact_search_values[l])&&!this.exact_search_values[l].ignore&&!oe.isEmptyOrZeroLength(this.exact_search_values[l].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[l].values);let _=await _a.getDataByHash(c);for(let d of c.hash_values)_.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,d))}catch(_){throw ie.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),ie.error(_),new Error(_s)}else try{c.search_attribute=n.attribute,await Promise.all(Array.from(this.exact_search_values[l].values).map(async _=>{let d=Object.assign({},c);d.search_value=_;let E=await _a.getDataByValue(d);for(let[f,h]of E)this.data[i].__merged_data[f]?this._updateMergedAttribute(i,f,n.attribute,h[n.attribute]):(this.data[i].__merged_data[f]=[...s[i]],this._updateMergedAttribute(i,f,n.attribute,h[n.attribute]),this._setMergedHashAttribute(i,oe.autoCast(f)))}))}catch(_){throw ie.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),ie.error(_),new Error(_s)}else if(!oe.isEmpty(this.comparator_search_values[l])&&!this.comparator_search_values[l].ignore&&!oe.isEmptyOrZeroLength(this.comparator_search_values[l].comparators))try{let _=this.comparator_search_values[l].comparators;for(let d=0,E=_.length;d<E;d++){let f=_[d];c.search_attribute=f.attribute,c.search_value=f.search_value;let h=await _a.getDataByValue(c,f.operation);if(u)for(let[S]of h)this.data[i].__merged_data[S]||(this.data[i].__merged_data[S]=[...s[i]],this._setMergedHashAttribute(i,oe.autoCast(S)));else for(let[S,T]of h)this.data[i].__merged_data[S]?this._updateMergedAttribute(i,S,n.attribute,T[n.attribute]):(this.data[i].__merged_data[S]=[...s[i]],this._updateMergedAttribute(i,S,n.attribute,T[n.attribute]),this._setMergedHashAttribute(i,oe.autoCast(S)))}}catch(_){throw ie.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),ie.error(_),new Error(_s)}else try{c.search_attribute=n.attribute,c.search_value="*";let _=await _a.getDataByValue(c);if(u)for(let[d]of _)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,oe.autoCast(d)));else for(let[d,E]of _)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,n.attribute,E[n.attribute]):(this.data[i].__merged_data[d]=[...s[i]],this._updateMergedAttribute(i,d,n.attribute,E[n.attribute]),this._setMergedHashAttribute(i,oe.autoCast(d)))}catch(_){throw ie.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),ie.error(_),new Error(_s)}}}_isSimpleSelect(){let t=!0;return Object.keys(this.statement).length!==2||!this.statement.columns||!this.statement.from||this.statement.from.length!==1?(t=!1,t):(this.statement.columns.forEach(r=>{r instanceof wt.yy.Column||(t=!1)}),t)}_updateOrderByToAliases(){this.statement.order.forEach(t=>{if(t.expression.aggregatorid){t.is_aggregator=!0;return}if(t.expression.value){t.is_ordinal=!0,this.has_ordinal=!0;return}else t.is_ordinal=!1;let r=this.statement.columns.filter(n=>{let i=n.aggregatorid?n.expression:n,o=n.aggregatorid?n.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let s=r[0];if(t.is_func=!!s.funcid,t.is_aggregator=!!s.aggregatorid,s.as)if(s.as&&!t.expression.tableid)t.expression.columnid=s.as,t.expression.columnid_orig=s.as_orig;else{let n=new wt.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}else{t.initial_select_column=Object.assign(new wt.yy.Column,t.expression),t.initial_select_column.as=`[${t.expression.columnid_orig}]`,t.expression.columnid=t.initial_select_column.as;return}if(!t.is_aggregator){let n=t.is_func?new wt.yy.FuncValue:new wt.yy.Column;t.initial_select_column=Object.assign(n,s)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(s=>!s.is_aggregator&&!s.is_ordinal).map(s=>s.is_func?{columnid:s.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:s.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],s=this.statement.from[0],n=[s],i=["? "+(s.as?" AS "+s.as:s.tableid)];t.push(Object.values(this.data[`${s.databaseid_orig}_${s.as?s.as_orig:s.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(f=>{f.joinmode&&f.joinmode!=="INNER"&&(this.has_outer_join=!0),n.push(f.table);let h=f.joinmode+" JOIN ? AS "+(f.as?f.as:f.table.tableid);f.on&&(h+=" ON "+f.on.toString()),i.push(h),t.push(Object.values(this.data[`${f.table.databaseid_orig}_${f.table.as?f.table.as_orig:f.table.tableid_orig}`].__merged_data))});let o=[],c={};n.forEach(f=>{let h=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__hash_name,S=f.as?f.as_orig:f.tableid_orig;o.push({key:`'${S}.${h}'`,schema:f.databaseid_orig,table:f.as?f.as_orig:f.tableid_orig,keys:new Set}),r.push(`${f.as?f.as:f.tableid}.\`${h}\` AS "${S}.${h}"`),c[f.as?f.as_orig:f.tableid_orig]=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"",l="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(l="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(f=>{f.is_func?r.push(f.initial_select_column.toString()):f.initial_select_column.tableid?r.push(`${f.initial_select_column.tableid}.${f.initial_select_column.columnid} AS ${f.expression.columnid}`):r.push(`${f.initial_select_column.columnid} AS ${f.expression.columnid}`)}));let _="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&(_=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let E=[];try{let f=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${l} ${_} ${d}`,h=this._convertColumnsToIndexes(f,n);E=await wt.promise(h,t),t=null}catch(f){throw ie.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),ie.error(f),new Error("There was a problem processing the data.")}if(E&&E.length>0){for(let f=0,h=E.length;f<h;f++){let S=E[f];o.forEach(T=>{S[T.key]!==null&&S[T.key]!==void 0&&T.keys.add(S[T.key])})}o.forEach(f=>{let h=Object.keys(this.data[`${f.schema}_${f.table}`].__merged_data),S=hu.difference(h,[...f.keys].map(T=>T.toString()));for(let T=0,A=S.length;T<A;T++){let g=S[T];delete this.data[`${f.schema}_${f.table}`].__merged_data[g]}})}return{existing_attributes:c,joined_length:E?E.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let s=[],n=new Sd(this.columns);for(let{node:i}of n)if(i&&i.columnid){let o=this._findColumn(i);if(o){let c=o.table.as?o.table.as:o.table.tableid;(!t[c]||t[c].indexOf(o.attribute)<0)&&s.push(o)}}s=hu.uniqBy(s,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(s)}catch(i){throw ie.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),ie.error(i),new Error(_s)}}async _getData(t){try{let r=t.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]?s[i].columns.push(n.attribute):s[i]={schema:n.table.databaseid,table:n.table.tableid,columns:[n.attribute]},s},{});for(let s in r){let n=r[s],i=this.data[s].__merged_data,o=[];for(let _ in i)o.push(i[_][0]);this.data[s].__merged_attributes.push(...n.columns);let c={schema:n.schema,table:n.table,hash_values:o,get_attributes:n.columns},u=await _a.getDataByHash(c),l=n.columns.length;for(let _=0,d=o.length;_<d;_++){let E=o[_],f=u.get(E);for(let h=0;h<l;h++){let S=n.columns[h],T=f[S]===void 0?null:f[S];this.data[s].__merged_data[E].push(T)}}}}catch(r){throw ie.error("Error thrown from getDataByHash function in SQLSearch class method getData."),ie.error(r),r}}async _finalSQL(){let t=[],r=this.statement.from[0];t.push(Object.values(this.data[`${r.databaseid_orig}_${r.as?r.as_orig:r.tableid_orig}`].__merged_data)),r.as=r.as?r.as:r.tableid,r.databaseid="",r.tableid="?",this.statement.joins&&this.statement.joins.forEach(n=>{n.as=n.as?n.as:n.table.tableid,t.push(Object.values(this.data[`${n.table.databaseid_orig}_${n.table.as?n.table.as_orig:n.table.tableid_orig}`].__merged_data)),n.table.databaseid="",n.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(n=>{if(n.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,u=o.aggregatorid?o.as_orig:c.as_orig;return n.expression.tableid?c.columnid_orig===n.expression.columnid_orig&&c.tableid_orig===n.expression.tableid_orig:c.columnid_orig===n.expression.columnid_orig||n.expression.columnid_orig===u}).length===0&&(n.expression.columnid=n.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&(this.statement.limit&&delete this.statement.limit,this.statement.offset&&delete this.statement.offset);let s;try{let n=this._buildSQL();ie.trace(`Final SQL: ${n}`),s=await wt.promise(n,t),this.has_outer_join&&(s=this._translateUndefinedValues(s)),ie.trace(`Final AlaSQL results data included ${s.length} rows`)}catch(n){throw ie.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),ie.error(n),new Error("There was a problem running the generated sql.")}return s}_translateUndefinedValues(t){try{let r=[];for(let s of t){let n=Object.create(null);Object.keys(s).forEach(i=>{s[i]===void 0?n[i]=null:n[i]=s[i]}),r.push(n)}return r}catch(r){return ie.error(X2.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),ie.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return this.statement.columns.forEach(s=>{if(s.funcid&&s.as){let n=s.toString().replace(" AS "+s.as,"");r=r.replace(s.toString(),n)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let s=t,n={};r.forEach(i=>{i.databaseid_orig?n[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:n[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=n[i],l=new RegExp(`${u}.\`${o}\``,"g"),_=`${u}.[${c}]`;s=s.replace(l,_)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),l=`[${c}]`;s=s.replace(u,l)});return s}async _simpleSQLQuery(){let t=this.statement.columns.reduce((s,n)=>(n.as_orig&&n.as_orig!=n.columnid_orig?s[n.columnid_orig]=n.as_orig:s[n.columnid_orig]||(s[n.columnid_orig]=n.columnid_orig),s),{}),r=this.fetch_attributes.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]||(s[i]={}),s[i][t[n.attribute]]=null,s},{});for(let s of this.fetch_attributes){let n=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,i={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]};try{i.search_attribute=s.attribute,i.search_value="*";let o=await _a.getDataByValue(i);for(let[c,u]of o)this.data[n].__merged_data[c]||(u[s.attribute]===void 0&&(u[s.attribute]=null),this.data[n].__merged_data[c]=Object.assign({},r[n])),this.data[n].__merged_data[c][t[s.attribute]]=u[s.attribute]??null}catch(o){throw ie.error("There was an error when processing this SQL operation. Check your logs"),ie.error(o),new Error(_s)}}return Object.values(Object.values(this.data)[0].__merged_data)}};dL.exports=RS});var jt=m((Vhe,fL)=>{"use strict";var e3=ib();fL.exports={searchByConditions:r3,searchByHash:s3,searchByValue:n3,search:i3};var AS=Vr(),{transformReq:OS}=F(),t3=EL();async function r3(e){return OS(e),AS.searchByConditions(e)}a(r3,"searchByConditions");async function s3(e){OS(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of AS.searchByHash(e))r&&t.push(r);return t}a(s3,"searchByHash");async function n3(e){OS(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of AS.searchByValue(e))t.push(r);return t}a(n3,"searchByValue");function i3(e,t){try{let r=new e3(e);r.validate(),new t3(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(i3,"search")});var Td=m((Khe,hL)=>{"use strict";var o3=Vr();hL.exports={writeTransaction:a3};function a3(e,t,r){return o3.writeTransaction(e,t,r)}a(a3,"writeTransaction")});var TL=m((zhe,SL)=>{"use strict";var c3=jt(),u3=$r(),mL=C(),l3=Xt(),Qhe=Td(),_3=require("clone"),bS=require("alasql"),d3=pd(),pL=require("util"),E3=pL.promisify(u3.getTableSchema),f3=pL.promisify(c3.search),h3=R(),NS=F();d3(bS);SL.exports={update:p3};var m3="There was a problem performing this update. Please check the logs and try again.";async function p3({statement:e,hdb_user:t}){let r=await E3(e.table.databaseid,e.table.tableid),s=S3(e.columns);NS.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=_3(n),c=NS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,l=bS.parse(u).statements[0],_=await f3(l),d=T3(s,_);return g3(o,d,t)}a(p3,"update");function S3(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=bS.compile(`SELECT ${r.expression.toString()} AS [${h3.FUNC_VAL}] FROM ?`)}),t}catch(t){throw mL.error(t),new Error(m3)}}a(S3,"createUpdateRecord");function T3(e,t){return NS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(T3,"buildUpdateRecords");async function g3(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},n=await l3.update(s);try{delete n.new_attributes,delete n.txn_time}catch(i){mL.error(`Error delete new_attributes from update response: ${i}`)}return n}a(g3,"updateRecords")});var RL=m((Zhe,gL)=>{var R3=require("alasql"),A3=jt(),O3=C(),N3=Vr(),IS=require("util"),yS=F(),b3=R(),y3=$r(),jhe=Td(),Xhe=Xt(),I3="record",w3="successfully deleted",C3=IS.callbackify(M3),L3=IS.promisify(A3.search),D3=IS.promisify(y3.getTableSchema);gL.exports={convertDelete:C3};function U3(e){return`${e.deleted_hashes.length} ${I3}${e.deleted_hashes.length===1?"":"s"} ${w3}`}a(U3,"generateReturnMessage");async function M3({statement:e,hdb_user:t}){let r=await D3(e.table.databaseid,e.table.tableid);yS.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=yS.isEmpty(n)?"":` WHERE ${n.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=R3.parse(o).statements[0],u={operation:b3.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{u.records=await L3(c);let l=await N3.deleteRecords(u);return yS.isEmptyOrZeroLength(l.message)&&(l.message=U3(l)),delete l.txn_time,l}catch(l){throw O3.error(l),l.hdb_code?l.message:l}}a(M3,"convertDelete")});var yL=m((tme,bL)=>{"use strict";var P3=Zn(),{hdb_errors:AL}=z(),{getDatabases:OL}=(_e(),re(be));bL.exports={checkSchemaExists:NL,checkSchemaTableExists:v3,schema_describe:P3};async function NL(e){if(!OL()[e])return AL.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(NL,"checkSchemaExists");async function v3(e,t){let r=await NL(e);if(r)return r;if(!OL()[e][t])return AL.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(v3,"checkSchemaTableExists")});var Nd={};Ke(Nd,{addAnalyticsListener:()=>DS,recordAction:()=>qs,recordActionBinary:()=>da,setAnalyticsEnabled:()=>B3});function B3(e){BL=e}function qs(e,t,r,s,n){if(!BL)return;let i=t+(r?"-"+r:"");s&&(i+="-"+s);let o=Ad.get(i);o?(o.push(e),o.total+=e):(o=[e],o.total=e,o.description={metric:t,path:r,method:s,type:n},Ad.set(i,o)),Rd||H3()}function da(e,t,r,s,n){qs(e?1:0,t,r,s,n)}function DS(e){qL.push(e)}function H3(){Rd=performance.now(),setTimeout(()=>{let e=performance.now()-Rd;Rd=0;let t=[],r={time:Date.now(),period:e,threadId:ao.threadId,metrics:t};for(let[n,i]of Ad)if(i.sort){i.sort();let o=i.length;t.push(Object.assign(i.description,{median:i[o>>1],mean:i.total/o,p95:i[Math.floor(o*.95)],p90:i[Math.floor(o*.9)],count:o}))}else t.push(i);let s=process.memoryUsage();t.push({metric:"memory",threadId:ao.threadId,...s});for(let n of qL)n(t);Ad=new Map,ao.parentPort?ao.parentPort.postMessage({type:HL,report:r}):GL({report:r})},LS).unref()}async function q3(e,t=6e4){let r=US(),s;for(let _ of r.primaryStore.getRange({start:gd+"z",end:gd,reverse:!0}))if(_.value?.time){s=_.value.time;break}if(Date.now()-t<s)return;let n,i=new Map,o;for(let{key:_,value:d}of r.primaryStore.getRange({start:s||!1,exclusiveStart:!0,end:1/0})){if(!d)continue;if(n){if(_>n+t)break}else n=_;o=_;let{metrics:E}=d;for(let f of E||[]){let{path:h,method:S,type:T,metric:A,count:g,threadId:x,...V}=f;g||(g=1);let I=A+(h?"-"+h:"");S&&(I+="-"+S);let b=i.get(I);if(b)for(let M in V){let J=V[M];if(typeof J=="number"){let B=b.count||1;b[M]=(b[M]*B+J*g)/(b.count=B+g)}}else b=Object.assign({period:t},f),i.set(I,b)}await F3()}for(let[_,d]of i)d.id=gd+Math.round(o)+"-"+_,d.time=o,r.put(d);let c=Date.now(),{idle:u,active:l}=performance.eventLoopUtilization();r.put({id:gd+Math.round(c)+"-main-thread-utilization",metric:"main-thread-utilization",idle:u-IL,active:l-wL,time:c}),IL=u,wL=l}async function G3(e,t){let r=US(),s=Date.now()-e;for(let n of r.primaryStore.getKeys({start:!1,end:s}))r.primaryStore.remove(n)}function US(){return CL||(CL=ft({table:"hdb_analytics",database:"system",expiration:864e3,audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"values"}]}))}function k3(){FL=!0,setInterval(async()=>{await q3(LS,CS),await G3(x3,LS)},CS/2).unref()}function GL(e,t){let r=e.report;r.threadId=t?.threadId||ao.threadId;for(let s of r.metrics)s.metric==="bytes-sent"&&(LL+=s.mean*s.count);r.totalBytesProcessed=LL,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(DL.get(t))}),DL.set(t,t.performance.eventLoopUtilization())),r.id=(0,PL.getNextMonotonicTime)(),US().put(r),FL||k3(),$3&&(xL=Y3(r))}async function Y3(e){if(await xL,!ai){let r=(0,mu.dirname)((0,ML.getLogFilePath)());try{ai=await(0,wS.open)((0,mu.join)(r,"analytics.log"),"r+")}catch{ai=await(0,wS.open)((0,mu.join)(r,"analytics.log"),"w+")}}let t=(await ai.stat()).size;if(t>V3){let r=Buffer.alloc(t);await ai.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await ai.write(r,{position:0}),await ai.truncate(r.length),t=r.length}await ai.write(JSON.stringify(e)+`
|
|
7
7
|
`,t)}var ao,UL,ML,mu,wS,PL,Od,vL,Ad,CS,BL,Rd,LS,HL,qL,gd,IL,wL,F3,x3,CL,FL,LL,DL,$3,xL,ai,V3,co=Te(()=>{ao=require("worker_threads"),UL=D(tt());_e();ML=D(C()),mu=require("path"),wS=require("fs/promises"),PL=D(Ht()),Od=D(Y()),vL=D(R());rs();(0,Od.initSync)();Ad=new Map,CS=(0,Od.get)(vL.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3,BL=CS>0;a(B3,"setAnalyticsEnabled");a(qs,"recordAction");Et.recordAnalytics=qs;a(da,"recordActionBinary");Rd=0,LS=1e3,HL="analytics-report",qL=[];a(DS,"addAnalyticsListener");a(H3,"sendAnalytics");gd="sum-";a(q3,"aggregation");IL=0,wL=0,F3=a(()=>new Promise(setImmediate),"rest");a(G3,"cleanup");x3=36e5;a(US,"getAnalyticsTable");(0,UL.setChildListenerByType)(HL,GL);a(k3,"startScheduledTasks");LL=0,DL=new Map,$3=!1;a(GL,"recordAnalytics");V3=1e6;a(Y3,"logAnalytics")});var Qe=m((mme,oD)=>{"use strict";var Ct=Y();Ct.initSync();var K3=require("fs-extra"),W3=require("semver"),gu=require("path"),{monotonicFactory:Q3}=require("ulidx"),BS=Q3(),z3=require("util"),$L=require("child_process"),J3=z3.promisify($L.exec),j3=$L.spawn,fe=Me(),Re=R(),bd=F(),Kr=C(),yd=mn(),X3=Td(),pu=et(),{Encoder:Z3,decode:HS}=require("msgpackr"),VL=new Z3,{isEmpty:uo}=bd,YL=er(),KL=12e10,e4=48*36e11,t4=5e9,{connect:r4,StorageType:WL,RetentionPolicy:QL,AckPolicy:Id,DeliverPolicy:wd,DiscardPolicy:s4,NatsConnection:dme,JetStreamManager:Eme,JetStreamClient:fme,StringCodec:hme,JSONCodec:n4,createInbox:qS,headers:i4,ErrorCode:kL}=require("nats"),{PACKAGE_ROOT:o4}=R(),a4=ki(),{recordAction:c4}=(co(),re(Nd)),zL=n4(),u4="clustering",l4=a4.engines[fe.NATS_SERVER_NAME],_4=gu.join(o4,"dependencies"),vS=gu.join(_4,`${process.platform}-${process.arch}`,fe.NATS_BINARY_NAME),MS,PS,Su,Ea,fa;oD.exports={runCommand:JL,checkNATSServerInstalled:d4,createConnection:FS,getConnection:Cd,getJetStreamManager:Ru,getJetStream:jL,getNATSReferences:rr,getServerList:f4,createLocalStream:GS,listStreams:XL,deleteLocalStream:h4,getServerConfig:Au,listRemoteStreams:m4,viewStream:p4,viewStreamIterator:S4,publishToStream:T4,createWorkQueueStream:g4,addSourceToWorkStream:eD,request:A4,removeSourceFromWorkStream:rD,reloadNATS:xS,reloadNATSHub:O4,reloadNATSLeaf:N4,extractServerName:tD,requestErrorHandler:b4,updateWorkStream:y4,createLocalTableStream:nD,createTableStreams:I4,purgeTableStream:iD,purgeSchemaTableStreams:w4,getStreamInfo:C4,updateLocalStreams:D4,closeConnection:E4,getJsmServerName:Ou,addNatsMsgHeader:ZL,updateIngestStreamConsumer:R4};async function JL(e,t=void 0){let{stdout:r,stderr:s}=await J3(e,{cwd:t});if(s)throw new Error(s.replace(`
|
|
@@ -24,12 +24,12 @@
|
|
|
24
24
|
|
|
25
25
|
`+_R.readFileSync(o):"")},s.http2=!0}return s}a(Yre,"getServerOptions");aH.exports=Yre});var _H=m((KTe,lH)=>{"use strict";var dR=Y();dR.initSync();var{CONFIG_PARAMS:uH}=R();function Kre(){let e=dR.get(uH.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST),t=dR.get(uH.CUSTOMFUNCTIONS_NETWORK_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(s,n)=>n(null,e.indexOf(s)!==-1))),r}a(Kre,"getCORSOptions");lH.exports=Kre});var fH=m((QTe,EH)=>{"use strict";var dH=Y();dH.initSync();var Wre=R();function Qre(){return dH.get(Wre.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT)}a(Qre,"getHeaderTimeoutConfig");EH.exports=Qre});var hR={};Ke(hR,{customFunctionsServer:()=>jre,handleFile:()=>Jre,ready:()=>ese});async function Jre(e,t,r,s){if(!Bn){let c=ER.get(fR.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS);Bn=IH(c),Et.http((await Bn).server)}let n=await Bn,i=(0,mH.dirname)(r),o=t.replace(/\/routes\/.*/g,"");o.startsWith("/")&&(o=o.slice(1)),hH.has(i)||(hH.add(i),n.register(Zre(i,o)))}async function jre(){try{ve.info("In Custom Functions Fastify server"+process.cwd()),ve.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),ve.debug(`Custom Functions server process ${process.pid} starting up.`),await Xre();let e=ER.get(fR.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS),t=e&&(e===!0||e.toUpperCase()===TRUE_COMPARE_VAL),r;try{r=Bn=await IH(t)}catch(s){throw ve.error(`Custom Functions buildServer error: ${s}`),s}try{await r.ready()}catch(s){throw ve.error(`Custom Functions server.ready() error: ${s}`),s}r.server.cantCleanupProperly=!0}catch(e){ve.error(`Custom Functions ${process.pid} Error: ${e}`),ve.error(e),process.exit(1)}}async function Xre(){try{ve.info("Custom Functions starting configuration."),await AH.setUsersToGlobal(),ve.info("Custom Functions completed configuration.")}catch(e){ve.error(e)}}function Zre(e,t){return async function(r){try{ve.info("Custom Functions starting buildRoutes"),ve.trace("Loading fastify routes folder "+e),(0,pH.existsSync)(e)&&r.register(RH.default,n=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:n.hdbCore,logger:ve.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((n,i,o)=>{n?.message?ve.error(n.message):n&&ve.error(n),o()})}catch(s){ve.error(`Custom Functions errored buildRoutes: ${s}`)}}}async function IH(e){ve.info("Custom Functions starting buildServer.");let t=(0,OH.default)(e),r=(0,SH.default)(t);r.server.headersTimeout=(0,bH.default)(),r.setErrorHandler(yH.serverErrorHandler);let s=(0,NH.default)();return s&&r.register(TH.default,s),r.register(function(n,i,o){n.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(gH.default),await r.register(zre),await r.after(),Ug(r),ve.info("Custom Functions completed buildServer."),r}function ese(){if(Bn)return Bn.then?Bn.then(e=>e.ready()):Bn.ready()}var mH,pH,SH,TH,gH,RH,ER,fR,ve,zre,AH,OH,NH,bH,yH,Bn,hH,wH=Te(()=>{mH=require("path"),pH=require("fs"),SH=D(require("fastify")),TH=D(require("@fastify/cors")),gH=D(Hg()),RH=D(require("@fastify/autoload")),ER=D(Y()),fR=D(R()),ve=D(C()),zre=D(oH()),AH=D(er()),OH=D(cH()),NH=D(_H()),bH=D(fH()),yH=D(gf());Da();rs();hH=new Set;a(Jre,"handleFile");a(jre,"customFunctionsServer");a(Xre,"setUp");a(Zre,"buildRouteFolder");a(IH,"buildServer");a(ese,"ready")});var mR={};Ke(mR,{start:()=>tse});function tse(e){let t=e.root;return{handleFile(r,s,n){LH||(LH=!0,e.server.http(async(i,o)=>{if(!i.isWebSocket){let c=CH.get(i.pathname);if(c)return{handlesHeaders:!0,body:(0,DH.default)(i,c)}}return o(i)},{runFirst:!0})),t&&(s.startsWith("/"+t)?s=s.slice(t.length+1):s.startsWith(t)&&(s=s.slice(t.length))),CH.set(s,n)}}}var DH,CH,LH,UH=Te(()=>{DH=D(require("send")),CH=new Map;a(tse,"start")});var HH=m(bf=>{"use strict";var{isMainThread:rse,parentPort:Tl,threadId:sse}=require("worker_threads"),{Socket:nse}=require("net"),{createServer:ise,IncomingMessage:ose}=require("http"),{createServer:ase}=require("https"),{readFileSync:$a}=require("fs"),Rf=C(),Ws=Y(),Va=R(),{server:Nf}=(rs(),re(Pc)),{WebSocketServer:cse}=require("ws"),{createServer:use}=require("tls"),{getTicketKeys:lse}=tt(),{Headers:_se}=(yE(),re(TP));process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&console.error("uncaughtException",e)});var{HDB_SETTINGS_NAMES:ege,CONFIG_PARAMS:tge}=Va;Ws.initSync();var gi={};bf.registerServer=OR;bf.httpServer=NR;bf.deliverSocket=AR;Nf.http=NR;Nf.request=mse;Nf.socket=pse;Nf.ws=Sse;var pR=[],SR=[],dse,Sl={},Af={},Ese=[],TR=[];rse||yf().loadRootComponents(!0).then(()=>{Tl.on("message",e=>{let{port:t,fd:r,data:s}=e;if(r)AR(r,t,s);else if(e.requestId)fse(e);else if(e.type===Va.ITC_EVENT_TYPES.SHUTDOWN)for(let n in gi){let i=gi[n];i.close?.(()=>{setTimeout(()=>{i.cantCleanupProperly||Rf.warn("Had to forcefully exit the thread",sse),process.exit(0)},i.cantCleanupProperly?2500:5e3).unref()}),i.closeIdleConnections?.()}}).ref(),Tl.postMessage({type:Va.ITC_EVENT_TYPES.CHILD_STARTED})});function AR(e,t,r){let s=e?.read?e:new nse({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),n=gi[t];if(n)typeof n=="function"?n(s):n.emit("connection",s),r&&s.emit("data",r);else{let i=a(o=>{setTimeout(()=>{let c=gi[t];c?(typeof c=="function"?c(s):c.emit("connection",s),r&&s.emit("data",r)):o<5?i(o+1):(Rf.error(`Server on port ${t} was not registered`),s.destroy())},1e3)},"retry");i(1)}return s}a(AR,"deliverSocket");var MH=new Map;function fse(e){let{port:t,event:r,data:s,requestId:n}=e,i;switch(i=MH.get(n),r){case"connection":i=AR(void 0,t),MH.set(n,i),i.write=(c,u,l)=>(Tl.postMessage({requestId:n,event:"data",data:c.toString("latin1")}),l&&l(),!0),i.end=(c,u,l)=>(Tl.postMessage({requestId:n,event:"end",data:c?.toString("latin1")}),l&&l(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),Tl.postMessage({requestId:n,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(s,"latin1"));break;case"drain":i._readableState.destroyed||i.emit("drain",{});break;case"end":i._readableState.destroyed||i.emit("end",{});break;case"error":i._readableState.destroyed||i.emit("error",{});break}}a(fse,"proxyRequest");function OR(e,t){+t||(t=parseInt(Ws.get(Va.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_PORT),10));let r=gi[t];if(r){let s=r.lastServer||r;s.off("unhandled",PH),s.on("unhandled",(n,i)=>{e.cantCleanupProperly&&(r.cantCleanupProperly=!0),e.emit("request",n,i)}),r.lastServer=e}else gi[t]=e;e.on("unhandled",PH)}a(OR,"registerServer");function vH(e){let t=[],r=parseInt(e?.securePort);return r&&t.push({port:r,secure:!0}),r=parseInt(e?.port),r&&t.push({port:r,secure:!1}),t.length===0&&(t=[{port:parseInt(Ws.get(Va.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_PORT),10),secure:Ws.get(Va.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}]),t}a(vH,"getPorts");function NR(e,t){for(let{port:r,secure:s}of vH(t))BH(r,s,t?.isOperationsServer),typeof e=="function"?TR[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):OR(e,r),Af[r]=gR(TR,r),dse=gR(Ese,r)}a(NR,"httpServer");function BH(e,t,r){if(!Sl[e]){let s={};if(t){let n=r?"operationsapi":"customfunctions",i=Ws.get(n+"_tls_privatekey"),o=Ws.get(n+"_tls_certificate"),c=Ws.get(n+"_tls_certificateauthority");s={key:$a(i),cert:$a(o)+(c?`
|
|
26
26
|
|
|
27
|
-
`+$a(c):""),ticketKeys:lse()}}Sl[e]=(t?ase:ise)(s,async(n,i)=>{try{let o=new Of(n);r&&(o.isOperationsServer=!0);let c=await Af[e](o);if(c.headers?.set?.("Server","HarperDB"),c.status===-1){for(let l of c.headers||[])i.setHeader(l[0],l[1]);return n.baseRequest=o,i.baseResponse=c,Sl[e].emit("unhandled",n,i)}c.handlesHeaders||i.writeHead(c.status||200,c.headers&&Array.from(c.headers));let u=c.body;u?.pipe?(u.pipe(i),u.destroy&&i.on("close",()=>{u.destroy()})):u?.then?u.then(l=>{i.end(l)},l=>{i.writeHead(l.statusCode||500),i.end(l.toString()),Rf.error(l)}):i.end(u)}catch(o){i.writeHead(o.statusCode||500),i.end(o.toString()),Rf.error(o)}}),OR(Sl[e],e)}return Sl[e]}a(BH,"getHTTPServer");function gR(e,t){let r=hse;for(let s=e.length;s>0;){let{listener:n,port:i}=e[--s];if(i===t||i==="all"){let o=r;r=a(c=>n(c,o),"next_callback")}}return r}a(gR,"makeCallbackChain");function hse(e){return e.user&&(e[Ti].user=e.user),{status:-1,body:"Not found",headers:new _se}}a(hse,"unhandled");function mse(e,t){NR(e,{requestOnly:!0,...t})}a(mse,"onRequest");function pse(e,t){if(t.securePort){let r=Ws.get("customfunctions_tls_privatekey"),s=Ws.get("customfunctions_tls_certificate"),n=Ws.get("customfunctions_tls_certificateauthority"),i=use({key:$a(r),cert:$a(s)+(n?`
|
|
27
|
+
`+$a(c):""),ticketKeys:lse()}}Sl[e]=(t?ase:ise)(s,async(n,i)=>{try{let o=new Of(n);r&&(o.isOperationsServer=!0);let c=await Af[e](o);if(c.headers?.set?.("Server","HarperDB"),c.status===-1){for(let l of c.headers||[])i.setHeader(l[0],l[1]);return n.baseRequest=o,i.baseResponse=c,Sl[e].emit("unhandled",n,i)}c.handlesHeaders||i.writeHead(c.status||200,c.headers&&(c.headers[Symbol.iterator]?Array.from(c.headers):c.headers));let u=c.body;u?.pipe?(u.pipe(i),u.destroy&&i.on("close",()=>{u.destroy()})):u?.then?u.then(l=>{i.end(l)},l=>{i.writeHead(l.statusCode||500),i.end(l.toString()),Rf.error(l)}):i.end(u)}catch(o){i.writeHead(o.statusCode||500),i.end(o.toString()),Rf.error(o)}}),OR(Sl[e],e)}return Sl[e]}a(BH,"getHTTPServer");function gR(e,t){let r=hse;for(let s=e.length;s>0;){let{listener:n,port:i}=e[--s];if(i===t||i==="all"){let o=r;r=a(c=>n(c,o),"next_callback")}}return r}a(gR,"makeCallbackChain");function hse(e){return e.user&&(e[Ti].user=e.user),{status:-1,body:"Not found",headers:new _se}}a(hse,"unhandled");function mse(e,t){NR(e,{requestOnly:!0,...t})}a(mse,"onRequest");function pse(e,t){if(t.securePort){let r=Ws.get("customfunctions_tls_privatekey"),s=Ws.get("customfunctions_tls_certificate"),n=Ws.get("customfunctions_tls_certificateauthority"),i=use({key:$a(r),cert:$a(s)+(n?`
|
|
28
28
|
|
|
29
29
|
`+$a(n):"")},e);gi[t.securePort]=o=>{i.emit("connection",o)}}t.port&&(gi[t.port]=e)}a(pse,"onSocket");Object.defineProperty(ose.prototype,"upgrade",{get(){return"connection"in this.headers&&"upgrade"in this.headers&&this.headers.connection.startsWith("Upgrade")&&this.headers.upgrade.toLowerCase()=="websocket"},set(e){}});function Sse(e,t){for(let{port:r,secure:s}of vH(t)){SR[r]||(SR[r]=new cse({server:BH(r,s)}),SR[r].on("connection",async(i,o)=>{let c=new Of(o);c.isWebSocket=!0;let u=Af[r](c),l=c.headers["sec-websocket-protocol"]||"";for(let _=0;_<pR.length;_++){let d=pR[_];if(d.protocol){if(d.protocol===l){d.listener(i,c,u);break}}else d.listener(i,c,u)}}));let n=t?.subProtocol||"";pR.push({listener:e,protocol:n}),Af[r]=gR(TR,r)}}a(Sse,"onWebSocket");function PH(e,t){t.writeHead(404),t.end(`Not found
|
|
30
30
|
`)}a(PH,"defaultNotFound");var Ti=Symbol("node request"),Of=class{static{a(this,"Request")}[Ti];#e;constructor(t){this.method=t.method;let r=t.url;this[Ti]=t,this.url=r,this.headers=t.headers,this.headers.get=Tse}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[Ti].socket.encrypted?"https":"http"}get ip(){return this[Ti].socket.remoteAddress}get body(){return this.#e||(this.#e=new RR(this[Ti]))}get host(){return this[Ti].authority||this[Ti].headers.host}get isAborted(){return!1}},RR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}};function Tse(e){return this[e.toLowerCase()]}a(Tse,"get")});var DR={};Ke(DR,{debugMode:()=>kH,startHTTPThreads:()=>Rse,startSocketServer:()=>CR,updateWorkerIdleness:()=>$H});async function Rse(e=2,t){if(t)IR(0,1,!0);else{let{loadRootComponents:r}=yf();if(e===0||kH)return(0,Ri.setMainIsWorker)(!0),bR=HH(),await r(!0),Promise.resolve([]);await r()}for(let r=0;r<e;r++)IR(r,e);return Promise.all(xH)}function IR(e,t=1,r){if(yR++,(0,Ri.startWorker)("server/threads/threadServer.js",{name:Cf.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(s){let n=new Promise((o,c)=>{function u(l){l.type===Cf.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(s.removeListener("message",u),o(s))}a(u,"onMessage"),s.on("message",u),s.on("error",c)});xH.push(n),await n,Ya.push(s),s.expectedIdle=1,s.lastIdle=0,s.requests=1,s.on("message",o=>{if(o.requestId){let c=wf.get(o.requestId);c&&c(o)}}),s.on("exit",i),s.on("shutdown",i);function i(){let o=Ya.indexOf(s);o>-1&&Ya.splice(o,1)}if(a(i,"removeWorker"),Ka){let o=Ka;Ka=[];for(let c of o)GH[c.localPort](c)}}}),r){let s=setInterval(()=>{wR?wR=!1:(clearInterval(s),console.log("shut down dynamic thread due to inactivity"),(0,Ri.shutdownWorkers)(),yR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function CR(e=0,t){if(typeof e=="string")try{(0,Df.existsSync)(e)&&(0,Df.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=Ase:r=Ose(t):r=LR;let s=(0,FH.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData},GH[e]=i=>{wR=!0,r(i,(o,c)=>{if(!o){bR?(bR.deliverSocket(i,e,c),i.resume()):yR>0?(Ka.length===0&&setTimeout(()=>{Ka.length>0&&console.warn("Incoming sockets/requests have been queued for workers to start, and no workers have handled them. Check to make sure an error is not preventing workers from starting")},1e4).unref(),Ka.push(i)):(console.log("start up a dynamic thread to handle request"),IR(0));return}o.requests++;let u=i._handle.fd;Lf.trace("Socket",u,"from",i.remoteAddress," routed to worker",o.threadId),u>=0?o.postMessage({port:e,fd:u,data:c}):yse(i,o,e)})}).listen(e);s.on("error",i=>{console.error("Error in socket server",i)}),process.env._UNREF_SERVER&&s.unref();let n=ki();return Lf.info(`HarperDB ${n.version} Server running on port ${e}`),s}function LR(e,t){let r,s=0;for(let n of Ya){if(n.threadId===-1)continue;let i=n.expectedIdle/n.requests;if(i>s)r=n;else if(s>=If)return If=i,t(r);s=i}If=0,t(r)}function Ase(e,t){let r=e.remoteAddress,s=Wa.get(r),n=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=n,t(s.worker);LR(e,i=>{Wa.set(r,{worker:i,lastUsed:n}),t(i)})}function Ose(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(s,n){s.on("data",i=>{s._handle.readStop();let c=i.toString("latin1").match(t)?.[1],u=Wa.get(c),l=Date.now();if(u&&u.worker.threadId!==-1)return u.lastUsed=l,n(u.worker);LR(s,_=>{Wa.set(c,{worker:_,lastUsed:l}),n(_,i)})})}a(r,"findByHeaderAffinity")}function $H(){If=0;for(let e of Ya)e.expectedIdle=e.recentELU.idle+Nse,e.requests=1;Ya.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function yse(e,t,r){let s=bse++;t.postMessage({port:r,requestId:s,event:"connection"}),e.on("data",n=>{let i=n.toString("latin1");t.postMessage({port:r,requestId:s,data:i,event:"data"})}).on("close",n=>{t.postMessage({port:r,requestId:s,event:"close",hadError:n})}).on("error",n=>{t.postMessage({port:r,requestId:s,event:"error",error:n})}).on("drain",n=>{t.postMessage({port:r,requestId:s,event:"drain",error:n})}).on("end",()=>{t.postMessage({port:r,requestId:s,event:"end"})}).resume(),wf.set(s,n=>{n.event=="data"&&e.write(Buffer.from(n.data,"latin1")),n.event=="end"&&(e.end(n.data&&Buffer.from(n.data,"latin1")),wf.delete(s)),n.event=="destroy"&&(e.destroy(),wf.delete(s))})}var Ri,FH,Cf,Lf,Df,gse,Ya,Ka,GH,bR,yR,xH,kH,wR,If,qH,Wa,Nse,wf,bse,Uf=Te(()=>{Ri=D(tt()),FH=require("net"),Cf=D(R()),Lf=D(C()),Df=require("fs"),{isMainThread:gse}=require("worker_threads"),Ya=[],Ka=[],GH=[],yR=0,xH=[];gse&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&console.error("uncaughtException",e)});a(Rse,"startHTTPThreads");a(IR,"startHTTPWorker");a(CR,"startSocketServer");If=0;a(LR,"findMostIdleWorker");qH=36e5,Wa=new Map;a(Ase,"findByRemoteAddressAffinity");a(Ose,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Wa)r.lastUsed+qH<e&&Wa.delete(t)},qH).unref();Nse=1e3;a($H,"updateWorkerIdleness");(0,Ri.setMonitorListener)($H);wf=new Map,bse=1;a(yse,"proxySocket")});var QH=m((cge,WH)=>{"use strict";var Ise=require("cluster"),ps=Y();ps.initSync();var YH=R(),ige=require("util"),Hn=C(),UR=require("fs"),wse=require("fastify"),oge=ki(),Cse=require("@fastify/cors"),Lse=require("@fastify/compress"),Dse=require("@fastify/static"),Use=Hg(),Mse=require("path"),{PACKAGE_ROOT:Pse}=R(),vse=$r(),Bse=F(),Hse=er(),qse=jc(),{server:Fse}=(rs(),re(Pc)),{authHandler:Gse,handlePostRequest:xse,serverErrorHandler:kse,reqBodyValidationHandler:$se}=gf(),age=require("net"),{registerContentHandlers:Vse}=(Da(),re(Gv)),Yse=1024*1024*1024,KH="TRUE",{HDB_SETTINGS_NAMES:Io,CONFIG_PARAMS:Kse}=YH,Wse=Io.CORS_ENABLED_KEY,Qse="CORS_ACCESSLIST",zse=Io.SERVER_TIMEOUT_KEY,Jse=Io.SERVER_KEEP_ALIVE_TIMEOUT_KEY,jse=Io.SERVER_HEADERS_TIMEOUT_KEY,Xse=Io.PRIVATE_KEY_KEY,Zse=Io.CERT_KEY,ene=Io.HTTP_SECURE_ENABLED_KEY,yo;WH.exports={hdbServer:VH,start:VH};async function VH(e){try{Hn.info("In Fastify server"+process.cwd()),Hn.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Hn.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=Ise.isMaster,await tne();let t=ps.get(ene),r=t&&(t===!0||t.toUpperCase()===KH);yo=rne(r),await yo.ready(),e||(e={}),e.isOperationsServer=!0,yo.server.cantCleanupProperly=!0;try{Fse.http(yo.server,e),yo.server.closeIdleConnections||await yo.listen({port:0,host:"::"})}catch(s){throw yo.close(),Hn.error(s),Hn.error(`Error configuring ${server_type} server`),s}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Hn.fatal(t),process.exit(1)}}a(VH,"operationsServer");async function tne(){Hn.trace("Configuring HarperDB process."),vse.setSchemaDataToGlobal(),await Hse.setUsersToGlobal(),await qse.getLicense()}a(tne,"setUp");function rne(e){Hn.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=sne(e),r=wse(t);r.server.headersTimeout=ine(),r.setErrorHandler(kse);let s=nne();s&&r.register(Cse,s),r.register(function(i,o,c){i.setNotFoundHandler(function(u,l){r.server.emit("unhandled",u.raw,l.raw)}),c()}),r.register(Use),r.register(Lse),r.register(Dse,{root:Mse.join(Pse,"docs")}),Vse(r);let n=ps.get(YH.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!Bse.isEmpty(n)&&n.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.callNotFound()}),r.post("/",{preValidation:[$se,Gse],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),xse(i,o)}),r.get("/health",()=>"HarperDB is running."),Hn.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(rne,"buildServer");function sne(e){let t=ps.get(zse),r=ps.get(Jse),s={bodyLimit:Yse,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1};if(e){let n=ps.get(Xse),i=ps.get(Zse),o=ps.get(Kse.OPERATIONSAPI_TLS_CERT_AUTH),c={allowHTTP1:!0,key:UR.readFileSync(n),cert:UR.readFileSync(i)+(o?`
|
|
31
31
|
|
|
32
|
-
`+UR.readFileSync(o):"")};s.http2=!0,s.https=c}return s}a(sne,"getServerOptions");function nne(){let e=ps.get(Wse),t=ps.get(Qse),r;return e&&(e===!0||e.toUpperCase()===KH)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(s,n)=>n(null,t.indexOf(s)!==-1))),r}a(nne,"getCORSOpts");function ine(){return ps.get(jse)}a(ine,"getHeaderTimeoutConfig")});var oq=m((dge,iq)=>{"use strict";var{decode:one}=require("msgpackr"),{isMainThread:ane,parentPort:cne,threadId:lge}=require("worker_threads"),MR=Qe(),Qa=Me(),une=R(),gl=C(),zH=Y(),XH=R();tt();var lne=mn(),{recordAction:_ne,recordActionBinary:dne}=(co(),re(Nd)),{publishToStream:Ene}=MR,_ge={durable:Qa.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:Qa.WORK_QUEUE_CONSUMER_NAMES.deliver_group},fne,hne,mne,ZH,eq;iq.exports={initialize:tq,workQueueListener:nq,setSubscription:pne,setIgnoreOrigin:Tne,getDatabaseSubscriptions:Sne};async function tq(){eq=!0,gl.notify("Starting clustering ingest service.");let{connection:e,jsm:t,js:r}=await MR.getNATSReferences();fne=e,hne=e.info.server_name,mne=t,ZH=r}a(tq,"initialize");var Pf=new Map;function pne(e,t,r){let s=Pf.get(e);s||Pf.set(e,s=new Map),s.set(t,r),eq||tq().then(nq)}a(pne,"setSubscription");function Sne(){return Pf}a(Sne,"getDatabaseSubscriptions");var rq;function Tne(e){rq=e}a(Tne,"setIgnoreOrigin");var sq=100,JH=new Array(sq),Mf=0;async function nq(){let t=await(await ZH.consumers.get(Qa.WORK_QUEUE_CONSUMER_NAMES.stream_name,Qa.WORK_QUEUE_CONSUMER_NAMES.durable_name)).consume();for await(let r of t)await JH[Mf],JH[Mf]=gne(r).catch(s=>{gl.error(s)}),++Mf>=sq&&(Mf=0)}a(nq,"workQueueListener");ane||cne.on("message",async e=>{let{type:t}=e;t===XH.ITC_EVENT_TYPES.SHUTDOWN&&MR.closeConnection()});async function gne(e){let t=one(e.data);_ne(e.data.length,"bytes-received",e.subject,t.operation,"ingest");let n=e.headers.get(Qa.MSG_HEADERS.ORIGIN)===zH.get(une.CONFIG_PARAMS.CLUSTERING_NODENAME)&&!rq;if(dne(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}try{let{operation:i,schema:o,next:c,table:u,records:l,hash_values:_,__origin:d}=t;gl.trace("processing message:",i,o,u,(l?"records: "+l.map(A=>A.id):"")+(_?"ids: "+_:""),"with sequence:",e.seq),gl.trace(`messageProcessor nats msg id: ${e.headers.get(Qa.MSG_HEADERS.NATS_MSG_ID)}`);let E;l||(l=_);let{timestamp:f,user:h,node_name:S}=d||{},T=Pf.get(o)?.get(u);if(!T)throw new Error("Missing table for replication message",u);if(i==="define_schema")t.type=i,T.send(t);else if(l.length===1&&!c)T.send({type:jH(i),value:l[0],id:_?.[0],timestamp:f,table:u,onCommit:E,user:h,nodeName:S});else{let A=l.map((g,x)=>({type:jH(i),value:g,id:_?.[x],table:u}));for(;c;)A.push({type:c.operation,value:c.record,id:c.id,table:c.table}),c=c.next;T.send({type:"transaction",writes:A,table:u,timestamp:f,onCommit:E,user:h,nodeName:S})}zH.get(XH.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&Ene(e.subject.split(".").slice(0,-1).join("."),lne.createNatsTableStreamName(o,u),e.headers,e.data)}catch(i){gl.error(i)}e.ack()}a(gne,"messageProcessor");function jH(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(jH,"convertOperation")});var FR={};Ke(FR,{disableNATS:()=>Ane,setNATSReplicator:()=>PR,start:()=>Rne});function Rne(){Bf.default.get(Hf.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&Nne()}function Ane(e=!0){_q=e}function Nne(){if(_q)return;let e=us(),t=Object.keys(e);t.push("system");for(let r of t){let s=e[r];for(let n in s){let i=s[n];PR(n,r,i)}}GR((r,s)=>{PR(r.tableName,r.databaseName,r),s&&Eq(r)}),!aq&&(aq=!0)}function PR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.Source?.isNATSReplicator)return;let s;r.sourcedFrom(class extends bt{static{a(this,"NATSReplicator")}put(o){let c;return s?.put&&(!s.put.reliesOnPrototype||s.prototype.put)&&(c=s.put(this[ue],o,this.getContext())),n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[ue],record:o},c)}delete(){let o;return s?.delete&&(!s.delete.reliesOnPrototype||s.prototype.delete)&&(o=s.delete(this[ue],this.getContext())),n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[ue]},o)}publish(o){let c;return s?.publish&&(!s.publish.reliesOnPrototype||s.prototype.publish)&&(c=s.publish(this[ue],o,this.getContext())),n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[ue],record:o},c)}invalidate(o){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[ue]})}static defineSchema(o){Eq(o)}static mergeSource(o,c){return s=o,s?.get&&(!s.get.reliesOnPrototype||s.prototype.get)&&(c?.replicationSource?this.get=async(u,l)=>{let _=await s.get(u,l);return _&&n(l).addWrite(t,{operation:"put",table:e,id:u,record:_}),_}:this.get=(u,l)=>s.get(u,l)),this}static subscribe(){let o=new ys;return(0,cq.setSubscription)(t,e,o),o}static subscribeOnThisThread(o){return o<One}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0});function n(i){let o=i?.transaction?.nats;return o||(i?.transaction?(i.transaction.push(o=i.transaction.nats=new vf(i.transaction,i)),o.user=i.user):o=dq),o}a(n,"getNATSTransaction")}function Eq(e){let t=Bf.default.get(Hf.default.CONFIG_PARAMS.CLUSTERING_NODENAME);(0,BR.publishToStream)(`${HR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,qR.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var BR,HR,qR,cq,uq,Bf,Hf,lq,_q,One,dq,aq,vf,vR,fq=Te(()=>{_e();Is();BR=D(Qe()),HR=D(Me()),qR=D(mn());Dc();cq=D(oq()),uq=D(Ht()),Bf=D(Y()),Hf=D(R()),lq=D(C());a(Rne,"start");a(Ane,"disableNATS");One=2;a(Nne,"assignReplicationSource");a(PR,"setNATSReplicator");a(Eq,"publishSchema");vf=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r,s){let n=this.writes_by_db.get(t);if(n||this.writes_by_db.set(t,n=[]),s?.then)return s.then(()=>n.push(r));n.push(r)}commit(t){let r=Bf.default.get(Hf.default.CONFIG_PARAMS.CLUSTERING_NODENAME),s=[];for(let[n,i]of this.writes_by_db){let o=[],c=[],u,l;for(let _ of i){let d=_.table,E=_.operation=="put"?"upsert":_.operation;u||(lq.trace(`Sending transaction event ${E}`),l=u={operation:E,schema:n,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,E!=="delete"&&(u.records=o)),u.table===d&&u.operation===E?(o.push(_.record),c.push(_.id)):l=l.next={operation:E,table:d,id:_.id,record:_.record}}s.push((0,BR.publishToStream)(`${HR.SUBJECT_PREFIXES.TXN}.${n}.${u.table}`,(0,qR.createNatsTableStreamName)(n,u.table),void 0,u))}return Promise.all(s)}},vR=class extends vf{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,uq.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit()}};dq=new vR});async function mq({clientId:e,user:t,listener:r,clean:s}){let n;if(e&&!s){let i=await xR.getResource(e,{});n=new $R(e,t,i),i&&(n.sessionWasPresent=!0)}else{if(e){let i=await xR.get(e);i&&i.delete()}n=new Ff(e,t)}return n}function kR(){return qf++,qf>65500&&(qf=1),qf}var hq,Rl,xR,qf,Ff,$R,pq=Te(()=>{_e();Qu();hq=D(Ht()),Rl=D(C());Yi();xR=ft({database:"system",table:"hdb_durable_session",attributes:[{name:"id",isPrimaryKey:!0},{name:"subscriptions",type:"array",elements:{attributes:[{name:"topic"},{name:"qos"},{name:"startTime"},{name:"acks"}]}}]});a(mq,"getSession");qf=1;a(kR,"getNextMessageId");Ff=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,s){let{topic:n,omitCurrent:i,startTime:o}=t,c=n.indexOf("?"),u,l;if(c>-1?(u=n.slice(c),l=n.slice(0,c)):l=n,!l)throw new Error("No topic provided");let _=!1,d;if((l.endsWith("+")||l.endsWith("#"))&&(_=!0,l.endsWith("+")&&(d=!0),l=l.slice(0,l.length-1)),l.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");if(l.indexOf("#")>-1||l.indexOf("+")>-1)throw new Error("Only trailing wildcards are supported");let E=this.subscriptions.find(g=>g.topic===n);E&&(E.end(),this.subscriptions.splice(this.subscriptions.indexOf(E),1));let f={search:u,user:this.user,startTime:o,omitCurrent:i,isCollection:_,shallowWildcard:d,url:""},h=hi.getMatch(l);if(!h)throw new Error(`The topic ${n} does not exist, no resource has been defined to handle this topic`);f.url=h.relativeURL;let S=h.path,T=h.Resource,A=await Xe(f,async()=>{let g=await T.subscribe(f);if(!g)throw new Error(`No subscription was returned from subscribe for topic ${n}`);if(!g[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${n}`);return(async()=>{for await(let x of g)try{let V;if(x.type&&x.type!=="put"&&x.type!=="delete"&&x.type!=="message"||s&&!s(x))continue;r?(x.topic=n,V=this.needsAcknowledge(x)):V=kR();let I=x.id;Array.isArray(I)&&(I=Ca(I)),I==null&&(I=""),this.listener(S+"/"+I,x.value,V,t)}catch(V){(0,Rl.warn)(V)}})(),g});return A.topic=n,A.qos=t.qos,this.subscriptions.push(A),A}resume(){}needsAcknowledge(t){return kR()}acknowledge(t){}async removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t);r&&r.end()}async publish(t,r){let{topic:s,retain:n}=t;t.data=r,t.user=this.user;let i=hi.getMatch(s);if(!i)throw new Error(`Can not publish to topic ${s} as it does not exist, no resource has been defined to handle this topic`);t.url=i.relativeURL;let o=i.Resource;return Xe(t,()=>n?r===void 0?o.delete(t,t):o.put(t,t.data,t):o.publish(t,t.data,t))}setListener(t){this.listener=t}disconnect(){for(let t of this.subscriptions)t.end();this.subscriptions=[]}},$R=class extends Ff{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,s){super(t,r),this.sessionRecord=s||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.timestamp):null)}resumeSubscription(t,r,s){return super.addSubscription(t,r,s)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=kR();return this.awaitingAcks.set(r,{topic:t.topic,timestamp:t.timestamp}),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t);let s=r.topic;for(let[,n]of this.awaitingAcks)if(n.topic===s&&n.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===s){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,Rl.trace)("Received ack",s,r.timestamp),this.sessionRecord.update();return}}for(let n of this.sessionRecord.subscriptions)n.topic===s&&(n.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:s,startTime:n}=t;return s>0&&!n&&(this.sessionRecord.subscriptions=this.subscriptions.map(i=>{let o=i.startTime;return o||(o=i.startTime=(0,hq.getNextMonotonicTime)()),(0,Rl.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),xR.put(this.sessionRecord)),t.qos}}});var KR={};Ke(KR,{start:()=>yne});async function yne({server:e,port:t,webSocket:r,securePort:s,requireAuthentication:n}){let i=e.mqtt={requireAuthentication:n};r&&e.ws((o,c,u)=>{if(o.protocol==="mqtt"){let{onMessage:l,onClose:_}=gq(o,(d,E)=>{if(o.send(d),E&&o._socket.writableNeedDrain)return new Promise(f=>this._socket.once("drain",f))},c,Promise.resolve(u).then(()=>c?.user),i);o.on("message",l),o.on("close",_),o.on("error",d=>{(0,qn.info)("WebSocket error",d)})}},{subProtocol:"mqtt"}),(t||s)&&e.socket(async o=>{let c;bne&&o.remoteAddress.includes("127.0.0.1")&&(c=await(0,Rq.getSuperUser)());let{onMessage:u,onClose:l}=gq(o,_=>o.write(_),null,c,i);o.on("data",u),o.on("close",l),o.on("error",_=>{(0,qn.info)("Socket error",_)})},{port:t,securePort:s})}function gq(e,t,r,s,n){Tq||(Tq=!0,DS(_=>{_.push({metric:"mqtt-connections",connections:VR})})),VR++;let i,o={protocolVersion:4},c=(0,Gf.parser)({protocolVersion:5});function u(_){c.parse(_)}a(u,"onMessage");function l(){VR--,i?.disconnect()}return a(l,"onClose"),c.on("packet",async _=>{s?.then&&(s=await s),i?.then&&await i;try{switch(_.cmd){case"connect":if(o.protocolVersion=_.protocolVersion,_.username)try{s=await Et.auth(_.username,_.password.toString()),(0,YR.get)(Fn.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&Sq.notify({username:s.username,status:Fn.AUTH_AUDIT_STATUS.SUCCESS,type:Fn.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,YR.get)(Fn.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&Sq.error({username:s.username,status:Fn.AUTH_AUDIT_STATUS.FAILURE,type:Fn.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),d({cmd:"connack",reasonCode:134,returnCode:134})}if(!s&&n.requireAuthentication)return d({cmd:"connack",reasonCode:134,returnCode:134});try{n.authorizeClient?.(_,s),i=mq({user:s,..._}),i=await i}catch(g){return(0,qn.error)(g),d({cmd:"connack",reasonCode:g.code||128,returnCode:g.code||128})}d({cmd:"connack",sessionPresent:i.sessionWasPresent,reasonCode:0,returnCode:0}),i.setListener((g,x,V,I)=>{try{let b=g.indexOf("/",1),M=b>0?g.slice(0,b):g;d({cmd:"publish",topic:g,payload:E(x),messageId:V||Math.floor(Math.random()*1e8),qos:I.qos},M)}catch(b){(0,qn.error)(b),i?.disconnect()}}),i.sessionWasPresent&&await i.resume();break;case"subscribe":let f=[];for(let g of _.subscriptions){let x;try{x=(await i.addSubscription(g,g.qos>=1)).qos||0}catch(V){(0,qn.error)(V),x=128}f.push(x)}await i.committed,d({cmd:"suback",granted:f,messageId:_.messageId});break;case"unsubscribe":for(let g of _.unsubscriptions)i.removeSubscription(g);d({cmd:"unsuback",messageId:_.messageId});break;case"pubrel":d({cmd:"pubcomp",messageId:_.messageId,reasonCode:0});return;case"publish":let h=_.qos===2?"pubrec":"puback",S=e.deserialize||(e.deserialize=Ba(r?.headers["content-type"])),T=_.payload?.length>0?S(_.payload):void 0,A;try{A=await i.publish(_,T)}catch(g){console.warn(g),_.qos>0&&d({cmd:h,messageId:_.messageId,reasonCode:128},_.topic)}_.qos>0&&d({cmd:h,messageId:_.messageId,reasonCode:A===!1?144:0},_.topic);break;case"pubrec":d({cmd:"pubrel",messageId:_.messageId,reasonCode:0});break;case"pubcomp":case"puback":i.acknowledge(_.messageId);break;case"pingreq":d({cmd:"pingresp"});break;case"disconnect":i?.disconnect(),e.close?e.close():e.end();break}}catch(f){console.error(f),d({cmd:"disconnect"})}function d(f,h){let S=(0,Gf.generate)(f,o);t(S),qs(S.length,"bytes-sent",h,f.cmd,"mqtt")}a(d,"sendPacket");function E(f){return r?Cn(f,r):JSON.stringify(f)}a(E,"serialize")}),{onMessage:u,onClose:l}}var Gf,Rq,YR,Fn,qn,Sq,bne,Tq,VR,Aq=Te(()=>{Gf=require("mqtt-packet");pq();Rq=D(er());Da();co();rs();YR=D(Y()),Fn=D(R()),qn=D(C()),Sq=(0,qn.loggerWithTag)("auth-event"),bne=!0;a(yne,"start");VR=0;a(gq,"onSocket")});var Uq={};Ke(Uq,{loadComponent:()=>xf,loadComponentDirectories:()=>Dq});function Dq(e,t){t&&(QR=t),e&&(zR=e);let r=[];if((0,Qs.existsSync)(WR)){let n=(0,Qs.readdirSync)(WR,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,Zr.join)(WR,o);r.push(xf(c,QR,"hdb",!1))}}let s=process.env.RUN_HDB_APP;return s&&r.push(xf(s,QR,s)),Promise.all(r).then(()=>{Lq=!0})}async function xf(e,t,r,s,n){if(!Nq.has(e)){Nq.set(e,!0),n&&(zR=n);try{let i,o=(0,Zr.join)(e,s?"harperdb-config.yaml":"config.yaml");(0,Qs.existsSync)(o)?i=(0,bq.parseDocument)((0,Qs.readFileSync)(o,"utf8"),{simpleKeys:!0}).toJSON():i=Lne;let c=[];for(let u in i){let l=i[u];if(!l)continue;let _,d=l.package;if(d){let E=e,f;for(;!(0,Qs.existsSync)(f=(0,Zr.join)(E,"node_modules",u));)if(E=(0,Zr.dirname)(E),E.length<(0,Cq.getHdbBasePath)().length){f=null;break}if(f)_=await xf(f,t,r,!1);else throw new Error(`Unable to find package ${u}:${d}`)}else _=Cne[u];if(_)try{c.push(_);let E=a(T=>(T.origin=r,ft(T)),"ensureTable"),f=l.network||(l.port||l.securePort)&&l,h=f?.securePort||f?.https&&f.port,S=!f?.https&&f?.port;if(Al.isMainThread&&(_=await _.startOnMainThread?.({server:Et,ensureTable:E,port:S,securePort:h,resources:t,...l})||_,s&&f))for(let T of[S,h])try{if(+T&&!Oq.includes(T)){Oq.push(T);let A=JR.get(jR.CONFIG_PARAMS.HTTP_SESSION_AFFINITY);CR(T,A)}}catch(A){console.error("Error listening on socket",T,A,u)}if(t.isWorker&&(_=await _.start?.({server:Et,ensureTable:E,port:S,securePort:h,resources:t,...l})||_),zR.set(_,!0),_.handleFile&&l.files){if(l.files.includes(".."))throw(0,wq.handleHDBError)("Can not reference parent directories");let T=(0,Zr.join)(e,l.files);for(let A of await(0,yq.default)(T,{onlyFiles:!1,objectMode:!0})){let{path:g,dirent:x}=A,V=(0,Zr.relative)(e,g),I=(0,Zr.basename)(e),b=l.path||"/";b=b.startsWith("/")?b:b.startsWith("./")?"/"+I+b.slice(2):b==="."?"/"+I:"/"+I+"/"+b,b+=(b.endsWith("/")?"":"/")+V;try{if(x.isFile()){let M=await wne(g);Al.isMainThread&&await _.setupFile?.(M,b,g,t),t.isWorker&&await _.handleFile?.(M,b,g,t)}else Al.isMainThread&&await _.setupDirectory?.(b,g,t),t.isWorker&&await _.handleDirectory?.(b,g,t)}catch(M){console.error(`Could not load ${x.isFile()?"file":"directory"} ${g} using ${l.module} for application ${e}`,M),t.set(l.path||"/",new Ol(M))}}}}catch(E){console.error(`Could not load component ${u} for application ${e}`,E),t.set(l.path||"/",new Ol(E),null,!0)}}if(Al.isMainThread&&!Lq&&(0,Iq.watchDir)(e,async()=>Dq()),i.extensionModule)return await A_((0,Zr.join)(e,i.extensionModule))}catch(i){console.error(`Could not load application directory ${e}`,i),t.set("",new Ol(i))}}}var Qs,Zr,Al,bq,JR,jR,yq,Iq,wq,Cq,Ine,wne,WR,zR,Lq,QR,Cne,Lne,Oq,Nq,Ol,Mq=Te(()=>{Qs=require("fs"),Zr=require("path"),Al=require("worker_threads"),bq=require("yaml"),JR=D(Y()),jR=D(R());qN();kN();$N();$v();wH();UH();yq=D(require("fast-glob")),Iq=D(tt());lm();rs();wq=D(z());Is();_e();Uf();Cq=D(Y()),Ine=D(QH());DE();fq();Aq();({readFile:wne}=Qs.promises),WR=JR.get(jR.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),zR=new Map;a(Dq,"loadComponentDirectories");Cne={REST:Bg,graphqlSchema:um,jsResource:dm,fastifyRoutes:hR,login:fm,static:mR,operationsApi:Ine,customFunctions:{},clustering:FR,authentication:zu,mqtt:KR},Lne={REST:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}},Oq=[],Nq=new Map;a(xf,"loadComponent");Ol=class extends bt{constructor(r){super();this.error=r}static{a(this,"ErrorResource")}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var Fq=m((Gge,qq)=>{"use strict";var Vf=require("fs-extra"),XR=require("path"),kf=C(),Pq=F(),$f=R(),Hq=Y(),Dne=et();qq.exports=Une;async function Une(){let e=Mne(),t=Hq.get($f.CONFIG_PARAMS.ROOTPATH),r=XR.join(t,"package.json"),s={dependencies:{harperdb:"file:"+$f.PACKAGE_ROOT}},n=XR.join(t,"node_modules");await Vf.ensureDir(n);let i,o=!0,c=!1;try{i=await Vf.readJson(r)}catch(u){if(Pq.isEmptyOrZeroLength(e))return;if(u.code!==$f.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!Pq.isEmptyOrZeroLength(e)){for(let{name:u,package:l}of e){let _=await vq(l);s.dependencies[u]=_+l}if(!o){kf.notify("Installing components"),await Bq(r,s);return}for(let{name:u,package:l}of e){let _=i.dependencies[u],d=await vq(l);if(_===void 0||_!==d+l){c=!0;break}}}for(let u in i.dependencies)s.dependencies[u]===void 0&&(kf.notify("Removing component",u),c=!0);c&&(kf.notify("Updating components."),await Bq(r,s))}a(Une,"installComponents");function Mne(){let e=Dne.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(Mne,"getComponentsConfig");async function vq(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":XR.extname(e)||await Vf.pathExists(e)?"file:":"github:"}a(vq,"getPkgPrefix");async function Bq(e,t){kf.trace("npm installing components package.json",t),await Vf.writeFile(e,JSON.stringify(t,null," ")),await GE().installAllRootModules(Hq.get($f.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}a(Bq,"installPackages")});var yf=m((kge,xq)=>{var{isMainThread:Gq}=require("worker_threads"),{getTables:Pne}=(_e(),re(be)),{loadComponentDirectories:vne,loadComponent:Bne}=(Mq(),re(Uq)),{resetResources:Hne}=(Qu(),re(SP)),qne=Fq(),Fne=et(),{dirname:Gne}=require("path"),{getConnection:xne}=Qe(),kne=Y(),$ne=R(),ZR=new Map;async function Vne(e=!1){!Gq&&kne.get($ne.CONFIG_PARAMS.CLUSTERING_ENABLED)&&xne(),Gq&&await qne();let t=Hne();Pne(),t.isWorker=e,await Bne(Gne(Fne.getConfigFilePath()),t,"hdb",!0,ZR),await vne(ZR,t);let r=[];for(let[s]of ZR)s.ready&&r.push(s.ready());r.length>0&&await Promise.all(r)}a(Vne,"loadRootComponents");xq.exports.loadRootComponents=Vne});var tt=m((Yge,Ni)=>{"use strict";var{Worker:Yne,MessageChannel:Kne,parentPort:zs,isMainThread:nA,threadId:Wne,workerData:Nl}=require("worker_threads"),{PACKAGE_ROOT:Qne}=R(),{join:Vq,isAbsolute:zne,extname:Kf}=require("path"),{server:Jne}=(rs(),re(Pc)),{watch:jne,readdir:Xne}=require("fs/promises"),{totalmem:kq}=require("os"),iA=R(),wo=C(),Vge=R(),{randomBytes:Zne}=require("crypto"),eie=1024*1024,Oi=[],Ai=[],tie=50,Yq=1e4,rie="restart",Kq="request_thread_info",Wq="resource_report",Qq="thread_info",zq="added-port",sie="ack",eA;Ni.exports={startWorker:tA,restartWorkers:oA,shutdownWorkers:aie,workers:Oi,setMonitorListener:hie,onMessageFromWorkers:cie,onMessageByType:uie,broadcast:lie,broadcastWithAcknowledgement:die,setChildListenerByType:oie,getWorkerIndex:jq,getTicketKeys:Xq,setMainIsWorker:nie,restartNumber:Nl?.restartNumber||1};var Jq;function jq(){return Nl?Nl.workerIndex:Jq?0:void 0}a(jq,"getWorkerIndex");function nie(e){Jq=e}a(nie,"setMainIsWorker");var Yf;function Xq(){return Yf||(Yf=nA?Zne(48):Nl.ticketKeys,Yf)}a(Xq,"getTicketKeys");Object.defineProperty(Jne,"workerIndex",{get(){return jq()}});var Zq={[Kq](e,t){Eie(t)},[Wq](e,t){fie(t,e)}};function tA(e,t={}){let r=process.constrainedMemory?.()||kq();r=Math.min(r,kq());let s=Math.max(Math.floor(r/eie/(1+(t.threadCount||1)/4)),512),n=Math.min(Math.max(s>>7,16),64),i=[];for(let c of Ai){let{port1:u,port2:l}=new Kne;c.postMessage({type:zq,port:u},[u]),i.push(l)}Kf(e)||(e+=".js");let o=new Yne(zne(e)?e:Vq(Qne,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:s,maxYoungGenerationSizeMb:n},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:i,workerIndex:t.workerIndex,name:t.name,restartNumber:Ni.exports.restartNumber,ticketKeys:Xq()},transferList:i},t));return Qf(o,!0),o.unexpectedRestarts=t.unexpectedRestarts||0,o.startCopy=()=>{tA(e,t)},o.on("error",c=>{console.error("Worker error:",c),wo.error("Worker error:",c)}),o.on("exit",c=>{Oi.splice(Oi.indexOf(o),1),!o.wasShutdown&&t.autoRestart!==!1&&(o.unexpectedRestarts<tie?(t.unexpectedRestarts=o.unexpectedRestarts+1,tA(e,t)):wo.error(`Thread has been restarted ${o.restarts} times and will not be restarted`))}),o.on("message",c=>{Zq[c.type]?.(c,o)}),Oi.push(o),pie(),t.onStarted&&t.onStarted(o),o.name=t.name,o}a(tA,"startWorker");var iie=[iA.THREAD_TYPES.HTTP];async function oA(e=null,t=2,r=!0){if(nA){if(r){let{loadRootComponents:n}=yf();await n()}Ni.exports.restartNumber++,t<1&&(t=t*Oi.length);let s=[];for(let n of Oi.slice(0)){if(e&&n.name!==e||n.wasShutdown)continue;n.postMessage({restartNumber:Ni.exports.restartNumber,type:iA.ITC_EVENT_TYPES.SHUTDOWN}),n.wasShutdown=!0,n.emit("shutdown",{});let i=iie.indexOf(n.name)>-1,o=new Promise(c=>{let u=setTimeout(()=>n.terminate(),Yq*2).unref();n.on("exit",()=>{clearTimeout(u),s.splice(s.indexOf(o)),!i&&r&&n.startCopy(),c()})});s.push(o),i&&r&&(n.startCopy(),s.length>=t&&await Promise.race(s))}await Promise.all(s)}else zs.postMessage({type:rie,workerType:e})}a(oA,"restartWorkers");function oie(e,t){Zq[e]=t}a(oie,"setChildListenerByType");function aie(e){return oA(e,1/0,!1)}a(aie,"shutdownWorkers");var e0=[];function cie(e){e0.push(e)}a(cie,"onMessageFromWorkers");var rA=new Map;function uie(e,t){let r=rA.get(e);r||rA.set(e,r=[]),r.push(t)}a(uie,"onMessageByType");function lie(e){for(let t of Ai)try{t.postMessage(e)}catch(r){wo.error("Unable to send message to worker",r)}}a(lie,"broadcast");var Wf=new Map,_ie=1;function die(e){return new Promise(t=>{let r=0;for(let s of Ai)try{let n=_ie++,i=a(()=>{Wf.delete(n),--r===0&&t(),s!==zs&&--s.refCount===0&&s.unref()},"ack_handler");i.port=s,s.ref(),s.refCount=(s.refCount||0)+1,Wf.set(e.requestId=n,i),s.hasAckCloseListener||(s.hasAckCloseListener=!0,s.on(s.close?"close":"exit",()=>{for(let[,o]of Wf)o.port===s&&o()})),s.postMessage(e),r++}catch(n){wo.error("Unable to send message to worker",n)}r===0&&t()})}a(die,"broadcastWithAcknowledgement");function Eie(e){e.postMessage({type:Qq,workers:t0()})}a(Eie,"sendThreadInfo");function t0(){let e=Date.now();return Oi.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}a(t0,"getChildWorkerInfo");function fie(e,t){e.resources=t,e.resources.updated=Date.now()}a(fie,"recordResourceReport");var sA;function hie(e){sA=e}a(hie,"setMonitorListener");var mie=1e3,$q=!1;function pie(){$q||($q=!0,setInterval(()=>{for(let e of Oi){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}sA&&sA()},mie).unref())}a(pie,"startMonitoring");var Sie=1e3;if(zs){Qf(zs);for(let e of Nl.addPorts)Qf(e);setInterval(()=>{let e=process.memoryUsage();zs.postMessage({type:Wq,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},Sie).unref(),eA=a(()=>new Promise((e,t)=>{zs.on("message",r),zs.postMessage({type:Kq});function r(s){s.type===Qq&&(zs.off("message",r),e(s.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else eA=t0;Ni.exports.getThreadInfo=eA;function Qf(e,t){Ai.push(e),e.on("message",r=>{if(r.type===zq)Qf(r.port);else if(r.type===sie){let s=Wf.get(r.id);s&&s()}else{for(let n of e0)n(r,e);let s=rA.get(r.type);if(s)for(let n of s)try{n(r,e)}catch(i){wo.error(i)}}}).on("close",()=>{Ai.splice(Ai.indexOf(e),1)}).on("exit",()=>{Ai.splice(Ai.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(Qf,"addPort");if(nA){let e,t,r=a(async(s,n)=>{n&&(e=n);for(let i of await Xne(s,{withFileTypes:!0}))i.isDirectory()&&r(Vq(s,i.name));for await(let{filename:i}of jne(s,{persistent:!1}))(Kf(i)===".ts"||Kf(i)===".js"||Kf(i)===".graphql")&&(t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await oA(),wo.info("Reloaded HarperDB components")},100))},"watch_dir");Ni.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else zs.on("message",async e=>{let{type:t}=e;t===iA.ITC_EVENT_TYPES.SHUTDOWN&&(Ni.exports.restartNumber=e.restartNumber,zs.unref(),setTimeout(()=>{wo.warn("Thread did not voluntarily terminate",Wne),process.exit(0)},Yq).unref())})});function _A(e){let t=e.auditStore=e.openDB(o0.AUDIT_STORE_NAME,gie);t.rootStore=e;let r=[];return t.addDeleteRemovalCallback=function(s,n){return r[s]=n,{remove(){delete r[s]}}},(0,c0.getWorkerIndex)()===0&&e.on("aftercommit",()=>{cA||(cA=setTimeout(()=>{if(cA=null,t.rootStore.status!=="closed")for(let{key:s,value:n}of t.getRange({start:[0,0],end:[Date.now()-r0,0]})){if((n[0]&15)===lA){let i=s[1];r[i]?.(s[2])}t.remove(s)}},r0/10).unref())}),t}function jf(e,t,r){let s=_0[r.type],n=3;if(t?t.length>80?(s|=zf,n=(0,Gn.writeKey)(t,Js,e?14:6),aA.setUint16(2,n)):(n=(0,Gn.writeKey)(t,Js,e?11:3),Js[1]=n):Js[1]=0,e){s|=l0;let i=s&zf?6:3;aA.setFloat64(i,e),t||(n=i+8)}return Js[0]=s,s&zf?aA.setUint16(4,0):Js[2]=0,r.value?Buffer.concat([Js.slice(0,n),r.value]):Js.subarray(0,n)}function bi(e,t){let r=e[0],s=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength)),n=r&zf,i=n?6:3,o;r&l0&&(o=s.getFloat64(i),i+=8);let c;n?c=s.getUint16(2):c=e[1];let u=r&uA?t.decoder.decode(e.subarray(c||i)):void 0;return{type:_0[r&7],value:u,lastVersion:o,get user(){return c?(0,Gn.readKey)(e,i,c):void 0}}}var Gn,Jf,o0,a0,c0,u0,Js,aA,Tie,gie,r0,cA,uA,s0,lA,n0,i0,zf,l0,_0,bl=Te(()=>{Gn=require("ordered-binary"),Jf=D(Y()),o0=D(Ge()),a0=D(R()),c0=D(tt()),u0=D(F());(0,Jf.initSync)();Js=Buffer.alloc(1024),aA=new DataView(Js.buffer,Js.byteOffset,1024),Tie={writeKey(e,t,r){if(Array.isArray(e)){let s=t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength));return s.setFloat64(r,e[0]),s.setUint32(r+8,e[1]),(0,Gn.writeKey)(e[2],t,r+12)}else return(0,Gn.writeKey)(e,t,r)},readKey(e,t,r){if(e[t]>40){let s=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength));return[s.getFloat64(t),s.getUint32(t+8),(0,Gn.readKey)(e,t+12,r)]}else return(0,Gn.readKey)(e,t,r)}},gie={encoding:"binary",keyEncoder:Tie},r0=(0,u0.convertToMS)((0,Jf.get)(a0.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,cA=null;a(_A,"openAuditStore");uA=16,s0=1,lA=2,n0=3,i0=4,zf=128,l0=64,_0={put:s0|uA,[s0]:"put",delete:lA,[lA]:"delete",message:n0|uA,[n0]:"message",invalidate:i0,[i0]:"invalidate"};a(jf,"createAuditEntry");a(bi,"readAuditEntry")});var dA,Co,Rie,yl,Xf,d0=Te(()=>{dA=D(Ht());bl();Co=Symbol("completion"),Rie=100,yl=class{static{a(this,"DatabaseTransaction")}writes=[];hasWrittenTime;username;lmdbDb;auditStore;readTxn;constructor(t,r,s){this.lmdbDb=t,this.username=r?.username,this.auditStore=s}getReadTxn(){return this.readTxn||(this.readTxn=this.lmdbDb.useReadTransaction())}resetReadSnapshot(){this.readTxn&&(this.readTxn.done(),this.readTxn=null)}addWrite(t){this.writes.push(t)}validate(){for(let t of this.writes||[])t.validate?.()}commit(t=(0,dA.getNextMonotonicTime)(),r=!0,s=0){this.resetReadSnapshot();let n,i=[],o=0,c;this.hasWrittenTime=!1;let u=a(_=>{let d=_.commit(t,s);if(d&&(d[Co]&&(i||(i=[]),i.push(d[Co])),c=_.store,this.auditStore)){d.user=this.username,d.lastVersion=_.lastVersion,d.newTxnTime&&!this.hasWrittenTime&&(t=d.newTxnTime),this.hasWrittenTime=!0;let E=[t,_.store.tableId,_.key];_.invalidated&&(E.invalidated=!0),this.auditStore.put(E,jf(_.lastVersion,this.username,d))}},"doWrite"),l=a(()=>{let _=this.writes[o++];if(_)if(_.key){let d=_.store.getEntry(_.key),E=s===0&&_.lastVersion!==void 0?_.lastVersion:_.lastVersion=d?.version??null,f=_.store.ifVersion(_.key,E,l);n=n||f}else l();else for(let d of this.writes)u(d)},"nextCondition");return this.writes.length<Rie>>s?l():(s=1,n=this.writes[0].store.transaction(()=>{for(let _ of this.writes)u(_);return!0})),n?.then(_=>_?(c&&i.push(c.flushed),Promise.all(i).then(()=>(this.writes=[],{txnTime:t}))):this.commit(t,r,s+1))}abort(){this.resetReadSnapshot(),this.writes=[]}},Xf=class extends yl{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit(this.timestamp)}get timestamp(){return this._timestamp||(this._timestamp=(0,dA.getNextMonotonicTime)())}getReadTxn(){}}});function m0(e,t,r,s,n){let i=e.primaryStore.env.path,o=e.primaryStore.tableId;Ja||((0,Lo.onMessageByType)(f0,d=>{let E=d.auditIds;fA(d.path,E,d.txnId)}),(0,Lo.onMessageByType)(h0,d=>{(0,js.trace)("confirming to proceed with txn",d.txnId)}),Ja=Object.create(null));let c=Ja[i]||(Ja[i]=[]);c.auditStore=e.auditStore;let u=c[o];u||(u=c[o]=new Map,u.envs=c,u.tableId=o,u.store=e.primaryStore),t=Ca(t);let l=new EA(r);l.startTime=s,n&&(l.includeDescendants=n);let _=u.get(t);return _?_.push(l):(u.set(t,_=[l]),_.tables=u,_.key=t),l.subscriptions=_,l}function fA(e,t,r,s){if(!Ja)return;let n=Ja[e];if(n){if(za&&za+1!==r){(0,js.trace)("Waiting to ensure latest txn id",za,"proceeds",r,s);let i=(async()=>{for(let[o,c]of Zf)o<r&&((0,js.trace)("Txn",r,"waiting for txn",o),await c);if(za+1!==r){await(0,Lo.broadcastWithAcknowledgement)({type:h0,txnId:r});for(let[o,c]of Zf)o<r&&((0,js.trace)("Txn",r,"waiting for txn",o),await c)}Zf.delete(r),(0,js.trace)("Proceeding with txn id",r),za=r-1,fA(e,t,r,s)})();return Zf.set(r,i),i}(0,js.trace)("Notifying with txn id",r,s),za=r;try{n.auditStore.resetReadTxn()}catch(i){throw i.message+=" in "+e,i}e:for(let i of t){let[o,c,u]=i,l=n[c];if(!l)continue;(0,E0.writeKey)(i,Oie,0);let _=i[3];_&&(i.length=3);let d,E=Ca(u),f;do{let h=l.get(E);if(h){for(let T of h)if(!(f&&!T.includeDescendants)){if(T.startTime>=o){(0,js.info)("omitting",u,T.startTime,o);continue}try{if(T.crossThreads===!1&&!s)continue;if(d===void 0){let A=n.auditStore.get(i);if(!A||(d=bi(A,l.store),d.type!=="message"&&l.store.getEntry(i[2])?.version!==i[0])||_&&d.type!=="invalidate")continue e}T.listener(u,d,o)}catch(A){console.error(A),(0,js.info)(A)}}}if(E==null)break;let S=E.lastIndexOf?.("/",E.length-2);S>-1?E=E.slice(0,S+1):E=null,f=!0}while(!0)}}}function p0(e,t){let r=t||e,s=r.env;if(t&&!t.cache&&(t.cache=new Map),!s.hasBroadcastListener){s.hasBroadcastListener=!0;let n=s.path;r.on("aftercommit",({next:i,last:o,txnId:c})=>{let u,l=[];if(t)do{if(i.flag&Aie)continue;let _;i.meta&&i.meta.store===t&&(_=i.meta.key)&&(typeof _[2]=="symbol"&&(_[2]=null),_.invalidated&&(_[3]=!0),l.push(_))}while(i!=o&&(i=i.next));l.length!==0&&((0,Lo.broadcast)({type:f0,path:n,auditIds:l,txnId:c,start:u}),fA(n,l,c,!0))})}}var js,Lo,E0,f0,h0,Aie,Ja,Oie,EA,za,Zf,S0=Te(()=>{js=D(C()),Lo=D(tt()),E0=require("ordered-binary");Dc();Qu();bl();f0="transaction",h0="transaction-await",Aie=67108864,Oie=Buffer.alloc(4096);a(m0,"addSubscription");EA=class extends ys{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let s=t.envs,n=t.dbi;delete s[n]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}},Zf=new Map;a(fA,"notifyFromTransactionData");a(p0,"listenToCommits")});var Xg={};Ke(Xg,{coerceType:()=>eh,makeTable:()=>rh,setServerUtilities:()=>wie});function rh(e){let{primaryKey:t,indices:r,tableId:s,tableName:n,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:l,dbisDB:_}=e,{expirationMS:d,audit:E,trackDeletes:f}=e,{attributes:h}=e;h||(h=[]),p0(i,u);let S=0,T,A,g,x={},V,I,b,M;for(let Z of h)(Z.assignCreatedTime||Z.name==="__createdtime__")&&(V=Z),(Z.assignUpdatedTime||Z.name==="__updatedtime__")&&(I=Z),Z.expiresAt&&(b=Z),Z.isPrimaryKey&&(x=Z);let J;E&&hO();class B extends bt{static name=n;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=n;static indices=r;static audit=E;static databasePath=o;static databaseName=c;static attributes=h;static expirationTimer;static createdTimeProperty=V;static updatedTimeProperty=I;static dbisDB=_;static schemaDefined=l;static sourcedFrom(p,N){if(N&&(this.sourceOptions=N,N.expiration&&this.setTTLExpiration(N.expiration)),this.Source)if(this.Source.mergeSource)this.Source=this.Source.mergeSource(p,this.sourceOptions);else if(p.mergeSource)this.Source=p.mergeSource(this.Source,this.sourceOptions);else throw new Error("Can not assign multiple sources to a table with no source providing a (static) mergeSource method");else this.Source=p;return A=p&&p.get&&(!p.get.reliesOnPrototype||p.prototype.get),(async()=>{let U=!1,y=a(async L=>{let H=L.value,k=L.table?xe[c][L.table]:B;if(c===Ss.SYSTEM_SCHEMA_NAME&&(L.table===Ss.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||L.table===Ss.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(U=!0),L.id===void 0&&(L.id=H[k.primaryKey],L.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(L));let P=await k.getResource(L.id,L,Il);switch(L.type){case"put":return P._writeUpdate(H,Il);case"delete":return P._writeDelete(Il);case"publish":return P._writePublish(H,Il);case"invalidate":return P.invalidate(Il);default:Mo.error("Unknown operation",L.type,L.id)}},"writeUpdate");try{let L=p.subscribe&&(!p.subscribe.reliesOnPrototype||p.prototype.subscribe);L&&f==null&&(f=!0);let H=p.subscribeOnThisThread?p.subscribeOnThisThread((0,Uo.getWorkerIndex)()):(0,Uo.getWorkerIndex)()===0,k=L&&H&&await p.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(k)for await(let P of k)try{if(!(P.type==="transaction"?P.writes[0]:P)){console.error("Bad subscription event");continue}let X=Xe(P,()=>{if(P.type==="transaction"){let j=[];for(let K of P.writes){K[Ne]=P;try{j.push(y(K))}catch(te){throw te.message+=" writing "+JSON.stringify(K)+" of event "+JSON.stringify(P),te}}return Promise.all(j)}else if(P.type==="define_schema"){let j=this.attributes.slice(0),K;for(let te of P.attributes)j.find(Be=>Be.name===te.name)||(j.push(te),K=!0);K&&(ft({table:n,database:c,attributes:j,origin:"cluster"}),Ll.signalSchemaChange(new Dl.SchemaEventMsg(process.pid,Ss.OPERATIONS_ENUM.CREATE_TABLE,c,n)))}else return y(P)});P.onCommit&&(X?.then&&U&&Ll.signalUserChange(new Dl.UserEventMsg(process.pid)),X?.then?X.then(P.onCommit):P.onCommit())}catch($){console.error("error in subscription handler",$)}}catch(L){console.error(L)}})(),this}static getResource(p,N,U){let y=super.getResource(p,N,U);if(p!=null)try{if(y.hasOwnProperty(le))return y;let L=y._txnForRequest();if(typeof p=="object"&&p&&!Array.isArray(p))throw new Error(`Invalid id ${JSON.stringify(p)}`);let H,k,$={transaction:L?.getReadTxn()},X;return Zl(p,N,$,y,U?.allowInvalidated,(j,K)=>{K?k(K):(y[le]=j?.value,y[fr]=j?.version,X=!0,H?.(y))}),X?y:new Promise((j,K)=>{H=j,k=K})}catch(L){throw L.message.includes("Unable to serialize object")&&(L.message+=": "+JSON.stringify(p)),L}return y}static setTTLExpiration(p){(0,Uo.getWorkerIndex)()===0&&(d=p*1e3,this.expirationTimer&&clearInterval(this.expirationTimer),this.expirationTimer=setInterval(()=>{if(this.primaryStore.rootStore.status!=="open")return clearInterval(this.expirationTimer);for(let{key:N,value:U,version:y}of this.primaryStore.getRange({start:!1,versions:!0}))y<Date.now()-d&&y>0&&U?.__invalidated__==null&&B.evict(N,U,y)},d).unref())}static enableAuditing(){E=!0,hO(),B.audit=!0}static coerceId(p){return p===""?null:eh(p,x)}static async dropTable(){if(delete xe[c][n],c===o){for(let p in r)_.remove(B.tableName+"/"+p),r[p].drop();_.remove(B.tableName+"/"),i.drop(),await _.committed}else console.log("legacy dropTable"),await i.close(),await fs.remove(data_path),await fs.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));Ll.signalSchemaChange(new Dl.SchemaEventMsg(process.pid,Ss.OPERATIONS_ENUM.DROP_TABLE,c,n))}static Source;static get(p,N){return p&&typeof p=="object"&&!Array.isArray(p)&&p.url===""?{recordCount:this.getRecordCount(),records:"./",name:n,database:c,attributes:h}:super.get(p,N)}get(p){if(typeof p=="string")return this.getProperty(p);if(this[_n])return this.search(p);if(p?.property)return this.getProperty(p.property);if(this.doesExist()||this[Ne]?.hasOwnProperty("returnNonexistent")&&this[Ne].returnNonexistent)return this}static allowRead(p,N){if(!p)return!1;let U=p.role.permission;if(U.super_user)return!0;if(U[n]?.read){let y=U[n].attribute_permissions;if(y){N||(N={});let L=N.select;if(L){let H=hA(y,"read");N.select=L.filter(k=>H[k])}else N.select=y.filter(H=>H.read).map(H=>H.attribute_name);return N}else return!0}}allowUpdate(p,N,U){if(!p)return!1;let y=p.role.permission;if(y.super_user)return!0;if(y[n]?.update){let L=y[n].attribute_permissions;if(L){let H=hA(L,"update");for(let k in N)if(!H[k])return!1;if(U)for(let k of L){let P=k.attribute_name;!k.update&&!(P in N)&&(N[P]=this.getProperty(P))}}else return!0}}allowCreate(p,N){return this.allowUpdate(p,{})}static allowCreate(p,N){if(!p)return!1;let U=p.role.permission;if(U.super_user)return!0;if(U[n]?.insert){let y=U[n].attribute_permissions;if(y){let L=hA(y,"insert");for(let H in N)if(!L[H])return!1}else return!0}}static allowDelete(p){if(!p)return!1;let N=p.role.permission;if(N.super_user||N[n]?.delete)return!0}update(p,N){if(!this._txnForRequest())throw new Error("Can not update a table resource outside of a transaction");if(p===!1)return this;let y;if(typeof p=="object"&&p){if(N)for(let L in this[le])p[L]===void 0&&(p[L]=void 0);y=this[Nt],y&&(p=Object.assign(y,p)),this[Nt]=y=p}return!this[le]&&t&&!(y||(y=this[Nt]))?.[t]&&(y||(y=this[Nt]=Object.create(null)),y[t]=this[ue]),this._writeUpdate(this),this}invalidate(p){this._txnForRequest().addWrite({key:this[ue],store:i,invalidated:!0,lastVersion:this[fr],nodeName:this[Ne]?.nodeName,commit:(U,y)=>{if(y)return;let L={__invalidated__:U};for(let $ in r)L[$]=this.getProperty($);let H=B.Source,k,P=this[ue];return p?.isNotification||H?.shouldReceiveInvalidations&&(k=H.invalidate(P,this)),i.put(this[ue],L,U),{type:E&&"invalidate",[Co]:k}}})}static evict(p,N,U){let y=this.Source;if(y?.get&&(!y.get.reliesOnPrototype||y.prototype.get)){let L;if(!N){let H=i.getEntry(p);if(!H)return;N=H.value,U=H.version}if(N)for(let H in r)L||(L={__invalidated__:0}),L[H]=N[H];return L?i.put(p,L,U,U):i.remove(p,U)}else return i.remove(p,U)}lock(){throw new Error("Not yet implemented")}static operation(p,N){return p.table||=n,p.schema||=c,I0.operation(p,N)}async put(p){this.update(p,!0)}_writeUpdate(p,N){let U=this._txnForRequest();if(this[ue]===void 0)throw new Error("Can not save record without an id");let y=this[le],L,H,k=this[ue];y||(this[le]={}),U.addWrite({key:k,store:i,lastVersion:this[fr],nodeName:this[Ne]?.nodeName,validate:()=>{this.validate(p)},commit:(P,$)=>{let X;if($){if(L)return;let K=i.getEntry(k);y=K?.value;let te=this[Ne];te&&K?.version>(te.lastModified||0)&&(te.lastModified=K.version)}if(!H){if(H=!0,N?.isNotification)p=Mc(p);else{if(p[R0]&&(L=!f_(p),L))return;t&&p[t]!==k&&(p[t]=k),I&&(p[I.name]=I.type==="Date"?new Date(P):I.type==="String"?new Date(P).toISOString():P),V&&(y?p[V.name]=y[V.name]:p[V.name]=V.type==="Date"?new Date(P):V.type==="String"?new Date(P).toISOString():P),p=Mc(p);let K=B.Source;K?.put&&(!K.put.reliesOnPrototype||K.prototype.put)&&(X=K.put(k,p,this))}if(p[le])throw new Error("Can not assign a record with a record property");this[le]=p}if(Mo.trace("Checking timestamp for put",k,this[fr]>P,this[fr],P),this[fr]>P)return E&&{type:"put",value:i.encoder.encode(p)};let j=i.encoder.encode(p);return i.put(this[ue],(0,ja.asBinary)(j),P),_t(this[ue],y,p),y===null&&!$&&Fi(-1),{type:E&&"put",value:j,[Co]:X}}})}async delete(p){return typeof p=="string"?this.deleteProperty(p):this[le]?this._writeDelete(p):!1}_writeDelete(p){let N=this._txnForRequest(),U,y=this[ue],L;return N.addWrite({key:y,store:i,lastVersion:this[fr],nodeName:this[Ne]?.nodeName,commit:(H,k)=>{let P=this[le];if(k){let $=i.getEntry(y);P=$?.value;let X=this[Ne];X&&$?.version>(X.lastModified||0)&&(X.lastModified=$.version)}if(!U&&(U=!0,!p?.isNotification)){let $=B.Source;$?.delete&&(!$.delete.reliesOnPrototype||$.prototype.delete)&&(L=$.delete(y,this))}if(!(this[fr]>H))return _t(this[ue],P),Mo.trace("Write delete entry",E||f,H),E||f?(i.put(this[ue],null,H),E||fO(),k||Fi(1)):i.remove(this[ue]),{type:E&&"delete",[Co]:L}}}),!0}search(p){let N=this._txnForRequest();if(!p)throw new Error("No query provided");let U=p.reverse===!0,y=p.conditions;y?y.length===void 0&&(y=Array.from(y)):y=Array.isArray(p)?p:p[Symbol.iterator]?Array.from(p):[],this[ue]&&(y=[{attribute:null,comparator:"prefix",value:this[ue]}].concat(y));for(let K of y){let te=K[0]??K.attribute,Be=te==null?x:h.find(Wn=>Wn.name==te);if(Be)Be.type&&(K[1]===void 0?K.value=L(K.value,Be):K[1]=L(K[1],Be));else if(te!=null)throw(0,Do.handleHDBError)(new Error,`${te} is not a defined attribute`,404)}function L(K,te){return Array.isArray(K)?K.map(Be=>eh(Be,te)):eh(K,te)}a(L,"coerceTypedValues"),y.length>1&&(y=(0,b0.sortBy)(y,K=>{if(K.estimated_count===void 0){let te=K.comparator||K.search_type;if(te===wl.SEARCH_TYPES.EQUALS){let Be=K[0]??K.attribute;if(Be==null||Be===t)K.estimated_count=1;else{let Wn=r[Be];K.estimated_count=Wn?Wn.getValuesCount(K[1]??K.value):1/0}}else te===wl.SEARCH_TYPES.CONTAINS||te===wl.SEARCH_TYPES.ENDS_WITH||te==="ne"?K.estimated_count=1/0:te===wl.SEARCH_TYPES.STARTS_WITH||te==="prefix"?K.estimated_count=bie:K.estimated_count=Nie}return K.estimated_count}));let H=N.getReadTxn();H.use();let k=p.select,P=y[0],$;if(!P)$=i.getRange(U?{end:!1,reverse:!0,transaction:H,lazy:k?.length<4}:{start:!1,transaction:H,lazy:k?.length<4}).map(({value:K})=>K?new Promise(te=>setImmediate(()=>te(K))):ja.SKIP);else{let K=rm(P,H,U,B,p.allowFullScan);if(!p.operator||p.operator.toLowerCase()==="and"){let te=y.slice(1).map(sm);$=j(K,te)}else{for(let Be=1;Be<y.length;Be++){let Wn=y[Be],Mh=rm(Wn,H,U,B,p.allowFullScan);K=K.concat(Mh)}let te=new Set;K=K.filter(Be=>te.has(Be)?!1:(te.add(Be),!0)),$=j(K)}}(p.offset||p.limit!==void 0)&&($=$.slice(p.offset,p.limit!==void 0?(p.offset||0)+p.limit:void 0)),$.onDone=()=>{H.done()};let X=this[Ne];function j(K,te){let Be=te?.length,Wn={transaction:H,lazy:Be>0||k?.length<4,alwaysPrefetch:!0};return K.map(Mh=>new Promise(Ph=>Zl(Mh,X,Wn,null,!1,GG=>{let vh=GG?.value;if(!vh)return Ph(ja.SKIP);for(let Bh=0;Bh<Be;Bh++)if(!te[Bh](vh))return Ph(ja.SKIP);Ph(vh)})))}return a(j,"idsToRecords"),$}async subscribe(p){if(!u)throw new Error("Can not subscribe to a table without an audit log");E||ft({table:n,database:c,schemaDefined:l,attributes:h,audit:!0});let N=m0(B,this[ue]??null,function(H,k,P){try{this.send({id:H,timestamp:P,...k})}catch($){console.error($)}},p.startTime,this[_n]),U=this[ue],y=p.previousCount;y>1e3&&(y=1e3);let L=p.startTime;if(this[_n]){if(L){if(y)throw new Do.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:H,value:k}of u.getRange({start:[L,Number.MAX_SAFE_INTEGER]})){let[P,$,X]=H;if(H.length>3&&(X=H.slice(2)),$!==s)continue;let j=bi(k,i);(U==null||N0(U,X))&&N.send({id:X,timestamp:P,...j}),N.startTime=P}}else if(y){let H=[];for(let{key:k,value:P}of u.getRange({start:"z",end:!1,reverse:!0}))try{let[$,X,j]=k;if(k.length>3&&(j=k.slice(2)),X!==s)continue;if(U==null||N0(U,j)){let K=bi(P,i);if(H.push({id:j,timestamp:$,...K}),--y<=0)break}}catch($){Mo.error("Error getting history entry",k,$)}for(let k=H.length;k>0;)N.send(H[--k]);H[0]&&(N.startTime=H[0].timestamp)}else if(!p.omitCurrent)for(let{key:H,value:k,version:P}of i.getRange({start:U??!1,end:U==null?void 0:[U,y0.MAXIMUM_KEY],versions:!0}))k&&N.send({id:H,timestamp:P,value:k})}else{y&&!L&&(L=0);let H=this[fr];if(L<H){let k=[],P=H;do{let $=[P,s,U],X=u.get($);if(X){p.omitCurrent=!0;let j=bi(X,i);k.push({id:U,timestamp:P,...j}),P=j.lastVersion}else break;y&&y--}while(P>L&&y!==0);for(let $=k.length;$>0;)N.send(k[--$]);N.startTime=H}!p.omitCurrent&&this.doesExist()&&N.send({id:U,timestamp:this[fr],value:this})}return p.listener&&N.on("data",p.listener),N}doesExist(){return!!this[le]}async publish(p,N){this._writePublish(p,N)}_writePublish(p,N){let U=this._txnForRequest(),y=this[ue]||null,L,H;U.addWrite({store:i,key:y,lastVersion:this[fr],nodeName:this[Ne]?.nodeName,validate:()=>{this.validate(p)},commit:(k,P)=>{if(this.validate(p),!H&&(H=!0,!N?.isNotification)){let j=B.Source;j?.publish&&(!j.publish.reliesOnPrototype||j.prototype.publish)&&(L=j.publish(y,p,this))}let $=P>0?i.get(y):this[le];$===void 0&&!P&&(E||f)&&(E||fO(),Fi(1));let X={type:"message",value:i.encoder.encode(p),[Co]:L};return!U.hasWrittenTime&&this[fr]>k&&(k=X.newTxnTime=this[fr]+.001),i.put(y,$??null,k),X}})}_txnForRequest(){let p=this[Ne],N=p?.transaction;if(N){let U;return(U=N?.find(y=>y.lmdbDb?.path===i.path))||N.push(U=new yl(i,p.user,u)),U}else return new Xf(i,p.user,u)}validate(p){let N;for(let U=0,y=h.length;U<y;U++){let L=h[U];if(L.type){let H=p[L.name];if(H!=null)switch(L.type){case"Int":case"Float":(typeof H!="number"||L.type==="Int"&&H!==Math.floor(H))&&(N||(N=[])).push(`Property ${L.name} must be an ${L.type==="Int"?"integer":"number"}`);break;case"ID":typeof H=="string"||H?.length>0&&H.every?.(k=>typeof k=="string")||(N||(N=[])).push(`Property ${L.name} must be a string, number, or an array (of strings and numbers)`);break;case"String":typeof H!="string"&&(N||(N=[])).push(`Property ${L.name} must be a string`)}}L.required&&p[L.name]==null&&(N||(N=[])).push(`Property ${L.name} is required`)}if(N)throw new Do.ClientError(N.join(". "))}getUpdatedTime(){return this[fr]}wasLoadedFromSource(){return A?!!this[A0]:void 0}static async addAttributes(p){let N=h.slice(0);for(let U of p){if(!U.name)throw new Do.ClientError("Attribute name is required");if(U.name.match(/[`/]/))throw new Do.ClientError("Attribute names cannot include backticks or forward slashes");N.push(U)}return ft({table:n,database:c,schemaDefined:l,attributes:N}),B.indexingOperation}static async removeAttributes(p){let N=h.filter(U=>!p.includes(U.name));return ft({table:n,database:c,schemaDefined:l,attributes:N}),B.indexingOperation}static getRecordCount(){let p=0;for(let{key:N,value:U}of i.getRange({end:!1}))p++,N[0]?.description==="deletions"&&(p+=U||0);return i.getStats().entryCount-p}static updatedAttributes(){m_(this,this)}static async deleteHistory(p=0){let N;for(let{key:U,value:y}of u.getRange({start:[0,0],end:[p,0]})){await new Promise(P=>setImmediate(P));let[L,H,k]=U;U.length>3&&(k=U.slice(2)),H===s&&(N=i.remove(k))}await N}static async*getHistory(p=0,N=1/0){for(let{key:U,value:y}of u.getRange({start:[p,0],end:[N,0]})){await new Promise($=>setImmediate($));let[L,H,k]=U;if(U.length>3&&(k=U.slice(2)),H!==s)continue;let P=bi(y,i);P.id=k,P.timestamp=L,yield P}}static async getHistoryOfRecord(p){let N=[],U=i.getEntry(p);if(!U)return N;let y=U.version,L=0;do{await new Promise(P=>setImmediate(P));let H=[y,s,p],k=u.get(H);if(k){let P=bi(k,i);P.timestamp=y,N.push(P),y=P.lastVersion}else break}while(L<1e3);return N.reverse()}static cleanup(){J?.remove()}}B.updatedAttributes();let Ie=B.prototype;return Ie[R0]=!0,d&&B.setTTLExpiration(d/1e3),b&&FG(),B;function _t(Z,p,N){let U;for(let y in r){let L=r[y],H=L.isIndexing,k=N?.[y],P=p?.[y];if(k===P&&!H)continue;U=!0;let $=(0,Cl.getIndexedValues)(P);if($){T0&&L.prefetch($.map(X=>({key:X,value:Z})),O0);for(let X=0,j=$.length;X<j;X++)L.remove($[X],Z)}if($=(0,Cl.getIndexedValues)(k),$){T0&&L.prefetch($.map(X=>({key:X,value:Z})),O0);for(let X=0,j=$.length;X<j;X++)L.put($[X],Z)}}return U}a(_t,"updateIndices");function Zl(Z,p,N,U,y,L){let H=a(()=>{let k=N.transaction;if(k?.isDone)throw new Error("Invalid read transaction");let P;k&&!k.hasRunLoadRecord&&(P=!0,k.hasRunLoadRecord=!0);let $;try{$=i.getEntry(Z,N)}catch(te){throw te.message+=". The read txn is "+JSON.stringify(k)+" first loadRecord: "+P,console.error(te),console.error("reader list",i.readerList()),console.error("reader check",i.readerCheck()),console.error("reader list",i.readerList()),te}let X,j,K;if($?(p&&$?.version>(p.lastModified||0)&&(p.lastModified=$.version),j=$.version,X=$.value,(j<0||!X||typeof X.__invalidated__=="number"||d&&j<Date.now()-d)&&(K=!0)):K=!0,A&&da(K,"cache-hit",n),K&&!y&&(U&&(U[A0]=!0),A))return hc(Z,X,j,p).then(te=>{if(te?.value?.[le])throw new Error("Can not assign a record with a record property");L(te)},te=>{L(null,te)});if($?.value?.[le])throw new Error("Can not assign a record with a record property");L($)},"whenPrefetched");if(!N.alwaysPrefetch&&(Z==null||i.cache?.get(Z)))return H();i.prefetch([Z],H)}a(Zl,"loadRecord");function Yo(){M=new Set,(0,Uo.onMessageByType)("transaction",Z),i.on("aftercommit",Z);function Z(){for(let p of M)p()}a(Z,"onCommit")}a(Yo,"setupCommitListeners");async function hc(Z,p=null,N,U){if(N<0){let P;return M||Yo(),await new Promise($=>{let X,j=a(()=>{if(P=i.getEntry(Z),!P||P.version>0){if(clearTimeout(X),M.delete(j),typeof P?.value?.__invalidated__=="number")return $(hc(Z,P.value,P.version,U));$(P)}},"listener");M.add(j),X=setTimeout(()=>{M.delete(j),$(hc(Z,P?.value,void 0,U))},1e4).unref()})}let y=p?.__invalidated__,L=-(N||1);i.put(Z,p,L,N);let H={transaction:U?.transaction,replacingRecord:p,replacingVersion:N},k=U?.responseHeaders;k&&(H.responseHeaders=k);try{let P=performance.now(),$=await B.Source.get(Z,H),X=performance.now()-P;qs(X,"cache-resolution",n),k&&k.append("Server-Timing",`cache-resolve;dur=${X.toFixed(2)}`);let j=H.lastModified||N;(!j||d&&j<Date.now()-d)&&(j=(0,Cl.getNextMonotonicTime)());let te=_t(Z,p,$)&&N||y>0;return $?(t&&($[t]=Z),typeof $.toJSON=="function"&&($=$.toJSON()),i.put(Z,$,j,L)):i.remove(Z,L),te&&E&&u.put([j,s,Z],jf(y,null,$?{type:"put",value:i.encoder.encode($)}:{type:"delete"})),{version:j,value:$}}catch(P){throw i.put(Z,p,N,L),P}}a(hc,"getFromSource");function Fi(Z){S||(S=i.get([g0,mA.threadId])||0),S+=Z,g||(g=setTimeout(()=>{g=null,i.rootStore.status==="open"&&i.put([g0,mA.threadId],S)},50))}a(Fi,"recordDeletion");function fO(){T||(T=setTimeout(()=>{if(T=null,i.rootStore.status==="open"){for(let{key:Z,value:p}of i.getRange({start:!0}))if(p===null){let N=i.getEntry(Z);N?.value===null&&i.remove(Z,N.version),Fi(-1)}}},B.getRecordCount()*100+Iie).unref())}a(fO,"enqueueDeletionCleanup");function hO(){J=u?.addDeleteRemovalCallback(s,Z=>{let p=i.getEntry(Z);p?.value===null&&i.remove(Z,p.version),Fi(-1)})}a(hO,"addDeleteRemoval");function FG(){(0,Uo.getWorkerIndex)()===0&&setInterval(async()=>{try{let Z=b.name,p=r[Z];if(!p)throw new Error(`expiresAt attribute ${b} must be indexed`);for(let{value:N}of p.getRange({start:!0,end:Date.now(),versions:!0,snapshot:!1})){let U=i.getEntry(N);U?.value?.[Z]<Date.now()&&B.evict(N,U.value,U.version),await new Promise(y=>setImmediate(y))}}catch(Z){Mo.error("Error in evicting old records",Z)}},yie).unref()}a(FG,"runRecordExpirationEviction")}function hA(e,t){let r=e.attr_object||(e.attr_object={}),s=r[t];if(s)return s;s=r[t]=Object.create(null);for(let n of e)s[n.attribute_name]=n[t];return s}function O0(){}function wie(e){I0=e}function eh(e,t){let r=t?.type;return e===null?e:r==="Int"?parseInt(e):r==="Float"?parseFloat(e):r==="Date"?(typeof e!="number"&&!Cie.test(e)&&(e+="Z"),new Date(e)):r?e:(0,th.autoCast)(e)}function N0(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let s=0;s<r;s++)if(t[s]!==e[s])return!1;return!0}return!1}else if(t[0]===e)return!0}var Ss,ja,Cl,b0,mA,wl,Ul,Do,Ll,Dl,Mo,y0,Uo,th,I0,Nie,bie,yie,T0,g0,fr,R0,fRe,A0,Il,Iie,Cie,_f=Te(()=>{Ss=D(R()),ja=require("lmdb"),Cl=D(Ht()),b0=require("lodash"),mA=require("worker_threads");Is();d0();wl=D(Ge()),Ul=D(Y());S0();Do=D(z()),Ll=D(Rn()),Dl=D(os());_e();g_();Mo=D(C());S_();Yi();y0=require("ordered-binary"),Uo=D(tt());bl();th=D(F());co();Nie=1e8,bie=1e7,yie=6e4;Ul.initSync();T0=Ul.get(Ss.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),g0=Symbol.for("deletions"),fr=Symbol.for("version"),R0=Symbol.for("incremental-update"),fRe=Symbol("source-resource"),A0=Symbol("load-from-source"),Il={isNotification:!0,allowInvalidated:!0},Iie=(0,th.convertToMS)(Ul.get(Ss.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(rh,"makeTable");a(hA,"attributesAsObject");a(O0,"noop");a(wie,"setServerUtilities");Cie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(eh,"coerceType");a(N0,"isDescendantId")});var be={};Ke(be,{database:()=>du,databases:()=>xe,dropDatabase:()=>pS,dropTableMeta:()=>vie,getDatabases:()=>us,getTables:()=>Lie,onUpdatedTable:()=>GR,readMetaDb:()=>Ml,resetDatabases:()=>Die,table:()=>ft,tables:()=>Rr});function Lie(){return oh||us(),Rr||{}}function us(){if(oh)return xe;oh=!0,tc=new Map;let e=(0,Bt.getHdbBasePath)()&&(0,Fe.join)((0,Bt.getHdbBasePath)(),hr.DATABASES_DIR_NAME),t=(0,Bt.get)(hr.CONFIG_PARAMS.SCHEMAS)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Bt.get)(hr.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,Ur.existsSync)(e)?e:(0,Fe.join)((0,Bt.getHdbBasePath)(),hr.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,Ur.existsSync)(e))for(let r of(0,Ur.readdirSync)(e,{withFileTypes:!0})){let s=(0,Fe.basename)(r.name,".mdb");r.isFile()&&(0,Fe.extname)(r.name).toLowerCase()===".mdb"&&!t[s]?.path&&Ml((0,Fe.join)(e,r.name),null,s)}if((0,Ur.existsSync)((0,ec.getBaseSchemaPath)())){for(let r of(0,Ur.readdirSync)((0,ec.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let s=(0,Fe.join)((0,ec.getBaseSchemaPath)(),r.name),n=(0,Fe.join)((0,ec.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,Ur.readdirSync)(s,{withFileTypes:!0}))if(i.isFile()&&(0,Fe.extname)(i.name).toLowerCase()===".mdb"){let o=(0,Fe.join)(n,i.name);Ml((0,Fe.join)(s,i.name),(0,Fe.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let s=t[r],n=s.path;if((0,Ur.existsSync)(n))for(let o of(0,Ur.readdirSync)(n,{withFileTypes:!0}))o.isFile()&&(0,Fe.extname)(o.name).toLowerCase()===".mdb"&&Ml((0,Fe.join)(n,o.name),(0,Fe.basename)(o.name,".mdb"),r);let i=s.tables;if(i)for(let o in i){let c=i[o],u=(0,Fe.join)(c.path,(0,Fe.basename)(o+".mdb"));(0,Ur.existsSync)(u)&&Ml(u,o,r,null,!0)}}for(let r in xe){let s=tc.get(r);if(s){let n=xe[r];r.includes("delete")&&qe.trace(`defined tables ${Array.from(s.keys())}`);for(let i in n)s.has(i)||(qe.trace(`delete table class ${i}`),delete n[i])}else if(delete xe[r],r==="data"){for(let n in Rr)delete Rr[n];delete Rr[ah]}}return tc=null,xe}}function Die(){oh=!1;for(let[,e]of yi)e.needsDeletion=!0;us();for(let[e,t]of yi)t.needsDeletion&&!e.endsWith("system.mdb")&&(console.log("closing database",e),t.close().then(()=>console.log("closed database",e)),yi.delete(e));return xe}function Ml(e,t,r=TA,s,n){let i=new pA.default(e,!1);e.includes("delete")&&qe.trace(`reading meta data from ${e}`);try{let o=yi.get(e);o?o.needsDeletion=!1:(o=(0,sh.open)(i),yi.set(e,o));let c=new Po.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(Xa.INTERNAL_DBIS_NAME,c)),l=o.auditStore;l||(s?(0,Ur.existsSync)(s)&&(i.path=s,l=(0,sh.open)(i),l.isLegacy=!0):l=_A(o));let _=D0(r),d=_[ah],E=new Map;for(let{key:f,value:h}of u.getRange({start:!1})){let[S,T]=f.toString().split("/");e.includes("delete")&&qe.trace(`read key ${f}`),T===""?T=h.name:T||(T=S,S=t,h.name||(h.name=T,h.indexed=!h.is_hash_attribute)),d?.add(S);let A=E.get(S);A||E.set(S,A={attributes:[]}),(T==null||h.is_hash_attribute)&&(A.primary=h),T!=null&&A.attributes.push(h),Object.defineProperty(h,"key",{value:f,configurable:!0})}for(let[f,h]of E){let{attributes:S,primary:T}=h;if(!T){for(let B of S)if(B.is_hash_attribute||B.isPrimaryKey){T=B;break}if(!T)throw new Error(`Unable to find a primary key attribute on table ${f}, with attributes: ${JSON.stringify(S)}`)}let A=_[f],g={},x=[],V,I,b=typeof T.audit=="boolean"?T.audit:(0,Bt.get)(hr.CONFIG_PARAMS.LOGGING_AUDITLOG),M=T.trackDeletes,J=T.expiration;if(A)g=A.indices,x=A.attributes,A.schemaVersion++;else{V=T.tableId,V?V>=(u.get(Za)||0)&&u.putSync(Za,V+1):(T.tableId=V=u.get(Za),V||(V=1),u.putSync(Za,V+1),u.putSync(T.key,T));let B=new Po.default(!T.is_hash_attribute,T.is_hash_attribute);qe.trace(`openDB ${T.key} from ${r}`),I=o.openDB(T.key,B),I.rootStore=o,I.tableId=V}for(let B of S){B.attribute=B.name;try{if(!B.is_hash_attribute&&(B.indexed||B.attribute&&!B.name)){if(!g[B.name]){let _t=new Po.default(!B.is_hash_attribute,B.is_hash_attribute);qe.trace(`openDB ${B.key} from ${r}`),g[B.name]=o.openDB(B.key,_t)}let Ie=x.find(_t=>_t.name===B.name);Ie?x.splice(x.indexOf(Ie),1,B):x.push(B)}}catch(Ie){qe.error("Error trying to update attribute",B,x,g,Ie)}}if(!A){qe.trace(`creating table class ${f}`,Object.keys(_)),A=U0(_,f,rh({primaryStore:I,auditStore:l,audit:b,expirationMS:J&&J*1e3,trackDeletes:M,tableName:f,tableId:V,primaryKey:T.name,databasePath:n?r+"/"+f:r,databaseName:r,indices:g,attributes:S,schemaDefined:T.schemaDefined,dbisDB:u})),A.schemaVersion=1;for(let B of gA)B(A)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function D0(e){let t=xe[e];if(t||(e==="data"?t=xe[e]=Rr:e==="system"?Object.defineProperty(xe,"system",{value:t=Object.create(null),configurable:!0}):t=xe[e]=Object.create(null)),tc&&!tc.has(e)){let r=new Set;t[ah]=r,tc.set(e,r)}return t}function U0(e,t,r){return e[t]=r,r}function du({database:e,table:t}){e||(e=TA),us();let r=D0(e),s=(0,Fe.join)((0,Bt.getHdbBasePath)(),hr.DATABASES_DIR_NAME),n=t&&(0,Bt.get)(hr.CONFIG_PARAMS.SCHEMAS)?.[e]?.tables?.[t]?.path;s=n||(0,Bt.get)(hr.CONFIG_PARAMS.SCHEMAS)?.[e]?.path||process.env.STORAGE_PATH||(0,Bt.get)(hr.CONFIG_PARAMS.STORAGE_PATH)||((0,Ur.existsSync)(s)?s:(0,Fe.join)((0,Bt.getHdbBasePath)(),hr.LEGACY_DATABASES_DIR_NAME));let i=(0,Fe.join)(s,(n?t:e)+".mdb"),o=yi.get(i);if(!o){let c=new pA.default(i,!1);o=(0,sh.open)(c),yi.set(i,o)}return o}async function pS(e){if(!xe[e])throw new Error("Schema does not exist");let t=xe[e];for(let r in t){let n=t[r].primaryStore.rootStore;yi.delete(n.path),n.status==="open"&&(await n.close(),await w0.remove(n.path))}if(e==="data"){for(let r in Rr)delete Rr[r];delete Rr[ah]}delete xe[e]}function ft({table:e,database:t,expiration:r,attributes:s,audit:n,trackDeletes:i,schemaDefined:o,origin:c}){t||(t=TA);let u=du({database:t,table:e}),l=xe[t],_=l?.[e];if(u.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let d,E,f,h;o==null&&(o=!0);let S=new Po.default(!1);for(let I of s)I.attribute?(I.name=I.attribute,I.indexed=!0):I.attribute=I.name,I.expiresAt&&(I.indexed=!0);let T,A;if(_){if(qe.trace(`${e} table already exists`),d=_.primaryKey,_.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);_.attributes.splice(0,_.attributes.length,...s)}else{let I=u.auditStore;I||(I=_A(u)),E=s.find(B=>B.isPrimaryKey)||{},d=E.name,E.is_hash_attribute=!0,E.schemaDefined=o,i&&(E.trackDeletes=!0),n=E.audit=typeof n=="boolean"?n:(0,Bt.get)(hr.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(E.expiration=r),c&&(E.origins?E.origins.includes(c)||E.origins.push(c):E.origins=[c]),qe.trace(`${e} table loading, opening primary store`);let b=new Po.default(!1,!0),M=e+"/";qe.trace(`openDB ${M} from ${t}`);let J=u.openDB(M,b);J.rootStore=u,qe.trace(`openDB ${Xa.INTERNAL_DBIS_NAME} from ${t}`),h=u.dbisDb=u.openDB(Xa.INTERNAL_DBIS_NAME,S),J.tableId=h.get(Za),J.tableId||(J.tableId=1),h.putSync(Za,J.tableId+1),E.tableId=J.tableId,_=U0(l,e,rh({primaryStore:J,auditStore:I,audit:n,trackDeletes:i,expirationMS:r&&r*1e3,primaryKey:d,tableName:e,tableId:J.tableId,databasePath:t,databaseName:t,indices:{},attributes:s,schemaDefined:o,dbisDB:h})),_.schemaVersion=1,T=!0,V(),h.put(M,E)}qe.trace(`${e} table loading, getting stored attributes`),f=_.indices,h||qe.trace(`openDB ${Xa.INTERNAL_DBIS_NAME} from ${t}`),h=h||(u.dbisDb=u.openDB(Xa.INTERNAL_DBIS_NAME,S)),_.dbisDB=h;let g=[];for(let{key:I,value:b}of h.getRange({start:!0})){let[M,J]=I.toString().split("/");if(J===""&&(J=b.name),J){if(M!==e)continue}else J=M;if(!s.find(Ie=>Ie.name===J)?.indexed&&b.indexed&&!b.isPrimaryKey){V(),T=!0,h.remove(I);let Ie=_.indices[M];Ie&&g.push(Ie)}}qe.trace(`${e} table loading, comparing atributes`);let x=[];try{for(let I of s||[]){let b=e+"/"+(I.name||"");Object.defineProperty(I,"key",{value:b,configurable:!0});let M=h.get(b);if(I.isPrimaryKey){if(n===!0&&!_.audit){_.enableAuditing(),M||(b=e+"/",M=h.get(b));let B=Object.assign({},M,{audit:!0});T=!0,V(),h.put(b,B)}continue}M?.attribute&&!M.name&&(M.indexed=!0);let J=!M||M.type!==I.type||M.indexed!==I.indexed||JSON.stringify(M.attributes)!==JSON.stringify(I.attributes)||JSON.stringify(M.elements)!==JSON.stringify(I.elements);if(I.indexed){let B=new Po.default(!0,!1);qe.trace(`openDB ${b} from ${t}`);let Ie=u.openDB(b,B);(J||M.indexingPID&&M.indexingPID!==process.pid||M.restartNumber<Pl.workerData?.restartNumber)&&(T=!0,V(),M=h.get(b),(J||M.indexingPID&&M.indexingPID!==process.pid||M.restartNumber<Pl.workerData?.restartNumber)&&(T=!0,I.lastIndexedKey=M?.lastIndexedKey||!1,I.indexingPID=process.pid,Ie.isIndexing=!0,Object.defineProperty(I,"dbi",{value:Ie}),x.push(I)),h.put(b,I)),f[I.name]=Ie}else J&&(T=!0,V(),h.put(b,I))}}finally{A&&A()}if(T&&(_.schemaVersion++,_.updatedAttributes()),qe.trace(`${e} table loading, running index`),x.length>0||g.length>0?_.indexingOperation=Pie(_,x,g):T&&nh.signalSchemaChange(new ih.SchemaEventMsg(process.pid,"schema-change",_.databaseName,_.tableName)),_.origin=c,T)for(let I of gA)I(_,c!=="cluster");return r&&_.setTTLExpiration(+r),qe.trace(`${e} table loaded`),_;function V(){A||u.transactionSync(()=>({then(I){A=I}}))}a(V,"startTxn")}async function Pie(e,t,r){try{let s=e.schemaVersion;await nh.signalSchemaChange(new ih.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let n;for(let u of r)n=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:l,value:_,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(_){if(u++,n=e.primaryStore.ifVersion(l,d,()=>{for(let E=0;E<c;E++){let f=t[E],h=f.name,S=(0,C0.getIndexedValues)(_[h]);if(S)for(let T=0,A=S.length;T<A;T++)f.dbi.put(S[T],l)}}),n.then(()=>u--,E=>{u--,qe.error(E)}),Pl.workerData&&Pl.workerData.restartNumber!==L0.restartNumber&&(i=!0),++o%100===0||i){for(let E of t)E.lastIndexedKey=l,e.dbisDB.put(E.key,E);if(i)return}u>Uie?await n:u>Mie&&await new Promise(E=>setImmediate(E))}for(let l of t)delete l.lastIndexedKey,delete l.indexingPID,l.dbi.isIndexing=!1,n=e.dbisDB.put(l.key,l)}await n,await nh.signalSchemaChange(new ih.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(s){qe.error("Error in indexing",s)}}function vie({table:e,database:t}){let r=du({database:t,table:e}),s=[],n=r.dbisDb;for(let i of n.getKeys({start:e+"/",end:e+"0"}))s.push(n.remove(i));return Promise.all(s)}function GR(e){gA.push(e)}var Bt,Xa,sh,Fe,Ur,ec,Po,pA,hr,w0,SA,C0,nh,ih,Pl,qe,L0,TA,ah,Rr,xe,Za,gA,oh,yi,tc,Uie,Mie,_e=Te(()=>{Bt=D(Y()),Xa=D(Ge()),sh=require("lmdb"),Fe=require("path"),Ur=require("fs"),ec=D(De());_f();Po=D(N_()),pA=D(y_()),hr=D(R()),w0=D(require("fs-extra")),SA=require("../index"),C0=D(Ht()),nh=D(Rn()),ih=D(os()),Pl=require("worker_threads"),qe=D(C()),L0=D(tt());bl();TA="data",ah=Symbol("defined-tables");(0,Bt.initSync)();Rr=Object.create(null),xe=Object.create(null);(0,SA._assignPackageExport)("databases",xe);(0,SA._assignPackageExport)("tables",Rr);Za=Symbol.for("next-table-id"),gA=[],yi=new Map;a(Lie,"getTables");a(us,"getDatabases");a(Die,"resetDatabases");a(Ml,"readMetaDb");a(D0,"ensureDB");a(U0,"setTable");a(du,"database");a(pS,"dropDatabase");a(ft,"table");Uie=1e3,Mie=10;a(Pie,"runIndexing");a(vie,"dropTableMeta");a(GR,"onUpdatedTable")});var F=m((ORe,K0)=>{"use strict";var Ii=require("path"),H0=require("fs-extra"),mr=C(),M0=require("fs-extra"),ch=require("os"),Bie=require("net"),Hie=require("recursive-iterator"),Ye=R(),qie=zh(),P0=require("papaparse"),uh=require("moment"),{inspect:Fie}=require("util"),v0=require("is-number"),ARe=require("lodash"),Gie=require("minimist"),xie=require("https"),kie=require("http"),{hdb_errors:lh}=z(),$ie=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,q0=require("util").promisify(setTimeout),Vie=100,Yie=5,Kie="",Wie=4,B0={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};K0.exports={isEmpty:Mr,isEmptyOrZeroLength:Xs,arrayHasEmptyValues:Jie,arrayHasEmptyOrZeroLengthValues:jie,buildFolderPath:Xie,isBoolean:F0,errorizeMessage:Qie,stripFileExtension:eoe,autoCast:toe,autoCastJSON:G0,autoCastJSONDeep:AA,removeDir:roe,compareVersions:soe,isCompatibleDataVersion:noe,escapeRawValue:ioe,unescapeValue:ooe,stringifyProps:aoe,timeoutPromise:uoe,isClusterOperation:_oe,getClusterUser:Eoe,checkGlobalSchemaTable:doe,getHomeDir:k0,getPropsFilePath:coe,promisifyPapaParse:foe,removeBOM:$0,createEventPromise:hoe,checkProcessRunning:moe,checkSchemaTableExist:poe,checkSchemaExists:V0,checkTableExists:Y0,getStartOfTomorrowInSeconds:Soe,getLimitKey:Toe,isObject:Zie,isNotEmptyAndHasValue:zie,autoCasterIsNumberCheck:x0,backtickASTSchemaItems:goe,isPortTaken:loe,createForkArgs:Roe,autoCastBoolean:Aoe,async_set_timeout:q0,getTableHashAttribute:Ooe,doesSchemaExist:Noe,doesTableExist:boe,stringifyObj:yoe,ms_to_time:Ioe,changeExtension:woe,getEnvCliRootPath:OA,noBootFile:Coe,httpRequest:Loe,transformReq:Doe,convertToMS:Uoe,PACKAGE_ROOT:Ye.PACKAGE_ROOT};function Qie(e){return e instanceof Error?e:new Error(e)}a(Qie,"errorizeMessage");function Mr(e){return e==null}a(Mr,"isEmpty");function zie(e){return!Mr(e)&&(e||e===0||e===""||F0(e))}a(zie,"isNotEmptyAndHasValue");function Xs(e){return Mr(e)||e.length===0||e.size===0}a(Xs,"isEmptyOrZeroLength");function Jie(e){if(Mr(e))return!0;for(let t=0;t<e.length;t++)if(Mr(e[t]))return!0;return!1}a(Jie,"arrayHasEmptyValues");function jie(e){if(Xs(e))return!0;for(let t=0;t<e.length;t++)if(Xs(e[t]))return!0;return!1}a(jie,"arrayHasEmptyOrZeroLengthValues");function Xie(...e){try{return e.join(Ii.sep)}catch{console.error(e)}}a(Xie,"buildFolderPath");function F0(e){return Mr(e)?!1:e===!0||e===!1}a(F0,"isBoolean");function Zie(e){return Mr(e)?!1:typeof e=="object"}a(Zie,"isObject");function eoe(e){return Xs(e)?Kie:e.slice(0,-Wie)}a(eoe,"stripFileExtension");function toe(e){return Mr(e)||e===""||typeof e!="string"?e:B0[e]!==void 0?B0[e]:x0(e)===!0?Number(e):$ie.test(e)?new Date(e):e}a(toe,"autoCast");function G0(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(G0,"autoCastJSON");function AA(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let s=e[t],n=AA(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=AA(r);s!==r&&(e[t]=s)}return e}else return G0(e)}a(AA,"autoCastJSONDeep");function x0(e){if(e.startsWith("0.")&&v0(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&v0(e))}a(x0,"autoCasterIsNumberCheck");async function roe(e){if(Xs(e))throw new Error(`Directory path: ${e} does not exist`);try{await M0.emptyDir(e),await M0.remove(e)}catch(t){throw mr.error(`Error removing files in ${e} -- ${t}`),t}}a(roe,"removeDir");function soe(e,t){if(Xs(e)){mr.info("Invalid current version sent as parameter.");return}if(Xs(t)){mr.info("Invalid upgrade version sent as parameter.");return}let r,s=/(\.0+)+$/,n=e.version?e.version:e,i=t.version?t.version:t,o=n.replace(s,"").split("."),c=i.replace(s,"").split("."),u=Math.min(o.length,c.length);for(let l=0;l<u;l++)if(r=parseInt(o[l],10)-parseInt(c[l],10),r)return r;return o.length-c.length}a(soe,"compareVersions");function noe(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(noe,"isCompatibleDataVersion");function ioe(e){if(Mr(e))return e;let t=String(e);return t==="."?Ye.UNICODE_PERIOD:t===".."?Ye.UNICODE_PERIOD+Ye.UNICODE_PERIOD:t.replace(Ye.FORWARD_SLASH_REGEX,Ye.UNICODE_FORWARD_SLASH)}a(ioe,"escapeRawValue");function ooe(e){if(Mr(e))return e;let t=String(e);return t===Ye.UNICODE_PERIOD?".":t===Ye.UNICODE_PERIOD+Ye.UNICODE_PERIOD?"..":String(e).replace(Ye.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(ooe,"unescapeValue");function aoe(e,t){if(Mr(e))return mr.info("Properties object is null"),"";let r="";return e.each(function(s,n){try{if(t&&t[s]){let i=t[s];for(let o of i)r+=";"+o+ch.EOL}!Xs(s)&&s[0]===";"?r+=" "+s+n+ch.EOL:Xs(s)||(r+=s+"="+n+ch.EOL)}catch{mr.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a(aoe,"stringifyProps");function k0(){let e;try{e=ch.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(k0,"getHomeDir");function coe(){let e=Ii.join(k0(),Ye.HDB_HOME_DIR_NAME,Ye.BOOT_PROPS_FILE_NAME);return H0.existsSync(e)||(e=Ii.join(__dirname,"../","hdb_boot_properties.file")),e}a(coe,"getPropsFilePath");function uoe(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a(uoe,"timeoutPromise");async function loe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=Bie.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(loe,"isPortTaken");function _oe(e){try{return Ye.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){mr.error(`Error checking operation against cluster ops ${t}`)}return!1}a(_oe,"isClusterOperation");function doe(e,t){let r=(_e(),re(be)).getDatabases();if(!r[e])return lh.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return lh.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(doe,"checkGlobalSchemaTable");function Eoe(e,t){if(Mr(t)){mr.warn("No CLUSTERING_USER defined, clustering disabled");return}if(Mr(e)||Xs(e)){mr.warn("No users to search.");return}let r;try{let s=e.get(t);s&&s.role.permission.cluster_user===!0&&s.active===!0&&(r=s)}catch(s){mr.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){mr.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Eoe,"getClusterUser");function foe(){P0.parsePromise=function(e,t,r){return new Promise(function(s,n){P0.parse(e,{header:!0,transformHeader:$0,chunk:t.bind(null,n),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:n,complete:s})})}}a(foe,"promisifyPapaParse");function $0(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a($0,"removeBOM");function hoe(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;mr.info(`Got cluster status event response: ${Fie(n)}`);try{i.cancel()}catch{mr.error("Error trying to cancel timeout.")}s(n)})})}a(hoe,"createEventPromise");async function moe(e){let t=!0,r=0;do await q0(Vie*r++),(await qie.findPs(e)).length>0&&(t=!1);while(t&&r<Yie);if(t)throw new Error(`process ${e} was not started`)}a(moe,"checkProcessRunning");function poe(e,t){let r=V0(e);if(r)return r;let s=Y0(e,t);if(s)return s}a(poe,"checkSchemaTableExist");function V0(e){let{getDatabases:t}=(_e(),re(be));if(!t()[e])return lh.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(V0,"checkSchemaExists");function Y0(e,t){let{getDatabases:r}=(_e(),re(be));if(!r()[e][t])return lh.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Y0,"checkTableExists");function Soe(){let e=uh().utc().add(1,Ye.MOMENT_DAYS_TAG).startOf(Ye.MOMENT_DAYS_TAG).unix(),t=uh().utc().unix();return e-t}a(Soe,"getStartOfTomorrowInSeconds");function Toe(){return uh().utc().format("DD-MM-YYYY")}a(Toe,"getLimitKey");function goe(e){try{let t=new Hie(e);for(let{node:r}of t)r&&(r.columnid&&typeof r.columnid!="string"&&(r.columnid=r.columnid.toString()),r.columnid&&!r.columnid.startsWith("`")&&(r.columnid_orig=r.columnid,r.columnid=`\`${r.columnid}\``),r.tableid&&!r.tableid.startsWith("`")&&(r.tableid_orig=r.tableid,r.tableid=`\`${r.tableid}\``),r.databaseid&&!r.databaseid.startsWith("`")&&(r.databaseid_orig=r.databaseid,r.databaseid=`\`${r.databaseid}\``),r.as&&typeof r.as=="string"&&!r.as.startsWith("[")&&(r.as_orig=r.as,r.as=`\`${r.as}\``))}catch(t){mr.error("Got an error back ticking items."),mr.error(t)}}a(goe,"backtickASTSchemaItems");function Roe(e){return[e]}a(Roe,"createForkArgs");function Aoe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Aoe,"autoCastBoolean");function Ooe(e,t){let{getDatabases:r}=(_e(),re(be)),s=r()[e]?.[t];return s?.primaryKey||s?.hash_attribute}a(Ooe,"getTableHashAttribute");function Noe(e){let{getDatabases:t}=(_e(),re(be));return t()[e]!==void 0}a(Noe,"doesSchemaExist");function boe(e,t){let{getDatabases:r}=(_e(),re(be));return r()[e]?.[t]!==void 0}a(boe,"doesTableExist");function yoe(e){try{return JSON.stringify(e)}catch{return e}}a(yoe,"stringifyObj");function Ioe(e){let t=uh.duration(e),r=t.seconds()>0?t.seconds()+"s":"",s=t.minutes()>0?t.minutes()+"m ":"",n=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+n+s+r}a(Ioe,"ms_to_time");function woe(e,t){let r=Ii.basename(e,Ii.extname(e));return Ii.join(Ii.dirname(e),r+t)}a(woe,"changeExtension");function OA(){if(process.env[Ye.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Ye.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=Gie(process.argv);if(e[Ye.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Ye.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(OA,"getEnvCliRootPath");var RA;function Coe(){if(RA)return RA;let e=OA();OA()&&H0.pathExistsSync(Ii.join(e,Ye.HDB_CONFIG_FILE))&&(RA=!0)}a(Coe,"noBootFile");function Loe(e,t){let r;return e.protocol==="http:"?r=kie:r=xie,new Promise((s,n)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",u=>{c.body+=u}),o.on("end",()=>{s(c)})});i.on("error",o=>{n(o)}),i.write(JSON.stringify(t)),i.end()})}a(Loe,"httpRequest");function Doe(e){if(!e.schema&&!e.database){e.schema=Ye.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(Doe,"transformReq");function Uoe(e){let t=0;if(typeof e=="number"&&(t=e),typeof e=="string")switch(t=parseFloat(e),e.slice(-1)){case"M":t*=86400*30;break;case"D":case"d":t*=86400;break;case"H":case"h":t*=3600;break;case"m":t*=60;break}return t*1e3}a(Uoe,"convertToMS")});var Y=m((bRe,z0)=>{"use strict";var NA=require("fs-extra"),Ts=require("path"),W0=require("os"),Moe=require("properties-reader"),vl=C(),vo=F(),ne=R(),_h=et(),Poe="Error initializing environment manager",dh="BOOT_PROPS_FILE_PATH",Q0=!1,voe={[ne.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[ne.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[ne.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},xn={};z0.exports={BOOT_PROPS_FILE_PATH:dh,getHdbBasePath:Boe,setHdbBasePath:Hoe,get:qoe,initSync:Goe,setProperty:he,initTestEnvironment:xoe};function Boe(){return xn[ne.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Boe,"getHdbBasePath");function Hoe(e){xn[ne.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(Hoe,"setHdbBasePath");function qoe(e){let t=_h.getConfigValue(e);return t===void 0?xn[e]:t}a(qoe,"get");function he(e,t){voe[e]&&(xn[e]=t),_h.updateConfigObject(e,t)}a(he,"setProperty");function Foe(){let e;try{e=vo.getPropsFilePath(),NA.accessSync(e,NA.constants.F_OK|NA.constants.R_OK),Q0=!0;let t=Moe(e);return xn[ne.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ne.HDB_SETTINGS_NAMES.INSTALL_USER),xn[ne.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ne.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),xn[dh]=e,!0}catch{return vl.trace(`Environment manager found no properties file at ${e}`),!1}}a(Foe,"doesPropFileExist");function Goe(e=!1){try{(Q0||Foe()||vo.noBootFile())&&(_h.initConfig(e),xn[ne.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=_h.getConfigValue(ne.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){vl.error(Poe),vl.error(t),console.error(t),process.exit(1)}}a(Goe,"initSync");function xoe(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:s,https_enabled:n,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=Ts.join(__dirname,"../../","unitTests");xn[dh]=Ts.join(u,"hdb_boot_properties.file"),he(ne.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Ts.join(u,"settings.test")),he(ne.HDB_SETTINGS_NAMES.INSTALL_USER,W0.userInfo()?W0.userInfo().username:void 0),he(ne.HDB_SETTINGS_NAMES.PRIVATE_KEY_KEY,Ts.join(u,"envDir","utility","keys","privateKey.pem")),he(ne.HDB_SETTINGS_NAMES.CERT_KEY,Ts.join(u,"envDir","utility","keys","certificate.pem")),he(ne.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,Ts.join(u,"envDir","utility","keys","privateKey.pem")),he(ne.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_CERTIFICATE,Ts.join(u,"envDir","utility","keys","certificate.pem")),he(ne.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),he(ne.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Ts.join(u,"envDir","log")),he(ne.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),he(ne.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),he(ne.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),he(ne.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Ts.join(u,"envDir")),he(ne.CONFIG_PARAMS.STORAGE_PATH,Ts.join(u,"envDir")),he(ne.HDB_SETTINGS_NAMES.HTTP_SECURE_ENABLED_KEY,vo.isEmpty(n)?!0:n),he(ne.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,vo.isEmpty(n)?!0:n),he(ne.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),he(ne.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,vo.isEmpty(i)?!1:i),he(ne.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORS,vo.isEmpty(i)?!1:i),he(ne.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),he(ne.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),he(ne.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),he(ne.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),he(ne.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Ts.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),he(ne.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,vo.isEmpty(c)?!1:c),o&&(he("CORS_ACCESSLIST",o),he(ne.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,o)),s&&(he(ne.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),he(ne.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,s)),t&&(he(ne.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),he(ne.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,t)),r&&(he(ne.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),he(ne.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${dh}. Please check your boot props and settings files`;vl.fatal(r),vl.error(t)}}a(xoe,"initTestEnvironment")});var yA=m((IRe,J0)=>{"use strict";var Bl=Y();Bl.initSync();var rc=require("fs-extra"),bA=require("path"),sc=R(),koe=require("crypto"),$oe=require("uuid").v4;J0.exports=Voe;function Voe(){if(Bl.getHdbBasePath()!==void 0){let e=bA.join(Bl.getHdbBasePath(),sc.LICENSE_KEY_DIR_NAME,sc.JWT_ENUM.JWT_PRIVATE_KEY_NAME),t=bA.join(Bl.getHdbBasePath(),sc.LICENSE_KEY_DIR_NAME,sc.JWT_ENUM.JWT_PUBLIC_KEY_NAME),r=bA.join(Bl.getHdbBasePath(),sc.LICENSE_KEY_DIR_NAME,sc.JWT_ENUM.JWT_PASSPHRASE_NAME);try{rc.accessSync(r),rc.accessSync(e),rc.accessSync(t)}catch(s){if(s.code==="ENOENT"){let n=$oe(),i=koe.generateKeyPairSync("rsa",{modulusLength:4096,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem",cipher:"aes-256-cbc",passphrase:n}});rc.writeFileSync(r,n),rc.writeFileSync(e,i.privateKey),rc.writeFileSync(t,i.publicKey)}else throw s}}}a(Voe,"checkJWTTokenExist")});var X0=m((CRe,j0)=>{"use strict";var IA=class{static{a(this,"HdbInfoInsertObject")}constructor(t,r,s){this.info_id=t,this.data_version_num=r,this.hdb_version_num=s}};j0.exports={HdbInfoInsertObject:IA}});var tF=m((DRe,eF)=>{"use strict";var Z0=R(),wA=class{static{a(this,"UpgradeObject")}constructor(t,r){this[Z0.UPGRADE_JSON_FIELD_NAMES_ENUM.DATA_VERSION]=t,this[Z0.UPGRADE_JSON_FIELD_NAMES_ENUM.UPGRADE_VERSION]=r}};eF.exports={UpgradeObject:wA}});var Eh=m((MRe,sF)=>{"use strict";var es=require("prompt"),nc=require("chalk"),rF=C(),gs=require("os"),CA=Gi(),LA=["yes","y"];async function Yoe(e){let t=`${gs.EOL}`+nc.bold.green("Your current HarperDB version requires that we complete an update process.")+`${gs.EOL}If a backup of your data has not been created, we recommend you cancel this process and backup before proceeding.${gs.EOL}${gs.EOL}You can read more about the changes in this upgrade at https://harperdb.io/developers/release-notes/${gs.EOL}`;es.override=CA(["CONFIRM_UPGRADE"]),es.start(),es.message=t;let r={properties:{CONFIRM_UPGRADE:{description:nc.magenta(`${gs.EOL}[CONFIRM_UPGRADE] Do you want to upgrade your HDB instance now? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"no",required:!0}}},s;try{s=await es.get([r])}catch(n){return rF.error("There was an error when prompting user about an upgrade."),rF.error(n),!1}return LA.includes(s.CONFIRM_UPGRADE)}a(Yoe,"forceUpdatePrompt");async function Koe(e){let t=`${gs.EOL}`+nc.bold.green(`Your installed HarperDB version is older than the version used to create your data. Downgrading is not recommended as it is not tested and guaranteed to work. However, if you need to downgrade, and a backup of your data has not been created, we recommend you cancel this process and backup before proceeding.${gs.EOL}`);es.override=CA(["CONFIRM_DOWNGRADE"]),es.start(),es.message=t;let r={properties:{CONFIRM_DOWNGRADE:{description:nc.magenta(`${gs.EOL}[CONFIRM_DOWNGRADE] Do you want to proceed with using your downgraded HDB instance now? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"no",required:!0}}},s=await es.get([r]);return LA.includes(s.CONFIRM_DOWNGRADE)}a(Koe,"forceDowngradePrompt");async function Woe(){let e=`${gs.EOL}`+nc.bold.green("We now require a Certifacte Authority certificate. HarperDB can generate all new certificates for you (your existing certificates will be backed up) or you can keep any existing certificates and add your own CA certificate. To add your own CA certificate set the <certificateAuthority> parameter in harperdb-config.yaml");es.override=CA(["GENERATE_CERTS"]),es.start(),es.message=e;let t={properties:{GENERATE_CERTS:{description:nc.magenta(`${gs.EOL}[GENERATE_CERTS] Do you want HarperDB to generate all new certificates? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"yes",required:!0}}},r=await es.get([t]);return LA.includes(r.GENERATE_CERTS)}a(Woe,"upgradeCertsPrompt");sF.exports={forceUpdatePrompt:Yoe,forceDowngradePrompt:Koe,upgradeCertsPrompt:Woe}});var UA=m((vRe,nF)=>{"use strict";var DA=class{static{a(this,"UpgradeDirective")}constructor(t){this.version=t,this.sync_functions=[],this.async_functions=[]}};nF.exports=DA});var oF=m((xRe,iF)=>{"use strict";var Qoe=F(),zoe=et(),HRe=C(),qRe=require("path"),FRe=require("fs"),GRe=R();iF.exports={getOldPropsValue:Joe};function Joe(e,t,r=!1){let s=t.getRaw(e);return Qoe.isNotEmptyAndHasValue(s)?s:r?zoe.getDefaultConfig(e):""}a(Joe,"getOldPropsValue")});var lF=m(($Re,uF)=>{"use strict";var wi=require("path"),Ci=require("fs-extra"),joe=require("properties-reader"),Xoe=UA(),at=C(),{getOldPropsValue:Le}=oF(),{HDB_SETTINGS_NAMES:Q,CONFIG_PARAMS:Bo}=R(),Ho=et(),fh=Y(),aF=F(),Zs=R(),MA=new Xoe("3.1.0"),cF=[];function Zoe(){let e=joe(fh.get(Q.SETTINGS_PATH_KEY)),t="Updating settings file for version 3.1.0";console.log(t),at.info(t);let r=` ;Settings for the HarperDB process.
|
|
32
|
+
`+UR.readFileSync(o):"")};s.http2=!0,s.https=c}return s}a(sne,"getServerOptions");function nne(){let e=ps.get(Wse),t=ps.get(Qse),r;return e&&(e===!0||e.toUpperCase()===KH)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(s,n)=>n(null,t.indexOf(s)!==-1))),r}a(nne,"getCORSOpts");function ine(){return ps.get(jse)}a(ine,"getHeaderTimeoutConfig")});var oq=m((dge,iq)=>{"use strict";var{decode:one}=require("msgpackr"),{isMainThread:ane,parentPort:cne,threadId:lge}=require("worker_threads"),MR=Qe(),Qa=Me(),une=R(),gl=C(),zH=Y(),XH=R();tt();var lne=mn(),{recordAction:_ne,recordActionBinary:dne}=(co(),re(Nd)),{publishToStream:Ene}=MR,_ge={durable:Qa.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:Qa.WORK_QUEUE_CONSUMER_NAMES.deliver_group},fne,hne,mne,ZH,eq;iq.exports={initialize:tq,workQueueListener:nq,setSubscription:pne,setIgnoreOrigin:Tne,getDatabaseSubscriptions:Sne};async function tq(){eq=!0,gl.notify("Starting clustering ingest service.");let{connection:e,jsm:t,js:r}=await MR.getNATSReferences();fne=e,hne=e.info.server_name,mne=t,ZH=r}a(tq,"initialize");var Pf=new Map;function pne(e,t,r){let s=Pf.get(e);s||Pf.set(e,s=new Map),s.set(t,r),eq||tq().then(nq)}a(pne,"setSubscription");function Sne(){return Pf}a(Sne,"getDatabaseSubscriptions");var rq;function Tne(e){rq=e}a(Tne,"setIgnoreOrigin");var sq=100,JH=new Array(sq),Mf=0;async function nq(){let t=await(await ZH.consumers.get(Qa.WORK_QUEUE_CONSUMER_NAMES.stream_name,Qa.WORK_QUEUE_CONSUMER_NAMES.durable_name)).consume();for await(let r of t)await JH[Mf],JH[Mf]=gne(r).catch(s=>{gl.error(s)}),++Mf>=sq&&(Mf=0)}a(nq,"workQueueListener");ane||cne.on("message",async e=>{let{type:t}=e;t===XH.ITC_EVENT_TYPES.SHUTDOWN&&MR.closeConnection()});async function gne(e){let t=one(e.data);_ne(e.data.length,"bytes-received",e.subject,t.operation,"ingest");let n=e.headers.get(Qa.MSG_HEADERS.ORIGIN)===zH.get(une.CONFIG_PARAMS.CLUSTERING_NODENAME)&&!rq;if(dne(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}try{let{operation:i,schema:o,next:c,table:u,records:l,hash_values:_,__origin:d}=t;gl.trace("processing message:",i,o,u,(l?"records: "+l.map(A=>A.id):"")+(_?"ids: "+_:""),"with sequence:",e.seq),gl.trace(`messageProcessor nats msg id: ${e.headers.get(Qa.MSG_HEADERS.NATS_MSG_ID)}`);let E;l||(l=_);let{timestamp:f,user:h,node_name:S}=d||{},T=Pf.get(o)?.get(u);if(!T)throw new Error("Missing table for replication message",u);if(i==="define_schema")t.type=i,T.send(t);else if(l.length===1&&!c)T.send({type:jH(i),value:l[0],id:_?.[0],timestamp:f,table:u,onCommit:E,user:h,nodeName:S});else{let A=l.map((g,x)=>({type:jH(i),value:g,id:_?.[x],table:u}));for(;c;)A.push({type:c.operation,value:c.record,id:c.id,table:c.table}),c=c.next;T.send({type:"transaction",writes:A,table:u,timestamp:f,onCommit:E,user:h,nodeName:S})}zH.get(XH.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&Ene(e.subject.split(".").slice(0,-1).join("."),lne.createNatsTableStreamName(o,u),e.headers,e.data)}catch(i){gl.error(i)}e.ack()}a(gne,"messageProcessor");function jH(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(jH,"convertOperation")});var FR={};Ke(FR,{disableNATS:()=>Ane,setNATSReplicator:()=>PR,start:()=>Rne});function Rne(){Bf.default.get(Hf.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&Nne()}function Ane(e=!0){_q=e}function Nne(){if(_q)return;let e=us(),t=Object.keys(e);t.push("system");for(let r of t){let s=e[r];for(let n in s){let i=s[n];PR(n,r,i)}}GR((r,s)=>{PR(r.tableName,r.databaseName,r),s&&Eq(r)}),!aq&&(aq=!0)}function PR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.Source?.isNATSReplicator)return;let s;r.sourcedFrom(class extends bt{static{a(this,"NATSReplicator")}put(o){let c;return s?.put&&(!s.put.reliesOnPrototype||s.prototype.put)&&(c=s.put(this[ue],o,this.getContext())),n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[ue],record:o},c)}delete(){let o;return s?.delete&&(!s.delete.reliesOnPrototype||s.prototype.delete)&&(o=s.delete(this[ue],this.getContext())),n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[ue]},o)}publish(o){let c;return s?.publish&&(!s.publish.reliesOnPrototype||s.prototype.publish)&&(c=s.publish(this[ue],o,this.getContext())),n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[ue],record:o},c)}invalidate(o){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[ue]})}static defineSchema(o){Eq(o)}static mergeSource(o,c){return s=o,s?.get&&(!s.get.reliesOnPrototype||s.prototype.get)&&(c?.replicationSource?this.get=async(u,l)=>{let _=await s.get(u,l);return _&&n(l).addWrite(t,{operation:"put",table:e,id:u,record:_}),_}:this.get=(u,l)=>s.get(u,l)),this}static subscribe(){let o=new ys;return(0,cq.setSubscription)(t,e,o),o}static subscribeOnThisThread(o){return o<One}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0});function n(i){let o=i?.transaction?.nats;return o||(i?.transaction?(i.transaction.push(o=i.transaction.nats=new vf(i.transaction,i)),o.user=i.user):o=dq),o}a(n,"getNATSTransaction")}function Eq(e){let t=Bf.default.get(Hf.default.CONFIG_PARAMS.CLUSTERING_NODENAME);(0,BR.publishToStream)(`${HR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,qR.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var BR,HR,qR,cq,uq,Bf,Hf,lq,_q,One,dq,aq,vf,vR,fq=Te(()=>{_e();Is();BR=D(Qe()),HR=D(Me()),qR=D(mn());Dc();cq=D(oq()),uq=D(Ht()),Bf=D(Y()),Hf=D(R()),lq=D(C());a(Rne,"start");a(Ane,"disableNATS");One=2;a(Nne,"assignReplicationSource");a(PR,"setNATSReplicator");a(Eq,"publishSchema");vf=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r,s){let n=this.writes_by_db.get(t);if(n||this.writes_by_db.set(t,n=[]),s?.then)return s.then(()=>n.push(r));n.push(r)}commit(t){let r=Bf.default.get(Hf.default.CONFIG_PARAMS.CLUSTERING_NODENAME),s=[];for(let[n,i]of this.writes_by_db){let o=[],c=[],u,l;for(let _ of i){let d=_.table,E=_.operation=="put"?"upsert":_.operation;u||(lq.trace(`Sending transaction event ${E}`),l=u={operation:E,schema:n,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,E!=="delete"&&(u.records=o)),u.table===d&&u.operation===E?(o.push(_.record),c.push(_.id)):l=l.next={operation:E,table:d,id:_.id,record:_.record}}s.push((0,BR.publishToStream)(`${HR.SUBJECT_PREFIXES.TXN}.${n}.${u.table}`,(0,qR.createNatsTableStreamName)(n,u.table),void 0,u))}return Promise.all(s)}},vR=class extends vf{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,uq.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit()}};dq=new vR});async function mq({clientId:e,user:t,listener:r,clean:s}){let n;if(e&&!s){let i=await xR.getResource(e,{});n=new $R(e,t,i),i&&(n.sessionWasPresent=!0)}else{if(e){let i=await xR.get(e);i&&i.delete()}n=new Ff(e,t)}return n}function kR(){return qf++,qf>65500&&(qf=1),qf}var hq,Rl,xR,qf,Ff,$R,pq=Te(()=>{_e();Qu();hq=D(Ht()),Rl=D(C());Yi();xR=ft({database:"system",table:"hdb_durable_session",attributes:[{name:"id",isPrimaryKey:!0},{name:"subscriptions",type:"array",elements:{attributes:[{name:"topic"},{name:"qos"},{name:"startTime"},{name:"acks"}]}}]});a(mq,"getSession");qf=1;a(kR,"getNextMessageId");Ff=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,s){let{topic:n,omitCurrent:i,startTime:o}=t,c=n.indexOf("?"),u,l;if(c>-1?(u=n.slice(c),l=n.slice(0,c)):l=n,!l)throw new Error("No topic provided");let _=!1,d;if((l.endsWith("+")||l.endsWith("#"))&&(_=!0,l.endsWith("+")&&(d=!0),l=l.slice(0,l.length-1)),l.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");if(l.indexOf("#")>-1||l.indexOf("+")>-1)throw new Error("Only trailing wildcards are supported");let E=this.subscriptions.find(g=>g.topic===n);E&&(E.end(),this.subscriptions.splice(this.subscriptions.indexOf(E),1));let f={search:u,user:this.user,startTime:o,omitCurrent:i,isCollection:_,shallowWildcard:d,url:""},h=hi.getMatch(l);if(!h)throw new Error(`The topic ${n} does not exist, no resource has been defined to handle this topic`);f.url=h.relativeURL;let S=h.path,T=h.Resource,A=await Xe(f,async()=>{let g=await T.subscribe(f);if(!g)throw new Error(`No subscription was returned from subscribe for topic ${n}`);if(!g[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${n}`);return(async()=>{for await(let x of g)try{let V;if(x.type&&x.type!=="put"&&x.type!=="delete"&&x.type!=="message"||s&&!s(x))continue;r?(x.topic=n,V=this.needsAcknowledge(x)):V=kR();let I=x.id;Array.isArray(I)&&(I=Ca(I)),I==null&&(I=""),this.listener(S+"/"+I,x.value,V,t)}catch(V){(0,Rl.warn)(V)}})(),g});return A.topic=n,A.qos=t.qos,this.subscriptions.push(A),A}resume(){}needsAcknowledge(t){return kR()}acknowledge(t){}async removeSubscription(t){let r=this.subscriptions.find(s=>s.topic===t);r&&r.end()}async publish(t,r){let{topic:s,retain:n}=t;t.data=r,t.user=this.user;let i=hi.getMatch(s);if(!i)throw new Error(`Can not publish to topic ${s} as it does not exist, no resource has been defined to handle this topic`);t.url=i.relativeURL;let o=i.Resource;return Xe(t,()=>n?r===void 0?o.delete(t,t):o.put(t,t.data,t):o.publish(t,t.data,t))}setListener(t){this.listener=t}disconnect(){for(let t of this.subscriptions)t.end();this.subscriptions=[]}},$R=class extends Ff{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,s){super(t,r),this.sessionRecord=s||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.timestamp):null)}resumeSubscription(t,r,s){return super.addSubscription(t,r,s)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=kR();return this.awaitingAcks.set(r,{topic:t.topic,timestamp:t.timestamp}),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t);let s=r.topic;for(let[,n]of this.awaitingAcks)if(n.topic===s&&n.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===s){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,Rl.trace)("Received ack",s,r.timestamp),this.sessionRecord.update();return}}for(let n of this.sessionRecord.subscriptions)n.topic===s&&(n.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:s,startTime:n}=t;return s>0&&!n&&(this.sessionRecord.subscriptions=this.subscriptions.map(i=>{let o=i.startTime;return o||(o=i.startTime=(0,hq.getNextMonotonicTime)()),(0,Rl.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),xR.put(this.sessionRecord)),t.qos}}});var KR={};Ke(KR,{start:()=>yne});async function yne({server:e,port:t,webSocket:r,securePort:s,requireAuthentication:n}){let i=e.mqtt={requireAuthentication:n};r&&e.ws((o,c,u)=>{if(o.protocol==="mqtt"){let{onMessage:l,onClose:_}=gq(o,(d,E)=>{if(o.send(d),E&&o._socket.writableNeedDrain)return new Promise(f=>this._socket.once("drain",f))},c,Promise.resolve(u).then(()=>c?.user),i);o.on("message",l),o.on("close",_),o.on("error",d=>{(0,qn.info)("WebSocket error",d)})}},{subProtocol:"mqtt"}),(t||s)&&e.socket(async o=>{let c;bne&&o.remoteAddress.includes("127.0.0.1")&&(c=await(0,Rq.getSuperUser)());let{onMessage:u,onClose:l}=gq(o,_=>o.write(_),null,c,i);o.on("data",u),o.on("close",l),o.on("error",_=>{(0,qn.info)("Socket error",_)})},{port:t,securePort:s})}function gq(e,t,r,s,n){Tq||(Tq=!0,DS(_=>{_.push({metric:"mqtt-connections",connections:VR})})),VR++;let i,o={protocolVersion:4},c=(0,Gf.parser)({protocolVersion:5});function u(_){c.parse(_)}a(u,"onMessage");function l(){VR--,i?.disconnect()}return a(l,"onClose"),c.on("packet",async _=>{s?.then&&(s=await s),i?.then&&await i;try{switch(_.cmd){case"connect":if(o.protocolVersion=_.protocolVersion,_.username)try{s=await Et.auth(_.username,_.password.toString()),(0,YR.get)(Fn.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&Sq.notify({username:s.username,status:Fn.AUTH_AUDIT_STATUS.SUCCESS,type:Fn.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,YR.get)(Fn.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&Sq.error({username:s.username,status:Fn.AUTH_AUDIT_STATUS.FAILURE,type:Fn.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),d({cmd:"connack",reasonCode:134,returnCode:134})}if(!s&&n.requireAuthentication)return d({cmd:"connack",reasonCode:134,returnCode:134});try{n.authorizeClient?.(_,s),i=mq({user:s,..._}),i=await i}catch(g){return(0,qn.error)(g),d({cmd:"connack",reasonCode:g.code||128,returnCode:g.code||128})}d({cmd:"connack",sessionPresent:i.sessionWasPresent,reasonCode:0,returnCode:0}),i.setListener((g,x,V,I)=>{try{let b=g.indexOf("/",1),M=b>0?g.slice(0,b):g;d({cmd:"publish",topic:g,payload:E(x),messageId:V||Math.floor(Math.random()*1e8),qos:I.qos},M)}catch(b){(0,qn.error)(b),i?.disconnect()}}),i.sessionWasPresent&&await i.resume();break;case"subscribe":let f=[];for(let g of _.subscriptions){let x;try{x=(await i.addSubscription(g,g.qos>=1)).qos||0}catch(V){(0,qn.error)(V),x=128}f.push(x)}await i.committed,d({cmd:"suback",granted:f,messageId:_.messageId});break;case"unsubscribe":for(let g of _.unsubscriptions)i.removeSubscription(g);d({cmd:"unsuback",messageId:_.messageId});break;case"pubrel":d({cmd:"pubcomp",messageId:_.messageId,reasonCode:0});return;case"publish":let h=_.qos===2?"pubrec":"puback",S=e.deserialize||(e.deserialize=Ba(r?.headers["content-type"])),T=_.payload?.length>0?S(_.payload):void 0,A;try{A=await i.publish(_,T)}catch(g){console.warn(g),_.qos>0&&d({cmd:h,messageId:_.messageId,reasonCode:128},_.topic)}_.qos>0&&d({cmd:h,messageId:_.messageId,reasonCode:A===!1?144:0},_.topic);break;case"pubrec":d({cmd:"pubrel",messageId:_.messageId,reasonCode:0});break;case"pubcomp":case"puback":i.acknowledge(_.messageId);break;case"pingreq":d({cmd:"pingresp"});break;case"disconnect":i?.disconnect(),e.close?e.close():e.end();break}}catch(f){console.error(f),d({cmd:"disconnect"})}function d(f,h){let S=(0,Gf.generate)(f,o);t(S),qs(S.length,"bytes-sent",h,f.cmd,"mqtt")}a(d,"sendPacket");function E(f){return r?Cn(f,r):JSON.stringify(f)}a(E,"serialize")}),{onMessage:u,onClose:l}}var Gf,Rq,YR,Fn,qn,Sq,bne,Tq,VR,Aq=Te(()=>{Gf=require("mqtt-packet");pq();Rq=D(er());Da();co();rs();YR=D(Y()),Fn=D(R()),qn=D(C()),Sq=(0,qn.loggerWithTag)("auth-event"),bne=!0;a(yne,"start");VR=0;a(gq,"onSocket")});var Uq={};Ke(Uq,{loadComponent:()=>xf,loadComponentDirectories:()=>Dq});function Dq(e,t){t&&(QR=t),e&&(zR=e);let r=[];if((0,Qs.existsSync)(WR)){let n=(0,Qs.readdirSync)(WR,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,Zr.join)(WR,o);r.push(xf(c,QR,"hdb",!1))}}let s=process.env.RUN_HDB_APP;return s&&r.push(xf(s,QR,s)),Promise.all(r).then(()=>{Lq=!0})}async function xf(e,t,r,s,n){if(!Nq.has(e)){Nq.set(e,!0),n&&(zR=n);try{let i,o=(0,Zr.join)(e,s?"harperdb-config.yaml":"config.yaml");(0,Qs.existsSync)(o)?i=(0,bq.parseDocument)((0,Qs.readFileSync)(o,"utf8"),{simpleKeys:!0}).toJSON():i=Lne;let c=[];for(let u in i){let l=i[u];if(!l)continue;let _,d=l.package;if(d){let E=e,f;for(;!(0,Qs.existsSync)(f=(0,Zr.join)(E,"node_modules",u));)if(E=(0,Zr.dirname)(E),E.length<(0,Cq.getHdbBasePath)().length){f=null;break}if(f)_=await xf(f,t,r,!1);else throw new Error(`Unable to find package ${u}:${d}`)}else _=Cne[u];if(_)try{c.push(_);let E=a(T=>(T.origin=r,ft(T)),"ensureTable"),f=l.network||(l.port||l.securePort)&&l,h=f?.securePort||f?.https&&f.port,S=!f?.https&&f?.port;if(Al.isMainThread&&(_=await _.startOnMainThread?.({server:Et,ensureTable:E,port:S,securePort:h,resources:t,...l})||_,s&&f))for(let T of[S,h])try{if(+T&&!Oq.includes(T)){Oq.push(T);let A=JR.get(jR.CONFIG_PARAMS.HTTP_SESSION_AFFINITY);CR(T,A)}}catch(A){console.error("Error listening on socket",T,A,u)}if(t.isWorker&&(_=await _.start?.({server:Et,ensureTable:E,port:S,securePort:h,resources:t,...l})||_),zR.set(_,!0),_.handleFile&&l.files){if(l.files.includes(".."))throw(0,wq.handleHDBError)("Can not reference parent directories");let T=(0,Zr.join)(e,l.files);for(let A of await(0,yq.default)(T,{onlyFiles:!1,objectMode:!0})){let{path:g,dirent:x}=A,V=(0,Zr.relative)(e,g),I=(0,Zr.basename)(e),b=l.path||"/";b=b.startsWith("/")?b:b.startsWith("./")?"/"+I+b.slice(2):b==="."?"/"+I:"/"+I+"/"+b,b+=(b.endsWith("/")?"":"/")+V;try{if(x.isFile()){let M=await wne(g);Al.isMainThread&&await _.setupFile?.(M,b,g,t),t.isWorker&&await _.handleFile?.(M,b,g,t)}else Al.isMainThread&&await _.setupDirectory?.(b,g,t),t.isWorker&&await _.handleDirectory?.(b,g,t)}catch(M){console.error(`Could not load ${x.isFile()?"file":"directory"} ${g} using ${l.module} for application ${e}`,M),t.set(l.path||"/",new Ol(M))}}}}catch(E){console.error(`Could not load component ${u} for application ${e}`,E),t.set(l.path||"/",new Ol(E),null,!0)}}if(Al.isMainThread&&!Lq&&(0,Iq.watchDir)(e,async()=>Dq()),i.extensionModule)return await A_((0,Zr.join)(e,i.extensionModule))}catch(i){console.error(`Could not load application directory ${e}`,i),t.set("",new Ol(i))}}}var Qs,Zr,Al,bq,JR,jR,yq,Iq,wq,Cq,Ine,wne,WR,zR,Lq,QR,Cne,Lne,Oq,Nq,Ol,Mq=Te(()=>{Qs=require("fs"),Zr=require("path"),Al=require("worker_threads"),bq=require("yaml"),JR=D(Y()),jR=D(R());qN();kN();$N();$v();wH();UH();yq=D(require("fast-glob")),Iq=D(tt());lm();rs();wq=D(z());Is();_e();Uf();Cq=D(Y()),Ine=D(QH());DE();fq();Aq();({readFile:wne}=Qs.promises),WR=JR.get(jR.CONFIG_PARAMS.CUSTOMFUNCTIONS_ROOT),zR=new Map;a(Dq,"loadComponentDirectories");Cne={REST:Bg,graphqlSchema:um,jsResource:dm,fastifyRoutes:hR,login:fm,static:mR,operationsApi:Ine,customFunctions:{},clustering:FR,authentication:zu,mqtt:KR},Lne={REST:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}},Oq=[],Nq=new Map;a(xf,"loadComponent");Ol=class extends bt{constructor(r){super();this.error=r}static{a(this,"ErrorResource")}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var Fq=m((Gge,qq)=>{"use strict";var Vf=require("fs-extra"),XR=require("path"),kf=C(),Pq=F(),$f=R(),Hq=Y(),Dne=et();qq.exports=Une;async function Une(){let e=Mne(),t=Hq.get($f.CONFIG_PARAMS.ROOTPATH),r=XR.join(t,"package.json"),s={dependencies:{harperdb:"file:"+$f.PACKAGE_ROOT}},n=XR.join(t,"node_modules");await Vf.ensureDir(n);let i,o=!0,c=!1;try{i=await Vf.readJson(r)}catch(u){if(Pq.isEmptyOrZeroLength(e))return;if(u.code!==$f.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!Pq.isEmptyOrZeroLength(e)){for(let{name:u,package:l}of e){let _=await vq(l);s.dependencies[u]=_+l}if(!o){kf.notify("Installing components"),await Bq(r,s);return}for(let{name:u,package:l}of e){let _=i.dependencies[u],d=await vq(l);if(_===void 0||_!==d+l){c=!0;break}}}for(let u in i.dependencies)s.dependencies[u]===void 0&&(kf.notify("Removing component",u),c=!0);c&&(kf.notify("Updating components."),await Bq(r,s))}a(Une,"installComponents");function Mne(){let e=Dne.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(Mne,"getComponentsConfig");async function vq(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":XR.extname(e)||await Vf.pathExists(e)?"file:":"github:"}a(vq,"getPkgPrefix");async function Bq(e,t){kf.trace("npm installing components package.json",t),await Vf.writeFile(e,JSON.stringify(t,null," ")),await GE().installAllRootModules(Hq.get($f.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}a(Bq,"installPackages")});var yf=m((kge,xq)=>{var{isMainThread:Gq}=require("worker_threads"),{getTables:Pne}=(_e(),re(be)),{loadComponentDirectories:vne,loadComponent:Bne}=(Mq(),re(Uq)),{resetResources:Hne}=(Qu(),re(SP)),qne=Fq(),Fne=et(),{dirname:Gne}=require("path"),{getConnection:xne}=Qe(),kne=Y(),$ne=R(),ZR=new Map;async function Vne(e=!1){!Gq&&kne.get($ne.CONFIG_PARAMS.CLUSTERING_ENABLED)&&xne(),Gq&&await qne();let t=Hne();Pne(),t.isWorker=e,await Bne(Gne(Fne.getConfigFilePath()),t,"hdb",!0,ZR),await vne(ZR,t);let r=[];for(let[s]of ZR)s.ready&&r.push(s.ready());r.length>0&&await Promise.all(r)}a(Vne,"loadRootComponents");xq.exports.loadRootComponents=Vne});var tt=m((Yge,Ni)=>{"use strict";var{Worker:Yne,MessageChannel:Kne,parentPort:zs,isMainThread:nA,threadId:Wne,workerData:Nl}=require("worker_threads"),{PACKAGE_ROOT:Qne}=R(),{join:Vq,isAbsolute:zne,extname:Kf}=require("path"),{server:Jne}=(rs(),re(Pc)),{watch:jne,readdir:Xne}=require("fs/promises"),{totalmem:kq}=require("os"),iA=R(),wo=C(),Vge=R(),{randomBytes:Zne}=require("crypto"),eie=1024*1024,Oi=[],Ai=[],tie=50,Yq=1e4,rie="restart",Kq="request_thread_info",Wq="resource_report",Qq="thread_info",zq="added-port",sie="ack",eA;Ni.exports={startWorker:tA,restartWorkers:oA,shutdownWorkers:aie,workers:Oi,setMonitorListener:hie,onMessageFromWorkers:cie,onMessageByType:uie,broadcast:lie,broadcastWithAcknowledgement:die,setChildListenerByType:oie,getWorkerIndex:jq,getTicketKeys:Xq,setMainIsWorker:nie,restartNumber:Nl?.restartNumber||1};var Jq;function jq(){return Nl?Nl.workerIndex:Jq?0:void 0}a(jq,"getWorkerIndex");function nie(e){Jq=e}a(nie,"setMainIsWorker");var Yf;function Xq(){return Yf||(Yf=nA?Zne(48):Nl.ticketKeys,Yf)}a(Xq,"getTicketKeys");Object.defineProperty(Jne,"workerIndex",{get(){return jq()}});var Zq={[Kq](e,t){Eie(t)},[Wq](e,t){fie(t,e)}};function tA(e,t={}){let r=process.constrainedMemory?.()||kq();r=Math.min(r,kq());let s=Math.max(Math.floor(r/eie/(1+(t.threadCount||1)/4)),512),n=Math.min(Math.max(s>>7,16),64),i=[];for(let c of Ai){let{port1:u,port2:l}=new Kne;c.postMessage({type:zq,port:u},[u]),i.push(l)}Kf(e)||(e+=".js");let o=new Yne(zne(e)?e:Vq(Qne,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:s,maxYoungGenerationSizeMb:n},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:i,workerIndex:t.workerIndex,name:t.name,restartNumber:Ni.exports.restartNumber,ticketKeys:Xq()},transferList:i},t));return Qf(o,!0),o.unexpectedRestarts=t.unexpectedRestarts||0,o.startCopy=()=>{tA(e,t)},o.on("error",c=>{console.error("Worker error:",c),wo.error("Worker error:",c)}),o.on("exit",c=>{Oi.splice(Oi.indexOf(o),1),!o.wasShutdown&&t.autoRestart!==!1&&(o.unexpectedRestarts<tie?(t.unexpectedRestarts=o.unexpectedRestarts+1,tA(e,t)):wo.error(`Thread has been restarted ${o.restarts} times and will not be restarted`))}),o.on("message",c=>{Zq[c.type]?.(c,o)}),Oi.push(o),pie(),t.onStarted&&t.onStarted(o),o.name=t.name,o}a(tA,"startWorker");var iie=[iA.THREAD_TYPES.HTTP];async function oA(e=null,t=2,r=!0){if(nA){if(r){let{loadRootComponents:n}=yf();await n()}Ni.exports.restartNumber++,t<1&&(t=t*Oi.length);let s=[];for(let n of Oi.slice(0)){if(e&&n.name!==e||n.wasShutdown)continue;n.postMessage({restartNumber:Ni.exports.restartNumber,type:iA.ITC_EVENT_TYPES.SHUTDOWN}),n.wasShutdown=!0,n.emit("shutdown",{});let i=iie.indexOf(n.name)>-1,o=new Promise(c=>{let u=setTimeout(()=>n.terminate(),Yq*2).unref();n.on("exit",()=>{clearTimeout(u),s.splice(s.indexOf(o)),!i&&r&&n.startCopy(),c()})});s.push(o),i&&r&&(n.startCopy(),s.length>=t&&await Promise.race(s))}await Promise.all(s)}else zs.postMessage({type:rie,workerType:e})}a(oA,"restartWorkers");function oie(e,t){Zq[e]=t}a(oie,"setChildListenerByType");function aie(e){return oA(e,1/0,!1)}a(aie,"shutdownWorkers");var e0=[];function cie(e){e0.push(e)}a(cie,"onMessageFromWorkers");var rA=new Map;function uie(e,t){let r=rA.get(e);r||rA.set(e,r=[]),r.push(t)}a(uie,"onMessageByType");function lie(e){for(let t of Ai)try{t.postMessage(e)}catch(r){wo.error("Unable to send message to worker",r)}}a(lie,"broadcast");var Wf=new Map,_ie=1;function die(e){return new Promise(t=>{let r=0;for(let s of Ai)try{let n=_ie++,i=a(()=>{Wf.delete(n),--r===0&&t(),s!==zs&&--s.refCount===0&&s.unref()},"ack_handler");i.port=s,s.ref(),s.refCount=(s.refCount||0)+1,Wf.set(e.requestId=n,i),s.hasAckCloseListener||(s.hasAckCloseListener=!0,s.on(s.close?"close":"exit",()=>{for(let[,o]of Wf)o.port===s&&o()})),s.postMessage(e),r++}catch(n){wo.error("Unable to send message to worker",n)}r===0&&t()})}a(die,"broadcastWithAcknowledgement");function Eie(e){e.postMessage({type:Qq,workers:t0()})}a(Eie,"sendThreadInfo");function t0(){let e=Date.now();return Oi.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}a(t0,"getChildWorkerInfo");function fie(e,t){e.resources=t,e.resources.updated=Date.now()}a(fie,"recordResourceReport");var sA;function hie(e){sA=e}a(hie,"setMonitorListener");var mie=1e3,$q=!1;function pie(){$q||($q=!0,setInterval(()=>{for(let e of Oi){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}sA&&sA()},mie).unref())}a(pie,"startMonitoring");var Sie=1e3;if(zs){Qf(zs);for(let e of Nl.addPorts)Qf(e);setInterval(()=>{let e=process.memoryUsage();zs.postMessage({type:Wq,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},Sie).unref(),eA=a(()=>new Promise((e,t)=>{zs.on("message",r),zs.postMessage({type:Kq});function r(s){s.type===Qq&&(zs.off("message",r),e(s.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else eA=t0;Ni.exports.getThreadInfo=eA;function Qf(e,t){Ai.push(e),e.on("message",r=>{if(r.type===zq)Qf(r.port);else if(r.type===sie){let s=Wf.get(r.id);s&&s()}else{for(let n of e0)n(r,e);let s=rA.get(r.type);if(s)for(let n of s)try{n(r,e)}catch(i){wo.error(i)}}}).on("close",()=>{Ai.splice(Ai.indexOf(e),1)}).on("exit",()=>{Ai.splice(Ai.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(Qf,"addPort");if(nA){let e,t,r=a(async(s,n)=>{n&&(e=n);for(let i of await Xne(s,{withFileTypes:!0}))i.isDirectory()&&r(Vq(s,i.name));for await(let{filename:i}of jne(s,{persistent:!1}))(Kf(i)===".ts"||Kf(i)===".js"||Kf(i)===".graphql")&&(t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await oA(),wo.info("Reloaded HarperDB components")},100))},"watch_dir");Ni.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else zs.on("message",async e=>{let{type:t}=e;t===iA.ITC_EVENT_TYPES.SHUTDOWN&&(Ni.exports.restartNumber=e.restartNumber,zs.unref(),setTimeout(()=>{wo.warn("Thread did not voluntarily terminate",Wne),process.exit(0)},Yq).unref())})});function _A(e){let t=e.auditStore=e.openDB(o0.AUDIT_STORE_NAME,gie);t.rootStore=e;let r=[];return t.addDeleteRemovalCallback=function(s,n){return r[s]=n,{remove(){delete r[s]}}},(0,c0.getWorkerIndex)()===0&&e.on("aftercommit",()=>{cA||(cA=setTimeout(()=>{if(cA=null,t.rootStore.status!=="closed")for(let{key:s,value:n}of t.getRange({start:[0,0],end:[Date.now()-r0,0]})){if((n[0]&15)===lA){let i=s[1];r[i]?.(s[2])}t.remove(s)}},r0/10).unref())}),t}function jf(e,t,r){let s=_0[r.type],n=3;if(t?t.length>80?(s|=zf,n=(0,Gn.writeKey)(t,Js,e?14:6),aA.setUint16(2,n)):(n=(0,Gn.writeKey)(t,Js,e?11:3),Js[1]=n):Js[1]=0,e){s|=l0;let i=s&zf?6:3;aA.setFloat64(i,e),t||(n=i+8)}return Js[0]=s,s&zf?aA.setUint16(4,0):Js[2]=0,r.value?Buffer.concat([Js.slice(0,n),r.value]):Js.subarray(0,n)}function bi(e,t){let r=e[0],s=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength)),n=r&zf,i=n?6:3,o;r&l0&&(o=s.getFloat64(i),i+=8);let c;n?c=s.getUint16(2):c=e[1];let u=r&uA?t.decoder.decode(e.subarray(c||i)):void 0;return{type:_0[r&7],value:u,lastVersion:o,get user(){return c?(0,Gn.readKey)(e,i,c):void 0}}}var Gn,Jf,o0,a0,c0,u0,Js,aA,Tie,gie,r0,cA,uA,s0,lA,n0,i0,zf,l0,_0,bl=Te(()=>{Gn=require("ordered-binary"),Jf=D(Y()),o0=D(Ge()),a0=D(R()),c0=D(tt()),u0=D(F());(0,Jf.initSync)();Js=Buffer.alloc(1024),aA=new DataView(Js.buffer,Js.byteOffset,1024),Tie={writeKey(e,t,r){if(Array.isArray(e)){let s=t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength));return s.setFloat64(r,e[0]),s.setUint32(r+8,e[1]),(0,Gn.writeKey)(e[2],t,r+12)}else return(0,Gn.writeKey)(e,t,r)},readKey(e,t,r){if(e[t]>40){let s=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength));return[s.getFloat64(t),s.getUint32(t+8),(0,Gn.readKey)(e,t+12,r)]}else return(0,Gn.readKey)(e,t,r)}},gie={encoding:"binary",keyEncoder:Tie},r0=(0,u0.convertToMS)((0,Jf.get)(a0.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,cA=null;a(_A,"openAuditStore");uA=16,s0=1,lA=2,n0=3,i0=4,zf=128,l0=64,_0={put:s0|uA,[s0]:"put",delete:lA,[lA]:"delete",message:n0|uA,[n0]:"message",invalidate:i0,[i0]:"invalidate"};a(jf,"createAuditEntry");a(bi,"readAuditEntry")});var dA,Co,Rie,yl,Xf,d0=Te(()=>{dA=D(Ht());bl();Co=Symbol("completion"),Rie=100,yl=class{static{a(this,"DatabaseTransaction")}writes=[];hasWrittenTime;username;lmdbDb;auditStore;readTxn;constructor(t,r,s){this.lmdbDb=t,this.username=r?.username,this.auditStore=s}getReadTxn(){return this.readTxn||(this.readTxn=this.lmdbDb.useReadTransaction())}resetReadSnapshot(){this.readTxn&&(this.readTxn.done(),this.readTxn=null)}addWrite(t){this.writes.push(t)}validate(){for(let t of this.writes||[])t.validate?.()}commit(t=(0,dA.getNextMonotonicTime)(),r=!0,s=0){this.resetReadSnapshot();let n,i=[],o=0,c;this.hasWrittenTime=!1;let u=a(_=>{let d=_.commit(t,s);if(d&&(d[Co]&&(i||(i=[]),i.push(d[Co])),c=_.store,this.auditStore)){d.user=this.username,d.lastVersion=_.lastVersion,d.newTxnTime&&!this.hasWrittenTime&&(t=d.newTxnTime),this.hasWrittenTime=!0;let E=[t,_.store.tableId,_.key];_.invalidated&&(E.invalidated=!0),this.auditStore.put(E,jf(_.lastVersion,this.username,d))}},"doWrite"),l=a(()=>{let _=this.writes[o++];if(_)if(_.key){let d=_.store.getEntry(_.key),E=s===0&&_.lastVersion!==void 0?_.lastVersion:_.lastVersion=d?.version??null,f=_.store.ifVersion(_.key,E,l);n=n||f}else l();else for(let d of this.writes)u(d)},"nextCondition");return this.writes.length<Rie>>s?l():(s=1,n=this.writes[0].store.transaction(()=>{for(let _ of this.writes)u(_);return!0})),n?.then(_=>_?(c&&i.push(c.flushed),Promise.all(i).then(()=>(this.writes=[],{txnTime:t}))):this.commit(t,r,s+1))}abort(){this.resetReadSnapshot(),this.writes=[]}},Xf=class extends yl{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit(this.timestamp)}get timestamp(){return this._timestamp||(this._timestamp=(0,dA.getNextMonotonicTime)())}getReadTxn(){}}});function m0(e,t,r,s,n){let i=e.primaryStore.env.path,o=e.primaryStore.tableId;Ja||((0,Lo.onMessageByType)(f0,d=>{let E=d.auditIds;fA(d.path,E,d.txnId)}),(0,Lo.onMessageByType)(h0,d=>{(0,js.trace)("confirming to proceed with txn",d.txnId)}),Ja=Object.create(null));let c=Ja[i]||(Ja[i]=[]);c.auditStore=e.auditStore;let u=c[o];u||(u=c[o]=new Map,u.envs=c,u.tableId=o,u.store=e.primaryStore),t=Ca(t);let l=new EA(r);l.startTime=s,n&&(l.includeDescendants=n);let _=u.get(t);return _?_.push(l):(u.set(t,_=[l]),_.tables=u,_.key=t),l.subscriptions=_,l}function fA(e,t,r,s){if(!Ja)return;let n=Ja[e];if(n){if(za&&za+1!==r){(0,js.trace)("Waiting to ensure latest txn id",za,"proceeds",r,s);let i=(async()=>{for(let[o,c]of Zf)o<r&&((0,js.trace)("Txn",r,"waiting for txn",o),await c);if(za+1!==r){await(0,Lo.broadcastWithAcknowledgement)({type:h0,txnId:r});for(let[o,c]of Zf)o<r&&((0,js.trace)("Txn",r,"waiting for txn",o),await c)}Zf.delete(r),(0,js.trace)("Proceeding with txn id",r),za=r-1,fA(e,t,r,s)})();return Zf.set(r,i),i}(0,js.trace)("Notifying with txn id",r,s),za=r;try{n.auditStore.resetReadTxn()}catch(i){throw i.message+=" in "+e,i}e:for(let i of t){let[o,c,u]=i,l=n[c];if(!l)continue;(0,E0.writeKey)(i,Oie,0);let _=i[3];_&&(i.length=3);let d,E=Ca(u),f;do{let h=l.get(E);if(h){for(let T of h)if(!(f&&!T.includeDescendants)){if(T.startTime>=o){(0,js.info)("omitting",u,T.startTime,o);continue}try{if(T.crossThreads===!1&&!s)continue;if(d===void 0){let A=n.auditStore.get(i);if(!A||(d=bi(A,l.store),d.type!=="message"&&l.store.getEntry(i[2])?.version!==i[0])||_&&d.type!=="invalidate")continue e}T.listener(u,d,o)}catch(A){console.error(A),(0,js.info)(A)}}}if(E==null)break;let S=E.lastIndexOf?.("/",E.length-2);S>-1?E=E.slice(0,S+1):E=null,f=!0}while(!0)}}}function p0(e,t){let r=t||e,s=r.env;if(t&&!t.cache&&(t.cache=new Map),!s.hasBroadcastListener){s.hasBroadcastListener=!0;let n=s.path;r.on("aftercommit",({next:i,last:o,txnId:c})=>{let u,l=[];if(t)do{if(i.flag&Aie)continue;let _;i.meta&&i.meta.store===t&&(_=i.meta.key)&&(typeof _[2]=="symbol"&&(_[2]=null),_.invalidated&&(_[3]=!0),l.push(_))}while(i!=o&&(i=i.next));l.length!==0&&((0,Lo.broadcast)({type:f0,path:n,auditIds:l,txnId:c,start:u}),fA(n,l,c,!0))})}}var js,Lo,E0,f0,h0,Aie,Ja,Oie,EA,za,Zf,S0=Te(()=>{js=D(C()),Lo=D(tt()),E0=require("ordered-binary");Dc();Qu();bl();f0="transaction",h0="transaction-await",Aie=67108864,Oie=Buffer.alloc(4096);a(m0,"addSubscription");EA=class extends ys{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let s=t.envs,n=t.dbi;delete s[n]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}},Zf=new Map;a(fA,"notifyFromTransactionData");a(p0,"listenToCommits")});var Xg={};Ke(Xg,{coerceType:()=>eh,makeTable:()=>rh,setServerUtilities:()=>wie});function rh(e){let{primaryKey:t,indices:r,tableId:s,tableName:n,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:l,dbisDB:_}=e,{expirationMS:d,audit:E,trackDeletes:f}=e,{attributes:h}=e;h||(h=[]),p0(i,u);let S=0,T,A,g,x={},V,I,b,M;for(let Z of h)(Z.assignCreatedTime||Z.name==="__createdtime__")&&(V=Z),(Z.assignUpdatedTime||Z.name==="__updatedtime__")&&(I=Z),Z.expiresAt&&(b=Z),Z.isPrimaryKey&&(x=Z);let J;E&&hO();class B extends bt{static name=n;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=n;static indices=r;static audit=E;static databasePath=o;static databaseName=c;static attributes=h;static expirationTimer;static createdTimeProperty=V;static updatedTimeProperty=I;static dbisDB=_;static schemaDefined=l;static sourcedFrom(p,N){if(N&&(this.sourceOptions=N,N.expiration&&this.setTTLExpiration(N.expiration)),this.Source)if(this.Source.mergeSource)this.Source=this.Source.mergeSource(p,this.sourceOptions);else if(p.mergeSource)this.Source=p.mergeSource(this.Source,this.sourceOptions);else throw new Error("Can not assign multiple sources to a table with no source providing a (static) mergeSource method");else this.Source=p;return A=p&&p.get&&(!p.get.reliesOnPrototype||p.prototype.get),(async()=>{let U=!1,y=a(async L=>{let H=L.value,k=L.table?xe[c][L.table]:B;if(c===Ss.SYSTEM_SCHEMA_NAME&&(L.table===Ss.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||L.table===Ss.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(U=!0),L.id===void 0&&(L.id=H[k.primaryKey],L.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(L));let P=await k.getResource(L.id,L,Il);switch(L.type){case"put":return P._writeUpdate(H,Il);case"delete":return P._writeDelete(Il);case"publish":return P._writePublish(H,Il);case"invalidate":return P.invalidate(Il);default:Mo.error("Unknown operation",L.type,L.id)}},"writeUpdate");try{let L=p.subscribe&&(!p.subscribe.reliesOnPrototype||p.prototype.subscribe);L&&f==null&&(f=!0);let H=p.subscribeOnThisThread?p.subscribeOnThisThread((0,Uo.getWorkerIndex)()):(0,Uo.getWorkerIndex)()===0,k=L&&H&&await p.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(k)for await(let P of k)try{if(!(P.type==="transaction"?P.writes[0]:P)){console.error("Bad subscription event");continue}let X=Xe(P,()=>{if(P.type==="transaction"){let j=[];for(let K of P.writes){K[Ne]=P;try{j.push(y(K))}catch(ee){throw ee.message+=" writing "+JSON.stringify(K)+" of event "+JSON.stringify(P),ee}}return Promise.all(j)}else if(P.type==="define_schema"){let j=this.attributes.slice(0),K;for(let ee of P.attributes)j.find(Be=>Be.name===ee.name)||(j.push(ee),K=!0);K&&(ft({table:n,database:c,attributes:j,origin:"cluster"}),Ll.signalSchemaChange(new Dl.SchemaEventMsg(process.pid,Ss.OPERATIONS_ENUM.CREATE_TABLE,c,n)))}else return y(P)});P.onCommit&&(X?.then&&U&&Ll.signalUserChange(new Dl.UserEventMsg(process.pid)),X?.then?X.then(P.onCommit):P.onCommit())}catch($){console.error("error in subscription handler",$)}}catch(L){console.error(L)}})(),this}static getResource(p,N,U){let y=super.getResource(p,N,U);if(p!=null)try{if(y.hasOwnProperty(le))return y;let L=y._txnForRequest();if(typeof p=="object"&&p&&!Array.isArray(p))throw new Error(`Invalid id ${JSON.stringify(p)}`);let H,k,$={transaction:L?.getReadTxn()},X;return Zl(p,N,$,y,U?.allowInvalidated,(j,K)=>{K?k(K):(y[le]=j?.value,y[fr]=j?.version,X=!0,H?.(y))}),X?y:new Promise((j,K)=>{H=j,k=K})}catch(L){throw L.message.includes("Unable to serialize object")&&(L.message+=": "+JSON.stringify(p)),L}return y}static setTTLExpiration(p){(0,Uo.getWorkerIndex)()===0&&(d=p*1e3,this.expirationTimer&&clearInterval(this.expirationTimer),this.expirationTimer=setInterval(()=>{if(this.primaryStore.rootStore.status!=="open")return clearInterval(this.expirationTimer);for(let{key:N,value:U,version:y}of this.primaryStore.getRange({start:!1,versions:!0}))y<Date.now()-d&&y>0&&U?.__invalidated__==null&&B.evict(N,U,y)},d).unref())}static enableAuditing(){E=!0,hO(),B.audit=!0}static coerceId(p){return p===""?null:eh(p,x)}static async dropTable(){if(delete xe[c][n],c===o){for(let p in r)_.remove(B.tableName+"/"+p),r[p].drop();_.remove(B.tableName+"/"),i.drop(),await _.committed}else console.log("legacy dropTable"),await i.close(),await fs.remove(data_path),await fs.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));Ll.signalSchemaChange(new Dl.SchemaEventMsg(process.pid,Ss.OPERATIONS_ENUM.DROP_TABLE,c,n))}static Source;static get(p,N){return p&&typeof p=="object"&&!Array.isArray(p)&&p.url===""?{recordCount:this.getRecordCount(),records:"./",name:n,database:c,attributes:h}:super.get(p,N)}get(p){if(typeof p=="string")return this.getProperty(p);if(this[_n])return this.search(p);if(p?.property)return this.getProperty(p.property);if(this.doesExist()||this[Ne]?.hasOwnProperty("returnNonexistent")&&this[Ne].returnNonexistent)return this}static allowRead(p,N){if(!p)return!1;let U=p.role.permission;if(U.super_user)return!0;if(U[n]?.read){let y=U[n].attribute_permissions;if(y){N||(N={});let L=N.select;if(L){let H=hA(y,"read");N.select=L.filter(k=>H[k])}else N.select=y.filter(H=>H.read).map(H=>H.attribute_name);return N}else return!0}}allowUpdate(p,N,U){if(!p)return!1;let y=p.role.permission;if(y.super_user)return!0;if(y[n]?.update){let L=y[n].attribute_permissions;if(L){let H=hA(L,"update");for(let k in N)if(!H[k])return!1;if(U)for(let k of L){let P=k.attribute_name;!k.update&&!(P in N)&&(N[P]=this.getProperty(P))}}else return!0}}allowCreate(p,N){return this.allowUpdate(p,{})}static allowCreate(p,N){if(!p)return!1;let U=p.role.permission;if(U.super_user)return!0;if(U[n]?.insert){let y=U[n].attribute_permissions;if(y){let L=hA(y,"insert");for(let H in N)if(!L[H])return!1}else return!0}}static allowDelete(p){if(!p)return!1;let N=p.role.permission;if(N.super_user||N[n]?.delete)return!0}update(p,N){if(!this._txnForRequest())throw new Error("Can not update a table resource outside of a transaction");if(p===!1)return this;let y;if(typeof p=="object"&&p){if(N)for(let L in this[le])p[L]===void 0&&(p[L]=void 0);y=this[Nt],y&&(p=Object.assign(y,p)),this[Nt]=y=p}return!this[le]&&t&&!(y||(y=this[Nt]))?.[t]&&(y||(y=this[Nt]=Object.create(null)),y[t]=this[ue]),this._writeUpdate(this),this}invalidate(p){this._txnForRequest().addWrite({key:this[ue],store:i,invalidated:!0,lastVersion:this[fr],nodeName:this[Ne]?.nodeName,commit:(U,y)=>{if(y)return;let L={__invalidated__:U};for(let $ in r)L[$]=this.getProperty($);let H=B.Source,k,P=this[ue];return p?.isNotification||H?.shouldReceiveInvalidations&&(k=H.invalidate(P,this)),i.put(this[ue],L,U),{type:E&&"invalidate",[Co]:k}}})}static evict(p,N,U){let y=this.Source;if(y?.get&&(!y.get.reliesOnPrototype||y.prototype.get)){let L;if(!N){let H=i.getEntry(p);if(!H)return;N=H.value,U=H.version}if(N)for(let H in r)L||(L={__invalidated__:0}),L[H]=N[H];return L?i.put(p,L,U,U):i.remove(p,U)}else return i.remove(p,U)}lock(){throw new Error("Not yet implemented")}static operation(p,N){return p.table||=n,p.schema||=c,I0.operation(p,N)}async put(p){this.update(p,!0)}_writeUpdate(p,N){let U=this._txnForRequest();if(this[ue]===void 0)throw new Error("Can not save record without an id");let y=this[le],L,H,k=this[ue];y||(this[le]={}),U.addWrite({key:k,store:i,lastVersion:this[fr],nodeName:this[Ne]?.nodeName,validate:()=>{this.validate(p)},commit:(P,$)=>{let X;if($){if(L)return;let K=i.getEntry(k);y=K?.value;let ee=this[Ne];ee&&K?.version>(ee.lastModified||0)&&(ee.lastModified=K.version)}if(!H){if(H=!0,N?.isNotification)p=Mc(p);else{if(p[R0]&&(L=!f_(p),L))return;t&&p[t]!==k&&(p[t]=k),I&&(p[I.name]=I.type==="Date"?new Date(P):I.type==="String"?new Date(P).toISOString():P),V&&(y?p[V.name]=y[V.name]:p[V.name]=V.type==="Date"?new Date(P):V.type==="String"?new Date(P).toISOString():P),p=Mc(p);let K=B.Source;K?.put&&(!K.put.reliesOnPrototype||K.prototype.put)&&(X=K.put(k,p,this))}if(p[le])throw new Error("Can not assign a record with a record property");this[le]=p}if(Mo.trace("Checking timestamp for put",k,this[fr]>P,this[fr],P),this[fr]>P)return E&&{type:"put",value:i.encoder.encode(p)};let j=i.encoder.encode(p);return i.put(this[ue],(0,ja.asBinary)(j),P),_t(this[ue],y,p),y===null&&!$&&Fi(-1),{type:E&&"put",value:j,[Co]:X}}})}async delete(p){return typeof p=="string"?this.deleteProperty(p):this[le]?this._writeDelete(p):!1}_writeDelete(p){let N=this._txnForRequest(),U,y=this[ue],L;return N.addWrite({key:y,store:i,lastVersion:this[fr],nodeName:this[Ne]?.nodeName,commit:(H,k)=>{let P=this[le];if(k){let $=i.getEntry(y);P=$?.value;let X=this[Ne];X&&$?.version>(X.lastModified||0)&&(X.lastModified=$.version)}if(!U&&(U=!0,!p?.isNotification)){let $=B.Source;$?.delete&&(!$.delete.reliesOnPrototype||$.prototype.delete)&&(L=$.delete(y,this))}if(!(this[fr]>H))return _t(this[ue],P),Mo.trace("Write delete entry",E||f,H),E||f?(i.put(this[ue],null,H),E||fO(),k||Fi(1)):i.remove(this[ue]),{type:E&&"delete",[Co]:L}}}),!0}search(p){let N=this._txnForRequest();if(!p)throw new Error("No query provided");let U=p.reverse===!0,y=p.conditions;y?y.length===void 0&&(y=Array.from(y)):y=Array.isArray(p)?p:p[Symbol.iterator]?Array.from(p):[],this[ue]&&(y=[{attribute:null,comparator:"prefix",value:this[ue]}].concat(y));for(let K of y){let ee=K[0]??K.attribute,Be=ee==null?x:h.find(Wn=>Wn.name==ee);if(Be)Be.type&&(K[1]===void 0?K.value=L(K.value,Be):K[1]=L(K[1],Be));else if(ee!=null)throw(0,Do.handleHDBError)(new Error,`${ee} is not a defined attribute`,404)}function L(K,ee){return Array.isArray(K)?K.map(Be=>eh(Be,ee)):eh(K,ee)}a(L,"coerceTypedValues"),y.length>1&&(y=(0,b0.sortBy)(y,K=>{if(K.estimated_count===void 0){let ee=K.comparator||K.search_type;if(ee===wl.SEARCH_TYPES.EQUALS){let Be=K[0]??K.attribute;if(Be==null||Be===t)K.estimated_count=1;else{let Wn=r[Be];K.estimated_count=Wn?Wn.getValuesCount(K[1]??K.value):1/0}}else ee===wl.SEARCH_TYPES.CONTAINS||ee===wl.SEARCH_TYPES.ENDS_WITH||ee==="ne"?K.estimated_count=1/0:ee===wl.SEARCH_TYPES.STARTS_WITH||ee==="prefix"?K.estimated_count=bie:K.estimated_count=Nie}return K.estimated_count}));let H=N.getReadTxn();H.use();let k=p.select,P=y[0],$;if(!P)$=i.getRange(U?{end:!1,reverse:!0,transaction:H,lazy:k?.length<4}:{start:!1,transaction:H,lazy:k?.length<4}).map(({value:K})=>K?new Promise(ee=>setImmediate(()=>ee(K))):ja.SKIP);else{let K=rm(P,H,U,B,p.allowFullScan);if(!p.operator||p.operator.toLowerCase()==="and"){let ee=y.slice(1).map(sm);$=j(K,ee)}else{for(let Be=1;Be<y.length;Be++){let Wn=y[Be],Mh=rm(Wn,H,U,B,p.allowFullScan);K=K.concat(Mh)}let ee=new Set;K=K.filter(Be=>ee.has(Be)?!1:(ee.add(Be),!0)),$=j(K)}}(p.offset||p.limit!==void 0)&&($=$.slice(p.offset,p.limit!==void 0?(p.offset||0)+p.limit:void 0)),$.onDone=()=>{H.done()};let X=this[Ne];function j(K,ee){let Be=ee?.length,Wn={transaction:H,lazy:Be>0||k?.length<4,alwaysPrefetch:!0};return K.map(Mh=>new Promise(Ph=>Zl(Mh,X,Wn,null,!1,GG=>{let vh=GG?.value;if(!vh)return Ph(ja.SKIP);for(let Bh=0;Bh<Be;Bh++)if(!ee[Bh](vh))return Ph(ja.SKIP);Ph(vh)})))}return a(j,"idsToRecords"),$}async subscribe(p){if(!u)throw new Error("Can not subscribe to a table without an audit log");E||ft({table:n,database:c,schemaDefined:l,attributes:h,audit:!0});let N=m0(B,this[ue]??null,function(H,k,P){try{this.send({id:H,timestamp:P,...k})}catch($){console.error($)}},p.startTime,this[_n]),U=this[ue],y=p.previousCount;y>1e3&&(y=1e3);let L=p.startTime;if(this[_n]){if(L){if(y)throw new Do.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:H,value:k}of u.getRange({start:[L,Number.MAX_SAFE_INTEGER]})){let[P,$,X]=H;if(H.length>3&&(X=H.slice(2)),$!==s)continue;let j=bi(k,i);(U==null||N0(U,X))&&N.send({id:X,timestamp:P,...j}),N.startTime=P}}else if(y){let H=[];for(let{key:k,value:P}of u.getRange({start:"z",end:!1,reverse:!0}))try{let[$,X,j]=k;if(k.length>3&&(j=k.slice(2)),X!==s)continue;if(U==null||N0(U,j)){let K=bi(P,i);if(H.push({id:j,timestamp:$,...K}),--y<=0)break}}catch($){Mo.error("Error getting history entry",k,$)}for(let k=H.length;k>0;)N.send(H[--k]);H[0]&&(N.startTime=H[0].timestamp)}else if(!p.omitCurrent)for(let{key:H,value:k,version:P}of i.getRange({start:U??!1,end:U==null?void 0:[U,y0.MAXIMUM_KEY],versions:!0}))k&&N.send({id:H,timestamp:P,value:k})}else{y&&!L&&(L=0);let H=this[fr];if(L<H){let k=[],P=H;do{let $=[P,s,U],X=u.get($);if(X){p.omitCurrent=!0;let j=bi(X,i);k.push({id:U,timestamp:P,...j}),P=j.lastVersion}else break;y&&y--}while(P>L&&y!==0);for(let $=k.length;$>0;)N.send(k[--$]);N.startTime=H}!p.omitCurrent&&this.doesExist()&&N.send({id:U,timestamp:this[fr],value:this})}return p.listener&&N.on("data",p.listener),N}doesExist(){return!!this[le]}async publish(p,N){this._writePublish(p,N)}_writePublish(p,N){let U=this._txnForRequest(),y=this[ue]||null,L,H;U.addWrite({store:i,key:y,lastVersion:this[fr],nodeName:this[Ne]?.nodeName,validate:()=>{this.validate(p)},commit:(k,P)=>{if(this.validate(p),!H&&(H=!0,!N?.isNotification)){let j=B.Source;j?.publish&&(!j.publish.reliesOnPrototype||j.prototype.publish)&&(L=j.publish(y,p,this))}let $=P>0?i.get(y):this[le];$===void 0&&!P&&(E||f)&&(E||fO(),Fi(1));let X={type:"message",value:i.encoder.encode(p),[Co]:L};return!U.hasWrittenTime&&this[fr]>k&&(k=X.newTxnTime=this[fr]+.001),i.put(y,$??null,k),X}})}_txnForRequest(){let p=this[Ne],N=p?.transaction;if(N){let U;return(U=N?.find(y=>y.lmdbDb?.path===i.path))||N.push(U=new yl(i,p.user,u)),U}else return new Xf(i,p.user,u)}validate(p){let N;for(let U=0,y=h.length;U<y;U++){let L=h[U];if(L.type){let H=p[L.name];if(H!=null)switch(L.type){case"Int":case"Float":(typeof H!="number"||L.type==="Int"&&H!==Math.floor(H))&&(N||(N=[])).push(`Property ${L.name} must be an ${L.type==="Int"?"integer":"number"}`);break;case"ID":typeof H=="string"||H?.length>0&&H.every?.(k=>typeof k=="string")||(N||(N=[])).push(`Property ${L.name} must be a string, number, or an array (of strings and numbers)`);break;case"String":typeof H!="string"&&(N||(N=[])).push(`Property ${L.name} must be a string`)}}L.required&&p[L.name]==null&&(N||(N=[])).push(`Property ${L.name} is required`)}if(N)throw new Do.ClientError(N.join(". "))}getUpdatedTime(){return this[fr]}wasLoadedFromSource(){return A?!!this[A0]:void 0}static async addAttributes(p){let N=h.slice(0);for(let U of p){if(!U.name)throw new Do.ClientError("Attribute name is required");if(U.name.match(/[`/]/))throw new Do.ClientError("Attribute names cannot include backticks or forward slashes");N.push(U)}return ft({table:n,database:c,schemaDefined:l,attributes:N}),B.indexingOperation}static async removeAttributes(p){let N=h.filter(U=>!p.includes(U.name));return ft({table:n,database:c,schemaDefined:l,attributes:N}),B.indexingOperation}static getRecordCount(){let p=0;for(let{key:N,value:U}of i.getRange({end:!1}))p++,N[0]?.description==="deletions"&&(p+=U||0);return i.getStats().entryCount-p}static updatedAttributes(){m_(this,this)}static async deleteHistory(p=0){let N;for(let{key:U,value:y}of u.getRange({start:[0,0],end:[p,0]})){await new Promise(P=>setImmediate(P));let[L,H,k]=U;U.length>3&&(k=U.slice(2)),H===s&&(N=i.remove(k))}await N}static async*getHistory(p=0,N=1/0){for(let{key:U,value:y}of u.getRange({start:[p,0],end:[N,0]})){await new Promise($=>setImmediate($));let[L,H,k]=U;if(U.length>3&&(k=U.slice(2)),H!==s)continue;let P=bi(y,i);P.id=k,P.timestamp=L,yield P}}static async getHistoryOfRecord(p){let N=[],U=i.getEntry(p);if(!U)return N;let y=U.version,L=0;do{await new Promise(P=>setImmediate(P));let H=[y,s,p],k=u.get(H);if(k){let P=bi(k,i);P.timestamp=y,N.push(P),y=P.lastVersion}else break}while(L<1e3);return N.reverse()}static cleanup(){J?.remove()}}B.updatedAttributes();let Ie=B.prototype;return Ie[R0]=!0,d&&B.setTTLExpiration(d/1e3),b&&FG(),B;function _t(Z,p,N){let U;for(let y in r){let L=r[y],H=L.isIndexing,k=N?.[y],P=p?.[y];if(k===P&&!H)continue;U=!0;let $=(0,Cl.getIndexedValues)(P);if($){T0&&L.prefetch($.map(X=>({key:X,value:Z})),O0);for(let X=0,j=$.length;X<j;X++)L.remove($[X],Z)}if($=(0,Cl.getIndexedValues)(k),$){T0&&L.prefetch($.map(X=>({key:X,value:Z})),O0);for(let X=0,j=$.length;X<j;X++)L.put($[X],Z)}}return U}a(_t,"updateIndices");function Zl(Z,p,N,U,y,L){let H=a(()=>{let k=N.transaction;if(k?.isDone)throw new Error("Invalid read transaction");let P;k&&!k.hasRunLoadRecord&&(P=!0,k.hasRunLoadRecord=!0);let $;try{$=i.getEntry(Z,N)}catch(ee){throw ee.message+=". The read txn is "+JSON.stringify(k)+" first loadRecord: "+P,console.error(ee),console.error("reader list",i.readerList()),console.error("reader check",i.readerCheck()),console.error("reader list",i.readerList()),ee}let X,j,K;if($?(p&&$?.version>(p.lastModified||0)&&(p.lastModified=$.version),j=$.version,X=$.value,(j<0||!X||typeof X.__invalidated__=="number"||d&&j<Date.now()-d)&&(K=!0)):K=!0,A&&da(K,"cache-hit",n),K&&!y&&(U&&(U[A0]=!0),A))return hc(Z,X,j,p).then(ee=>{if(ee?.value?.[le])throw new Error("Can not assign a record with a record property");p&&ee?.version>(p.lastModified||0)&&(p.lastModified=ee.version),L(ee)},ee=>{L(null,ee)});if($?.value?.[le])throw new Error("Can not assign a record with a record property");L($)},"whenPrefetched");if(!N.alwaysPrefetch&&(Z==null||i.cache?.get(Z)))return H();i.prefetch([Z],H)}a(Zl,"loadRecord");function Yo(){M=new Set,(0,Uo.onMessageByType)("transaction",Z),i.on("aftercommit",Z);function Z(){for(let p of M)p()}a(Z,"onCommit")}a(Yo,"setupCommitListeners");async function hc(Z,p=null,N,U){if(N<0){let P;return M||Yo(),await new Promise($=>{let X,j=a(()=>{if(P=i.getEntry(Z),!P||P.version>0){if(clearTimeout(X),M.delete(j),typeof P?.value?.__invalidated__=="number")return $(hc(Z,P.value,P.version,U));$(P)}},"listener");M.add(j),X=setTimeout(()=>{M.delete(j),$(hc(Z,P?.value,void 0,U))},1e4).unref()})}let y=p?.__invalidated__,L=-(N||1);i.put(Z,p,L,N);let H={transaction:U?.transaction,replacingRecord:p,replacingVersion:N},k=U?.responseHeaders;k&&(H.responseHeaders=k);try{let P=performance.now(),$=await B.Source.get(Z,H),X=performance.now()-P;qs(X,"cache-resolution",n),k&&k.append("Server-Timing",`cache-resolve;dur=${X.toFixed(2)}`);let j=H.lastModified||N;(!j||d&&j<Date.now()-d)&&(j=(0,Cl.getNextMonotonicTime)());let ee=_t(Z,p,$)&&N||y>0;return $?(t&&($[t]=Z),typeof $.toJSON=="function"&&($=$.toJSON()),i.put(Z,$,j,L)):i.remove(Z,L),ee&&E&&u.put([j,s,Z],jf(y,null,$?{type:"put",value:i.encoder.encode($)}:{type:"delete"})),{version:j,value:$}}catch(P){throw i.put(Z,p,N,L),P}}a(hc,"getFromSource");function Fi(Z){S||(S=i.get([g0,mA.threadId])||0),S+=Z,g||(g=setTimeout(()=>{g=null,i.rootStore.status==="open"&&i.put([g0,mA.threadId],S)},50))}a(Fi,"recordDeletion");function fO(){T||(T=setTimeout(()=>{if(T=null,i.rootStore.status==="open"){for(let{key:Z,value:p}of i.getRange({start:!0}))if(p===null){let N=i.getEntry(Z);N?.value===null&&i.remove(Z,N.version),Fi(-1)}}},B.getRecordCount()*100+Iie).unref())}a(fO,"enqueueDeletionCleanup");function hO(){J=u?.addDeleteRemovalCallback(s,Z=>{let p=i.getEntry(Z);p?.value===null&&i.remove(Z,p.version),Fi(-1)})}a(hO,"addDeleteRemoval");function FG(){(0,Uo.getWorkerIndex)()===0&&setInterval(async()=>{try{let Z=b.name,p=r[Z];if(!p)throw new Error(`expiresAt attribute ${b} must be indexed`);for(let{value:N}of p.getRange({start:!0,end:Date.now(),versions:!0,snapshot:!1})){let U=i.getEntry(N);U?.value?.[Z]<Date.now()&&B.evict(N,U.value,U.version),await new Promise(y=>setImmediate(y))}}catch(Z){Mo.error("Error in evicting old records",Z)}},yie).unref()}a(FG,"runRecordExpirationEviction")}function hA(e,t){let r=e.attr_object||(e.attr_object={}),s=r[t];if(s)return s;s=r[t]=Object.create(null);for(let n of e)s[n.attribute_name]=n[t];return s}function O0(){}function wie(e){I0=e}function eh(e,t){let r=t?.type;return e===null?e:r==="Int"?parseInt(e):r==="Float"?parseFloat(e):r==="Date"?(typeof e!="number"&&!Cie.test(e)&&(e+="Z"),new Date(e)):r?e:(0,th.autoCast)(e)}function N0(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let s=0;s<r;s++)if(t[s]!==e[s])return!1;return!0}return!1}else if(t[0]===e)return!0}var Ss,ja,Cl,b0,mA,wl,Ul,Do,Ll,Dl,Mo,y0,Uo,th,I0,Nie,bie,yie,T0,g0,fr,R0,fRe,A0,Il,Iie,Cie,_f=Te(()=>{Ss=D(R()),ja=require("lmdb"),Cl=D(Ht()),b0=require("lodash"),mA=require("worker_threads");Is();d0();wl=D(Ge()),Ul=D(Y());S0();Do=D(z()),Ll=D(Rn()),Dl=D(os());_e();g_();Mo=D(C());S_();Yi();y0=require("ordered-binary"),Uo=D(tt());bl();th=D(F());co();Nie=1e8,bie=1e7,yie=6e4;Ul.initSync();T0=Ul.get(Ss.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),g0=Symbol.for("deletions"),fr=Symbol.for("version"),R0=Symbol.for("incremental-update"),fRe=Symbol("source-resource"),A0=Symbol("load-from-source"),Il={isNotification:!0,allowInvalidated:!0},Iie=(0,th.convertToMS)(Ul.get(Ss.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(rh,"makeTable");a(hA,"attributesAsObject");a(O0,"noop");a(wie,"setServerUtilities");Cie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(eh,"coerceType");a(N0,"isDescendantId")});var be={};Ke(be,{database:()=>du,databases:()=>xe,dropDatabase:()=>pS,dropTableMeta:()=>vie,getDatabases:()=>us,getTables:()=>Lie,onUpdatedTable:()=>GR,readMetaDb:()=>Ml,resetDatabases:()=>Die,table:()=>ft,tables:()=>Rr});function Lie(){return oh||us(),Rr||{}}function us(){if(oh)return xe;oh=!0,tc=new Map;let e=(0,Bt.getHdbBasePath)()&&(0,Fe.join)((0,Bt.getHdbBasePath)(),hr.DATABASES_DIR_NAME),t=(0,Bt.get)(hr.CONFIG_PARAMS.SCHEMAS)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Bt.get)(hr.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,Ur.existsSync)(e)?e:(0,Fe.join)((0,Bt.getHdbBasePath)(),hr.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,Ur.existsSync)(e))for(let r of(0,Ur.readdirSync)(e,{withFileTypes:!0})){let s=(0,Fe.basename)(r.name,".mdb");r.isFile()&&(0,Fe.extname)(r.name).toLowerCase()===".mdb"&&!t[s]?.path&&Ml((0,Fe.join)(e,r.name),null,s)}if((0,Ur.existsSync)((0,ec.getBaseSchemaPath)())){for(let r of(0,Ur.readdirSync)((0,ec.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let s=(0,Fe.join)((0,ec.getBaseSchemaPath)(),r.name),n=(0,Fe.join)((0,ec.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,Ur.readdirSync)(s,{withFileTypes:!0}))if(i.isFile()&&(0,Fe.extname)(i.name).toLowerCase()===".mdb"){let o=(0,Fe.join)(n,i.name);Ml((0,Fe.join)(s,i.name),(0,Fe.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let s=t[r],n=s.path;if((0,Ur.existsSync)(n))for(let o of(0,Ur.readdirSync)(n,{withFileTypes:!0}))o.isFile()&&(0,Fe.extname)(o.name).toLowerCase()===".mdb"&&Ml((0,Fe.join)(n,o.name),(0,Fe.basename)(o.name,".mdb"),r);let i=s.tables;if(i)for(let o in i){let c=i[o],u=(0,Fe.join)(c.path,(0,Fe.basename)(o+".mdb"));(0,Ur.existsSync)(u)&&Ml(u,o,r,null,!0)}}for(let r in xe){let s=tc.get(r);if(s){let n=xe[r];r.includes("delete")&&qe.trace(`defined tables ${Array.from(s.keys())}`);for(let i in n)s.has(i)||(qe.trace(`delete table class ${i}`),delete n[i])}else if(delete xe[r],r==="data"){for(let n in Rr)delete Rr[n];delete Rr[ah]}}return tc=null,xe}}function Die(){oh=!1;for(let[,e]of yi)e.needsDeletion=!0;us();for(let[e,t]of yi)t.needsDeletion&&!e.endsWith("system.mdb")&&(console.log("closing database",e),t.close().then(()=>console.log("closed database",e)),yi.delete(e));return xe}function Ml(e,t,r=TA,s,n){let i=new pA.default(e,!1);e.includes("delete")&&qe.trace(`reading meta data from ${e}`);try{let o=yi.get(e);o?o.needsDeletion=!1:(o=(0,sh.open)(i),yi.set(e,o));let c=new Po.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(Xa.INTERNAL_DBIS_NAME,c)),l=o.auditStore;l||(s?(0,Ur.existsSync)(s)&&(i.path=s,l=(0,sh.open)(i),l.isLegacy=!0):l=_A(o));let _=D0(r),d=_[ah],E=new Map;for(let{key:f,value:h}of u.getRange({start:!1})){let[S,T]=f.toString().split("/");e.includes("delete")&&qe.trace(`read key ${f}`),T===""?T=h.name:T||(T=S,S=t,h.name||(h.name=T,h.indexed=!h.is_hash_attribute)),d?.add(S);let A=E.get(S);A||E.set(S,A={attributes:[]}),(T==null||h.is_hash_attribute)&&(A.primary=h),T!=null&&A.attributes.push(h),Object.defineProperty(h,"key",{value:f,configurable:!0})}for(let[f,h]of E){let{attributes:S,primary:T}=h;if(!T){for(let B of S)if(B.is_hash_attribute||B.isPrimaryKey){T=B;break}if(!T)throw new Error(`Unable to find a primary key attribute on table ${f}, with attributes: ${JSON.stringify(S)}`)}let A=_[f],g={},x=[],V,I,b=typeof T.audit=="boolean"?T.audit:(0,Bt.get)(hr.CONFIG_PARAMS.LOGGING_AUDITLOG),M=T.trackDeletes,J=T.expiration;if(A)g=A.indices,x=A.attributes,A.schemaVersion++;else{V=T.tableId,V?V>=(u.get(Za)||0)&&u.putSync(Za,V+1):(T.tableId=V=u.get(Za),V||(V=1),u.putSync(Za,V+1),u.putSync(T.key,T));let B=new Po.default(!T.is_hash_attribute,T.is_hash_attribute);qe.trace(`openDB ${T.key} from ${r}`),I=o.openDB(T.key,B),I.rootStore=o,I.tableId=V}for(let B of S){B.attribute=B.name;try{if(!B.is_hash_attribute&&(B.indexed||B.attribute&&!B.name)){if(!g[B.name]){let _t=new Po.default(!B.is_hash_attribute,B.is_hash_attribute);qe.trace(`openDB ${B.key} from ${r}`),g[B.name]=o.openDB(B.key,_t)}let Ie=x.find(_t=>_t.name===B.name);Ie?x.splice(x.indexOf(Ie),1,B):x.push(B)}}catch(Ie){qe.error("Error trying to update attribute",B,x,g,Ie)}}if(!A){qe.trace(`creating table class ${f}`,Object.keys(_)),A=U0(_,f,rh({primaryStore:I,auditStore:l,audit:b,expirationMS:J&&J*1e3,trackDeletes:M,tableName:f,tableId:V,primaryKey:T.name,databasePath:n?r+"/"+f:r,databaseName:r,indices:g,attributes:S,schemaDefined:T.schemaDefined,dbisDB:u})),A.schemaVersion=1;for(let B of gA)B(A)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function D0(e){let t=xe[e];if(t||(e==="data"?t=xe[e]=Rr:e==="system"?Object.defineProperty(xe,"system",{value:t=Object.create(null),configurable:!0}):t=xe[e]=Object.create(null)),tc&&!tc.has(e)){let r=new Set;t[ah]=r,tc.set(e,r)}return t}function U0(e,t,r){return e[t]=r,r}function du({database:e,table:t}){e||(e=TA),us();let r=D0(e),s=(0,Fe.join)((0,Bt.getHdbBasePath)(),hr.DATABASES_DIR_NAME),n=t&&(0,Bt.get)(hr.CONFIG_PARAMS.SCHEMAS)?.[e]?.tables?.[t]?.path;s=n||(0,Bt.get)(hr.CONFIG_PARAMS.SCHEMAS)?.[e]?.path||process.env.STORAGE_PATH||(0,Bt.get)(hr.CONFIG_PARAMS.STORAGE_PATH)||((0,Ur.existsSync)(s)?s:(0,Fe.join)((0,Bt.getHdbBasePath)(),hr.LEGACY_DATABASES_DIR_NAME));let i=(0,Fe.join)(s,(n?t:e)+".mdb"),o=yi.get(i);if(!o){let c=new pA.default(i,!1);o=(0,sh.open)(c),yi.set(i,o)}return o}async function pS(e){if(!xe[e])throw new Error("Schema does not exist");let t=xe[e];for(let r in t){let n=t[r].primaryStore.rootStore;yi.delete(n.path),n.status==="open"&&(await n.close(),await w0.remove(n.path))}if(e==="data"){for(let r in Rr)delete Rr[r];delete Rr[ah]}delete xe[e]}function ft({table:e,database:t,expiration:r,attributes:s,audit:n,trackDeletes:i,schemaDefined:o,origin:c}){t||(t=TA);let u=du({database:t,table:e}),l=xe[t],_=l?.[e];if(u.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let d,E,f,h;o==null&&(o=!0);let S=new Po.default(!1);for(let I of s)I.attribute?(I.name=I.attribute,I.indexed=!0):I.attribute=I.name,I.expiresAt&&(I.indexed=!0);let T,A;if(_){if(qe.trace(`${e} table already exists`),d=_.primaryKey,_.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);_.attributes.splice(0,_.attributes.length,...s)}else{let I=u.auditStore;I||(I=_A(u)),E=s.find(B=>B.isPrimaryKey)||{},d=E.name,E.is_hash_attribute=!0,E.schemaDefined=o,i&&(E.trackDeletes=!0),n=E.audit=typeof n=="boolean"?n:(0,Bt.get)(hr.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(E.expiration=r),c&&(E.origins?E.origins.includes(c)||E.origins.push(c):E.origins=[c]),qe.trace(`${e} table loading, opening primary store`);let b=new Po.default(!1,!0),M=e+"/";qe.trace(`openDB ${M} from ${t}`);let J=u.openDB(M,b);J.rootStore=u,qe.trace(`openDB ${Xa.INTERNAL_DBIS_NAME} from ${t}`),h=u.dbisDb=u.openDB(Xa.INTERNAL_DBIS_NAME,S),J.tableId=h.get(Za),J.tableId||(J.tableId=1),h.putSync(Za,J.tableId+1),E.tableId=J.tableId,_=U0(l,e,rh({primaryStore:J,auditStore:I,audit:n,trackDeletes:i,expirationMS:r&&r*1e3,primaryKey:d,tableName:e,tableId:J.tableId,databasePath:t,databaseName:t,indices:{},attributes:s,schemaDefined:o,dbisDB:h})),_.schemaVersion=1,T=!0,V(),h.put(M,E)}qe.trace(`${e} table loading, getting stored attributes`),f=_.indices,h||qe.trace(`openDB ${Xa.INTERNAL_DBIS_NAME} from ${t}`),h=h||(u.dbisDb=u.openDB(Xa.INTERNAL_DBIS_NAME,S)),_.dbisDB=h;let g=[];for(let{key:I,value:b}of h.getRange({start:!0})){let[M,J]=I.toString().split("/");if(J===""&&(J=b.name),J){if(M!==e)continue}else J=M;if(!s.find(Ie=>Ie.name===J)?.indexed&&b.indexed&&!b.isPrimaryKey){V(),T=!0,h.remove(I);let Ie=_.indices[M];Ie&&g.push(Ie)}}qe.trace(`${e} table loading, comparing atributes`);let x=[];try{for(let I of s||[]){let b=e+"/"+(I.name||"");Object.defineProperty(I,"key",{value:b,configurable:!0});let M=h.get(b);if(I.isPrimaryKey){if(n===!0&&!_.audit){_.enableAuditing(),M||(b=e+"/",M=h.get(b));let B=Object.assign({},M,{audit:!0});T=!0,V(),h.put(b,B)}continue}M?.attribute&&!M.name&&(M.indexed=!0);let J=!M||M.type!==I.type||M.indexed!==I.indexed||JSON.stringify(M.attributes)!==JSON.stringify(I.attributes)||JSON.stringify(M.elements)!==JSON.stringify(I.elements);if(I.indexed){let B=new Po.default(!0,!1);qe.trace(`openDB ${b} from ${t}`);let Ie=u.openDB(b,B);(J||M.indexingPID&&M.indexingPID!==process.pid||M.restartNumber<Pl.workerData?.restartNumber)&&(T=!0,V(),M=h.get(b),(J||M.indexingPID&&M.indexingPID!==process.pid||M.restartNumber<Pl.workerData?.restartNumber)&&(T=!0,I.lastIndexedKey=M?.lastIndexedKey||!1,I.indexingPID=process.pid,Ie.isIndexing=!0,Object.defineProperty(I,"dbi",{value:Ie}),x.push(I)),h.put(b,I)),f[I.name]=Ie}else J&&(T=!0,V(),h.put(b,I))}}finally{A&&A()}if(T&&(_.schemaVersion++,_.updatedAttributes()),qe.trace(`${e} table loading, running index`),x.length>0||g.length>0?_.indexingOperation=Pie(_,x,g):T&&nh.signalSchemaChange(new ih.SchemaEventMsg(process.pid,"schema-change",_.databaseName,_.tableName)),_.origin=c,T)for(let I of gA)I(_,c!=="cluster");return r&&_.setTTLExpiration(+r),qe.trace(`${e} table loaded`),_;function V(){A||u.transactionSync(()=>({then(I){A=I}}))}a(V,"startTxn")}async function Pie(e,t,r){try{let s=e.schemaVersion;await nh.signalSchemaChange(new ih.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let n;for(let u of r)n=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:l,value:_,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(_){if(u++,n=e.primaryStore.ifVersion(l,d,()=>{for(let E=0;E<c;E++){let f=t[E],h=f.name,S=(0,C0.getIndexedValues)(_[h]);if(S)for(let T=0,A=S.length;T<A;T++)f.dbi.put(S[T],l)}}),n.then(()=>u--,E=>{u--,qe.error(E)}),Pl.workerData&&Pl.workerData.restartNumber!==L0.restartNumber&&(i=!0),++o%100===0||i){for(let E of t)E.lastIndexedKey=l,e.dbisDB.put(E.key,E);if(i)return}u>Uie?await n:u>Mie&&await new Promise(E=>setImmediate(E))}for(let l of t)delete l.lastIndexedKey,delete l.indexingPID,l.dbi.isIndexing=!1,n=e.dbisDB.put(l.key,l)}await n,await nh.signalSchemaChange(new ih.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(s){qe.error("Error in indexing",s)}}function vie({table:e,database:t}){let r=du({database:t,table:e}),s=[],n=r.dbisDb;for(let i of n.getKeys({start:e+"/",end:e+"0"}))s.push(n.remove(i));return Promise.all(s)}function GR(e){gA.push(e)}var Bt,Xa,sh,Fe,Ur,ec,Po,pA,hr,w0,SA,C0,nh,ih,Pl,qe,L0,TA,ah,Rr,xe,Za,gA,oh,yi,tc,Uie,Mie,_e=Te(()=>{Bt=D(Y()),Xa=D(Ge()),sh=require("lmdb"),Fe=require("path"),Ur=require("fs"),ec=D(De());_f();Po=D(N_()),pA=D(y_()),hr=D(R()),w0=D(require("fs-extra")),SA=require("../index"),C0=D(Ht()),nh=D(Rn()),ih=D(os()),Pl=require("worker_threads"),qe=D(C()),L0=D(tt());bl();TA="data",ah=Symbol("defined-tables");(0,Bt.initSync)();Rr=Object.create(null),xe=Object.create(null);(0,SA._assignPackageExport)("databases",xe);(0,SA._assignPackageExport)("tables",Rr);Za=Symbol.for("next-table-id"),gA=[],yi=new Map;a(Lie,"getTables");a(us,"getDatabases");a(Die,"resetDatabases");a(Ml,"readMetaDb");a(D0,"ensureDB");a(U0,"setTable");a(du,"database");a(pS,"dropDatabase");a(ft,"table");Uie=1e3,Mie=10;a(Pie,"runIndexing");a(vie,"dropTableMeta");a(GR,"onUpdatedTable")});var F=m((ORe,K0)=>{"use strict";var Ii=require("path"),H0=require("fs-extra"),mr=C(),M0=require("fs-extra"),ch=require("os"),Bie=require("net"),Hie=require("recursive-iterator"),Ye=R(),qie=zh(),P0=require("papaparse"),uh=require("moment"),{inspect:Fie}=require("util"),v0=require("is-number"),ARe=require("lodash"),Gie=require("minimist"),xie=require("https"),kie=require("http"),{hdb_errors:lh}=z(),$ie=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,q0=require("util").promisify(setTimeout),Vie=100,Yie=5,Kie="",Wie=4,B0={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};K0.exports={isEmpty:Mr,isEmptyOrZeroLength:Xs,arrayHasEmptyValues:Jie,arrayHasEmptyOrZeroLengthValues:jie,buildFolderPath:Xie,isBoolean:F0,errorizeMessage:Qie,stripFileExtension:eoe,autoCast:toe,autoCastJSON:G0,autoCastJSONDeep:AA,removeDir:roe,compareVersions:soe,isCompatibleDataVersion:noe,escapeRawValue:ioe,unescapeValue:ooe,stringifyProps:aoe,timeoutPromise:uoe,isClusterOperation:_oe,getClusterUser:Eoe,checkGlobalSchemaTable:doe,getHomeDir:k0,getPropsFilePath:coe,promisifyPapaParse:foe,removeBOM:$0,createEventPromise:hoe,checkProcessRunning:moe,checkSchemaTableExist:poe,checkSchemaExists:V0,checkTableExists:Y0,getStartOfTomorrowInSeconds:Soe,getLimitKey:Toe,isObject:Zie,isNotEmptyAndHasValue:zie,autoCasterIsNumberCheck:x0,backtickASTSchemaItems:goe,isPortTaken:loe,createForkArgs:Roe,autoCastBoolean:Aoe,async_set_timeout:q0,getTableHashAttribute:Ooe,doesSchemaExist:Noe,doesTableExist:boe,stringifyObj:yoe,ms_to_time:Ioe,changeExtension:woe,getEnvCliRootPath:OA,noBootFile:Coe,httpRequest:Loe,transformReq:Doe,convertToMS:Uoe,PACKAGE_ROOT:Ye.PACKAGE_ROOT};function Qie(e){return e instanceof Error?e:new Error(e)}a(Qie,"errorizeMessage");function Mr(e){return e==null}a(Mr,"isEmpty");function zie(e){return!Mr(e)&&(e||e===0||e===""||F0(e))}a(zie,"isNotEmptyAndHasValue");function Xs(e){return Mr(e)||e.length===0||e.size===0}a(Xs,"isEmptyOrZeroLength");function Jie(e){if(Mr(e))return!0;for(let t=0;t<e.length;t++)if(Mr(e[t]))return!0;return!1}a(Jie,"arrayHasEmptyValues");function jie(e){if(Xs(e))return!0;for(let t=0;t<e.length;t++)if(Xs(e[t]))return!0;return!1}a(jie,"arrayHasEmptyOrZeroLengthValues");function Xie(...e){try{return e.join(Ii.sep)}catch{console.error(e)}}a(Xie,"buildFolderPath");function F0(e){return Mr(e)?!1:e===!0||e===!1}a(F0,"isBoolean");function Zie(e){return Mr(e)?!1:typeof e=="object"}a(Zie,"isObject");function eoe(e){return Xs(e)?Kie:e.slice(0,-Wie)}a(eoe,"stripFileExtension");function toe(e){return Mr(e)||e===""||typeof e!="string"?e:B0[e]!==void 0?B0[e]:x0(e)===!0?Number(e):$ie.test(e)?new Date(e):e}a(toe,"autoCast");function G0(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(G0,"autoCastJSON");function AA(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let s=e[t],n=AA(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=AA(r);s!==r&&(e[t]=s)}return e}else return G0(e)}a(AA,"autoCastJSONDeep");function x0(e){if(e.startsWith("0.")&&v0(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&v0(e))}a(x0,"autoCasterIsNumberCheck");async function roe(e){if(Xs(e))throw new Error(`Directory path: ${e} does not exist`);try{await M0.emptyDir(e),await M0.remove(e)}catch(t){throw mr.error(`Error removing files in ${e} -- ${t}`),t}}a(roe,"removeDir");function soe(e,t){if(Xs(e)){mr.info("Invalid current version sent as parameter.");return}if(Xs(t)){mr.info("Invalid upgrade version sent as parameter.");return}let r,s=/(\.0+)+$/,n=e.version?e.version:e,i=t.version?t.version:t,o=n.replace(s,"").split("."),c=i.replace(s,"").split("."),u=Math.min(o.length,c.length);for(let l=0;l<u;l++)if(r=parseInt(o[l],10)-parseInt(c[l],10),r)return r;return o.length-c.length}a(soe,"compareVersions");function noe(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(noe,"isCompatibleDataVersion");function ioe(e){if(Mr(e))return e;let t=String(e);return t==="."?Ye.UNICODE_PERIOD:t===".."?Ye.UNICODE_PERIOD+Ye.UNICODE_PERIOD:t.replace(Ye.FORWARD_SLASH_REGEX,Ye.UNICODE_FORWARD_SLASH)}a(ioe,"escapeRawValue");function ooe(e){if(Mr(e))return e;let t=String(e);return t===Ye.UNICODE_PERIOD?".":t===Ye.UNICODE_PERIOD+Ye.UNICODE_PERIOD?"..":String(e).replace(Ye.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(ooe,"unescapeValue");function aoe(e,t){if(Mr(e))return mr.info("Properties object is null"),"";let r="";return e.each(function(s,n){try{if(t&&t[s]){let i=t[s];for(let o of i)r+=";"+o+ch.EOL}!Xs(s)&&s[0]===";"?r+=" "+s+n+ch.EOL:Xs(s)||(r+=s+"="+n+ch.EOL)}catch{mr.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a(aoe,"stringifyProps");function k0(){let e;try{e=ch.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(k0,"getHomeDir");function coe(){let e=Ii.join(k0(),Ye.HDB_HOME_DIR_NAME,Ye.BOOT_PROPS_FILE_NAME);return H0.existsSync(e)||(e=Ii.join(__dirname,"../","hdb_boot_properties.file")),e}a(coe,"getPropsFilePath");function uoe(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a(uoe,"timeoutPromise");async function loe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=Bie.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(loe,"isPortTaken");function _oe(e){try{return Ye.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){mr.error(`Error checking operation against cluster ops ${t}`)}return!1}a(_oe,"isClusterOperation");function doe(e,t){let r=(_e(),re(be)).getDatabases();if(!r[e])return lh.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return lh.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(doe,"checkGlobalSchemaTable");function Eoe(e,t){if(Mr(t)){mr.warn("No CLUSTERING_USER defined, clustering disabled");return}if(Mr(e)||Xs(e)){mr.warn("No users to search.");return}let r;try{let s=e.get(t);s&&s.role.permission.cluster_user===!0&&s.active===!0&&(r=s)}catch(s){mr.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){mr.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Eoe,"getClusterUser");function foe(){P0.parsePromise=function(e,t,r){return new Promise(function(s,n){P0.parse(e,{header:!0,transformHeader:$0,chunk:t.bind(null,n),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:n,complete:s})})}}a(foe,"promisifyPapaParse");function $0(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a($0,"removeBOM");function hoe(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;mr.info(`Got cluster status event response: ${Fie(n)}`);try{i.cancel()}catch{mr.error("Error trying to cancel timeout.")}s(n)})})}a(hoe,"createEventPromise");async function moe(e){let t=!0,r=0;do await q0(Vie*r++),(await qie.findPs(e)).length>0&&(t=!1);while(t&&r<Yie);if(t)throw new Error(`process ${e} was not started`)}a(moe,"checkProcessRunning");function poe(e,t){let r=V0(e);if(r)return r;let s=Y0(e,t);if(s)return s}a(poe,"checkSchemaTableExist");function V0(e){let{getDatabases:t}=(_e(),re(be));if(!t()[e])return lh.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(V0,"checkSchemaExists");function Y0(e,t){let{getDatabases:r}=(_e(),re(be));if(!r()[e][t])return lh.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Y0,"checkTableExists");function Soe(){let e=uh().utc().add(1,Ye.MOMENT_DAYS_TAG).startOf(Ye.MOMENT_DAYS_TAG).unix(),t=uh().utc().unix();return e-t}a(Soe,"getStartOfTomorrowInSeconds");function Toe(){return uh().utc().format("DD-MM-YYYY")}a(Toe,"getLimitKey");function goe(e){try{let t=new Hie(e);for(let{node:r}of t)r&&(r.columnid&&typeof r.columnid!="string"&&(r.columnid=r.columnid.toString()),r.columnid&&!r.columnid.startsWith("`")&&(r.columnid_orig=r.columnid,r.columnid=`\`${r.columnid}\``),r.tableid&&!r.tableid.startsWith("`")&&(r.tableid_orig=r.tableid,r.tableid=`\`${r.tableid}\``),r.databaseid&&!r.databaseid.startsWith("`")&&(r.databaseid_orig=r.databaseid,r.databaseid=`\`${r.databaseid}\``),r.as&&typeof r.as=="string"&&!r.as.startsWith("[")&&(r.as_orig=r.as,r.as=`\`${r.as}\``))}catch(t){mr.error("Got an error back ticking items."),mr.error(t)}}a(goe,"backtickASTSchemaItems");function Roe(e){return[e]}a(Roe,"createForkArgs");function Aoe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Aoe,"autoCastBoolean");function Ooe(e,t){let{getDatabases:r}=(_e(),re(be)),s=r()[e]?.[t];return s?.primaryKey||s?.hash_attribute}a(Ooe,"getTableHashAttribute");function Noe(e){let{getDatabases:t}=(_e(),re(be));return t()[e]!==void 0}a(Noe,"doesSchemaExist");function boe(e,t){let{getDatabases:r}=(_e(),re(be));return r()[e]?.[t]!==void 0}a(boe,"doesTableExist");function yoe(e){try{return JSON.stringify(e)}catch{return e}}a(yoe,"stringifyObj");function Ioe(e){let t=uh.duration(e),r=t.seconds()>0?t.seconds()+"s":"",s=t.minutes()>0?t.minutes()+"m ":"",n=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+n+s+r}a(Ioe,"ms_to_time");function woe(e,t){let r=Ii.basename(e,Ii.extname(e));return Ii.join(Ii.dirname(e),r+t)}a(woe,"changeExtension");function OA(){if(process.env[Ye.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Ye.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=Gie(process.argv);if(e[Ye.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Ye.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(OA,"getEnvCliRootPath");var RA;function Coe(){if(RA)return RA;let e=OA();OA()&&H0.pathExistsSync(Ii.join(e,Ye.HDB_CONFIG_FILE))&&(RA=!0)}a(Coe,"noBootFile");function Loe(e,t){let r;return e.protocol==="http:"?r=kie:r=xie,new Promise((s,n)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",u=>{c.body+=u}),o.on("end",()=>{s(c)})});i.on("error",o=>{n(o)}),i.write(JSON.stringify(t)),i.end()})}a(Loe,"httpRequest");function Doe(e){if(!e.schema&&!e.database){e.schema=Ye.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(Doe,"transformReq");function Uoe(e){let t=0;if(typeof e=="number"&&(t=e),typeof e=="string")switch(t=parseFloat(e),e.slice(-1)){case"M":t*=86400*30;break;case"D":case"d":t*=86400;break;case"H":case"h":t*=3600;break;case"m":t*=60;break}return t*1e3}a(Uoe,"convertToMS")});var Y=m((bRe,z0)=>{"use strict";var NA=require("fs-extra"),Ts=require("path"),W0=require("os"),Moe=require("properties-reader"),vl=C(),vo=F(),ne=R(),_h=et(),Poe="Error initializing environment manager",dh="BOOT_PROPS_FILE_PATH",Q0=!1,voe={[ne.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[ne.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[ne.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},xn={};z0.exports={BOOT_PROPS_FILE_PATH:dh,getHdbBasePath:Boe,setHdbBasePath:Hoe,get:qoe,initSync:Goe,setProperty:he,initTestEnvironment:xoe};function Boe(){return xn[ne.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Boe,"getHdbBasePath");function Hoe(e){xn[ne.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(Hoe,"setHdbBasePath");function qoe(e){let t=_h.getConfigValue(e);return t===void 0?xn[e]:t}a(qoe,"get");function he(e,t){voe[e]&&(xn[e]=t),_h.updateConfigObject(e,t)}a(he,"setProperty");function Foe(){let e;try{e=vo.getPropsFilePath(),NA.accessSync(e,NA.constants.F_OK|NA.constants.R_OK),Q0=!0;let t=Moe(e);return xn[ne.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ne.HDB_SETTINGS_NAMES.INSTALL_USER),xn[ne.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ne.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),xn[dh]=e,!0}catch{return vl.trace(`Environment manager found no properties file at ${e}`),!1}}a(Foe,"doesPropFileExist");function Goe(e=!1){try{(Q0||Foe()||vo.noBootFile())&&(_h.initConfig(e),xn[ne.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=_h.getConfigValue(ne.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){vl.error(Poe),vl.error(t),console.error(t),process.exit(1)}}a(Goe,"initSync");function xoe(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:s,https_enabled:n,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=Ts.join(__dirname,"../../","unitTests");xn[dh]=Ts.join(u,"hdb_boot_properties.file"),he(ne.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Ts.join(u,"settings.test")),he(ne.HDB_SETTINGS_NAMES.INSTALL_USER,W0.userInfo()?W0.userInfo().username:void 0),he(ne.HDB_SETTINGS_NAMES.PRIVATE_KEY_KEY,Ts.join(u,"envDir","utility","keys","privateKey.pem")),he(ne.HDB_SETTINGS_NAMES.CERT_KEY,Ts.join(u,"envDir","utility","keys","certificate.pem")),he(ne.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,Ts.join(u,"envDir","utility","keys","privateKey.pem")),he(ne.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_CERTIFICATE,Ts.join(u,"envDir","utility","keys","certificate.pem")),he(ne.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),he(ne.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Ts.join(u,"envDir","log")),he(ne.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),he(ne.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),he(ne.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),he(ne.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Ts.join(u,"envDir")),he(ne.CONFIG_PARAMS.STORAGE_PATH,Ts.join(u,"envDir")),he(ne.HDB_SETTINGS_NAMES.HTTP_SECURE_ENABLED_KEY,vo.isEmpty(n)?!0:n),he(ne.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,vo.isEmpty(n)?!0:n),he(ne.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),he(ne.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,vo.isEmpty(i)?!1:i),he(ne.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORS,vo.isEmpty(i)?!1:i),he(ne.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),he(ne.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),he(ne.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),he(ne.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),he(ne.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Ts.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),he(ne.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,vo.isEmpty(c)?!1:c),o&&(he("CORS_ACCESSLIST",o),he(ne.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,o)),s&&(he(ne.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),he(ne.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,s)),t&&(he(ne.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),he(ne.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,t)),r&&(he(ne.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),he(ne.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${dh}. Please check your boot props and settings files`;vl.fatal(r),vl.error(t)}}a(xoe,"initTestEnvironment")});var yA=m((IRe,J0)=>{"use strict";var Bl=Y();Bl.initSync();var rc=require("fs-extra"),bA=require("path"),sc=R(),koe=require("crypto"),$oe=require("uuid").v4;J0.exports=Voe;function Voe(){if(Bl.getHdbBasePath()!==void 0){let e=bA.join(Bl.getHdbBasePath(),sc.LICENSE_KEY_DIR_NAME,sc.JWT_ENUM.JWT_PRIVATE_KEY_NAME),t=bA.join(Bl.getHdbBasePath(),sc.LICENSE_KEY_DIR_NAME,sc.JWT_ENUM.JWT_PUBLIC_KEY_NAME),r=bA.join(Bl.getHdbBasePath(),sc.LICENSE_KEY_DIR_NAME,sc.JWT_ENUM.JWT_PASSPHRASE_NAME);try{rc.accessSync(r),rc.accessSync(e),rc.accessSync(t)}catch(s){if(s.code==="ENOENT"){let n=$oe(),i=koe.generateKeyPairSync("rsa",{modulusLength:4096,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem",cipher:"aes-256-cbc",passphrase:n}});rc.writeFileSync(r,n),rc.writeFileSync(e,i.privateKey),rc.writeFileSync(t,i.publicKey)}else throw s}}}a(Voe,"checkJWTTokenExist")});var X0=m((CRe,j0)=>{"use strict";var IA=class{static{a(this,"HdbInfoInsertObject")}constructor(t,r,s){this.info_id=t,this.data_version_num=r,this.hdb_version_num=s}};j0.exports={HdbInfoInsertObject:IA}});var tF=m((DRe,eF)=>{"use strict";var Z0=R(),wA=class{static{a(this,"UpgradeObject")}constructor(t,r){this[Z0.UPGRADE_JSON_FIELD_NAMES_ENUM.DATA_VERSION]=t,this[Z0.UPGRADE_JSON_FIELD_NAMES_ENUM.UPGRADE_VERSION]=r}};eF.exports={UpgradeObject:wA}});var Eh=m((MRe,sF)=>{"use strict";var es=require("prompt"),nc=require("chalk"),rF=C(),gs=require("os"),CA=Gi(),LA=["yes","y"];async function Yoe(e){let t=`${gs.EOL}`+nc.bold.green("Your current HarperDB version requires that we complete an update process.")+`${gs.EOL}If a backup of your data has not been created, we recommend you cancel this process and backup before proceeding.${gs.EOL}${gs.EOL}You can read more about the changes in this upgrade at https://harperdb.io/developers/release-notes/${gs.EOL}`;es.override=CA(["CONFIRM_UPGRADE"]),es.start(),es.message=t;let r={properties:{CONFIRM_UPGRADE:{description:nc.magenta(`${gs.EOL}[CONFIRM_UPGRADE] Do you want to upgrade your HDB instance now? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"no",required:!0}}},s;try{s=await es.get([r])}catch(n){return rF.error("There was an error when prompting user about an upgrade."),rF.error(n),!1}return LA.includes(s.CONFIRM_UPGRADE)}a(Yoe,"forceUpdatePrompt");async function Koe(e){let t=`${gs.EOL}`+nc.bold.green(`Your installed HarperDB version is older than the version used to create your data. Downgrading is not recommended as it is not tested and guaranteed to work. However, if you need to downgrade, and a backup of your data has not been created, we recommend you cancel this process and backup before proceeding.${gs.EOL}`);es.override=CA(["CONFIRM_DOWNGRADE"]),es.start(),es.message=t;let r={properties:{CONFIRM_DOWNGRADE:{description:nc.magenta(`${gs.EOL}[CONFIRM_DOWNGRADE] Do you want to proceed with using your downgraded HDB instance now? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"no",required:!0}}},s=await es.get([r]);return LA.includes(s.CONFIRM_DOWNGRADE)}a(Koe,"forceDowngradePrompt");async function Woe(){let e=`${gs.EOL}`+nc.bold.green("We now require a Certifacte Authority certificate. HarperDB can generate all new certificates for you (your existing certificates will be backed up) or you can keep any existing certificates and add your own CA certificate. To add your own CA certificate set the <certificateAuthority> parameter in harperdb-config.yaml");es.override=CA(["GENERATE_CERTS"]),es.start(),es.message=e;let t={properties:{GENERATE_CERTS:{description:nc.magenta(`${gs.EOL}[GENERATE_CERTS] Do you want HarperDB to generate all new certificates? (yes/no)`),pattern:/y(es)?$|n(o)?$/,message:"Must respond 'yes' or 'no'",default:"yes",required:!0}}},r=await es.get([t]);return LA.includes(r.GENERATE_CERTS)}a(Woe,"upgradeCertsPrompt");sF.exports={forceUpdatePrompt:Yoe,forceDowngradePrompt:Koe,upgradeCertsPrompt:Woe}});var UA=m((vRe,nF)=>{"use strict";var DA=class{static{a(this,"UpgradeDirective")}constructor(t){this.version=t,this.sync_functions=[],this.async_functions=[]}};nF.exports=DA});var oF=m((xRe,iF)=>{"use strict";var Qoe=F(),zoe=et(),HRe=C(),qRe=require("path"),FRe=require("fs"),GRe=R();iF.exports={getOldPropsValue:Joe};function Joe(e,t,r=!1){let s=t.getRaw(e);return Qoe.isNotEmptyAndHasValue(s)?s:r?zoe.getDefaultConfig(e):""}a(Joe,"getOldPropsValue")});var lF=m(($Re,uF)=>{"use strict";var wi=require("path"),Ci=require("fs-extra"),joe=require("properties-reader"),Xoe=UA(),at=C(),{getOldPropsValue:Le}=oF(),{HDB_SETTINGS_NAMES:Q,CONFIG_PARAMS:Bo}=R(),Ho=et(),fh=Y(),aF=F(),Zs=R(),MA=new Xoe("3.1.0"),cF=[];function Zoe(){let e=joe(fh.get(Q.SETTINGS_PATH_KEY)),t="Updating settings file for version 3.1.0";console.log(t),at.info(t);let r=` ;Settings for the HarperDB process.
|
|
33
33
|
|
|
34
34
|
;The directory selected during install where the database files reside.
|
|
35
35
|
${Q.HDB_ROOT_KEY} = ${Le(Q.HDB_ROOT_KEY,e)}
|
|
@@ -101,8 +101,8 @@ ${Q.MAX_CUSTOM_FUNCTION_PROCESSES} = ${Ho.getDefaultConfig(Bo.HTTP_THREADS)}
|
|
|
101
101
|
`,s=fh.get("settings_path"),n=wi.dirname(s),i=wi.join(n,"3_1_0_upgrade_settings.bak");try{at.info(`Backing up old settings file to: ${i}`),Ci.copySync(s,i)}catch(c){throw at.error(c),console.error("There was a problem writing the backup for the old settings file. Please check the log for details."),c}try{at.info("New settings file values for 3.1.0 upgrade:",r),at.info(`Creating new/upgraded settings file at '${s}'`),Ci.writeFileSync(s,r),at.info("Updating env variables with new settings values")}catch(c){throw console.error("There was a problem writing the new settings file. Please check the log for details."),at.error("Attempting to reset the settings file to its original state. Use the '.bak' file if this fails."),at.error(c),Ci.copySync(i,s),c}fh.initSync();let o="New settings file for 3.1.0 upgrade successfully created.";return console.log(o),at.info(o),o}a(Zoe,"updateSettingsFile_3_1_0");function eae(){let e=wi.join(aF.getHomeDir(),Zs.HDB_HOME_DIR_NAME,Zs.LICENSE_KEY_DIR_NAME,Zs.LICENSE_FILE_NAME),t=wi.join(aF.getHomeDir(),Zs.HDB_HOME_DIR_NAME,Zs.LICENSE_KEY_DIR_NAME,Zs.REG_KEY_FILE_NAME),r=wi.join(fh.getHdbBasePath(),Zs.LICENSE_KEY_DIR_NAME,Zs.LICENSE_FILE_NAME),s=wi.join(r,Zs.LICENSE_FILE_NAME),n=wi.join(r,Zs.REG_KEY_FILE_NAME),i="Move license files for version 3.1.0";console.log(i),at.info(i);let o="Creating .license directory";console.log(o),at.info(o),Ci.mkdirpSync(r);try{Ci.accessSync(e);try{let c="Moving licence file";console.log(c),at.info(c),Ci.moveSync(e,s);let u="License file successfully moved.";console.log(u),at.info(u)}catch{let u="moving license file failed";console.error(u),at.error(u)}}catch{let u=`license file '${e}' does not exist.`;console.warn(u),at.warn(u)}try{Ci.accessSync(t);try{let c="Moving registration file";console.log(c),at.info(c),Ci.moveSync(t,n);let u="Registration file successfully moved.";console.log(u),at.info(u)}catch{let u="moving registration file failed";console.error(u),at.error(u)}}catch{let u=`registration file '${t}' does not exist.`;console.warn(u),at.warn(u)}}a(eae,"moveLicenseFiles");MA.sync_functions.push(Zoe);MA.sync_functions.push(eae);cF.push(MA);uF.exports=cF});var hF=m((YRe,fF)=>{"use strict";var Pr=we(),{insertRecords:tae}=Wi(),rae=Ht(),Li=Ge(),sae=F(),kn=C(),nae=F(),en=require("fs-extra"),$n=require("path"),iae=require("cli-progress"),Hl=require("assert"),oae=require("pino"),aae=Y();fF.exports=cae;var hh,_F,mh,PA,$t,ql=!1;async function cae(e=!0){return hh=aae.getHdbBasePath(),_F=$n.join(hh,"schema"),mh=$n.join(hh,"4_0_0_upgrade_tmp"),PA=$n.join(hh,"transactions"),console.info("Reindexing upgrade started for schemas"),kn.notify("Reindexing upgrade started for schemas"),await dF(_F,!1,e),await en.pathExists(PA)&&(console.info(`
|
|
102
102
|
|
|
103
103
|
Reindexing upgrade started for transaction logs`),kn.notify("Reindexing upgrade started for transaction logs"),await dF(PA,!0,e)),kn.notify("Reindexing upgrade complete"),"Reindexing for 4.0.0 upgrade complete"+(ql?", but errors occurred":"")}a(cae,"reindexUpgrade");async function dF(e,t,r){let s=await en.readdir(e),n=s.length;for(let i=0;i<n;i++){let o=s[i],c=$n.join(e,o.toString());if(o===".DS_Store")continue;let u=await en.readdir(c),l=u.length;for(let _=0;_<l;_++){let d=u[_];if(d!==".DS_Store"&&en.statSync($n.join(c,d)).isDirectory())try{await uae(o,d,t),$t.info(`Reindexing started for ${o}.${d}`),kn.notify(`${t?"Transaction":"Schema"} reindexing started for ${o}.${d}`),await _ae(o,d,c,t,r),$t.info(`Reindexing completed for ${o}.${d}`),kn.notify(`Reindexing completed for ${o}.${d}`)}catch(E){ql=!0,E.schema_path=c,E.table_name=d,kn.error("There was an error with the reindex upgrade, check the logs in hdb/3_0_0_upgrade_tmp for more details"),kn.error(E),$t.error(E),console.error(E)}}}if(!ql)try{await en.rm(mh,{recursive:!0})}catch{}}a(dF,"processTables");async function uae(e,t,r){let n=`${e}_${t}_${r?"transaction_reindex":"schema_reindex"}.log`,i=$n.join(mh,n);await en.ensureDir(mh),await en.writeFile(i,""),$t=oae({level:"debug",formatters:{bindings(){}}},i)}a(uae,"initPinoLogger");var lae=20;async function _ae(e,t,r,s,n){let i;try{i=await Pr.openEnvironment(r,t,s)}catch(g){if(g.message==="MDB_INVALID: File is not an LMDB file"){kn.notify(`${e}.${t} file is not from the old environment and has been skipped`),console.info(`${e}.${t} file is not from the old environment and has been skipped`),$t.error(g);return}throw g}let o=fae(i.dbis),c=Pr.openDBI(i,o),u=Object.keys(i.dbis),l=Pr.statDBI(i,o);$t.info(`Old environment stats: ${JSON.stringify(l)}`);let _=new iae.SingleBar({format:`${e}.${t} |{bar}| {percentage}% || {value}/{total} records`,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",hideCursor:!0,clearOnComplete:!1});_.start(l.entryCount,0,{});let d=await Pr.createEnvironment(r,t,!1);Pr.createDBI(d,o,!1,!0);let E=[];try{for(let g of c.getRange({start:!1}))g.value=Object.assign({},g.value),E.push(g),s||e==="system"&&(t==="hdb_schema"&&(g.key=g.key.toString(),g.value.name=g.value.name.toString()),t==="hdb_table"&&(g.key=g.key.toString(),g.value.schema=g.value.schema.toString(),g.value.name=g.value.name.toString()),t==="hdb_attribute"&&(g.key=g.key.toString(),g.value.schema=g.value.schema.toString(),g.value.table=g.value.table.toString(),g.value.attribute=g.value.attribute.toString())),E.length>lae&&await f();await f()}catch(g){throw ql=!0,$t.error(g),g}async function f(){let g,x=E.map(({value:I})=>I);s?g=await Promise.all(x.map(I=>dae(d,I))):g=await tae(d,o,u.filter(I=>I!=="__blob__"),x,!1);for(let I=0,b=E.length;I<b;I++){let{key:M,value:J}=E[I];$t.info(`Record hash value: ${M} hash: ${o}`);let B;s?B=g[I]:B=g.written_hashes.indexOf(M)>-1,Hl(B,!0),Eae(d,o,J[o],s),$t.info(`Insert success, written hashes: ${g.written_hashes}`),_.increment()}E=[],_.value/_.total*100%10===0&&kn.notify(`${e}.${t} ${_.value}/${_.total} records inserted`),$t.info(`${_.value}/${_.total} records inserted`)}a(f,"finishOutstanding"),_.stop();let h=Pr.statDBI(i,o),S=Pr.statDBI(d,o);if($t.info(`Old stats entry count: ${h.entryCount}. New stats entry count: ${S.entryCount}`),Hl.deepStrictEqual(h.entryCount,S.entryCount),await Pr.closeEnvironment(i),await Pr.closeEnvironment(d),delete global.lmdb_map[`${e}.${t}`],n){let g=$n.join(r,t),x=$n.join(g,"data.mdb"),V=$n.join(g,"lock.mdb");await en.unlink(x),await en.unlink(V),await en.rmdir(g),$t.info(`Deleted old environment files from schema folder: ${x}, ${V}`)}let T=await Pr.openEnvironment(r,t),A=Pr.statDBI(T,o);$t.info(`New stats: ${JSON.stringify(S)}. New stats after move: ${JSON.stringify(A)}`),Hl.deepStrictEqual(A.entryCount,S.entryCount),await Pr.closeEnvironment(T),delete global.lmdb_map[`${e}.${t}`]}a(_ae,"processTable");async function dae(e,t){Pr.initializeDBIs(e,Li.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Li.TRANSACTIONS_DBIS);let r=t.timestamp;return e.dbis[Li.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(r,()=>{e.dbis[Li.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(r,t),nae.isEmpty(t.user_name)||e.dbis[Li.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(t.user_name,r);for(let s of t.hash_values)e.dbis[Li.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s,r)})}a(dae,"insertTransaction");function Eae(e,t,r,s){let i=e.dbis[t].get(r);Hl.deepStrictEqual(typeof i,"object");let o;if(s){let c={[Li.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME]:i.user_name,[Li.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE]:i.hash_values};o=Object.entries(c)}else o=Object.entries(i);for(let[c,u]of o)if(c!==t&&e.dbis[c]!==void 0&&!sae.isEmptyOrZeroLength(u))if(s&&c==="hash_value")for(let l=0,_=u.length;l<_;l++){let d=u[l];EF(e,c,d,r)}else EF(e,c,u,r)}a(Eae,"validateIndices");function EF(e,t,r,s){try{let n=!1,i=rae.getIndexedValues(r);if(!i)return;for(let o of i)n=e.dbis[t].doesExist(o,s),n||$t.info(`Validate indices did not find value in new DBI: ${o}. Hash: ${s}`),Hl.deepStrictEqual(n,!0)}catch(n){ql=!0,$t.error(n),console.error(n)}}a(EF,"validateIndex");function fae(e){let t;for(let[r,s]of Object.entries(e))if(s.__dbi_defintion__.is_hash_attribute===!0){t=r;break}return t}a(fae,"getHashDBI")});var qA=m((WRe,pF)=>{"use strict";var hae=require("mkcert"),ph=require("path"),vA=require("fs-extra"),BA=C(),mae=Y(),HA=R(),ic=dp(),pae=Gi(),Sae=et();pF.exports={generateKeys:Tae,updateConfigCert:mF};async function Tae(){let e=mae.getHdbBasePath(),t=ph.join(e,HA.LICENSE_KEY_DIR_NAME),r=await hae.createCert({domains:["127.0.0.1","localhost","::1"],validityDays:365,caKey:ic.CERTIFICATE_VALUES.key,caCert:ic.CERTIFICATE_VALUES.cert}),s=ph.join(t,ic.CERTIFICATE_PEM_NAME),n=ph.join(t,ic.PRIVATEKEY_PEM_NAME),i=ph.join(t,ic.CA_PEM_NAME);try{await vA.writeFile(s,r.cert)}catch(o){throw BA.error(o),console.error("There was a problem creating the certificate file. Please check the install log for details."),o}try{await vA.writeFile(n,r.key)}catch(o){throw BA.error(o),console.error("There was a problem creating the private key file. Please check the install log for details."),o}try{await vA.writeFile(i,ic.CERTIFICATE_VALUES.cert)}catch(o){throw BA.error(o),console.error("There was a problem creating the certificate authority file. Please check the install log for details."),o}mF(s,n,i)}a(Tae,"generateKeys");function mF(e,t,r){let s=pae(Object.keys(HA.CONFIG_PARAM_MAP),!0),n=HA.CONFIG_PARAMS,i={[n.CLUSTERING_TLS_CERTIFICATE]:s[n.CLUSTERING_TLS_CERTIFICATE.toLowerCase()]?s[n.CLUSTERING_TLS_CERTIFICATE]:e,[n.CLUSTERING_TLS_PRIVATEKEY]:s[n.CLUSTERING_TLS_PRIVATEKEY.toLowerCase()]?s[n.CLUSTERING_TLS_PRIVATEKEY.toLowerCase()]:t,[n.CLUSTERING_TLS_CERT_AUTH]:s[n.CLUSTERING_TLS_CERT_AUTH.toLowerCase()]?s[n.CLUSTERING_TLS_CERT_AUTH.toLowerCase()]:r,[n.CUSTOMFUNCTIONS_TLS_CERTIFICATE]:s[n.CUSTOMFUNCTIONS_TLS_CERTIFICATE.toLowerCase()]?s[n.CUSTOMFUNCTIONS_TLS_CERTIFICATE.toLowerCase()]:e,[n.CUSTOMFUNCTIONS_TLS_PRIVATEKEY]:s[n.CUSTOMFUNCTIONS_TLS_PRIVATEKEY.toLowerCase()]?s[n.CUSTOMFUNCTIONS_TLS_PRIVATEKEY.toLowerCase()]:t,[n.CUSTOMFUNCTIONS_TLS_CERT_AUTH]:s[n.CUSTOMFUNCTIONS_TLS_CERT_AUTH.toLowerCase()]?s[n.CUSTOMFUNCTIONS_TLS_CERT_AUTH.toLowerCase()]:r,[n.OPERATIONSAPI_TLS_CERTIFICATE]:s[n.OPERATIONSAPI_TLS_CERTIFICATE.toLowerCase()]?s[n.OPERATIONSAPI_TLS_CERTIFICATE.toLowerCase()]:e,[n.OPERATIONSAPI_TLS_PRIVATEKEY]:s[n.OPERATIONSAPI_TLS_PRIVATEKEY.toLowerCase()]?s[n.OPERATIONSAPI_TLS_PRIVATEKEY.toLowerCase()]:t,[n.OPERATIONSAPI_TLS_CERT_AUTH]:s[n.OPERATIONSAPI_TLS_CERT_AUTH.toLowerCase()]?s[n.OPERATIONSAPI_TLS_CERT_AUTH.toLowerCase()]:r};Sae.updateConfigValue(void 0,void 0,i,!1,!0)}a(mF,"updateConfigCert")});var AF=m((JRe,RF)=>{"use strict";var Sh=require("path"),Di=require("fs-extra"),gae=UA(),qo=C(),SF=et(),FA=Y(),Rs=R(),Th=F(),Rae=require("properties-reader"),Aae=as(),Oae=kd(),Nae=jt(),zRe=require("util"),bae=Nae.searchByValue,yae=Xt(),Iae=uE(),wae=Me(),Cae=hF(),TF=qA(),Lae=Eh(),xl=new gae("4.0.0"),gF=[],Fl,Gl;async function Dae(){try{if(await Lae.upgradeCertsPrompt()){if(console.log("Generating new certificates."),Fl){let t=Th.changeExtension(Fl,".bak");await Di.move(Fl,t)}if(Gl){let t=Th.changeExtension(Gl,".bak");await Di.move(Gl,t)}await TF.generateKeys()}else console.log("Using existing certificates."),TF.updateConfigCert(Fl,Gl,void 0)}catch(e){throw console.error("There was a problem generating new keys. Please check the log for details."),e}}a(Dae,"generateNewKeys");async function Uae(){console.log("Updating HarperDB nodes."),qo.info("Updating HarperDB nodes.");let e=[];try{let t=new Aae(Rs.SYSTEM_SCHEMA_NAME,Rs.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*","name",["*"]),r=Array.from(await bae(t)),s=[];for(let i=0,o=r.length;i<o;i++){let c=r[i];if(!wae.NATS_TERM_CONSTRAINTS_RX.test(c.name)){let _=`Node name '${c.name}' is invalid, must not contain ., * or >. Please change name and try again.`;throw console.error(_),_}let u={host:c.host,port:c.port};e.push(u);let l=[];for(let _=0,d=c.subscriptions.length;_<d;_++){let E=c.subscriptions[_],f=E.channel.split(":");l.push({schema:f[0],table:f[1],publish:E.publish,subscribe:E.subscribe})}s.push({name:c.name,subscriptions:l,system_info:{hdb_version:Rs.PRE_4_0_0_VERSION,node_version:void 0,platform:void 0}})}if(Th.isEmptyOrZeroLength(s))return;let n=new Oae(Rs.SYSTEM_SCHEMA_NAME,Rs.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,s);await yae.update(n)}catch(t){throw console.error("There was a problem updating the hdb_nodes table. Please check the log for details."),t}try{Iae.setRoutes({server:"hub",routes:e})}catch(t){throw console.error("There was a problem setting the clustering routes. Please check the log for details."),t}}a(Uae,"updateNodes");async function Mae(){let e=FA.get(Rs.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY);if(!e.includes(Sh.join("config","settings.js"))){qo.info("pre 4.0.0 settings.js file not found, skipping settings file update");return}let t="Updating settings file for version 4.0.0";console.log(t),qo.info(t);let r=Sh.dirname(e),s=FA.get(Rs.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),n=Sh.join(s,"backup","4_0_0_upgrade_settings.bak"),i=Sh.join(s,Rs.HDB_CONFIG_FILE);try{qo.info(`Backing up old settings file to: ${n}`),console.log(`Backing up old settings file to: ${n}`),Di.copySync(e,n)}catch(d){throw console.error("There was a problem writing the backup for the old settings file. Please check the log for details."),d}try{qo.info(`Creating new/upgraded settings file at '${i}'`),console.log(`Creating new/upgraded settings file at '${i}'`),qo.info("Updating env variables with new settings values");let d=SF.initOldConfig(e);Fl=d[Rs.CONFIG_PARAMS.OPERATIONSAPI_TLS_CERTIFICATE.toLowerCase()],Gl=d[Rs.CONFIG_PARAMS.OPERATIONSAPI_TLS_PRIVATEKEY.toLowerCase()],SF.createConfigFile(d)}catch(d){throw console.log("There was a problem creating the new HarperDB config file. Please check the log for details."),d}let o=Th.getPropsFilePath();Di.accessSync(o,Di.constants.F_OK|Di.constants.R_OK);let u=Rae(o).get(Rs.HDB_SETTINGS_NAMES.INSTALL_USER),l=`settings_path = ${i}
|
|
104
|
-
install_user = ${u}`;try{Di.writeFileSync(o,l)}catch(d){throw console.log("There was a problem updating the HarperDB boot properties file. Please check the log for details."),d}try{FA.initSync(!0)}catch(d){throw console.error("Unable to initialize new properties. Please check the log for details."),d}let _="New settings file for 4.0.0 upgrade successfully created.";try{Di.removeSync(r),console.log(_),qo.info(_)}catch(d){throw console.error("There was a problem deleting the old settings file and directory. Please check the log for details."),d}}a(Mae,"updateSettingsFile_4_0_0");xl.async_functions.push(Mae);xl.async_functions.push(Dae);xl.async_functions.push(Cae);xl.async_functions.push(Uae);gF.push(xl);RF.exports=gF});var GA=m((XRe,yF)=>{"use strict";var Fo=F(),Pae=R(),OF=C(),{DATA_VERSION:vae,UPGRADE_VERSION:Bae}=Pae.UPGRADE_JSON_FIELD_NAMES_ENUM,NF=lF(),gh=AF(),Go=new Map;NF&&NF.forEach(e=>{Go.set(e.version,e)});gh&&gh.forEach(e=>{Go.set(e.version,e)});gh&&gh.forEach(e=>{Go.set(e.version,e)});function Hae(){return[...Go.keys()].sort(Fo.compareVersions)}a(Hae,"getSortedVersions");function bF(e){let t=e[vae],r=e[Bae];return Fo.isEmptyOrZeroLength(t)||Fo.isEmptyOrZeroLength(r)?(OF.info(`There is an issue with the version data in your instance of HDB. Current version data: ${e}`),OF.error("There was an error when trying to evaluate the version information for your instance. Trying to start the server anyways but it may fail. If you continue to have this problem, please contact support@harperdb.io."),[]):[...Go.keys()].sort(Fo.compareVersions).filter(function(s){return Fo.compareVersions(s,t)>0&&Fo.compareVersions(s,r)<=0})}a(bF,"getVersionsForUpgrade");function qae(e){return bF(e).length>0}a(qae,"hasUpgradesRequired");function Fae(e){return Fo.isEmptyOrZeroLength(e)?null:Go.has(e)?Go.get(e):null}a(Fae,"getDirectiveByVersion");yF.exports={getSortedVersions:Hae,getDirectiveByVersion:Fae,getVersionsForUpgrade:bF,hasUpgradesRequired:qae}});var Rh=m((eAe,DF)=>{"use strict";var Gae=require("util"),xA=require("chalk"),xae=require("os"),wF=Xt(),kae=jt(),vr=R(),CF=X0(),$A=op(),{UpgradeObject:IF}=tF(),{forceDowngradePrompt:$ae}=Eh(),Vae=$i(),kl=C(),oc=F(),VA=$r(),Yae=(_e(),re(be)),Kae=GA(),Wae=Gae.promisify(VA.setSchemaDataToGlobal),Qae=kae.searchByValue,zae="info_id",Jae="2.9.9",jae="3.0.0";async function Xae(e){let t=new CF.HdbInfoInsertObject(1,e,e),r=new $A.InsertObject(vr.OPERATIONS_ENUM.INSERT,vr.SYSTEM_SCHEMA_NAME,vr.SYSTEM_TABLE_NAMES.INFO_TABLE_NAME,vr.SYSTEM_TABLE_HASH_ATTRIBUTES.INFO_TABLE_ATTRIBUTE,[t]);return VA.setSchemaDataToGlobal(),wF.insert(r)}a(Xae,"insertHdbInstallInfo");async function kA(e){let t,r=await LF(),s=new Map([[0,{}]]);for(let c of r)s.set(c.info_id,c);let i=Math.max.apply(null,[...s.keys()])+1;t=new CF.HdbInfoInsertObject(i,e,e);let o=new $A.InsertObject(vr.OPERATIONS_ENUM.INSERT,vr.SYSTEM_SCHEMA_NAME,vr.SYSTEM_TABLE_NAMES.INFO_TABLE_NAME,vr.SYSTEM_TABLE_HASH_ATTRIBUTES.INFO_TABLE_ATTRIBUTE,[t]);return await Wae(),wF.insert(o)}a(kA,"insertHdbUpgradeInfo");async function LF(){let e=new $A.NoSQLSeachObject(vr.SYSTEM_SCHEMA_NAME,vr.SYSTEM_TABLE_NAMES.INFO_TABLE_NAME,zae,vr.SYSTEM_TABLE_HASH_ATTRIBUTES.INFO_TABLE_ATTRIBUTE,["*"],"*"),t=[];try{t=Array.from(await Qae(e))}catch(r){kl.info(r)}return t}a(LF,"getAllHdbInfoRecords");async function Zae(){let e=await LF();if(e.length===0)return;let t,r=new Map;for(let n of e)r.set(n.info_id,n);let s=Math.max.apply(null,[...r.keys()]);return t=r.get(s),t}a(Zae,"getLatestHdbInfoRecord");async function ece(){kl.info("Checking if HDB software has been updated");try{let e=Vae.version(),t=await Zae(),r;if(oc.isEmpty(t))r=Jae;else if(r=t.data_version_num,oc.compareVersions(r.toString(),e.toString())>0){if(!oc.isCompatibleDataVersion(r.toString(),e.toString()))throw console.log(xA.yellow(`This instance's data was last run on version ${r}`)),console.error(xA.red(`You have installed a version lower than the version that your data was created on or was upgraded to. This may cause issues and is currently not supported.${xae.EOL}${vr.SUPPORT_HELP_MSG}`)),new Error("Trying to downgrade major HDB versions is not supported.");oc.isCompatibleDataVersion(r.toString(),e.toString(),!0)||(console.log(xA.yellow(`This instance's data was last run on version ${r}`)),await $ae(new IF(r,e))?await kA(e.toString()):(console.log("Cancelled downgrade, closing HarperDB"),process.exit(0)))}if(VA.setSchemaDataToGlobal(),tce(r),e.toString()===r.toString())return;let s=new IF(r,e);if(Kae.hasUpgradesRequired(s))return s;oc.compareVersions(s.data_version.toString(),s.upgrade_version.toString())<0&&(await kA(s.upgrade_version),kl.notify(`HarperDB running on upgraded version: ${s.upgrade_version}`))}catch(e){throw kl.fatal("Error while trying to evaluate the state of hdb data and the installed hdb version"),kl.fatal(e),e}}a(ece,"getVersionUpdateInfo");function tce(e){let t=`You are attempting to upgrade from an old instance of HarperDB that is no longer supported. In order to upgrade to this version, you must do a fresh install. If you need support, please contact ${vr.HDB_SUPPORT_ADDRESS}`;if(!("hdb_info"in Yae.databases.system))throw console.log(t),new Error(t);if(!oc.isEmpty(e)&&e<jae)throw console.log(t),new Error(t)}a(tce,"checkIfInstallIsSupported");DF.exports={insertHdbInstallInfo:Xae,insertHdbUpgradeInfo:kA,getVersionUpdateInfo:ece}});var BF=m((rAe,vF)=>{"use strict";var YA=require("joi"),{boolean:rce,string:UF,number:sce}=YA.types(),MF=require("fs-extra"),$l=R(),PF=require("path"),nce=He();vF.exports=ice;function ice(e){let t=UF.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null),r=YA.object({[$l.INSTALL_PROMPTS.ROOTPATH]:YA.custom(oce),[$l.INSTALL_PROMPTS.OPERATIONSAPI_NETWORK_PORT]:sce.min(0),[$l.INSTALL_PROMPTS.TC_AGREEMENT]:UF.valid("yes","YES","Yes"),[$l.INSTALL_PROMPTS.CLUSTERING_NODENAME]:t,[$l.INSTALL_PROMPTS.CLUSTERING_ENABLED]:rce});return nce.validateBySchema(e,r)}a(ice,"installValidator");function oce(e,t){if(MF.existsSync(PF.join(e,"system/hdb_user/data.mdb"))||MF.existsSync(PF.join(e,"system/hdb_user.mdb")))return t.message(`'${e}' is already in use. Please enter a different path.`)}a(oce,"validateRootAvailable")});var qF=m((nAe,HF)=>{"use strict";var{mkdirpSync:ace}=require("fs-extra"),tn=require("path"),ac=R(),WA=C(),cce=Vr(),KA=En(),uce=De();HF.exports=lce;async function lce(e){WA.trace("Mounting HarperDB"),As(e),As(tn.join(e,"backup")),As(tn.join(e,"trash")),As(tn.join(e,"keys")),As(tn.join(e,"keys",ac.LICENSE_FILE_NAME)),As(tn.join(e,"log")),As(tn.join(e,"doc")),As(tn.join(e,"database")),As(tn.join(e,ac.TRANSACTIONS_DIR_NAME)),As(tn.join(e,"clustering","leaf")),As(tn.join(e,"components")),await _ce()}a(lce,"mountHdb");async function _ce(){let e=cu(),t=Object.keys(KA);for(let r=0;r<t.length;r++){let s=t[r],n=KA[s].hash_attribute;try{uce.initSystemSchemaPaths(ac.SYSTEM_SCHEMA_NAME,s);let i=new e(ac.SYSTEM_SCHEMA_NAME,s,n);i.attributes=KA[s].attributes;let o=i.attributes.find(({attribute:c})=>c===n);o.isPrimaryKey=!0,await cce.createTable(s,i)}catch(i){throw WA.error(`issue creating environment for ${ac.SYSTEM_SCHEMA_NAME}.${s}: ${i}`),i}}}a(_ce,"createLMDBTables");function As(e){ace(e,{mode:ac.HDB_FILE_PERMISSIONS}),WA.info(`Directory ${e} created`)}a(As,"makeDirectory")});var Ah=m((aAe,zF)=>{"use strict";var JA=require("os"),kF=require("inquirer"),Vn=require("fs-extra"),dce=require("properties-reader"),xo=require("chalk"),vi=require("path"),Ece=require("human-readable-ids").hri,fce=require("ora"),ct=C(),Bi=Y(),uc=F(),QA=Gi(),$F=Rh(),VF=$i(),ee=R(),hce=BF(),mce=qF(),YF=et(),pce=er(),Sce=qd(),Tce=yA(),gce=$r(),Rce=require("util").promisify,Ace=Rce(gce.setSchemaDataToGlobal),Oce=qA(),cc=a(e=>e,"PROMPT_ANSWER_TRANSFORMER"),Vt=a(e=>xo.magenta.bold(e),"HDB_PROMPT_MSG"),Nce="https://harperdb.io/legal/end-user-license-agreement",Hi=JA.EOL,Ui="",bce="yes",FF="Starting HarperDB install...",GF="HarperDB installation was successful.",xF="Terms & Conditions acceptance is required to proceed with installation. Exiting install...",yce="An out of date version of HarperDB is already installed.",zA="It appears that HarperDB is already installed. Exiting install...",Ice="Aborting install",wce=new RegExp(/^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/),Cce=new RegExp(/^[^\s.,*>]+$/),Lce=JA.homedir(),Dce=vi.join(Lce,ee.HDB_ROOT_DIR_NAME),Uce=9925,Mce="HDB_ADMIN",Pce="CLUSTER_USER",pr={DESTINATION:"Please enter a destination for HarperDB:",HDB_PORT:"Please enter a server listening port for HarperDB:",HDB_USERNAME:"Please enter a username for the HDB_ADMIN:",HDB_PASS:"Please enter a password for the HDB_ADMIN:",NODE_NAME:"Please enter a unique name for this node:",CLUSTER_USERNAME:"Please enter a username for the CLUSTER_USER:",CLUSTER_PASS:"Please enter a password for the CLUSTER_USER:"},oAe=uc.getEnvCliRootPath(),Pi;zF.exports=KF;KF.createSuperUser=QF;async function KF(){console.log(Vt(Hi+FF+Hi)),ct.notify(FF);let e=Bce(),t=hce(e);if(t)throw t.message;await Hce(),await qce(e);let r=await vce(e);Pi=r[ee.INSTALL_PROMPTS.ROOTPATH],await Vn.pathExists(vi.join(Pi,ee.HDB_CONFIG_FILE))&&(console.error(zA),process.exit());let s=fce({prefixText:Vt("Installing"),color:"magenta",spinner:"simpleDots"});if(s.start(),uc.isEmpty(Pi))throw new Error("Installer should have the HDB root param at the stage it is in but it does not.");Bi.setHdbBasePath(Pi),await mce(Pi),await Fce(),await Gce(r),ct.initLogSettings(!0),await QF(r),await kce(r),await Oce.generateKeys(),await $ce(),Tce(),s.stop(),console.log(Vt(Hi+GF+Hi)),ct.notify(GF)}a(KF,"install");async function vce(e){ct.trace("Getting install prompts and params.");let t,r=[{type:"input",transformer:cc,when:Mi(e[ee.INSTALL_PROMPTS.ROOTPATH],pr.DESTINATION),name:ee.INSTALL_PROMPTS.ROOTPATH,prefix:Ui,default:Dce,validate:async n=>rn(n)?rn(n):await Vn.pathExists(vi.join(n,"system","hdb_user.mdb"))?`'${n}' is already in use. Please enter a different path.`:!0,message:Vt(pr.DESTINATION)},{type:"input",transformer:cc,when:Mi(e[ee.INSTALL_PROMPTS.OPERATIONSAPI_NETWORK_PORT],pr.HDB_PORT),name:ee.INSTALL_PROMPTS.OPERATIONSAPI_NETWORK_PORT,prefix:Ui,default:Uce,validate:n=>wce.test(n)?!0:"Invalid port.",message:Vt(pr.HDB_PORT)},{type:"input",transformer:cc,when:Mi(e[ee.INSTALL_PROMPTS.HDB_ADMIN_USERNAME],pr.HDB_USERNAME),name:ee.INSTALL_PROMPTS.HDB_ADMIN_USERNAME,prefix:Ui,default:Mce,validate:n=>rn(n)?rn(n):(t=n,!0),message:Vt(pr.HDB_USERNAME)},{type:"password",when:Mi(e[ee.INSTALL_PROMPTS.HDB_ADMIN_PASSWORD],pr.HDB_PASS),name:ee.INSTALL_PROMPTS.HDB_ADMIN_PASSWORD,prefix:Ui,validate:n=>rn(n)?rn(n):!0,message:Vt(pr.HDB_PASS)}];if(uc.autoCastBoolean(e[ee.INSTALL_PROMPTS.CLUSTERING_ENABLED])===!0){let n=[{type:"input",transformer:cc,when:Mi(e[ee.INSTALL_PROMPTS.CLUSTERING_NODENAME],pr.NODE_NAME),name:ee.INSTALL_PROMPTS.CLUSTERING_NODENAME,prefix:Ui,default:Ece.random(),validate:i=>Cce.test(i)?!0:"Invalid node name, must not contain ., * or >",message:Vt(pr.NODE_NAME)},{type:"input",transformer:cc,when:Mi(e[ee.INSTALL_PROMPTS.CLUSTERING_USER],pr.CLUSTER_USERNAME),name:ee.INSTALL_PROMPTS.CLUSTERING_USER,prefix:Ui,default:Pce,validate:i=>rn(i)?rn(i):i.toLowerCase()===t.toLowerCase()?"Username is already in use.":!0,message:Vt(pr.CLUSTER_USERNAME)},{type:"password",when:Mi(e[ee.INSTALL_PROMPTS.CLUSTERING_PASSWORD],pr.CLUSTER_PASS),name:ee.INSTALL_PROMPTS.CLUSTERING_PASSWORD,prefix:Ui,validate:i=>rn(i)?rn(i):!0,message:Vt(pr.CLUSTER_PASS)}];r.push(...n)}let s=await kF.prompt(r);if(Object.keys(s).length===0)return e;for(let n in s)e[n]===void 0&&(e[n]=s[n]);return e}a(vce,"installPrompts");function Mi(e,t){return e!==void 0?(t.includes("password")?(console.log(`${Vt(t)} ${xo.gray("[hidden]")}`),ct.trace(`${Vt(t)} [hidden]`)):(console.log(`${Vt(t)} ${e}`),ct.trace(`${Vt(t)} ${e}`)),!1):!0}a(Mi,"displayCmdEnvVar");function rn(e){let t=e.replace(/ /g,"");if(t===""||t==="''"||t==='""')return"Value cannot be empty."}a(rn,"checkForEmptyValue");function Bce(){let e=Object.keys(ee.INSTALL_PROMPTS),t=QA(e),r=QA(Object.keys(ee.CONFIG_PARAM_MAP),!0),s={};for(let n of e){let i=ee.CONFIG_PARAM_MAP[n.toLowerCase()];t[n]?i===void 0?s[n]=t[n]:s[i.toUpperCase()]=t[n]:i!==void 0&&r[i.toLowerCase()]&&(s[n]=r[i.toLowerCase()])}return s}a(Bce,"checkForPromptOverride");async function Hce(){ct.trace("Checking for existing install.");let e=uc.getPropsFilePath(),t=await Vn.pathExists(e),r;if(t){ct.trace(`Install found an existing boot prop file at:${e}`);let s=dce(e),n=YF.getConfigValue(ee.BOOT_PROP_PARAMS.SETTINGS_PATH_KEY)||s.get(ee.BOOT_PROP_PARAMS.SETTINGS_PATH_KEY);r=await Vn.pathExists(n)}if(!t&&uc.noBootFile()&&(r=!0),r){if(ct.trace(`Install found existing HDB config at:${e}`),await $F.getVersionUpdateInfo()){let n=`Please use \`harperdb upgrade\` to update to ${VF.version()}. Exiting install...`;console.log(Hi+xo.magenta.bold(yce)),console.log(xo.magenta.bold(n)),ct.error(n)}else console.log(Hi+xo.magenta.bold(zA)),ct.error(zA);process.exit(0)}}a(Hce,"checkForExistingInstall");async function qce(e){ct.info("Asking for terms agreement.");let t=`Terms & Conditions can be found at ${Nce}${Hi}and can be viewed by typing or copying and pasting the URL into your web browser.${Hi}I Agree to the HarperDB Terms and Conditions. (yes/no)`,r={prefix:Ui,transformer:cc,when:Mi(e[ee.INSTALL_PROMPTS.TC_AGREEMENT],t),name:ee.INSTALL_PROMPTS.TC_AGREEMENT,message:Vt(t),validate:n=>n.toLowerCase()==="yes"||n.toLowerCase()==="no"?!0:xo.yellow("Please enter 'yes' or 'no'")},s=await kF.prompt([r]);s[ee.INSTALL_PROMPTS.TC_AGREEMENT]&&s[ee.INSTALL_PROMPTS.TC_AGREEMENT].toLowerCase()!==bce&&(console.log(xo.yellow(xF)),ct.error(xF),process.exit(0))}a(qce,"termsAgreement");async function Fce(){let e=vi.join(Pi,ee.HDB_CONFIG_FILE),t;try{t=JA.userInfo().username}catch{t=process.env.USERNAME||process.env.USER||process.env.LOGNAME||process.env.LNAME||process.env.SUDO_USER}if(t){let r=`settings_path = ${e}
|
|
105
|
-
install_user = ${t}`,s=uc.getHomeDir(),n=vi.join(s,ee.HDB_HOME_DIR_NAME),i=vi.join(n,ee.LICENSE_KEY_DIR_NAME);try{Vn.mkdirpSync(n,{mode:ee.HDB_FILE_PERMISSIONS}),Vn.mkdirpSync(i,{mode:ee.HDB_FILE_PERMISSIONS})}catch{console.error(`Could not make settings directory ${ee.HDB_HOME_DIR_NAME} in home directory. Please check your permissions and try again.`)}let o=vi.join(n,ee.BOOT_PROPS_FILE_NAME);try{await Vn.writeFile(o,r)}catch(c){throw ct.error(`There was an error creating the boot file at path: ${o}`),c}Bi.setProperty(ee.HDB_SETTINGS_NAMES.INSTALL_USER,`${t}`),Bi.setProperty(ee.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,e),Bi.setProperty(Bi.BOOT_PROPS_FILE_PATH,o)}}a(Fce,"createBootPropertiesFile");async function Gce(e){ct.trace("Creating HarperDB config file");let t=QA(Object.keys(ee.CONFIG_PARAM_MAP),!0);Object.assign(t,e);try{YF.createConfigFile(t),Bi.initSync()}catch(r){xce(r)}}a(Gce,"createConfigFile");function xce(e){ct.error(`Error creating HarperDB config file. Rolling back install - ${e}`),console.error(e),console.error(Ice);let t=vi.resolve(Bi.get(Bi.BOOT_PROPS_FILE_PATH),"../");t&&Vn.removeSync(t),Pi&&Vn.removeSync(Pi),process.exit(1)}a(xce,"rollbackInstall");async function WF(e,t){ct.trace("Creating admin user"),await Ace();let r;try{r=await Sce.addRole(e)}catch(s){if(s.message.includes("already exists"))t=void 0;else throw s.message+="Error creating role",s}if(t)try{t.role=r.role,await pce.addUser(t)}catch(s){throw s.message=`Error creating user - ${s}`,s}}a(WF,"createAdminUser");async function QF(e){ct.trace("Creating Super user.");let t={role:"super_user",permission:{super_user:!0}},r={username:e[ee.INSTALL_PROMPTS.HDB_ADMIN_USERNAME].toString(),password:e[ee.INSTALL_PROMPTS.HDB_ADMIN_PASSWORD].toString(),active:!0};await WF(t,r),delete e[ee.INSTALL_PROMPTS.HDB_ADMIN_USERNAME],delete e[ee.INSTALL_PROMPTS.HDB_ADMIN_PASSWORD]}a(QF,"createSuperUser");async function kce(e){ct.trace("Creating Cluster user.");let t;e[ee.INSTALL_PROMPTS.CLUSTERING_USER]&&e[ee.INSTALL_PROMPTS.CLUSTERING_PASSWORD]&&(t={username:e[ee.INSTALL_PROMPTS.CLUSTERING_USER].toString(),password:e[ee.INSTALL_PROMPTS.CLUSTERING_PASSWORD].toString(),active:!0}),await WF({role:"cluster_user",permission:{cluster_user:!0}},t),delete e[ee.INSTALL_PROMPTS.CLUSTERING_USER],delete e[ee.INSTALL_PROMPTS.CLUSTERING_PASSWORD]}a(kce,"createClusterUser");async function $ce(){let e=VF.version();if(e)await $F.insertHdbInstallInfo(e);else throw new Error("The version is missing/removed from HarperDB package.json")}a($ce,"insertHdbVersionInfo")});var XF=m((uAe,jF)=>{"use strict";var jA=F(),Br=C(),JF=GA();jF.exports={processDirectives:Vce};async function Vce(e){console.log("Starting upgrade process...");let t=JF.getVersionsForUpgrade(e),r=Wce(t),s=[],n=r.length;for(let i=0;i<n;i++){let o=r[i],c=`Running upgrade for version ${o.version}`;Br.notify(c),console.log(c);let u=[],l=[];try{u=Yce(o.sync_functions)}catch(_){throw Br.error(`Error while running an upgrade script for ${o.version}`),_}try{l=await Kce(o.async_functions)}catch(_){throw Br.error(`Error while running an upgrade script for ${o.version}`),_}s.push(...u,...l)}return s}a(Vce,"processDirectives");function Yce(e){if(jA.isEmptyOrZeroLength(e))return Br.info("No functions found to run for upgrade"),[];if(!Array.isArray(e))return Br.info("Passed parameter is not an array"),[];let t=[];for(let r of e){if(Br.info(`Running function ${r.name}`),!(r instanceof Function)){Br.info("Variable being processed is not a function");continue}let s=r();Br.info(s),t.push(s)}return t}a(Yce,"runSyncFunctions");async function Kce(e){if(jA.isEmptyOrZeroLength(e))return Br.info("No functions found to run for upgrade"),[];if(!Array.isArray(e))return Br.info("Passed parameter is not an array"),[];let t=[],r=e.length;for(let s=0;s<r;s++){let n=e[s];if(Br.info(`Running function ${n.name}`),!(n instanceof Function)){Br.info("Variable being processed is not a function");continue}let i=await n();Br.info(i),t.push(i)}return t}a(Kce,"runAsyncFunctions");function Wce(e){if(jA.isEmptyOrZeroLength(e))return[];let t=[];for(let r of e){let s=JF.getDirectiveByVersion(r);s&&t.push(s)}return t}a(Wce,"getUpgradeDirectivesToInstall")});var eO=m((_Ae,nG)=>{"use strict";var Oh=Y();Oh.initSync();var rG=require("chalk"),ZF=require("fs-extra"),Kn=C(),Yn=R(),eG=$i(),Qce=XF(),XA=F(),sG=Rh(),zce=Eh(),tG=zh(),Jce=$r(),jce=require("util").promisify,Xce=jce(Jce.setSchemaDataToGlobal),ZA,{UPGRADE_VERSION:Nh}=Yn.UPGRADE_JSON_FIELD_NAMES_ENUM;nG.exports={upgrade:Zce};async function Zce(e){await Xce(),ZA===void 0&&(ZA=ya()),ZF.existsSync(Oh.get(Oh.BOOT_PROPS_FILE_PATH))||(Vl("The hdb_boot_properties file was not found. Please install HDB.",Yn.LOG_LEVELS.ERROR),process.exit(1)),ZF.existsSync(Oh.get(Yn.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY))||(Vl("The hdb settings file was not found. Please make sure HDB is installed.",Yn.LOG_LEVELS.ERROR),process.exit(1));let t=e;t||(t=await sG.getVersionUpdateInfo(),t||(console.log("HarperDB version is current"),process.exit(0))),Vl(`This version of HarperDB is ${eG.version()}`,Yn.LOG_LEVELS.INFO);let r=t[Nh]?t[Nh]:eG.version();r||(console.log(`Current Version field missing from the package.json file. Cannot continue with upgrade. If you need support, please contact ${Yn.HDB_SUPPORT_ADDRESS}`),Kn.notify("Missing new version field from upgrade info object"),process.exit(1)),await eue();let s,n=0;try{s=await zce.forceUpdatePrompt(t)}catch(i){Kn.error("There was an error when prompting user about upgrade."),Kn.error(i),s=!1,n=1}s||(console.log("Cancelled upgrade, closing HarperDB"),process.exit(n)),Kn.info(`Starting upgrade to version ${r}`),await tue(t),Vl(`HarperDB was successfully upgraded to version ${t[Nh]}`,Yn.LOG_LEVELS.INFO)}a(Zce,"upgrade");async function eue(){let e=!1,t=await tG.findPs(Yn.HDB_PROC_NAME);if(XA.isEmptyOrZeroLength(t)||(e=!0),!e){let r=await tG.findPs("hdb_express");XA.isEmptyOrZeroLength(r)||(e=!0)}if(!e){let r=await ZA.list();XA.isEmptyOrZeroLength(r)||(e=!0)}if(e){let r="HarperDB is running, please stop all HarperDB services with 'harperdb stop' and run the upgrade command again.";console.log(rG.red(r)),Kn.error(r),process.exit(1)}}a(eue,"checkIfRunning");async function tue(e){try{await Qce.processDirectives(e)}catch(t){throw Vl("There was an error during the data upgrade. Please check the logs.",Yn.LOG_LEVELS.ERROR),t}try{await sG.insertHdbUpgradeInfo(e[Nh])}catch(t){Kn.error("Error updating the 'hdb_info' system table."),Kn.error(t)}}a(tue,"runUpgrade");function Vl(e,t=void 0){t||(t=Kn.info),Kn[t](e),console.log(rG.magenta(e))}a(Vl,"printToLogAndConsole")});var uG=m((EAe,cG)=>{"use strict";var{promises:rO,createReadStream:rue,createWriteStream:sue}=require("fs"),{createGzip:nue}=require("zlib"),{promisify:iue}=require("util"),{pipeline:oue}=require("stream"),aue=iue(oue),cue=require("path"),$o=Y();$o.initSync();var ko=C(),{CONFIG_PARAMS:Yl,ITC_EVENT_TYPES:uue}=R(),{onMessageFromWorkers:lue}=tt(),_ue=6e4,due="'interval' and 'maxSize' are both undefined, to enable logging rotation at least one of these values must be defined in harperdb-config.yaml",Eue="'logging.rotation.path' is undefined, to enable logging rotation set this value in harperdb-config.yaml",tO,oG;cG.exports=aG;lue(e=>{e.type===uue.RESTART&&($o.initSync(!0),clearInterval(oG),$o.get(Yl.LOGGING_ROTATION_ENABLED)&&aG())});async function aG(){try{let e=ko.getLogFilePath(),t=$o.get(Yl.LOGGING_ROTATION_MAXSIZE),r=$o.get(Yl.LOGGING_ROTATION_INTERVAL);if(!t&&!r){ko.error(due);return}let s=$o.get(Yl.LOGGING_ROTATION_PATH);if(!s){ko.error(Eue);return}let n;if(t){let o=t.slice(-1),c=t.slice(0,-1);o==="G"?n=c*1e9:o==="M"?n=c*1e6:n=c*1e3}let i;if(r){let o=r.slice(-1),c=r.slice(0,-1);o==="D"?i=c*1440:o==="H"?i=c*60:i=c}tO=Date.now()/6e4,ko.trace("Log rotate enabled, maxSize:",t,"interval:",r),oG=setInterval(async()=>{if(n){let o;o=await rO.stat(e),o.size>=n&&await iG(e,s)}i&&Date.now()/6e4-tO>=i&&(await iG(e,s),tO=Date.now()/6e4)},_ue).unref()}catch(e){ko.error(e)}}a(aG,"logRotator");async function iG(e,t){let r=$o.get(Yl.LOGGING_ROTATION_COMPRESS),s=cue.join(t,`HDB-${new Date(Date.now()).toISOString().replaceAll(":","-")}.${r?"log.gz":"log"}`);r?(await aue(rue(e),nue(),sue(s)),await rO.unlink(e)):await rO.rename(e,s),ko.closeLogFile(),ko.notify(`hdb.log rotated, old log moved to ${s}`)}a(iG,"moveLogFile")});var _c=m((OAe,mG)=>{"use strict";var Ns=Y();Ns.initSync();var hAe=wa(),ut=R(),Yt=C(),Vo=require("fs-extra"),lc=require("path"),fue=yA(),hue=Ah(),sO=require("chalk"),mue=ki(),ts=F(),lG=et(),_G=Gi(),pue=SE(),Sue=eO(),Tue=uG(),gue=require("minimist"),{PACKAGE_ROOT:Rue}=R(),{startHTTPThreads:Aue,startSocketServer:mAe,mostIdleRouting:pAe,remoteAffinityRouting:SAe}=(Uf(),re(DR)),Oue=Rh(),{isMainThread:Nue}=require("worker_threads"),TAe=En(),gAe=Zn(),RAe=Xp(),AAe=cu(),nO=R(),Os,bue="Upgrade complete. Starting HarperDB.",yue="Got an error while trying to upgrade your HarperDB instance. Exiting HarperDB.",Iue="HarperDB not found, starting install process.",wue="There was an error during install, check install_log.log for more details. Exiting.",Cue="HarperDB successfully started.";async function dG(e=!1,t=!1){if(console.log(sO.magenta("Starting HarperDB...")),await hG()===!1){console.log(Iue);try{await hue()}catch(n){console.error(wue,n),Yt.error(n),process.exit(1)}}await Vo.writeFile(lc.join(Ns.get(nO.CONFIG_PARAMS.ROOTPATH),nO.HDB_PID_FILE),`${process.pid}`),Yt.info("HarperDB PID",process.pid),Os===void 0&&(Os=ya());let r;try{let n=await Oue.getVersionUpdateInfo();n!==void 0&&(r=n[ut.UPGRADE_JSON_FIELD_NAMES_ENUM.UPGRADE_VERSION],await Sue.upgrade(n),console.log(bue))}catch(n){r?(console.error(`Got an error while trying to upgrade your HarperDB instance to version ${r}. Exiting HarperDB.`),Yt.error(n)):(console.error(yue),Yt.error(n)),process.exit(1)}if(!e){let n=_G(Object.keys(ut.CONFIG_PARAM_MAP),!0);!ts.isEmpty(n)&&!ts.isEmptyOrZeroLength(Object.keys(n))&&lG.updateConfigValue(void 0,void 0,n,!0,!0)}fue(),Due(),ts.autoCastBoolean(Ns.get(ut.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY))&&Nue&&await pue.generateNatsConfig(t)}a(dG,"initialize");async function EG(e=!1){try{let t=gue(process.argv);t.ROOTPATH&&lG.updateConfigObject("settings_path",lc.join(t.ROOTPATH,ut.HDB_CONFIG_FILE)),await dG(e,!0);let r=ts.autoCastBoolean(Ns.get(ut.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY)),s=process.env.IS_SCRIPTED_SERVICE&&!t.service,n=r,i=ts.autoCastBoolean(Ns.get(ut.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY));if(ts.isEmpty(t.service))await Aue(Ns.get(nO.CONFIG_PARAMS.HTTP_THREADS)),n&&(s||await Os.startClusteringProcesses(),await Os.startClusteringThreads());else{if(typeof t.service!="string"){let c=`Run service argument expected a string but received: ${t.service}`;Yt.error(c),console.log(c),process.exit(1)}let o=t.service.split(",");for(let c of o){let u=c.toLowerCase();if(ut.PROCESS_DESCRIPTORS_VALIDATE[u]===void 0){Yt.error(`Run received unrecognized service command argument: ${u}`);continue}if(u===ut.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS.toLowerCase()&&!i){Yt.error(`${u} is not enabled in settings`);continue}if(u.includes("clustering")&&!r){Yt.error(`${u} is not enabled in settings`);continue}u==="clustering"?await Os.startClusteringProcesses():await Os.startService(ut.PROCESS_DESCRIPTORS_VALIDATE[u]);let l=`${ut.PROCESS_DESCRIPTORS_VALIDATE[u]} successfully started.`;Yt.notify(l),console.log(l)}}Ns.get(ut.CONFIG_PARAMS.LOGGING_ROTATION_ENABLED)&&await Tue(),s||fG()}catch(t){console.error(t),Yt.error(t),process.exit(1)}}a(EG,"main");function fG(){Yt.suppressLogging(()=>{console.log(sO.magenta(""+Vo.readFileSync(lc.join(Rue,"utility/install/ascii_logo.txt")))),console.log(sO.magenta(`|------------- HarperDB ${mue.version} successfully started ------------|`))}),Yt.notify(Cue)}a(fG,"started");async function Lue(){if(Uue())return EG();try{Os===void 0&&(Os=ya()),Os.enterPM2Mode(),await dG(),ts.autoCastBoolean(Ns.get(ut.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY))&&await Os.startClusteringProcesses(),await Os.startService(ut.PROCESS_DESCRIPTORS.HDB),fG(),process.exit(0)}catch(e){console.error(e),Yt.error(e),process.exit(1)}}a(Lue,"launch");function Due(){let e=lc.join(Ns.getHdbBasePath(),ut.LICENSE_KEY_DIR_NAME,ut.LICENSE_FILE_NAME),t=lc.join(e,ut.LICENSE_FILE_NAME),r=lc.join(e,ut.REG_KEY_FILE_NAME);try{let{HARPERDB_FINGERPRINT:s,HARPERDB_LICENSE:n}=_G(["HARPERDB_FINGERPRINT","HARPERDB_LICENSE"]);if(ts.isEmpty(s)||ts.isEmpty(n))return;Vo.mkdirpSync(e),Vo.writeFileSync(r,s),Vo.writeFileSync(t,n)}catch(s){let n=`Failed to write license & fingerprint due to: ${s.message}`;console.error(n),Yt.error(n)}}a(Due,"writeLicenseFromVars");mG.exports={launch:Lue,main:EG,isHdbInstalled:hG};async function hG(){try{await Vo.stat(ts.getPropsFilePath()),await Vo.stat(Ns.get(ut.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY))}catch(e){if(ts.noBootFile())return!0;if(e.code==="ENOENT")return!1;throw Yt.error(`Error checking for HDB install - ${e}`),e}return!0}a(hG,"isHdbInstalled");function Uue(){return ts.autoCastBoolean(Ns.get(ut.CONFIG_PARAMS.OPERATIONSAPI_FOREGROUND))}a(Uue,"getRunInForeground")});var SG=m((bAe,pG)=>{var Mue=Ah(),Pue=C();pG.exports=vue;async function vue(){try{await Mue()}catch(e){console.error("There was an error during the install."),console.error(e),Pue.error(e),process.exit(1)}}a(vue,"install")});var RG=m((IAe,gG)=>{"use strict";var Bue=_E(),Hue=C(),TG="Registration failed.";async function que(){let e;try{e=await Bue.register()}catch(t){return Hue.error(`Registration error ${t}`),TG}return e||TG}a(que,"register");gG.exports={register:que}});var bG=m((CAe,NG)=>{"use strict";var Fue=C(),Gue=R(),xue=require("util"),kue=require("child_process"),AG=xue.promisify(kue.exec),$ue=Nn(),Kl=ya(),OG="Stopping HarperDB.";NG.exports=Vue;async function Vue(){if(console.log(OG),Fue.notify(OG),await Kl.isServiceRegistered(Gue.HDB_PROC_DESCRIPTOR)){Kl.enterPM2Mode();let r=await Kl.getUniqueServicesList();for(let s in r)await Kl.stop(s)}await Kl.kill();let t=await $ue.getHDBProcessInfo();t.clustering.forEach(r=>{AG(`kill ${r.pid}`)}),t.core.forEach(r=>{AG(`kill ${r.pid}`)})}a(Vue,"stop")});var LG=m((DAe,CG)=>{"use strict";var iO=require("fs-extra"),oO=require("path"),Yue=require("yaml"),Wl=Qe(),Ql=R(),yG=Me(),IG=C(),Kue=er(),Wue=aE(),Que=iE(),zue=Nn(),wG=Y();wG.initSync();var sn={RUNNING:"running",STOPPED:"stopped",ERRORED:"errored"},Sr={LEAF:"leaf server",HUB:"hub server"},bh;CG.exports=Jue;async function Jue(){bh=wG.get(Ql.CONFIG_PARAMS.ROOTPATH);let e={harperdb:{status:sn.STOPPED}},t;try{t=Number.parseInt(await iO.readFile(oO.join(bh,Ql.HDB_PID_FILE),"utf8"))}catch(s){throw s.code===Ql.NODE_ERROR_CODES.ENOENT?new Error("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB"):s}let r=await zue.getHDBProcessInfo();for(let s of r.core)if(s.pid===t){e.harperdb.status=sn.RUNNING,e.harperdb.pid=t;break}if(e.clustering=await jue(r),e.clustering[Sr.HUB].status===sn.RUNNING&&e.clustering[Sr.LEAF].status===sn.RUNNING){let s=[],n=await Wue({});for(let o of n.nodes){let c={};for(let u in o)c[u.replace("_"," ")]=o[u];s.push(c)}e.clustering.network=s;let i=await Que.clusterStatus();e.clustering.replication={"node name":i.node_name,"is enabled":i.is_enabled,connections:[]};for(let o of i.connections){let c={};c["node name"]=o?.node_name,c.status=o?.status,c.ports={clustering:o?.ports?.clustering,"operations api":o?.ports?.operations_api},c["latency ms"]=o?.latency_ms,c.uptime=o?.uptime,c.subscriptions=o?.subscriptions,c["system info"]={"hdb version":o?.system_info?.hdb_version,"node version":o?.system_info?.node_version,platform:o?.system_info?.platform},e.clustering.replication.connections.push(c)}await Wl.closeConnection()}console.log(Yue.stringify(e)),process.exit()}a(Jue,"status");async function jue(e){let t={[Sr.HUB]:{},[Sr.LEAF]:{}};if(e.clustering.length===0)return t[Sr.HUB].status=sn.STOPPED,t[Sr.LEAF].status=sn.STOPPED,t;let{port:r}=Wl.getServerConfig(Ql.PROCESS_DESCRIPTORS.CLUSTERING_HUB),{username:s,decrypt_hash:n}=await Kue.getClusterUser();try{(await Wl.createConnection(r,s,n,!1)).close(),t[Sr.HUB].status=sn.RUNNING}catch{t[Sr.HUB].status=sn.ERRORED}let{port:i}=Wl.getServerConfig(Ql.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);try{(await Wl.createConnection(i,s,n,!1)).close(),t[Sr.LEAF].status=sn.RUNNING}catch{t[Sr.LEAF].status=sn.ERRORED}try{t[Sr.HUB].pid=Number.parseInt(await iO.readFile(oO.join(bh,"clustering",yG.PID_FILES.HUB),"utf8"))}catch(o){IG.error(o),t[Sr.HUB].pid=void 0}try{t[Sr.LEAF].pid=Number.parseInt(await iO.readFile(oO.join(bh,"clustering",yG.PID_FILES.LEAF),"utf8"))}catch(o){IG.error(o),t[Sr.LEAF].pid=void 0}return t}a(jue,"getHubLeafStatus")});var HG=m(()=>{"use strict";var Xue=require("os"),wh=require("https"),qi=require("fs-extra"),Zue=require("yaml"),ele=require("human-readable-ids").hri,{pipeline:DG}=require("stream/promises"),{createWriteStream:Ch,ensureDir:Lh}=require("fs-extra"),{join:nn}=require("path"),uO=require("lodash"),tle=Y(),rle=Nn(),vG=C(),yh=et(),{restart:sle}=wa(),BG=F(),UG=Qe(),nle=$r(),{isHdbInstalled:ile,main:ole}=_c(),ale=Ah(),lO=R(),{SYSTEM_TABLE_NAMES:MG,SYSTEM_SCHEMA_NAME:cle,CONFIG_PARAMS:zl,OPERATIONS_ENUM:Hr}=lO,ule=9925,lle="info",_le=1e4,dle="clone-node-config.yaml",_O=[MG.ROLE_TABLE_NAME,MG.USER_TABLE_NAME],Jl=process.env.HDB_LEADER_USERNAME,jl=process.env.HDB_LEADER_PASSWORD,Xl=process.env.HDB_LEADER_URL,aO=process.env.HDB_LEADER_CLUSTERING_HOST,Ele=process.env.HDB_LEADER_CLUSTERING_PORT,cO,ye,lt,je,dO,dc;async function fle(){if(await ile())throw new Error("Existing install of HarperDB found on clone node.");if(console.info("Cloning node: "+Xl),ye?.rootPath)dc=ye.rootPath;else try{dc=process.env.ROOTPATH?process.env.ROOTPATH:nn(Xue.homedir(),lO.HDB_ROOT_DIR_NAME)}catch(t){throw console.error(t),new Error("There was an setting default rootPath. Please set 'rootPath' in clone-node-config.yaml")}let e;try{e=nn(dc,dle),ye=Zue.parseDocument(qi.readFileSync(e,"utf8"),{simpleKeys:!0}).toJSON()}catch{console.info(e+" not found, using default config values.")}dO=ye?.clustering?.nodeName??ele.random(),lt=await Dh({operation:Hr.GET_CONFIGURATION}),lt=await JSON.parse(lt.body),global.fetch?(await Sle(),process.env.NODE_TLS_REJECT_UNAUTHORIZED&&delete process.env.NODE_TLS_REJECT_UNAUTHORIZED):await ple(),await mle(),await hle(),await Tle(),await gle(),console.info("Successfully cloned node: "+Xl)}a(fle,"cloneNode");async function hle(){console.info("Cloning configuration"),cO=lt?.clustering?.enabled;let e={[zl.ROOTPATH]:dc};if(cO&&ye?.clustering?.enabled!==!1){if(aO==null)throw new Error("'HDB_LEADER_CLUSTERING_HOST' must be defined");e[zl.CLUSTERING_ENABLED]=!0;let s=lt?.clustering?.hubServer?.cluster?.network?.routes,n=parseInt(Ele)||lt?.clustering?.hubServer?.cluster?.network?.port;e[zl.CLUSTERING_USER]=lt?.clustering?.user;let i=tle.get(zl.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES);Array.isArray(i)?i.push({host:aO,port:n}):i=[{host:aO,port:n}],Array.isArray(s)&&i.concat(s),e[zl.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES]=i}let t=ye?.componentConfig?.exclude;t=t?t.reduce((s,n)=>({...s,[n.name]:!0}),{}):[];for(let s in lt)lt[s]?.package&&!t[s]&&await yh.addConfig(s,lt[s]);ye?.databases&&await yh.addConfig("databases",lt?.schemas);let r=yh.flattenConfig(ye);for(let s in r){let n=lO.CONFIG_PARAM_MAP[s.toLowerCase()];n&&(e[n]=r[s])}e.rootPath==null&&delete e.rootPath,e?.clustering_nodeName==null&&(e.clustering_nodeName=dO),vG.info("Cloning config:",e),uO.isEmpty(e)||await yh.updateConfigValue(void 0,void 0,e,!1,!0)}a(hle,"cloneConfig");async function mle(){if(console.info("Clone node installing HarperDB."),process.env.TC_AGREEMENT="yes",process.env.ROOTPATH=dc,!Jl)throw new Error("HDB_LEADER_USERNAME is undefined.");if(process.env.HDB_ADMIN_USERNAME=Jl,!jl)throw new Error("HDB_LEADER_PASSWORD is undefined.");process.env.HDB_ADMIN_PASSWORD=jl,process.env.OPERATIONSAPI_NETWORK_PORT=ye?.operationsApi?.network?.port??ule,process.env.CLUSTERING_NODENAME=dO,process.env.CLUSTERING_LOGLEVEL=ye?.clustering?.logLevel??lle,await ale()}a(mle,"installHDB");async function ple(){console.info("Cloning system database");let e=Ec("system");await Lh(e);let t=nn(e,"system.mdb"),r=Ch(t,{overwrite:!0}),s=await PG({operation:Hr.GET_BACKUP,database:"system",tables:_O},r);await qi.utimes(t,Date.now(),new Date(s.date)),je=await Dh({operation:Hr.DESCRIBE_ALL}),je=await JSON.parse(je.body);let n=ye?.databaseConfig?.excludeDatabases;if(n=n?n.reduce((o,c)=>({...o,[c.database]:!0}),{}):{},lt.schemas)for(let o in lt.schemas)Object.keys(lt.schemas[o]).includes("tables")&&(n[o]=!0,console.info(`Excluding database '${o}' from clone because leader node has custom pathing configured for one or more of its tables`));let i=ye?.databaseConfig?.excludeTables;i=i?i.reduce((o,c)=>({...o,[c.database==null?null:c.database+c.table]:!0}),{}):{};for(let o in je){if(n[o]){je[o]="excluded";continue}if(uO.isEmpty(je[o]))continue;let c=[],u=!1;for(let h in je[o])i[o+h]?(u=!0,je[o][h]="excluded"):c.push(h);let l;u?(console.info(`Cloning database: ${o} tables: ${c}`),l={operation:Hr.GET_BACKUP,database:o,tables:c}):(console.info(`Cloning database: ${o}`),l={operation:Hr.GET_BACKUP,database:o});let _=Ec(o);await Lh(_);let d=nn(_,o+".mdb"),E=Ch(d,{overwrite:!0}),f=await PG(l,E);await qi.utimes(d,Date.now(),new Date(f.date))}}a(ple,"cloneTables");async function Sle(){console.info("Cloning system database");let e=await Ih({operation:Hr.GET_BACKUP,database:"system",tables:_O},!0),t=Ec("system");await Lh(t);let r=nn(t,"system.mdb");await DG(e.body,Ch(r,{overwrite:!0})),await qi.utimes(r,Date.now(),new Date(e.headers.get("date"))),je=await Ih({operation:Hr.DESCRIBE_ALL}),je=await je.json();let s=ye?.databaseConfig?.excludeDatabases;if(s=s?s.reduce((i,o)=>({...i,[o.database]:!0}),{}):{},lt.schemas)for(let i in lt.schemas)Object.keys(lt.schemas[i]).includes("tables")&&(s[i]=!0,console.info(`Excluding database '${i}' from clone because leader node has custom pathing configured for one or more of its tables`));let n=ye?.databaseConfig?.excludeTables;n=n?n.reduce((i,o)=>({...i,[o.database==null?null:o.database+o.table]:!0}),{}):{};for(let i in je){if(s[i]){je[i]="excluded";continue}if(uO.isEmpty(je[i]))continue;let o=[],c=!1;for(let f in je[i])n[i+f]?(c=!0,je[i][f]="excluded"):o.push(f);let u;c?(console.info(`Cloning database: ${i} tables: ${o}`),u=await Ih({operation:Hr.GET_BACKUP,database:i,tables:o},!0)):(console.info(`Cloning database: ${i}`),u=await Ih({operation:Hr.GET_BACKUP,database:i},!0));let l=Ec(i);await Lh(l);let _=new Date(u.headers.get("date")),d=nn(l,`${_.getTime()}-${i}.mdb`);await DG(u.body,Ch(d,{overwrite:!0}));let E=nn(l,i+".mdb");await qi.rename(d,E),await qi.utimes(E,Date.now(),_)}}a(Sle,"cloneTablesFetch");async function Ih(e,t=!1){let r=ye?.httpsRejectUnauthorized??!1,s=new wh.Agent({rejectUnauthorized:r});r||(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");let i={Authorization:"Basic "+Buffer.from(Jl+":"+jl).toString("base64"),"Content-Type":"application/json"};t&&(i["Accept-Encoding"]="gzip");let o=await fetch(Xl,{method:"POST",headers:i,body:JSON.stringify(e),agent:s,compress:!0});if(o.ok)return o;throw console.error(`HTTP Error Response: ${o.status} ${o.statusText}`),new Error(await o.text())}a(Ih,"leaderHttpReqFetch");function Ec(e){return ye?.databases&&ye?.databases[e]?.path||ye?.storage&&ye?.storage?.path||nn(dc,"database")}a(Ec,"getDbFileDir");async function Tle(){let{deployComponent:e}=PE(),t=await Dh({operation:Hr.GET_COMPONENTS});t=await JSON.parse(t.body);let r=[];if(t.entries.length){for(let n of t.entries){if(!n.entries)continue;let i=!1;if(ye?.componentConfig?.exclude){for(let o of ye.componentConfig.exclude)if(o?.name!=null&&o.name===n.name){i=!0;break}}i||r.push(n.name)}let s=ye?.componentConfig?.skipNodeModules!==!1;for(let n of r){console.info("Cloning component: "+n);let i=await Dh({operation:Hr.PACKAGE_COMPONENT,project:n,skip_node_modules:s}),{payload:o}=await JSON.parse(i.body);await e({payload:o,project:n})}}}a(Tle,"cloneComponents");async function gle(){if(!cO)return;let e=await rle.getHDBProcessInfo();e.clustering.length===0||e.core.length===0?await ole():(console.info(await sle({operation:Hr.RESTART})),await BG.async_set_timeout(_le)),console.info("Clustering cloned tables");let t=ye?.clusteringConfig?.subscribeToLeaderNode!==!1,r=ye?.clusteringConfig?.publishToLeaderNode!==!1;await nle.setSchemaDataToGlobalAsync();let s=Du(),n=[],i=await qi.stat(nn(Ec("system"),"system.mdb"));for(let o of _O)n.push({schema:cle,table:o,subscribe:t,publish:r,start_time:i.mtime.toISOString()});for(let o in je){if(je[o]==="excluded")continue;let c=await qi.stat(nn(Ec(o),o+".mdb"));for(let u in je[o])je[o][u]!=="excluded"&&n.push({schema:o,table:u,subscribe:t,publish:r,start_time:c.mtime.toISOString()})}await UG.createTableStreams(n),vG.info("Sending add_node request to node:",lt?.clustering?.nodeName,"with subscriptions:",n),await s({operation:Hr.ADD_NODE,node_name:lt?.clustering?.nodeName,subscriptions:n},!0),await UG.closeConnection()}a(gle,"clusterTables");async function Dh(e){let t=new wh.Agent({rejectUnauthorized:ye?.httpsRejectUnauthorized??!1}),s={Authorization:"Basic "+Buffer.from(Jl+":"+jl).toString("base64"),"Content-Type":"application/json"},n=new URL(Xl),i={protocol:n.protocol,host:n.hostname,method:"POST",headers:s};return n.protocol==="https:"&&(i.agent=t),n.port&&(i.port=n.port),await BG.httpRequest(i,e)}a(Dh,"leaderHttpReq");async function PG(e,t){let r=new wh.Agent({rejectUnauthorized:ye?.httpsRejectUnauthorized??!1}),n={Authorization:"Basic "+Buffer.from(Jl+":"+jl).toString("base64"),"Content-Type":"application/json"},i=new URL(Xl),o={protocol:i.protocol,host:i.hostname,method:"POST",headers:n};return i.protocol==="https:"&&(o.agent=r),i.port&&(o.port=i.port),new Promise((c,u)=>{let l=wh.request(o,_=>{_.pipe(t),_.on("end",()=>{t.close(),c(_.headers)})});l.on("error",_=>{u(_)}),l.write(JSON.stringify(e)),l.end()})}a(PG,"leaderHttpStream");fle().then().catch(e=>{console.log(e)})});var fc=C(),Rle=$i(),EO=R(),Uh=require("fs"),qG=require("path"),BAe=require("os"),{PACKAGE_ROOT:Ale}=R(),Ole=jO(),HAe=Y(),Nle=(Uf(),re(DR)),{SERVICE_ACTIONS_ENUM:bs}=EO;ble();function ble(){let e=Ole();if(e)if(e.error){console.error(e.error),fc.error(e.error);return}else e.warn&&(console.warn(e.warn),fc.warn(e.warn));let t;Uh.readdir(qG.join(Ale,"bin"),r=>{if(r)return fc.error(r);process.argv&&process.argv[2]&&!process.argv[2].startsWith("-")&&(t=process.argv[2].toLowerCase());let s;switch(t){case bs.DEBUG:require("inspector").open(9229),Nle.debugMode=!0;case bs.RUN:let n=process.argv[3];n&&n[0]!=="-"&&(Uh.existsSync(n)||(console.error(`The folder ${n} does not exist`),process.exit(1)),Uh.statSync(n).isDirectory()||(console.error(`The path ${n} is not a folder`),process.exit(1)),Uh.existsSync(qG.join(n,EO.HDB_CONFIG_FILE))?process.env.ROOTPATH=n:process.env.RUN_HDB_APP=n),_c().main();break;case bs.START:s=_c().launch();break;case bs.INSTALL:SG()().then(()=>_c().main(!0)).catch(E=>{console.error(E)});break;case bs.REGISTER:RG().register().then(E=>{console.log(E)}).catch(E=>{console.error(E)});break;case bs.STOP:bG()().then(()=>{process.exit(0)}).catch(E=>{console.error(E)});break;case bs.RESTART:wa().restart({}).then().catch(E=>{fc.error(E),console.error(`There was an error restarting harperdb. ${E}`),process.exit(1)});break;case bs.VERSION:Rle.printVersion();break;case bs.UPGRADE:fc.setLogLevel(EO.LOG_LEVELS.INFO),eO().upgrade(null).then(()=>{console.log("Your instance of HDB is up to date!")}).catch(E=>{fc.error(`Got an error during upgrade ${E}`)});break;case bs.STATUS:LG()().then().catch(E=>{console.error(E)});break;case void 0:process.env.HDB_LEADER_URL?HG():_c().main();break;default:console.warn(`The "${t}" command is not understood.`);case bs.HELP:console.log(`
|
|
104
|
+
install_user = ${u}`;try{Di.writeFileSync(o,l)}catch(d){throw console.log("There was a problem updating the HarperDB boot properties file. Please check the log for details."),d}try{FA.initSync(!0)}catch(d){throw console.error("Unable to initialize new properties. Please check the log for details."),d}let _="New settings file for 4.0.0 upgrade successfully created.";try{Di.removeSync(r),console.log(_),qo.info(_)}catch(d){throw console.error("There was a problem deleting the old settings file and directory. Please check the log for details."),d}}a(Mae,"updateSettingsFile_4_0_0");xl.async_functions.push(Mae);xl.async_functions.push(Dae);xl.async_functions.push(Cae);xl.async_functions.push(Uae);gF.push(xl);RF.exports=gF});var GA=m((XRe,yF)=>{"use strict";var Fo=F(),Pae=R(),OF=C(),{DATA_VERSION:vae,UPGRADE_VERSION:Bae}=Pae.UPGRADE_JSON_FIELD_NAMES_ENUM,NF=lF(),gh=AF(),Go=new Map;NF&&NF.forEach(e=>{Go.set(e.version,e)});gh&&gh.forEach(e=>{Go.set(e.version,e)});gh&&gh.forEach(e=>{Go.set(e.version,e)});function Hae(){return[...Go.keys()].sort(Fo.compareVersions)}a(Hae,"getSortedVersions");function bF(e){let t=e[vae],r=e[Bae];return Fo.isEmptyOrZeroLength(t)||Fo.isEmptyOrZeroLength(r)?(OF.info(`There is an issue with the version data in your instance of HDB. Current version data: ${e}`),OF.error("There was an error when trying to evaluate the version information for your instance. Trying to start the server anyways but it may fail. If you continue to have this problem, please contact support@harperdb.io."),[]):[...Go.keys()].sort(Fo.compareVersions).filter(function(s){return Fo.compareVersions(s,t)>0&&Fo.compareVersions(s,r)<=0})}a(bF,"getVersionsForUpgrade");function qae(e){return bF(e).length>0}a(qae,"hasUpgradesRequired");function Fae(e){return Fo.isEmptyOrZeroLength(e)?null:Go.has(e)?Go.get(e):null}a(Fae,"getDirectiveByVersion");yF.exports={getSortedVersions:Hae,getDirectiveByVersion:Fae,getVersionsForUpgrade:bF,hasUpgradesRequired:qae}});var Rh=m((eAe,DF)=>{"use strict";var Gae=require("util"),xA=require("chalk"),xae=require("os"),wF=Xt(),kae=jt(),vr=R(),CF=X0(),$A=op(),{UpgradeObject:IF}=tF(),{forceDowngradePrompt:$ae}=Eh(),Vae=$i(),kl=C(),oc=F(),VA=$r(),Yae=(_e(),re(be)),Kae=GA(),Wae=Gae.promisify(VA.setSchemaDataToGlobal),Qae=kae.searchByValue,zae="info_id",Jae="2.9.9",jae="3.0.0";async function Xae(e){let t=new CF.HdbInfoInsertObject(1,e,e),r=new $A.InsertObject(vr.OPERATIONS_ENUM.INSERT,vr.SYSTEM_SCHEMA_NAME,vr.SYSTEM_TABLE_NAMES.INFO_TABLE_NAME,vr.SYSTEM_TABLE_HASH_ATTRIBUTES.INFO_TABLE_ATTRIBUTE,[t]);return VA.setSchemaDataToGlobal(),wF.insert(r)}a(Xae,"insertHdbInstallInfo");async function kA(e){let t,r=await LF(),s=new Map([[0,{}]]);for(let c of r)s.set(c.info_id,c);let i=Math.max.apply(null,[...s.keys()])+1;t=new CF.HdbInfoInsertObject(i,e,e);let o=new $A.InsertObject(vr.OPERATIONS_ENUM.INSERT,vr.SYSTEM_SCHEMA_NAME,vr.SYSTEM_TABLE_NAMES.INFO_TABLE_NAME,vr.SYSTEM_TABLE_HASH_ATTRIBUTES.INFO_TABLE_ATTRIBUTE,[t]);return await Wae(),wF.insert(o)}a(kA,"insertHdbUpgradeInfo");async function LF(){let e=new $A.NoSQLSeachObject(vr.SYSTEM_SCHEMA_NAME,vr.SYSTEM_TABLE_NAMES.INFO_TABLE_NAME,zae,vr.SYSTEM_TABLE_HASH_ATTRIBUTES.INFO_TABLE_ATTRIBUTE,["*"],"*"),t=[];try{t=Array.from(await Qae(e))}catch(r){kl.info(r)}return t}a(LF,"getAllHdbInfoRecords");async function Zae(){let e=await LF();if(e.length===0)return;let t,r=new Map;for(let n of e)r.set(n.info_id,n);let s=Math.max.apply(null,[...r.keys()]);return t=r.get(s),t}a(Zae,"getLatestHdbInfoRecord");async function ece(){kl.info("Checking if HDB software has been updated");try{let e=Vae.version(),t=await Zae(),r;if(oc.isEmpty(t))r=Jae;else if(r=t.data_version_num,oc.compareVersions(r.toString(),e.toString())>0){if(!oc.isCompatibleDataVersion(r.toString(),e.toString()))throw console.log(xA.yellow(`This instance's data was last run on version ${r}`)),console.error(xA.red(`You have installed a version lower than the version that your data was created on or was upgraded to. This may cause issues and is currently not supported.${xae.EOL}${vr.SUPPORT_HELP_MSG}`)),new Error("Trying to downgrade major HDB versions is not supported.");oc.isCompatibleDataVersion(r.toString(),e.toString(),!0)||(console.log(xA.yellow(`This instance's data was last run on version ${r}`)),await $ae(new IF(r,e))?await kA(e.toString()):(console.log("Cancelled downgrade, closing HarperDB"),process.exit(0)))}if(VA.setSchemaDataToGlobal(),tce(r),e.toString()===r.toString())return;let s=new IF(r,e);if(Kae.hasUpgradesRequired(s))return s;oc.compareVersions(s.data_version.toString(),s.upgrade_version.toString())<0&&(await kA(s.upgrade_version),kl.notify(`HarperDB running on upgraded version: ${s.upgrade_version}`))}catch(e){throw kl.fatal("Error while trying to evaluate the state of hdb data and the installed hdb version"),kl.fatal(e),e}}a(ece,"getVersionUpdateInfo");function tce(e){let t=`You are attempting to upgrade from an old instance of HarperDB that is no longer supported. In order to upgrade to this version, you must do a fresh install. If you need support, please contact ${vr.HDB_SUPPORT_ADDRESS}`;if(!("hdb_info"in Yae.databases.system))throw console.log(t),new Error(t);if(!oc.isEmpty(e)&&e<jae)throw console.log(t),new Error(t)}a(tce,"checkIfInstallIsSupported");DF.exports={insertHdbInstallInfo:Xae,insertHdbUpgradeInfo:kA,getVersionUpdateInfo:ece}});var BF=m((rAe,vF)=>{"use strict";var YA=require("joi"),{boolean:rce,string:UF,number:sce}=YA.types(),MF=require("fs-extra"),$l=R(),PF=require("path"),nce=He();vF.exports=ice;function ice(e){let t=UF.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null),r=YA.object({[$l.INSTALL_PROMPTS.ROOTPATH]:YA.custom(oce),[$l.INSTALL_PROMPTS.OPERATIONSAPI_NETWORK_PORT]:sce.min(0),[$l.INSTALL_PROMPTS.TC_AGREEMENT]:UF.valid("yes","YES","Yes"),[$l.INSTALL_PROMPTS.CLUSTERING_NODENAME]:t,[$l.INSTALL_PROMPTS.CLUSTERING_ENABLED]:rce});return nce.validateBySchema(e,r)}a(ice,"installValidator");function oce(e,t){if(MF.existsSync(PF.join(e,"system/hdb_user/data.mdb"))||MF.existsSync(PF.join(e,"system/hdb_user.mdb")))return t.message(`'${e}' is already in use. Please enter a different path.`)}a(oce,"validateRootAvailable")});var qF=m((nAe,HF)=>{"use strict";var{mkdirpSync:ace}=require("fs-extra"),tn=require("path"),ac=R(),WA=C(),cce=Vr(),KA=En(),uce=De();HF.exports=lce;async function lce(e){WA.trace("Mounting HarperDB"),As(e),As(tn.join(e,"backup")),As(tn.join(e,"trash")),As(tn.join(e,"keys")),As(tn.join(e,"keys",ac.LICENSE_FILE_NAME)),As(tn.join(e,"log")),As(tn.join(e,"doc")),As(tn.join(e,"database")),As(tn.join(e,ac.TRANSACTIONS_DIR_NAME)),As(tn.join(e,"clustering","leaf")),As(tn.join(e,"components")),await _ce()}a(lce,"mountHdb");async function _ce(){let e=cu(),t=Object.keys(KA);for(let r=0;r<t.length;r++){let s=t[r],n=KA[s].hash_attribute;try{uce.initSystemSchemaPaths(ac.SYSTEM_SCHEMA_NAME,s);let i=new e(ac.SYSTEM_SCHEMA_NAME,s,n);i.attributes=KA[s].attributes;let o=i.attributes.find(({attribute:c})=>c===n);o.isPrimaryKey=!0,await cce.createTable(s,i)}catch(i){throw WA.error(`issue creating environment for ${ac.SYSTEM_SCHEMA_NAME}.${s}: ${i}`),i}}}a(_ce,"createLMDBTables");function As(e){ace(e,{mode:ac.HDB_FILE_PERMISSIONS}),WA.info(`Directory ${e} created`)}a(As,"makeDirectory")});var Ah=m((aAe,zF)=>{"use strict";var JA=require("os"),kF=require("inquirer"),Vn=require("fs-extra"),dce=require("properties-reader"),xo=require("chalk"),vi=require("path"),Ece=require("human-readable-ids").hri,fce=require("ora"),ct=C(),Bi=Y(),uc=F(),QA=Gi(),$F=Rh(),VF=$i(),te=R(),hce=BF(),mce=qF(),YF=et(),pce=er(),Sce=qd(),Tce=yA(),gce=$r(),Rce=require("util").promisify,Ace=Rce(gce.setSchemaDataToGlobal),Oce=qA(),cc=a(e=>e,"PROMPT_ANSWER_TRANSFORMER"),Vt=a(e=>xo.magenta.bold(e),"HDB_PROMPT_MSG"),Nce="https://harperdb.io/legal/end-user-license-agreement",Hi=JA.EOL,Ui="",bce="yes",FF="Starting HarperDB install...",GF="HarperDB installation was successful.",xF="Terms & Conditions acceptance is required to proceed with installation. Exiting install...",yce="An out of date version of HarperDB is already installed.",zA="It appears that HarperDB is already installed. Exiting install...",Ice="Aborting install",wce=new RegExp(/^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/),Cce=new RegExp(/^[^\s.,*>]+$/),Lce=JA.homedir(),Dce=vi.join(Lce,te.HDB_ROOT_DIR_NAME),Uce=9925,Mce="HDB_ADMIN",Pce="CLUSTER_USER",pr={DESTINATION:"Please enter a destination for HarperDB:",HDB_PORT:"Please enter a server listening port for HarperDB:",HDB_USERNAME:"Please enter a username for the HDB_ADMIN:",HDB_PASS:"Please enter a password for the HDB_ADMIN:",NODE_NAME:"Please enter a unique name for this node:",CLUSTER_USERNAME:"Please enter a username for the CLUSTER_USER:",CLUSTER_PASS:"Please enter a password for the CLUSTER_USER:"},oAe=uc.getEnvCliRootPath(),Pi;zF.exports=KF;KF.createSuperUser=QF;async function KF(){console.log(Vt(Hi+FF+Hi)),ct.notify(FF);let e=Bce(),t=hce(e);if(t)throw t.message;await Hce(),await qce(e);let r=await vce(e);Pi=r[te.INSTALL_PROMPTS.ROOTPATH],await Vn.pathExists(vi.join(Pi,te.HDB_CONFIG_FILE))&&(console.error(zA),process.exit());let s=fce({prefixText:Vt("Installing"),color:"magenta",spinner:"simpleDots"});if(s.start(),uc.isEmpty(Pi))throw new Error("Installer should have the HDB root param at the stage it is in but it does not.");Bi.setHdbBasePath(Pi),await mce(Pi),await Fce(),await Gce(r),ct.initLogSettings(!0),await QF(r),await kce(r),await Oce.generateKeys(),await $ce(),Tce(),s.stop(),console.log(Vt(Hi+GF+Hi)),ct.notify(GF)}a(KF,"install");async function vce(e){ct.trace("Getting install prompts and params.");let t,r=[{type:"input",transformer:cc,when:Mi(e[te.INSTALL_PROMPTS.ROOTPATH],pr.DESTINATION),name:te.INSTALL_PROMPTS.ROOTPATH,prefix:Ui,default:Dce,validate:async n=>rn(n)?rn(n):await Vn.pathExists(vi.join(n,"system","hdb_user.mdb"))?`'${n}' is already in use. Please enter a different path.`:!0,message:Vt(pr.DESTINATION)},{type:"input",transformer:cc,when:Mi(e[te.INSTALL_PROMPTS.OPERATIONSAPI_NETWORK_PORT],pr.HDB_PORT),name:te.INSTALL_PROMPTS.OPERATIONSAPI_NETWORK_PORT,prefix:Ui,default:Uce,validate:n=>wce.test(n)?!0:"Invalid port.",message:Vt(pr.HDB_PORT)},{type:"input",transformer:cc,when:Mi(e[te.INSTALL_PROMPTS.HDB_ADMIN_USERNAME],pr.HDB_USERNAME),name:te.INSTALL_PROMPTS.HDB_ADMIN_USERNAME,prefix:Ui,default:Mce,validate:n=>rn(n)?rn(n):(t=n,!0),message:Vt(pr.HDB_USERNAME)},{type:"password",when:Mi(e[te.INSTALL_PROMPTS.HDB_ADMIN_PASSWORD],pr.HDB_PASS),name:te.INSTALL_PROMPTS.HDB_ADMIN_PASSWORD,prefix:Ui,validate:n=>rn(n)?rn(n):!0,message:Vt(pr.HDB_PASS)}];if(uc.autoCastBoolean(e[te.INSTALL_PROMPTS.CLUSTERING_ENABLED])===!0){let n=[{type:"input",transformer:cc,when:Mi(e[te.INSTALL_PROMPTS.CLUSTERING_NODENAME],pr.NODE_NAME),name:te.INSTALL_PROMPTS.CLUSTERING_NODENAME,prefix:Ui,default:Ece.random(),validate:i=>Cce.test(i)?!0:"Invalid node name, must not contain ., * or >",message:Vt(pr.NODE_NAME)},{type:"input",transformer:cc,when:Mi(e[te.INSTALL_PROMPTS.CLUSTERING_USER],pr.CLUSTER_USERNAME),name:te.INSTALL_PROMPTS.CLUSTERING_USER,prefix:Ui,default:Pce,validate:i=>rn(i)?rn(i):i.toLowerCase()===t.toLowerCase()?"Username is already in use.":!0,message:Vt(pr.CLUSTER_USERNAME)},{type:"password",when:Mi(e[te.INSTALL_PROMPTS.CLUSTERING_PASSWORD],pr.CLUSTER_PASS),name:te.INSTALL_PROMPTS.CLUSTERING_PASSWORD,prefix:Ui,validate:i=>rn(i)?rn(i):!0,message:Vt(pr.CLUSTER_PASS)}];r.push(...n)}let s=await kF.prompt(r);if(Object.keys(s).length===0)return e;for(let n in s)e[n]===void 0&&(e[n]=s[n]);return e}a(vce,"installPrompts");function Mi(e,t){return e!==void 0?(t.includes("password")?(console.log(`${Vt(t)} ${xo.gray("[hidden]")}`),ct.trace(`${Vt(t)} [hidden]`)):(console.log(`${Vt(t)} ${e}`),ct.trace(`${Vt(t)} ${e}`)),!1):!0}a(Mi,"displayCmdEnvVar");function rn(e){let t=e.replace(/ /g,"");if(t===""||t==="''"||t==='""')return"Value cannot be empty."}a(rn,"checkForEmptyValue");function Bce(){let e=Object.keys(te.INSTALL_PROMPTS),t=QA(e),r=QA(Object.keys(te.CONFIG_PARAM_MAP),!0),s={};for(let n of e){let i=te.CONFIG_PARAM_MAP[n.toLowerCase()];t[n]?i===void 0?s[n]=t[n]:s[i.toUpperCase()]=t[n]:i!==void 0&&r[i.toLowerCase()]&&(s[n]=r[i.toLowerCase()])}return s}a(Bce,"checkForPromptOverride");async function Hce(){ct.trace("Checking for existing install.");let e=uc.getPropsFilePath(),t=await Vn.pathExists(e),r;if(t){ct.trace(`Install found an existing boot prop file at:${e}`);let s=dce(e),n=YF.getConfigValue(te.BOOT_PROP_PARAMS.SETTINGS_PATH_KEY)||s.get(te.BOOT_PROP_PARAMS.SETTINGS_PATH_KEY);r=await Vn.pathExists(n)}if(!t&&uc.noBootFile()&&(r=!0),r){if(ct.trace(`Install found existing HDB config at:${e}`),await $F.getVersionUpdateInfo()){let n=`Please use \`harperdb upgrade\` to update to ${VF.version()}. Exiting install...`;console.log(Hi+xo.magenta.bold(yce)),console.log(xo.magenta.bold(n)),ct.error(n)}else console.log(Hi+xo.magenta.bold(zA)),ct.error(zA);process.exit(0)}}a(Hce,"checkForExistingInstall");async function qce(e){ct.info("Asking for terms agreement.");let t=`Terms & Conditions can be found at ${Nce}${Hi}and can be viewed by typing or copying and pasting the URL into your web browser.${Hi}I Agree to the HarperDB Terms and Conditions. (yes/no)`,r={prefix:Ui,transformer:cc,when:Mi(e[te.INSTALL_PROMPTS.TC_AGREEMENT],t),name:te.INSTALL_PROMPTS.TC_AGREEMENT,message:Vt(t),validate:n=>n.toLowerCase()==="yes"||n.toLowerCase()==="no"?!0:xo.yellow("Please enter 'yes' or 'no'")},s=await kF.prompt([r]);s[te.INSTALL_PROMPTS.TC_AGREEMENT]&&s[te.INSTALL_PROMPTS.TC_AGREEMENT].toLowerCase()!==bce&&(console.log(xo.yellow(xF)),ct.error(xF),process.exit(0))}a(qce,"termsAgreement");async function Fce(){let e=vi.join(Pi,te.HDB_CONFIG_FILE),t;try{t=JA.userInfo().username}catch{t=process.env.USERNAME||process.env.USER||process.env.LOGNAME||process.env.LNAME||process.env.SUDO_USER}if(t){let r=`settings_path = ${e}
|
|
105
|
+
install_user = ${t}`,s=uc.getHomeDir(),n=vi.join(s,te.HDB_HOME_DIR_NAME),i=vi.join(n,te.LICENSE_KEY_DIR_NAME);try{Vn.mkdirpSync(n,{mode:te.HDB_FILE_PERMISSIONS}),Vn.mkdirpSync(i,{mode:te.HDB_FILE_PERMISSIONS})}catch{console.error(`Could not make settings directory ${te.HDB_HOME_DIR_NAME} in home directory. Please check your permissions and try again.`)}let o=vi.join(n,te.BOOT_PROPS_FILE_NAME);try{await Vn.writeFile(o,r)}catch(c){throw ct.error(`There was an error creating the boot file at path: ${o}`),c}Bi.setProperty(te.HDB_SETTINGS_NAMES.INSTALL_USER,`${t}`),Bi.setProperty(te.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,e),Bi.setProperty(Bi.BOOT_PROPS_FILE_PATH,o)}}a(Fce,"createBootPropertiesFile");async function Gce(e){ct.trace("Creating HarperDB config file");let t=QA(Object.keys(te.CONFIG_PARAM_MAP),!0);Object.assign(t,e);try{YF.createConfigFile(t),Bi.initSync()}catch(r){xce(r)}}a(Gce,"createConfigFile");function xce(e){ct.error(`Error creating HarperDB config file. Rolling back install - ${e}`),console.error(e),console.error(Ice);let t=vi.resolve(Bi.get(Bi.BOOT_PROPS_FILE_PATH),"../");t&&Vn.removeSync(t),Pi&&Vn.removeSync(Pi),process.exit(1)}a(xce,"rollbackInstall");async function WF(e,t){ct.trace("Creating admin user"),await Ace();let r;try{r=await Sce.addRole(e)}catch(s){if(s.message.includes("already exists"))t=void 0;else throw s.message+="Error creating role",s}if(t)try{t.role=r.role,await pce.addUser(t)}catch(s){throw s.message=`Error creating user - ${s}`,s}}a(WF,"createAdminUser");async function QF(e){ct.trace("Creating Super user.");let t={role:"super_user",permission:{super_user:!0}},r={username:e[te.INSTALL_PROMPTS.HDB_ADMIN_USERNAME].toString(),password:e[te.INSTALL_PROMPTS.HDB_ADMIN_PASSWORD].toString(),active:!0};await WF(t,r),delete e[te.INSTALL_PROMPTS.HDB_ADMIN_USERNAME],delete e[te.INSTALL_PROMPTS.HDB_ADMIN_PASSWORD]}a(QF,"createSuperUser");async function kce(e){ct.trace("Creating Cluster user.");let t;e[te.INSTALL_PROMPTS.CLUSTERING_USER]&&e[te.INSTALL_PROMPTS.CLUSTERING_PASSWORD]&&(t={username:e[te.INSTALL_PROMPTS.CLUSTERING_USER].toString(),password:e[te.INSTALL_PROMPTS.CLUSTERING_PASSWORD].toString(),active:!0}),await WF({role:"cluster_user",permission:{cluster_user:!0}},t),delete e[te.INSTALL_PROMPTS.CLUSTERING_USER],delete e[te.INSTALL_PROMPTS.CLUSTERING_PASSWORD]}a(kce,"createClusterUser");async function $ce(){let e=VF.version();if(e)await $F.insertHdbInstallInfo(e);else throw new Error("The version is missing/removed from HarperDB package.json")}a($ce,"insertHdbVersionInfo")});var XF=m((uAe,jF)=>{"use strict";var jA=F(),Br=C(),JF=GA();jF.exports={processDirectives:Vce};async function Vce(e){console.log("Starting upgrade process...");let t=JF.getVersionsForUpgrade(e),r=Wce(t),s=[],n=r.length;for(let i=0;i<n;i++){let o=r[i],c=`Running upgrade for version ${o.version}`;Br.notify(c),console.log(c);let u=[],l=[];try{u=Yce(o.sync_functions)}catch(_){throw Br.error(`Error while running an upgrade script for ${o.version}`),_}try{l=await Kce(o.async_functions)}catch(_){throw Br.error(`Error while running an upgrade script for ${o.version}`),_}s.push(...u,...l)}return s}a(Vce,"processDirectives");function Yce(e){if(jA.isEmptyOrZeroLength(e))return Br.info("No functions found to run for upgrade"),[];if(!Array.isArray(e))return Br.info("Passed parameter is not an array"),[];let t=[];for(let r of e){if(Br.info(`Running function ${r.name}`),!(r instanceof Function)){Br.info("Variable being processed is not a function");continue}let s=r();Br.info(s),t.push(s)}return t}a(Yce,"runSyncFunctions");async function Kce(e){if(jA.isEmptyOrZeroLength(e))return Br.info("No functions found to run for upgrade"),[];if(!Array.isArray(e))return Br.info("Passed parameter is not an array"),[];let t=[],r=e.length;for(let s=0;s<r;s++){let n=e[s];if(Br.info(`Running function ${n.name}`),!(n instanceof Function)){Br.info("Variable being processed is not a function");continue}let i=await n();Br.info(i),t.push(i)}return t}a(Kce,"runAsyncFunctions");function Wce(e){if(jA.isEmptyOrZeroLength(e))return[];let t=[];for(let r of e){let s=JF.getDirectiveByVersion(r);s&&t.push(s)}return t}a(Wce,"getUpgradeDirectivesToInstall")});var eO=m((_Ae,nG)=>{"use strict";var Oh=Y();Oh.initSync();var rG=require("chalk"),ZF=require("fs-extra"),Kn=C(),Yn=R(),eG=$i(),Qce=XF(),XA=F(),sG=Rh(),zce=Eh(),tG=zh(),Jce=$r(),jce=require("util").promisify,Xce=jce(Jce.setSchemaDataToGlobal),ZA,{UPGRADE_VERSION:Nh}=Yn.UPGRADE_JSON_FIELD_NAMES_ENUM;nG.exports={upgrade:Zce};async function Zce(e){await Xce(),ZA===void 0&&(ZA=ya()),ZF.existsSync(Oh.get(Oh.BOOT_PROPS_FILE_PATH))||(Vl("The hdb_boot_properties file was not found. Please install HDB.",Yn.LOG_LEVELS.ERROR),process.exit(1)),ZF.existsSync(Oh.get(Yn.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY))||(Vl("The hdb settings file was not found. Please make sure HDB is installed.",Yn.LOG_LEVELS.ERROR),process.exit(1));let t=e;t||(t=await sG.getVersionUpdateInfo(),t||(console.log("HarperDB version is current"),process.exit(0))),Vl(`This version of HarperDB is ${eG.version()}`,Yn.LOG_LEVELS.INFO);let r=t[Nh]?t[Nh]:eG.version();r||(console.log(`Current Version field missing from the package.json file. Cannot continue with upgrade. If you need support, please contact ${Yn.HDB_SUPPORT_ADDRESS}`),Kn.notify("Missing new version field from upgrade info object"),process.exit(1)),await eue();let s,n=0;try{s=await zce.forceUpdatePrompt(t)}catch(i){Kn.error("There was an error when prompting user about upgrade."),Kn.error(i),s=!1,n=1}s||(console.log("Cancelled upgrade, closing HarperDB"),process.exit(n)),Kn.info(`Starting upgrade to version ${r}`),await tue(t),Vl(`HarperDB was successfully upgraded to version ${t[Nh]}`,Yn.LOG_LEVELS.INFO)}a(Zce,"upgrade");async function eue(){let e=!1,t=await tG.findPs(Yn.HDB_PROC_NAME);if(XA.isEmptyOrZeroLength(t)||(e=!0),!e){let r=await tG.findPs("hdb_express");XA.isEmptyOrZeroLength(r)||(e=!0)}if(!e){let r=await ZA.list();XA.isEmptyOrZeroLength(r)||(e=!0)}if(e){let r="HarperDB is running, please stop all HarperDB services with 'harperdb stop' and run the upgrade command again.";console.log(rG.red(r)),Kn.error(r),process.exit(1)}}a(eue,"checkIfRunning");async function tue(e){try{await Qce.processDirectives(e)}catch(t){throw Vl("There was an error during the data upgrade. Please check the logs.",Yn.LOG_LEVELS.ERROR),t}try{await sG.insertHdbUpgradeInfo(e[Nh])}catch(t){Kn.error("Error updating the 'hdb_info' system table."),Kn.error(t)}}a(tue,"runUpgrade");function Vl(e,t=void 0){t||(t=Kn.info),Kn[t](e),console.log(rG.magenta(e))}a(Vl,"printToLogAndConsole")});var uG=m((EAe,cG)=>{"use strict";var{promises:rO,createReadStream:rue,createWriteStream:sue}=require("fs"),{createGzip:nue}=require("zlib"),{promisify:iue}=require("util"),{pipeline:oue}=require("stream"),aue=iue(oue),cue=require("path"),$o=Y();$o.initSync();var ko=C(),{CONFIG_PARAMS:Yl,ITC_EVENT_TYPES:uue}=R(),{onMessageFromWorkers:lue}=tt(),_ue=6e4,due="'interval' and 'maxSize' are both undefined, to enable logging rotation at least one of these values must be defined in harperdb-config.yaml",Eue="'logging.rotation.path' is undefined, to enable logging rotation set this value in harperdb-config.yaml",tO,oG;cG.exports=aG;lue(e=>{e.type===uue.RESTART&&($o.initSync(!0),clearInterval(oG),$o.get(Yl.LOGGING_ROTATION_ENABLED)&&aG())});async function aG(){try{let e=ko.getLogFilePath(),t=$o.get(Yl.LOGGING_ROTATION_MAXSIZE),r=$o.get(Yl.LOGGING_ROTATION_INTERVAL);if(!t&&!r){ko.error(due);return}let s=$o.get(Yl.LOGGING_ROTATION_PATH);if(!s){ko.error(Eue);return}let n;if(t){let o=t.slice(-1),c=t.slice(0,-1);o==="G"?n=c*1e9:o==="M"?n=c*1e6:n=c*1e3}let i;if(r){let o=r.slice(-1),c=r.slice(0,-1);o==="D"?i=c*1440:o==="H"?i=c*60:i=c}tO=Date.now()/6e4,ko.trace("Log rotate enabled, maxSize:",t,"interval:",r),oG=setInterval(async()=>{if(n){let o;o=await rO.stat(e),o.size>=n&&await iG(e,s)}i&&Date.now()/6e4-tO>=i&&(await iG(e,s),tO=Date.now()/6e4)},_ue).unref()}catch(e){ko.error(e)}}a(aG,"logRotator");async function iG(e,t){let r=$o.get(Yl.LOGGING_ROTATION_COMPRESS),s=cue.join(t,`HDB-${new Date(Date.now()).toISOString().replaceAll(":","-")}.${r?"log.gz":"log"}`);r?(await aue(rue(e),nue(),sue(s)),await rO.unlink(e)):await rO.rename(e,s),ko.closeLogFile(),ko.notify(`hdb.log rotated, old log moved to ${s}`)}a(iG,"moveLogFile")});var _c=m((OAe,mG)=>{"use strict";var Ns=Y();Ns.initSync();var hAe=wa(),ut=R(),Yt=C(),Vo=require("fs-extra"),lc=require("path"),fue=yA(),hue=Ah(),sO=require("chalk"),mue=ki(),ts=F(),lG=et(),_G=Gi(),pue=SE(),Sue=eO(),Tue=uG(),gue=require("minimist"),{PACKAGE_ROOT:Rue}=R(),{startHTTPThreads:Aue,startSocketServer:mAe,mostIdleRouting:pAe,remoteAffinityRouting:SAe}=(Uf(),re(DR)),Oue=Rh(),{isMainThread:Nue}=require("worker_threads"),TAe=En(),gAe=Zn(),RAe=Xp(),AAe=cu(),nO=R(),Os,bue="Upgrade complete. Starting HarperDB.",yue="Got an error while trying to upgrade your HarperDB instance. Exiting HarperDB.",Iue="HarperDB not found, starting install process.",wue="There was an error during install, check install_log.log for more details. Exiting.",Cue="HarperDB successfully started.";async function dG(e=!1,t=!1){if(console.log(sO.magenta("Starting HarperDB...")),await hG()===!1){console.log(Iue);try{await hue()}catch(n){console.error(wue,n),Yt.error(n),process.exit(1)}}await Vo.writeFile(lc.join(Ns.get(nO.CONFIG_PARAMS.ROOTPATH),nO.HDB_PID_FILE),`${process.pid}`),Yt.info("HarperDB PID",process.pid),Os===void 0&&(Os=ya());let r;try{let n=await Oue.getVersionUpdateInfo();n!==void 0&&(r=n[ut.UPGRADE_JSON_FIELD_NAMES_ENUM.UPGRADE_VERSION],await Sue.upgrade(n),console.log(bue))}catch(n){r?(console.error(`Got an error while trying to upgrade your HarperDB instance to version ${r}. Exiting HarperDB.`),Yt.error(n)):(console.error(yue),Yt.error(n)),process.exit(1)}if(!e){let n=_G(Object.keys(ut.CONFIG_PARAM_MAP),!0);!ts.isEmpty(n)&&!ts.isEmptyOrZeroLength(Object.keys(n))&&lG.updateConfigValue(void 0,void 0,n,!0,!0)}fue(),Due(),ts.autoCastBoolean(Ns.get(ut.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY))&&Nue&&await pue.generateNatsConfig(t)}a(dG,"initialize");async function EG(e=!1){try{let t=gue(process.argv);t.ROOTPATH&&lG.updateConfigObject("settings_path",lc.join(t.ROOTPATH,ut.HDB_CONFIG_FILE)),await dG(e,!0);let r=ts.autoCastBoolean(Ns.get(ut.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY)),s=process.env.IS_SCRIPTED_SERVICE&&!t.service,n=r,i=ts.autoCastBoolean(Ns.get(ut.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY));if(ts.isEmpty(t.service))await Aue(Ns.get(nO.CONFIG_PARAMS.HTTP_THREADS)),n&&(s||await Os.startClusteringProcesses(),await Os.startClusteringThreads());else{if(typeof t.service!="string"){let c=`Run service argument expected a string but received: ${t.service}`;Yt.error(c),console.log(c),process.exit(1)}let o=t.service.split(",");for(let c of o){let u=c.toLowerCase();if(ut.PROCESS_DESCRIPTORS_VALIDATE[u]===void 0){Yt.error(`Run received unrecognized service command argument: ${u}`);continue}if(u===ut.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS.toLowerCase()&&!i){Yt.error(`${u} is not enabled in settings`);continue}if(u.includes("clustering")&&!r){Yt.error(`${u} is not enabled in settings`);continue}u==="clustering"?await Os.startClusteringProcesses():await Os.startService(ut.PROCESS_DESCRIPTORS_VALIDATE[u]);let l=`${ut.PROCESS_DESCRIPTORS_VALIDATE[u]} successfully started.`;Yt.notify(l),console.log(l)}}Ns.get(ut.CONFIG_PARAMS.LOGGING_ROTATION_ENABLED)&&await Tue(),s||fG()}catch(t){console.error(t),Yt.error(t),process.exit(1)}}a(EG,"main");function fG(){Yt.suppressLogging(()=>{console.log(sO.magenta(""+Vo.readFileSync(lc.join(Rue,"utility/install/ascii_logo.txt")))),console.log(sO.magenta(`|------------- HarperDB ${mue.version} successfully started ------------|`))}),Yt.notify(Cue)}a(fG,"started");async function Lue(){if(Uue())return EG();try{Os===void 0&&(Os=ya()),Os.enterPM2Mode(),await dG(),ts.autoCastBoolean(Ns.get(ut.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY))&&await Os.startClusteringProcesses(),await Os.startService(ut.PROCESS_DESCRIPTORS.HDB),fG(),process.exit(0)}catch(e){console.error(e),Yt.error(e),process.exit(1)}}a(Lue,"launch");function Due(){let e=lc.join(Ns.getHdbBasePath(),ut.LICENSE_KEY_DIR_NAME,ut.LICENSE_FILE_NAME),t=lc.join(e,ut.LICENSE_FILE_NAME),r=lc.join(e,ut.REG_KEY_FILE_NAME);try{let{HARPERDB_FINGERPRINT:s,HARPERDB_LICENSE:n}=_G(["HARPERDB_FINGERPRINT","HARPERDB_LICENSE"]);if(ts.isEmpty(s)||ts.isEmpty(n))return;Vo.mkdirpSync(e),Vo.writeFileSync(r,s),Vo.writeFileSync(t,n)}catch(s){let n=`Failed to write license & fingerprint due to: ${s.message}`;console.error(n),Yt.error(n)}}a(Due,"writeLicenseFromVars");mG.exports={launch:Lue,main:EG,isHdbInstalled:hG};async function hG(){try{await Vo.stat(ts.getPropsFilePath()),await Vo.stat(Ns.get(ut.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY))}catch(e){if(ts.noBootFile())return!0;if(e.code==="ENOENT")return!1;throw Yt.error(`Error checking for HDB install - ${e}`),e}return!0}a(hG,"isHdbInstalled");function Uue(){return ts.autoCastBoolean(Ns.get(ut.CONFIG_PARAMS.OPERATIONSAPI_FOREGROUND))}a(Uue,"getRunInForeground")});var SG=m((bAe,pG)=>{var Mue=Ah(),Pue=C();pG.exports=vue;async function vue(){try{await Mue()}catch(e){console.error("There was an error during the install."),console.error(e),Pue.error(e),process.exit(1)}}a(vue,"install")});var RG=m((IAe,gG)=>{"use strict";var Bue=_E(),Hue=C(),TG="Registration failed.";async function que(){let e;try{e=await Bue.register()}catch(t){return Hue.error(`Registration error ${t}`),TG}return e||TG}a(que,"register");gG.exports={register:que}});var bG=m((CAe,NG)=>{"use strict";var Fue=C(),Gue=R(),xue=require("util"),kue=require("child_process"),AG=xue.promisify(kue.exec),$ue=Nn(),Kl=ya(),OG="Stopping HarperDB.";NG.exports=Vue;async function Vue(){if(console.log(OG),Fue.notify(OG),await Kl.isServiceRegistered(Gue.HDB_PROC_DESCRIPTOR)){Kl.enterPM2Mode();let r=await Kl.getUniqueServicesList();for(let s in r)await Kl.stop(s)}await Kl.kill();let t=await $ue.getHDBProcessInfo();t.clustering.forEach(r=>{AG(`kill ${r.pid}`)}),t.core.forEach(r=>{AG(`kill ${r.pid}`)})}a(Vue,"stop")});var LG=m((DAe,CG)=>{"use strict";var iO=require("fs-extra"),oO=require("path"),Yue=require("yaml"),Wl=Qe(),Ql=R(),yG=Me(),IG=C(),Kue=er(),Wue=aE(),Que=iE(),zue=Nn(),wG=Y();wG.initSync();var sn={RUNNING:"running",STOPPED:"stopped",ERRORED:"errored"},Sr={LEAF:"leaf server",HUB:"hub server"},bh;CG.exports=Jue;async function Jue(){bh=wG.get(Ql.CONFIG_PARAMS.ROOTPATH);let e={harperdb:{status:sn.STOPPED}},t;try{t=Number.parseInt(await iO.readFile(oO.join(bh,Ql.HDB_PID_FILE),"utf8"))}catch(s){throw s.code===Ql.NODE_ERROR_CODES.ENOENT?new Error("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB"):s}let r=await zue.getHDBProcessInfo();for(let s of r.core)if(s.pid===t){e.harperdb.status=sn.RUNNING,e.harperdb.pid=t;break}if(e.clustering=await jue(r),e.clustering[Sr.HUB].status===sn.RUNNING&&e.clustering[Sr.LEAF].status===sn.RUNNING){let s=[],n=await Wue({});for(let o of n.nodes){let c={};for(let u in o)c[u.replace("_"," ")]=o[u];s.push(c)}e.clustering.network=s;let i=await Que.clusterStatus();e.clustering.replication={"node name":i.node_name,"is enabled":i.is_enabled,connections:[]};for(let o of i.connections){let c={};c["node name"]=o?.node_name,c.status=o?.status,c.ports={clustering:o?.ports?.clustering,"operations api":o?.ports?.operations_api},c["latency ms"]=o?.latency_ms,c.uptime=o?.uptime,c.subscriptions=o?.subscriptions,c["system info"]={"hdb version":o?.system_info?.hdb_version,"node version":o?.system_info?.node_version,platform:o?.system_info?.platform},e.clustering.replication.connections.push(c)}await Wl.closeConnection()}console.log(Yue.stringify(e)),process.exit()}a(Jue,"status");async function jue(e){let t={[Sr.HUB]:{},[Sr.LEAF]:{}};if(e.clustering.length===0)return t[Sr.HUB].status=sn.STOPPED,t[Sr.LEAF].status=sn.STOPPED,t;let{port:r}=Wl.getServerConfig(Ql.PROCESS_DESCRIPTORS.CLUSTERING_HUB),{username:s,decrypt_hash:n}=await Kue.getClusterUser();try{(await Wl.createConnection(r,s,n,!1)).close(),t[Sr.HUB].status=sn.RUNNING}catch{t[Sr.HUB].status=sn.ERRORED}let{port:i}=Wl.getServerConfig(Ql.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);try{(await Wl.createConnection(i,s,n,!1)).close(),t[Sr.LEAF].status=sn.RUNNING}catch{t[Sr.LEAF].status=sn.ERRORED}try{t[Sr.HUB].pid=Number.parseInt(await iO.readFile(oO.join(bh,"clustering",yG.PID_FILES.HUB),"utf8"))}catch(o){IG.error(o),t[Sr.HUB].pid=void 0}try{t[Sr.LEAF].pid=Number.parseInt(await iO.readFile(oO.join(bh,"clustering",yG.PID_FILES.LEAF),"utf8"))}catch(o){IG.error(o),t[Sr.LEAF].pid=void 0}return t}a(jue,"getHubLeafStatus")});var HG=m(()=>{"use strict";var Xue=require("os"),wh=require("https"),qi=require("fs-extra"),Zue=require("yaml"),ele=require("human-readable-ids").hri,{pipeline:DG}=require("stream/promises"),{createWriteStream:Ch,ensureDir:Lh}=require("fs-extra"),{join:nn}=require("path"),uO=require("lodash"),tle=Y(),rle=Nn(),vG=C(),yh=et(),{restart:sle}=wa(),BG=F(),UG=Qe(),nle=$r(),{isHdbInstalled:ile,main:ole}=_c(),ale=Ah(),lO=R(),{SYSTEM_TABLE_NAMES:MG,SYSTEM_SCHEMA_NAME:cle,CONFIG_PARAMS:zl,OPERATIONS_ENUM:Hr}=lO,ule=9925,lle="info",_le=1e4,dle="clone-node-config.yaml",_O=[MG.ROLE_TABLE_NAME,MG.USER_TABLE_NAME],Jl=process.env.HDB_LEADER_USERNAME,jl=process.env.HDB_LEADER_PASSWORD,Xl=process.env.HDB_LEADER_URL,aO=process.env.HDB_LEADER_CLUSTERING_HOST,Ele=process.env.HDB_LEADER_CLUSTERING_PORT,cO,ye,lt,je,dO,dc;async function fle(){if(await ile())throw new Error("Existing install of HarperDB found on clone node.");if(console.info("Cloning node: "+Xl),ye?.rootPath)dc=ye.rootPath;else try{dc=process.env.ROOTPATH?process.env.ROOTPATH:nn(Xue.homedir(),lO.HDB_ROOT_DIR_NAME)}catch(t){throw console.error(t),new Error("There was an setting default rootPath. Please set 'rootPath' in clone-node-config.yaml")}let e;try{e=nn(dc,dle),ye=Zue.parseDocument(qi.readFileSync(e,"utf8"),{simpleKeys:!0}).toJSON()}catch{console.info(e+" not found, using default config values.")}dO=ye?.clustering?.nodeName??ele.random(),lt=await Dh({operation:Hr.GET_CONFIGURATION}),lt=await JSON.parse(lt.body),global.fetch?(await Sle(),process.env.NODE_TLS_REJECT_UNAUTHORIZED&&delete process.env.NODE_TLS_REJECT_UNAUTHORIZED):await ple(),await mle(),await hle(),await Tle(),await gle(),console.info("Successfully cloned node: "+Xl)}a(fle,"cloneNode");async function hle(){console.info("Cloning configuration"),cO=lt?.clustering?.enabled;let e={[zl.ROOTPATH]:dc};if(cO&&ye?.clustering?.enabled!==!1){if(aO==null)throw new Error("'HDB_LEADER_CLUSTERING_HOST' must be defined");e[zl.CLUSTERING_ENABLED]=!0;let s=lt?.clustering?.hubServer?.cluster?.network?.routes,n=parseInt(Ele)||lt?.clustering?.hubServer?.cluster?.network?.port;e[zl.CLUSTERING_USER]=lt?.clustering?.user;let i=tle.get(zl.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES);Array.isArray(i)?i.push({host:aO,port:n}):i=[{host:aO,port:n}],Array.isArray(s)&&i.concat(s),e[zl.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES]=i}let t=ye?.componentConfig?.exclude;t=t?t.reduce((s,n)=>({...s,[n.name]:!0}),{}):[];for(let s in lt)lt[s]?.package&&!t[s]&&await yh.addConfig(s,lt[s]);ye?.databases&&await yh.addConfig("databases",lt?.schemas);let r=yh.flattenConfig(ye);for(let s in r){let n=lO.CONFIG_PARAM_MAP[s.toLowerCase()];n&&(e[n]=r[s])}e.rootPath==null&&delete e.rootPath,e?.clustering_nodeName==null&&(e.clustering_nodeName=dO),vG.info("Cloning config:",e),uO.isEmpty(e)||await yh.updateConfigValue(void 0,void 0,e,!1,!0)}a(hle,"cloneConfig");async function mle(){if(console.info("Clone node installing HarperDB."),process.env.TC_AGREEMENT="yes",process.env.ROOTPATH=dc,!Jl)throw new Error("HDB_LEADER_USERNAME is undefined.");if(process.env.HDB_ADMIN_USERNAME=Jl,!jl)throw new Error("HDB_LEADER_PASSWORD is undefined.");process.env.HDB_ADMIN_PASSWORD=jl,process.env.OPERATIONSAPI_NETWORK_PORT=ye?.operationsApi?.network?.port??ule,process.env.CLUSTERING_NODENAME=dO,process.env.CLUSTERING_LOGLEVEL=ye?.clustering?.logLevel??lle,await ale()}a(mle,"installHDB");async function ple(){console.info("Cloning system database");let e=Ec("system");await Lh(e);let t=nn(e,"system.mdb"),r=Ch(t,{overwrite:!0}),s=await PG({operation:Hr.GET_BACKUP,database:"system",tables:_O},r);await qi.utimes(t,Date.now(),new Date(s.date)),je=await Dh({operation:Hr.DESCRIBE_ALL}),je=await JSON.parse(je.body);let n=ye?.databaseConfig?.excludeDatabases;if(n=n?n.reduce((o,c)=>({...o,[c.database]:!0}),{}):{},lt.schemas)for(let o in lt.schemas)Object.keys(lt.schemas[o]).includes("tables")&&(n[o]=!0,console.info(`Excluding database '${o}' from clone because leader node has custom pathing configured for one or more of its tables`));let i=ye?.databaseConfig?.excludeTables;i=i?i.reduce((o,c)=>({...o,[c.database==null?null:c.database+c.table]:!0}),{}):{};for(let o in je){if(n[o]){je[o]="excluded";continue}if(uO.isEmpty(je[o]))continue;let c=[],u=!1;for(let h in je[o])i[o+h]?(u=!0,je[o][h]="excluded"):c.push(h);let l;u?(console.info(`Cloning database: ${o} tables: ${c}`),l={operation:Hr.GET_BACKUP,database:o,tables:c}):(console.info(`Cloning database: ${o}`),l={operation:Hr.GET_BACKUP,database:o});let _=Ec(o);await Lh(_);let d=nn(_,o+".mdb"),E=Ch(d,{overwrite:!0}),f=await PG(l,E);await qi.utimes(d,Date.now(),new Date(f.date))}}a(ple,"cloneTables");async function Sle(){console.info("Cloning system database");let e=await Ih({operation:Hr.GET_BACKUP,database:"system",tables:_O},!0),t=Ec("system");await Lh(t);let r=nn(t,"system.mdb");await DG(e.body,Ch(r,{overwrite:!0})),await qi.utimes(r,Date.now(),new Date(e.headers.get("date"))),je=await Ih({operation:Hr.DESCRIBE_ALL}),je=await je.json();let s=ye?.databaseConfig?.excludeDatabases;if(s=s?s.reduce((i,o)=>({...i,[o.database]:!0}),{}):{},lt.schemas)for(let i in lt.schemas)Object.keys(lt.schemas[i]).includes("tables")&&(s[i]=!0,console.info(`Excluding database '${i}' from clone because leader node has custom pathing configured for one or more of its tables`));let n=ye?.databaseConfig?.excludeTables;n=n?n.reduce((i,o)=>({...i,[o.database==null?null:o.database+o.table]:!0}),{}):{};for(let i in je){if(s[i]){je[i]="excluded";continue}if(uO.isEmpty(je[i]))continue;let o=[],c=!1;for(let f in je[i])n[i+f]?(c=!0,je[i][f]="excluded"):o.push(f);let u;c?(console.info(`Cloning database: ${i} tables: ${o}`),u=await Ih({operation:Hr.GET_BACKUP,database:i,tables:o},!0)):(console.info(`Cloning database: ${i}`),u=await Ih({operation:Hr.GET_BACKUP,database:i},!0));let l=Ec(i);await Lh(l);let _=new Date(u.headers.get("date")),d=nn(l,`${_.getTime()}-${i}.mdb`);await DG(u.body,Ch(d,{overwrite:!0}));let E=nn(l,i+".mdb");await qi.rename(d,E),await qi.utimes(E,Date.now(),_)}}a(Sle,"cloneTablesFetch");async function Ih(e,t=!1){let r=ye?.httpsRejectUnauthorized??!1,s=new wh.Agent({rejectUnauthorized:r});r||(process.env.NODE_TLS_REJECT_UNAUTHORIZED="0");let i={Authorization:"Basic "+Buffer.from(Jl+":"+jl).toString("base64"),"Content-Type":"application/json"};t&&(i["Accept-Encoding"]="gzip");let o=await fetch(Xl,{method:"POST",headers:i,body:JSON.stringify(e),agent:s,compress:!0});if(o.ok)return o;throw console.error(`HTTP Error Response: ${o.status} ${o.statusText}`),new Error(await o.text())}a(Ih,"leaderHttpReqFetch");function Ec(e){return ye?.databases&&ye?.databases[e]?.path||ye?.storage&&ye?.storage?.path||nn(dc,"database")}a(Ec,"getDbFileDir");async function Tle(){let{deployComponent:e}=PE(),t=await Dh({operation:Hr.GET_COMPONENTS});t=await JSON.parse(t.body);let r=[];if(t.entries.length){for(let n of t.entries){if(!n.entries)continue;let i=!1;if(ye?.componentConfig?.exclude){for(let o of ye.componentConfig.exclude)if(o?.name!=null&&o.name===n.name){i=!0;break}}i||r.push(n.name)}let s=ye?.componentConfig?.skipNodeModules!==!1;for(let n of r){console.info("Cloning component: "+n);let i=await Dh({operation:Hr.PACKAGE_COMPONENT,project:n,skip_node_modules:s}),{payload:o}=await JSON.parse(i.body);await e({payload:o,project:n})}}}a(Tle,"cloneComponents");async function gle(){if(!cO)return;let e=await rle.getHDBProcessInfo();e.clustering.length===0||e.core.length===0?await ole():(console.info(await sle({operation:Hr.RESTART})),await BG.async_set_timeout(_le)),console.info("Clustering cloned tables");let t=ye?.clusteringConfig?.subscribeToLeaderNode!==!1,r=ye?.clusteringConfig?.publishToLeaderNode!==!1;await nle.setSchemaDataToGlobalAsync();let s=Du(),n=[],i=await qi.stat(nn(Ec("system"),"system.mdb"));for(let o of _O)n.push({schema:cle,table:o,subscribe:t,publish:r,start_time:i.mtime.toISOString()});for(let o in je){if(je[o]==="excluded")continue;let c=await qi.stat(nn(Ec(o),o+".mdb"));for(let u in je[o])je[o][u]!=="excluded"&&n.push({schema:o,table:u,subscribe:t,publish:r,start_time:c.mtime.toISOString()})}await UG.createTableStreams(n),vG.info("Sending add_node request to node:",lt?.clustering?.nodeName,"with subscriptions:",n),await s({operation:Hr.ADD_NODE,node_name:lt?.clustering?.nodeName,subscriptions:n},!0),await UG.closeConnection()}a(gle,"clusterTables");async function Dh(e){let t=new wh.Agent({rejectUnauthorized:ye?.httpsRejectUnauthorized??!1}),s={Authorization:"Basic "+Buffer.from(Jl+":"+jl).toString("base64"),"Content-Type":"application/json"},n=new URL(Xl),i={protocol:n.protocol,host:n.hostname,method:"POST",headers:s};return n.protocol==="https:"&&(i.agent=t),n.port&&(i.port=n.port),await BG.httpRequest(i,e)}a(Dh,"leaderHttpReq");async function PG(e,t){let r=new wh.Agent({rejectUnauthorized:ye?.httpsRejectUnauthorized??!1}),n={Authorization:"Basic "+Buffer.from(Jl+":"+jl).toString("base64"),"Content-Type":"application/json"},i=new URL(Xl),o={protocol:i.protocol,host:i.hostname,method:"POST",headers:n};return i.protocol==="https:"&&(o.agent=r),i.port&&(o.port=i.port),new Promise((c,u)=>{let l=wh.request(o,_=>{_.pipe(t),_.on("end",()=>{t.close(),c(_.headers)})});l.on("error",_=>{u(_)}),l.write(JSON.stringify(e)),l.end()})}a(PG,"leaderHttpStream");fle().then().catch(e=>{console.log(e)})});var fc=C(),Rle=$i(),EO=R(),Uh=require("fs"),qG=require("path"),BAe=require("os"),{PACKAGE_ROOT:Ale}=R(),Ole=jO(),HAe=Y(),Nle=(Uf(),re(DR)),{SERVICE_ACTIONS_ENUM:bs}=EO;ble();function ble(){let e=Ole();if(e)if(e.error){console.error(e.error),fc.error(e.error);return}else e.warn&&(console.warn(e.warn),fc.warn(e.warn));let t;Uh.readdir(qG.join(Ale,"bin"),r=>{if(r)return fc.error(r);process.argv&&process.argv[2]&&!process.argv[2].startsWith("-")&&(t=process.argv[2].toLowerCase());let s;switch(t){case bs.DEBUG:require("inspector").open(9229),Nle.debugMode=!0;case bs.RUN:let n=process.argv[3];n&&n[0]!=="-"&&(Uh.existsSync(n)||(console.error(`The folder ${n} does not exist`),process.exit(1)),Uh.statSync(n).isDirectory()||(console.error(`The path ${n} is not a folder`),process.exit(1)),Uh.existsSync(qG.join(n,EO.HDB_CONFIG_FILE))?process.env.ROOTPATH=n:process.env.RUN_HDB_APP=n),_c().main();break;case bs.START:s=_c().launch();break;case bs.INSTALL:SG()().then(()=>_c().main(!0)).catch(E=>{console.error(E)});break;case bs.REGISTER:RG().register().then(E=>{console.log(E)}).catch(E=>{console.error(E)});break;case bs.STOP:bG()().then(()=>{process.exit(0)}).catch(E=>{console.error(E)});break;case bs.RESTART:wa().restart({}).then().catch(E=>{fc.error(E),console.error(`There was an error restarting harperdb. ${E}`),process.exit(1)});break;case bs.VERSION:Rle.printVersion();break;case bs.UPGRADE:fc.setLogLevel(EO.LOG_LEVELS.INFO),eO().upgrade(null).then(()=>{console.log("Your instance of HDB is up to date!")}).catch(E=>{fc.error(`Got an error during upgrade ${E}`)});break;case bs.STATUS:LG()().then().catch(E=>{console.error(E)});break;case void 0:process.env.HDB_LEADER_URL?HG():_c().main();break;default:console.warn(`The "${t}" command is not understood.`);case bs.HELP:console.log(`
|
|
106
106
|
Usage: harperdb [command]
|
|
107
107
|
|
|
108
108
|
With no command, harperdb will simply run HarperDB (in the foreground)
|