harperdb 4.0.4 → 4.0.5

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.
@@ -1,14 +1,14 @@
1
- "use strict";var qb=Object.defineProperty;var a=(e,t)=>qb(e,"name",{value:t,configurable:!0});var h=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var eh=h((PJ,jd)=>{var Gb=require("fastify-plugin");jd.exports=Gb(function(e,t,r){e.addHook("onResponse",async(s,n)=>{n.getResponseTime()}),e.addHook("onSend",async(s,n)=>{let i=n.getResponseTime().toFixed(3);n.header("HDB-Response-Time",i),n.header("Server-Timing",`db;dur=${i}`)}),r()},{name:"hdb-request-time"})});var T=h((BJ,dh)=>{"use strict";var Ye=require("path"),Fb=require("fs");function Vb(){let e=__dirname;for(;!Fb.existsSync(Ye.join(e,"package.json"));){let t=Ye.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(Vb,"getHDBPackageRoot");var Gt=Vb(),th="js",$n=th,kb="harperdb-config.yaml",xb="defaultConfig.yaml",$b="hdb",rh=`hdbServer.${$n}`,sh=`customFunctionsServer.${$n}`,nh=`hdbIpcServer.${$n}`,Yb=`restartHdb.${$n}`,eu="HarperDB",Sa="Custom Functions",fa="Clustering Hub",Ta="Clustering Leaf",tu="Clustering Ingest Service",ru="Clustering Reply Service",Kb="foreground.pid",j_={HDB:eu,IPC:"IPC",CLUSTERING_HUB:fa,CLUSTERING_LEAF:Ta,CLUSTERING_INGEST_SERVICE:tu,CLUSTERING_REPLY_SERVICE:ru,CUSTOM_FUNCTIONS:Sa,RESTART_HDB:"Restart HDB",INSTALL:"Install",RUN:"Run",STOP:"Stop",UPGRADE:"Upgrade",REGISTER:"Register",JOB:"Job",PM2_LOGROTATE:"pm2-logrotate",CLUSTERING_UPGRADE_4_0_0:"Upgrade-4-0-0"},Qb={HDB:"hdb.log",IPC:"ipc.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log",CLUSTERING_INGEST_SERVICE:"clustering_ingest_service.log",CLUSTERING_REPLY_SERVICE:"clustering_reply_service.log",CUSTOM_FUNCTIONS:"custom_functions.log",INSTALL:"install.log",CLI:"cli.log",PM2:"pm2.log",CLUSTERING_UPGRADE:"clustering_upgrade.log",JOBS:"jobs.log"},Wb={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},Jb={harperdb:eu,ipc:"IPC","clustering hub":fa,"clustering leaf":Ta,"clustering ingest service":tu,"clustering reply service":ru,"custom functions":Sa,custom_functions:Sa,"pm2-logrotate":j_.PM2_LOGROTATE,logrotate:j_.PM2_LOGROTATE,clustering:"clustering","clustering config":"clustering config"},Zb={CLUSTERING_HUB_PROC_DESCRIPTOR:fa,CLUSTERING_LEAF_PROC_DESCRIPTOR:Ta,CLUSTERING_INGEST_PROC_DESCRIPTOR:tu,CLUSTERING_REPLY_SERVICE_DESCRIPTOR:ru},ha={HDB:Ye.join(Gt,"server/harperdb"),IPC:Ye.join(Gt,"server/ipc"),CUSTOM_FUNCTIONS:Ye.join(Gt,"server/customFunctions"),CLUSTERING_HUB:Ye.join(Gt,"server/nats"),CLUSTERING_LEAF:Ye.join(Gt,"server/nats")},Xb={HDB:Ye.join(ha.HDB,rh),IPC:Ye.join(ha.IPC,nh),CUSTOM_FUNCTIONS:Ye.join(ha.CUSTOM_FUNCTIONS,sh)},zb={HDB:Ye.join(Gt,"launchServiceScripts/launchHarperDB.js"),CUSTOM_FUNCTIONS:Ye.join(Gt,"launchServiceScripts/launchCustomFunctions.js"),NATS_INGEST_SERVICE:Ye.join(Gt,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:Ye.join(Gt,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:Ye.resolve(Gt,"launchServiceScripts/launchUpdateNodes4-0-0.js")},jb={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},ih="support@harperdb.io",eC="customer-success@harperdb.io",ah=1,tC=4141,oh="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",rC="https://www.harperdb.io/product",sC=`For support, please submit a request at ${oh} or contact ${ih}`,ch=`For license support, please contact ${eC}`,nC="None of the specified records were found.",iC="hash attribute not found",aC=`Your current license only supports ${ah} role. ${ch}`,oC="Your current license only supports 3 connections to a node.",cC="127.0.0.1",_C=1,uC=/^\.$/,lC=/^\.\.$/,EC="U+002E",dC=/\//g,hC="U+002F",SC=/U\+002F/g,fC=/^U\+002E$/,TC=/^U\+002EU\+002E$/,mC="d",RC=999999,AC="*",pC="--max-old-space-size=",OC="system",NC="__hdb_hash",gC=".harperdb",IC=".hdb",bC="keys",CC="hdb_boot_properties.file",wC=".updateConfig.json",UC="SIGTSTP",LC=24,yC=6e4,DC=448,MC="blob",PC="trash",BC="schema",vC="transactions",HC=".count",qC="id",GC="install_log.log",FC="run_log.log",VC="PROCESS_NAME",kC={SETTINGS_PATH_KEY:"settings_path"},_h=require("lodash"),xC={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"},$C={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},YC={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},KC={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"},QC={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"},ht="hdb_internal:",WC={CREATE_SCHEMA:ht+"create_schema",CREATE_TABLE:ht+"create_table",CREATE_ATTRIBUTE:ht+"create_attribute",ADD_USER:ht+"add_user",ALTER_USER:ht+"alter_user",DROP_USER:ht+"drop_user",HDB_NODES:ht+"hdb_nodes",HDB_USERS:ht+"hdb_users",HDB_WORKERS:ht+"hdb_workers",CATCHUP:ht+"catchup",SCHEMA_CATCHUP:ht+"schema_catchup",WORKER_ROOM:ht+"cluster_workers"},JC={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"},ZC="060493.ks",XC=".license",zC={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},I={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",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_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",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",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",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",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",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"},jC={CSV:".csv",JSON:".json"},ew={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key"},tw={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Br={};Br[I.CREATE_SCHEMA]=I.CREATE_SCHEMA;Br[I.CREATE_TABLE]=I.CREATE_TABLE;Br[I.CREATE_ATTRIBUTE]=I.CREATE_ATTRIBUTE;Br[I.INSERT]=I.INSERT;Br[I.UPDATE]=I.UPDATE;Br[I.UPSERT]=I.UPSERT;Br[I.DELETE]=I.DELETE;var Z=Object.create(null);Z[I.DESCRIBE_ALL]=I.DESCRIBE_ALL;Z[I.DESCRIBE_TABLE]=I.DESCRIBE_TABLE;Z[I.DESCRIBE_SCHEMA]=I.DESCRIBE_SCHEMA;Z[I.READ_LOG]=I.READ_LOG;Z[I.ADD_NODE]=I.ADD_NODE;Z[I.LIST_USERS]=I.LIST_USERS;Z[I.LIST_ROLES]=I.LIST_ROLES;Z[I.USER_INFO]=I.USER_INFO;Z[I.SQL]=I.SQL;Z[I.GET_JOB]=I.GET_JOB;Z[I.SEARCH_JOBS_BY_START_DATE]=I.SEARCH_JOBS_BY_START_DATE;Z[I.DELETE_FILES_BEFORE]=I.DELETE_FILES_BEFORE;Z[I.EXPORT_LOCAL]=I.EXPORT_LOCAL;Z[I.EXPORT_TO_S3]=I.EXPORT_TO_S3;Z[I.CLUSTER_STATUS]=I.CLUSTER_STATUS;Z[I.REMOVE_NODE]=I.REMOVE_NODE;Z[I.RESTART]=I.RESTART;Z[I.CUSTOM_FUNCTIONS_STATUS]=I.CUSTOM_FUNCTIONS_STATUS;Z[I.GET_CUSTOM_FUNCTIONS]=I.GET_CUSTOM_FUNCTIONS;Z[I.GET_CUSTOM_FUNCTION]=I.GET_CUSTOM_FUNCTION;Z[I.SET_CUSTOM_FUNCTION]=I.SET_CUSTOM_FUNCTION;Z[I.DROP_CUSTOM_FUNCTION]=I.DROP_CUSTOM_FUNCTION;Z[I.ADD_CUSTOM_FUNCTION_PROJECT]=I.ADD_CUSTOM_FUNCTION_PROJECT;Z[I.DROP_CUSTOM_FUNCTION_PROJECT]=I.DROP_CUSTOM_FUNCTION_PROJECT;Z[I.PACKAGE_CUSTOM_FUNCTION_PROJECT]=I.PACKAGE_CUSTOM_FUNCTION_PROJECT;Z[I.DEPLOY_CUSTOM_FUNCTION_PROJECT]=I.DEPLOY_CUSTOM_FUNCTION_PROJECT;var rw={RUN:"run",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade"},sw={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},uh={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",IPC_SERVER_PORT:"IPC_SERVER_PORT",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"},nw=_h.invert(uh),f={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_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",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",IPC_NETWORK_PORT:"ipc_network_port",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_ROTATION_COMPRESS:"logging_rotation_compress",LOGGING_ROTATION_DATEFORMAT:"logging_rotation_dateFormat",LOGGING_ROTATION_MAXSIZE:"logging_rotation_maxSize",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",LOGGING_STDSTREAMS:"logging_stdStreams",LOGGING_AUDITLOG:"logging_auditLog",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"},iw={hdb_root_key:f.ROOTPATH,hdb_root:f.ROOTPATH,server_port_key:f.OPERATIONSAPI_NETWORK_PORT,server_port:f.OPERATIONSAPI_NETWORK_PORT,cert_key:f.OPERATIONSAPI_TLS_CERTIFICATE,certificate:f.OPERATIONSAPI_TLS_CERTIFICATE,private_key_key:f.OPERATIONSAPI_TLS_PRIVATEKEY,private_key:f.OPERATIONSAPI_TLS_PRIVATEKEY,http_secure_enabled_key:f.OPERATIONSAPI_NETWORK_HTTPS,https_on:f.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:f.OPERATIONSAPI_NETWORK_CORS,cors_on:f.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:f.LOGGING_LEVEL,log_level:f.LOGGING_LEVEL,log_path_key:f.LOGGING_ROOT,log_path:f.LOGGING_ROOT,log_daily_rotate:f.LOGGING_ROTATION_ROTATE,log_rotate:f.LOGGING_ROTATION_ROTATE,log_rotate_max_size:f.LOGGING_ROTATION_MAXSIZE,log_rotate_retain:f.LOGGING_ROTATION_RETAIN,log_rotate_compress:f.LOGGING_ROTATION_COMPRESS,log_rotate_date_format:f.LOGGING_ROTATION_DATEFORMAT,log_rotate_rotate_module:f.LOGGING_ROTATION_ROTATEMODULE,log_rotate_worker_interval:f.LOGGING_ROTATION_WORKERINTERVAL,log_rotate_rotate_interval:f.LOGGING_ROTATION_ROTATEINTERVAL,log_rotate_timezone:f.LOGGING_ROTATION_TIMEZONE,props_env_key:f.OPERATIONSAPI_NODEENV,node_env:f.OPERATIONSAPI_NODEENV,clustering_node_name_key:f.CLUSTERING_NODENAME,node_name:f.CLUSTERING_NODENAME,clustering_enabled_key:f.CLUSTERING_ENABLED,clustering:f.CLUSTERING_ENABLED,max_http_threads:f.HTTP_THREADS,max_hdb_processes:f.HTTP_THREADS,server_timeout_key:f.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:f.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:f.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:f.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:f.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:f.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:f.LOGGING_AUDITLOG,disable_transaction_log:f.LOGGING_AUDITLOG,operation_token_timeout_key:f.OPERATIONSAPI_AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:f.OPERATIONSAPI_AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:f.OPERATIONSAPI_AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:f.OPERATIONSAPI_AUTHENTICATION_REFRESHTOKENTIMEOUT,ipc_server_port:f.IPC_NETWORK_PORT,custom_functions_enabled_key:f.CUSTOMFUNCTIONS_ENABLED,custom_functions:f.CUSTOMFUNCTIONS_ENABLED,custom_functions_port_key:f.CUSTOMFUNCTIONS_NETWORK_PORT,custom_functions_port:f.CUSTOMFUNCTIONS_NETWORK_PORT,custom_functions_directory_key:f.CUSTOMFUNCTIONS_ROOT,custom_functions_directory:f.CUSTOMFUNCTIONS_ROOT,max_custom_function_processes:f.HTTP_THREADS,log_to_file:f.LOGGING_FILE,log_to_stdstreams:f.LOGGING_STDSTREAMS,run_in_foreground:f.OPERATIONSAPI_FOREGROUND,local_studio_on:f.LOCALSTUDIO_ENABLED,clustering_port:f.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:f.CLUSTERING_USER,clustering_enabled:f.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:f.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:f.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:f.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:f.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:f.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:f.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:f.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_nodename:f.CLUSTERING_NODENAME,clustering_tls_certificate:f.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:f.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:f.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:f.CLUSTERING_TLS_INSECURE,customfunctions_enabled:f.CUSTOMFUNCTIONS_ENABLED,customfunctions_network_port:f.CUSTOMFUNCTIONS_NETWORK_PORT,customfunctions_tls_certificate:f.CUSTOMFUNCTIONS_TLS_CERTIFICATE,customfunctions_network_cors:f.CUSTOMFUNCTIONS_NETWORK_CORS,customfunctions_network_corsaccesslist:f.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,customfunctions_network_headerstimeout:f.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,customfunctions_network_https:f.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:f.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:f.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:f.CUSTOMFUNCTIONS_TLS_CERT_AUTH,customfunctions_network_timeout:f.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,customfunctions_nodeenv:f.CUSTOMFUNCTIONS_NODEENV,http_threads:f.HTTP_THREADS,customfunctions_processes:f.HTTP_THREADS,customfunctions_root:f.CUSTOMFUNCTIONS_ROOT,ipc_network_port:f.IPC_NETWORK_PORT,localstudio_enabled:f.LOCALSTUDIO_ENABLED,logging_file:f.LOGGING_FILE,logging_level:f.LOGGING_LEVEL,logging_root:f.LOGGING_ROOT,logging_rotation_compress:f.LOGGING_ROTATION_COMPRESS,logging_rotation_dateformat:f.LOGGING_ROTATION_DATEFORMAT,logging_rotation_maxsize:f.LOGGING_ROTATION_MAXSIZE,logging_rotation_retain:f.LOGGING_ROTATION_RETAIN,logging_rotation_rotate:f.LOGGING_ROTATION_ROTATE,logging_rotation_rotateinterval:f.LOGGING_ROTATION_ROTATEINTERVAL,logging_rotation_rotatemodule:f.LOGGING_ROTATION_ROTATEMODULE,logging_rotation_timezone:f.LOGGING_ROTATION_TIMEZONE,logging_rotation_workerinterval:f.LOGGING_ROTATION_WORKERINTERVAL,logging_stdstreams:f.LOGGING_STDSTREAMS,logging_auditlog:f.LOGGING_AUDITLOG,operationsapi_authentication_operationtokentimeout:f.OPERATIONSAPI_AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:f.OPERATIONSAPI_AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_foreground:f.OPERATIONSAPI_FOREGROUND,operationsapi_tls_certificate:f.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_network_cors:f.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:f.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:f.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:f.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:f.OPERATIONSAPI_NETWORK_PORT,operationsapi_tls_privatekey:f.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_network_timeout:f.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_nodeenv:f.OPERATIONSAPI_NODEENV,operationsapi_root:f.ROOTPATH,rootpath:f.ROOTPATH,storage_writeasync:f.STORAGE_WRITEASYNC,storage_overlappingsync:f.STORAGE_OVERLAPPINGSYNC},aw={csv_file_load:"csv_file_load",csv_data_load:I.CSV_DATA_LOAD,csv_url_load:I.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"},ow={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"},cw={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},_w={FILE_SYSTEM:"fs",LMDB:"lmdb"},uw={API_CALL_DEFAULT:1e4,VERSION_DEFAULT:"2.2.0"},lw={DEVELOPMENT:8192,DEFAULT:512},Ew={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"},dw={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"},hw={ENOENT:"ENOENT",EACCES:"EACCES"},lh={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},Sw="__clustering__",fw=Object.values(lh),Tw=15984864e5,Eh={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},mw=_h.invert(Eh),Rw={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"},Aw=111,pw=`\r
2
- `,Ow={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Nw=["*","%"],gw="unauthorized_access",Iw="func_val",bw={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},Cw={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},ww="hdb_ipc_server",Uw="hdb_ipc_client_",Lw={RESTART:"restart",CHILD_STARTED:"child_started",CHILD_STOPPED:"child_stopped",SCHEMA:"schema",USER:"user",CLUSTER_STATUS_RESPONSE:"cluster_status_response",CLUSTER_STATUS_REQUEST:"cluster_status_request"},yw={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},Dw={STOPPED:"stopped",ONLINE:"online"},Mw="3.x.x";dh.exports={LOCAL_HARPERDB_OPERATIONS:Z,HDB_SUPPORT_ADDRESS:ih,HDB_SUPPORT_URL:oh,HDB_PRICING_URL:rC,SUPPORT_HELP_MSG:sC,LICENSE_HELP_MSG:ch,HDB_PROC_NAME:rh,HDB_PROC_DESCRIPTOR:eu,CLUSTERING_LEAF_PROC_DESCRIPTOR:Ta,CLUSTERING_HUB_PROC_DESCRIPTOR:fa,SYSTEM_SCHEMA_NAME:OC,HASH_FOLDER_NAME:NC,HDB_HOME_DIR_NAME:gC,UPDATE_FILE_NAME:wC,LICENSE_KEY_DIR_NAME:bC,BOOT_PROPS_FILE_NAME:CC,JOB_TYPE_ENUM:aw,JOB_STATUS_ENUM:zC,SYSTEM_TABLE_NAMES:KC,SYSTEM_TABLE_HASH_ATTRIBUTES:QC,OPERATIONS_ENUM:I,VALID_S3_FILE_TYPES:jC,S3_BUCKET_AUTH_KEYS:ew,VALID_SQL_OPS_ENUM:tw,GEO_CONVERSION_ENUM:sw,HDB_SETTINGS_NAMES:uh,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:nw,SERVICE_ACTIONS_ENUM:rw,CLUSTER_MESSAGE_TYPE_ENUM:ow,CLUSTER_CONNECTION_DIRECTION_ENUM:cw,CLUSTER_EVENTS_DEFS_ENUM:Ew,PERIOD_REGEX:uC,DOUBLE_PERIOD_REGEX:lC,UNICODE_PERIOD:EC,FORWARD_SLASH_REGEX:dC,UNICODE_FORWARD_SLASH:hC,ESCAPED_FORWARD_SLASH_REGEX:SC,ESCAPED_PERIOD_REGEX:fC,ESCAPED_DOUBLE_PERIOD_REGEX:TC,REG_KEY_FILE_NAME:ZC,RESTART_TIMEOUT_MS:yC,HDB_FILE_PERMISSIONS:DC,SCHEMA_DIR_NAME:BC,TRANSACTIONS_DIR_NAME:vC,LIMIT_COUNT_NAME:HC,ID_ATTRIBUTE_STRING:qC,INSERT_MODULE_ENUM:$C,UPGRADE_JSON_FIELD_NAMES_ENUM:YC,RESTART_CODE:UC,RESTART_CODE_NUM:LC,CLUSTER_OPERATIONS:Br,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:JC,HDB_INTERNAL_SC_CHANNEL_PREFIX:ht,INTERNAL_SC_CHANNELS:WC,CLUSTERING_MESSAGE_TYPES:Rw,HDB_FILE_SUFFIX:IC,BLOB_FOLDER_NAME:MC,HDB_TRASH_DIR:PC,ORIGINATOR_SET_VALUE:Aw,LICENSE_VALUES:uw,RAM_ALLOCATION_ENUM:lw,STORAGE_TYPES_ENUM:_w,TIME_STAMP_NAMES_ENUM:lh,TIME_STAMP_NAMES:fw,PERMS_UPDATE_RELEASE_TIMESTAMP:Tw,SEARCH_NOT_FOUND_MESSAGE:nC,SEARCH_ATTRIBUTE_NOT_FOUND:iC,LICENSE_ROLE_DENIED_RESPONSE:aC,LICENSE_MAX_CONNS_REACHED:oC,BASIC_LICENSE_MAX_NON_CU_ROLES:ah,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:tC,VALUE_SEARCH_COMPARATORS:Eh,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:mw,LICENSE_FILE_NAME:XC,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:dw,NEW_LINE:pw,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:_C,MOMENT_DAYS_TAG:mC,API_TURNOVER_SEC:RC,LOOPBACK:cC,CODE_EXTENSION:$n,WILDCARD_SEARCH_VALUE:AC,NODE_ERROR_CODES:hw,JAVASCRIPT_EXTENSION:th,PERMS_CRUD_ENUM:Ow,UNAUTHORIZED_PERMISSION_NAME:gw,SEARCH_WILDCARDS:Nw,FUNC_VAL:Iw,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:bw,JWT_ENUM:Cw,CLUSTERING_FLAG:Sw,RUN_LOG:FC,INSTALL_LOG:GC,IPC_SERVER_MODULE:nh,HDB_IPC_SERVER:ww,IPC_EVENT_TYPES:Lw,HDB_IPC_CLIENT_PREFIX:Uw,CUSTOM_FUNCTION_PROC_NAME:sh,CUSTOM_FUNCTION_PROC_DESCRIPTOR:Sa,SERVICES:yw,MEM_SETTING_KEY:pC,HDB_RESTART_SCRIPT:Yb,PROCESS_DESCRIPTORS:j_,SERVICE_SERVERS:Xb,SERVICE_SERVERS_CWD:ha,PROCESS_DESCRIPTORS_VALIDATE:Jb,LAUNCH_SERVICE_SCRIPTS:zb,LOG_LEVELS:Wb,PROCESS_NAME_ENV_PROP:VC,PROCESS_LOG_NAMES:Qb,PM2_PROCESS_STATUSES:Dw,CONFIG_PARAM_MAP:iw,CONFIG_PARAMS:f,HDB_CONFIG_FILE:kb,HDB_DEFAULT_CONFIG_FILE:xb,ROLE_TYPES_ENUM:jb,BOOT_PROP_PARAMS:kC,INSTALL_PROMPTS:xC,HDB_ROOT_DIR_NAME:$b,CLUSTERING_PROCESSES:Zb,FOREGROUND_PID_FILE:Kb,PACKAGE_ROOT:Gt,PRE_4_0_0_VERSION:Mw}});var su=h((vJ,fh)=>{"use strict";var hh=require("minimist");fh.exports=Pw;function Pw(e=[],t=!1){if(!Array.isArray(e))return{};let r,s;t?(r=Sh(process.env),s=Sh(hh(process.argv))):(r=process.env,s=hh(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(Pw,"assignCMDENVVariables");function Sh(e){let t,r=Object.keys(e),s=r.length,n={};for(;s--;)t=r[s],n[t.toLowerCase()]=e[t];return n}a(Sh,"objKeysToLowerCase")});var g=h((HJ,Nh)=>{"use strict";var os=require("fs-extra"),cs=require("path"),mh=require("yaml"),Rh=require("properties-reader"),Re=T(),Bw=su(),vw=require("os"),{PACKAGE_ROOT:au}=T(),st={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},ma=cs.join(au,"logs"),vr=process.env.pm_id===void 0,Hw=cs.join(au,"config/yaml/",Re.HDB_DEFAULT_CONFIG_FILE),ou=process.env.PROCESS_NAME===void 0?Re.PROCESS_DESCRIPTORS.INSTALL:process.env.PROCESS_NAME,Ys,Xt,dr,rt,nu,Ks;Ks===void 0&&Ah();Nh.exports={createLogFile:qw,notify:Vw,fatal:kw,error:iu,warn:xw,info:Gw,debug:Fw,trace:Oh,setLogLevel:Yw,log_level:rt};function Ah(){try{if(Ks===void 0){let e=$w();Ks=Rh(e),{level:rt,config_log_path:nu,to_file:Xt,to_stream:dr}=Kw(Ks.get("settings_path"))}}catch(e){if(Ks=void 0,e.code===Re.NODE_ERROR_CODES.ENOENT){let t=Bw(Object.keys(Re.CONFIG_PARAM_MAP),!0);for(let i in t){let o=Re.CONFIG_PARAM_MAP[i];o&&o.toLowerCase();let c=t[i];if(o===Re.CONFIG_PARAMS.LOGGING_LEVEL){rt=c;continue}if(o===Re.CONFIG_PARAMS.LOGGING_STDSTREAMS){dr=c;continue}o===Re.CONFIG_PARAMS.LOGGING_FILE&&(Xt=o)}let{default_level:r,default_to_file:s,default_to_stream:n}=Qw();Xt=Xt===void 0?s:Xt,Xt=Th(Xt),dr=dr===void 0?n:dr,dr=Th(dr),rt=rt===void 0?r:rt,nu=ma;return}throw iu("Error initializing log settings"),iu(e),e}}a(Ah,"initLogSettings");function qw(e,t){if(!vr){Oh("createLogFile should only be used if the process is not being managed by pm2");return}Ks===void 0&&Ah(),ou=t;let r;e===Re.PROCESS_LOG_NAMES.INSTALL?r=ma:r=nu,Xt&&(Ys=cs.join(r,e),os.ensureFileSync(Ys))}a(qw,"createLogFile");function _s(e,t){let r=new Date(Date.now()).toISOString(),s="",n=t.length,i=n-1;for(let o=0;o<n;o++){let c=t[o];c instanceof Error&&c.stack?s+=c.stack:typeof c=="object"?s+=JSON.stringify(c):s+=c,o<i&&(s+=" ")}return`{"process_name": "${ou}", "level": "${e}", "timestamp": "${r}", "message": "${s}"}
3
- `}a(_s,"createLogRecord");function ph(e){Ys===void 0&&(ou=Re.PROCESS_DESCRIPTORS.INSTALL,os.ensureDirSync(ma),Ys=cs.join(ma,Re.PROCESS_LOG_NAMES.INSTALL),os.ensureFileSync(Ys)),os.appendFileSync(Ys,e)}a(ph,"writeToLogFile");function Ra(e){Xt&&ph(e),dr&&process.stdout.write(e)}a(Ra,"nonPm2LogStdOut");function cu(e){Xt&&ph(e),dr&&process.stderr.write(e)}a(cu,"nonPm2LogStdErr");function Gw(...e){if(st[rt]<=st.info){let t=_s("info",e);if(vr){Ra(t);return}process.stdout.write(t)}}a(Gw,"info");function Oh(...e){if(st[rt]<=st.trace){let t=_s("trace",e);if(vr){Ra(t);return}process.stdout.write(t)}}a(Oh,"trace");function iu(...e){if(st[rt]<=st.error){let t=_s("error",e);if(vr){cu(t);return}process.stderr.write(t)}}a(iu,"error");function Fw(...e){if(st[rt]<=st.debug){let t=_s("debug",e);if(vr){Ra(t);return}process.stdout.write(t)}}a(Fw,"debug");function Vw(...e){if(st[rt]<=st.notify){let t=_s("notify",e);if(vr){Ra(t);return}process.stdout.write(t)}}a(Vw,"notify");function kw(...e){if(st[rt]<=st.fatal){let t=_s("fatal",e);if(vr){cu(t);return}process.stderr.write(t)}}a(kw,"fatal");function xw(...e){if(st[rt]<=st.warn){let t=_s("warn",e);if(vr){cu(t);return}process.stderr.write(t)}}a(xw,"warn");function $w(){let e;try{e=vw.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=cs.join(e,Re.HDB_HOME_DIR_NAME,Re.BOOT_PROPS_FILE_NAME);return os.existsSync(t)||(t=cs.join(au,"utility/hdb_boot_properties.file")),t}a($w,"getPropsFilePath");function Yw(e){rt=e}a(Yw,"setLogLevel");function Th(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Th,"autoCastBoolean");function Kw(e){try{if(e.includes("config/settings.js")){let o=Rh(e);return{level:o.get(Re.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:cs.dirname(o.get(Re.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(Re.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(Re.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=mh.parseDocument(os.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===Re.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(Kw,"getLogConfig");function Qw(){try{let e=mh.parseDocument(os.readFileSync(Hw,"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(Qw,"getDefaultConfig")});var Ih=h((qJ,gh)=>{"use strict";var Ww=require("util"),Jw=require("path"),Zw=require("child_process"),Xw=Ww.promisify(Zw.execFile),zw=1e3*1e3*10;gh.exports={findPs:jw};async function jw(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:s}=await Xw("ps",["wwxo",`pid,${r}`],{maxBuffer:zw});for(let n of s.trim().split(`
4
- `).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:Jw.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(jw,"findPs")});var Ke=h((GJ,Ch)=>{"use strict";var eU="__dbis__",tU="__environment_name__",rU="__dbi_defintion__",sU={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"},nU=["__createdtime__","__updatedtime__"],iU="\uFFFF",bh={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},aU=Object.values(bh);Ch.exports={INTERNAL_DBIS_NAME:eU,DBI_DEFINITION_NAME:rU,SEARCH_TYPES:sU,TIMESTAMP_NAMES:nU,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:tU,TRANSACTIONS_DBI_NAMES_ENUM:bh,TRANSACTIONS_DBIS:aU,OVERFLOW_MARKER:iU}});var Qe=h((FJ,vh)=>{"use strict";var wh=T(),Uh=Ke(),Lh={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},yh=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),Dh={500:yh("There was an error processing your request."),400:"Invalid request"},oU=Dh[Lh.INTERNAL_SERVER_ERROR],cU={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.`},_U={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},uU={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"},lU={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_ARRAY:"ids must be an array",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 ${Uh.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${Uh.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"},EU={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${wh.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 ${wh.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"},Mh={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"},dU={DEFAULT_INVALID_REQUEST:"Invalid request",OP_AUTH_PERMS_ERROR:"This operation is not authorized due to role restrictions and/or invalid schema 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' schema, tables and records are used internally by HarperDB and cannot be updated or removed."},hU={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 schema metadata for '${e}'`,SCHEMA_TABLE_PERM_ERROR:(e,t)=>`Your role does not have permission to view schema.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`},SU={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=>`Schema '${e}' does not exist`,SCHEMA_EXISTS_ERR:e=>`Schema '${e}' already exists`,TABLE_EXISTS_ERR:(e,t)=>`Table '${t}' already exists in schema '${e}'`,SCHEMA_REQUIRED_ERR:"schema is required",TABLE_NOT_FOUND:(e,t)=>`Table '${e}.${t}' does not exist`,TABLE_REQUIRED_ERR:"table is required"},fU={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},TU={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`},Ph={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.`},Bh={INVALID_IPC_DATA_TYPE:"Invalid IPC event data type, must be an object",MISSING_TYPE:"IPC event missing 'type'",MISSING_MSG:"IPC event missing 'message'",MISSING_ORIGIN:"IPC event message missing 'originator' property",INVALID_EVENT:e=>`IPC server received invalid event type: ${e}`},mU={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 customFunctions enabled to true in hdb/harperdb-config.yaml file."},RU={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},AU={...Mh,...uU,...cU,...dU,...hU,...SU,...fU,...TU,...EU,...Ph,...Bh,...mU,...RU,..._U};vh.exports={CHECK_LOGS_WRAPPER:yh,HDB_ERROR_MSGS:AU,DEFAULT_ERROR_MSGS:Dh,DEFAULT_ERROR_RESP:oU,HTTP_STATUS_CODES:Lh,LMDB_ERRORS_ENUM:lU,AUTHENTICATION_ERROR_MSGS:Mh,VALIDATION_ERROR_MSGS:Ph,IPC_ERRORS:Bh}});var D=h((VJ,Gh)=>{"use strict";var Qs=Qe(),pU=g(),OU=T(),Yn=class extends Error{constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,Hh),this.http_resp_code=s||Qs.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Qs.DEFAULT_ERROR_MSGS[s]?Qs.DEFAULT_ERROR_MSGS[s]:Qs.DEFAULT_ERROR_MSGS[Qs.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,typeof this.message!="string"&&(this.stack=t.stack),i&&pU[n](i)}};a(Yn,"HdbError");function Hh(e,t,r,s=OU.LOG_LEVELS.ERROR,n=null,i=!1){if(qh(e))return e;let o=new Yn(e,t,r,s,n);return i&&delete o.stack,o}a(Hh,"handleHDBError");function qh(e){return e.__proto__.constructor.name===Yn.name}a(qh,"isHDBError");Gh.exports={isHDBError:qh,handleHDBError:Hh,hdb_errors:Qs}});var b=h((xJ,eS)=>{"use strict";var _u=require("path"),NU=require("fs-extra"),be=g(),Fh=require("fs-extra"),gU=require("truncate-utf8-bytes"),Kn=require("os"),IU=require("net"),bU=require("recursive-iterator"),ye=T(),Yh=Ih(),Vh=require("papaparse"),Aa=require("moment"),{inspect:CU}=require("util"),kh=require("is-number"),kJ=require("lodash"),{hdb_errors:pa}=D(),Kh=require("util").promisify(setTimeout),wU=100,UU=5,LU="",yU=4,xh=255,$h={true:!0,false:!1,undefined:null,null:null,NaN:NaN};eS.exports={isEmpty:St,isEmptyOrZeroLength:zt,arrayHasEmptyValues:PU,arrayHasEmptyOrZeroLengthValues:BU,buildFolderPath:vU,isBoolean:Qh,errorizeMessage:DU,stripFileExtension:qU,autoCast:GU,autoCastJSONDeep:uu,removeDir:VU,compareVersions:kU,isCompatibleDataVersion:xU,escapeRawValue:Jh,unescapeValue:$U,stringifyProps:YU,valueConverter:KU,timeoutPromise:WU,isClusterOperation:ZU,getClusterUser:jU,sendTransactionToSocketCluster:XU,checkGlobalSchemaTable:zU,getHomeDir:Zh,getPropsFilePath:QU,promisifyPapaParse:eL,removeBOM:Xh,createEventPromise:tL,checkProcessRunning:rL,checkSchemaTableExist:sL,checkSchemaExists:zh,checkTableExists:jh,getStartOfTomorrowInSeconds:nL,getLimitKey:iL,isObject:HU,isNotEmptyAndHasValue:MU,autoCasterIsNumberCheck:Wh,backtickASTSchemaItems:aL,isPortTaken:JU,stopProcess:oL,createForkArgs:cL,autoCastBoolean:_L,async_set_timeout:Kh,getTableHashAttribute:uL,doesSchemaExist:lL,doesTableExist:EL,stringifyObj:dL,ms_to_time:hL,PACKAGE_ROOT:ye.PACKAGE_ROOT};function DU(e){return e instanceof Error?e:new Error(e)}a(DU,"errorizeMessage");function St(e){return e==null}a(St,"isEmpty");function MU(e){return!St(e)&&(e||e===0||e===""||Qh(e))}a(MU,"isNotEmptyAndHasValue");function zt(e){return St(e)||e.length===0||e.size===0}a(zt,"isEmptyOrZeroLength");function PU(e){if(St(e))return!0;for(let t=0;t<e.length;t++)if(St(e[t]))return!0;return!1}a(PU,"arrayHasEmptyValues");function BU(e){if(zt(e))return!0;for(let t=0;t<e.length;t++)if(zt(e[t]))return!0;return!1}a(BU,"arrayHasEmptyOrZeroLengthValues");function vU(...e){try{return e.join(_u.sep)}catch{console.error(e)}}a(vU,"buildFolderPath");function Qh(e){return St(e)?!1:e===!0||e===!1}a(Qh,"isBoolean");function HU(e){return St(e)?!1:typeof e=="object"}a(HU,"isObject");function qU(e){return zt(e)?LU:e.slice(0,-yU)}a(qU,"stripFileExtension");function GU(e){return St(e)||e===""||typeof e!="string"?e:$h[e]!==void 0?$h[e]:Wh(e)===!0?Number(e):e}a(GU,"autoCast");function FU(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(FU,"autoCastJSON");function uu(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=uu(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=uu(r);s!==r&&(e[t]=s)}return e}else return FU(e)}a(uu,"autoCastJSONDeep");function Wh(e){if(e.startsWith("0.")&&kh(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&kh(e))}a(Wh,"autoCasterIsNumberCheck");async function VU(e){if(zt(e))throw new Error(`Directory path: ${e} does not exist`);try{await Fh.emptyDir(e),await Fh.remove(e)}catch(t){throw be.error(`Error removing files in ${e} -- ${t}`),t}}a(VU,"removeDir");function kU(e,t){if(zt(e)){be.info("Invalid current version sent as parameter.");return}if(zt(t)){be.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("."),_=Math.min(o.length,c.length);for(let u=0;u<_;u++)if(r=parseInt(o[u],10)-parseInt(c[u],10),r)return r;return o.length-c.length}a(kU,"compareVersions");function xU(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(xU,"isCompatibleDataVersion");function Jh(e){if(St(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(Jh,"escapeRawValue");function $U(e){if(St(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($U,"unescapeValue");function YU(e,t){if(St(e))return be.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+Kn.EOL}!zt(s)&&s[0]===";"?r+=" "+s+n+Kn.EOL:zt(s)||(r+=s+"="+n+Kn.EOL)}catch{be.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a(YU,"stringifyProps");function KU(e){let t;try{t=typeof e=="object"?JSON.stringify(e):e}catch(n){be.error(n),t=e}let r=String(Jh(t)),s=Buffer.byteLength(r)>xh?gU(r,xh)+"/blob":r;return{value:t,value_stripped:r,value_path:s}}a(KU,"valueConverter");function Zh(){let e;try{e=Kn.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(Zh,"getHomeDir");function QU(){let e=_u.join(Zh(),ye.HDB_HOME_DIR_NAME,ye.BOOT_PROPS_FILE_NAME);return NU.existsSync(e)||(e=_u.join(__dirname,"../","hdb_boot_properties.file")),e}a(QU,"getPropsFilePath");function WU(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a(WU,"timeoutPromise");async function JU(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=IU.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(JU,"isPortTaken");function ZU(e){try{return ye.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){be.error(`Error checking operation against cluster ops ${t}`)}return!1}a(ZU,"isClusterOperation");function XU(e,t,r){if(global.hdb_socket_client!==void 0){be.trace(`Sending transaction to channel: ${e}`);let{hdb_user:s,hdb_auth_header:n,...i}=t;i.__originator||(i.__originator={}),i.__transacted=!0,r&&(i.__originator[r]=ye.ORIGINATOR_SET_VALUE),global.hdb_socket_client.publish(e,i)}}a(XU,"sendTransactionToSocketCluster");function zU(e,t){if(!global.hdb_schema[e])return pa.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!global.hdb_schema[e]||!global.hdb_schema[e][t])return pa.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(zU,"checkGlobalSchemaTable");function jU(e,t){if(St(t)){be.warn("No CLUSTERING_USER defined, clustering disabled");return}if(St(e)||zt(e)){be.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){be.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){be.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(jU,"getClusterUser");function eL(){Vh.parsePromise=function(e,t){return new Promise(function(r,s){Vh.parse(e,{header:!0,transformHeader:Xh,chunk:t.bind(null,s),skipEmptyLines:!0,dynamicTyping:!0,error:s,complete:r})})}}a(eL,"promisifyPapaParse");function Xh(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(Xh,"removeBOM");function tL(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;be.info(`Got cluster status event response: ${CU(n)}`);try{i.cancel()}catch{be.error("Error trying to cancel timeout.")}s(n)})})}a(tL,"createEventPromise");async function rL(e){let t=!0,r=0;do await Kh(wU*r++),(await Yh.findPs(e)).length>0&&(t=!1);while(t&&r<UU);if(t)throw new Error(`process ${e} was not started`)}a(rL,"checkProcessRunning");function sL(e,t){let r=zh(e);if(r)return r;let s=jh(e,t);if(s)return s}a(sL,"checkSchemaTableExist");function zh(e){if(!global.hdb_schema[e])return pa.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(zh,"checkSchemaExists");function jh(e,t){if(!global.hdb_schema[e][t])return pa.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(jh,"checkTableExists");function nL(){let e=Aa().utc().add(1,ye.MOMENT_DAYS_TAG).startOf(ye.MOMENT_DAYS_TAG).unix(),t=Aa().utc().unix();return e-t}a(nL,"getStartOfTomorrowInSeconds");function iL(){return Aa().utc().format("DD-MM-YYYY")}a(iL,"getLimitKey");function aL(e){try{let t=new bU(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){be.error("Got an error back ticking items."),be.error(t)}}a(aL,"backtickASTSchemaItems");async function oL(e){let t=Kn.userInfo();(await Yh.findPs(e)).forEach(s=>{(t.uid==0||s.uid==t.uid)&&(process.kill(s.pid),be.trace(`Following process was killed by stopProcess: ${s.cmd}`))})}a(oL,"stopProcess");function cL(e){return[e]}a(cL,"createForkArgs");function _L(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(_L,"autoCastBoolean");function uL(e,t){return global.hdb_schema?.[e]?.[t]?.hash_attribute}a(uL,"getTableHashAttribute");function lL(e){return global?.hdb_schema?.[e]!==void 0}a(lL,"doesSchemaExist");function EL(e,t){return global?.hdb_schema?.[e]?.[t]!==void 0}a(EL,"doesTableExist");function dL(e){try{return JSON.stringify(e)}catch{return e}}a(dL,"stringifyObj");function hL(e){let t=Aa.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(hL,"ms_to_time")});var rS=h(($J,tS)=>{"use strict";var SL={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))},fL="certificate.pem",TL="privateKey.pem",mL="ca.pem";tS.exports={CERTIFICATE_VALUES:SL,CERTIFICATE_PEM_NAME:fL,PRIVATEKEY_PEM_NAME:TL,CA_PEM_NAME:mL}});var de=h((YJ,sS)=>{"use strict";var nt=require("validate.js");nt.validators.type=function(e,t,r,s){return e===null||typeof e>"u"||nt.validators.type.checks[t](e)?null:` must be a '${t}' value`};nt.validators.type.checks={Object:function(e){return nt.isObject(e)&&!nt.isArray(e)},Array:nt.isArray,Integer:nt.isInteger,Number:nt.isNumber,String:nt.isString,Date:nt.isDate,Boolean:function(e){return typeof e=="boolean"}};nt.validators.hasValidFileExt=function(e,t){return!nt.isString(e)||e===""||t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`};sS.exports={validateObject:RL,validateObjectAsync:AL,validateBySchema:pL};function RL(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=nt(e,t,{format:"flat"});return r?new Error(r):null}a(RL,"validateObject");async function AL(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await nt.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}a(AL,"validateObjectAsync");function pL(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(pL,"validateBySchema")});var Eu=h((KJ,iS)=>{"use strict";var OL=require("fs-extra"),F=require("joi"),NL=require("os"),{boolean:De,string:Sr,number:jt,array:lu}=F.types(),Ft=require("path"),gL=g(),Oa=b(),fr=rS(),IL=de(),hr="keys",bL=fr.CERTIFICATE_PEM_NAME,CL=fr.PRIVATEKEY_PEM_NAME,wL=fr.CA_PEM_NAME,UL=fr.CERTIFICATE_PEM_NAME,LL=fr.PRIVATEKEY_PEM_NAME,yL=fr.CA_PEM_NAME,DL=fr.CERTIFICATE_PEM_NAME,ML=fr.PRIVATEKEY_PEM_NAME,PL=fr.CA_PEM_NAME,BL="log",vL="custom_functions",HL="Invalid logging.rotation.maxSize unit. Available units are G, M or K",qL="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",GL="rootPath config parameter is undefined",FL="clustering.enabled config parameter is undefined",Hr=jt.min(0).required(),Na=lu.items({host:Sr.required(),port:Hr}).empty(null),it;iS.exports={configValidator:VL,routesValidator:KL,route_constraints:Na};function VL(e){if(it=e.rootPath,Oa.isEmpty(it))throw GL;let t=De.required(),r=F.valid("production","development").required(),s=jt.min(1).max(1e3).empty(null).default(YL),n=Sr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(nS),i=F.custom(xL).messages({"any.custom":"{:#label} {:#error}"}).empty(null).default(nS),o=Sr.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null),c=e.clustering?.enabled;if(Oa.isEmpty(c))throw FL;let _;return c===!0?_=F.object({enabled:t,hubServer:F.object({cluster:F.object({name:F.required().empty(null),network:F.object({port:Hr,routes:Na}).required()}).required(),leafNodes:F.object({network:F.object({port:Hr}).required()}).required(),network:F.object({port:Hr}).required()}).required(),leafServer:F.object({network:F.object({port:Hr,routes:Na}).required()}).required(),nodeName:o,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:De.required()}),user:F.string().required()}).required():_=F.object({enabled:t,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:De.required()})}).required(),F.object({clustering:_,customFunctions:F.object({enabled:t,network:F.object({cors:De.required(),corsAccessList:lu.required(),headersTimeout:jt.min(1).required(),https:De.required(),keepAliveTimeout:jt.min(1).required(),port:Hr,timeout:jt.min(1).required()}),nodeEnv:r,root:n,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),ipc:F.object({network:F.object({port:Hr})}).required(),localStudio:F.object({enabled:t}).required(),logging:F.object({file:De.required(),level:F.valid("notify","fatal","error","warn","info","debug","trace"),rotation:F.object({compress:De.required(),dateFormat:Sr.required(),maxSize:Sr.custom($L).required(),retain:jt.min(0).required(),rotate:De.required(),rotateInterval:Sr.required(),rotateModule:De.required(),timezone:Sr.required(),workerInterval:jt.min(1).required()}).required(),root:n,stdStreams:De.required(),auditLog:De.required()}).required(),operationsApi:F.object({authentication:F.object({operationTokenTimeout:F.required(),refreshTokenTimeout:F.required()}).required(),foreground:De.required(),network:F.object({cors:De.required(),corsAccessList:lu.required(),headersTimeout:jt.min(1).required(),https:De.required(),keepAliveTimeout:jt.min(1).required(),port:Hr,timeout:jt.min(1).required()}).required(),nodeEnv:r,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),rootPath:Sr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),http:F.object({threads:s}).required(),storage:F.object({writeAsync:De.required(),overlappingSync:De.optional()}).required()}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(VL,"configValidator");function kL(e){return OL.existsSync(e)?null:`Specified path ${e} does not exist.`}a(kL,"doesPathExist");function xL(e,t){F.assert(e,Sr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+\.pem+$/).messages({"string.pattern.base":"must be a valid directory path and specify a .pem file"}));let r=kL(e);if(r)return t.message(r)}a(xL,"validatePemFile");function $L(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(HL);let s=e.slice(0,-1);if(isNaN(parseInt(s)))return t.message(qL)}a($L,"validateRotationMaxSize");function YL(e,t){let r=t.state.path.join("."),s=NL.cpus().length,n=s-1;return n<=2&&(n=2),gL.info(`Detected ${s} cores on this machine, defaulting ${r} to ${n}`),n}a(YL,"setDefaultThreads");function nS(e,t){if(!Oa.isEmpty(t.original))return t.original;let r=t.state.path.join(".");if(Oa.isEmpty(it))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"customFunctions.root":return Ft.join(it,vL);case"logging.root":return Ft.join(it,BL);case"operationsApi.tls.certificate":return Ft.join(it,hr,bL);case"operationsApi.tls.privateKey":return Ft.join(it,hr,CL);case"operationsApi.tls.certificateAuthority":return Ft.join(it,hr,wL);case"customFunctions.tls.certificate":return Ft.join(it,hr,UL);case"customFunctions.tls.privateKey":return Ft.join(it,hr,LL);case"customFunctions.tls.certificateAuthority":return Ft.join(it,hr,yL);case"clustering.tls.certificate":return Ft.join(it,hr,DL);case"clustering.tls.privateKey":return Ft.join(it,hr,ML);case"clustering.tls.certificateAuthority":return Ft.join(it,hr,PL);default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(nS,"setDefaultRoot");function KL(e){let t=F.object({routes:Na});return IL.validateBySchema({routes:e},t)}a(KL,"routesValidator")});var Tr=h((QJ,ES)=>{"use strict";var se=T(),bt=b(),We=g(),{configValidator:QL,routesValidator:aS}=Eu(),Vt=require("fs-extra"),WL=require("yaml"),Ws=require("path"),JL=require("is-number"),ba=require("properties-reader"),ZL=require("lodash"),{handleHDBError:XL}=D(),{HTTP_STATUS_CODES:zL,HDB_ERROR_MSGS:ga}=Qe(),{PACKAGE_ROOT:jL}=T(),ey="Unable to get config value because config is uninitialized",ty="Config successfully initialized",ry="Error backing up config file",sy="Empty parameter sent to getConfigValue",oS=Ws.join(jL,"config","yaml",se.HDB_DEFAULT_CONFIG_FILE),ny="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",Ia,at;ES.exports={createConfigFile:iy,getDefaultConfig:ay,getConfigValue:cS,initConfig:_S,flattenConfig:us,updateConfigValue:uS,updateConfigObject:oy,getConfiguration:cy,setConfiguration:_y,readConfigFile:Su,getClusteringRoutes:uy,initOldConfig:lS,getConfigFromFile:ly};function iy(e){let t=Js(oS);Ia=us(t.toJSON());for(let i in e){let o=se.CONFIG_PARAM_MAP[i.toLowerCase()];if(o!==void 0){let c=o.split("_"),_=du(o,e[i]);try{t.setIn([...c],_)}catch(u){We.error(u)}}}hu(t);let r=t.toJSON();at=us(r);let s=t.getIn(["rootPath"]),n=Ws.join(s,se.HDB_CONFIG_FILE);Vt.createFileSync(n),Vt.writeFileSync(n,String(t)),We.trace(`Config file written to ${n}`)}a(iy,"createConfigFile");function ay(e){if(Ia===void 0){let r=Js(oS);Ia=us(r.toJSON())}let t=se.CONFIG_PARAM_MAP[e.toLowerCase()];if(t!==void 0)return Ia[t.toLowerCase()]}a(ay,"getDefaultConfig");function cS(e){if(bt.isEmpty(e)){We.error(sy);return}if(at===void 0){We.trace(ey);return}let t=se.CONFIG_PARAM_MAP[e.toLowerCase()];if(t!==void 0)return at[t.toLowerCase()]}a(cS,"getConfigValue");function _S(e=!1){if(at===void 0||e){let t=bt.getPropsFilePath();try{Vt.accessSync(t,Vt.constants.F_OK|Vt.constants.R_OK)}catch(o){throw We.error(o),new Error(`HarperDB properties file at path ${t} does not exist`)}let s=ba(t).get(se.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),n;if(s.includes("config/settings.js"))try{lS(s);return}catch(o){if(o.code!==se.NODE_ERROR_CODES.ENOENT)throw o}try{n=Js(s)}catch(o){if(o.code===se.NODE_ERROR_CODES.ENOENT){We.trace(`HarperDB config file not found at ${s}.
5
- This can occur during early stages of install where the config file has not yet been created`);return}else throw We.error(o),new Error(`Error reading HarperDB config file at ${s}`)}hu(n);let i=n.toJSON();at=us(i),We.trace(ty)}}a(_S,"initConfig");function hu(e){let t=e.toJSON(),r=QL(t);if(r.error)throw ga.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(["operationsApi","tls","certificate"],r.value.operationsApi.tls.certificate),e.setIn(["operationsApi","tls","privateKey"],r.value.operationsApi.tls.privateKey),e.setIn(["operationsApi","tls","certificateAuthority"],r.value.operationsApi.tls.certificateAuthority),e.setIn(["customFunctions","tls","certificate"],r.value.customFunctions.tls.certificate),e.setIn(["customFunctions","tls","privateKey"],r.value.customFunctions.tls.privateKey),e.setIn(["customFunctions","tls","certificateAuthority"],r.value.customFunctions.tls.certificateAuthority),e.setIn(["clustering","tls","certificate"],r.value.clustering.tls.certificate),e.setIn(["clustering","tls","privateKey"],r.value.clustering.tls.privateKey),e.setIn(["clustering","tls","certificateAuthority"],r.value.clustering.tls.certificateAuthority)}a(hu,"validateConfig");function oy(e,t){at===void 0&&(at={});let r=se.CONFIG_PARAM_MAP[e.toLowerCase()];if(r===void 0){We.trace(`Unable to update config object because config param '${e}' does not exist`);return}at[r.toLowerCase()]=t}a(oy,"updateConfigObject");function uS(e,t,r=void 0,s=!1,n=!1){at===void 0&&_S();let i=cS(se.CONFIG_PARAM_MAP.hdb_root),o=Ws.join(i,se.HDB_CONFIG_FILE),c=Js(o);if(r===void 0){let l=se.CONFIG_PARAM_MAP[e.toLowerCase()];if(l===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=l.split("_"),d=du(l,t);c.setIn([...E],d)}else for(let l in r){let E=se.CONFIG_PARAM_MAP[l.toLowerCase()];if(E!==void 0){let d=E.split("_"),S=du(E,r[l]);try{c.setIn([...d],S)}catch(m){We.error(m)}}}hu(c);let _=c.getIn(["rootPath"]),u=Ws.join(_,se.HDB_CONFIG_FILE);if(s===!0)try{let l=Ws.join(_,"backup",`${se.HDB_CONFIG_FILE}.bak`);Vt.copySync(o,l),We.trace(`Config file: ${o} backed up to: ${l}`)}catch(l){We.error(ry),We.error(l)}Vt.writeFileSync(u,String(c)),n&&(at=us(c.toJSON())),We.trace(`Config parameter: ${e} updated with value: ${t}`)}a(uS,"updateConfigValue");function us(e){let t={};for(let r in e)if(!!e.hasOwnProperty(r))if(typeof e[r]=="object"&&e[r]!==null&&!Array.isArray(e[r])){let s=us(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(us,"flattenConfig");function du(e,t){if(e===se.CONFIG_PARAMS.CLUSTERING_NODENAME||e===se.CONFIG_PARAMS.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(JL(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||bt.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 bt.autoCast(t)}a(du,"castConfigValue");function cy(){let e=bt.getPropsFilePath(),r=ba(e).get(se.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY);return Js(r).toJSON()}a(cy,"getConfiguration");async function _y(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return uS(void 0,void 0,n,!0),ny}catch(i){throw typeof i=="string"||i instanceof String?XL(i,i,zL.BAD_REQUEST,void 0,void 0,!0):i}}a(_y,"setConfiguration");function Su(){let e=bt.getPropsFilePath();try{Vt.accessSync(e,Vt.constants.F_OK|Vt.constants.R_OK)}catch(n){throw We.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let r=ba(e).get(se.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY);return Js(r).toJSON()}a(Su,"readConfigFile");function Js(e){return WL.parseDocument(Vt.readFileSync(e,"utf8"),{simpleKeys:!0})}a(Js,"parseYamlDoc");function uy(){let e=Su(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=bt.isEmptyOrZeroLength(t)?[]:t;let r=aS(t);if(r)throw ga.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=bt.isEmptyOrZeroLength(s)?[]:s;let n=aS(s);if(n)throw ga.CONFIG_VALIDATION(n.message);if(!bt.isEmptyOrZeroLength(s)&&!bt.isEmptyOrZeroLength(t)){let i=t.filter(o=>s.some(c=>c.host===o.host&&c.port===o.port));if(!bt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw ga.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:s}}a(uy,"getClusteringRoutes");function lS(e){let t=ba(e);at={};for(let r in se.CONFIG_PARAM_MAP){let s=t.get(r.toUpperCase());if(bt.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=se.CONFIG_PARAM_MAP[r].toLowerCase();n===se.CONFIG_PARAMS.LOGGING_ROOT?at[n]=Ws.dirname(s):at[n]=s}return at}a(lS,"initOldConfig");function ly(e){let t=Su();return ZL.get(t,e.replaceAll("_","."))}a(ly,"getConfigFromFile")});var V=h((WJ,hS)=>{"use strict";var fu=require("fs-extra"),er=require("path"),Ey=require("os"),dy=require("properties-reader"),Qn=g(),Zs=b(),M=T(),Ca=Tr(),hy="Error initializing environment manager",wa="BOOT_PROPS_FILE_PATH",dS=!1,Sy={[M.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},mr={};hS.exports={BOOT_PROPS_FILE_PATH:wa,getHdbBasePath:fy,setHdbBasePath:Ty,get:my,initSync:Ay,setProperty:Y,initTestEnvironment:py};function fy(){return mr[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(fy,"getHdbBasePath");function Ty(e){mr[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(Ty,"setHdbBasePath");function my(e){let t=Ca.getConfigValue(e);return t===void 0?mr[e]:t}a(my,"get");function Y(e,t){Sy[e]&&(mr[e]=t),Ca.updateConfigObject(e,t)}a(Y,"setProperty");function Ry(){let e;try{e=Zs.getPropsFilePath(),fu.accessSync(e,fu.constants.F_OK|fu.constants.R_OK),dS=!0;let t=dy(e);return mr[M.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(M.HDB_SETTINGS_NAMES.INSTALL_USER),mr[M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),mr[wa]=e,!0}catch{return Qn.trace(`Environment manager found no properties file at ${e}`),!1}}a(Ry,"doesPropFileExist");function Ay(e=!1){try{(dS||Ry())&&(Ca.initConfig(e),mr[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Ca.getConfigValue(M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Qn.error(hy),Qn.error(t),console.error(t),process.exit(1)}}a(Ay,"initSync");function py(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,_=er.join(__dirname,"../../","unitTests");mr[wa]=er.join(_,"hdb_boot_properties.file"),Y(M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,er.join(_,"settings.test")),Y(M.HDB_SETTINGS_NAMES.INSTALL_USER,Ey.userInfo().username),Y(M.HDB_SETTINGS_NAMES.PRIVATE_KEY_KEY,er.join(_,"envDir","utility","keys","privateKey.pem")),Y(M.HDB_SETTINGS_NAMES.CERT_KEY,er.join(_,"envDir","utility","keys","certificate.pem")),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,er.join(_,"envDir","utility","keys","privateKey.pem")),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_CERTIFICATE,er.join(_,"envDir","utility","keys","certificate.pem")),Y(M.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Y(M.HDB_SETTINGS_NAMES.LOG_PATH_KEY,er.join(_,"envDir","log")),Y(M.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Y(M.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Y(M.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Y(M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,er.join(_,"envDir")),Y(M.HDB_SETTINGS_NAMES.HTTP_SECURE_ENABLED_KEY,Zs.isEmpty(n)?!0:n),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,Zs.isEmpty(n)?!0:n),Y(M.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Y(M.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Zs.isEmpty(i)?!1:i),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORS,Zs.isEmpty(i)?!1:i),Y(M.HDB_SETTINGS_NAMES.IPC_SERVER_PORT,9383),Y(M.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Y(M.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Y(M.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Y(M.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Y(M.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,er.resolve(__dirname,"../../unitTests/server/customFunctions/custom_functions")),Y(M.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Zs.isEmpty(c)?!1:c),o&&(Y("CORS_ACCESSLIST",o),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,o)),s&&(Y(M.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,s)),t&&(Y(M.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,t)),r&&(Y(M.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${wa}. Please check your boot props and settings files`;Qn.fatal(r),Qn.error(t)}}a(py,"initTestEnvironment")});var ls=h((JJ,Oy)=>{Oy.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_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]}}});var CS=h((XJ,bS)=>{"use strict";var Tu=require("recursive-iterator"),Ny=require("alasql"),mu=require("clone"),SS=b(),{handleHDBError:fS,hdb_errors:gy}=D(),{HDB_ERROR_MSGS:TS,HTTP_STATUS_CODES:mS}=gy,Iy=["DISTINCT_ARRAY"],RS=Symbol("validateTables"),Ru=Symbol("validateTable"),ZJ=Symbol("getAllColumns"),AS=Symbol("validateAllColumns"),Ua=Symbol("findColumn"),pS=Symbol("validateOrderBy"),Wn=Symbol("validateSegment"),Au=Symbol("validateColumn"),OS=Symbol("setColumnsForTable"),NS=Symbol("checkColumnsForAsterisk"),gS=Symbol("validateGroupBy"),IS=Symbol("hasColumns"),La=class{constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[RS](),this[NS](),this[AS]()}[RS](){if(this[IS]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[Ru](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[Ru](t.table)})}}[IS](){let t=!1,r=new Tu(this.statement);for(let{node:s,path:n}of r)if(s&&s.columnid){t=!0;break}return t}[Ru](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;if(!global.hdb_schema[t.databaseid])throw fS(new Error,TS.SCHEMA_NOT_FOUND(t.databaseid),mS.NOT_FOUND);if(!global.hdb_schema[t.databaseid][t.tableid])throw fS(new Error,TS.TABLE_NOT_FOUND(t.databaseid,t.tableid),mS.NOT_FOUND);global.hdb_schema[t.databaseid][t.tableid].attributes.forEach(s=>{let n=mu(s);n.table=mu(t),this.attributes.push(n)})}[Ua](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)}[NS](){let t=new Tu(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[OS](r.tableid)}[OS](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&this.statement.columns.push(new Ny.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[AS](){this[Wn](this.statement.columns,!1),this[Wn](this.statement.joins,!1),this[Wn](this.statement.where,!1),this[gS](this.statement.group,!1),this[Wn](this.statement.order,!0)}[Wn](t,r){if(!t)return;let s=new Tu(t),n=[];for(let{node:i,path:o}of s)!SS.isEmpty(i)&&!SS.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[pS](i):n.push(this[Au](i)));return n}[gS](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&Iy.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=mu(s);delete n.as,r.push(n)}else if(s.columnid){let n=this[Ua](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[Ua](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`}[pS](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[Au](t)}[Au](t){let r=this[Ua](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]}};a(La,"SelectValidator");bS.exports=La});var pu=h((zJ,wS)=>{"use strict";var ya=class{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")}};a(ya,"BridgeMethods");wS.exports=ya});var Es=h((tZ,DS)=>{"use strict";var US=Qe().LMDB_ERRORS_ENUM,jJ=require("lmdb"),by=Ke(),eZ=require("buffer").Buffer,Cy=require("microtime"),{OVERFLOW_MARKER:LS,MAX_SEARCH_KEY_LENGTH:Da}=by,yS=["number","string","symbol","boolean","bigint"];function wy(e){if(!e)throw new Error(US.ENV_REQUIRED);if(e.constructor.name!=="LMDBStore")throw new Error(US.INVALID_ENVIRONMENT)}a(wy,"validateEnv");function Uy(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(Uy,"stringifyData");function Ly(e){return e instanceof Date?e.valueOf():e}a(Ly,"convertKeyValueToWrite");function yy(e){if(e==null)return;if(yS.includes(typeof e))return e.length>Da?[e.slice(0,Da)+LS]:[e];let t;if(Array.isArray(e)){t=[];for(let r=0,s=e.length;r<s;r++){let n=e[r];yS.includes(typeof n)&&(n.length>Da?t.push(n.slice(0,Da)+LS):t.push(n))}}return t}a(yy,"getIndexedValues");function Dy(){let e=Cy.now().toString(),t=e.length-3;return Number(e.slice(0,t)+"."+e.slice(t))}a(Dy,"getMicroTime");DS.exports={validateEnv:wy,stringifyData:Uy,convertKeyValueToWrite:Ly,getMicroTime:Dy,getIndexedValues:yy}});var PS=h((rZ,MS)=>{"use strict";var Ma=class{constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};a(Ma,"DBIDefinition");MS.exports=Ma});var vS=h((sZ,BS)=>{"use strict";var Pa=class{constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache={validated:!0},this.randomAccessStructure=!0,this.freezeData=!0)}};a(Pa,"OpenDBIObject");BS.exports=Pa});var qS=h((nZ,HS)=>{"use strict";var Ba=class{constructor(t,r,s,n,i=!1,o=!1,c=void 0){this.path=t,this.mapSize=r,this.maxDbs=s,this.maxReaders=n,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=i,this.trackMetrics=!0,this.noSync=o,c!==void 0&&(this.overlappingSync=c)}};a(Ba,"OpenEnvironmentObject");HS.exports=Ba});var X=h((aZ,ZS)=>{"use strict";var Ou=require("lmdb"),Ct=require("fs-extra"),kt=require("path"),Ha=Es(),GS=g(),Me=Qe().LMDB_ERRORS_ENUM,qa=PS(),Nu=vS(),FS=qS(),qr=Ke(),iZ=T(),Jn=V();Jn.initSync();var VS=Jn.get("STORAGE_WRITEASYNC")===!0||Jn.get("STORAGE_WRITEASYNC")==="true"||Jn.get("STORAGE_WRITEASYNC")==="TRUE",kS=Jn.get("STORAGE_OVERLAPPINGSYNC"),xS=1024*1024*1024,$S=1e4,YS=1e3,xt=qr.INTERNAL_DBIS_NAME,KS=qr.DBI_DEFINITION_NAME,My="data.mdb",Py="lock.mdb",Zn=".mdb",By="-lock",va=class{constructor(t,r,s=!1){this.dbi=wt(t,r),this.key_type=this.dbi[qr.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[qr.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:s===!1}),this.cursor=new Ou.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};a(va,"TransactionCursor");function gu(e,t){if(e===void 0)throw new Error(Me.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(Me.ENV_NAME_REQUIRED)}a(gu,"pathEnvNameValidation");async function Iu(e,t,r=!0){try{await Ct.access(e)}catch(s){throw s.code==="ENOENT"?new Error(Me.INVALID_BASE_PATH):s}try{let s=kt.join(e,t+Zn);return await Ct.access(s,Ct.constants.R_OK|Ct.constants.F_OK),s}catch(s){if(s.code==="ENOENT")if(r)try{return await Ct.access(kt.join(e,t,My),Ct.constants.R_OK|Ct.constants.F_OK),kt.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(Me.INVALID_ENVIRONMENT)}else throw new Error(Me.INVALID_ENVIRONMENT);throw s}}a(Iu,"validateEnvironmentPath");function Ga(e,t){if(Ha.validateEnv(e),t===void 0)throw new Error(Me.DBI_NAME_REQUIRED)}a(Ga,"validateEnvDBIName");async function vy(e,t,r=!1,s=!1){gu(e,t),t=t.toString();try{return await Iu(e,t,s),bu(e,t,r)}catch(n){if(n.message===Me.INVALID_ENVIRONMENT){let i=kt.join(e,t);await Ct.mkdirp(s?i:e);let o=new FS(s?i:i+Zn,xS,$S,YS,!1,VS,kS),c=Ou.open(o);c.dbis=Object.create(null);let _=new Nu(!1);c.openDB(xt,_),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let u=Cu(e,t,r);return c[qr.ENVIRONMENT_NAME_KEY]=u,global.lmdb_map[u]=c,c}throw n}}a(vy,"createEnvironment");async function Hy(e,t,r,s=!0){let n=await bu(e,t);if(r===void 0)throw new Error(Me.DESTINATION_PATH_REQUIRED);try{await Ct.access(kt.dirname(r))}catch(i){throw i.code==="ENOENT"?new Error(Me.INVALID_DESTINATION_PATH):i}await n.backup(r,s)}a(Hy,"copyEnvironment");async function bu(e,t,r=!1){gu(e,t),t=t.toString();let s=Cu(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 Iu(e,t),i=kt.join(e,t+Zn),o=n!=i,c=new FS(n,xS,$S,YS,o,VS,kS),_=Ou.open(c);_.dbis=Object.create(null);let u=WS(_);for(let l=0;l<u.length;l++)wt(_,u[l]);return _[qr.ENVIRONMENT_NAME_KEY]=s,global.lmdb_map[s]=_,_}a(bu,"openEnvironment");async function qy(e,t,r=!1){gu(e,t),t=t.toString();let s=kt.join(e,t+Zn),n=await Iu(e,t);if(global.lmdb_map!==void 0){let i=Cu(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await QS(o),delete global.lmdb_map[i]}}await Ct.remove(n),await Ct.remove(n===s?n+By:kt.join(kt.dirname(n),Py))}a(qy,"deleteEnvironment");async function QS(e){Ha.validateEnv(e);let t=e[qr.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(QS,"closeEnvironment");function Cu(e,t,r=!1){let n=`${kt.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}a(Cu,"getCachedEnvironmentName");function Gy(e){Ha.validateEnv(e);let t=Object.create(null),r=wt(e,xt);for(let{key:s,value:n}of r.getRange({start:!1}))if(s!==xt)try{t[s]=Object.assign(new qa,n)}catch{GS.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}a(Gy,"listDBIDefinitions");function WS(e){Ha.validateEnv(e);let t=[],r=wt(e,xt);for(let{key:s}of r.getRange({start:!1}))s!==xt&&t.push(s);return t}a(WS,"listDBIs");function Fy(e,t){let s=wt(e,xt).getEntry(t),n=new qa;if(s!==void 0){try{n=Object.assign(n,s.value)}catch{GS.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return n}}a(Fy,"getDBIDefinition");function JS(e,t,r,s=!1){if(Ga(e,t),t=t.toString(),t===xt)throw new Error(Me.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return wt(e,t)}catch(n){if(n.message===Me.DBI_DOES_NOT_EXIST){let i=new Nu(r,s===!0),o=e.openDB(t,i),c=new qa(r===!0,s);return o[KS]=c,wt(e,xt).putSync(t,c),e.dbis[t]=o,o}throw n}}a(JS,"createDBI");function wt(e,t){if(Ga(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==xt?r=Fy(e,t):r=new qa,r===void 0)throw new Error(Me.DBI_DOES_NOT_EXIST);let s;try{let n=new Nu(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(Me.DBI_DOES_NOT_EXIST):n}return s[KS]=r,e.dbis[t]=s,s}a(wt,"openDBI");function Vy(e,t){Ga(e,t),t=t.toString();let r=wt(e,t),s=r.getStats();return r[qr.DBI_DEFINITION_NAME].is_hash_attribute&&s.entryCount>0&&s.entryCount--,s}a(Vy,"statDBI");async function ky(e,t){try{let r=kt.join(e,t+Zn);return(await Ct.stat(r)).size}catch{throw new Error(Me.INVALID_ENVIRONMENT)}}a(ky,"environmentDataSize");function xy(e,t){if(Ga(e,t),t=t.toString(),t===xt)throw new Error(Me.CANNOT_DROP_INTERNAL_DBIS_NAME);wt(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],wt(e,xt).removeSync(t)}a(xy,"dropDBI");function $y(e,t,r){for(let s=0;s<r.length;s++){let n=r[s];if(!e.dbis[n])try{wt(e,n)}catch(i){if(i.message===Me.DBI_DOES_NOT_EXIST)JS(e,n,n!==t,n===t);else throw i}}}a($y,"initializeDBIs");ZS.exports={openDBI:wt,openEnvironment:bu,createEnvironment:vy,listDBIs:WS,listDBIDefinitions:Gy,createDBI:JS,dropDBI:xy,statDBI:Vy,deleteEnvironment:qy,initializeDBIs:$y,TransactionCursor:va,environmentDataSize:ky,copyEnvironment:Hy,closeEnvironment:QS}});var zS=h((oZ,XS)=>{"use strict";var Fa=class{constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};a(Fa,"InsertRecordsResponseObject");XS.exports=Fa});var ef=h((cZ,jS)=>{"use strict";var Va=class{constructor(t=[],r=[],s=void 0,n=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s,this.original_records=n}};a(Va,"UpdateRecordsResponseObject");jS.exports=Va});var rf=h((_Z,tf)=>{"use strict";var ka=class{constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};a(ka,"UpsertRecordsResponseObject");tf.exports=ka});var Xs=h((dZ,nf)=>{"use strict";var Yy=X(),Ky=zS(),Qy=ef(),Wy=rf(),zn=Es(),Xn=Qe().LMDB_ERRORS_ENUM,Jy=Ke(),Gr=T(),Zy=b(),Xy=require("uuid"),uZ=require("lmdb"),{handleHDBError:zy,hdb_errors:jy}=D(),{OVERFLOW_MARKER:lZ,MAX_SEARCH_KEY_LENGTH:EZ}=Jy,wu=Gr.TIME_STAMP_NAMES_ENUM.CREATED_TIME,ds=Gr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function eD(e,t,r,s,n=!0){Du(e,t,r,s),Uu(e,t,r);let i=new Ky,o=[],c=[];for(let _=0;_<s.length;_++){let u=s[_];sf(u,!0,n);let l=tD(e,t,r,u),E=u[t];o.push(l),c.push(E)}return Lu(o,c,s,i)}a(eD,"insertRecords");function tD(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 u=c([[{}]]);Array.isArray(u)&&(c=u[0][Gr.FUNC_VAL],s[o]=c)}let _=zn.getIndexedValues(c);if(_)for(let u=0,l=_.length;u<l;u++)e.dbis[o].put(_[u],n)}e.dbis[t].put(n,s,s[ds])})}a(tD,"insertRecord");function rD(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(rD,"removeSkippedRecords");function sf(e,t,r=!0){let s=Date.now();(r===!0||!Number.isInteger(e[ds]))&&(e[ds]=s),t===!0?(r===!0||!Number.isInteger(e[wu]))&&(e[wu]=s):delete e[wu]}a(sf,"setTimestamps");function Uu(e,t,r){r.indexOf(Gr.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Gr.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Gr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Gr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),Yy.initializeDBIs(e,t,r)}a(Uu,"initializeTransaction");async function sD(e,t,r,s,n=!0){Du(e,t,r,s),Uu(e,t,r);let i=new Qy,o=[],c=[],_=[];for(let u=0;u<s.length;u++){let l=s[u],E=l[t],d;try{d=yu(e,t,l,E,i,!0,n)}catch{i.skipped_hashes.push(E),o.push(u);continue}c.push(d),_.push(E)}return Lu(c,_,s,i,o)}a(sD,"updateRecords");async function nD(e,t,r,s,n=!0){try{Du(e,t,r,s)}catch(_){throw zy(_,_.message,jy.HTTP_STATUS_CODES.BAD_REQUEST)}Uu(e,t,r);let i=new Wy,o=[],c=[];for(let _=0;_<s.length;_++){let u=s[_],l;Zy.isEmpty(u[t])?(l=Xy.v4(),u[t]=l):l=u[t];let E=yu(e,t,u,l,i,!1,n);o.push(E),c.push(l)}return Lu(o,c,s,i)}a(nD,"upsertRecords");async function Lu(e,t,r,s,n=[]){let i=await Promise.all(e);for(let o=0,c=i.length;o<c;o++)i[o]===!0?s.written_hashes.push(t[o]):(s.skipped_hashes.push(t[o]),n.push(o));return s.txn_time=zn.getMicroTime(),rD(r,n),s}a(Lu,"finalizeWrite");function yu(e,t,r,s,n,i=!1,o=!0){let c=e.dbis[t],_=c.getEntry(s),u=_?.value,l=u;if(!u){if(i)return!1;u={}}if(sf(r,!l,o),Number.isInteger(r[ds])&&u[ds]>r[ds])return!1;l&&n.original_records.push(u);let E,d=a(()=>{for(let m in r){if(!r.hasOwnProperty(m)||m===t)continue;let R=r[m],w=e.dbis[m];if(w===void 0)continue;let U=u[m];if(typeof R=="function"){let j=R([[u]]);Array.isArray(j)&&(R=j[0][Gr.FUNC_VAL],r[m]=R)}if(R===U)continue;let B=zn.getIndexedValues(U);if(B)for(let j=0,k=B.length;j<k;j++)w.remove(B[j],s);if(B=zn.getIndexedValues(R),B)for(let j=0,k=B.length;j<k;j++)w.put(B[j],s)}let S=Object.assign({},u,r);c.put(s,S,S[ds])},"do_put");return _?E=c.ifVersion(s,_.version,d):E=c.ifNoExists(s,d),E.then(S=>S?!0:yu(e,t,r,s,n,i,o))}a(yu,"updateUpsertRecord");function iD(e,t,r){if(zn.validateEnv(e),t===void 0)throw new Error(Xn.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Xn.WRITE_ATTRIBUTES_REQUIRED):new Error(Xn.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(iD,"validateBasic");function Du(e,t,r,s){if(iD(e,t,r),!Array.isArray(s))throw s===void 0?new Error(Xn.RECORDS_REQUIRED):new Error(Xn.RECORDS_MUST_BE_ARRAY)}a(Du,"validateWrite");nf.exports={insertRecords:eD,updateRecords:sD,upsertRecords:nD}});var re=h((hZ,of)=>{"use strict";var Mu=T(),zs=V(),Pu=require("path");zs.initSync();var xa,$a,Ya;function af(){if(xa!==void 0)return xa;if(zs.getHdbBasePath()!==void 0)return xa=Pu.join(zs.getHdbBasePath(),Mu.SCHEMA_DIR_NAME),xa}a(af,"getBaseSchemaPath");function aD(){if($a!==void 0)return $a;if(zs.getHdbBasePath()!==void 0)return $a=Pu.join(af(),Mu.SYSTEM_SCHEMA_NAME),$a}a(aD,"getSystemSchemaPath");function oD(){if(Ya!==void 0)return Ya;if(zs.getHdbBasePath()!==void 0)return Ya=Pu.join(zs.getHdbBasePath(),Mu.TRANSACTIONS_DIR_NAME),Ya}a(oD,"getTransactionAuditStorePath");of.exports={getBaseSchemaPath:af,getSystemSchemaPath:aD,getTransactionAuditStorePath:oD}});var Rr=h((SZ,uf)=>{"use strict";var _f=b(),cf=T(),Qa=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Bu=require("joi"),Ka={schema_format:{pattern:Qa,message:"names cannot include backticks or forward slashes"},schema_length:{maximum:250,tooLong:"cannot exceed 250 characters"}},cD=Bu.alternatives(Bu.string().min(1).max(Ka.schema_length.maximum).pattern(Qa).messages({"string.pattern.base":"{:#label} "+Ka.schema_format.message}),Bu.number()).required();function _D(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>Ka.schema_length.maximum?`'${e}' maximum of 250 characters`:Qa.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(_D,"checkValidTable");function uD(e,t){return _f.doesSchemaExist(e)?e:t.message(`Schema '${e}' does not exist`)}a(uD,"validateSchemaExists");function lD(e,t){let r=t.state.ancestors[0].schema;return _f.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(lD,"validateTableExists");function ED(e,t){return e.toLowerCase()===cf.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid schema name, '${cf.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(ED,"validateSchemaName");uf.exports={common_validators:Ka,schema_regex:Qa,hdb_schema_table:cD,validateSchemaExists:uD,validateTableExists:lD,validateSchemaName:ED,checkValidTable:_D}});var Wa=h((fZ,lf)=>{var{common_validators:Fr}=Rr(),jn=de(),$t="is required",z={schema:{presence:!0,format:Fr.schema_format,length:Fr.schema_length},table:{presence:!0,format:Fr.schema_format,length:Fr.schema_length},attribute:{presence:!0,format:Fr.schema_format,length:Fr.schema_length},hash_attribute:{presence:!0,format:Fr.schema_format,length:Fr.schema_length}};function ei(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(ei,"makeAttributesStrings");function dD(e){return e=ei(e),z.schema.presence={message:$t},z.table.presence=!1,z.attribute.presence=!1,z.hash_attribute.presence=!1,jn.validateObject(e,z)}a(dD,"schema_object");function hD(e){return e=ei(e),z.schema.presence={message:$t},z.table.presence={message:$t},z.attribute.presence=!1,z.hash_attribute.presence=!1,jn.validateObject(e,z)}a(hD,"table_object");function SD(e){return e=ei(e),z.schema.presence={message:$t},z.table.presence={message:$t},z.attribute.presence=!1,z.hash_attribute.presence={message:$t},jn.validateObject(e,z)}a(SD,"create_table_object");function fD(e){return e=ei(e),z.schema.presence={message:$t},z.table.presence={message:$t},z.attribute.presence={message:$t},z.hash_attribute.presence=!1,jn.validateObject(e,z)}a(fD,"attribute_object");function TD(e){return e=ei(e),z.schema.presence={message:$t},z.table.presence={message:$t},z.attribute.presence=!1,z.hash_attribute.presence=!1,jn.validateObject(e,z)}a(TD,"describe_table");function mD(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(mD,"validateTableResidence");lf.exports={schema_object:dD,create_table_object:SD,table_object:hD,attribute_object:fD,describe_table:TD,validateTableResidence:mD}});var df=h((TZ,Ef)=>{"use strict";var RD=require("uuid"),Ja=class{constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||RD.v4(),this.schema_table=`${this.schema}.${this.table}`}};a(Ja,"CreateAttributeObject");Ef.exports=Ja});var Xa=h((mZ,hf)=>{"use strict";var AD=df(),Za=class extends AD{constructor(t,r,s,n,i=!0,o=!1){super(t,r,s,n),this.dup_sort=i,this.is_hash_attribute=o}};a(Za,"LMDBCreateAttributeObject");hf.exports=Za});var ff=h((RZ,Sf)=>{"use strict";Sf.exports=OD;var pD="inserted";function OD(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===pD?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(OD,"returnObject")});var za=h((AZ,mf)=>{"use strict";var ND=T(),vu=X(),gD=Xs(),{getSystemSchemaPath:ID,getBaseSchemaPath:bD}=re(),CD=require("path"),wD=ls(),UD=Wa(),LD=Xa(),yD=ff(),{handleHDBError:DD,hdb_errors:MD}=D(),PD=b(),Hu=wD.hdb_attribute,Tf=[];for(let e=0;e<Hu.attributes.length;e++)Tf.push(Hu.attributes[e].attribute);var BD="inserted";mf.exports=vD;async function vD(e){let t=UD.attribute_object(e);if(t)throw DD(new Error,t.message,MD.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=PD.isEmpty(e.dup_sort)||e.dup_sort=="true";let r=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(r=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(r)&&r.length>0){for(let n of r)if(n.attribute===e.attribute)throw new Error(`attribute '${n.attribute}' already exists in ${e.schema}.${e.table}`)}let s=new LD(e.schema,e.table,e.attribute,e.id);try{let n=await vu.openEnvironment(CD.join(bD(),e.schema.toString()),e.table);if(n.dbis[e.attribute]!==void 0)throw new Error(`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`);vu.createDBI(n,e.attribute,e.dup_sort,e.is_hash_attribute);let i=await vu.openEnvironment(ID(),ND.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:o,skipped_hashes:c}=await gD.insertRecords(i,Hu.hash_attribute,Tf,[s]);return yD(BD,o,{records:[s]},c)}catch(n){throw n}}a(vD,"lmdbCreateAttribute")});var Gu=h((pZ,Af)=>{var{hdb_schema_table:Rf}=Rr(),HD=de(),qu=require("joi"),qD={undefined:"undefined",null:"null"},GD=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||qD[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"),FD=qu.object({schema:Rf,table:Rf,records:qu.array().items(qu.object().custom(GD)).required()});Af.exports=function(e){return HD.validateBySchema(e,FD)}});var ja=h((NZ,Of)=>{"use strict";var Ar=b(),pf=g(),OZ=Gu();Of.exports=VD;function VD(e){if(Ar.isEmpty(e))throw new Error("invalid update parameters defined.");if(Ar.isEmptyOrZeroLength(e.schema))throw new Error("invalid schema specified.");if(Ar.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");if(!Array.isArray(e.records))throw new Error("records must be an array");let t=global.hdb_schema[e.schema][e.table];if(Ar.isEmpty(t))throw new Error(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.hash_attribute,s=new Set,n={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&Ar.isEmptyOrZeroLength(o[r]))throw pf.error("a valid hash attribute must be provided with update record:",o),new Error("a valid hash attribute must be provided with update record, check log for more info");if(!Ar.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw pf.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Error(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!Ar.isEmpty(o[r])&&o[r]!==""&&s.has(Ar.autoCast(o[r]))&&(o.skip=!0),s.add(Ar.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(VD,"insertUpdateValidate")});var ti=h((gZ,Nf)=>{"use strict";var kD=T().OPERATIONS_ENUM,eo=class{constructor(t,r,s,n,i=void 0){this.operation=kD.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};a(eo,"InsertObject");Nf.exports=eo});var ro=h((bZ,gf)=>{"use strict";var IZ=ti(),to=T(),Vu=b(),Fu=g(),xD=require("uuid"),{handleHDBError:ri,hdb_errors:$D}=D(),{HDB_ERROR_MSGS:si,HTTP_STATUS_CODES:ni}=$D;gf.exports=YD;function YD(e,t,r){for(let n=0;n<t.length;n++)KD(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];QD(i,r,e.operation)}}a(YD,"processRows");function KD(e){if(Buffer.byteLength(String(e))>to.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw ri(new Error,si.ATTR_NAME_LENGTH_ERR(e),ni.BAD_REQUEST,void 0,void 0,!0);if(Vu.isEmptyOrZeroLength(e)||Vu.isEmpty(e.trim()))throw ri(new Error,si.ATTR_NAME_NULLISH_ERR,ni.BAD_REQUEST,void 0,void 0,!0)}a(KD,"validateAttribute");function QD(e,t,r){if(!e.hasOwnProperty(t)||Vu.isEmptyOrZeroLength(e[t])){if(r===to.OPERATIONS_ENUM.INSERT||r===to.OPERATIONS_ENUM.UPSERT){e[t]=xD.v4();return}throw Fu.error("Update transaction aborted due to record with no hash value:",e),ri(new Error,si.RECORD_MISSING_HASH_ERR,ni.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>to.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Fu.error(e),ri(new Error,si.HASH_VAL_LENGTH_ERR,ni.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw Fu.error(e),ri(new Error,si.INVALID_FORWARD_SLASH_IN_HASH_ERR,ni.BAD_REQUEST,void 0,void 0,!0)}a(QD,"validateHash")});var bf=h((CZ,If)=>{"use strict";var so=class{constructor(t,r){this.type=t,this.message=r}};a(so,"IPCEventObject");If.exports=so});var Vr=h((wZ,Cf)=>{"use strict";var WD=g(),ku=b(),JD=T(),{IPC_ERRORS:ii}=Qe();Cf.exports={sendIpcEvent:ZD,validateEvent:XD,SchemaEventMsg:zD,UserEventMsg:jD};function ZD(e){global.hdb_ipc?global.hdb_ipc.emitToServer(e):WD.warn("Tried to send event:",e,"to HDB IPC client but it does not exist")}a(ZD,"sendIpcEvent");function XD(e){if(typeof e!="object")return ii.INVALID_IPC_DATA_TYPE;if(!e.hasOwnProperty("type")||ku.isEmpty(e.type))return ii.MISSING_TYPE;if(!e.hasOwnProperty("message")||ku.isEmpty(e.message))return ii.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||ku.isEmpty(e.message.originator))return ii.MISSING_ORIGIN;if(JD.IPC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return ii.INVALID_EVENT(e.type)}a(XD,"validateEvent");function zD(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(zD,"SchemaEventMsg");function jD(e){this.originator=e}a(jD,"UserEventMsg")});var js=h((LZ,yf)=>{"use strict";var wf=T(),UZ=b(),no=g(),Uf=bf(),{sendIpcEvent:Lf}=Vr();function eM(e){try{no.trace("signalSchemaChange called with message:",e);let t=new Uf(wf.IPC_EVENT_TYPES.SCHEMA,e);Lf(t)}catch(t){no.error(t)}}a(eM,"signalSchemaChange");function tM(e){try{no.trace("signalUserChange called with message:",e);let t=new Uf(wf.IPC_EVENT_TYPES.USER,e);Lf(t)}catch(t){no.error(t)}}a(tM,"signalUserChange");yf.exports={signalSchemaChange:eM,signalUserChange:tM}});var io=h((yZ,Mf)=>{"use strict";var Df=b(),rM=T(),sM=g(),nM=za(),iM=Xa(),aM=js(),{SchemaEventMsg:oM}=Vr(),cM="already exists in";Mf.exports=_M;async function _M(e,t,r){try{if(Df.isEmptyOrZeroLength(r))return r;let s=[];Df.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 uM(e,t.schema,t.name,i)})),n}catch(s){throw s}}a(_M,"lmdbCheckForNewAttributes");async function uM(e,t,r,s){let n=new iM(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await lM(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(cM))sM.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(uM,"createNewAttribute");async function lM(e){let t;try{return t=await nM(e),aM.signalSchemaChange(new oM(process.pid,rM.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}catch(r){throw r}}a(lM,"createAttribute")});var en=h((DZ,Pf)=>{"use strict";var ao=class{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}};a(ao,"LMDBTransactionObject");Pf.exports=ao});var vf=h((MZ,Bf)=>{"use strict";var EM=en(),dM=T().OPERATIONS_ENUM,oo=class extends EM{constructor(t,r,s,n,i=void 0){super(dM.INSERT,r,s,n,i),this.records=t}};a(oo,"LMDBInsertTransactionObject");Bf.exports=oo});var qf=h((PZ,Hf)=>{"use strict";var hM=en(),SM=T().OPERATIONS_ENUM,co=class extends hM{constructor(t,r,s,n,i,o=void 0){super(SM.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};a(co,"LMDBUpdateTransactionObject");Hf.exports=co});var Ff=h((BZ,Gf)=>{"use strict";var fM=en(),TM=T().OPERATIONS_ENUM,_o=class extends fM{constructor(t,r,s,n,i,o=void 0){super(TM.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};a(_o,"LMDBUpsertTransactionObject");Gf.exports=_o});var kf=h((vZ,Vf)=>{"use strict";var mM=en(),RM=T().OPERATIONS_ENUM,uo=class extends mM{constructor(t,r,s,n,i=void 0){super(RM.DELETE,s,n,t,i),this.original_records=r}};a(uo,"LMDBDeleteTransactionObject");Vf.exports=uo});var ai=h((HZ,Kf)=>{"use strict";var AM=require("path"),xf=X(),pM=vf(),OM=qf(),NM=Ff(),gM=kf(),tn=Ke(),$f=b(),{CONFIG_PARAMS:IM}=T(),Yf=V();Yf.initSync();var lo=T().OPERATIONS_ENUM,{getTransactionAuditStorePath:bM}=re();Kf.exports=CM;async function CM(e,t){if(Yf.get(IM.LOGGING_AUDITLOG)===!1)return;let r=AM.join(bM(),e.schema.toString()),s=await xf.openEnvironment(r,e.table,!0),n=wM(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){xf.initializeDBIs(s,tn.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,tn.TRANSACTIONS_DBIS);try{let i=n.timestamp;return await s.dbis[tn.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{s.dbis[tn.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,n),$f.isEmpty(n.user_name)||s.dbis[tn.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(n.user_name,i);for(let o=0;o<n.hash_values.length;o++)s.dbis[tn.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(n.hash_values[o],i)})}catch(i){throw i}}}a(CM,"writeTransaction");function wM(e,t){let r=$f.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===lo.INSERT)return new pM(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===lo.UPDATE)return new OM(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===lo.UPSERT)return new NM(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===lo.DELETE)return new gM(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(wM,"createTransactionObject")});var xu=h((GZ,Qf)=>{"use strict";var UM=ja(),qZ=ti(),rn=T(),LM=ro(),yM=Xs().insertRecords,DM=X(),MM=require("path"),PM=g(),BM=io(),{getBaseSchemaPath:vM}=re(),HM=ai();Qf.exports=qM;async function qM(e){try{let{schema_table:t,attributes:r}=UM(e);LM(e,r,t.hash_attribute),e.schema!==rn.SYSTEM_SCHEMA_NAME&&(r.includes(rn.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(rn.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(rn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(rn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await BM(e.hdb_auth_header,t,r),n=MM.join(vM(),e.schema.toString()),i=await DM.openEnvironment(n,e.table),o=await yM(i,t.hash_attribute,r,e.records,e[rn.CLUSTERING_FLAG]!==!0);try{await HM(e,o)}catch(c){PM.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(qM,"lmdbCreateRecords")});var Zf=h((FZ,Jf)=>{"use strict";var Wf=T(),GM=xu(),FM=ti(),VM=require("fs-extra"),kM=require("path"),{getBaseSchemaPath:xM}=re();Jf.exports=$M;async function $M(e){let t=[{name:e.schema,createddate:Date.now()}],r=new FM(Wf.SYSTEM_SCHEMA_NAME,Wf.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await GM(r),await VM.mkdirp(kM.join(xM(),e.schema.toString()))}a($M,"lmdbCreateSchema")});var zf=h((VZ,Xf)=>{"use strict";var Eo=class{constructor(t=[],r=[],s=void 0,n=[]){this.deleted=t,this.skipped=r,this.txn_time=s,this.original_records=n}};a(Eo,"DeleteRecordsResponseObject");Xf.exports=Eo});var Ku=h((YZ,tT)=>{"use strict";var jf=X(),$u=Es(),Yu=Qe().LMDB_ERRORS_ENUM,YM=Ke(),eT=g(),kZ=b(),KM=require("lmdb"),QM=zf(),{OVERFLOW_MARKER:xZ,MAX_SEARCH_KEY_LENGTH:$Z}=YM;async function WM(e,t,r){if($u.validateEnv(e),t===void 0)throw new Error(Yu.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Yu.IDS_REQUIRED):new Error(Yu.IDS_MUST_BE_ARRAY);try{let s=jf.listDBIs(e);jf.initializeDBIs(e,t,s);let n=new QM,i,o=[],c=[];for(let E=0,d=r.length;E<d;E++)try{i=r[E];let S=e.dbis[t].get(i);if(!S){n.skipped.push(i);continue}let m=e.dbis[t].ifVersion(i,KM.IF_EXISTS,()=>{e.dbis[t].remove(i);for(let R=0;R<s.length;R++){let w=s[R];if(!S.hasOwnProperty(w)||w===t)continue;let U=e.dbis[w],B=S[w];if(B!=null)try{let j=$u.getIndexedValues(B);if(j)for(let k=0,J=j.length;k<J;k++)U.remove(j[k],i)}catch{eT.warn(`cannot delete from attribute: ${w}, ${B}:${i}`)}}});o.push(m),c.push(i),n.original_records.push(S)}catch(S){eT.warn(S),n.skipped.push(i)}let _=[],u=await Promise.all(o);for(let E=0,d=u.length;E<d;E++)u[E]===!0?n.deleted.push(c[E]):(n.skipped.push(c[E]),_.push(E));let l=0;for(let E=0;E<_.length;E++){let d=_[E];n.original_records.splice(d-l,1),l++}return n.txn_time=$u.getMicroTime(),n}catch(s){throw s}}a(WM,"deleteRecords");tT.exports={deleteRecords:WM}});var oi=h((KZ,sT)=>{"use strict";var sn=b(),JM=Ku(),ZM=X(),XM=require("path"),{getBaseSchemaPath:zM}=re(),jM=ai(),eP=g();sT.exports=tP;async function tP(e,t=!0){let s=global.hdb_schema[e.schema][e.table].hash_attribute;if(sn.isEmpty(s))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(sn.isEmptyOrZeroLength(e.hash_values)&&!sn.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let _=e.records[c][s];sn.isEmpty(_)||e.hash_values.push(_)}}if(sn.isEmptyOrZeroLength(e.hash_values))return rT([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(sn.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=XM.join(zM(),e.schema.toString()),i=await ZM.openEnvironment(n,e.table),o=await JM.deleteRecords(i,s,e.hash_values);try{t===!0&&await jM(e,o)}catch(c){eP.error(`unable to write transaction due to ${c.message}`)}return rT(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(tP,"lmdbDeleteRecords");function rT(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(rT,"createDeleteResponse")});var Wu=h((WZ,nT)=>{"use strict";var rP=T(),QZ=Es();function Qu(e,t){let r=Object.create(null);if(t.length===1&&rP.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(Qu,"parseRow");function sP(e,t,r,s){let n=Qu(r,e);s.push(n)}a(sP,"searchAll");function nP(e,t,r,s){let n=Qu(r,e);s[t]=n}a(nP,"searchAllToMap");function iP(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(iP,"iterateDBI");function hs(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(hs,"pushResults");function aP(e,t,r,s,n,i){t.toString().endsWith(e)&&hs(t,r,s,n,i)}a(aP,"endsWith");function oP(e,t,r,s,n,i){t.toString().includes(e)&&hs(t,r,s,n,i)}a(oP,"contains");function cP(e,t,r,s,n,i){t>e&&hs(t,r,s,n,i)}a(cP,"greaterThanCompare");function _P(e,t,r,s,n,i){t>=e&&hs(t,r,s,n,i)}a(_P,"greaterThanEqualCompare");function uP(e,t,r,s,n,i){t<e&&hs(t,r,s,n,i)}a(uP,"lessThanCompare");function lP(e,t,r,s,n,i){t<=e&&hs(t,r,s,n,i)}a(lP,"lessThanEqualCompare");nT.exports={parseRow:Qu,searchAll:sP,searchAllToMap:nP,iterateDBI:iP,endsWith:aP,contains:oP,greaterThanCompare:cP,greaterThanEqualCompare:_P,lessThanCompare:uP,lessThanEqualCompare:lP,pushResults:hs}});var nn=h((XZ,uT)=>{"use strict";var Ut=X(),EP=g(),ft=Es(),kr=Ke(),_e=Qe().LMDB_ERRORS_ENUM,JZ=b(),dP=T(),Yt=Wu(),ZZ=require("lmdb"),{OVERFLOW_MARKER:iT,MAX_SEARCH_KEY_LENGTH:hP}=kr,ci={lazy:!0};function aT(e,t,r,s,n=!1,i=void 0,o=void 0){let c=Object.create(null),_=Ut.openDBI(e,r);_[kr.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r);let u=Ju(e,t,r);for(let{key:l,value:E}of _.getRange({start:n?void 0:!1,end:n?!1:void 0,limit:i,offset:o,reverse:n}))s(u(l,E),E,c,t,r);return c}a(aT,"iterateFullIndex");function _i(e,t,r,s,n,i=!1,o=void 0,c=void 0,_=!1,u=!1){let l=[[],[]],E=Ut.openDBI(e,r),d=Ju(e,t,r);E[kr.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r);let S=i===!0?s:n,m=i===!0?n:s,R=i===!0?!_:!u,w=i===!0?u:_;for(let{key:U,value:B}of E.getRange({start:m,end:S,reverse:i,limit:o,offset:c,inclusiveEnd:R,exclusiveStart:w}))Yt.pushResults(d(U,B),B,l,t,r);return l}a(_i,"iterateRangeBetween");function Ju(e,t,r){let s;return function(n,i){if(typeof n=="string"&&n.endsWith(iT)){if(!s)if(t)s=Ut.openDBI(e,t);else{let c=Ut.listDBIs(e);for(let _=0,u=c.length;_<u&&(s=Ut.openDBI(e,c[_]),!s[kr.DBI_DEFINITION_NAME].is_hash_attribute);_++);}n=s.get(i,ci)[r]}return n}}a(Ju,"getOverflowCheck");function SP(e,t,r,s=!1,n=void 0,i=void 0){if(ft.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);ho(r),r=ui(e,r);let o=[],c=Ut.openDBI(e,t);for(let{key:_,value:u}of c.getRange({start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}))Yt.searchAll(r,_,u,o);return o}a(SP,"searchAll");function fP(e,t,r,s=!1,n=void 0,i=void 0){if(ft.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);return ho(r),r=ui(e,r),aT(e,t,t,Yt.searchAllToMap.bind(null,r),s,n,i)}a(fP,"searchAllToMap");function TP(e,t,r=!1,s=void 0,n=void 0){if(ft.validateEnv(e),t===void 0)throw new Error(_e.ATTRIBUTE_REQUIRED);return aT(e,void 0,t,Yt.iterateDBI,r,s,n)}a(TP,"iterateDBI");function mP(e,t){if(ft.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);return Ut.statDBI(e,t).entryCount}a(mP,"countAll");function RP(e,t,r,s,n=!1,i=void 0,o=void 0){xr(e,r,s);let c=Ut.openDBI(e,r);s=ft.convertKeyValueToWrite(s);let _=[[],[]];if(c[kr.DBI_DEFINITION_NAME].is_hash_attribute){t=r;let u=c.get(s,ci);u!==void 0&&Yt.pushResults(s,u,_,t,r)}else for(let u of c.getValues(s,{reverse:n,limit:i,offset:o}))Yt.pushResults(s,u,_,t,r);return _}a(RP,"equals");function AP(e,t,r){return xr(e,t,r),Ut.openDBI(e,t).getValuesCount(r)}a(AP,"count");function pP(e,t,r,s,n=!1,i=void 0,o=void 0){xr(e,r,s);let c=[[],[]],_=Ut.openDBI(e,r);_[kr.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r),s=ft.convertKeyValueToWrite(s);let u=!0;if(typeof s=="number"&&(u=!1),n===!0){let l;for(let E of _.getKeys({start:s}))if(!E.startsWith(s)){l=E;break}l!==void 0&&(Number.isInteger(o)?o++:i++);for(let{key:E,value:d}of _.getRange({start:l,end:void 0,reverse:n,limit:i,offset:o}))if(E!==l){if(E.toString().startsWith(s))Yt.pushResults(E,d,c,t,r);else if(u===!0)break}}else for(let{key:l,value:E}of _.getRange({start:s,reverse:n,limit:i,offset:o}))if(l.toString().startsWith(s))Yt.pushResults(l,E,c,t,r);else if(u===!0)break;return c}a(pP,"startsWith");function OP(e,t,r,s,n=!1,i=void 0,o=void 0){return oT(e,t,r,s,n,i,o,!0)}a(OP,"endsWith");function oT(e,t,r,s,n=!1,i=void 0,o=void 0,c=!1){xr(e,r,s);let _=[[],[]],u=Ut.openDBI(e,r);u[kr.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r);let l=Ju(e,t,r);o=Number.isInteger(o)?o:0;for(let d of u.getKeys({end:n?!1:void 0,reverse:n})){if(i===0)break;let S=d.toString();if(S.endsWith(iT))for(let m of u.getValues(d)){let R=l(d,m);(c?R.endsWith(s):R.includes(s))&&E(R,m)}else if(c?S.endsWith(s):S.includes(s))if(u[kr.DBI_DEFINITION_NAME].is_hash_attribute)E(d,d);else for(let m of u.getValues(d))E(d,m)}function E(d,S){if(o>0){o--;return}i!==0&&(Yt.pushResults(d,S,_,t,r),i--)}return a(E,"found_match"),_}a(oT,"contains");function NP(e,t,r,s,n=!1,i=void 0,o=void 0){xr(e,r,s);let c=typeof s,_;return c==="string"?_="\uFFFF":c==="number"?_=1/0:c==="boolean"&&(_=!0),_i(e,t,r,s,_,n,i,o,!0,!1)}a(NP,"greaterThan");function gP(e,t,r,s,n=!1,i=void 0,o=void 0){xr(e,r,s);let c=typeof s,_;return c==="string"?_="\uFFFF":c==="number"?_=1/0:c==="boolean"&&(_=!0),_i(e,t,r,s,_,n,i,o,!1,!1)}a(gP,"greaterThanEqual");function IP(e,t,r,s,n=!1,i=void 0,o=void 0){xr(e,r,s);let c=typeof s,_;return c==="string"?_="\0":c==="number"?_=-1/0:c==="boolean"&&(_=!1),_i(e,t,r,_,s,n,i,o,!1,!0)}a(IP,"lessThan");function bP(e,t,r,s,n=!1,i=void 0,o=void 0){xr(e,r,s);let c=typeof s,_;return c==="string"?_="\0":c==="number"?_=-1/0:c==="boolean"&&(_=!1),_i(e,t,r,_,s,n,i,o,!1,!1)}a(bP,"lessThanEqual");function CP(e,t,r,s,n,i=!1,o=void 0,c=void 0){if(ft.validateEnv(e),r===void 0)throw new Error(_e.ATTRIBUTE_REQUIRED);if(s===void 0)throw new Error(_e.START_VALUE_REQUIRED);if(n===void 0)throw new Error(_e.END_VALUE_REQUIRED);if(s=ft.convertKeyValueToWrite(s),n=ft.convertKeyValueToWrite(n),s>n)throw new Error(_e.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return _i(e,t,r,s,n,i,o,c)}a(CP,"between");function wP(e,t,r,s){if(ft.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);if(ho(r),r=ui(e,r),s===void 0)throw new Error(_e.ID_REQUIRED);let n=null,i=e.dbis[t].get(s,r.length<3?ci:void 0);return i&&(n=Yt.parseRow(i,r)),n}a(wP,"searchByHash");function UP(e,t,r){if(ft.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(_e.ID_REQUIRED);let s=!0;return e.dbis[t].get(r,ci)===void 0&&(s=!1),s}a(UP,"checkHashExists");function LP(e,t,r,s,n=[]){_T(e,t,r,s,n);let i=cT(e,t,r,s,n);return Object.values(i)}a(LP,"batchSearchByHash");function yP(e,t,r,s,n=[]){return _T(e,t,r,s,n),cT(e,t,r,s,n)}a(yP,"batchSearchByHashToMap");function cT(e,t,r,s,n=[]){r=ui(e,r);let i=Object.create(null),o=r.length<3?ci:void 0;for(let c=0;c<s.length;c++){let _=s[c];try{let u=e.dbis[t].get(_,o);if(u){let l=Yt.parseRow(u,r);i[_]=l}else n.push(_)}catch(u){throw EP.warn(u),u}}return i}a(cT,"batchHashSearch");function _T(e,t,r,s,n){if(ft.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);if(ho(r),!Array.isArray(s))throw s===void 0?new Error(_e.IDS_REQUIRED):new Error(_e.IDS_MUST_BE_ARRAY);Array.isArray(n)||(n=[])}a(_T,"initializeBatchSearchByHash");function ho(e){if(!Array.isArray(e))throw e===void 0?new Error(_e.FETCH_ATTRIBUTES_REQUIRED):new Error(_e.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(ho,"validateFetchAttributes");function xr(e,t,r){if(ft.validateEnv(e),t===void 0)throw new Error(_e.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(_e.SEARCH_VALUE_REQUIRED);if(r?.length>hP)throw new Error(_e.SEARCH_VALUE_TOO_LARGE)}a(xr,"validateComparisonFunctions");function ui(e,t){return t.length===1&&dP.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=Ut.listDBIs(e)),t}a(ui,"setGetWholeRowAttributes");uT.exports={searchAll:SP,searchAllToMap:fP,count:AP,countAll:mP,equals:RP,startsWith:pP,endsWith:OP,contains:oT,searchByHash:wP,setGetWholeRowAttributes:ui,batchSearchByHash:LP,batchSearchByHashToMap:yP,checkHashExists:UP,iterateDBI:TP,greaterThan:NP,greaterThanEqual:gP,lessThan:IP,lessThanEqual:bP,between:CP}});var li=h((jZ,hT)=>{var lT=require("lodash"),ET=de(),Q=require("joi"),DP=b(),{hdb_schema_table:Kt,checkValidTable:dT}=Rr(),{handleHDBError:MP,hdb_errors:PP}=D(),{HTTP_STATUS_CODES:BP}=PP,zZ=Q.object({schema:Kt,table:Kt,hash_values:Q.array().min(1).items(Q.alternatives(Q.string(),Q.number())).required(),get_attributes:Q.array().min(1).items(Kt).required()}),vP=Q.object({schema:Kt,table:Kt,search_attribute:Kt,search_value:Q.any().required(),get_attributes:Q.array().min(1).items(Kt).required(),desc:Q.bool(),limit:Q.number().integer().min(1),offset:Q.number().integer().min(0)}),HP=Q.object({schema:Kt,table:Kt,operator:Q.string().valid("and","or").default("and").lowercase(),offset:Q.number().integer().min(0),limit:Q.number().integer().min(1),get_attributes:Q.array().min(1).items(Kt).required(),conditions:Q.array().min(1).items(Q.object({search_attribute:Kt,search_type:Q.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between").required(),search_value:Q.when("search_type",{switch:[{is:"equals",then:Q.any()},{is:"between",then:Q.array().items(Q.alternatives([Q.string(),Q.number()])).length(2)}],otherwise:Q.alternatives(Q.string(),Q.number())}).required()})).required()});hT.exports=function(e,t){let r=null;switch(t){case"value":r=ET.validateBySchema(e,vP);break;case"hashes":let i=function(o){n?n+=". "+o:n=o};var s=i;a(i,"addError");let n;i(dT("schema",e.schema)),i(dT("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=ET.validateBySchema(e,HP);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=DP.checkGlobalSchemaTable(e.schema,e.table);if(n)return MP(new Error,n,BP.NOT_FOUND);let o=global.hdb_schema[e.schema][e.table].attributes,c=[...e.get_attributes];if(t==="value"&&c.push(e.search_attribute),t==="conditions")for(let u=0,l=e.conditions.length;u<l;u++){let E=e.conditions[u];c.push(E.search_attribute)}let _=lT.filter(c,u=>u!=="*"&&u.attribute!=="*"&&!lT.some(o,l=>l===u||l.attribute===u||l.attribute===u.attribute));if(_&&_.length>0){let u=_.join(", ");return u=u.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${u}'`)}}return r}});var Zu=h((eX,ST)=>{"use strict";var qP=X(),GP=li(),FP=require("path"),{getBaseSchemaPath:VP}=re();ST.exports=kP;function kP(e){let t=GP(e,"hashes");if(t)throw t;let r=FP.join(VP(),e.schema.toString());return qP.openEnvironment(r,e.table)}a(kP,"initialize")});var Xu=h((tX,fT)=>{"use strict";var xP=nn(),$P=Zu();fT.exports=YP;async function YP(e){try{let t=await $P(e),r=global.hdb_schema[e.schema][e.table];return xP.batchSearchByHashToMap(t,r.hash_attribute,e.get_attributes,e.hash_values)}catch(t){throw t}}a(YP,"lmdbGetDataByHash")});var Ss=h((rX,TT)=>{"use strict";var So=class{constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};a(So,"SearchByHashObject");TT.exports=So});var RT=h((nX,mT)=>{"use strict";var sX=Ss(),KP=nn(),QP=Zu();mT.exports=WP;async function WP(e){try{let t=await QP(e),r=global.hdb_schema[e.schema][e.table];return KP.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}catch(t){throw t}}a(WP,"lmdbSearchByHash")});var Qt=h((iX,AT)=>{"use strict";var fo=class{constructor(t,r,s,n,i,o,c,_=!1,u=void 0,l=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=_,this.limit=u,this.offset=l}};a(fo,"SearchObject");AT.exports=fo});var To=h((aX,IT)=>{"use strict";var Je=nn(),JP=X(),ZP=require("path"),XP=b(),L=Ke(),fs=T(),{getBaseSchemaPath:zP}=re(),jP=ls(),pT=Qe().LMDB_ERRORS_ENUM,{compareKeys:an}=require("ordered-binary"),pr=fs.SEARCH_WILDCARDS;async function eB(e,t,r){let s;e.schema===fs.SYSTEM_SCHEMA_NAME?s=jP[e.table]:s=global.hdb_schema[e.schema][e.table];let n=gT(e,s.hash_attribute,r,t);return OT(e,n,s.hash_attribute,r)}a(eB,"prepSearch");async function OT(e,t,r,s){let n=ZP.join(zP(),e.schema.toString()),i=await JP.openEnvironment(n,e.table),o=NT(i,e,t,r);if([L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,L.SEARCH_TYPES.SEARCH_ALL,L.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(sB(e,r)===!1)return s===!0?rB(o):o[1];let _=o[0];return s===!0?Je.batchSearchByHashToMap(i,r,e.get_attributes,_):Je.batchSearchByHash(i,r,e.get_attributes,_)}a(OT,"executeSearch");function NT(e,t,r,s){let n,i=s;t.get_attributes.indexOf(s)<0&&(i=void 0);let{reverse:o,limit:c,offset:_}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,_=Number.isInteger(_)?_:void 0,r){case L.SEARCH_TYPES.EQUALS:n=Je.equals(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.CONTAINS:n=Je.contains(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.ENDS_WITH:case L.SEARCH_TYPES._ENDS_WITH:n=Je.endsWith(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.STARTS_WITH:case L.SEARCH_TYPES._STARTS_WITH:n=Je.startsWith(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Je.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Je.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case L.SEARCH_TYPES.SEARCH_ALL:return Je.searchAll(e,s,t.get_attributes,o,c,_);case L.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Je.searchAllToMap(e,s,t.get_attributes,o,c,_);case L.SEARCH_TYPES.BETWEEN:n=Je.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,_);break;case L.SEARCH_TYPES.GREATER_THAN:case L.SEARCH_TYPES._GREATER_THAN:n=Je.greaterThan(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.GREATER_THAN_EQUAL:case L.SEARCH_TYPES._GREATER_THAN_EQUAL:n=Je.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.LESS_THAN:case L.SEARCH_TYPES._LESS_THAN:n=Je.lessThan(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.LESS_THAN_EQUAL:case L.SEARCH_TYPES._LESS_THAN_EQUAL:n=Je.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,_);break;default:return Object.create(null)}return n}a(NT,"searchByType");function tB(e){let t=e.search_type,r=e.search_attribute,s=e.search_value;switch(t){case L.SEARCH_TYPES.EQUALS:return n=>n[r]===s;case L.SEARCH_TYPES.CONTAINS:return n=>typeof n[r]=="string"&&n[r].includes(s);case L.SEARCH_TYPES.ENDS_WITH:case L.SEARCH_TYPES._ENDS_WITH:return n=>typeof n[r]=="string"&&n[r].endsWith(s);case L.SEARCH_TYPES.STARTS_WITH:case L.SEARCH_TYPES._STARTS_WITH:return n=>typeof n[r]=="string"&&n[r].startsWith(s);case L.SEARCH_TYPES.BETWEEN:return n=>{let i=n[r];return an(i,s[0])>=0&&an(i,s[1])<=0};case L.SEARCH_TYPES.GREATER_THAN:case L.SEARCH_TYPES._GREATER_THAN:return n=>an(n[r],s)>0;case L.SEARCH_TYPES.GREATER_THAN_EQUAL:case L.SEARCH_TYPES._GREATER_THAN_EQUAL:return n=>an(n[r],s)>=0;case L.SEARCH_TYPES.LESS_THAN:case L.SEARCH_TYPES._LESS_THAN:return n=>an(n[r],s)<0;case L.SEARCH_TYPES.LESS_THAN_EQUAL:case L.SEARCH_TYPES._LESS_THAN_EQUAL:return n=>an(n[r],s)<=0;default:return Object.create(null)}}a(tB,"filterByType");function rB(e){let t=Object.create(null);for(let r=0,s=e[0].length;r<s;r++)t[e[0][r]]=e[1][r];return t}a(rB,"createMapFromArrays");function sB(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(sB,"checkToFetchMore");function gT(e,t,r,s){if(XP.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),pr.indexOf(n)>-1)return r===!0?L.SEARCH_TYPES.SEARCH_ALL_TO_MAP:L.SEARCH_TYPES.SEARCH_ALL;if(n.indexOf(pr[0])<0&&n.indexOf(pr[1])<0)return c===!0?r===!0?L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:L.SEARCH_TYPES.EQUALS;if(pr.indexOf(i)>=0&&pr.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),L.SEARCH_TYPES.CONTAINS;if(pr.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),L.SEARCH_TYPES.ENDS_WITH;if(pr.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),L.SEARCH_TYPES.STARTS_WITH;if(n.includes(pr[0])||n.includes(pr[1]))return L.SEARCH_TYPES.EQUALS;throw new Error(pT.UNKNOWN_SEARCH_TYPE)}else switch(s){case fs.VALUE_SEARCH_COMPARATORS.BETWEEN:return L.SEARCH_TYPES.BETWEEN;case fs.VALUE_SEARCH_COMPARATORS.GREATER:return L.SEARCH_TYPES.GREATER_THAN;case fs.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return L.SEARCH_TYPES.GREATER_THAN_EQUAL;case fs.VALUE_SEARCH_COMPARATORS.LESS:return L.SEARCH_TYPES.LESS_THAN;case fs.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return L.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(pT.UNKNOWN_SEARCH_TYPE)}}a(gT,"createSearchTypeFromSearchObject");IT.exports={executeSearch:OT,createSearchTypeFromSearchObject:gT,prepSearch:eB,searchByType:NT,filterByType:tB}});var CT=h((cX,bT)=>{"use strict";var oX=Qt(),nB=li(),iB=b(),aB=T(),oB=To();bT.exports=cB;async function cB(e,t){if(!iB.isEmpty(t)&&aB.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=nB(e,"value");if(s)throw s;let n=!0;try{return await oB.prepSearch(e,t,n)}catch(i){throw i}}a(cB,"lmdbGetDataByValue")});var on=h((uX,wT)=>{"use strict";var _X=Qt(),_B=li(),uB=b(),lB=T(),EB=To();wT.exports=dB;async function dB(e,t){if(!uB.isEmpty(t)&&lB.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=_B(e,"value");if(s)throw s;let n=!1;try{return await EB.prepSearch(e,t,n)}catch(i){throw i}}a(dB,"lmdbSearchByValue")});var LT=h((EX,UT)=>{"use strict";var lX=Ke(),mo=class{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}};a(mo,"SearchByConditionsObject");var Ro=class{constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}};a(Ro,"SearchCondition");var Ao=class{constructor(t,r){this.attribute=t,this.desc=r}};a(Ao,"SortAttribute");UT.exports={SearchByConditionsObject:mo,SearchCondition:Ro,SortAttribute:Ao}});var vT=h((hX,BT)=>{"use strict";var dX=LT().SearchByConditionsObject,hB=Qt(),SB=li(),zu=nn(),po=Ke(),PT=To(),fB=Wu(),yT=require("lodash"),{getBaseSchemaPath:TB}=re(),mB=require("path"),RB=X(),{handleHDBError:DT,hdb_errors:AB}=D(),{HTTP_STATUS_CODES:pB}=AB,OB=1e8,NB={lazy:!0};BT.exports=gB;async function gB(e){try{let t=SB(e,"conditions");if(t)throw DT(t,t.message,pB.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=mB.join(TB(),e.schema.toString()),s=await RB.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table],i=yT.sortBy(e.conditions,o=>{if(o.estimated_count===void 0){let c=o.search_type;c===po.SEARCH_TYPES.EQUALS?o.estimated_count=zu.count(s,o.search_attribute,o.search_value):c===po.SEARCH_TYPES.CONTAINS||c===po.SEARCH_TYPES.ENDS_WITH?o.estimated_count=1/0:o.estimated_count=OB}return o.estimated_count});if(!e.operator||e.operator.toLowerCase()==="and"){let[o]=await MT(s,e,i[0],n.hash_attribute),c=s.dbis[n.hash_attribute],_=i.slice(1).map(PT.filterByType),u=_.length,l=[],E=zu.setGetWholeRowAttributes(s,e.get_attributes),d=e.offset>-1?e.offset:0,S=e.limit>-1?e.limit:1/0;e:for(let m of o){let R=c.get(m,NB);for(let w=0;w<u;w++)if(!_[w](R))continue e;if(d>0){d--;continue}if(S<=0)break;S--,l.push(fB.parseRow(R,E))}return l}else{let o=[],c=[];for(let _ of i){let[u]=await MT(s,e,_,n.hash_attribute);c.push(u)}if(o=yT.union(...c),e.limit>0||e.offset>0){let _=Number.isInteger(e.limit)?e.limit:o.length;o=o.splice(e.offset,_)}return zu.batchSearchByHash(s,n.hash_attribute,e.get_attributes,o)}}catch(t){throw DT(t)}}a(gB,"lmdbSearchByConditions");async function MT(e,t,r,s){let n=new hB(t.schema,t.table,void 0,void 0,s,t.get_attributes),i=r.search_type;return n.search_attribute=r.search_attribute,i===po.SEARCH_TYPES.BETWEEN?(n.search_value=r.search_value[0],n.end_value=r.search_value[1]):n.search_value=r.search_value,PT.searchByType(e,n,i,s)}a(MT,"executeConditionSearch")});var Ei=h((SX,HT)=>{"use strict";var IB=T().OPERATIONS_ENUM,Oo=class{constructor(t,r,s,n=void 0){this.operation=IB.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};a(Oo,"DeleteObject");HT.exports=Oo});var ju=h((fX,qT)=>{"use strict";var No=class{constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};a(No,"DropAttributeObject");qT.exports=No});var tl=h((mX,GT)=>{"use strict";var bB=Qt(),CB=Ei(),TX=ju(),tr=T(),wB=b(),el=X(),UB=ls(),LB=on(),yB=oi(),{getBaseSchemaPath:DB}=re(),MB=require("path");GT.exports=PB;async function PB(e,t=!0){let r;e.schema===tr.SYSTEM_SCHEMA_NAME?r=UB[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await vB(e),n=MB.join(DB(),e.schema.toString()),i=await el.openEnvironment(n,e.table);return t===!0&&await BB(e,i,r.hash_attribute),el.dropDBI(i,e.attribute),s}a(PB,"lmdbDropAttribute");async function BB(e,t,r){let s=el.openDBI(t,r),n,i=e.attribute;for(let{key:o,value:c,version:_}of s.getRange({start:!1,versions:!0})){let u={};for(let l in c)l!==i&&(u[l]=c[l]);n=t.dbis[r].put(o,u,_)}await n}a(BB,"removeAttributeFromAllObjects");async function vB(e){let t=new bB(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,tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),s=(await LB(t)).filter(o=>o[tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(wB.isEmptyOrZeroLength(s))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let n=s.map(o=>o[tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new CB(tr.SYSTEM_SCHEMA_NAME,tr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return yB(i)}a(vB,"dropAttributeFromSystem")});var xT=h((RX,kT)=>{"use strict";var HB=tl(),qB=ju(),FT=b(),VT=g(),GB=Qe().LMDB_ERRORS_ENUM;kT.exports=FB;async function FB(e){if(FT.isEmpty(global.hdb_schema[e.schema])||FT.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);let t=global.hdb_schema[e.schema][e.table],r;try{for(let s=0;s<t.attributes.length;s++){r=t.attributes[s].attribute;let n=new qB(e.schema,e.table,r);try{await HB(n,!1)}catch(i){i.message!==GB.DBI_DOES_NOT_EXIST&&VT.error(`unable to drop attribute ${e.schema}.${e.table}.${r}:`+i)}}}catch(s){throw VT.error(`Error dropping attribute ${r}`),s}}a(FB,"lmdbDropAllAttributes")});var rl=h((pX,zT)=>{"use strict";var WT=Qt(),JT=Ei(),ZT=on(),XT=oi(),AX=xT(),ot=T(),$T=b(),YT=X(),{getBaseSchemaPath:VB,getTransactionAuditStorePath:kB}=re(),KT=require("path"),QT=g();zT.exports=xB;async function xB(e){try{if($T.isEmpty(global.hdb_schema[e.schema])||$T.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await $B(e),await YB(e);let t=KT.join(VB(),e.schema.toString());try{await YT.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")QT.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=KT.join(kB(),e.schema.toString());await YT.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")QT.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(xB,"lmdbDropTable");async function $B(e){let t=new WT(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,ot.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[ot.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=await ZT(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 JT(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await XT(n)}a($B,"deleteAttributesFromSystem");async function YB(e){let t=new WT(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,ot.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[ot.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,ot.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,ot.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,s;try{r=await ZT(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 JT(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await XT(n)}catch(i){throw i}}a(YB,"dropTableFromSystem")});var em=h((NX,jT)=>{"use strict";var KB=require("fs-extra"),QB=Qt(),WB=Ss(),JB=Ei(),ZB=rl(),XB=oi(),zB=Xu(),jB=on(),Or=T(),OX=b(),ev=require("path"),{getBaseSchemaPath:tv}=re(),{handleHDBError:rv,hdb_errors:sv}=D(),{HDB_ERROR_MSGS:nv,HTTP_STATUS_CODES:iv}=sv;jT.exports=av;async function av(e){let t;try{t=await ov(e.schema);let r=new QB(Or.SYSTEM_SCHEMA_NAME,Or.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),s=await jB(r);for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await ZB(c)}catch(_){if(_.message!=="invalid environment")throw _}}let n=new JB(Or.SYSTEM_SCHEMA_NAME,Or.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await XB(n);let i=ev.join(tv(),t.toString());await KB.remove(i)}catch(r){throw r}}a(av,"lmdbDropSchema");async function ov(e){let t=new WB(Or.SYSTEM_SCHEMA_NAME,Or.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,s;try{r=await zB(t)}catch(n){throw n}for(let n in r)r[n].name===e&&(s=e);if(!s)throw rv(new Error,nv.SCHEMA_NOT_FOUND(e),iv.NOT_FOUND,void 0,void 0,!0);return s}a(ov,"validateDropSchema")});var sl=h((gX,tm)=>{"use strict";var go=class{constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};a(go,"CreateTableObject");tm.exports=go});var sm=h((bX,rm)=>{"use strict";var cv=require("path"),_v=require("fs-extra"),Io=X(),{getTransactionAuditStorePath:uv}=re(),nl=Ke(),IX=sl();rm.exports=lv;async function lv(e){let t;try{let r=cv.join(uv(),e.schema.toString());await _v.mkdirp(r),t=await Io.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{Io.createDBI(t,nl.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),Io.createDBI(t,nl.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),Io.createDBI(t,nl.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(lv,"createTransactionsAuditEnvironment")});var om=h((CX,am)=>{"use strict";var il=T(),nm=X(),Ev=Xs(),dv=require("path"),{getSystemSchemaPath:hv,getBaseSchemaPath:Sv}=re(),fv=ls(),Tv=za(),al=Xa(),mv=g(),Rv=sm(),cl=fv.hdb_table,im=[];for(let e=0;e<cl.attributes.length;e++)im.push(cl.attributes[e].attribute);am.exports=Av;async function Av(e,t){let r=dv.join(Sv(),t.schema.toString()),s=new al(t.schema,t.table,il.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=new al(t.schema,t.table,il.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new al(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await nm.createEnvironment(r,t.table),e!==void 0){let o=await nm.openEnvironment(hv(),il.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await Ev.insertRecords(o,cl.hash_attribute,im,[e]),await ol(s),await ol(n),await ol(i)}await Rv(t)}catch(o){throw o}}a(Av,"lmdbCreateTable");async function ol(e){try{await Tv(e)}catch(t){mv.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(ol,"createAttribute")});var _m=h((wX,cm)=>{"use strict";var pv=ja(),Ov=ro(),Nv=io(),cn=T(),gv=Xs().updateRecords,Iv=X(),bv=require("path"),{getBaseSchemaPath:Cv}=re(),wv=ai(),Uv=g();cm.exports=Lv;async function Lv(e){try{let{schema_table:t,attributes:r}=pv(e);Ov(e,r,t.hash_attribute),e.schema!==cn.SYSTEM_SCHEMA_NAME&&(r.includes(cn.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(cn.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(cn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(cn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await Nv(e.hdb_auth_header,t,r),n=bv.join(Cv(),e.schema.toString()),i=await Iv.openEnvironment(n,e.table),o=await gv(i,t.hash_attribute,r,e.records,e[cn.CLUSTERING_FLAG]!==!0);try{await wv(e,o)}catch(c){Uv.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(Lv,"lmdbUpdateRecords")});var lm=h((UX,um)=>{"use strict";var yv=T().OPERATIONS_ENUM,bo=class{constructor(t,r,s,n=void 0){this.operation=yv.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};a(bo,"UpsertObject");um.exports=bo});var dm=h((yX,Em)=>{"use strict";var LX=lm(),Dv=ja(),Mv=ro(),Pv=io(),_n=T(),Bv=Xs().upsertRecords,vv=X(),Hv=require("path"),{getBaseSchemaPath:qv}=re(),Gv=ai(),Fv=g(),{handleHDBError:Vv,hdb_errors:kv}=D();Em.exports=xv;async function xv(e){let t;try{t=Dv(e)}catch(_){throw Vv(_,_.message,kv.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;Mv(e,s,r.hash_attribute),e.schema!==_n.SYSTEM_SCHEMA_NAME&&(s.includes(_n.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||s.push(_n.TIME_STAMP_NAMES_ENUM.CREATED_TIME),s.includes(_n.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||s.push(_n.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await Pv(e.hdb_auth_header,r,s),i=Hv.join(qv(),e.schema.toString()),o=await vv.openEnvironment(i,e.table),c=await Bv(o,r.hash_attribute,s,e.records,e[_n.CLUSTERING_FLAG]!==!0);try{await Gv(e,c)}catch(_){Fv.error(`unable to write transaction due to ${_.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:n,txn_time:c.txn_time}}a(xv,"lmdbUpsertRecords")});var Rm=h((DX,mm)=>{"use strict";var $v=Qt(),hm=b(),Sm=g(),Yv=on(),fm=T(),Kv=Ku().deleteRecords,Qv=X(),Wv=require("path"),{getBaseSchemaPath:Jv}=re(),{promisify:Zv}=require("util"),Xv=Zv(setTimeout),Tm=1e4,zv=10;mm.exports=jv;async function jv(e){let t=global.hdb_schema[e.schema][e.table].hash_attribute;if(hm.isEmptyOrZeroLength(t))throw new Error(`Could not retrieve hash attribute for schema: ${e.schema} table: ${e.table}`);let r=Date.parse(e.date),s;try{let n=new $v(e.schema,e.table,fm.TIME_STAMP_NAMES_ENUM.CREATED_TIME,r,void 0,[t]);s=await Yv(n,fm.VALUE_SEARCH_COMPARATORS.LESS)}catch(n){throw Sm.error(`Error searching for date: ${e.date} in schema: ${e.schema} table: ${e.table}`),n}return hm.isEmptyOrZeroLength(s)?(Sm.trace("No records found to delete"),{message:"No records found to delete"}):await eH(e,s,t)}a(jv,"lmdbDeleteRecordsBefore");async function eH(e,t,r){let s=Wv.join(Jv(),e.schema.toString()),n=await Qv.openEnvironment(s,e.table),i={message:"",deleted_hashes:[],skipped_hashes:[]};for(let o=0,c=t.length;o<c;o+=Tm){let _=t.slice(o,o+Tm),u=[];for(let l=0,E=_.length;l<E;l++)u.push(_[l][r]);try{let l=await Kv(n,r,u);i.deleted_hashes=i.deleted_hashes.concat(l.deleted),i.skipped_hashes=i.skipped_hashes.concat(l.skipped)}catch(l){throw l}await Xv(zv)}return i.message=`${i.deleted_hashes.length} of ${i.deleted_hashes.length+i.skipped_hashes.length} records successfully deleted`,i}a(eH,"chunkDeletes")});var pm=h((MX,Am)=>{"use strict";var Co=class{constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};a(Co,"DeleteBeforeObject");Am.exports=Co});var Nm=h((PX,Om)=>{"use strict";var wo=class{constructor(t=void 0,r=void 0,s=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=s}};a(wo,"DeleteAuditLogsBeforeResults");Om.exports=wo});var bm=h((vX,Im)=>{"use strict";var _l=X(),{getTransactionAuditStorePath:tH}=re(),BX=pm(),rH=require("path"),di=Ke(),sH=b(),gm=Nm(),nH=require("util").promisify,iH=nH(setTimeout),aH=1e4,oH=100;Im.exports=cH;async function cH(e){let t=rH.join(tH(),e.schema),r=await _l.openEnvironment(t,e.table,!0),s=_l.listDBIs(r);_l.initializeDBIs(r,di.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new gm;do n=await _H(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 iH(oH);while(n.transactions_deleted>0);return i}a(cH,"deleteAuditLogsBefore");async function _H(e,t){let r=new gm;try{let s=e.dbis[di.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[di.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];sH.isEmpty(c)||(n=e.dbis[di.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let _=0;_<o.hash_values.length;_++)n=e.dbis[di.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[_],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>aH)break}return await n,r}catch(s){throw s}}a(_H,"deleteTransactions")});var Mm=h((HX,Dm)=>{"use strict";var ul=X(),un=Ke(),Cm=Es(),ll=T(),wm=b(),{getTransactionAuditStorePath:uH}=re(),lH=require("path"),EH=nn(),Uo=en(),dH=g();Dm.exports=hH;async function hH(e){let t=lH.join(uH(),e.schema),r=await ul.openEnvironment(t,e.table,!0),s=ul.listDBIs(r);ul.initializeDBIs(r,un.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;switch(e.search_type){case ll.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return Um(r,e.search_values);case ll.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return n=global.hdb_schema[e.schema][e.table].hash_attribute,fH(r,e.search_values,n);case ll.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return SH(r,e.search_values);default:return Um(r)}}a(hH,"readAuditLog");function Um(e,t=[0,Cm.getMicroTime()]){wm.isEmpty(t[0])&&(t[0]=0),wm.isEmpty(t[1])&&(t[1]=Cm.getMicroTime());let r=[];try{let s=e.dbis[un.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let i of s.getKeys({start:t[1]}))if(i!==t[1]){n=i;break}for(let{value:i}of s.getRange({start:t[0],end:n})){let o=Object.assign(new Uo,i);r.push(o)}return r}catch(s){throw s}}a(Um,"searchTransactionsByTimestamp");function SH(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[un.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(n))i.push(o);r.set(n,ym(e,i))}return Object.fromEntries(r)}a(SH,"searchTransactionsByUsername");function fH(e,t,r){let s=new Map;for(let c=0,_=t.length;c<_;c++){let u=t[c],l=EH.equals(e,un.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,un.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,u);for(let E=0,d=l[0].length;E<d;E++){let S=l[0][E],m=Number(S);s.has(m)?s.get(m).push(u.toString()):s.set(m,[u.toString()])}}let n=Array.from(s.keys()),i=ym(e,n),o=new Map;for(let c=0;c<i.length;c++){let _=i[c],u=_.timestamp,l=s.get(u);Lm(_,"records",r,l,o),Lm(_,"original_records",r,l,o)}return Object.fromEntries(o)}a(fH,"searchTransactionsByHashValues");function Lm(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],_=c[r].toString();if(s.indexOf(_)>=0)if(n.has(_)){let u=n.get(_),l=u[u.length-1];if(l.timestamp===i)l[t]=[c];else{let E=new Uo(e.operation,e.user_name,i,void 0);E[t]=[c],u.push(E)}}else{let u=new Uo(e.operation,e.user_name,i,void 0);u[t]=[c],n.set(_,[u])}}}a(Lm,"loopRecords");function ym(e,t){let r=[];try{let s=e.dbis[un.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 Uo,i);r.push(o)}}catch(i){dH.warn(i)}return r}catch(s){throw s}}a(ym,"batchSearchTransactions")});var Bm=h((qX,Pm)=>{"use strict";var TH=require("path"),{getBaseSchemaPath:mH}=re(),RH=X();Pm.exports={writeTransaction:AH};async function AH(e,t,r){let s=TH.join(mH(),e);return(await RH.openEnvironment(s,t)).transaction(r)}a(AH,"writeTransaction")});var Hm=h((GX,vm)=>{"use strict";var pH=require("path"),{getBaseSchemaPath:OH}=re(),NH=X();vm.exports={flush:gH};async function gH(e,t){let r=pH.join(OH(),e.toString());return(await NH.openEnvironment(r,t.toString())).flushed}a(gH,"flush")});var Gm=h((FX,qm)=>{"use strict";var Ae=g(),{handleHDBError:IH}=D(),bH=pu(),CH=za(),wH=xu(),UH=Zf(),LH=oi(),yH=Xu(),DH=RT(),MH=CT(),PH=on(),BH=vT(),vH=em(),HH=om(),qH=_m(),GH=dm(),FH=Rm(),VH=bm(),kH=rl(),xH=tl(),$H=Mm(),YH=Bm(),KH=Hm(),Lo=class extends bH{async searchByConditions(t){try{return BH(t)}catch(r){throw Ae.error(r),r}}async getDataByHash(t){try{return await yH(t)}catch(r){throw Ae.error(r),r}}async searchByHash(t){try{return await DH(t)}catch(r){throw Ae.error(r),r}}async getDataByValue(t,r){try{return await MH(t,r)}catch(s){throw Ae.error(s),s}}async searchByValue(t){try{return await PH(t)}catch(r){throw Ae.error(r),r}}async createSchema(t){try{return await UH(t)}catch(r){throw Ae.error(r),r}}async dropSchema(t){try{return await vH(t)}catch(r){throw Ae.error(r),r}}async createTable(t,r){try{return await HH(t,r)}catch(s){throw Ae.error(s),s}}async dropTable(t){try{return await kH(t)}catch(r){throw Ae.error(r),r}}async createAttribute(t){try{return await CH(t)}catch(r){throw Ae.error(r),r}}async createRecords(t){try{return await wH(t)}catch(r){throw Ae.error(r),r}}async updateRecords(t){try{return await qH(t)}catch(r){throw Ae.error(r),r}}async upsertRecords(t){try{return await GH(t)}catch(r){throw IH(r,null,null,Ae.ERR,r)}}async deleteRecords(t){try{return await LH(t)}catch(r){throw Ae.error(r),r}}async deleteRecordsBefore(t){try{return await FH(t)}catch(r){throw Ae.error(r),r}}async dropAttribute(t){try{return await xH(t)}catch(r){throw Ae.error(r),r}}async deleteAuditLogsBefore(t){try{return await VH(t)}catch(r){throw Ae.error(r),r}}async readAuditLog(t){try{return await $H(t)}catch(r){throw Ae.error(r),r}}writeTransaction(t,r,s){return YH.writeTransaction(t,r,s)}flush(t,r){return KH.flush(t,r)}};a(Lo,"LMDBBridge");qm.exports=Lo});var Nr=h((VX,Vm)=>{"use strict";var QH=Gm(),WH=pu(),JH=V();JH.initSync();var Fm;function ZH(){return Fm instanceof WH?Fm:new QH}a(ZH,"getBridge");Vm.exports=ZH()});var Ym=h((kX,$m)=>{"use strict";var km=require("lodash"),hi=require("mathjs"),XH=require("jsonata"),xm=b();$m.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?km.uniqWith(e,km.isEqual):e,searchJSON:zH,mad:Si.bind(null,hi.mad),mean:Si.bind(null,hi.mean),mode:Si.bind(null,hi.mode),prod:Si.bind(null,hi.prod),median:Si.bind(null,hi.median)};function Si(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(Si,"aggregateFunction");function zH(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(xm.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),xm.isEmpty(this.__ala__.res[r])){let s=XH(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(zH,"searchJSON")});var Qm=h((xX,Km)=>{"use strict";var he=require("moment"),El="YYYY-MM-DDTHH:mm:ss.SSSZZ";he.suppressDeprecationWarnings=!0;Km.exports={current_date:()=>he().utc().format("YYYY-MM-DD"),current_time:()=>he().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return he(e).utc().format("YYYY");case"month":return he(e).utc().format("MM");case"day":return he(e).utc().format("DD");case"hour":return he(e).utc().format("HH");case"minute":return he(e).utc().format("mm");case"second":return he(e).utc().format("ss");case"millisecond":return he(e).utc().format("SSS");default:break}},date:e=>he(e).utc().format(El),date_format:(e,t)=>he(e).utc().format(t),date_add:(e,t,r)=>he(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>he(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let s=he(e).utc(),n=he(t).utc();return r?s.diff(n,r,!0):s.diff(n)},now:()=>he().utc().valueOf(),get_server_time:()=>he().format(El),offset_utc:(e,t)=>he(e).utc().utcOffset(t).format(El)}});var Xm=h(($X,Zm)=>{"use strict";var jH=require("@turf/area"),eq=require("@turf/length"),tq=require("@turf/circle"),rq=require("@turf/difference"),sq=require("@turf/distance"),nq=require("@turf/boolean-contains"),iq=require("@turf/boolean-equal"),aq=require("@turf/boolean-disjoint"),oq=require("@turf/helpers"),Wm=T(),x=b();Zm.exports={geoArea:cq,geoLength:_q,geoCircle:uq,geoDifference:lq,geoDistance:Jm,geoNear:Eq,geoContains:dq,geoEqual:hq,geoCrosses:Sq,geoConvert:fq};var dl="geo1 is required",hl="geo2 is required";function cq(e){if(x.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=x.autoCast(e)),jH.default(e)}a(cq,"geoArea");function _q(e,t){if(x.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=x.autoCast(e)),eq.default(e,{units:t||"kilometers"})}a(_q,"geoLength");function uq(e,t,r){if(x.isEmpty(e))throw new Error("point is required");if(x.isEmpty(t))throw new Error("radius is required");return typeof e=="string"&&(e=x.autoCast(e)),tq.default(e,t,{units:r||"kilometers"})}a(uq,"geoCircle");function lq(e,t){if(x.isEmpty(e))throw new Error("poly1 is required");if(x.isEmpty(t))throw new Error("poly2 is required");return typeof e=="string"&&(e=x.autoCast(e)),typeof t=="string"&&(t=x.autoCast(t)),rq(e,t)}a(lq,"geoDifference");function Jm(e,t,r){if(x.isEmpty(e))throw new Error("point1 is required");if(x.isEmpty(t))throw new Error("point2 is required");return typeof e=="string"&&(e=x.autoCast(e)),typeof t=="string"&&(t=x.autoCast(t)),sq.default(e,t,{units:r||"kilometers"})}a(Jm,"geoDistance");function Eq(e,t,r,s){if(x.isEmpty(e))throw new Error("point1 is required");if(x.isEmpty(t))throw new Error("point2 is required");if(x.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=x.autoCast(e)),typeof t=="string"&&(t=x.autoCast(t)),isNaN(r))throw new Error("distance must be a number");return Jm(e,t,s)<=r}a(Eq,"geoNear");function dq(e,t){if(x.isEmpty(e))throw new Error(dl);if(x.isEmpty(e))throw new Error(hl);return typeof e=="string"&&(e=x.autoCast(e)),typeof t=="string"&&(t=x.autoCast(t)),nq.default(e,t)}a(dq,"geoContains");function hq(e,t){if(x.isEmpty(e))throw new Error(dl);if(x.isEmpty(e))throw new Error(hl);return typeof e=="string"&&(e=x.autoCast(e)),typeof t=="string"&&(t=x.autoCast(t)),iq.default(e,t)}a(hq,"geoEqual");function Sq(e,t){if(x.isEmpty(e))throw new Error(dl);if(x.isEmpty(e))throw new Error(hl);return typeof e=="string"&&(e=x.autoCast(e)),typeof t=="string"&&(t=x.autoCast(t)),!aq.default(e,t)}a(Sq,"geoCrosses");function fq(e,t,r){if(x.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(x.isEmpty(t))throw new Error("geo_type is required");if(x.isEmpty(Wm.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(Wm.GEO_CONVERSION_ENUM).join(",")}`);return oq[t](e,r)}a(fq,"geoConvert")});var yo=h((YX,zm)=>{var Ts=Ym(),Tt=Qm(),rr=Xm();zm.exports=e=>{e.aggr.mad=e.aggr.MAD=Ts.mad,e.aggr.mean=e.aggr.MEAN=Ts.mean,e.aggr.mode=e.aggr.MODE=Ts.mode,e.aggr.prod=e.aggr.PROD=Ts.prod,e.aggr.median=e.aggr.MEDIAN=Ts.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=Ts.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=Ts.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=Tt.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Tt.current_time,e.fn.extract=e.fn.EXTRACT=Tt.extract,e.fn.date=e.fn.DATE=Tt.date,e.fn.date_format=e.fn.DATE_FORMAT=Tt.date_format,e.fn.date_add=e.fn.DATE_ADD=Tt.date_add,e.fn.date_sub=e.fn.DATE_SUB=Tt.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Tt.date_diff,e.fn.now=e.fn.NOW=Tt.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Tt.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Tt.get_server_time,e.fn.getdate=e.fn.GETDATE=Tt.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Tt.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=rr.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=rr.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=rr.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=rr.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=rr.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=rr.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=rr.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=rr.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=rr.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=rr.geoNear}});var tR=h((KX,eR)=>{"use strict";var fi=require("lodash"),Pe=require("alasql");Pe.options.cache=!1;var Tq=yo(),jm=require("clone"),Do=require("recursive-iterator"),v=g(),q=b(),ln=Nr(),mq=T(),{hdb_errors:Rq}=D(),Aq="IS NULL",Ti="There was a problem performing this search. Please check the logs and try again.";Tq(Pe);var Mo=class{constructor(t,r){if(q.isEmpty(t))throw v.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(),q.backtickASTSchemaItems(this.statement)}async search(){let t;try{let s=await this._checkEmptySQL();if(!q.isEmptyOrZeroLength(s))return v.trace("No results returned from checkEmptySQL SQLSearch method."),s}catch(s){throw v.error("Error thrown from checkEmptySQL in SQLSearch class method search."),v.error(s),new Error(Ti)}try{let s=await this._getFetchAttributeValues();if(s)return s}catch(s){throw v.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),v.error(s),new Error(Ti)}if(Object.keys(this.data).length===0)return v.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(s){throw v.error("Error thrown from processJoins in SQLSearch class method search."),v.error(s),new Error(Ti)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(s){throw v.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),v.error(s),new Error(Ti)}try{return t=await this._finalSQL(),t}catch(s){throw v.error("Error thrown from finalSQL in SQLSearch class method search."),v.error(s),new Error(Ti)}}_getColumns(){let t=new Do(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(jm(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=fi.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=global.hdb_schema[r.databaseid][r.tableid].hash_attribute,this.data[s].__merged_data={},this.data[s].__merged_attributes=[],this.data[s].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(q.isEmpty(this.statement.where)){v.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new Do(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!q.isEmpty(r)&&r.right)if(q.isNotEmptyAndHasValue(r.right.value)){let s=q.autoCast(r.right.value);[!0,!1].indexOf(s)>=0?r.right=new Pe.yy.LogicValue({value:s}):r.right instanceof Pe.yy.StringValue&&!q.isEmpty(s)&&q.autoCasterIsNumberCheck(s.toString())&&(r.right=new Pe.yy.NumValue({value:s}))}else Array.isArray(r.right)&&r.right.forEach((s,n)=>{let i=q.autoCast(s.value);[!0,!1].indexOf(i)>=0?r.right[n]=new Pe.yy.LogicValue({value:i}):s instanceof Pe.yy.StringValue&&q.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new Pe.yy.NumValue({value:i}))});if(t){v.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new Do(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(!q.isEmpty(mq.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(q.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(q.isEmptyOrZeroLength(r.left.columnid)||q.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(q.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"=":!q.isEmpty(r.right.value)||!q.isEmpty(r.left.value)?s.add(q.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let _=Array.isArray(r.right)?r.right:r.left;for(let u=0;u<_.length;u++)if(_[u].value)s.add(_[u].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(q.isEmptyOrZeroLength(this.all_table_attributes)&&q.isEmptyOrZeroLength(this.statement.from)&&q.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&&fi.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(q.isEmptyOrZeroLength(r)){let s=this.columns.columns.filter(n=>n.as?t.columnid===n.as:!1);q.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(q.isEmptyOrZeroLength(this.all_table_attributes)&&!q.isEmptyOrZeroLength(this.columns.columns))return t;if(q.isEmptyOrZeroLength(this.all_table_attributes)&&q.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await Pe.promise(r)}catch(r){throw v.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),v.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(jm(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(q.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(Aq)>-1&&this.tables.forEach(n=>{let i={columnid:global.hdb_schema[n.databaseid][n.tableid].hash_attribute,tableid:n.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=fi.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]},_=!1,u=[n.table.databaseid,n.table.tableid,n.attribute].join("/");if(n.attribute===o&&(_=!0),!q.isEmpty(this.exact_search_values[u])&&!this.exact_search_values[u].ignore&&!q.isEmptyOrZeroLength(this.exact_search_values[u].values))if(_)try{c.hash_values=Array.from(this.exact_search_values[u].values);let l=await ln.getDataByHash(c);for(let E of c.hash_values)E in l&&!this.data[i].__merged_data[E]&&(this.data[i].__merged_data[E]=[...s[i]],this._setMergedHashAttribute(i,E))}catch(l){v.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),v.error(l)}else try{c.search_attribute=n.attribute,await Promise.all(Array.from(this.exact_search_values[u].values).map(async l=>{let E=Object.assign({},c);E.search_value=l;let d=await ln.getDataByValue(E);for(let S in d)this.data[i].__merged_data[S]?this._updateMergedAttribute(i,S,n.attribute,d[S][n.attribute]):(this.data[i].__merged_data[S]=[...s[i]],this._updateMergedAttribute(i,S,n.attribute,d[S][n.attribute]),this._setMergedHashAttribute(i,q.autoCast(S)))}))}catch(l){v.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),v.error(l)}else if(!q.isEmpty(this.comparator_search_values[u])&&!this.comparator_search_values[u].ignore&&!q.isEmptyOrZeroLength(this.comparator_search_values[u].comparators))try{let l=this.comparator_search_values[u].comparators;for(let E=0,d=l.length;E<d;E++){let S=l[E];c.search_attribute=S.attribute,c.search_value=S.search_value;let m=await ln.getDataByValue(c,S.operation);if(_)for(let R in m)this.data[i].__merged_data[R]||(this.data[i].__merged_data[R]=[...s[i]],this._setMergedHashAttribute(i,q.autoCast(R)));else for(let R in m)this.data[i].__merged_data[R]?this._updateMergedAttribute(i,R,n.attribute,m[R][n.attribute]):(this.data[i].__merged_data[R]=[...s[i]],this._updateMergedAttribute(i,R,n.attribute,m[R][n.attribute]),this._setMergedHashAttribute(i,q.autoCast(R)))}}catch(l){v.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),v.error(l)}else try{c.search_attribute=n.attribute,c.search_value="*";let l=await ln.getDataByValue(c);if(_)for(let E in l)this.data[i].__merged_data[E]||(this.data[i].__merged_data[E]=[...s[i]],this._setMergedHashAttribute(i,q.autoCast(E)));else for(let E in l)this.data[i].__merged_data[E]?this._updateMergedAttribute(i,E,n.attribute,l[E][n.attribute]):(this.data[i].__merged_data[E]=[...s[i]],this._updateMergedAttribute(i,E,n.attribute,l[E][n.attribute]),this._setMergedHashAttribute(i,q.autoCast(E)))}catch(l){v.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),v.error(l)}}}_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 Pe.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 Pe.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}else{t.initial_select_column=Object.assign(new Pe.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 Pe.yy.FuncValue:new Pe.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(S=>{S.joinmode&&S.joinmode!=="INNER"&&(this.has_outer_join=!0),n.push(S.table);let m=S.joinmode+" JOIN ? AS "+(S.as?S.as:S.table.tableid);S.on&&(m+=" ON "+S.on.toString()),i.push(m),t.push(Object.values(this.data[`${S.table.databaseid_orig}_${S.table.as?S.table.as_orig:S.table.tableid_orig}`].__merged_data))});let o=[],c={};n.forEach(S=>{let m=this.data[`${S.databaseid_orig}_${S.as?S.as_orig:S.tableid_orig}`].__hash_name,R=S.as?S.as_orig:S.tableid_orig;o.push({key:`'${R}.${m}'`,schema:S.databaseid_orig,table:S.as?S.as_orig:S.tableid_orig,keys:new Set}),r.push(`${S.as?S.as:S.tableid}.\`${m}\` AS "${R}.${m}"`),c[S.as?S.as_orig:S.tableid_orig]=this.data[`${S.databaseid_orig}_${S.as?S.as_orig:S.tableid_orig}`].__merged_attributes});let _=this.statement.where?"WHERE "+this.statement.where:"",u="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(u="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(S=>{S.is_func?r.push(S.initial_select_column.toString()):S.initial_select_column.tableid?r.push(`${S.initial_select_column.tableid}.${S.initial_select_column.columnid} AS ${S.expression.columnid}`):r.push(`${S.initial_select_column.columnid} AS ${S.expression.columnid}`)}));let l="",E="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",E=this.statement.offset?"OFFSET "+this.statement.offset:"");let d=[];try{let S=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${_} ${u} ${l} ${E}`,m=this._convertColumnsToIndexes(S,n);d=await Pe.promise(m,t),t=null}catch(S){throw v.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),v.error(S),new Error("There was a problem processing the data.")}if(d&&d.length>0){for(let S=0,m=d.length;S<m;S++){let R=d[S];o.forEach(w=>{R[w.key]!==null&&R[w.key]!==void 0&&w.keys.add(R[w.key])})}o.forEach(S=>{let m=Object.keys(this.data[`${S.schema}_${S.table}`].__merged_data),R=fi.difference(m,[...S.keys].map(w=>w.toString()));for(let w=0,U=R.length;w<U;w++){let B=R[w];delete this.data[`${S.schema}_${S.table}`].__merged_data[B]}})}return{existing_attributes:c,joined_length:d?d.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let s=[],n=new Do(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=fi.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){v.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),v.error(i)}}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 l in i)o.push(i[l][0]);this.data[s].__merged_attributes.push(...n.columns);let c={schema:n.schema,table:n.table,hash_values:o,get_attributes:n.columns},_=await ln.getDataByHash(c),u=n.columns.length;for(let l=0,E=o.length;l<E;l++){let d=o[l],S=_[d];for(let m=0;m<u;m++){let R=n.columns[m],w=S[R]===void 0?null:S[R];this.data[s].__merged_data[d].push(w)}}}}catch(r){throw v.error("Error thrown from getDataByHash function in SQLSearch class method getData."),v.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,_=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===_}).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();v.trace(`Final SQL: ${n}`),s=await Pe.promise(n,t),this.has_outer_join&&(s=this._translateUndefinedValues(s)),v.trace(`Final AlaSQL results data included ${s.length} rows`)}catch(n){throw v.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),v.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 v.error(Rq.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),v.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 _=n[i],u=new RegExp(`${_}.\`${o}\``,"g"),l=`${_}.[${c}]`;s=s.replace(u,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let _=new RegExp(`\`${o}\``,"g"),u=`[${c}]`;s=s.replace(_,u)});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 ln.getDataByValue(i);for(let c in o)this.data[n].__merged_data[c]||(this.data[n].__merged_data[c]=Object.assign({},r[n])),this.data[n].__merged_data[c][t[s.attribute]]=o[c][s.attribute]}catch(o){v.error("There was an error when processing this SQL operation. Check your logs"),v.error(o)}}return Object.values(Object.values(this.data)[0].__merged_data)}};a(Mo,"SQLSearch");eR.exports=Mo});var mt=h((QX,sR)=>{"use strict";var pq=CS();sR.exports={searchByConditions:Iq,searchByHash:bq,searchByValue:Cq,search:wq};var Sl=Nr(),rR=require("util"),Oq=rR.callbackify(Sl.searchByHash),Nq=rR.callbackify(Sl.searchByValue),gq=tR();async function Iq(e){return Sl.searchByConditions(e)}a(Iq,"searchByConditions");function bq(e,t){try{Oq(e,(r,s)=>{if(r){t(r);return}t(null,s)})}catch(r){return t(r)}}a(bq,"searchByHash");function Cq(e,t){try{e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc),Nq(e,(r,s)=>{if(r){t(r);return}t(null,s)})}catch(r){return t(r)}}a(Cq,"searchByValue");function wq(e,t){try{let r=new pq(e);r.validate(),new gq(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(wq,"search")});var $r=h((WX,oR)=>{"use strict";var mi=require("crypto"),iR="aes-256-cbc",Uq=32,Lq=16,fl=64,aR=32,yq=fl+aR,nR=new Map;oR.exports={encrypt:Dq,decrypt:Mq,createNatsTableStreamName:Pq};function Dq(e){let t=mi.randomBytes(Uq),r=mi.randomBytes(Lq),s=mi.createCipheriv(iR,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(Dq,"encrypt");function Mq(e){let t=e.substr(0,fl),r=e.substr(fl,aR),s=e.substr(yq,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),o=mi.createDecipheriv(iR,Buffer.from(t,"hex"),n),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(Mq,"decrypt");function Pq(e,t){let r=`${e}.${t}`,s=nR.get(r);return s||(s=mi.createHash("md5").update(`${e}.${t}`).digest("hex"),nR.set(r,s)),s}a(Pq,"createNatsTableStreamName")});var ms=h((JX,hR)=>{"use strict";var _R=mt(),Yr=g(),uR=Wa(),Bq=require("lodash"),vq=require("path"),Hq=$r(),Tl=b(),{promisify:lR}=require("util"),ee=T(),{handleHDBError:Po,hdb_errors:qq}=D(),{HDB_ERROR_MSGS:Bo,HTTP_STATUS_CODES:ER}=qq,Gq=V();Gq.initSync();var cR=X(),Fq=re(),Ri=lR(_R.searchByValue),Vq=lR(_R.searchByHash),En="name",dR="hash_attribute",ml="schema",kq="schema_table",xq="attribute";hR.exports={describeAll:$q,describeTable:vo,describeSchema:Kq};async function $q(e){try{let t=Tl.isEmptyOrZeroLength(e),r,s;t||(r=e.hdb_user.role.permission,s=r.super_user||r.cluster_user);let n={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,search_attribute:En,search_value:ee.WILDCARD_SEARCH_VALUE,get_attributes:[En]},i=await Ri(n);if(Tl.isEmptyOrZeroLength(i))return{};let o={},c={};for(let d in i)o[i[d].name]=!0,!t&&!s&&(c[i[d].name]=r[i[d].name].describe);let _={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,search_attribute:ee.ID_ATTRIBUTE_STRING,search_value:ee.WILDCARD_SEARCH_VALUE,get_attributes:[dR,ee.ID_ATTRIBUTE_STRING,En,ml]},u=await Ri(_),l=[];for(let d of u)try{let S;if(t||s)S=await vo({schema:d.schema,table:d.name});else if(r&&r[d.schema].describe&&r[d.schema].tables[d.name].describe){let m=r[d.schema].tables[d.name].attribute_permissions;S=await vo({schema:d.schema,table:d.name},m)}S&&l.push(S)}catch(S){Yr.error(S)}let E={};for(let d in l)t||s?(E[l[d].schema]==null&&(E[l[d].schema]={}),E[l[d].schema][l[d].name]=l[d],o[l[d].schema]&&delete o[l[d].schema]):c[l[d].schema]&&(E[l[d].schema]==null&&(E[l[d].schema]={}),E[l[d].schema][l[d].name]=l[d],o[l[d].schema]&&delete o[l[d].schema]);for(let d in o)t||s?E[d]={}:c[d]&&(E[d]={});return E}catch(t){return Yr.error("Got an error in describeAll"),Yr.error(t),Po(new Error,Bo.DESCRIBE_ALL_ERR)}}a($q,"describeAll");async function vo(e,t){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={},o=uR.describe_table(e);if(o)throw o;if(r===ee.SYSTEM_SCHEMA_NAME)return global.hdb_schema[ee.SYSTEM_SCHEMA_NAME][s];let c={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,hash_attribute:ee.SYSTEM_TABLE_HASH_ATTRIBUTES.TABLE_TABLE_HASH_ATTRIBUTE,search_attribute:En,search_value:s,hash_values:[],get_attributes:[ee.WILDCARD_SEARCH_VALUE]},_=await Ri(c);if(!_||_.length===0)throw Po(new Error,Bo.TABLE_NOT_FOUND(e.schema,e.table),ER.NOT_FOUND);for await(let u of _)try{if(u.schema!==r)continue;if(i=u,!i.hash_attribute)throw Po(new Error,Bo.INVALID_TABLE_ERR(i));let l={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,hash_attribute:ee.SYSTEM_TABLE_HASH_ATTRIBUTES.ATTRIBUTE_TABLE_HASH_ATTRIBUTE,search_attribute:kq,search_value:r+"."+s,get_attributes:[xq]},E=await Ri(l);E=Bq.uniqBy(E,d=>d.attribute),n&&n.length>0&&(E=Yq(n)),i.attributes=E,i.clustering_stream_name=Hq.createNatsTableStreamName(u.schema,u.name);try{let d=vq.join(Fq.getBaseSchemaPath(),i.schema.toString()),S=await cR.openEnvironment(d,i.name),m=cR.statDBI(S,i.hash_attribute);i.record_count=m.entryCount}catch(d){Yr.warn(`unable to stat table dbi due to ${d}`)}}catch(l){Yr.error(`There was an error getting attributes for table '${u.name}'`),Yr.error(l)}return i}a(vo,"descTable");function Yq(e){return e.reduce((t,r)=>(r.describe&&t.push({attribute:r.attribute_name}),t),[])}a(Yq,"getAttrsByPerms");async function Kq(e){let t=uR.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(),n={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,hash_attribute:ee.SYSTEM_TABLE_HASH_ATTRIBUTES.TABLE_TABLE_HASH_ATTRIBUTE,search_attribute:ml,search_value:s,hash_values:[],get_attributes:[dR,ee.ID_ATTRIBUTE_STRING,En,ml]},i=await Ri(n);if(i&&i.length<1){let o={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,hash_attribute:ee.SYSTEM_TABLE_HASH_ATTRIBUTES.SCHEMA_TABLE_HASH_ATTRIBUTE,hash_values:[s],get_attributes:[En]},c=await Vq(o);if(c&&c.length<1)throw Po(new Error,Bo.SCHEMA_NOT_FOUND(e.schema),ER.NOT_FOUND);return{}}else{let o={};return await Promise.all(i.map(async c=>{try{let _;if(r&&r.tables[c.name]&&(_=r.tables[c.name]),Tl.isEmpty(_)||_.describe){let u=await vo({schema:e.schema,table:c.name},_?_.attribute_permissions:null);u&&(o[u.name]=u)}}catch(_){Yr.error(`Error describing schema table '${e.schema}.${c}'`),Yr.error(_)}})),o}}a(Kq,"describeSchema")});var Kr=h((zX,RR)=>{var ZX=require("async"),dn=ls(),XX=g(),{callbackify:TR,promisify:Qq}=require("util");RR.exports={setSchemaDataToGlobal:SR,getTableSchema:Zq,getSystemSchema:zq,setSchemaDataToGlobalAsync:Qq(SR)};var mR=ms(),Wq=TR(mR.describeAll),Jq=TR(mR.describeTable);function SR(e){Wq(null,(t,r)=>{if(t){e(t);return}r.system||(r.system=dn),global.hdb_schema=r,e(null,null)})}a(SR,"setSchemaDataToGlobal");function fR(e,t){return e==="system"?dn[t]:global.hdb_schema[e][t]}a(fR,"returnSchema");function Zq(e,t,r){!global.hdb_schema||!global.hdb_schema[e]||!global.hdb_schema[e][t]?Xq(e,t,s=>{if(s)return r(s);if(!global.hdb_schema[e])return r(`schema ${e} does not exist`);if(!global.hdb_schema[e]||!global.hdb_schema[e][t])return r(`table ${e}.${t} does not exist`);r(null,fR(e,t))}):r(null,fR(e,t))}a(Zq,"getTableSchema");function Xq(e,t,r){let s={table:t,schema:e};if(e==="system"){global.hdb_schema?global.hdb_schema.system=dn:global.hdb_schema={system:dn},r();return}Jq(s,(n,i)=>{if(n){r(n);return}if(!i.schema&&!i.name){r();return}global.hdb_schema||(global.hdb_schema={system:dn}),global.hdb_schema[e]||(global.hdb_schema[e]={}),global.hdb_schema[e][t]=i,r()})}a(Xq,"setTableDataToGlobal");function zq(){return dn}a(zq,"getSystemSchema")});var yt=h((jX,OR)=>{"use strict";var qo=Gu(),Lt=b(),jq=require("util"),Go=Nr(),eG=Kr(),Rl=g(),{handleHDBError:Qr,hdb_errors:tG}=D(),{HTTP_STATUS_CODES:Rs}=tG,rG=jq.promisify(eG.getTableSchema),sG="updated",AR="inserted",pR="upserted";OR.exports={insert:iG,update:aG,upsert:oG,validation:nG,flush:cG};async function nG(e){if(Lt.isEmpty(e))throw new Error("invalid update parameters defined.");if(Lt.isEmptyOrZeroLength(e.schema))throw new Error("invalid schema specified.");if(Lt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await rG(e.schema,e.table),r=qo(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&&Lt.isEmptyOrZeroLength(c[s]))throw Rl.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(!Lt.isEmptyOrZeroLength(c[s])&&(c[s]==="null"||c[s]==="undefined"))throw Rl.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[s]}" is not a valid hash attribute value`);!Lt.isEmpty(c[s])&&c[s]!==""&&n.has(Lt.autoCast(c[s]))&&(c.skip=!0),n.add(Lt.autoCast(c[s]));for(let _ in c)i[_]=1}),i[s]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(i)}}a(nG,"validation");async function iG(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=qo(e);if(t)throw Qr(new Error,t.message,Rs.BAD_REQUEST);let r=Lt.checkSchemaTableExist(e.schema,e.table);if(r)throw Qr(new Error,r,Rs.BAD_REQUEST);try{let s=await Go.createRecords(e);return Ho(AR,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}catch(s){throw s}}a(iG,"insertData");async function aG(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=qo(e);if(t)throw Qr(new Error,t.message,Rs.BAD_REQUEST);let r=Lt.checkSchemaTableExist(e.schema,e.table);if(r)throw Qr(new Error,r,Rs.BAD_REQUEST);try{let s=await Go.updateRecords(e);return Lt.isEmpty(s.existing_rows)?Ho(sG,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time):Ho(s.update_action,[],e,s.hashes,void 0,s.txn_time)}catch(s){throw s}}a(aG,"updateData");async function oG(e){if(e.operation!=="upsert")throw Qr(new Error,"invalid operation, must be upsert",Rs.INTERNAL_SERVER_ERROR);let t=qo(e);if(t)throw Qr(new Error,t.message,Rs.BAD_REQUEST);let r=Lt.checkSchemaTableExist(e.schema,e.table);if(r)throw Qr(new Error,r,Rs.BAD_REQUEST);try{let s=await Go.upsertRecords(e);return Ho(pR,s.written_hashes,e,[],s.new_attributes,s.txn_time)}catch(s){let n=`There was an error during an upsert op: ${s}`;throw Qr(s,null,null,Rl.ERR,n)}}a(oG,"upsertData");function Ho(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===AR?(o.inserted_hashes=t,o.skipped_hashes=s,o):e===pR?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=s,o)}a(Ho,"returnObject");function cG(e){return Go.flush(e.schema,e.table)}a(cG,"flush")});var pl=h((e3,IR)=>{var _G=de(),Al=require("joi"),{hdb_schema_table:NR}=Rr(),gR={schema:NR,table:NR},uG={date:Al.date().iso().required()},lG={timestamp:Al.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};IR.exports=function(e,t){let r=t==="timestamp"?{...gR,...lG}:{...gR,...uG},s=Al.object(r);return _G.validateBySchema(e,s)}});var UR=h((t3,wR)=>{var EG=de(),bR=require("joi"),{hdb_schema_table:CR}=Rr(),dG=bR.object({schema:CR,table:CR,hash_values:bR.array().required()});wR.exports=function(e){return EG.validateBySchema(e,dG)}});var yR=h((r3,LR)=>{"use strict";var Fo=class{constructor(t,r,s,n,i){this.operation=t,this.schema=r,this.table=s,this.hash_attribute=n,this.records=i}};a(Fo,"InsertObject");var Vo=class{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}};a(Vo,"NoSQLSeachObject");var ko=class{constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};a(ko,"DeleteResponseObject");LR.exports={InsertObject:Fo,NoSQLSeachObject:Vo,DeleteResponseObject:ko}});var ps=h((s3,vR)=>{"use strict";var MR=pl(),hG=UR(),xo=b(),DR=require("moment"),PR=g(),{promisify:SG,callbackify:fG}=require("util"),As=T(),TG=Kr(),Ol=SG(TG.getTableSchema),Nl=Nr(),{DeleteResponseObject:mG}=yR(),{handleHDBError:Wr,hdb_errors:RG}=D(),{HDB_ERROR_MSGS:$o,HTTP_STATUS_CODES:Jr}=RG,AG="records successfully deleted",pG=fG(BR);vR.exports={delete:pG,deleteRecord:BR,deleteFilesBefore:OG,deleteAuditLogsBefore:NG};async function OG(e){let t=MR(e,"date");if(t)throw Wr(t,t.message,Jr.BAD_REQUEST,void 0,void 0,!0);if(!DR(e.date,DR.ISO_8601).isValid())throw Wr(new Error,$o.INVALID_DATE,Jr.BAD_REQUEST,As.LOG_LEVELS.ERROR,$o.INVALID_DATE,!0);let s=xo.checkSchemaTableExist(e.schema,e.table);if(s)throw Wr(new Error,s,Jr.NOT_FOUND,As.LOG_LEVELS.ERROR,s,!0);try{let n=await Nl.deleteRecordsBefore(e);if(await Ol(e.schema,e.table),PR.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}catch(n){throw n}}a(OG,"deleteFilesBefore");async function NG(e){let t=MR(e,"timestamp");if(t)throw Wr(t,t.message,Jr.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e.timestamp))throw Wr(new Error,$o.INVALID_VALUE("Timestamp"),Jr.BAD_REQUEST,As.LOG_LEVELS.ERROR,$o.INVALID_VALUE("Timestamp"),!0);let r=xo.checkSchemaTableExist(e.schema,e.table);if(r)throw Wr(new Error,r,Jr.NOT_FOUND,As.LOG_LEVELS.ERROR,r,!0);try{let s=await Nl.deleteAuditLogsBefore(e);return await Ol(e.schema,e.table),PR.info(`Finished deleting audit logs before ${e.timestamp}`),s}catch(s){throw s}}a(NG,"deleteAuditLogsBefore");async function BR(e){let t=hG(e);if(t)throw Wr(t,t.message,Jr.BAD_REQUEST,void 0,void 0,!0);let r=xo.checkSchemaTableExist(e.schema,e.table);if(r)throw Wr(new Error,r,Jr.NOT_FOUND,As.LOG_LEVELS.ERROR,r,!0);try{await Ol(e.schema,e.table);let s=await Nl.deleteRecords(e);return xo.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${AG}`),s}catch(s){if(s.message===As.SEARCH_NOT_FOUND_MESSAGE){let n=new mG;return n.message=As.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}a(BR,"deleteRecord")});var Yo=h((n3,GR)=>{var gG=require("crypto"),HR=9;function IG(e){let t=CG(HR),r=qR(e+t);return t+r}a(IG,"createHash");function bG(e,t){let r=e.substr(0,HR),s=r+qR(t+r);return e===s}a(bG,"validateHash");function CG(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(CG,"generateSalt");function qR(e){return gG.createHash("md5").update(e).digest("hex")}a(qR,"md5");GR.exports={hash:IG,validate:bG}});var VR=h((i3,FR)=>{var gl=de(),Ze={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 wG(e){return Ze.password.presence=!0,Ze.username.presence=!0,Ze.role.presence=!0,Ze.active.presence=!0,gl.validateObject(e,Ze)}a(wG,"addUserValidation");function UG(e){return Ze.password.presence=!1,Ze.username.presence=!0,Ze.role.presence=!1,Ze.active.presence=!1,gl.validateObject(e,Ze)}a(UG,"alterUserValidation");function LG(e){return Ze.password.presence=!1,Ze.username.presence=!0,Ze.role.presence=!1,Ze.active.presence=!1,gl.validateObject(e,Ze)}a(LG,"dropUserValidation");FR.exports={addUserValidation:wG,alterUserValidation:UG,dropUserValidation:LG}});var Se=h((o3,xR)=>{"use strict";var{platform:a3}=require("os"),yG="nats-server.zip",Il="nats-server",DG=process.platform==="win32"?`${Il}.exe`:Il,bl="HDB",MG=/^[^\s.,*>]+$/,kR="__request__",PG=a(e=>`${e}.${kR}`,"REQUEST_SUBJECT"),BG={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},vG={HUB:"hub.pid",LEAF:"leaf.pid"},HG={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},qG={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:bl,deliver_subject:"__HDB__.WORKQUEUE"},GG={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:bl,deliver_subject:"HDB.SCHEMAQUEUE"},FG={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:bl,deliver_subject:"HDB.USERQUEUE"},VG={SUCCESS:"success",ERROR:"error"},kG={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},xG={TXN:"txn",MSGID:"msgid"};xR.exports={NATS_SERVER_ZIP:yG,NATS_SERVER_NAME:Il,NATS_BINARY_NAME:DG,PID_FILES:vG,NATS_CONFIG_FILES:BG,SERVER_SUFFIX:HG,WORK_QUEUE_CONSUMER_NAMES:qG,SCHEMA_QUEUE_CONSUMER_NAMES:GG,USER_QUEUE_CONSUMER_NAMES:FG,NATS_TERM_CONSTRAINTS_RX:MG,REQUEST_SUFFIX:kR,UPDATE_REMOTE_RESPONSE_STATUSES:VG,CLUSTER_STATUS_STATUSES:kG,REQUEST_SUBJECT:PG,SUBJECT_PREFIXES:xG}});var YR=h((c3,$R)=>{"use strict";var Zr=T(),Ai=class{constructor(t=0,r=Zr.STORAGE_TYPES_ENUM.LMDB,s=Zr.LICENSE_VALUES.API_CALL_DEFAULT,n=Zr.RAM_ALLOCATION_ENUM.DEFAULT,i=Zr.LICENSE_VALUES.VERSION_DEFAULT,o){this.exp_date=t,this.storage_type=r,this.api_call=s,this.ram_allocation=n,this.version=i,this.fingerprint=o}};a(Ai,"BaseLicense");var Ko=class extends Ai{constructor(t=0,r=Zr.STORAGE_TYPES_ENUM.LMDB,s=Zr.LICENSE_VALUES.API_CALL_DEFAULT,n=Zr.RAM_ALLOCATION_ENUM.DEFAULT,i=Zr.LICENSE_VALUES.VERSION_DEFAULT,o,c=!1){super(t,r,s,n,i,o),this.enterprise=c}};a(Ko,"ExtendedLicense");$R.exports={BaseLicense:Ai,ExtendedLicense:Ko}});var pi=h((_3,XR)=>{"use strict";var Sn=require("fs-extra"),KR=Yo(),QR=require("crypto"),$G=require("moment"),YG=require("uuid").v4,Xe=g(),wl=require("path"),KG=b(),Rt=T(),QG=YR().ExtendedLicense,hn="invalid license key format",WG="061183",JG="mofi25",ZG="aes-256-cbc",XG=16,zG=32,WR=V();WR.initSync();var Cl;XR.exports={validateLicense:JR,generateFingerPrint:eF,licenseSearch:ZR,getLicense:sF};function Ul(){return wl.join(WR.getHdbBasePath(),Rt.LICENSE_KEY_DIR_NAME,Rt.LICENSE_FILE_NAME)}a(Ul,"getLicenseDirPath");function jG(){let e=Ul();return wl.join(e,Rt.LICENSE_FILE_NAME)}a(jG,"getLicenseFilePath");function Ll(){let e=Ul();return wl.join(e,Rt.REG_KEY_FILE_NAME)}a(Ll,"getFingerPrintFilePath");async function eF(){let e=Ll();try{return await Sn.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await tF();throw Xe.error(`Error writing fingerprint file to ${e}`),Xe.error(t),new Error("There was an error generating the fingerprint")}}a(eF,"generateFingerPrint");async function tF(){let e=YG(),t=KR.hash(e),r=Ll();try{await Sn.mkdirp(Ul()),await Sn.writeFile(r,t)}catch(s){if(s.code==="EEXIST")return t;throw Xe.error(`Error writing fingerprint file to ${r}`),Xe.error(s),new Error("There was an error generating the fingerprint")}return t}a(tF,"writeFingerprint");function JR(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,storage_type:Rt.STORAGE_TYPES_ENUM.LMDB,api_call:Rt.LICENSE_VALUES.API_CALL_DEFAULT,ram_allocation:Rt.RAM_ALLOCATION_ENUM.DEFAULT,version:Rt.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Xe.error("empty license key passed to validate."),r;let s=Ll(),n=!1;try{n=Sn.statSync(s)}catch(i){Xe.error(i)}if(n){let i;try{i=Sn.readFileSync(s,"utf8")}catch{Xe.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(JG),c=o[1];c=Buffer.concat([Buffer.from(c)],XG);let _=Buffer.concat([Buffer.from(i)],zG),u=QR.createDecipheriv(ZG,_,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let l=null;try{l=u.update(o[0],"hex","utf8"),l.trim(),l+=u.final("utf8")}catch{let S=rF(o[0],i);if(S)l=S;else throw r.valid_license=!1,r.valid_machine=!1,console.error(hn),Xe.error(hn),new Error(hn)}let E;if(isNaN(l))try{E=JSON.parse(l),r.api_call=E.api_call,r.version=E.version,r.storage_type=E.storage_type,r.exp_date=E.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),E.ram_allocation&&(r.ram_allocation=E.ram_allocation)}catch{throw console.error(hn),Xe.error(hn),new Error(hn)}else r.exp_date=l;r.exp_date<$G().valueOf()&&(r.valid_date=!1),KR.validate(o[1],`${WG}${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||Xe.error("Invalid licence"),r}a(JR,"validateLicense");function rF(e,t){try{let r=QR.createDecipher("aes192",t),s=r.update(e,"hex","utf8");return s.trim(),s+=r.final("utf8"),s}catch{Xe.warn("Check old license failed")}}a(rF,"checkOldLicense");function ZR(){let e=new QG;e.api_call=0;let t=[];try{t=Sn.readFileSync(jG(),"utf-8").split(Rt.NEW_LINE)}catch(r){r.code==="ENOENT"?Xe.info("no license file found"):Xe.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let s=t[r];try{if(KG.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=JR(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.api_call+=i.api_call,e.ram_allocation=i.ram_allocation,e.storage_type=i.storage_type,e.enterprise=!0)}catch(n){Xe.error("There was an error parsing the license string."),Xe.error(n),e.api_call=Rt.LICENSE_VALUES.API_CALL_DEFAULT,e.ram_allocation=Rt.RAM_ALLOCATION_ENUM.DEFAULT,e.storage_type=Rt.STORAGE_TYPES_ENUM.LMDB,e.enterprise=!1}}return e.api_call===0&&(e.api_call=Rt.LICENSE_VALUES.API_CALL_DEFAULT),Cl=e,e}a(ZR,"licenseSearch");async function sF(){return Cl||await ZR(),Cl}a(sF,"getLicense")});var gr=h((u3,lA)=>{"use strict";var tA="username is required",rA="nothing to update, must supply active, role or password to update",sA="password cannot be an empty string",nA="If role is specified, it cannot be empty.",iA="active must be true or false";lA.exports={addUser:lF,alterUser:EF,dropUser:hF,userInfo:SF,listUsers:Wo,listUsersExternal:fF,setUsersToGlobal:Oi,findAndValidateUser:RF,getClusterUser:AF,USERNAME_REQUIRED:tA,ALTERUSER_NOTHING_TO_UPDATE:rA,EMPTY_PASSWORD:sA,EMPTY_ROLE:nA,ACTIVE_BOOLEAN:iA};var aA=yt(),nF=ps(),Dl=Yo(),oA=VR(),cA=mt(),Ml=js(),Ce=b(),_A=require("validate.js"),H=g(),{promisify:Pl}=require("util"),Bl=$r(),Os=T(),zR=Se(),iF=Tr(),vl=V(),aF=pi(),oF=ls(),{handleHDBError:sr,hdb_errors:cF}=D(),{HTTP_STATUS_CODES:nr,AUTHENTICATION_ERROR_MSGS:yl,HDB_ERROR_MSGS:fn}=cF,{UserEventMsg:Hl}=Vr(),jR=require("lodash"),uA={username:!0,active:!0,role:!0,password:!0},eA=new Map,Qo=Pl(cA.searchByValue),_F=Pl(cA.searchByHash),uF=Pl(nF.delete);async function lF(e){let t=_A.cleanAttributes(e,uA),r=oA.addUserValidation(t);if(r)throw sr(new Error,r.message,nr.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 Qo(s)}catch(u){throw H.error("There was an error searching for a role in add user"),H.error(u),u}if(!n||n.length<1)throw sr(new Error,fn.ROLE_NAME_NOT_FOUND(t.role),nr.NOT_FOUND,void 0,void 0,!0);if(n.length>1)throw sr(new Error,fn.DUP_ROLES_FOUND(t.role),nr.CONFLICT,void 0,void 0,!0);n[0].permission.cluster_user===!0&&(t.hash=Bl.encrypt(t.password)),t.password=Dl.hash(t.password),t.role=n[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await aA.insert(i)}catch(u){throw H.error("There was an error searching for a user."),H.error(u),u}H.debug(o);try{await Oi()}catch(u){throw H.error("Got an error setting users to global"),H.error(u),u}if(o.skipped_hashes.length===1)throw sr(new Error,fn.USER_ALREADY_EXISTS(t.username),nr.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);c.role=n[0];let _={user:null};return _.user=c,Ce.sendTransactionToSocketCluster(Os.INTERNAL_SC_CHANNELS.ADD_USER,_,vl.get(Os.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY)),Ml.signalUserChange(new Hl(process.pid)),`${c.username} successfully added`}a(lF,"addUser");async function EF(e){let t=_A.cleanAttributes(e,uA);if(Ce.isEmptyOrZeroLength(t.username))throw new Error(tA);if(Ce.isEmptyOrZeroLength(t.password)&&Ce.isEmptyOrZeroLength(t.role)&&Ce.isEmptyOrZeroLength(t.active))throw new Error(rA);if(!Ce.isEmpty(t.password)&&Ce.isEmptyOrZeroLength(t.password.trim()))throw new Error(sA);if(!Ce.isEmpty(t.active)&&!Ce.isBoolean(t.active))throw new Error(iA);let r=dF(t.username);if(!Ce.isEmpty(t.password)&&!Ce.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=Bl.encrypt(t.password)),t.password=Dl.hash(t.password)),t.role==="")throw new Error(nA);if(t.role){let o={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["*"]},c;try{c=await Qo(o)}catch(_){throw H.error("Got an error searching for a role."),H.error(_),_}if(!c||c.length===0){let _=fn.ALTER_USER_ROLE_NOT_FOUND(t.role);throw H.error(_),sr(new Error,_,nr.NOT_FOUND,void 0,void 0,!0)}if(c.length>1){let _=fn.ALTER_USER_DUP_ROLES(t.role);throw H.error(_),sr(new Error,_,nr.CONFLICT,void 0,void 0,!0)}t.role=c[0].id}let s={operation:"update",schema:"system",table:"hdb_user",records:[t]},n;try{n=await aA.update(s)}catch(o){throw H.error("Error during update."),H.error(o),o}try{await Oi()}catch(o){throw H.error("Got an error setting users to global"),H.error(o),o}let i={user:null};return i.user=t,Ce.sendTransactionToSocketCluster(Os.INTERNAL_SC_CHANNELS.ALTER_USER,i,vl.get(Os.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY)),Ml.signalUserChange(new Hl(process.pid)),n}a(EF,"alterUser");function dF(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(dF,"isClusterUser");async function hF(e){try{let t=oA.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Ce.isEmpty(global.hdb_users.get(e.username)))throw sr(new Error,fn.USER_NOT_EXIST(e.username),nr.NOT_FOUND,void 0,void 0,!0);let s;try{s=await uF(r)}catch(i){throw H.error("Got an error deleting a user."),H.error(i),i}H.debug(s);try{await Oi()}catch(i){throw H.error("Got an error setting users to global."),H.error(i),i}let n={user:null};return n.user=e,Ce.sendTransactionToSocketCluster(Os.INTERNAL_SC_CHANNELS.DROP_USER,n,vl.get(Os.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY)),Ml.signalUserChange(new Hl(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(hF,"dropUser");async function SF(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 _F(r)}catch(n){throw H.error("Got an error searching for a role."),H.error(n),n}t.role=s[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw H.error(r),r}return t}a(SF,"userInfo");async function fF(){let e;try{e=await Wo()}catch(t){throw H.error("Got an error listing users."),H.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(fF,"listUsersExternal");async function Wo(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=jR.cloneDeep(await Qo(e))}catch(r){throw H.error("Got an error searching for roles."),H.error(r),r}if(!Ce.isEmptyOrZeroLength(t)){let r={};for(let o in t)r[t[o].id]=t[o];let s={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},n;try{n=jR.cloneDeep(await Qo(s))}catch(o){throw H.error("Got an error searching for users."),H.error(o),o}let i=new Map;for(let o in n){let c=n[o];c.role=r[n[o].role],TF(c.role),i.set(c.username,c)}return(await aF.getLicense()).enterprise?i:mF(i)}}catch(e){throw H.error("got an error listing users"),H.error(e),Ce.errorizeMessage(e)}return null}a(Wo,"listUsers");function TF(e){try{if(!e){H.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(oF)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){H.error("Got an error trying to set system permissions."),H.error(t)}}a(TF,"appendSystemTablesToRole");function mF(e){try{if(H.info("No enterprise license found. System is limited to 1 clustering role and 1 user role"),!e)return new Map;let t=Object.create(null),r=new Map;e.forEach((n,i)=>{n.role.permission.cluster_user===void 0||n.role.permission.cluster_user===!1?n.role.permission.super_user===!0&&(t[n.role.id]||(t[n.role.id]=new Map),t[n.role.id].set(i,n)):r.set(i,n)});let s={role:void 0,count:0};return Object.keys(t).forEach(n=>{let i=t[n];i.size>=s.count&&(s.role=n,s.count=i.size)}),s.role===void 0?(H.error("No roles found with active users. This is bad."),new Map):(r=new Map([...r,...t[s.role]]),r)}catch(t){return H.error("error filtering users."),H.error(t),new Map}}a(mF,"nonEnterpriseFilter");async function Oi(){try{let e=await Wo();global.hdb_users=e}catch(e){throw H.error(e),e}}a(Oi,"setUsersToGlobal");async function RF(e,t,r=!0){global.hdb_users||await Oi();let s=global.hdb_users.get(e);if(!s)throw sr(new Error,yl.GENERIC_AUTH_FAIL,nr.UNAUTHORIZED,void 0,void 0,!0);if(s&&!s.active)throw sr(new Error,yl.USER_INACTIVE,nr.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(eA.get(t)===s.password)return n;if(Dl.validate(s.password,t))eA.set(t,s.password);else throw sr(new Error,yl.GENERIC_AUTH_FAIL,nr.UNAUTHORIZED,void 0,void 0,!0)}return n}a(RF,"findAndValidateUser");async function AF(){let e=await Wo(),t=iF.getConfigFromFile(Os.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Ce.isEmpty(r))return r.decrypt_hash=Bl.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+zR.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+zR.SERVER_SUFFIX.ADMIN,r}a(AF,"getClusterUser")});var SA=h((l3,hA)=>{"use strict";var pF=require("node-ipc").IPC,EA=b(),dA=T(),Ir=g(),{IPC_ERRORS:Tn}=Qe(),OF=require("os"),Jo=class{constructor(t,r){this.ipc=new pF,this.server_name=dA.HDB_IPC_SERVER,this.ipc.config.retry=OF.platform()=="win32"?6e5:100,this.ipc.config.id=dA.HDB_IPC_CLIENT_PREFIX+t,this.ipc.config.silent=!0,this.event_handlers=r,this.connect()}connect(){this.ipc.connectTo(this.server_name,()=>{this.generateEventHandlers(this.event_handlers)})}addEventHandler(t,r){this.ipc.of[this.server_name].on(t,r)}generateEventHandlers(t){this.ipc.of[this.server_name].on("connect",()=>{Ir.info(`IPC client ${this.ipc.config.id} connected to ${this.server_name}`)}),this.ipc.of[this.server_name].on("disconnect",()=>{Ir.info(`IPC client ${this.ipc.config.id} disconnected from ${this.server_name}`)}),this.ipc.of[this.server_name].on("error",r=>{r.code==="ECONNREFUSED"&&Ir.warn("Error connecting to HDB IPC server. Confirm that the server is running."),Ir.warn(`Error with IPC client ${this.ipc.config.id}`),Ir.warn(r)});for(let[r,s]of Object.entries(t))this.addEventHandler(r,s)}emitToServer(t){if(typeof t!="object")throw Ir.warn(Tn.INVALID_IPC_DATA_TYPE),new Error(Tn.INVALID_IPC_DATA_TYPE);if(EA.isEmpty(t.type))throw Ir.warn(Tn.MISSING_TYPE),new Error(Tn.MISSING_TYPE);if(EA.isEmpty(t.message))throw Ir.warn(Tn.MISSING_MSG),new Error(Tn.MISSING_MSG);Ir.trace(`IPC client ${this.ipc.config.id} emitting`,t),this.ipc.of[this.server_name].emit("message",t)}};a(Jo,"IPCClient");hA.exports=Jo});var mA=h((E3,TA)=>{"use strict";var ql=X(),NF=g(),fA=Qe().LMDB_ERRORS_ENUM;TA.exports=gF;async function gF(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 ql.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==fA.ENV_REQUIRED)throw c}}break;case"drop_table":let s=`${e.schema}.${e.table}`,n=`txn.${s}`;try{await ql.closeEnvironment(global.lmdb_map[s]),await ql.closeEnvironment(global.lmdb_map[n])}catch(i){if(i.message!==fA.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){NF.error(t)}}a(gF,"cleanLMDBMap")});var NA=h((d3,OA)=>{"use strict";var Ns=g(),Zo=T(),IF=mA(),RA=Kr(),bF=ms(),CF=gr(),{validateEvent:pA}=Vr(),wF={[Zo.IPC_EVENT_TYPES.SCHEMA]:UF,[Zo.IPC_EVENT_TYPES.USER]:yF};async function UF(e){let t=pA(e);if(t){Ns.error(t);return}Ns.trace(`IPC schemaHandler ${Zo.HDB_IPC_CLIENT_PREFIX}${process.pid} received schema event:`,e),await IF(e.message),await LF(e.message)}a(UF,"schemaHandler");async function LF(e){try{if(global.hdb_schema!==void 0&&typeof global.hdb_schema=="object"&&e.operation!==void 0)switch(e.operation){case"drop_schema":delete global.hdb_schema[e.schema];break;case"drop_table":global.hdb_schema[e.schema]!==void 0&&delete global.hdb_schema[e.schema][e.table];break;case"create_schema":global.hdb_schema[e.schema]===void 0&&(global.hdb_schema[e.schema]={});break;case"create_table":case"create_attribute":global.hdb_schema[e.schema]===void 0&&(global.hdb_schema[e.schema]={}),global.hdb_schema[e.schema][e.table]=await bF.describeTable({schema:e.schema,table:e.table});break;default:RA.setSchemaDataToGlobal(AA);break}else RA.setSchemaDataToGlobal(AA)}catch(t){Ns.error(t)}}a(LF,"syncSchemaMetadata");function AA(e){e&&Ns.error(e)}a(AA,"handleErrorCallback");async function yF(e){try{let t=pA(e);if(t){Ns.error(t);return}Ns.trace(`IPC userHandler ${Zo.HDB_IPC_CLIENT_PREFIX}${process.pid} received user event:`,e),await CF.setUsersToGlobal()}catch(t){Ns.error(t)}}a(yF,"userHandler");OA.exports=wF});var bA=h((h3,IA)=>{"use strict";var gA=require("fs"),Ni=V();Ni.initSync();var{CONFIG_PARAMS:Xo}=T(),DF=1024*1024*1024;function MF(e){let t=Ni.get(Xo.CUSTOMFUNCTIONS_NETWORK_TIMEOUT),r=Ni.get(Xo.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT),s={bodyLimit:DF,connectionTimeout:t,keepAliveTimeout:r,ignoreTrailingSlash:!0};if(e){let n=Ni.get(Xo.CUSTOMFUNCTIONS_TLS_PRIVATEKEY),i=Ni.get(Xo.CUSTOMFUNCTIONS_TLS_CERTIFICATE);s.https={key:gA.readFileSync(`${n}`),cert:gA.readFileSync(`${i}`)}}return s}a(MF,"getServerOptions");IA.exports=MF});var UA=h((S3,wA)=>{"use strict";var Gl=V();Gl.initSync();var{CONFIG_PARAMS:CA}=T();function PF(){let e=Gl.get(CA.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST),t=Gl.get(CA.CUSTOMFUNCTIONS_NETWORK_CORS),r;if(t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization"],credentials:!1},e&&e.length>0&&e[0]!==null)){let s=e.split(",");r.origin=(n,i)=>s.indexOf(n)!==-1?i(null,!0):i(new Error(`domain ${n} is not on access list`))}return r}a(PF,"getCORSOptions");wA.exports=PF});var DA=h((f3,yA)=>{"use strict";var LA=V();LA.initSync();var BF=T();function vF(){return LA.get(BF.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT)}a(vF,"getHeaderTimeoutConfig");yA.exports=vF});var PA=h((T3,MA)=>{var HF=de(),qF={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};MA.exports=function(e){return HF.validateObject(e,qF)}});var Fl=h((m3,BA)=>{"use strict";var GF=T().OPERATIONS_ENUM,zo=class{constructor(t,r,s,n=void 0){this.operation=GF.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};a(zo,"UpdateObject");BA.exports=zo});var HA=h((R3,vA)=>{"use strict";var FF={OPERATION:"operation",REFRESH:"refresh"},jo=class{constructor(t,r){this.operation_token=t,this.refresh_token=r}};a(jo,"JWTTokens");var ec=class{constructor(t,r,s){this.public_key=t,this.private_key=r,this.passphrase=s}};a(ec,"JWTRSAKeys");vA.exports={JWTTokens:jo,TOKEN_TYPE_ENUM:FF,JWTRSAKeys:ec}});var nc=h((A3,VA)=>{"use strict";var Ii=require("jsonwebtoken"),Vl=require("fs-extra"),kl=b(),Dt=T(),{handleHDBError:ct,hdb_errors:VF}=D(),{HTTP_STATUS_CODES:_t,AUTHENTICATION_ERROR_MSGS:ut}=VF,gi=g(),qA=Yo(),Yl=gr(),kF=yt().update,xF=Fl(),$F=js(),{UserEventMsg:YF}=Vr(),Xr=V();Xr.initSync();var xl=require("path"),{JWTTokens:KF,JWTRSAKeys:QF,TOKEN_TYPE_ENUM:tc}=HA(),WF=Xr.get(Dt.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?Xr.get(Dt.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",JF=Xr.get(Dt.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?Xr.get(Dt.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",rc="RS256",$l;VA.exports={createTokens:ZF,validateOperationToken:zF,refreshOperationToken:XF,validateRefreshToken:FA};async function ZF(e){if(kl.isEmpty(e)||typeof e!="object")throw ct(new Error,ut.INVALID_AUTH_OBJECT,_t.BAD_REQUEST,void 0,void 0,!0);if(kl.isEmpty(e.username))throw ct(new Error,ut.USERNAME_REQUIRED,_t.BAD_REQUEST,void 0,void 0,!0);if(kl.isEmpty(e.password))throw ct(new Error,ut.PASSWORD_REQUIRED,_t.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await Yl.findAndValidateUser(e.username,e.password),!t)throw ct(new Error,ut.INVALID_CREDENTIALS,_t.UNAUTHORIZED,void 0,void 0,!0)}catch(d){throw gi.error(d),ct(new Error,ut.INVALID_CREDENTIALS,_t.UNAUTHORIZED,void 0,void 0,!0)}let r=await sc(),s=!1,n=!1;t.role&&t.role.permission&&(s=t.role.permission.super_user===!0,n=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:s,cluster_user:n},o=await GA(i,r.private_key,r.passphrase),c=await Ii.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:JF,algorithm:rc,subject:tc.REFRESH}),_=qA.hash(c),u=new xF(Dt.SYSTEM_SCHEMA_NAME,Dt.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:_}]),l,E;try{l=await kF(u)}catch(d){gi.error(d),E=d}if(E!==void 0||l.skipped_hashes.length>0)throw ct(new Error,ut.REFRESH_TOKEN_SAVE_FAILED,_t.INTERNAL_SERVER_ERROR);return $F.signalUserChange(new YF(process.pid)),new KF(o,c)}a(ZF,"createTokens");async function GA(e,t,r){return await Ii.sign(e,{key:t,passphrase:r},{expiresIn:WF,algorithm:rc,subject:tc.OPERATION})}a(GA,"signOperationToken");async function sc(){if($l===void 0)try{let e=xl.join(Xr.getHdbBasePath(),Dt.LICENSE_KEY_DIR_NAME,Dt.JWT_ENUM.JWT_PASSPHRASE_NAME),t=xl.join(Xr.getHdbBasePath(),Dt.LICENSE_KEY_DIR_NAME,Dt.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=xl.join(Xr.getHdbBasePath(),Dt.LICENSE_KEY_DIR_NAME,Dt.JWT_ENUM.JWT_PUBLIC_KEY_NAME),s=(await Vl.readFile(e)).toString(),n=(await Vl.readFile(t)).toString(),i=(await Vl.readFile(r)).toString();$l=new QF(i,n,s)}catch(e){throw gi.error(e),ct(new Error,ut.NO_ENCRYPTION_KEYS,_t.INTERNAL_SERVER_ERROR)}return $l}a(sc,"getJWTRSAKeys");async function XF(e){if(!e)throw ct(new Error,ut.INVALID_BODY,_t.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw ct(new Error,ut.REFRESH_TOKEN_REQUIRED,_t.BAD_REQUEST,void 0,void 0,!0);await FA(e.refresh_token);let t=await sc(),r=await Ii.decode(e.refresh_token);return{operation_token:await GA({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(XF,"refreshOperationToken");async function zF(e){try{let t=await sc(),r=await Ii.verify(e,t.public_key,{algorithms:rc,subject:tc.OPERATION});return await Yl.findAndValidateUser(r.username,void 0,!1)}catch(t){throw gi.warn(t),t.name&&t.name==="TokenExpiredError"?ct(new Error,ut.TOKEN_EXPIRED,_t.FORBIDDEN):ct(new Error,ut.INVALID_TOKEN,_t.UNAUTHORIZED)}}a(zF,"validateOperationToken");async function FA(e){let t;try{let r=await sc(),s=await Ii.verify(e,r.public_key,{algorithms:rc,subject:tc.REFRESH});t=await Yl.findAndValidateUser(s.username,void 0,!1)}catch(r){throw gi.warn(r),r.name&&r.name==="TokenExpiredError"?ct(new Error,ut.TOKEN_EXPIRED,_t.FORBIDDEN):ct(new Error,ut.INVALID_TOKEN,_t.UNAUTHORIZED)}if(!qA.validate(t.refresh_token,e))throw ct(new Error,ut.INVALID_TOKEN,_t.UNAUTHORIZED);return t}a(FA,"validateRefreshToken")});var Kl=h((O3,$A)=>{"use strict";var jF=PA(),mn=require("passport"),e0=require("passport-local").Strategy,t0=require("passport-http").BasicStrategy,r0=require("util"),s0=gr(),xA=r0.callbackify(s0.findAndValidateUser),p3=Qe(),n0=T(),kA=nc();mn.use(new e0(function(e,t,r){xA(e,t,r)}));mn.use(new t0(function(e,t,r){xA(e,t,r)}));mn.serializeUser(function(e,t){t(null,e)});mn.deserializeUser(function(e,t){t(null,e)});function i0(e,t,r){let s,n;if(e.headers&&e.headers.authorization){let o=e.headers.authorization.split(" ");s=o[0],n=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("User not found")}switch(a(i,"handleResponse"),s){case"Basic":mn.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body&&e.body.operation&&e.body.operation===n0.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?kA.validateRefreshToken(n).then(o=>{e.body.refresh_token=n,r(null,o)}).catch(o=>{r(o)}):kA.validateOperationToken(n).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:mn.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(i0,"authorize");function a0(e,t){let r=jF(e);if(r){t(r);return}let s={authorized:!0,messages:[]},n=e.user.role;if(!n||!n.permission)return t("Invalid role");let i=JSON.parse(n.permission);if(i.super_user)return t(null,s);if(!i[e.schema])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.schema} schema`),t(null,s);if(!i[e.schema].tables[e.table])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.table} table`),t(null,s);if(!i[e.schema].tables[e.table][e.operation])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,s);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return s.authorized=!1,s.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,s);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(s.authorized=!1,s.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,s)}a(a0,"checkPermissions");$A.exports={authorize:i0,checkPermissions:a0}});var ic=h((N3,YA)=>{"use strict";var o0=Nr();YA.exports={writeTransaction:c0};function c0(e,t,r){return o0.writeTransaction(e,t,r)}a(c0,"writeTransaction")});var Ql=h((g3,_0)=>{_0.exports={name:"harperdb",version:"4.0.4",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.13.0","go-lang":"1.19.3","nats-server":"2.9.8"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"See License in ./license/Community+Edition+and+Evaluation+End+User+License+Agreement.pdf",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ data_layer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ data_layer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",test:"rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license --storage_type=lmdb && npm run cover:upgrade && npm run cover:nats && npm run cover:cfserver && npm run cover:lmdbbridge && npm run cover:lmdbutility && npm run cover:hdbserver && npm run cover:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license --storage_type=lmdb","cover:main":"cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","cover:lmdbbridge":"cd bin/ && nyc --no-clean --reporter=lcovonly --retries 3 ../node_modules/mocha/bin/_mocha '../unitTests/data_layer/harperBridge/lmdbBridge/**/*.js' --parallel --config '../unitTests/.mocharc.json'","cover:lmdbutility":"cd bin/ && nyc --no-clean --reporter=lcovonly --retries 3 ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --config '../unitTests/.mocharc.json'","cover:hdbserver":"cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --config '../unitTests/.mocharc.json'","cover:cfserver":"npm run submodules && cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","cover:nats":"cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","cover:upgrade":"cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.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/data_layer/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:{"@fastify/accepts-serializer":"5.1.0","@fastify/autoload":"5.4.0","@fastify/compress":"6.1.1","@fastify/cors":"8.1.0","@fastify/static":"6.5.0","@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",async:"3.2.3","aws-sdk":"2.1096.0",chalk:"4.1.2","cli-progress":"3.10.0",clone:"2.1.2",esbuild:"^0.14.49","fast-glob":"3.2.11",fastify:"4.8.1","fastify-plugin":"4.2.1","fill-range":"7.0.1","fs-extra":"10.0.1","human-readable-ids":"1.0.4",inquirer:"8.2.2","is-number":"7.0.0",joi:"17.6.0",json2csv:"5.0.7",jsonata:"1.8.6",jsonwebtoken:"8.5.1",lmdb:"2.7.6",lodash:"4.17.21",mathjs:"10.4.0",microtime:"3.1.1",minimist:"1.2.6",mkcert:"1.5.0",moment:"2.29.4",msgpackr:"1.8.2",nats:"2.9.2",needle:"3.1.0","node-ipc":"9.1.4","node-stream-zip":"1.15.0","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.3.0",papaparse:"5.3.2",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.3.1",pm2:"5.2.0",prompt:"1.2.2","properties-reader":"2.2.0","recursive-iterator":"3.3.0",semver:"7.3.5","stream-chain":"2.2.5","stream-json":"1.7.4",systeminformation:"5.12.4","tar-fs":"2.1.1","truncate-utf8-bytes":"1.0.2",ulidx:"0.3.0",uuid:"9.0.0","validate.js":"0.11.1",yaml:"1.10.2"},devDependencies:{axios:"0.27.2",chai:"4.3.4","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","hook-std":"2.0.0","intercept-stdout":"0.1.2",mocha:"8.3.2","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",newman:"5.2.3","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"1.21.0","newman-reporter-teamcity":"0.1.11","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.3.2",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},"newman-reporter-html":{newman:"5.2.3"}}}});var At=h((B3,lp)=>{"use strict";var ir=V();ir.initSync();var u0=require("fs-extra"),l0=require("semver"),Li=require("path"),{monotonicFactory:E0}=require("ulidx"),d0=E0(),QA=require("util"),WA=require("child_process"),h0=QA.promisify(WA.exec),S0=WA.spawn,te=Se(),ne=T(),jl=b(),br=g(),ac=$r(),f0=ic(),bi=Tr(),{encode:Zl,decode:JA}=require("msgpackr"),{isEmpty:gs}=jl,ZA=gr(),I3=Ss(),T0=mt(),b3=QA.promisify(T0.searchByHash),{connect:m0,StorageType:XA,RetentionPolicy:zA,AckPolicy:jA,DeliverPolicy:Xl,NatsConnection:C3,JetStreamManager:w3,JetStreamClient:U3,StringCodec:L3,JSONCodec:R0,createInbox:eE,StreamSource:y3,headers:A0,toJsMsg:p0,nuid:D3,JetStreamOptions:M3,ErrorCode:KA,nanos:P3}=require("nats"),{PACKAGE_ROOT:O0}=T(),N0=Ql(),ep=R0(),g0="clustering",I0=N0.engines[te.NATS_SERVER_NAME],b0=Li.join(O0,"dependencies"),zl=Li.join(b0,`${process.platform}-${process.arch}`,te.NATS_BINARY_NAME),Wl,Jl,Ci,wi,Ui,Wt;lp.exports={runCommand:tp,checkNATSServerInstalled:C0,createConnection:tE,getConnection:oc,getJetStreamManager:Rn,getJetStream:rp,getNATSReferences:Mt,getServerList:U0,createLocalStream:rE,listStreams:sp,deleteLocalStream:L0,getServerConfig:yi,listRemoteStreams:y0,viewStream:D0,publishToStream:M0,createWorkQueueStream:P0,addSourceToWorkStream:np,request:B0,removeSourceFromWorkStream:ap,reloadNATS:sE,reloadNATSHub:v0,reloadNATSLeaf:H0,extractServerName:ip,requestErrorHandler:q0,updateWorkStream:G0,createLocalTableStream:cp,createTableStreams:F0,purgeTableStream:_p,purgeSchemaTableStreams:V0,getStreamInfo:k0,updateNodeNameLocalStreams:x0,closeConnection:w0};async function tp(e,t=void 0){let{stdout:r,stderr:s}=await h0(e,{cwd:t});if(s)throw new Error(s.replace(`
1
+ "use strict";var Mb=Object.defineProperty;var a=(e,t)=>Mb(e,"name",{value:t,configurable:!0});var h=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Zd=h((mJ,Xd)=>{var Pb=require("fastify-plugin");Xd.exports=Pb(function(e,t,r){e.addHook("onResponse",async(s,n)=>{n.getResponseTime()}),e.addHook("onSend",async(s,n)=>{let i=n.getResponseTime().toFixed(3);n.header("HDB-Response-Time",i),n.header("Server-Timing",`db;dur=${i}`)}),r()},{name:"hdb-request-time"})});var T=h((RJ,uh)=>{"use strict";var Ye=require("path"),Bb=require("fs");function vb(){let e=__dirname;for(;!Bb.existsSync(Ye.join(e,"package.json"));){let t=Ye.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(vb,"getHDBPackageRoot");var qt=vb(),zd="js",Vn=zd,Hb="harperdb-config.yaml",qb="defaultConfig.yaml",Gb="hdb",jd=`hdbServer.${Vn}`,eh=`customFunctionsServer.${Vn}`,th=`hdbIpcServer.${Vn}`,Fb=`restartHdb.${Vn}`,z_="HarperDB",da="Custom Functions",ha="Clustering Hub",Sa="Clustering Leaf",j_="Clustering Ingest Service",eu="Clustering Reply Service",Vb="foreground.pid",Z_={HDB:z_,IPC:"IPC",CLUSTERING_HUB:ha,CLUSTERING_LEAF:Sa,CLUSTERING_INGEST_SERVICE:j_,CLUSTERING_REPLY_SERVICE:eu,CUSTOM_FUNCTIONS:da,RESTART_HDB:"Restart HDB",INSTALL:"Install",RUN:"Run",STOP:"Stop",UPGRADE:"Upgrade",REGISTER:"Register",JOB:"Job",PM2_LOGROTATE:"pm2-logrotate",CLUSTERING_UPGRADE_4_0_0:"Upgrade-4-0-0"},$b={HDB:"hdb.log",IPC:"ipc.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log",CLUSTERING_INGEST_SERVICE:"clustering_ingest_service.log",CLUSTERING_REPLY_SERVICE:"clustering_reply_service.log",CUSTOM_FUNCTIONS:"custom_functions.log",INSTALL:"install.log",CLI:"cli.log",PM2:"pm2.log",CLUSTERING_UPGRADE:"clustering_upgrade.log",JOBS:"jobs.log"},kb={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},xb={harperdb:z_,ipc:"IPC","clustering hub":ha,"clustering leaf":Sa,"clustering ingest service":j_,"clustering reply service":eu,"custom functions":da,custom_functions:da,"pm2-logrotate":Z_.PM2_LOGROTATE,logrotate:Z_.PM2_LOGROTATE,clustering:"clustering","clustering config":"clustering config"},Yb={CLUSTERING_HUB_PROC_DESCRIPTOR:ha,CLUSTERING_LEAF_PROC_DESCRIPTOR:Sa,CLUSTERING_INGEST_PROC_DESCRIPTOR:j_,CLUSTERING_REPLY_SERVICE_DESCRIPTOR:eu},Ea={HDB:Ye.join(qt,"server/harperdb"),IPC:Ye.join(qt,"server/ipc"),CUSTOM_FUNCTIONS:Ye.join(qt,"server/customFunctions"),CLUSTERING_HUB:Ye.join(qt,"server/nats"),CLUSTERING_LEAF:Ye.join(qt,"server/nats")},Kb={HDB:Ye.join(Ea.HDB,jd),IPC:Ye.join(Ea.IPC,th),CUSTOM_FUNCTIONS:Ye.join(Ea.CUSTOM_FUNCTIONS,eh)},Wb={HDB:Ye.join(qt,"launchServiceScripts/launchHarperDB.js"),CUSTOM_FUNCTIONS:Ye.join(qt,"launchServiceScripts/launchCustomFunctions.js"),NATS_INGEST_SERVICE:Ye.join(qt,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:Ye.join(qt,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:Ye.resolve(qt,"launchServiceScripts/launchUpdateNodes4-0-0.js")},Qb={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},rh="support@harperdb.io",Jb="customer-success@harperdb.io",sh=1,Xb=4141,nh="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",Zb="https://www.harperdb.io/product",zb=`For support, please submit a request at ${nh} or contact ${rh}`,ih=`For license support, please contact ${Jb}`,jb="None of the specified records were found.",eC="hash attribute not found",tC=`Your current license only supports ${sh} role. ${ih}`,rC="Your current license only supports 3 connections to a node.",sC="127.0.0.1",nC=1,iC=/^\.$/,aC=/^\.\.$/,oC="U+002E",cC=/\//g,_C="U+002F",uC=/U\+002F/g,lC=/^U\+002E$/,EC=/^U\+002EU\+002E$/,dC="d",hC=999999,SC="*",fC="--max-old-space-size=",TC="system",mC="__hdb_hash",RC=".harperdb",AC=".hdb",pC="keys",OC="hdb_boot_properties.file",NC=".updateConfig.json",gC="SIGTSTP",IC=24,bC=6e4,CC=448,wC="blob",UC="trash",LC="schema",yC="transactions",DC=".count",MC="id",PC="install_log.log",BC="run_log.log",vC="PROCESS_NAME",HC={SETTINGS_PATH_KEY:"settings_path"},ah=require("lodash"),qC={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"},GC={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},FC={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},VC={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"},$C={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"},dt="hdb_internal:",kC={CREATE_SCHEMA:dt+"create_schema",CREATE_TABLE:dt+"create_table",CREATE_ATTRIBUTE:dt+"create_attribute",ADD_USER:dt+"add_user",ALTER_USER:dt+"alter_user",DROP_USER:dt+"drop_user",HDB_NODES:dt+"hdb_nodes",HDB_USERS:dt+"hdb_users",HDB_WORKERS:dt+"hdb_workers",CATCHUP:dt+"catchup",SCHEMA_CATCHUP:dt+"schema_catchup",WORKER_ROOM:dt+"cluster_workers"},xC={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"},YC="060493.ks",KC=".license",WC={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},I={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",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_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",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",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",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",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",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"},QC={CSV:".csv",JSON:".json"},JC={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key"},XC={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},yr={};yr[I.CREATE_SCHEMA]=I.CREATE_SCHEMA;yr[I.CREATE_TABLE]=I.CREATE_TABLE;yr[I.CREATE_ATTRIBUTE]=I.CREATE_ATTRIBUTE;yr[I.INSERT]=I.INSERT;yr[I.UPDATE]=I.UPDATE;yr[I.UPSERT]=I.UPSERT;yr[I.DELETE]=I.DELETE;var X=Object.create(null);X[I.DESCRIBE_ALL]=I.DESCRIBE_ALL;X[I.DESCRIBE_TABLE]=I.DESCRIBE_TABLE;X[I.DESCRIBE_SCHEMA]=I.DESCRIBE_SCHEMA;X[I.READ_LOG]=I.READ_LOG;X[I.ADD_NODE]=I.ADD_NODE;X[I.LIST_USERS]=I.LIST_USERS;X[I.LIST_ROLES]=I.LIST_ROLES;X[I.USER_INFO]=I.USER_INFO;X[I.SQL]=I.SQL;X[I.GET_JOB]=I.GET_JOB;X[I.SEARCH_JOBS_BY_START_DATE]=I.SEARCH_JOBS_BY_START_DATE;X[I.DELETE_FILES_BEFORE]=I.DELETE_FILES_BEFORE;X[I.EXPORT_LOCAL]=I.EXPORT_LOCAL;X[I.EXPORT_TO_S3]=I.EXPORT_TO_S3;X[I.CLUSTER_STATUS]=I.CLUSTER_STATUS;X[I.REMOVE_NODE]=I.REMOVE_NODE;X[I.RESTART]=I.RESTART;X[I.CUSTOM_FUNCTIONS_STATUS]=I.CUSTOM_FUNCTIONS_STATUS;X[I.GET_CUSTOM_FUNCTIONS]=I.GET_CUSTOM_FUNCTIONS;X[I.GET_CUSTOM_FUNCTION]=I.GET_CUSTOM_FUNCTION;X[I.SET_CUSTOM_FUNCTION]=I.SET_CUSTOM_FUNCTION;X[I.DROP_CUSTOM_FUNCTION]=I.DROP_CUSTOM_FUNCTION;X[I.ADD_CUSTOM_FUNCTION_PROJECT]=I.ADD_CUSTOM_FUNCTION_PROJECT;X[I.DROP_CUSTOM_FUNCTION_PROJECT]=I.DROP_CUSTOM_FUNCTION_PROJECT;X[I.PACKAGE_CUSTOM_FUNCTION_PROJECT]=I.PACKAGE_CUSTOM_FUNCTION_PROJECT;X[I.DEPLOY_CUSTOM_FUNCTION_PROJECT]=I.DEPLOY_CUSTOM_FUNCTION_PROJECT;var ZC={RUN:"run",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade"},zC={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},oh={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",IPC_SERVER_PORT:"IPC_SERVER_PORT",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"},jC=ah.invert(oh),f={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_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",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",IPC_NETWORK_PORT:"ipc_network_port",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_ROTATION_COMPRESS:"logging_rotation_compress",LOGGING_ROTATION_DATEFORMAT:"logging_rotation_dateFormat",LOGGING_ROTATION_MAXSIZE:"logging_rotation_maxSize",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",LOGGING_STDSTREAMS:"logging_stdStreams",LOGGING_AUDITLOG:"logging_auditLog",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"},ew={hdb_root_key:f.ROOTPATH,hdb_root:f.ROOTPATH,server_port_key:f.OPERATIONSAPI_NETWORK_PORT,server_port:f.OPERATIONSAPI_NETWORK_PORT,cert_key:f.OPERATIONSAPI_TLS_CERTIFICATE,certificate:f.OPERATIONSAPI_TLS_CERTIFICATE,private_key_key:f.OPERATIONSAPI_TLS_PRIVATEKEY,private_key:f.OPERATIONSAPI_TLS_PRIVATEKEY,http_secure_enabled_key:f.OPERATIONSAPI_NETWORK_HTTPS,https_on:f.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:f.OPERATIONSAPI_NETWORK_CORS,cors_on:f.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:f.LOGGING_LEVEL,log_level:f.LOGGING_LEVEL,log_path_key:f.LOGGING_ROOT,log_path:f.LOGGING_ROOT,log_daily_rotate:f.LOGGING_ROTATION_ROTATE,log_rotate:f.LOGGING_ROTATION_ROTATE,log_rotate_max_size:f.LOGGING_ROTATION_MAXSIZE,log_rotate_retain:f.LOGGING_ROTATION_RETAIN,log_rotate_compress:f.LOGGING_ROTATION_COMPRESS,log_rotate_date_format:f.LOGGING_ROTATION_DATEFORMAT,log_rotate_rotate_module:f.LOGGING_ROTATION_ROTATEMODULE,log_rotate_worker_interval:f.LOGGING_ROTATION_WORKERINTERVAL,log_rotate_rotate_interval:f.LOGGING_ROTATION_ROTATEINTERVAL,log_rotate_timezone:f.LOGGING_ROTATION_TIMEZONE,props_env_key:f.OPERATIONSAPI_NODEENV,node_env:f.OPERATIONSAPI_NODEENV,clustering_node_name_key:f.CLUSTERING_NODENAME,node_name:f.CLUSTERING_NODENAME,clustering_enabled_key:f.CLUSTERING_ENABLED,clustering:f.CLUSTERING_ENABLED,max_http_threads:f.HTTP_THREADS,max_hdb_processes:f.HTTP_THREADS,server_timeout_key:f.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:f.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:f.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:f.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:f.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:f.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:f.LOGGING_AUDITLOG,disable_transaction_log:f.LOGGING_AUDITLOG,operation_token_timeout_key:f.OPERATIONSAPI_AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:f.OPERATIONSAPI_AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:f.OPERATIONSAPI_AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:f.OPERATIONSAPI_AUTHENTICATION_REFRESHTOKENTIMEOUT,ipc_server_port:f.IPC_NETWORK_PORT,custom_functions_enabled_key:f.CUSTOMFUNCTIONS_ENABLED,custom_functions:f.CUSTOMFUNCTIONS_ENABLED,custom_functions_port_key:f.CUSTOMFUNCTIONS_NETWORK_PORT,custom_functions_port:f.CUSTOMFUNCTIONS_NETWORK_PORT,custom_functions_directory_key:f.CUSTOMFUNCTIONS_ROOT,custom_functions_directory:f.CUSTOMFUNCTIONS_ROOT,max_custom_function_processes:f.HTTP_THREADS,log_to_file:f.LOGGING_FILE,log_to_stdstreams:f.LOGGING_STDSTREAMS,run_in_foreground:f.OPERATIONSAPI_FOREGROUND,local_studio_on:f.LOCALSTUDIO_ENABLED,clustering_port:f.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:f.CLUSTERING_USER,clustering_enabled:f.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:f.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:f.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:f.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:f.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:f.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:f.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:f.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_nodename:f.CLUSTERING_NODENAME,clustering_tls_certificate:f.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:f.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:f.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:f.CLUSTERING_TLS_INSECURE,customfunctions_enabled:f.CUSTOMFUNCTIONS_ENABLED,customfunctions_network_port:f.CUSTOMFUNCTIONS_NETWORK_PORT,customfunctions_tls_certificate:f.CUSTOMFUNCTIONS_TLS_CERTIFICATE,customfunctions_network_cors:f.CUSTOMFUNCTIONS_NETWORK_CORS,customfunctions_network_corsaccesslist:f.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,customfunctions_network_headerstimeout:f.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,customfunctions_network_https:f.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:f.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:f.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:f.CUSTOMFUNCTIONS_TLS_CERT_AUTH,customfunctions_network_timeout:f.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,customfunctions_nodeenv:f.CUSTOMFUNCTIONS_NODEENV,http_threads:f.HTTP_THREADS,customfunctions_processes:f.HTTP_THREADS,customfunctions_root:f.CUSTOMFUNCTIONS_ROOT,ipc_network_port:f.IPC_NETWORK_PORT,localstudio_enabled:f.LOCALSTUDIO_ENABLED,logging_file:f.LOGGING_FILE,logging_level:f.LOGGING_LEVEL,logging_root:f.LOGGING_ROOT,logging_rotation_compress:f.LOGGING_ROTATION_COMPRESS,logging_rotation_dateformat:f.LOGGING_ROTATION_DATEFORMAT,logging_rotation_maxsize:f.LOGGING_ROTATION_MAXSIZE,logging_rotation_retain:f.LOGGING_ROTATION_RETAIN,logging_rotation_rotate:f.LOGGING_ROTATION_ROTATE,logging_rotation_rotateinterval:f.LOGGING_ROTATION_ROTATEINTERVAL,logging_rotation_rotatemodule:f.LOGGING_ROTATION_ROTATEMODULE,logging_rotation_timezone:f.LOGGING_ROTATION_TIMEZONE,logging_rotation_workerinterval:f.LOGGING_ROTATION_WORKERINTERVAL,logging_stdstreams:f.LOGGING_STDSTREAMS,logging_auditlog:f.LOGGING_AUDITLOG,operationsapi_authentication_operationtokentimeout:f.OPERATIONSAPI_AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:f.OPERATIONSAPI_AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_foreground:f.OPERATIONSAPI_FOREGROUND,operationsapi_tls_certificate:f.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_network_cors:f.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:f.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:f.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:f.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:f.OPERATIONSAPI_NETWORK_PORT,operationsapi_tls_privatekey:f.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:f.OPERATIONSAPI_TLS_CERT_AUTH,operationsapi_network_timeout:f.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_nodeenv:f.OPERATIONSAPI_NODEENV,operationsapi_root:f.ROOTPATH,rootpath:f.ROOTPATH,storage_writeasync:f.STORAGE_WRITEASYNC,storage_overlappingsync:f.STORAGE_OVERLAPPINGSYNC},tw={csv_file_load:"csv_file_load",csv_data_load:I.CSV_DATA_LOAD,csv_url_load:I.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"},rw={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"},sw={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},nw={FILE_SYSTEM:"fs",LMDB:"lmdb"},iw={API_CALL_DEFAULT:1e4,VERSION_DEFAULT:"2.2.0"},aw={DEVELOPMENT:8192,DEFAULT:512},ow={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"},cw={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"},_w={ENOENT:"ENOENT",EACCES:"EACCES"},ch={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},uw="__clustering__",lw=Object.values(ch),Ew=15984864e5,_h={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},dw=ah.invert(_h),hw={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"},Sw=111,fw=`\r
2
+ `,Tw={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},mw=["*","%"],Rw="unauthorized_access",Aw="func_val",pw={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},Ow={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},Nw="hdb_ipc_server",gw="hdb_ipc_client_",Iw={RESTART:"restart",CHILD_STARTED:"child_started",CHILD_STOPPED:"child_stopped",SCHEMA:"schema",USER:"user",CLUSTER_STATUS_RESPONSE:"cluster_status_response",CLUSTER_STATUS_REQUEST:"cluster_status_request"},bw={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},Cw={STOPPED:"stopped",ONLINE:"online"},ww="3.x.x";uh.exports={LOCAL_HARPERDB_OPERATIONS:X,HDB_SUPPORT_ADDRESS:rh,HDB_SUPPORT_URL:nh,HDB_PRICING_URL:Zb,SUPPORT_HELP_MSG:zb,LICENSE_HELP_MSG:ih,HDB_PROC_NAME:jd,HDB_PROC_DESCRIPTOR:z_,CLUSTERING_LEAF_PROC_DESCRIPTOR:Sa,CLUSTERING_HUB_PROC_DESCRIPTOR:ha,SYSTEM_SCHEMA_NAME:TC,HASH_FOLDER_NAME:mC,HDB_HOME_DIR_NAME:RC,UPDATE_FILE_NAME:NC,LICENSE_KEY_DIR_NAME:pC,BOOT_PROPS_FILE_NAME:OC,JOB_TYPE_ENUM:tw,JOB_STATUS_ENUM:WC,SYSTEM_TABLE_NAMES:VC,SYSTEM_TABLE_HASH_ATTRIBUTES:$C,OPERATIONS_ENUM:I,VALID_S3_FILE_TYPES:QC,S3_BUCKET_AUTH_KEYS:JC,VALID_SQL_OPS_ENUM:XC,GEO_CONVERSION_ENUM:zC,HDB_SETTINGS_NAMES:oh,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:jC,SERVICE_ACTIONS_ENUM:ZC,CLUSTER_MESSAGE_TYPE_ENUM:rw,CLUSTER_CONNECTION_DIRECTION_ENUM:sw,CLUSTER_EVENTS_DEFS_ENUM:ow,PERIOD_REGEX:iC,DOUBLE_PERIOD_REGEX:aC,UNICODE_PERIOD:oC,FORWARD_SLASH_REGEX:cC,UNICODE_FORWARD_SLASH:_C,ESCAPED_FORWARD_SLASH_REGEX:uC,ESCAPED_PERIOD_REGEX:lC,ESCAPED_DOUBLE_PERIOD_REGEX:EC,REG_KEY_FILE_NAME:YC,RESTART_TIMEOUT_MS:bC,HDB_FILE_PERMISSIONS:CC,SCHEMA_DIR_NAME:LC,TRANSACTIONS_DIR_NAME:yC,LIMIT_COUNT_NAME:DC,ID_ATTRIBUTE_STRING:MC,INSERT_MODULE_ENUM:GC,UPGRADE_JSON_FIELD_NAMES_ENUM:FC,RESTART_CODE:gC,RESTART_CODE_NUM:IC,CLUSTER_OPERATIONS:yr,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:xC,HDB_INTERNAL_SC_CHANNEL_PREFIX:dt,INTERNAL_SC_CHANNELS:kC,CLUSTERING_MESSAGE_TYPES:hw,HDB_FILE_SUFFIX:AC,BLOB_FOLDER_NAME:wC,HDB_TRASH_DIR:UC,ORIGINATOR_SET_VALUE:Sw,LICENSE_VALUES:iw,RAM_ALLOCATION_ENUM:aw,STORAGE_TYPES_ENUM:nw,TIME_STAMP_NAMES_ENUM:ch,TIME_STAMP_NAMES:lw,PERMS_UPDATE_RELEASE_TIMESTAMP:Ew,SEARCH_NOT_FOUND_MESSAGE:jb,SEARCH_ATTRIBUTE_NOT_FOUND:eC,LICENSE_ROLE_DENIED_RESPONSE:tC,LICENSE_MAX_CONNS_REACHED:rC,BASIC_LICENSE_MAX_NON_CU_ROLES:sh,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:Xb,VALUE_SEARCH_COMPARATORS:_h,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:dw,LICENSE_FILE_NAME:KC,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:cw,NEW_LINE:fw,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:nC,MOMENT_DAYS_TAG:dC,API_TURNOVER_SEC:hC,LOOPBACK:sC,CODE_EXTENSION:Vn,WILDCARD_SEARCH_VALUE:SC,NODE_ERROR_CODES:_w,JAVASCRIPT_EXTENSION:zd,PERMS_CRUD_ENUM:Tw,UNAUTHORIZED_PERMISSION_NAME:Rw,SEARCH_WILDCARDS:mw,FUNC_VAL:Aw,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:pw,JWT_ENUM:Ow,CLUSTERING_FLAG:uw,RUN_LOG:BC,INSTALL_LOG:PC,IPC_SERVER_MODULE:th,HDB_IPC_SERVER:Nw,IPC_EVENT_TYPES:Iw,HDB_IPC_CLIENT_PREFIX:gw,CUSTOM_FUNCTION_PROC_NAME:eh,CUSTOM_FUNCTION_PROC_DESCRIPTOR:da,SERVICES:bw,MEM_SETTING_KEY:fC,HDB_RESTART_SCRIPT:Fb,PROCESS_DESCRIPTORS:Z_,SERVICE_SERVERS:Kb,SERVICE_SERVERS_CWD:Ea,PROCESS_DESCRIPTORS_VALIDATE:xb,LAUNCH_SERVICE_SCRIPTS:Wb,LOG_LEVELS:kb,PROCESS_NAME_ENV_PROP:vC,PROCESS_LOG_NAMES:$b,PM2_PROCESS_STATUSES:Cw,CONFIG_PARAM_MAP:ew,CONFIG_PARAMS:f,HDB_CONFIG_FILE:Hb,HDB_DEFAULT_CONFIG_FILE:qb,ROLE_TYPES_ENUM:Qb,BOOT_PROP_PARAMS:HC,INSTALL_PROMPTS:qC,HDB_ROOT_DIR_NAME:Gb,CLUSTERING_PROCESSES:Yb,FOREGROUND_PID_FILE:Vb,PACKAGE_ROOT:qt,PRE_4_0_0_VERSION:ww}});var tu=h((AJ,dh)=>{"use strict";var lh=require("minimist");dh.exports=Uw;function Uw(e=[],t=!1){if(!Array.isArray(e))return{};let r,s;t?(r=Eh(process.env),s=Eh(lh(process.argv))):(r=process.env,s=lh(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(Uw,"assignCMDENVVariables");function Eh(e){let t,r=Object.keys(e),s=r.length,n={};for(;s--;)t=r[s],n[t.toLowerCase()]=e[t];return n}a(Eh,"objKeysToLowerCase")});var g=h((pJ,Ah)=>{"use strict";var ss=require("fs-extra"),ns=require("path"),Sh=require("yaml"),fh=require("properties-reader"),Re=T(),Lw=tu(),yw=require("os"),{PACKAGE_ROOT:nu}=T(),st={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},fa=ns.join(nu,"logs"),Dr=process.env.pm_id===void 0,Dw=ns.join(nu,"config/yaml/",Re.HDB_DEFAULT_CONFIG_FILE),iu=process.env.PROCESS_NAME===void 0?Re.PROCESS_DESCRIPTORS.INSTALL:process.env.PROCESS_NAME,$s,Jt,ur,rt,ru,ks;ks===void 0&&Th();Ah.exports={createLogFile:Mw,notify:vw,fatal:Hw,error:su,warn:qw,info:Pw,debug:Bw,trace:Rh,setLogLevel:Fw,log_level:rt};function Th(){try{if(ks===void 0){let e=Gw();ks=fh(e),{level:rt,config_log_path:ru,to_file:Jt,to_stream:ur}=Vw(ks.get("settings_path"))}}catch(e){if(ks=void 0,e.code===Re.NODE_ERROR_CODES.ENOENT){let t=Lw(Object.keys(Re.CONFIG_PARAM_MAP),!0);for(let i in t){let o=Re.CONFIG_PARAM_MAP[i];o&&o.toLowerCase();let c=t[i];if(o===Re.CONFIG_PARAMS.LOGGING_LEVEL){rt=c;continue}if(o===Re.CONFIG_PARAMS.LOGGING_STDSTREAMS){ur=c;continue}o===Re.CONFIG_PARAMS.LOGGING_FILE&&(Jt=o)}let{default_level:r,default_to_file:s,default_to_stream:n}=$w();Jt=Jt===void 0?s:Jt,Jt=hh(Jt),ur=ur===void 0?n:ur,ur=hh(ur),rt=rt===void 0?r:rt,ru=fa;return}throw su("Error initializing log settings"),su(e),e}}a(Th,"initLogSettings");function Mw(e,t){if(!Dr){Rh("createLogFile should only be used if the process is not being managed by pm2");return}ks===void 0&&Th(),iu=t;let r;e===Re.PROCESS_LOG_NAMES.INSTALL?r=fa:r=ru,Jt&&($s=ns.join(r,e),ss.ensureFileSync($s))}a(Mw,"createLogFile");function is(e,t){let r=new Date(Date.now()).toISOString(),s="",n=t.length,i=n-1;for(let o=0;o<n;o++){let c=t[o];c instanceof Error&&c.stack?s+=c.stack:typeof c=="object"?s+=JSON.stringify(c):s+=c,o<i&&(s+=" ")}return`{"process_name": "${iu}", "level": "${e}", "timestamp": "${r}", "message": "${s}"}
3
+ `}a(is,"createLogRecord");function mh(e){$s===void 0&&(iu=Re.PROCESS_DESCRIPTORS.INSTALL,ss.ensureDirSync(fa),$s=ns.join(fa,Re.PROCESS_LOG_NAMES.INSTALL),ss.ensureFileSync($s)),ss.appendFileSync($s,e)}a(mh,"writeToLogFile");function Ta(e){Jt&&mh(e),ur&&process.stdout.write(e)}a(Ta,"nonPm2LogStdOut");function au(e){Jt&&mh(e),ur&&process.stderr.write(e)}a(au,"nonPm2LogStdErr");function Pw(...e){if(st[rt]<=st.info){let t=is("info",e);if(Dr){Ta(t);return}process.stdout.write(t)}}a(Pw,"info");function Rh(...e){if(st[rt]<=st.trace){let t=is("trace",e);if(Dr){Ta(t);return}process.stdout.write(t)}}a(Rh,"trace");function su(...e){if(st[rt]<=st.error){let t=is("error",e);if(Dr){au(t);return}process.stderr.write(t)}}a(su,"error");function Bw(...e){if(st[rt]<=st.debug){let t=is("debug",e);if(Dr){Ta(t);return}process.stdout.write(t)}}a(Bw,"debug");function vw(...e){if(st[rt]<=st.notify){let t=is("notify",e);if(Dr){Ta(t);return}process.stdout.write(t)}}a(vw,"notify");function Hw(...e){if(st[rt]<=st.fatal){let t=is("fatal",e);if(Dr){au(t);return}process.stderr.write(t)}}a(Hw,"fatal");function qw(...e){if(st[rt]<=st.warn){let t=is("warn",e);if(Dr){au(t);return}process.stderr.write(t)}}a(qw,"warn");function Gw(){let e;try{e=yw.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=ns.join(e,Re.HDB_HOME_DIR_NAME,Re.BOOT_PROPS_FILE_NAME);return ss.existsSync(t)||(t=ns.join(nu,"utility/hdb_boot_properties.file")),t}a(Gw,"getPropsFilePath");function Fw(e){rt=e}a(Fw,"setLogLevel");function hh(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(hh,"autoCastBoolean");function Vw(e){try{if(e.includes("config/settings.js")){let o=fh(e);return{level:o.get(Re.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:ns.dirname(o.get(Re.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(Re.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(Re.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=Sh.parseDocument(ss.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===Re.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(Vw,"getLogConfig");function $w(){try{let e=Sh.parseDocument(ss.readFileSync(Dw,"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($w,"getDefaultConfig")});var Oh=h((OJ,ph)=>{"use strict";var kw=require("util"),xw=require("path"),Yw=require("child_process"),Kw=kw.promisify(Yw.execFile),Ww=1e3*1e3*10;ph.exports={findPs:Qw};async function Qw(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:s}=await Kw("ps",["wwxo",`pid,${r}`],{maxBuffer:Ww});for(let n of s.trim().split(`
4
+ `).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:xw.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(Qw,"findPs")});var Ke=h((NJ,gh)=>{"use strict";var Jw="__dbis__",Xw="__environment_name__",Zw="__dbi_defintion__",zw={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"},jw=["__createdtime__","__updatedtime__"],eU="\uFFFF",Nh={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},tU=Object.values(Nh);gh.exports={INTERNAL_DBIS_NAME:Jw,DBI_DEFINITION_NAME:Zw,SEARCH_TYPES:zw,TIMESTAMP_NAMES:jw,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:Xw,TRANSACTIONS_DBI_NAMES_ENUM:Nh,TRANSACTIONS_DBIS:tU,OVERFLOW_MARKER:eU}});var We=h((gJ,Mh)=>{"use strict";var Ih=T(),bh=Ke(),Ch={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},wh=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),Uh={500:wh("There was an error processing your request."),400:"Invalid request"},rU=Uh[Ch.INTERNAL_SERVER_ERROR],sU={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.`},nU={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},iU={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"},aU={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_ARRAY:"ids must be an array",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 ${bh.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${bh.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"},oU={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${Ih.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 ${Ih.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"},Lh={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"},cU={DEFAULT_INVALID_REQUEST:"Invalid request",OP_AUTH_PERMS_ERROR:"This operation is not authorized due to role restrictions and/or invalid schema 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' schema, tables and records are used internally by HarperDB and cannot be updated or removed."},_U={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 schema metadata for '${e}'`,SCHEMA_TABLE_PERM_ERROR:(e,t)=>`Your role does not have permission to view schema.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`},uU={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=>`Schema '${e}' does not exist`,SCHEMA_EXISTS_ERR:e=>`Schema '${e}' already exists`,TABLE_EXISTS_ERR:(e,t)=>`Table '${t}' already exists in schema '${e}'`,SCHEMA_REQUIRED_ERR:"schema is required",TABLE_NOT_FOUND:(e,t)=>`Table '${e}.${t}' does not exist`,TABLE_REQUIRED_ERR:"table is required"},lU={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},EU={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`},yh={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.`},Dh={INVALID_IPC_DATA_TYPE:"Invalid IPC event data type, must be an object",MISSING_TYPE:"IPC event missing 'type'",MISSING_MSG:"IPC event missing 'message'",MISSING_ORIGIN:"IPC event message missing 'originator' property",INVALID_EVENT:e=>`IPC server received invalid event type: ${e}`},dU={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 customFunctions enabled to true in hdb/harperdb-config.yaml file."},hU={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},SU={...Lh,...iU,...sU,...cU,..._U,...uU,...lU,...EU,...oU,...yh,...Dh,...dU,...hU,...nU};Mh.exports={CHECK_LOGS_WRAPPER:wh,HDB_ERROR_MSGS:SU,DEFAULT_ERROR_MSGS:Uh,DEFAULT_ERROR_RESP:rU,HTTP_STATUS_CODES:Ch,LMDB_ERRORS_ENUM:aU,AUTHENTICATION_ERROR_MSGS:Lh,VALIDATION_ERROR_MSGS:yh,IPC_ERRORS:Dh}});var D=h((IJ,vh)=>{"use strict";var xs=We(),fU=g(),TU=T(),$n=class extends Error{constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,Ph),this.http_resp_code=s||xs.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(xs.DEFAULT_ERROR_MSGS[s]?xs.DEFAULT_ERROR_MSGS[s]:xs.DEFAULT_ERROR_MSGS[xs.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,typeof this.message!="string"&&(this.stack=t.stack),i&&fU[n](i)}};a($n,"HdbError");function Ph(e,t,r,s=TU.LOG_LEVELS.ERROR,n=null,i=!1){if(Bh(e))return e;let o=new $n(e,t,r,s,n);return i&&delete o.stack,o}a(Ph,"handleHDBError");function Bh(e){return e.__proto__.constructor.name===$n.name}a(Bh,"isHDBError");vh.exports={isHDBError:Bh,handleHDBError:Ph,hdb_errors:xs}});var b=h((CJ,Zh)=>{"use strict";var as=require("path"),mU=require("fs-extra"),be=g(),Hh=require("fs-extra"),RU=require("truncate-utf8-bytes"),kn=require("os"),AU=require("net"),pU=require("recursive-iterator"),ye=T(),$h=Oh(),qh=require("papaparse"),ma=require("moment"),{inspect:OU}=require("util"),Gh=require("is-number"),bJ=require("lodash"),{hdb_errors:Ra}=D(),kh=require("util").promisify(setTimeout),NU=100,gU=5,IU="",bU=4,Fh=255,Vh={true:!0,false:!1,undefined:null,null:null,NaN:NaN};Zh.exports={isEmpty:ht,isEmptyOrZeroLength:Xt,arrayHasEmptyValues:UU,arrayHasEmptyOrZeroLengthValues:LU,buildFolderPath:yU,isBoolean:xh,errorizeMessage:CU,stripFileExtension:MU,autoCast:PU,autoCastJSONDeep:ou,removeDir:vU,compareVersions:HU,isCompatibleDataVersion:qU,escapeRawValue:Kh,unescapeValue:GU,stringifyProps:FU,valueConverter:VU,timeoutPromise:kU,isClusterOperation:YU,getClusterUser:QU,sendTransactionToSocketCluster:KU,checkGlobalSchemaTable:WU,getHomeDir:Wh,getPropsFilePath:$U,promisifyPapaParse:JU,removeBOM:Qh,createEventPromise:XU,checkProcessRunning:ZU,checkSchemaTableExist:zU,checkSchemaExists:Jh,checkTableExists:Xh,getStartOfTomorrowInSeconds:jU,getLimitKey:eL,isObject:DU,isNotEmptyAndHasValue:wU,autoCasterIsNumberCheck:Yh,backtickASTSchemaItems:tL,isPortTaken:xU,stopProcess:rL,createForkArgs:sL,autoCastBoolean:nL,async_set_timeout:kh,getTableHashAttribute:iL,doesSchemaExist:aL,doesTableExist:oL,stringifyObj:cL,ms_to_time:_L,changeExtension:uL,PACKAGE_ROOT:ye.PACKAGE_ROOT};function CU(e){return e instanceof Error?e:new Error(e)}a(CU,"errorizeMessage");function ht(e){return e==null}a(ht,"isEmpty");function wU(e){return!ht(e)&&(e||e===0||e===""||xh(e))}a(wU,"isNotEmptyAndHasValue");function Xt(e){return ht(e)||e.length===0||e.size===0}a(Xt,"isEmptyOrZeroLength");function UU(e){if(ht(e))return!0;for(let t=0;t<e.length;t++)if(ht(e[t]))return!0;return!1}a(UU,"arrayHasEmptyValues");function LU(e){if(Xt(e))return!0;for(let t=0;t<e.length;t++)if(Xt(e[t]))return!0;return!1}a(LU,"arrayHasEmptyOrZeroLengthValues");function yU(...e){try{return e.join(as.sep)}catch{console.error(e)}}a(yU,"buildFolderPath");function xh(e){return ht(e)?!1:e===!0||e===!1}a(xh,"isBoolean");function DU(e){return ht(e)?!1:typeof e=="object"}a(DU,"isObject");function MU(e){return Xt(e)?IU:e.slice(0,-bU)}a(MU,"stripFileExtension");function PU(e){return ht(e)||e===""||typeof e!="string"?e:Vh[e]!==void 0?Vh[e]:Yh(e)===!0?Number(e):e}a(PU,"autoCast");function BU(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(BU,"autoCastJSON");function ou(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=ou(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=ou(r);s!==r&&(e[t]=s)}return e}else return BU(e)}a(ou,"autoCastJSONDeep");function Yh(e){if(e.startsWith("0.")&&Gh(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&Gh(e))}a(Yh,"autoCasterIsNumberCheck");async function vU(e){if(Xt(e))throw new Error(`Directory path: ${e} does not exist`);try{await Hh.emptyDir(e),await Hh.remove(e)}catch(t){throw be.error(`Error removing files in ${e} -- ${t}`),t}}a(vU,"removeDir");function HU(e,t){if(Xt(e)){be.info("Invalid current version sent as parameter.");return}if(Xt(t)){be.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("."),_=Math.min(o.length,c.length);for(let u=0;u<_;u++)if(r=parseInt(o[u],10)-parseInt(c[u],10),r)return r;return o.length-c.length}a(HU,"compareVersions");function qU(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(qU,"isCompatibleDataVersion");function Kh(e){if(ht(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(Kh,"escapeRawValue");function GU(e){if(ht(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(GU,"unescapeValue");function FU(e,t){if(ht(e))return be.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+kn.EOL}!Xt(s)&&s[0]===";"?r+=" "+s+n+kn.EOL:Xt(s)||(r+=s+"="+n+kn.EOL)}catch{be.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a(FU,"stringifyProps");function VU(e){let t;try{t=typeof e=="object"?JSON.stringify(e):e}catch(n){be.error(n),t=e}let r=String(Kh(t)),s=Buffer.byteLength(r)>Fh?RU(r,Fh)+"/blob":r;return{value:t,value_stripped:r,value_path:s}}a(VU,"valueConverter");function Wh(){let e;try{e=kn.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(Wh,"getHomeDir");function $U(){let e=as.join(Wh(),ye.HDB_HOME_DIR_NAME,ye.BOOT_PROPS_FILE_NAME);return mU.existsSync(e)||(e=as.join(__dirname,"../","hdb_boot_properties.file")),e}a($U,"getPropsFilePath");function kU(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a(kU,"timeoutPromise");async function xU(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=AU.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(xU,"isPortTaken");function YU(e){try{return ye.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){be.error(`Error checking operation against cluster ops ${t}`)}return!1}a(YU,"isClusterOperation");function KU(e,t,r){if(global.hdb_socket_client!==void 0){be.trace(`Sending transaction to channel: ${e}`);let{hdb_user:s,hdb_auth_header:n,...i}=t;i.__originator||(i.__originator={}),i.__transacted=!0,r&&(i.__originator[r]=ye.ORIGINATOR_SET_VALUE),global.hdb_socket_client.publish(e,i)}}a(KU,"sendTransactionToSocketCluster");function WU(e,t){if(!global.hdb_schema[e])return Ra.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!global.hdb_schema[e]||!global.hdb_schema[e][t])return Ra.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(WU,"checkGlobalSchemaTable");function QU(e,t){if(ht(t)){be.warn("No CLUSTERING_USER defined, clustering disabled");return}if(ht(e)||Xt(e)){be.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){be.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){be.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(QU,"getClusterUser");function JU(){qh.parsePromise=function(e,t){return new Promise(function(r,s){qh.parse(e,{header:!0,transformHeader:Qh,chunk:t.bind(null,s),skipEmptyLines:!0,dynamicTyping:!0,error:s,complete:r})})}}a(JU,"promisifyPapaParse");function Qh(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(Qh,"removeBOM");function XU(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;be.info(`Got cluster status event response: ${OU(n)}`);try{i.cancel()}catch{be.error("Error trying to cancel timeout.")}s(n)})})}a(XU,"createEventPromise");async function ZU(e){let t=!0,r=0;do await kh(NU*r++),(await $h.findPs(e)).length>0&&(t=!1);while(t&&r<gU);if(t)throw new Error(`process ${e} was not started`)}a(ZU,"checkProcessRunning");function zU(e,t){let r=Jh(e);if(r)return r;let s=Xh(e,t);if(s)return s}a(zU,"checkSchemaTableExist");function Jh(e){if(!global.hdb_schema[e])return Ra.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(Jh,"checkSchemaExists");function Xh(e,t){if(!global.hdb_schema[e][t])return Ra.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Xh,"checkTableExists");function jU(){let e=ma().utc().add(1,ye.MOMENT_DAYS_TAG).startOf(ye.MOMENT_DAYS_TAG).unix(),t=ma().utc().unix();return e-t}a(jU,"getStartOfTomorrowInSeconds");function eL(){return ma().utc().format("DD-MM-YYYY")}a(eL,"getLimitKey");function tL(e){try{let t=new pU(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){be.error("Got an error back ticking items."),be.error(t)}}a(tL,"backtickASTSchemaItems");async function rL(e){let t=kn.userInfo();(await $h.findPs(e)).forEach(s=>{(t.uid==0||s.uid==t.uid)&&(process.kill(s.pid),be.trace(`Following process was killed by stopProcess: ${s.cmd}`))})}a(rL,"stopProcess");function sL(e){return[e]}a(sL,"createForkArgs");function nL(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(nL,"autoCastBoolean");function iL(e,t){return global.hdb_schema?.[e]?.[t]?.hash_attribute}a(iL,"getTableHashAttribute");function aL(e){return global?.hdb_schema?.[e]!==void 0}a(aL,"doesSchemaExist");function oL(e,t){return global?.hdb_schema?.[e]?.[t]!==void 0}a(oL,"doesTableExist");function cL(e){try{return JSON.stringify(e)}catch{return e}}a(cL,"stringifyObj");function _L(e){let t=ma.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(_L,"ms_to_time");function uL(e,t){let r=as.basename(e,as.extname(e));return as.join(as.dirname(e),r+t)}a(uL,"changeExtension")});var de=h((wJ,zh)=>{"use strict";var nt=require("validate.js");nt.validators.type=function(e,t,r,s){return e===null||typeof e>"u"||nt.validators.type.checks[t](e)?null:` must be a '${t}' value`};nt.validators.type.checks={Object:function(e){return nt.isObject(e)&&!nt.isArray(e)},Array:nt.isArray,Integer:nt.isInteger,Number:nt.isNumber,String:nt.isString,Date:nt.isDate,Boolean:function(e){return typeof e=="boolean"}};nt.validators.hasValidFileExt=function(e,t){return!nt.isString(e)||e===""||t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`};zh.exports={validateObject:lL,validateObjectAsync:EL,validateBySchema:dL};function lL(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=nt(e,t,{format:"flat"});return r?new Error(r):null}a(lL,"validateObject");async function EL(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await nt.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}a(EL,"validateObjectAsync");function dL(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(dL,"validateBySchema")});var _u=h((UJ,eS)=>{"use strict";var hL=require("fs-extra"),F=require("joi"),SL=require("os"),{boolean:De,string:lr,number:Zt,array:cu}=F.types(),jh=require("path"),fL=g(),Aa=b(),TL=de(),mL="log",RL="custom_functions",AL="Invalid logging.rotation.maxSize unit. Available units are G, M or K",pL="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",OL="rootPath config parameter is undefined",NL="clustering.enabled config parameter is undefined",Mr=Zt.min(0).required(),pa=cu.items({host:lr.required(),port:Mr}).empty(null),xn;eS.exports={configValidator:gL,routesValidator:LL,route_constraints:pa};function gL(e){if(xn=e.rootPath,Aa.isEmpty(xn))throw OL;let t=De.required(),r=F.valid("production","development").required(),s=Zt.min(1).max(1e3).empty(null).default(wL),n=lr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(UL),i=F.custom(bL).messages({"any.custom":"{:#label} {:#error}"}),o=lr.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null),c=e.clustering?.enabled;if(Aa.isEmpty(c))throw NL;let _;return c===!0?_=F.object({enabled:t,hubServer:F.object({cluster:F.object({name:F.required().empty(null),network:F.object({port:Mr,routes:pa}).required()}).required(),leafNodes:F.object({network:F.object({port:Mr}).required()}).required(),network:F.object({port:Mr}).required()}).required(),leafServer:F.object({network:F.object({port:Mr,routes:pa}).required()}).required(),nodeName:o,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:De.required()}),user:F.string().required()}).required():_=F.object({enabled:t,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:De.required()})}).required(),F.object({clustering:_,customFunctions:F.object({enabled:t,network:F.object({cors:De.required(),corsAccessList:cu.required(),headersTimeout:Zt.min(1).required(),https:De.required(),keepAliveTimeout:Zt.min(1).required(),port:Mr,timeout:Zt.min(1).required()}),nodeEnv:r,root:n,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),ipc:F.object({network:F.object({port:Mr})}).required(),localStudio:F.object({enabled:t}).required(),logging:F.object({file:De.required(),level:F.valid("notify","fatal","error","warn","info","debug","trace"),rotation:F.object({compress:De.required(),dateFormat:lr.required(),maxSize:lr.custom(CL).required(),retain:Zt.min(0).required(),rotate:De.required(),rotateInterval:lr.required(),rotateModule:De.required(),timezone:lr.required(),workerInterval:Zt.min(1).required()}).required(),root:n,stdStreams:De.required(),auditLog:De.required()}).required(),operationsApi:F.object({authentication:F.object({operationTokenTimeout:F.required(),refreshTokenTimeout:F.required()}).required(),foreground:De.required(),network:F.object({cors:De.required(),corsAccessList:cu.required(),headersTimeout:Zt.min(1).required(),https:De.required(),keepAliveTimeout:Zt.min(1).required(),port:Mr,timeout:Zt.min(1).required()}).required(),nodeEnv:r,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),rootPath:lr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),http:F.object({threads:s}).required(),storage:F.object({writeAsync:De.required(),overlappingSync:De.optional()}).required()}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(gL,"configValidator");function IL(e){return hL.existsSync(e)?null:`Specified path ${e} does not exist.`}a(IL,"doesPathExist");function bL(e,t){if(e===null)return;F.assert(e,lr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+\.pem+$/).messages({"string.pattern.base":"must be a valid directory path and specify a .pem file"}));let r=IL(e);return r?t.message(r):e}a(bL,"validatePemFile");function CL(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(AL);let s=e.slice(0,-1);if(isNaN(parseInt(s)))return t.message(pL)}a(CL,"validateRotationMaxSize");function wL(e,t){let r=t.state.path.join("."),s=SL.cpus().length,n=s-1;return n<=2&&(n=2),fL.info(`Detected ${s} cores on this machine, defaulting ${r} to ${n}`),n}a(wL,"setDefaultThreads");function UL(e,t){if(!Aa.isEmpty(t.original))return t.original;let r=t.state.path.join(".");if(Aa.isEmpty(xn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"customFunctions.root":return jh.join(xn,RL);case"logging.root":return jh.join(xn,mL);default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(UL,"setDefaultRoot");function LL(e){let t=F.object({routes:pa});return TL.validateBySchema({routes:e},t)}a(LL,"routesValidator")});var Er=h((LJ,oS)=>{"use strict";var se=T(),It=b(),Qe=g(),{configValidator:yL,routesValidator:tS}=_u(),Gt=require("fs-extra"),DL=require("yaml"),Ys=require("path"),ML=require("is-number"),ga=require("properties-reader"),PL=require("lodash"),{handleHDBError:BL}=D(),{HTTP_STATUS_CODES:vL,HDB_ERROR_MSGS:Oa}=We(),{PACKAGE_ROOT:HL}=T(),qL="Unable to get config value because config is uninitialized",GL="Config successfully initialized",FL="Error backing up config file",VL="Empty parameter sent to getConfigValue",rS=Ys.join(HL,"config","yaml",se.HDB_DEFAULT_CONFIG_FILE),$L="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",Na,it;oS.exports={createConfigFile:kL,getDefaultConfig:xL,getConfigValue:sS,initConfig:nS,flattenConfig:os,updateConfigValue:iS,updateConfigObject:YL,getConfiguration:KL,setConfiguration:WL,readConfigFile:Eu,getClusteringRoutes:QL,initOldConfig:aS,getConfigFromFile:JL};function kL(e){let t=Ks(rS);Na=os(t.toJSON());for(let i in e){let o=se.CONFIG_PARAM_MAP[i.toLowerCase()];if(o!==void 0){let c=o.split("_"),_=uu(o,e[i]);try{t.setIn([...c],_)}catch(u){Qe.error(u)}}}lu(t);let r=t.toJSON();it=os(r);let s=t.getIn(["rootPath"]),n=Ys.join(s,se.HDB_CONFIG_FILE);Gt.createFileSync(n),Gt.writeFileSync(n,String(t)),Qe.trace(`Config file written to ${n}`)}a(kL,"createConfigFile");function xL(e){if(Na===void 0){let r=Ks(rS);Na=os(r.toJSON())}let t=se.CONFIG_PARAM_MAP[e.toLowerCase()];if(t!==void 0)return Na[t.toLowerCase()]}a(xL,"getDefaultConfig");function sS(e){if(It.isEmpty(e)){Qe.error(VL);return}if(it===void 0){Qe.trace(qL);return}let t=se.CONFIG_PARAM_MAP[e.toLowerCase()];if(t!==void 0)return it[t.toLowerCase()]}a(sS,"getConfigValue");function nS(e=!1){if(it===void 0||e){let t=It.getPropsFilePath();try{Gt.accessSync(t,Gt.constants.F_OK|Gt.constants.R_OK)}catch(o){throw Qe.error(o),new Error(`HarperDB properties file at path ${t} does not exist`)}let s=ga(t).get(se.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),n;if(s.includes("config/settings.js"))try{aS(s);return}catch(o){if(o.code!==se.NODE_ERROR_CODES.ENOENT)throw o}try{n=Ks(s)}catch(o){if(o.code===se.NODE_ERROR_CODES.ENOENT){Qe.trace(`HarperDB config file not found at ${s}.
5
+ This can occur during early stages of install where the config file has not yet been created`);return}else throw Qe.error(o),new Error(`Error reading HarperDB config file at ${s}`)}lu(n);let i=n.toJSON();it=os(i),Qe.trace(GL)}}a(nS,"initConfig");function lu(e){let t=e.toJSON(),r=yL(t);if(r.error)throw Oa.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(["operationsApi","tls","certificate"],r.value.operationsApi.tls.certificate),e.setIn(["operationsApi","tls","privateKey"],r.value.operationsApi.tls.privateKey),e.setIn(["operationsApi","tls","certificateAuthority"],r.value.operationsApi.tls.certificateAuthority),e.setIn(["customFunctions","tls","certificate"],r.value.customFunctions.tls.certificate),e.setIn(["customFunctions","tls","privateKey"],r.value.customFunctions.tls.privateKey),e.setIn(["customFunctions","tls","certificateAuthority"],r.value.customFunctions.tls.certificateAuthority),e.setIn(["clustering","tls","certificate"],r.value.clustering.tls.certificate),e.setIn(["clustering","tls","privateKey"],r.value.clustering.tls.privateKey),e.setIn(["clustering","tls","certificateAuthority"],r.value.clustering.tls.certificateAuthority)}a(lu,"validateConfig");function YL(e,t){it===void 0&&(it={});let r=se.CONFIG_PARAM_MAP[e.toLowerCase()];if(r===void 0){Qe.trace(`Unable to update config object because config param '${e}' does not exist`);return}it[r.toLowerCase()]=t}a(YL,"updateConfigObject");function iS(e,t,r=void 0,s=!1,n=!1){it===void 0&&nS();let i=sS(se.CONFIG_PARAM_MAP.hdb_root),o=Ys.join(i,se.HDB_CONFIG_FILE),c=Ks(o);if(r===void 0){let l=se.CONFIG_PARAM_MAP[e.toLowerCase()];if(l===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=l.split("_"),d=uu(l,t);c.setIn([...E],d)}else for(let l in r){let E=se.CONFIG_PARAM_MAP[l.toLowerCase()];if(E!==void 0){let d=E.split("_"),S=uu(E,r[l]);try{c.setIn([...d],S)}catch(m){Qe.error(m)}}}lu(c);let _=c.getIn(["rootPath"]),u=Ys.join(_,se.HDB_CONFIG_FILE);if(s===!0)try{let l=Ys.join(_,"backup",`${se.HDB_CONFIG_FILE}.bak`);Gt.copySync(o,l),Qe.trace(`Config file: ${o} backed up to: ${l}`)}catch(l){Qe.error(FL),Qe.error(l)}Gt.writeFileSync(u,String(c)),n&&(it=os(c.toJSON())),Qe.trace(`Config parameter: ${e} updated with value: ${t}`)}a(iS,"updateConfigValue");function os(e){let t={};for(let r in e)if(!!e.hasOwnProperty(r))if(typeof e[r]=="object"&&e[r]!==null&&!Array.isArray(e[r])){let s=os(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(os,"flattenConfig");function uu(e,t){if(e===se.CONFIG_PARAMS.CLUSTERING_NODENAME||e===se.CONFIG_PARAMS.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(ML(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||It.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 It.autoCast(t)}a(uu,"castConfigValue");function KL(){let e=It.getPropsFilePath(),r=ga(e).get(se.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY);return Ks(r).toJSON()}a(KL,"getConfiguration");async function WL(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return iS(void 0,void 0,n,!0),$L}catch(i){throw typeof i=="string"||i instanceof String?BL(i,i,vL.BAD_REQUEST,void 0,void 0,!0):i}}a(WL,"setConfiguration");function Eu(){let e=It.getPropsFilePath();try{Gt.accessSync(e,Gt.constants.F_OK|Gt.constants.R_OK)}catch(n){throw Qe.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let r=ga(e).get(se.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY);return Ks(r).toJSON()}a(Eu,"readConfigFile");function Ks(e){return DL.parseDocument(Gt.readFileSync(e,"utf8"),{simpleKeys:!0})}a(Ks,"parseYamlDoc");function QL(){let e=Eu(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=It.isEmptyOrZeroLength(t)?[]:t;let r=tS(t);if(r)throw Oa.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=It.isEmptyOrZeroLength(s)?[]:s;let n=tS(s);if(n)throw Oa.CONFIG_VALIDATION(n.message);if(!It.isEmptyOrZeroLength(s)&&!It.isEmptyOrZeroLength(t)){let i=t.filter(o=>s.some(c=>c.host===o.host&&c.port===o.port));if(!It.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw Oa.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:s}}a(QL,"getClusteringRoutes");function aS(e){let t=ga(e);it={};for(let r in se.CONFIG_PARAM_MAP){let s=t.get(r.toUpperCase());if(It.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=se.CONFIG_PARAM_MAP[r].toLowerCase();n===se.CONFIG_PARAMS.LOGGING_ROOT?it[n]=Ys.dirname(s):it[n]=s}return it}a(aS,"initOldConfig");function JL(e){let t=Eu();return PL.get(t,e.replaceAll("_","."))}a(JL,"getConfigFromFile")});var V=h((yJ,_S)=>{"use strict";var du=require("fs-extra"),zt=require("path"),XL=require("os"),ZL=require("properties-reader"),Yn=g(),Ws=b(),M=T(),Ia=Er(),zL="Error initializing environment manager",ba="BOOT_PROPS_FILE_PATH",cS=!1,jL={[M.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},dr={};_S.exports={BOOT_PROPS_FILE_PATH:ba,getHdbBasePath:ey,setHdbBasePath:ty,get:ry,initSync:ny,setProperty:Y,initTestEnvironment:iy};function ey(){return dr[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(ey,"getHdbBasePath");function ty(e){dr[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(ty,"setHdbBasePath");function ry(e){let t=Ia.getConfigValue(e);return t===void 0?dr[e]:t}a(ry,"get");function Y(e,t){jL[e]&&(dr[e]=t),Ia.updateConfigObject(e,t)}a(Y,"setProperty");function sy(){let e;try{e=Ws.getPropsFilePath(),du.accessSync(e,du.constants.F_OK|du.constants.R_OK),cS=!0;let t=ZL(e);return dr[M.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(M.HDB_SETTINGS_NAMES.INSTALL_USER),dr[M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),dr[ba]=e,!0}catch{return Yn.trace(`Environment manager found no properties file at ${e}`),!1}}a(sy,"doesPropFileExist");function ny(e=!1){try{(cS||sy())&&(Ia.initConfig(e),dr[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Ia.getConfigValue(M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Yn.error(zL),Yn.error(t),console.error(t),process.exit(1)}}a(ny,"initSync");function iy(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,_=zt.join(__dirname,"../../","unitTests");dr[ba]=zt.join(_,"hdb_boot_properties.file"),Y(M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,zt.join(_,"settings.test")),Y(M.HDB_SETTINGS_NAMES.INSTALL_USER,XL.userInfo().username),Y(M.HDB_SETTINGS_NAMES.PRIVATE_KEY_KEY,zt.join(_,"envDir","utility","keys","privateKey.pem")),Y(M.HDB_SETTINGS_NAMES.CERT_KEY,zt.join(_,"envDir","utility","keys","certificate.pem")),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,zt.join(_,"envDir","utility","keys","privateKey.pem")),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_CERTIFICATE,zt.join(_,"envDir","utility","keys","certificate.pem")),Y(M.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Y(M.HDB_SETTINGS_NAMES.LOG_PATH_KEY,zt.join(_,"envDir","log")),Y(M.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Y(M.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Y(M.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Y(M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,zt.join(_,"envDir")),Y(M.HDB_SETTINGS_NAMES.HTTP_SECURE_ENABLED_KEY,Ws.isEmpty(n)?!0:n),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,Ws.isEmpty(n)?!0:n),Y(M.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Y(M.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Ws.isEmpty(i)?!1:i),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORS,Ws.isEmpty(i)?!1:i),Y(M.HDB_SETTINGS_NAMES.IPC_SERVER_PORT,9383),Y(M.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Y(M.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Y(M.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Y(M.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Y(M.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,zt.resolve(__dirname,"../../unitTests/server/customFunctions/custom_functions")),Y(M.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Ws.isEmpty(c)?!1:c),o&&(Y("CORS_ACCESSLIST",o),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,o)),s&&(Y(M.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,s)),t&&(Y(M.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,t)),r&&(Y(M.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${ba}. Please check your boot props and settings files`;Yn.fatal(r),Yn.error(t)}}a(iy,"initTestEnvironment")});var cs=h((DJ,ay)=>{ay.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_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]}}});var OS=h((PJ,pS)=>{"use strict";var hu=require("recursive-iterator"),oy=require("alasql"),Su=require("clone"),uS=b(),{handleHDBError:lS,hdb_errors:cy}=D(),{HDB_ERROR_MSGS:ES,HTTP_STATUS_CODES:dS}=cy,_y=["DISTINCT_ARRAY"],hS=Symbol("validateTables"),fu=Symbol("validateTable"),MJ=Symbol("getAllColumns"),SS=Symbol("validateAllColumns"),Ca=Symbol("findColumn"),fS=Symbol("validateOrderBy"),Kn=Symbol("validateSegment"),Tu=Symbol("validateColumn"),TS=Symbol("setColumnsForTable"),mS=Symbol("checkColumnsForAsterisk"),RS=Symbol("validateGroupBy"),AS=Symbol("hasColumns"),wa=class{constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[hS](),this[mS](),this[SS]()}[hS](){if(this[AS]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[fu](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[fu](t.table)})}}[AS](){let t=!1,r=new hu(this.statement);for(let{node:s,path:n}of r)if(s&&s.columnid){t=!0;break}return t}[fu](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;if(!global.hdb_schema[t.databaseid])throw lS(new Error,ES.SCHEMA_NOT_FOUND(t.databaseid),dS.NOT_FOUND);if(!global.hdb_schema[t.databaseid][t.tableid])throw lS(new Error,ES.TABLE_NOT_FOUND(t.databaseid,t.tableid),dS.NOT_FOUND);global.hdb_schema[t.databaseid][t.tableid].attributes.forEach(s=>{let n=Su(s);n.table=Su(t),this.attributes.push(n)})}[Ca](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)}[mS](){let t=new hu(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[TS](r.tableid)}[TS](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&this.statement.columns.push(new oy.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[SS](){this[Kn](this.statement.columns,!1),this[Kn](this.statement.joins,!1),this[Kn](this.statement.where,!1),this[RS](this.statement.group,!1),this[Kn](this.statement.order,!0)}[Kn](t,r){if(!t)return;let s=new hu(t),n=[];for(let{node:i,path:o}of s)!uS.isEmpty(i)&&!uS.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[fS](i):n.push(this[Tu](i)));return n}[RS](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&_y.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=Su(s);delete n.as,r.push(n)}else if(s.columnid){let n=this[Ca](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[Ca](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`}[fS](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[Tu](t)}[Tu](t){let r=this[Ca](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]}};a(wa,"SelectValidator");pS.exports=wa});var mu=h((BJ,NS)=>{"use strict";var Ua=class{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")}};a(Ua,"BridgeMethods");NS.exports=Ua});var _s=h((qJ,CS)=>{"use strict";var gS=We().LMDB_ERRORS_ENUM,vJ=require("lmdb"),uy=Ke(),HJ=require("buffer").Buffer,ly=require("microtime"),{OVERFLOW_MARKER:IS,MAX_SEARCH_KEY_LENGTH:La}=uy,bS=["number","string","symbol","boolean","bigint"];function Ey(e){if(!e)throw new Error(gS.ENV_REQUIRED);if(e.constructor.name!=="LMDBStore")throw new Error(gS.INVALID_ENVIRONMENT)}a(Ey,"validateEnv");function dy(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(dy,"stringifyData");function hy(e){return e instanceof Date?e.valueOf():e}a(hy,"convertKeyValueToWrite");function Sy(e){if(e==null)return;if(bS.includes(typeof e))return e.length>La?[e.slice(0,La)+IS]:[e];let t;if(Array.isArray(e)){t=[];for(let r=0,s=e.length;r<s;r++){let n=e[r];bS.includes(typeof n)&&(n.length>La?t.push(n.slice(0,La)+IS):t.push(n))}}return t}a(Sy,"getIndexedValues");function fy(){let e=ly.now().toString(),t=e.length-3;return Number(e.slice(0,t)+"."+e.slice(t))}a(fy,"getMicroTime");CS.exports={validateEnv:Ey,stringifyData:dy,convertKeyValueToWrite:hy,getMicroTime:fy,getIndexedValues:Sy}});var US=h((GJ,wS)=>{"use strict";var ya=class{constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};a(ya,"DBIDefinition");wS.exports=ya});var yS=h((FJ,LS)=>{"use strict";var Da=class{constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache={validated:!0},this.randomAccessStructure=!0,this.freezeData=!0)}};a(Da,"OpenDBIObject");LS.exports=Da});var MS=h((VJ,DS)=>{"use strict";var Ma=class{constructor(t,r,s,n,i=!1,o=!1,c=void 0){this.path=t,this.mapSize=r,this.maxDbs=s,this.maxReaders=n,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=i,this.trackMetrics=!0,this.noSync=o,c!==void 0&&(this.overlappingSync=c)}};a(Ma,"OpenEnvironmentObject");DS.exports=Ma});var Z=h((kJ,YS)=>{"use strict";var Ru=require("lmdb"),bt=require("fs-extra"),Ft=require("path"),Ba=_s(),PS=g(),Me=We().LMDB_ERRORS_ENUM,va=US(),Au=yS(),BS=MS(),Pr=Ke(),$J=T(),Wn=V();Wn.initSync();var vS=Wn.get("STORAGE_WRITEASYNC")===!0||Wn.get("STORAGE_WRITEASYNC")==="true"||Wn.get("STORAGE_WRITEASYNC")==="TRUE",HS=Wn.get("STORAGE_OVERLAPPINGSYNC"),qS=1024*1024*1024,GS=1e4,FS=1e3,Vt=Pr.INTERNAL_DBIS_NAME,VS=Pr.DBI_DEFINITION_NAME,Ty="data.mdb",my="lock.mdb",Qn=".mdb",Ry="-lock",Pa=class{constructor(t,r,s=!1){this.dbi=Ct(t,r),this.key_type=this.dbi[Pr.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[Pr.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:s===!1}),this.cursor=new Ru.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};a(Pa,"TransactionCursor");function pu(e,t){if(e===void 0)throw new Error(Me.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(Me.ENV_NAME_REQUIRED)}a(pu,"pathEnvNameValidation");async function Ou(e,t,r=!0){try{await bt.access(e)}catch(s){throw s.code==="ENOENT"?new Error(Me.INVALID_BASE_PATH):s}try{let s=Ft.join(e,t+Qn);return await bt.access(s,bt.constants.R_OK|bt.constants.F_OK),s}catch(s){if(s.code==="ENOENT")if(r)try{return await bt.access(Ft.join(e,t,Ty),bt.constants.R_OK|bt.constants.F_OK),Ft.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(Me.INVALID_ENVIRONMENT)}else throw new Error(Me.INVALID_ENVIRONMENT);throw s}}a(Ou,"validateEnvironmentPath");function Ha(e,t){if(Ba.validateEnv(e),t===void 0)throw new Error(Me.DBI_NAME_REQUIRED)}a(Ha,"validateEnvDBIName");async function Ay(e,t,r=!1,s=!1){pu(e,t),t=t.toString();try{return await Ou(e,t,s),Nu(e,t,r)}catch(n){if(n.message===Me.INVALID_ENVIRONMENT){let i=Ft.join(e,t);await bt.mkdirp(s?i:e);let o=new BS(s?i:i+Qn,qS,GS,FS,!1,vS,HS),c=Ru.open(o);c.dbis=Object.create(null);let _=new Au(!1);c.openDB(Vt,_),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let u=gu(e,t,r);return c[Pr.ENVIRONMENT_NAME_KEY]=u,global.lmdb_map[u]=c,c}throw n}}a(Ay,"createEnvironment");async function py(e,t,r,s=!0){let n=await Nu(e,t);if(r===void 0)throw new Error(Me.DESTINATION_PATH_REQUIRED);try{await bt.access(Ft.dirname(r))}catch(i){throw i.code==="ENOENT"?new Error(Me.INVALID_DESTINATION_PATH):i}await n.backup(r,s)}a(py,"copyEnvironment");async function Nu(e,t,r=!1){pu(e,t),t=t.toString();let s=gu(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 Ou(e,t),i=Ft.join(e,t+Qn),o=n!=i,c=new BS(n,qS,GS,FS,o,vS,HS),_=Ru.open(c);_.dbis=Object.create(null);let u=kS(_);for(let l=0;l<u.length;l++)Ct(_,u[l]);return _[Pr.ENVIRONMENT_NAME_KEY]=s,global.lmdb_map[s]=_,_}a(Nu,"openEnvironment");async function Oy(e,t,r=!1){pu(e,t),t=t.toString();let s=Ft.join(e,t+Qn),n=await Ou(e,t);if(global.lmdb_map!==void 0){let i=gu(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await $S(o),delete global.lmdb_map[i]}}await bt.remove(n),await bt.remove(n===s?n+Ry:Ft.join(Ft.dirname(n),my))}a(Oy,"deleteEnvironment");async function $S(e){Ba.validateEnv(e);let t=e[Pr.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a($S,"closeEnvironment");function gu(e,t,r=!1){let n=`${Ft.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}a(gu,"getCachedEnvironmentName");function Ny(e){Ba.validateEnv(e);let t=Object.create(null),r=Ct(e,Vt);for(let{key:s,value:n}of r.getRange({start:!1}))if(s!==Vt)try{t[s]=Object.assign(new va,n)}catch{PS.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}a(Ny,"listDBIDefinitions");function kS(e){Ba.validateEnv(e);let t=[],r=Ct(e,Vt);for(let{key:s}of r.getRange({start:!1}))s!==Vt&&t.push(s);return t}a(kS,"listDBIs");function gy(e,t){let s=Ct(e,Vt).getEntry(t),n=new va;if(s!==void 0){try{n=Object.assign(n,s.value)}catch{PS.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return n}}a(gy,"getDBIDefinition");function xS(e,t,r,s=!1){if(Ha(e,t),t=t.toString(),t===Vt)throw new Error(Me.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return Ct(e,t)}catch(n){if(n.message===Me.DBI_DOES_NOT_EXIST){let i=new Au(r,s===!0),o=e.openDB(t,i),c=new va(r===!0,s);return o[VS]=c,Ct(e,Vt).putSync(t,c),e.dbis[t]=o,o}throw n}}a(xS,"createDBI");function Ct(e,t){if(Ha(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==Vt?r=gy(e,t):r=new va,r===void 0)throw new Error(Me.DBI_DOES_NOT_EXIST);let s;try{let n=new Au(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(Me.DBI_DOES_NOT_EXIST):n}return s[VS]=r,e.dbis[t]=s,s}a(Ct,"openDBI");function Iy(e,t){Ha(e,t),t=t.toString();let r=Ct(e,t),s=r.getStats();return r[Pr.DBI_DEFINITION_NAME].is_hash_attribute&&s.entryCount>0&&s.entryCount--,s}a(Iy,"statDBI");async function by(e,t){try{let r=Ft.join(e,t+Qn);return(await bt.stat(r)).size}catch{throw new Error(Me.INVALID_ENVIRONMENT)}}a(by,"environmentDataSize");function Cy(e,t){if(Ha(e,t),t=t.toString(),t===Vt)throw new Error(Me.CANNOT_DROP_INTERNAL_DBIS_NAME);Ct(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],Ct(e,Vt).removeSync(t)}a(Cy,"dropDBI");function wy(e,t,r){for(let s=0;s<r.length;s++){let n=r[s];if(!e.dbis[n])try{Ct(e,n)}catch(i){if(i.message===Me.DBI_DOES_NOT_EXIST)xS(e,n,n!==t,n===t);else throw i}}}a(wy,"initializeDBIs");YS.exports={openDBI:Ct,openEnvironment:Nu,createEnvironment:Ay,listDBIs:kS,listDBIDefinitions:Ny,createDBI:xS,dropDBI:Cy,statDBI:Iy,deleteEnvironment:Oy,initializeDBIs:wy,TransactionCursor:Pa,environmentDataSize:by,copyEnvironment:py,closeEnvironment:$S}});var WS=h((xJ,KS)=>{"use strict";var qa=class{constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};a(qa,"InsertRecordsResponseObject");KS.exports=qa});var JS=h((YJ,QS)=>{"use strict";var Ga=class{constructor(t=[],r=[],s=void 0,n=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s,this.original_records=n}};a(Ga,"UpdateRecordsResponseObject");QS.exports=Ga});var ZS=h((KJ,XS)=>{"use strict";var Fa=class{constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};a(Fa,"UpsertRecordsResponseObject");XS.exports=Fa});var Qs=h((XJ,jS)=>{"use strict";var Uy=Z(),Ly=WS(),yy=JS(),Dy=ZS(),Xn=_s(),Jn=We().LMDB_ERRORS_ENUM,My=Ke(),Br=T(),Py=b(),By=require("uuid"),WJ=require("lmdb"),{handleHDBError:vy,hdb_errors:Hy}=D(),{OVERFLOW_MARKER:QJ,MAX_SEARCH_KEY_LENGTH:JJ}=My,Iu=Br.TIME_STAMP_NAMES_ENUM.CREATED_TIME,us=Br.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function qy(e,t,r,s,n=!0){Uu(e,t,r,s),bu(e,t,r);let i=new Ly,o=[],c=[];for(let _=0;_<s.length;_++){let u=s[_];zS(u,!0,n);let l=Gy(e,t,r,u),E=u[t];o.push(l),c.push(E)}return Cu(o,c,s,i)}a(qy,"insertRecords");function Gy(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 u=c([[{}]]);Array.isArray(u)&&(c=u[0][Br.FUNC_VAL],s[o]=c)}let _=Xn.getIndexedValues(c);if(_)for(let u=0,l=_.length;u<l;u++)e.dbis[o].put(_[u],n)}e.dbis[t].put(n,s,s[us])})}a(Gy,"insertRecord");function Fy(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(Fy,"removeSkippedRecords");function zS(e,t,r=!0){let s=Date.now();(r===!0||!Number.isInteger(e[us]))&&(e[us]=s),t===!0?(r===!0||!Number.isInteger(e[Iu]))&&(e[Iu]=s):delete e[Iu]}a(zS,"setTimestamps");function bu(e,t,r){r.indexOf(Br.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Br.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Br.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Br.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),Uy.initializeDBIs(e,t,r)}a(bu,"initializeTransaction");async function Vy(e,t,r,s,n=!0){Uu(e,t,r,s),bu(e,t,r);let i=new yy,o=[],c=[],_=[];for(let u=0;u<s.length;u++){let l=s[u],E=l[t],d;try{d=wu(e,t,l,E,i,!0,n)}catch{i.skipped_hashes.push(E),o.push(u);continue}c.push(d),_.push(E)}return Cu(c,_,s,i,o)}a(Vy,"updateRecords");async function $y(e,t,r,s,n=!0){try{Uu(e,t,r,s)}catch(_){throw vy(_,_.message,Hy.HTTP_STATUS_CODES.BAD_REQUEST)}bu(e,t,r);let i=new Dy,o=[],c=[];for(let _=0;_<s.length;_++){let u=s[_],l;Py.isEmpty(u[t])?(l=By.v4(),u[t]=l):l=u[t];let E=wu(e,t,u,l,i,!1,n);o.push(E),c.push(l)}return Cu(o,c,s,i)}a($y,"upsertRecords");async function Cu(e,t,r,s,n=[]){let i=await Promise.all(e);for(let o=0,c=i.length;o<c;o++)i[o]===!0?s.written_hashes.push(t[o]):(s.skipped_hashes.push(t[o]),n.push(o));return s.txn_time=Xn.getMicroTime(),Fy(r,n),s}a(Cu,"finalizeWrite");function wu(e,t,r,s,n,i=!1,o=!0){let c=e.dbis[t],_=c.getEntry(s),u=_?.value,l=u;if(!u){if(i)return!1;u={}}if(zS(r,!l,o),Number.isInteger(r[us])&&u[us]>r[us])return!1;l&&n.original_records.push(u);let E,d=a(()=>{for(let m in r){if(!r.hasOwnProperty(m)||m===t)continue;let R=r[m],w=e.dbis[m];if(w===void 0)continue;let U=u[m];if(typeof R=="function"){let j=R([[u]]);Array.isArray(j)&&(R=j[0][Br.FUNC_VAL],r[m]=R)}if(R===U)continue;let B=Xn.getIndexedValues(U);if(B)for(let j=0,$=B.length;j<$;j++)w.remove(B[j],s);if(B=Xn.getIndexedValues(R),B)for(let j=0,$=B.length;j<$;j++)w.put(B[j],s)}let S=Object.assign({},u,r);c.put(s,S,S[us])},"do_put");return _?E=c.ifVersion(s,_.version,d):E=c.ifNoExists(s,d),E.then(S=>S?!0:wu(e,t,r,s,n,i,o))}a(wu,"updateUpsertRecord");function ky(e,t,r){if(Xn.validateEnv(e),t===void 0)throw new Error(Jn.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Jn.WRITE_ATTRIBUTES_REQUIRED):new Error(Jn.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(ky,"validateBasic");function Uu(e,t,r,s){if(ky(e,t,r),!Array.isArray(s))throw s===void 0?new Error(Jn.RECORDS_REQUIRED):new Error(Jn.RECORDS_MUST_BE_ARRAY)}a(Uu,"validateWrite");jS.exports={insertRecords:qy,updateRecords:Vy,upsertRecords:$y}});var re=h((ZJ,tf)=>{"use strict";var Lu=T(),Js=V(),yu=require("path");Js.initSync();var Va,$a,ka;function ef(){if(Va!==void 0)return Va;if(Js.getHdbBasePath()!==void 0)return Va=yu.join(Js.getHdbBasePath(),Lu.SCHEMA_DIR_NAME),Va}a(ef,"getBaseSchemaPath");function xy(){if($a!==void 0)return $a;if(Js.getHdbBasePath()!==void 0)return $a=yu.join(ef(),Lu.SYSTEM_SCHEMA_NAME),$a}a(xy,"getSystemSchemaPath");function Yy(){if(ka!==void 0)return ka;if(Js.getHdbBasePath()!==void 0)return ka=yu.join(Js.getHdbBasePath(),Lu.TRANSACTIONS_DIR_NAME),ka}a(Yy,"getTransactionAuditStorePath");tf.exports={getBaseSchemaPath:ef,getSystemSchemaPath:xy,getTransactionAuditStorePath:Yy}});var hr=h((zJ,nf)=>{"use strict";var sf=b(),rf=T(),Ya=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Du=require("joi"),xa={schema_format:{pattern:Ya,message:"names cannot include backticks or forward slashes"},schema_length:{maximum:250,tooLong:"cannot exceed 250 characters"}},Ky=Du.alternatives(Du.string().min(1).max(xa.schema_length.maximum).pattern(Ya).messages({"string.pattern.base":"{:#label} "+xa.schema_format.message}),Du.number()).required();function Wy(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>xa.schema_length.maximum?`'${e}' maximum of 250 characters`:Ya.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(Wy,"checkValidTable");function Qy(e,t){return sf.doesSchemaExist(e)?e:t.message(`Schema '${e}' does not exist`)}a(Qy,"validateSchemaExists");function Jy(e,t){let r=t.state.ancestors[0].schema;return sf.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(Jy,"validateTableExists");function Xy(e,t){return e.toLowerCase()===rf.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid schema name, '${rf.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(Xy,"validateSchemaName");nf.exports={common_validators:xa,schema_regex:Ya,hdb_schema_table:Ky,validateSchemaExists:Qy,validateTableExists:Jy,validateSchemaName:Xy,checkValidTable:Wy}});var Ka=h((jJ,af)=>{var{common_validators:vr}=hr(),Zn=de(),$t="is required",z={schema:{presence:!0,format:vr.schema_format,length:vr.schema_length},table:{presence:!0,format:vr.schema_format,length:vr.schema_length},attribute:{presence:!0,format:vr.schema_format,length:vr.schema_length},hash_attribute:{presence:!0,format:vr.schema_format,length:vr.schema_length}};function zn(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(zn,"makeAttributesStrings");function Zy(e){return e=zn(e),z.schema.presence={message:$t},z.table.presence=!1,z.attribute.presence=!1,z.hash_attribute.presence=!1,Zn.validateObject(e,z)}a(Zy,"schema_object");function zy(e){return e=zn(e),z.schema.presence={message:$t},z.table.presence={message:$t},z.attribute.presence=!1,z.hash_attribute.presence=!1,Zn.validateObject(e,z)}a(zy,"table_object");function jy(e){return e=zn(e),z.schema.presence={message:$t},z.table.presence={message:$t},z.attribute.presence=!1,z.hash_attribute.presence={message:$t},Zn.validateObject(e,z)}a(jy,"create_table_object");function eD(e){return e=zn(e),z.schema.presence={message:$t},z.table.presence={message:$t},z.attribute.presence={message:$t},z.hash_attribute.presence=!1,Zn.validateObject(e,z)}a(eD,"attribute_object");function tD(e){return e=zn(e),z.schema.presence={message:$t},z.table.presence={message:$t},z.attribute.presence=!1,z.hash_attribute.presence=!1,Zn.validateObject(e,z)}a(tD,"describe_table");function rD(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(rD,"validateTableResidence");af.exports={schema_object:Zy,create_table_object:jy,table_object:zy,attribute_object:eD,describe_table:tD,validateTableResidence:rD}});var cf=h((eX,of)=>{"use strict";var sD=require("uuid"),Wa=class{constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||sD.v4(),this.schema_table=`${this.schema}.${this.table}`}};a(Wa,"CreateAttributeObject");of.exports=Wa});var Ja=h((tX,_f)=>{"use strict";var nD=cf(),Qa=class extends nD{constructor(t,r,s,n,i=!0,o=!1){super(t,r,s,n),this.dup_sort=i,this.is_hash_attribute=o}};a(Qa,"LMDBCreateAttributeObject");_f.exports=Qa});var lf=h((rX,uf)=>{"use strict";uf.exports=aD;var iD="inserted";function aD(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===iD?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(aD,"returnObject")});var Xa=h((sX,df)=>{"use strict";var oD=T(),Mu=Z(),cD=Qs(),{getSystemSchemaPath:_D,getBaseSchemaPath:uD}=re(),lD=require("path"),ED=cs(),dD=Ka(),hD=Ja(),SD=lf(),{handleHDBError:fD,hdb_errors:TD}=D(),mD=b(),Pu=ED.hdb_attribute,Ef=[];for(let e=0;e<Pu.attributes.length;e++)Ef.push(Pu.attributes[e].attribute);var RD="inserted";df.exports=AD;async function AD(e){let t=dD.attribute_object(e);if(t)throw fD(new Error,t.message,TD.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=mD.isEmpty(e.dup_sort)||e.dup_sort=="true";let r=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(r=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(r)&&r.length>0){for(let n of r)if(n.attribute===e.attribute)throw new Error(`attribute '${n.attribute}' already exists in ${e.schema}.${e.table}`)}let s=new hD(e.schema,e.table,e.attribute,e.id);try{let n=await Mu.openEnvironment(lD.join(uD(),e.schema.toString()),e.table);if(n.dbis[e.attribute]!==void 0)throw new Error(`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`);Mu.createDBI(n,e.attribute,e.dup_sort,e.is_hash_attribute);let i=await Mu.openEnvironment(_D(),oD.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:o,skipped_hashes:c}=await cD.insertRecords(i,Pu.hash_attribute,Ef,[s]);return SD(RD,o,{records:[s]},c)}catch(n){throw n}}a(AD,"lmdbCreateAttribute")});var vu=h((nX,Sf)=>{var{hdb_schema_table:hf}=hr(),pD=de(),Bu=require("joi"),OD={undefined:"undefined",null:"null"},ND=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||OD[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"),gD=Bu.object({schema:hf,table:hf,records:Bu.array().items(Bu.object().custom(ND)).required()});Sf.exports=function(e){return pD.validateBySchema(e,gD)}});var Za=h((aX,Tf)=>{"use strict";var Sr=b(),ff=g(),iX=vu();Tf.exports=ID;function ID(e){if(Sr.isEmpty(e))throw new Error("invalid update parameters defined.");if(Sr.isEmptyOrZeroLength(e.schema))throw new Error("invalid schema specified.");if(Sr.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");if(!Array.isArray(e.records))throw new Error("records must be an array");let t=global.hdb_schema[e.schema][e.table];if(Sr.isEmpty(t))throw new Error(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.hash_attribute,s=new Set,n={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&Sr.isEmptyOrZeroLength(o[r]))throw ff.error("a valid hash attribute must be provided with update record:",o),new Error("a valid hash attribute must be provided with update record, check log for more info");if(!Sr.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw ff.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Error(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!Sr.isEmpty(o[r])&&o[r]!==""&&s.has(Sr.autoCast(o[r]))&&(o.skip=!0),s.add(Sr.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(ID,"insertUpdateValidate")});var jn=h((oX,mf)=>{"use strict";var bD=T().OPERATIONS_ENUM,za=class{constructor(t,r,s,n,i=void 0){this.operation=bD.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};a(za,"InsertObject");mf.exports=za});var eo=h((_X,Rf)=>{"use strict";var cX=jn(),ja=T(),qu=b(),Hu=g(),CD=require("uuid"),{handleHDBError:ei,hdb_errors:wD}=D(),{HDB_ERROR_MSGS:ti,HTTP_STATUS_CODES:ri}=wD;Rf.exports=UD;function UD(e,t,r){for(let n=0;n<t.length;n++)LD(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];yD(i,r,e.operation)}}a(UD,"processRows");function LD(e){if(Buffer.byteLength(String(e))>ja.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw ei(new Error,ti.ATTR_NAME_LENGTH_ERR(e),ri.BAD_REQUEST,void 0,void 0,!0);if(qu.isEmptyOrZeroLength(e)||qu.isEmpty(e.trim()))throw ei(new Error,ti.ATTR_NAME_NULLISH_ERR,ri.BAD_REQUEST,void 0,void 0,!0)}a(LD,"validateAttribute");function yD(e,t,r){if(!e.hasOwnProperty(t)||qu.isEmptyOrZeroLength(e[t])){if(r===ja.OPERATIONS_ENUM.INSERT||r===ja.OPERATIONS_ENUM.UPSERT){e[t]=CD.v4();return}throw Hu.error("Update transaction aborted due to record with no hash value:",e),ei(new Error,ti.RECORD_MISSING_HASH_ERR,ri.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>ja.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Hu.error(e),ei(new Error,ti.HASH_VAL_LENGTH_ERR,ri.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw Hu.error(e),ei(new Error,ti.INVALID_FORWARD_SLASH_IN_HASH_ERR,ri.BAD_REQUEST,void 0,void 0,!0)}a(yD,"validateHash")});var pf=h((uX,Af)=>{"use strict";var to=class{constructor(t,r){this.type=t,this.message=r}};a(to,"IPCEventObject");Af.exports=to});var Hr=h((lX,Of)=>{"use strict";var DD=g(),Gu=b(),MD=T(),{IPC_ERRORS:si}=We();Of.exports={sendIpcEvent:PD,validateEvent:BD,SchemaEventMsg:vD,UserEventMsg:HD};function PD(e){global.hdb_ipc?global.hdb_ipc.emitToServer(e):DD.warn("Tried to send event:",e,"to HDB IPC client but it does not exist")}a(PD,"sendIpcEvent");function BD(e){if(typeof e!="object")return si.INVALID_IPC_DATA_TYPE;if(!e.hasOwnProperty("type")||Gu.isEmpty(e.type))return si.MISSING_TYPE;if(!e.hasOwnProperty("message")||Gu.isEmpty(e.message))return si.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||Gu.isEmpty(e.message.originator))return si.MISSING_ORIGIN;if(MD.IPC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return si.INVALID_EVENT(e.type)}a(BD,"validateEvent");function vD(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(vD,"SchemaEventMsg");function HD(e){this.originator=e}a(HD,"UserEventMsg")});var Xs=h((dX,bf)=>{"use strict";var Nf=T(),EX=b(),ro=g(),gf=pf(),{sendIpcEvent:If}=Hr();function qD(e){try{ro.trace("signalSchemaChange called with message:",e);let t=new gf(Nf.IPC_EVENT_TYPES.SCHEMA,e);If(t)}catch(t){ro.error(t)}}a(qD,"signalSchemaChange");function GD(e){try{ro.trace("signalUserChange called with message:",e);let t=new gf(Nf.IPC_EVENT_TYPES.USER,e);If(t)}catch(t){ro.error(t)}}a(GD,"signalUserChange");bf.exports={signalSchemaChange:qD,signalUserChange:GD}});var so=h((hX,wf)=>{"use strict";var Cf=b(),FD=T(),VD=g(),$D=Xa(),kD=Ja(),xD=Xs(),{SchemaEventMsg:YD}=Hr(),KD="already exists in";wf.exports=WD;async function WD(e,t,r){try{if(Cf.isEmptyOrZeroLength(r))return r;let s=[];Cf.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 QD(e,t.schema,t.name,i)})),n}catch(s){throw s}}a(WD,"lmdbCheckForNewAttributes");async function QD(e,t,r,s){let n=new kD(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await JD(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(KD))VD.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(QD,"createNewAttribute");async function JD(e){let t;try{return t=await $D(e),xD.signalSchemaChange(new YD(process.pid,FD.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}catch(r){throw r}}a(JD,"createAttribute")});var Zs=h((SX,Uf)=>{"use strict";var no=class{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}};a(no,"LMDBTransactionObject");Uf.exports=no});var yf=h((fX,Lf)=>{"use strict";var XD=Zs(),ZD=T().OPERATIONS_ENUM,io=class extends XD{constructor(t,r,s,n,i=void 0){super(ZD.INSERT,r,s,n,i),this.records=t}};a(io,"LMDBInsertTransactionObject");Lf.exports=io});var Mf=h((TX,Df)=>{"use strict";var zD=Zs(),jD=T().OPERATIONS_ENUM,ao=class extends zD{constructor(t,r,s,n,i,o=void 0){super(jD.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};a(ao,"LMDBUpdateTransactionObject");Df.exports=ao});var Bf=h((mX,Pf)=>{"use strict";var eM=Zs(),tM=T().OPERATIONS_ENUM,oo=class extends eM{constructor(t,r,s,n,i,o=void 0){super(tM.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};a(oo,"LMDBUpsertTransactionObject");Pf.exports=oo});var Hf=h((RX,vf)=>{"use strict";var rM=Zs(),sM=T().OPERATIONS_ENUM,co=class extends rM{constructor(t,r,s,n,i=void 0){super(sM.DELETE,s,n,t,i),this.original_records=r}};a(co,"LMDBDeleteTransactionObject");vf.exports=co});var ni=h((AX,Vf)=>{"use strict";var nM=require("path"),qf=Z(),iM=yf(),aM=Mf(),oM=Bf(),cM=Hf(),zs=Ke(),Gf=b(),{CONFIG_PARAMS:_M}=T(),Ff=V();Ff.initSync();var _o=T().OPERATIONS_ENUM,{getTransactionAuditStorePath:uM}=re();Vf.exports=lM;async function lM(e,t){if(Ff.get(_M.LOGGING_AUDITLOG)===!1)return;let r=nM.join(uM(),e.schema.toString()),s=await qf.openEnvironment(r,e.table,!0),n=EM(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){qf.initializeDBIs(s,zs.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,zs.TRANSACTIONS_DBIS);try{let i=n.timestamp;return await s.dbis[zs.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{s.dbis[zs.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,n),Gf.isEmpty(n.user_name)||s.dbis[zs.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(n.user_name,i);for(let o=0;o<n.hash_values.length;o++)s.dbis[zs.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(n.hash_values[o],i)})}catch(i){throw i}}}a(lM,"writeTransaction");function EM(e,t){let r=Gf.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===_o.INSERT)return new iM(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===_o.UPDATE)return new aM(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===_o.UPSERT)return new oM(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===_o.DELETE)return new cM(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(EM,"createTransactionObject")});var Fu=h((OX,$f)=>{"use strict";var dM=Za(),pX=jn(),js=T(),hM=eo(),SM=Qs().insertRecords,fM=Z(),TM=require("path"),mM=g(),RM=so(),{getBaseSchemaPath:AM}=re(),pM=ni();$f.exports=OM;async function OM(e){try{let{schema_table:t,attributes:r}=dM(e);hM(e,r,t.hash_attribute),e.schema!==js.SYSTEM_SCHEMA_NAME&&(r.includes(js.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(js.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(js.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(js.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await RM(e.hdb_auth_header,t,r),n=TM.join(AM(),e.schema.toString()),i=await fM.openEnvironment(n,e.table),o=await SM(i,t.hash_attribute,r,e.records,e[js.CLUSTERING_FLAG]!==!0);try{await pM(e,o)}catch(c){mM.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(OM,"lmdbCreateRecords")});var Yf=h((NX,xf)=>{"use strict";var kf=T(),NM=Fu(),gM=jn(),IM=require("fs-extra"),bM=require("path"),{getBaseSchemaPath:CM}=re();xf.exports=wM;async function wM(e){let t=[{name:e.schema,createddate:Date.now()}],r=new gM(kf.SYSTEM_SCHEMA_NAME,kf.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await NM(r),await IM.mkdirp(bM.join(CM(),e.schema.toString()))}a(wM,"lmdbCreateSchema")});var Wf=h((gX,Kf)=>{"use strict";var uo=class{constructor(t=[],r=[],s=void 0,n=[]){this.deleted=t,this.skipped=r,this.txn_time=s,this.original_records=n}};a(uo,"DeleteRecordsResponseObject");Kf.exports=uo});var ku=h((wX,Xf)=>{"use strict";var Qf=Z(),Vu=_s(),$u=We().LMDB_ERRORS_ENUM,UM=Ke(),Jf=g(),IX=b(),LM=require("lmdb"),yM=Wf(),{OVERFLOW_MARKER:bX,MAX_SEARCH_KEY_LENGTH:CX}=UM;async function DM(e,t,r){if(Vu.validateEnv(e),t===void 0)throw new Error($u.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error($u.IDS_REQUIRED):new Error($u.IDS_MUST_BE_ARRAY);try{let s=Qf.listDBIs(e);Qf.initializeDBIs(e,t,s);let n=new yM,i,o=[],c=[];for(let E=0,d=r.length;E<d;E++)try{i=r[E];let S=e.dbis[t].get(i);if(!S){n.skipped.push(i);continue}let m=e.dbis[t].ifVersion(i,LM.IF_EXISTS,()=>{e.dbis[t].remove(i);for(let R=0;R<s.length;R++){let w=s[R];if(!S.hasOwnProperty(w)||w===t)continue;let U=e.dbis[w],B=S[w];if(B!=null)try{let j=Vu.getIndexedValues(B);if(j)for(let $=0,J=j.length;$<J;$++)U.remove(j[$],i)}catch{Jf.warn(`cannot delete from attribute: ${w}, ${B}:${i}`)}}});o.push(m),c.push(i),n.original_records.push(S)}catch(S){Jf.warn(S),n.skipped.push(i)}let _=[],u=await Promise.all(o);for(let E=0,d=u.length;E<d;E++)u[E]===!0?n.deleted.push(c[E]):(n.skipped.push(c[E]),_.push(E));let l=0;for(let E=0;E<_.length;E++){let d=_[E];n.original_records.splice(d-l,1),l++}return n.txn_time=Vu.getMicroTime(),n}catch(s){throw s}}a(DM,"deleteRecords");Xf.exports={deleteRecords:DM}});var ii=h((UX,zf)=>{"use strict";var en=b(),MM=ku(),PM=Z(),BM=require("path"),{getBaseSchemaPath:vM}=re(),HM=ni(),qM=g();zf.exports=GM;async function GM(e,t=!0){let s=global.hdb_schema[e.schema][e.table].hash_attribute;if(en.isEmpty(s))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(en.isEmptyOrZeroLength(e.hash_values)&&!en.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let _=e.records[c][s];en.isEmpty(_)||e.hash_values.push(_)}}if(en.isEmptyOrZeroLength(e.hash_values))return Zf([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(en.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=BM.join(vM(),e.schema.toString()),i=await PM.openEnvironment(n,e.table),o=await MM.deleteRecords(i,s,e.hash_values);try{t===!0&&await HM(e,o)}catch(c){qM.error(`unable to write transaction due to ${c.message}`)}return Zf(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(GM,"lmdbDeleteRecords");function Zf(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(Zf,"createDeleteResponse")});var Yu=h((yX,jf)=>{"use strict";var FM=T(),LX=_s();function xu(e,t){let r=Object.create(null);if(t.length===1&&FM.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(xu,"parseRow");function VM(e,t,r,s){let n=xu(r,e);s.push(n)}a(VM,"searchAll");function $M(e,t,r,s){let n=xu(r,e);s[t]=n}a($M,"searchAllToMap");function kM(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(kM,"iterateDBI");function ls(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(ls,"pushResults");function xM(e,t,r,s,n,i){t.toString().endsWith(e)&&ls(t,r,s,n,i)}a(xM,"endsWith");function YM(e,t,r,s,n,i){t.toString().includes(e)&&ls(t,r,s,n,i)}a(YM,"contains");function KM(e,t,r,s,n,i){t>e&&ls(t,r,s,n,i)}a(KM,"greaterThanCompare");function WM(e,t,r,s,n,i){t>=e&&ls(t,r,s,n,i)}a(WM,"greaterThanEqualCompare");function QM(e,t,r,s,n,i){t<e&&ls(t,r,s,n,i)}a(QM,"lessThanCompare");function JM(e,t,r,s,n,i){t<=e&&ls(t,r,s,n,i)}a(JM,"lessThanEqualCompare");jf.exports={parseRow:xu,searchAll:VM,searchAllToMap:$M,iterateDBI:kM,endsWith:xM,contains:YM,greaterThanCompare:KM,greaterThanEqualCompare:WM,lessThanCompare:QM,lessThanEqualCompare:JM,pushResults:ls}});var tn=h((PX,iT)=>{"use strict";var wt=Z(),XM=g(),St=_s(),qr=Ke(),_e=We().LMDB_ERRORS_ENUM,DX=b(),ZM=T(),kt=Yu(),MX=require("lmdb"),{OVERFLOW_MARKER:eT,MAX_SEARCH_KEY_LENGTH:zM}=qr,ai={lazy:!0};function tT(e,t,r,s,n=!1,i=void 0,o=void 0){let c=Object.create(null),_=wt.openDBI(e,r);_[qr.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r);let u=Ku(e,t,r);for(let{key:l,value:E}of _.getRange({start:n?void 0:!1,end:n?!1:void 0,limit:i,offset:o,reverse:n}))s(u(l,E),E,c,t,r);return c}a(tT,"iterateFullIndex");function oi(e,t,r,s,n,i=!1,o=void 0,c=void 0,_=!1,u=!1){let l=[[],[]],E=wt.openDBI(e,r),d=Ku(e,t,r);E[qr.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r);let S=i===!0?s:n,m=i===!0?n:s,R=i===!0?!_:!u,w=i===!0?u:_;for(let{key:U,value:B}of E.getRange({start:m,end:S,reverse:i,limit:o,offset:c,inclusiveEnd:R,exclusiveStart:w}))kt.pushResults(d(U,B),B,l,t,r);return l}a(oi,"iterateRangeBetween");function Ku(e,t,r){let s;return function(n,i){if(typeof n=="string"&&n.endsWith(eT)){if(!s)if(t)s=wt.openDBI(e,t);else{let c=wt.listDBIs(e);for(let _=0,u=c.length;_<u&&(s=wt.openDBI(e,c[_]),!s[qr.DBI_DEFINITION_NAME].is_hash_attribute);_++);}n=s.get(i,ai)[r]}return n}}a(Ku,"getOverflowCheck");function jM(e,t,r,s=!1,n=void 0,i=void 0){if(St.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);lo(r),r=ci(e,r);let o=[],c=wt.openDBI(e,t);for(let{key:_,value:u}of c.getRange({start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}))kt.searchAll(r,_,u,o);return o}a(jM,"searchAll");function eP(e,t,r,s=!1,n=void 0,i=void 0){if(St.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);return lo(r),r=ci(e,r),tT(e,t,t,kt.searchAllToMap.bind(null,r),s,n,i)}a(eP,"searchAllToMap");function tP(e,t,r=!1,s=void 0,n=void 0){if(St.validateEnv(e),t===void 0)throw new Error(_e.ATTRIBUTE_REQUIRED);return tT(e,void 0,t,kt.iterateDBI,r,s,n)}a(tP,"iterateDBI");function rP(e,t){if(St.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);return wt.statDBI(e,t).entryCount}a(rP,"countAll");function sP(e,t,r,s,n=!1,i=void 0,o=void 0){Gr(e,r,s);let c=wt.openDBI(e,r);s=St.convertKeyValueToWrite(s);let _=[[],[]];if(c[qr.DBI_DEFINITION_NAME].is_hash_attribute){t=r;let u=c.get(s,ai);u!==void 0&&kt.pushResults(s,u,_,t,r)}else for(let u of c.getValues(s,{reverse:n,limit:i,offset:o}))kt.pushResults(s,u,_,t,r);return _}a(sP,"equals");function nP(e,t,r){return Gr(e,t,r),wt.openDBI(e,t).getValuesCount(r)}a(nP,"count");function iP(e,t,r,s,n=!1,i=void 0,o=void 0){Gr(e,r,s);let c=[[],[]],_=wt.openDBI(e,r);_[qr.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r),s=St.convertKeyValueToWrite(s);let u=!0;if(typeof s=="number"&&(u=!1),n===!0){let l;for(let E of _.getKeys({start:s}))if(!E.startsWith(s)){l=E;break}l!==void 0&&(Number.isInteger(o)?o++:i++);for(let{key:E,value:d}of _.getRange({start:l,end:void 0,reverse:n,limit:i,offset:o}))if(E!==l){if(E.toString().startsWith(s))kt.pushResults(E,d,c,t,r);else if(u===!0)break}}else for(let{key:l,value:E}of _.getRange({start:s,reverse:n,limit:i,offset:o}))if(l.toString().startsWith(s))kt.pushResults(l,E,c,t,r);else if(u===!0)break;return c}a(iP,"startsWith");function aP(e,t,r,s,n=!1,i=void 0,o=void 0){return rT(e,t,r,s,n,i,o,!0)}a(aP,"endsWith");function rT(e,t,r,s,n=!1,i=void 0,o=void 0,c=!1){Gr(e,r,s);let _=[[],[]],u=wt.openDBI(e,r);u[qr.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r);let l=Ku(e,t,r);o=Number.isInteger(o)?o:0;for(let d of u.getKeys({end:n?!1:void 0,reverse:n})){if(i===0)break;let S=d.toString();if(S.endsWith(eT))for(let m of u.getValues(d)){let R=l(d,m);(c?R.endsWith(s):R.includes(s))&&E(R,m)}else if(c?S.endsWith(s):S.includes(s))if(u[qr.DBI_DEFINITION_NAME].is_hash_attribute)E(d,d);else for(let m of u.getValues(d))E(d,m)}function E(d,S){if(o>0){o--;return}i!==0&&(kt.pushResults(d,S,_,t,r),i--)}return a(E,"found_match"),_}a(rT,"contains");function oP(e,t,r,s,n=!1,i=void 0,o=void 0){Gr(e,r,s);let c=typeof s,_;return c==="string"?_="\uFFFF":c==="number"?_=1/0:c==="boolean"&&(_=!0),oi(e,t,r,s,_,n,i,o,!0,!1)}a(oP,"greaterThan");function cP(e,t,r,s,n=!1,i=void 0,o=void 0){Gr(e,r,s);let c=typeof s,_;return c==="string"?_="\uFFFF":c==="number"?_=1/0:c==="boolean"&&(_=!0),oi(e,t,r,s,_,n,i,o,!1,!1)}a(cP,"greaterThanEqual");function _P(e,t,r,s,n=!1,i=void 0,o=void 0){Gr(e,r,s);let c=typeof s,_;return c==="string"?_="\0":c==="number"?_=-1/0:c==="boolean"&&(_=!1),oi(e,t,r,_,s,n,i,o,!1,!0)}a(_P,"lessThan");function uP(e,t,r,s,n=!1,i=void 0,o=void 0){Gr(e,r,s);let c=typeof s,_;return c==="string"?_="\0":c==="number"?_=-1/0:c==="boolean"&&(_=!1),oi(e,t,r,_,s,n,i,o,!1,!1)}a(uP,"lessThanEqual");function lP(e,t,r,s,n,i=!1,o=void 0,c=void 0){if(St.validateEnv(e),r===void 0)throw new Error(_e.ATTRIBUTE_REQUIRED);if(s===void 0)throw new Error(_e.START_VALUE_REQUIRED);if(n===void 0)throw new Error(_e.END_VALUE_REQUIRED);if(s=St.convertKeyValueToWrite(s),n=St.convertKeyValueToWrite(n),s>n)throw new Error(_e.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return oi(e,t,r,s,n,i,o,c)}a(lP,"between");function EP(e,t,r,s){if(St.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);if(lo(r),r=ci(e,r),s===void 0)throw new Error(_e.ID_REQUIRED);let n=null,i=e.dbis[t].get(s,r.length<3?ai:void 0);return i&&(n=kt.parseRow(i,r)),n}a(EP,"searchByHash");function dP(e,t,r){if(St.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(_e.ID_REQUIRED);let s=!0;return e.dbis[t].get(r,ai)===void 0&&(s=!1),s}a(dP,"checkHashExists");function hP(e,t,r,s,n=[]){nT(e,t,r,s,n);let i=sT(e,t,r,s,n);return Object.values(i)}a(hP,"batchSearchByHash");function SP(e,t,r,s,n=[]){return nT(e,t,r,s,n),sT(e,t,r,s,n)}a(SP,"batchSearchByHashToMap");function sT(e,t,r,s,n=[]){r=ci(e,r);let i=Object.create(null),o=r.length<3?ai:void 0;for(let c=0;c<s.length;c++){let _=s[c];try{let u=e.dbis[t].get(_,o);if(u){let l=kt.parseRow(u,r);i[_]=l}else n.push(_)}catch(u){throw XM.warn(u),u}}return i}a(sT,"batchHashSearch");function nT(e,t,r,s,n){if(St.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);if(lo(r),!Array.isArray(s))throw s===void 0?new Error(_e.IDS_REQUIRED):new Error(_e.IDS_MUST_BE_ARRAY);Array.isArray(n)||(n=[])}a(nT,"initializeBatchSearchByHash");function lo(e){if(!Array.isArray(e))throw e===void 0?new Error(_e.FETCH_ATTRIBUTES_REQUIRED):new Error(_e.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(lo,"validateFetchAttributes");function Gr(e,t,r){if(St.validateEnv(e),t===void 0)throw new Error(_e.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(_e.SEARCH_VALUE_REQUIRED);if(r?.length>zM)throw new Error(_e.SEARCH_VALUE_TOO_LARGE)}a(Gr,"validateComparisonFunctions");function ci(e,t){return t.length===1&&ZM.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=wt.listDBIs(e)),t}a(ci,"setGetWholeRowAttributes");iT.exports={searchAll:jM,searchAllToMap:eP,count:nP,countAll:rP,equals:sP,startsWith:iP,endsWith:aP,contains:rT,searchByHash:EP,setGetWholeRowAttributes:ci,batchSearchByHash:hP,batchSearchByHashToMap:SP,checkHashExists:dP,iterateDBI:tP,greaterThan:oP,greaterThanEqual:cP,lessThan:_P,lessThanEqual:uP,between:lP}});var _i=h((vX,_T)=>{var aT=require("lodash"),oT=de(),W=require("joi"),fP=b(),{hdb_schema_table:xt,checkValidTable:cT}=hr(),{handleHDBError:TP,hdb_errors:mP}=D(),{HTTP_STATUS_CODES:RP}=mP,BX=W.object({schema:xt,table:xt,hash_values:W.array().min(1).items(W.alternatives(W.string(),W.number())).required(),get_attributes:W.array().min(1).items(xt).required()}),AP=W.object({schema:xt,table:xt,search_attribute:xt,search_value:W.any().required(),get_attributes:W.array().min(1).items(xt).required(),desc:W.bool(),limit:W.number().integer().min(1),offset:W.number().integer().min(0)}),pP=W.object({schema:xt,table:xt,operator:W.string().valid("and","or").default("and").lowercase(),offset:W.number().integer().min(0),limit:W.number().integer().min(1),get_attributes:W.array().min(1).items(xt).required(),conditions:W.array().min(1).items(W.object({search_attribute:xt,search_type:W.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between").required(),search_value:W.when("search_type",{switch:[{is:"equals",then:W.any()},{is:"between",then:W.array().items(W.alternatives([W.string(),W.number()])).length(2)}],otherwise:W.alternatives(W.string(),W.number())}).required()})).required()});_T.exports=function(e,t){let r=null;switch(t){case"value":r=oT.validateBySchema(e,AP);break;case"hashes":let i=function(o){n?n+=". "+o:n=o};var s=i;a(i,"addError");let n;i(cT("schema",e.schema)),i(cT("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=oT.validateBySchema(e,pP);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=fP.checkGlobalSchemaTable(e.schema,e.table);if(n)return TP(new Error,n,RP.NOT_FOUND);let o=global.hdb_schema[e.schema][e.table].attributes,c=[...e.get_attributes];if(t==="value"&&c.push(e.search_attribute),t==="conditions")for(let u=0,l=e.conditions.length;u<l;u++){let E=e.conditions[u];c.push(E.search_attribute)}let _=aT.filter(c,u=>u!=="*"&&u.attribute!=="*"&&!aT.some(o,l=>l===u||l.attribute===u||l.attribute===u.attribute));if(_&&_.length>0){let u=_.join(", ");return u=u.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${u}'`)}}return r}});var Wu=h((HX,uT)=>{"use strict";var OP=Z(),NP=_i(),gP=require("path"),{getBaseSchemaPath:IP}=re();uT.exports=bP;function bP(e){let t=NP(e,"hashes");if(t)throw t;let r=gP.join(IP(),e.schema.toString());return OP.openEnvironment(r,e.table)}a(bP,"initialize")});var Qu=h((qX,lT)=>{"use strict";var CP=tn(),wP=Wu();lT.exports=UP;async function UP(e){try{let t=await wP(e),r=global.hdb_schema[e.schema][e.table];return CP.batchSearchByHashToMap(t,r.hash_attribute,e.get_attributes,e.hash_values)}catch(t){throw t}}a(UP,"lmdbGetDataByHash")});var Es=h((GX,ET)=>{"use strict";var Eo=class{constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};a(Eo,"SearchByHashObject");ET.exports=Eo});var hT=h((VX,dT)=>{"use strict";var FX=Es(),LP=tn(),yP=Wu();dT.exports=DP;async function DP(e){try{let t=await yP(e),r=global.hdb_schema[e.schema][e.table];return LP.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}catch(t){throw t}}a(DP,"lmdbSearchByHash")});var Yt=h(($X,ST)=>{"use strict";var ho=class{constructor(t,r,s,n,i,o,c,_=!1,u=void 0,l=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=_,this.limit=u,this.offset=l}};a(ho,"SearchObject");ST.exports=ho});var So=h((kX,AT)=>{"use strict";var Je=tn(),MP=Z(),PP=require("path"),BP=b(),L=Ke(),ds=T(),{getBaseSchemaPath:vP}=re(),HP=cs(),fT=We().LMDB_ERRORS_ENUM,{compareKeys:rn}=require("ordered-binary"),fr=ds.SEARCH_WILDCARDS;async function qP(e,t,r){let s;e.schema===ds.SYSTEM_SCHEMA_NAME?s=HP[e.table]:s=global.hdb_schema[e.schema][e.table];let n=RT(e,s.hash_attribute,r,t);return TT(e,n,s.hash_attribute,r)}a(qP,"prepSearch");async function TT(e,t,r,s){let n=PP.join(vP(),e.schema.toString()),i=await MP.openEnvironment(n,e.table),o=mT(i,e,t,r);if([L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,L.SEARCH_TYPES.SEARCH_ALL,L.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(VP(e,r)===!1)return s===!0?FP(o):o[1];let _=o[0];return s===!0?Je.batchSearchByHashToMap(i,r,e.get_attributes,_):Je.batchSearchByHash(i,r,e.get_attributes,_)}a(TT,"executeSearch");function mT(e,t,r,s){let n,i=s;t.get_attributes.indexOf(s)<0&&(i=void 0);let{reverse:o,limit:c,offset:_}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,_=Number.isInteger(_)?_:void 0,r){case L.SEARCH_TYPES.EQUALS:n=Je.equals(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.CONTAINS:n=Je.contains(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.ENDS_WITH:case L.SEARCH_TYPES._ENDS_WITH:n=Je.endsWith(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.STARTS_WITH:case L.SEARCH_TYPES._STARTS_WITH:n=Je.startsWith(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Je.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Je.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case L.SEARCH_TYPES.SEARCH_ALL:return Je.searchAll(e,s,t.get_attributes,o,c,_);case L.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Je.searchAllToMap(e,s,t.get_attributes,o,c,_);case L.SEARCH_TYPES.BETWEEN:n=Je.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,_);break;case L.SEARCH_TYPES.GREATER_THAN:case L.SEARCH_TYPES._GREATER_THAN:n=Je.greaterThan(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.GREATER_THAN_EQUAL:case L.SEARCH_TYPES._GREATER_THAN_EQUAL:n=Je.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.LESS_THAN:case L.SEARCH_TYPES._LESS_THAN:n=Je.lessThan(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.LESS_THAN_EQUAL:case L.SEARCH_TYPES._LESS_THAN_EQUAL:n=Je.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,_);break;default:return Object.create(null)}return n}a(mT,"searchByType");function GP(e){let t=e.search_type,r=e.search_attribute,s=e.search_value;switch(t){case L.SEARCH_TYPES.EQUALS:return n=>n[r]===s;case L.SEARCH_TYPES.CONTAINS:return n=>typeof n[r]=="string"&&n[r].includes(s);case L.SEARCH_TYPES.ENDS_WITH:case L.SEARCH_TYPES._ENDS_WITH:return n=>typeof n[r]=="string"&&n[r].endsWith(s);case L.SEARCH_TYPES.STARTS_WITH:case L.SEARCH_TYPES._STARTS_WITH:return n=>typeof n[r]=="string"&&n[r].startsWith(s);case L.SEARCH_TYPES.BETWEEN:return n=>{let i=n[r];return rn(i,s[0])>=0&&rn(i,s[1])<=0};case L.SEARCH_TYPES.GREATER_THAN:case L.SEARCH_TYPES._GREATER_THAN:return n=>rn(n[r],s)>0;case L.SEARCH_TYPES.GREATER_THAN_EQUAL:case L.SEARCH_TYPES._GREATER_THAN_EQUAL:return n=>rn(n[r],s)>=0;case L.SEARCH_TYPES.LESS_THAN:case L.SEARCH_TYPES._LESS_THAN:return n=>rn(n[r],s)<0;case L.SEARCH_TYPES.LESS_THAN_EQUAL:case L.SEARCH_TYPES._LESS_THAN_EQUAL:return n=>rn(n[r],s)<=0;default:return Object.create(null)}}a(GP,"filterByType");function FP(e){let t=Object.create(null);for(let r=0,s=e[0].length;r<s;r++)t[e[0][r]]=e[1][r];return t}a(FP,"createMapFromArrays");function VP(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(VP,"checkToFetchMore");function RT(e,t,r,s){if(BP.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),fr.indexOf(n)>-1)return r===!0?L.SEARCH_TYPES.SEARCH_ALL_TO_MAP:L.SEARCH_TYPES.SEARCH_ALL;if(n.indexOf(fr[0])<0&&n.indexOf(fr[1])<0)return c===!0?r===!0?L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:L.SEARCH_TYPES.EQUALS;if(fr.indexOf(i)>=0&&fr.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),L.SEARCH_TYPES.CONTAINS;if(fr.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),L.SEARCH_TYPES.ENDS_WITH;if(fr.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),L.SEARCH_TYPES.STARTS_WITH;if(n.includes(fr[0])||n.includes(fr[1]))return L.SEARCH_TYPES.EQUALS;throw new Error(fT.UNKNOWN_SEARCH_TYPE)}else switch(s){case ds.VALUE_SEARCH_COMPARATORS.BETWEEN:return L.SEARCH_TYPES.BETWEEN;case ds.VALUE_SEARCH_COMPARATORS.GREATER:return L.SEARCH_TYPES.GREATER_THAN;case ds.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return L.SEARCH_TYPES.GREATER_THAN_EQUAL;case ds.VALUE_SEARCH_COMPARATORS.LESS:return L.SEARCH_TYPES.LESS_THAN;case ds.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return L.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(fT.UNKNOWN_SEARCH_TYPE)}}a(RT,"createSearchTypeFromSearchObject");AT.exports={executeSearch:TT,createSearchTypeFromSearchObject:RT,prepSearch:qP,searchByType:mT,filterByType:GP}});var OT=h((YX,pT)=>{"use strict";var xX=Yt(),$P=_i(),kP=b(),xP=T(),YP=So();pT.exports=KP;async function KP(e,t){if(!kP.isEmpty(t)&&xP.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=$P(e,"value");if(s)throw s;let n=!0;try{return await YP.prepSearch(e,t,n)}catch(i){throw i}}a(KP,"lmdbGetDataByValue")});var sn=h((WX,NT)=>{"use strict";var KX=Yt(),WP=_i(),QP=b(),JP=T(),XP=So();NT.exports=ZP;async function ZP(e,t){if(!QP.isEmpty(t)&&JP.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=WP(e,"value");if(s)throw s;let n=!1;try{return await XP.prepSearch(e,t,n)}catch(i){throw i}}a(ZP,"lmdbSearchByValue")});var IT=h((JX,gT)=>{"use strict";var QX=Ke(),fo=class{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}};a(fo,"SearchByConditionsObject");var To=class{constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}};a(To,"SearchCondition");var mo=class{constructor(t,r){this.attribute=t,this.desc=r}};a(mo,"SortAttribute");gT.exports={SearchByConditionsObject:fo,SearchCondition:To,SortAttribute:mo}});var yT=h((ZX,LT)=>{"use strict";var XX=IT().SearchByConditionsObject,zP=Yt(),jP=_i(),Ju=tn(),Ro=Ke(),UT=So(),eB=Yu(),bT=require("lodash"),{getBaseSchemaPath:tB}=re(),rB=require("path"),sB=Z(),{handleHDBError:CT,hdb_errors:nB}=D(),{HTTP_STATUS_CODES:iB}=nB,aB=1e8,oB={lazy:!0};LT.exports=cB;async function cB(e){try{let t=jP(e,"conditions");if(t)throw CT(t,t.message,iB.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=rB.join(tB(),e.schema.toString()),s=await sB.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table],i=bT.sortBy(e.conditions,o=>{if(o.estimated_count===void 0){let c=o.search_type;c===Ro.SEARCH_TYPES.EQUALS?o.estimated_count=Ju.count(s,o.search_attribute,o.search_value):c===Ro.SEARCH_TYPES.CONTAINS||c===Ro.SEARCH_TYPES.ENDS_WITH?o.estimated_count=1/0:o.estimated_count=aB}return o.estimated_count});if(!e.operator||e.operator.toLowerCase()==="and"){let[o]=await wT(s,e,i[0],n.hash_attribute),c=s.dbis[n.hash_attribute],_=i.slice(1).map(UT.filterByType),u=_.length,l=[],E=Ju.setGetWholeRowAttributes(s,e.get_attributes),d=e.offset>-1?e.offset:0,S=e.limit>-1?e.limit:1/0;e:for(let m of o){let R=c.get(m,oB);for(let w=0;w<u;w++)if(!_[w](R))continue e;if(d>0){d--;continue}if(S<=0)break;S--,l.push(eB.parseRow(R,E))}return l}else{let o=[],c=[];for(let _ of i){let[u]=await wT(s,e,_,n.hash_attribute);c.push(u)}if(o=bT.union(...c),e.limit>0||e.offset>0){let _=Number.isInteger(e.limit)?e.limit:o.length;o=o.splice(e.offset,_)}return Ju.batchSearchByHash(s,n.hash_attribute,e.get_attributes,o)}}catch(t){throw CT(t)}}a(cB,"lmdbSearchByConditions");async function wT(e,t,r,s){let n=new zP(t.schema,t.table,void 0,void 0,s,t.get_attributes),i=r.search_type;return n.search_attribute=r.search_attribute,i===Ro.SEARCH_TYPES.BETWEEN?(n.search_value=r.search_value[0],n.end_value=r.search_value[1]):n.search_value=r.search_value,UT.searchByType(e,n,i,s)}a(wT,"executeConditionSearch")});var ui=h((zX,DT)=>{"use strict";var _B=T().OPERATIONS_ENUM,Ao=class{constructor(t,r,s,n=void 0){this.operation=_B.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};a(Ao,"DeleteObject");DT.exports=Ao});var Xu=h((jX,MT)=>{"use strict";var po=class{constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};a(po,"DropAttributeObject");MT.exports=po});var zu=h((tZ,PT)=>{"use strict";var uB=Yt(),lB=ui(),eZ=Xu(),jt=T(),EB=b(),Zu=Z(),dB=cs(),hB=sn(),SB=ii(),{getBaseSchemaPath:fB}=re(),TB=require("path");PT.exports=mB;async function mB(e,t=!0){let r;e.schema===jt.SYSTEM_SCHEMA_NAME?r=dB[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await AB(e),n=TB.join(fB(),e.schema.toString()),i=await Zu.openEnvironment(n,e.table);return t===!0&&await RB(e,i,r.hash_attribute),Zu.dropDBI(i,e.attribute),s}a(mB,"lmdbDropAttribute");async function RB(e,t,r){let s=Zu.openDBI(t,r),n,i=e.attribute;for(let{key:o,value:c,version:_}of s.getRange({start:!1,versions:!0})){let u={};for(let l in c)l!==i&&(u[l]=c[l]);n=t.dbis[r].put(o,u,_)}await n}a(RB,"removeAttributeFromAllObjects");async function AB(e){let t=new uB(jt.SYSTEM_SCHEMA_NAME,jt.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,jt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[jt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,jt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),s=(await hB(t)).filter(o=>o[jt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(EB.isEmptyOrZeroLength(s))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let n=s.map(o=>o[jt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new lB(jt.SYSTEM_SCHEMA_NAME,jt.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return SB(i)}a(AB,"dropAttributeFromSystem")});var qT=h((rZ,HT)=>{"use strict";var pB=zu(),OB=Xu(),BT=b(),vT=g(),NB=We().LMDB_ERRORS_ENUM;HT.exports=gB;async function gB(e){if(BT.isEmpty(global.hdb_schema[e.schema])||BT.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);let t=global.hdb_schema[e.schema][e.table],r;try{for(let s=0;s<t.attributes.length;s++){r=t.attributes[s].attribute;let n=new OB(e.schema,e.table,r);try{await pB(n,!1)}catch(i){i.message!==NB.DBI_DOES_NOT_EXIST&&vT.error(`unable to drop attribute ${e.schema}.${e.table}.${r}:`+i)}}}catch(s){throw vT.error(`Error dropping attribute ${r}`),s}}a(gB,"lmdbDropAllAttributes")});var ju=h((nZ,WT)=>{"use strict";var kT=Yt(),xT=ui(),YT=sn(),KT=ii(),sZ=qT(),at=T(),GT=b(),FT=Z(),{getBaseSchemaPath:IB,getTransactionAuditStorePath:bB}=re(),VT=require("path"),$T=g();WT.exports=CB;async function CB(e){try{if(GT.isEmpty(global.hdb_schema[e.schema])||GT.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await wB(e),await UB(e);let t=VT.join(IB(),e.schema.toString());try{await FT.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")$T.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=VT.join(bB(),e.schema.toString());await FT.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")$T.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(CB,"lmdbDropTable");async function wB(e){let t=new kT(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,at.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[at.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=await YT(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 xT(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await KT(n)}a(wB,"deleteAttributesFromSystem");async function UB(e){let t=new kT(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,at.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[at.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,at.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,at.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,s;try{r=await YT(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 xT(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await KT(n)}catch(i){throw i}}a(UB,"dropTableFromSystem")});var JT=h((aZ,QT)=>{"use strict";var LB=require("fs-extra"),yB=Yt(),DB=Es(),MB=ui(),PB=ju(),BB=ii(),vB=Qu(),HB=sn(),Tr=T(),iZ=b(),qB=require("path"),{getBaseSchemaPath:GB}=re(),{handleHDBError:FB,hdb_errors:VB}=D(),{HDB_ERROR_MSGS:$B,HTTP_STATUS_CODES:kB}=VB;QT.exports=xB;async function xB(e){let t;try{t=await YB(e.schema);let r=new yB(Tr.SYSTEM_SCHEMA_NAME,Tr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),s=await HB(r);for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await PB(c)}catch(_){if(_.message!=="invalid environment")throw _}}let n=new MB(Tr.SYSTEM_SCHEMA_NAME,Tr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await BB(n);let i=qB.join(GB(),t.toString());await LB.remove(i)}catch(r){throw r}}a(xB,"lmdbDropSchema");async function YB(e){let t=new DB(Tr.SYSTEM_SCHEMA_NAME,Tr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,s;try{r=await vB(t)}catch(n){throw n}for(let n in r)r[n].name===e&&(s=e);if(!s)throw FB(new Error,$B.SCHEMA_NOT_FOUND(e),kB.NOT_FOUND,void 0,void 0,!0);return s}a(YB,"validateDropSchema")});var el=h((oZ,XT)=>{"use strict";var Oo=class{constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};a(Oo,"CreateTableObject");XT.exports=Oo});var zT=h((_Z,ZT)=>{"use strict";var KB=require("path"),WB=require("fs-extra"),No=Z(),{getTransactionAuditStorePath:QB}=re(),tl=Ke(),cZ=el();ZT.exports=JB;async function JB(e){let t;try{let r=KB.join(QB(),e.schema.toString());await WB.mkdirp(r),t=await No.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{No.createDBI(t,tl.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),No.createDBI(t,tl.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),No.createDBI(t,tl.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(JB,"createTransactionsAuditEnvironment")});var rm=h((uZ,tm)=>{"use strict";var rl=T(),jT=Z(),XB=Qs(),ZB=require("path"),{getSystemSchemaPath:zB,getBaseSchemaPath:jB}=re(),ev=cs(),tv=Xa(),sl=Ja(),rv=g(),sv=zT(),il=ev.hdb_table,em=[];for(let e=0;e<il.attributes.length;e++)em.push(il.attributes[e].attribute);tm.exports=nv;async function nv(e,t){let r=ZB.join(jB(),t.schema.toString()),s=new sl(t.schema,t.table,rl.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=new sl(t.schema,t.table,rl.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new sl(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await jT.createEnvironment(r,t.table),e!==void 0){let o=await jT.openEnvironment(zB(),rl.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await XB.insertRecords(o,il.hash_attribute,em,[e]),await nl(s),await nl(n),await nl(i)}await sv(t)}catch(o){throw o}}a(nv,"lmdbCreateTable");async function nl(e){try{await tv(e)}catch(t){rv.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(nl,"createAttribute")});var nm=h((lZ,sm)=>{"use strict";var iv=Za(),av=eo(),ov=so(),nn=T(),cv=Qs().updateRecords,_v=Z(),uv=require("path"),{getBaseSchemaPath:lv}=re(),Ev=ni(),dv=g();sm.exports=hv;async function hv(e){try{let{schema_table:t,attributes:r}=iv(e);av(e,r,t.hash_attribute),e.schema!==nn.SYSTEM_SCHEMA_NAME&&(r.includes(nn.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(nn.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(nn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(nn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await ov(e.hdb_auth_header,t,r),n=uv.join(lv(),e.schema.toString()),i=await _v.openEnvironment(n,e.table),o=await cv(i,t.hash_attribute,r,e.records,e[nn.CLUSTERING_FLAG]!==!0);try{await Ev(e,o)}catch(c){dv.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(hv,"lmdbUpdateRecords")});var am=h((EZ,im)=>{"use strict";var Sv=T().OPERATIONS_ENUM,go=class{constructor(t,r,s,n=void 0){this.operation=Sv.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};a(go,"UpsertObject");im.exports=go});var cm=h((hZ,om)=>{"use strict";var dZ=am(),fv=Za(),Tv=eo(),mv=so(),an=T(),Rv=Qs().upsertRecords,Av=Z(),pv=require("path"),{getBaseSchemaPath:Ov}=re(),Nv=ni(),gv=g(),{handleHDBError:Iv,hdb_errors:bv}=D();om.exports=Cv;async function Cv(e){let t;try{t=fv(e)}catch(_){throw Iv(_,_.message,bv.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;Tv(e,s,r.hash_attribute),e.schema!==an.SYSTEM_SCHEMA_NAME&&(s.includes(an.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||s.push(an.TIME_STAMP_NAMES_ENUM.CREATED_TIME),s.includes(an.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||s.push(an.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await mv(e.hdb_auth_header,r,s),i=pv.join(Ov(),e.schema.toString()),o=await Av.openEnvironment(i,e.table),c=await Rv(o,r.hash_attribute,s,e.records,e[an.CLUSTERING_FLAG]!==!0);try{await Nv(e,c)}catch(_){gv.error(`unable to write transaction due to ${_.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:n,txn_time:c.txn_time}}a(Cv,"lmdbUpsertRecords")});var hm=h((SZ,dm)=>{"use strict";var wv=Yt(),_m=b(),um=g(),Uv=sn(),lm=T(),Lv=ku().deleteRecords,yv=Z(),Dv=require("path"),{getBaseSchemaPath:Mv}=re(),{promisify:Pv}=require("util"),Bv=Pv(setTimeout),Em=1e4,vv=10;dm.exports=Hv;async function Hv(e){let t=global.hdb_schema[e.schema][e.table].hash_attribute;if(_m.isEmptyOrZeroLength(t))throw new Error(`Could not retrieve hash attribute for schema: ${e.schema} table: ${e.table}`);let r=Date.parse(e.date),s;try{let n=new wv(e.schema,e.table,lm.TIME_STAMP_NAMES_ENUM.CREATED_TIME,r,void 0,[t]);s=await Uv(n,lm.VALUE_SEARCH_COMPARATORS.LESS)}catch(n){throw um.error(`Error searching for date: ${e.date} in schema: ${e.schema} table: ${e.table}`),n}return _m.isEmptyOrZeroLength(s)?(um.trace("No records found to delete"),{message:"No records found to delete"}):await qv(e,s,t)}a(Hv,"lmdbDeleteRecordsBefore");async function qv(e,t,r){let s=Dv.join(Mv(),e.schema.toString()),n=await yv.openEnvironment(s,e.table),i={message:"",deleted_hashes:[],skipped_hashes:[]};for(let o=0,c=t.length;o<c;o+=Em){let _=t.slice(o,o+Em),u=[];for(let l=0,E=_.length;l<E;l++)u.push(_[l][r]);try{let l=await Lv(n,r,u);i.deleted_hashes=i.deleted_hashes.concat(l.deleted),i.skipped_hashes=i.skipped_hashes.concat(l.skipped)}catch(l){throw l}await Bv(vv)}return i.message=`${i.deleted_hashes.length} of ${i.deleted_hashes.length+i.skipped_hashes.length} records successfully deleted`,i}a(qv,"chunkDeletes")});var fm=h((fZ,Sm)=>{"use strict";var Io=class{constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};a(Io,"DeleteBeforeObject");Sm.exports=Io});var mm=h((TZ,Tm)=>{"use strict";var bo=class{constructor(t=void 0,r=void 0,s=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=s}};a(bo,"DeleteAuditLogsBeforeResults");Tm.exports=bo});var pm=h((RZ,Am)=>{"use strict";var al=Z(),{getTransactionAuditStorePath:Gv}=re(),mZ=fm(),Fv=require("path"),li=Ke(),Vv=b(),Rm=mm(),$v=require("util").promisify,kv=$v(setTimeout),xv=1e4,Yv=100;Am.exports=Kv;async function Kv(e){let t=Fv.join(Gv(),e.schema),r=await al.openEnvironment(t,e.table,!0),s=al.listDBIs(r);al.initializeDBIs(r,li.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new Rm;do n=await Wv(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 kv(Yv);while(n.transactions_deleted>0);return i}a(Kv,"deleteAuditLogsBefore");async function Wv(e,t){let r=new Rm;try{let s=e.dbis[li.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[li.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];Vv.isEmpty(c)||(n=e.dbis[li.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let _=0;_<o.hash_values.length;_++)n=e.dbis[li.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[_],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>xv)break}return await n,r}catch(s){throw s}}a(Wv,"deleteTransactions")});var wm=h((AZ,Cm)=>{"use strict";var ol=Z(),on=Ke(),Om=_s(),cl=T(),Nm=b(),{getTransactionAuditStorePath:Qv}=re(),Jv=require("path"),Xv=tn(),Co=Zs(),Zv=g();Cm.exports=zv;async function zv(e){let t=Jv.join(Qv(),e.schema),r=await ol.openEnvironment(t,e.table,!0),s=ol.listDBIs(r);ol.initializeDBIs(r,on.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;switch(e.search_type){case cl.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return gm(r,e.search_values);case cl.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return n=global.hdb_schema[e.schema][e.table].hash_attribute,eH(r,e.search_values,n);case cl.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return jv(r,e.search_values);default:return gm(r)}}a(zv,"readAuditLog");function gm(e,t=[0,Om.getMicroTime()]){Nm.isEmpty(t[0])&&(t[0]=0),Nm.isEmpty(t[1])&&(t[1]=Om.getMicroTime());let r=[];try{let s=e.dbis[on.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let i of s.getKeys({start:t[1]}))if(i!==t[1]){n=i;break}for(let{value:i}of s.getRange({start:t[0],end:n})){let o=Object.assign(new Co,i);r.push(o)}return r}catch(s){throw s}}a(gm,"searchTransactionsByTimestamp");function jv(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[on.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(n))i.push(o);r.set(n,bm(e,i))}return Object.fromEntries(r)}a(jv,"searchTransactionsByUsername");function eH(e,t,r){let s=new Map;for(let c=0,_=t.length;c<_;c++){let u=t[c],l=Xv.equals(e,on.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,on.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,u);for(let E=0,d=l[0].length;E<d;E++){let S=l[0][E],m=Number(S);s.has(m)?s.get(m).push(u.toString()):s.set(m,[u.toString()])}}let n=Array.from(s.keys()),i=bm(e,n),o=new Map;for(let c=0;c<i.length;c++){let _=i[c],u=_.timestamp,l=s.get(u);Im(_,"records",r,l,o),Im(_,"original_records",r,l,o)}return Object.fromEntries(o)}a(eH,"searchTransactionsByHashValues");function Im(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],_=c[r].toString();if(s.indexOf(_)>=0)if(n.has(_)){let u=n.get(_),l=u[u.length-1];if(l.timestamp===i)l[t]=[c];else{let E=new Co(e.operation,e.user_name,i,void 0);E[t]=[c],u.push(E)}}else{let u=new Co(e.operation,e.user_name,i,void 0);u[t]=[c],n.set(_,[u])}}}a(Im,"loopRecords");function bm(e,t){let r=[];try{let s=e.dbis[on.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 Co,i);r.push(o)}}catch(i){Zv.warn(i)}return r}catch(s){throw s}}a(bm,"batchSearchTransactions")});var Lm=h((pZ,Um)=>{"use strict";var tH=require("path"),{getBaseSchemaPath:rH}=re(),sH=Z();Um.exports={writeTransaction:nH};async function nH(e,t,r){let s=tH.join(rH(),e);return(await sH.openEnvironment(s,t)).transaction(r)}a(nH,"writeTransaction")});var Dm=h((OZ,ym)=>{"use strict";var iH=require("path"),{getBaseSchemaPath:aH}=re(),oH=Z();ym.exports={flush:cH};async function cH(e,t){let r=iH.join(aH(),e.toString());return(await oH.openEnvironment(r,t.toString())).flushed}a(cH,"flush")});var Pm=h((NZ,Mm)=>{"use strict";var Ae=g(),{handleHDBError:_H}=D(),uH=mu(),lH=Xa(),EH=Fu(),dH=Yf(),hH=ii(),SH=Qu(),fH=hT(),TH=OT(),mH=sn(),RH=yT(),AH=JT(),pH=rm(),OH=nm(),NH=cm(),gH=hm(),IH=pm(),bH=ju(),CH=zu(),wH=wm(),UH=Lm(),LH=Dm(),wo=class extends uH{async searchByConditions(t){try{return RH(t)}catch(r){throw Ae.error(r),r}}async getDataByHash(t){try{return await SH(t)}catch(r){throw Ae.error(r),r}}async searchByHash(t){try{return await fH(t)}catch(r){throw Ae.error(r),r}}async getDataByValue(t,r){try{return await TH(t,r)}catch(s){throw Ae.error(s),s}}async searchByValue(t){try{return await mH(t)}catch(r){throw Ae.error(r),r}}async createSchema(t){try{return await dH(t)}catch(r){throw Ae.error(r),r}}async dropSchema(t){try{return await AH(t)}catch(r){throw Ae.error(r),r}}async createTable(t,r){try{return await pH(t,r)}catch(s){throw Ae.error(s),s}}async dropTable(t){try{return await bH(t)}catch(r){throw Ae.error(r),r}}async createAttribute(t){try{return await lH(t)}catch(r){throw Ae.error(r),r}}async createRecords(t){try{return await EH(t)}catch(r){throw Ae.error(r),r}}async updateRecords(t){try{return await OH(t)}catch(r){throw Ae.error(r),r}}async upsertRecords(t){try{return await NH(t)}catch(r){throw _H(r,null,null,Ae.ERR,r)}}async deleteRecords(t){try{return await hH(t)}catch(r){throw Ae.error(r),r}}async deleteRecordsBefore(t){try{return await gH(t)}catch(r){throw Ae.error(r),r}}async dropAttribute(t){try{return await CH(t)}catch(r){throw Ae.error(r),r}}async deleteAuditLogsBefore(t){try{return await IH(t)}catch(r){throw Ae.error(r),r}}async readAuditLog(t){try{return await wH(t)}catch(r){throw Ae.error(r),r}}writeTransaction(t,r,s){return UH.writeTransaction(t,r,s)}flush(t,r){return LH.flush(t,r)}};a(wo,"LMDBBridge");Mm.exports=wo});var mr=h((gZ,vm)=>{"use strict";var yH=Pm(),DH=mu(),MH=V();MH.initSync();var Bm;function PH(){return Bm instanceof DH?Bm:new yH}a(PH,"getBridge");vm.exports=PH()});var Fm=h((IZ,Gm)=>{"use strict";var Hm=require("lodash"),Ei=require("mathjs"),BH=require("jsonata"),qm=b();Gm.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?Hm.uniqWith(e,Hm.isEqual):e,searchJSON:vH,mad:di.bind(null,Ei.mad),mean:di.bind(null,Ei.mean),mode:di.bind(null,Ei.mode),prod:di.bind(null,Ei.prod),median:di.bind(null,Ei.median)};function di(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(di,"aggregateFunction");function vH(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(qm.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),qm.isEmpty(this.__ala__.res[r])){let s=BH(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(vH,"searchJSON")});var $m=h((bZ,Vm)=>{"use strict";var he=require("moment"),_l="YYYY-MM-DDTHH:mm:ss.SSSZZ";he.suppressDeprecationWarnings=!0;Vm.exports={current_date:()=>he().utc().format("YYYY-MM-DD"),current_time:()=>he().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return he(e).utc().format("YYYY");case"month":return he(e).utc().format("MM");case"day":return he(e).utc().format("DD");case"hour":return he(e).utc().format("HH");case"minute":return he(e).utc().format("mm");case"second":return he(e).utc().format("ss");case"millisecond":return he(e).utc().format("SSS");default:break}},date:e=>he(e).utc().format(_l),date_format:(e,t)=>he(e).utc().format(t),date_add:(e,t,r)=>he(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>he(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let s=he(e).utc(),n=he(t).utc();return r?s.diff(n,r,!0):s.diff(n)},now:()=>he().utc().valueOf(),get_server_time:()=>he().format(_l),offset_utc:(e,t)=>he(e).utc().utcOffset(t).format(_l)}});var Km=h((CZ,Ym)=>{"use strict";var HH=require("@turf/area"),qH=require("@turf/length"),GH=require("@turf/circle"),FH=require("@turf/difference"),VH=require("@turf/distance"),$H=require("@turf/boolean-contains"),kH=require("@turf/boolean-equal"),xH=require("@turf/boolean-disjoint"),YH=require("@turf/helpers"),km=T(),k=b();Ym.exports={geoArea:KH,geoLength:WH,geoCircle:QH,geoDifference:JH,geoDistance:xm,geoNear:XH,geoContains:ZH,geoEqual:zH,geoCrosses:jH,geoConvert:eq};var ul="geo1 is required",ll="geo2 is required";function KH(e){if(k.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=k.autoCast(e)),HH.default(e)}a(KH,"geoArea");function WH(e,t){if(k.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=k.autoCast(e)),qH.default(e,{units:t||"kilometers"})}a(WH,"geoLength");function QH(e,t,r){if(k.isEmpty(e))throw new Error("point is required");if(k.isEmpty(t))throw new Error("radius is required");return typeof e=="string"&&(e=k.autoCast(e)),GH.default(e,t,{units:r||"kilometers"})}a(QH,"geoCircle");function JH(e,t){if(k.isEmpty(e))throw new Error("poly1 is required");if(k.isEmpty(t))throw new Error("poly2 is required");return typeof e=="string"&&(e=k.autoCast(e)),typeof t=="string"&&(t=k.autoCast(t)),FH(e,t)}a(JH,"geoDifference");function xm(e,t,r){if(k.isEmpty(e))throw new Error("point1 is required");if(k.isEmpty(t))throw new Error("point2 is required");return typeof e=="string"&&(e=k.autoCast(e)),typeof t=="string"&&(t=k.autoCast(t)),VH.default(e,t,{units:r||"kilometers"})}a(xm,"geoDistance");function XH(e,t,r,s){if(k.isEmpty(e))throw new Error("point1 is required");if(k.isEmpty(t))throw new Error("point2 is required");if(k.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=k.autoCast(e)),typeof t=="string"&&(t=k.autoCast(t)),isNaN(r))throw new Error("distance must be a number");return xm(e,t,s)<=r}a(XH,"geoNear");function ZH(e,t){if(k.isEmpty(e))throw new Error(ul);if(k.isEmpty(e))throw new Error(ll);return typeof e=="string"&&(e=k.autoCast(e)),typeof t=="string"&&(t=k.autoCast(t)),$H.default(e,t)}a(ZH,"geoContains");function zH(e,t){if(k.isEmpty(e))throw new Error(ul);if(k.isEmpty(e))throw new Error(ll);return typeof e=="string"&&(e=k.autoCast(e)),typeof t=="string"&&(t=k.autoCast(t)),kH.default(e,t)}a(zH,"geoEqual");function jH(e,t){if(k.isEmpty(e))throw new Error(ul);if(k.isEmpty(e))throw new Error(ll);return typeof e=="string"&&(e=k.autoCast(e)),typeof t=="string"&&(t=k.autoCast(t)),!xH.default(e,t)}a(jH,"geoCrosses");function eq(e,t,r){if(k.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(k.isEmpty(t))throw new Error("geo_type is required");if(k.isEmpty(km.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(km.GEO_CONVERSION_ENUM).join(",")}`);return YH[t](e,r)}a(eq,"geoConvert")});var Uo=h((wZ,Wm)=>{var hs=Fm(),ft=$m(),er=Km();Wm.exports=e=>{e.aggr.mad=e.aggr.MAD=hs.mad,e.aggr.mean=e.aggr.MEAN=hs.mean,e.aggr.mode=e.aggr.MODE=hs.mode,e.aggr.prod=e.aggr.PROD=hs.prod,e.aggr.median=e.aggr.MEDIAN=hs.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=hs.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=hs.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=ft.current_date,e.fn.current_time=e.fn.CURRENT_TIME=ft.current_time,e.fn.extract=e.fn.EXTRACT=ft.extract,e.fn.date=e.fn.DATE=ft.date,e.fn.date_format=e.fn.DATE_FORMAT=ft.date_format,e.fn.date_add=e.fn.DATE_ADD=ft.date_add,e.fn.date_sub=e.fn.DATE_SUB=ft.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=ft.date_diff,e.fn.now=e.fn.NOW=ft.now,e.fn.offset_utc=e.fn.OFFSET_UTC=ft.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=ft.get_server_time,e.fn.getdate=e.fn.GETDATE=ft.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=ft.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=er.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=er.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=er.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=er.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=er.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=er.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=er.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=er.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=er.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=er.geoNear}});var Xm=h((UZ,Jm)=>{"use strict";var hi=require("lodash"),Pe=require("alasql");Pe.options.cache=!1;var tq=Uo(),Qm=require("clone"),Lo=require("recursive-iterator"),v=g(),q=b(),cn=mr(),rq=T(),{hdb_errors:sq}=D(),nq="IS NULL",Si="There was a problem performing this search. Please check the logs and try again.";tq(Pe);var yo=class{constructor(t,r){if(q.isEmpty(t))throw v.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(),q.backtickASTSchemaItems(this.statement)}async search(){let t;try{let s=await this._checkEmptySQL();if(!q.isEmptyOrZeroLength(s))return v.trace("No results returned from checkEmptySQL SQLSearch method."),s}catch(s){throw v.error("Error thrown from checkEmptySQL in SQLSearch class method search."),v.error(s),new Error(Si)}try{let s=await this._getFetchAttributeValues();if(s)return s}catch(s){throw v.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),v.error(s),new Error(Si)}if(Object.keys(this.data).length===0)return v.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(s){throw v.error("Error thrown from processJoins in SQLSearch class method search."),v.error(s),new Error(Si)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(s){throw v.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),v.error(s),new Error(Si)}try{return t=await this._finalSQL(),t}catch(s){throw v.error("Error thrown from finalSQL in SQLSearch class method search."),v.error(s),new Error(Si)}}_getColumns(){let t=new Lo(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(Qm(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=hi.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=global.hdb_schema[r.databaseid][r.tableid].hash_attribute,this.data[s].__merged_data={},this.data[s].__merged_attributes=[],this.data[s].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(q.isEmpty(this.statement.where)){v.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new Lo(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!q.isEmpty(r)&&r.right)if(q.isNotEmptyAndHasValue(r.right.value)){let s=q.autoCast(r.right.value);[!0,!1].indexOf(s)>=0?r.right=new Pe.yy.LogicValue({value:s}):r.right instanceof Pe.yy.StringValue&&!q.isEmpty(s)&&q.autoCasterIsNumberCheck(s.toString())&&(r.right=new Pe.yy.NumValue({value:s}))}else Array.isArray(r.right)&&r.right.forEach((s,n)=>{let i=q.autoCast(s.value);[!0,!1].indexOf(i)>=0?r.right[n]=new Pe.yy.LogicValue({value:i}):s instanceof Pe.yy.StringValue&&q.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new Pe.yy.NumValue({value:i}))});if(t){v.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new Lo(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(!q.isEmpty(rq.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(q.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(q.isEmptyOrZeroLength(r.left.columnid)||q.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(q.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"=":!q.isEmpty(r.right.value)||!q.isEmpty(r.left.value)?s.add(q.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let _=Array.isArray(r.right)?r.right:r.left;for(let u=0;u<_.length;u++)if(_[u].value)s.add(_[u].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(q.isEmptyOrZeroLength(this.all_table_attributes)&&q.isEmptyOrZeroLength(this.statement.from)&&q.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&&hi.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(q.isEmptyOrZeroLength(r)){let s=this.columns.columns.filter(n=>n.as?t.columnid===n.as:!1);q.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(q.isEmptyOrZeroLength(this.all_table_attributes)&&!q.isEmptyOrZeroLength(this.columns.columns))return t;if(q.isEmptyOrZeroLength(this.all_table_attributes)&&q.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await Pe.promise(r)}catch(r){throw v.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),v.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(Qm(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(q.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(nq)>-1&&this.tables.forEach(n=>{let i={columnid:global.hdb_schema[n.databaseid][n.tableid].hash_attribute,tableid:n.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=hi.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]},_=!1,u=[n.table.databaseid,n.table.tableid,n.attribute].join("/");if(n.attribute===o&&(_=!0),!q.isEmpty(this.exact_search_values[u])&&!this.exact_search_values[u].ignore&&!q.isEmptyOrZeroLength(this.exact_search_values[u].values))if(_)try{c.hash_values=Array.from(this.exact_search_values[u].values);let l=await cn.getDataByHash(c);for(let E of c.hash_values)E in l&&!this.data[i].__merged_data[E]&&(this.data[i].__merged_data[E]=[...s[i]],this._setMergedHashAttribute(i,E))}catch(l){v.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),v.error(l)}else try{c.search_attribute=n.attribute,await Promise.all(Array.from(this.exact_search_values[u].values).map(async l=>{let E=Object.assign({},c);E.search_value=l;let d=await cn.getDataByValue(E);for(let S in d)this.data[i].__merged_data[S]?this._updateMergedAttribute(i,S,n.attribute,d[S][n.attribute]):(this.data[i].__merged_data[S]=[...s[i]],this._updateMergedAttribute(i,S,n.attribute,d[S][n.attribute]),this._setMergedHashAttribute(i,q.autoCast(S)))}))}catch(l){v.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),v.error(l)}else if(!q.isEmpty(this.comparator_search_values[u])&&!this.comparator_search_values[u].ignore&&!q.isEmptyOrZeroLength(this.comparator_search_values[u].comparators))try{let l=this.comparator_search_values[u].comparators;for(let E=0,d=l.length;E<d;E++){let S=l[E];c.search_attribute=S.attribute,c.search_value=S.search_value;let m=await cn.getDataByValue(c,S.operation);if(_)for(let R in m)this.data[i].__merged_data[R]||(this.data[i].__merged_data[R]=[...s[i]],this._setMergedHashAttribute(i,q.autoCast(R)));else for(let R in m)this.data[i].__merged_data[R]?this._updateMergedAttribute(i,R,n.attribute,m[R][n.attribute]):(this.data[i].__merged_data[R]=[...s[i]],this._updateMergedAttribute(i,R,n.attribute,m[R][n.attribute]),this._setMergedHashAttribute(i,q.autoCast(R)))}}catch(l){v.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),v.error(l)}else try{c.search_attribute=n.attribute,c.search_value="*";let l=await cn.getDataByValue(c);if(_)for(let E in l)this.data[i].__merged_data[E]||(this.data[i].__merged_data[E]=[...s[i]],this._setMergedHashAttribute(i,q.autoCast(E)));else for(let E in l)this.data[i].__merged_data[E]?this._updateMergedAttribute(i,E,n.attribute,l[E][n.attribute]):(this.data[i].__merged_data[E]=[...s[i]],this._updateMergedAttribute(i,E,n.attribute,l[E][n.attribute]),this._setMergedHashAttribute(i,q.autoCast(E)))}catch(l){v.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),v.error(l)}}}_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 Pe.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 Pe.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}else{t.initial_select_column=Object.assign(new Pe.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 Pe.yy.FuncValue:new Pe.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(S=>{S.joinmode&&S.joinmode!=="INNER"&&(this.has_outer_join=!0),n.push(S.table);let m=S.joinmode+" JOIN ? AS "+(S.as?S.as:S.table.tableid);S.on&&(m+=" ON "+S.on.toString()),i.push(m),t.push(Object.values(this.data[`${S.table.databaseid_orig}_${S.table.as?S.table.as_orig:S.table.tableid_orig}`].__merged_data))});let o=[],c={};n.forEach(S=>{let m=this.data[`${S.databaseid_orig}_${S.as?S.as_orig:S.tableid_orig}`].__hash_name,R=S.as?S.as_orig:S.tableid_orig;o.push({key:`'${R}.${m}'`,schema:S.databaseid_orig,table:S.as?S.as_orig:S.tableid_orig,keys:new Set}),r.push(`${S.as?S.as:S.tableid}.\`${m}\` AS "${R}.${m}"`),c[S.as?S.as_orig:S.tableid_orig]=this.data[`${S.databaseid_orig}_${S.as?S.as_orig:S.tableid_orig}`].__merged_attributes});let _=this.statement.where?"WHERE "+this.statement.where:"",u="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(u="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(S=>{S.is_func?r.push(S.initial_select_column.toString()):S.initial_select_column.tableid?r.push(`${S.initial_select_column.tableid}.${S.initial_select_column.columnid} AS ${S.expression.columnid}`):r.push(`${S.initial_select_column.columnid} AS ${S.expression.columnid}`)}));let l="",E="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",E=this.statement.offset?"OFFSET "+this.statement.offset:"");let d=[];try{let S=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${_} ${u} ${l} ${E}`,m=this._convertColumnsToIndexes(S,n);d=await Pe.promise(m,t),t=null}catch(S){throw v.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),v.error(S),new Error("There was a problem processing the data.")}if(d&&d.length>0){for(let S=0,m=d.length;S<m;S++){let R=d[S];o.forEach(w=>{R[w.key]!==null&&R[w.key]!==void 0&&w.keys.add(R[w.key])})}o.forEach(S=>{let m=Object.keys(this.data[`${S.schema}_${S.table}`].__merged_data),R=hi.difference(m,[...S.keys].map(w=>w.toString()));for(let w=0,U=R.length;w<U;w++){let B=R[w];delete this.data[`${S.schema}_${S.table}`].__merged_data[B]}})}return{existing_attributes:c,joined_length:d?d.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let s=[],n=new Lo(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=hi.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){v.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),v.error(i)}}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 l in i)o.push(i[l][0]);this.data[s].__merged_attributes.push(...n.columns);let c={schema:n.schema,table:n.table,hash_values:o,get_attributes:n.columns},_=await cn.getDataByHash(c),u=n.columns.length;for(let l=0,E=o.length;l<E;l++){let d=o[l],S=_[d];for(let m=0;m<u;m++){let R=n.columns[m],w=S[R]===void 0?null:S[R];this.data[s].__merged_data[d].push(w)}}}}catch(r){throw v.error("Error thrown from getDataByHash function in SQLSearch class method getData."),v.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,_=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===_}).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();v.trace(`Final SQL: ${n}`),s=await Pe.promise(n,t),this.has_outer_join&&(s=this._translateUndefinedValues(s)),v.trace(`Final AlaSQL results data included ${s.length} rows`)}catch(n){throw v.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),v.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 v.error(sq.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),v.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 _=n[i],u=new RegExp(`${_}.\`${o}\``,"g"),l=`${_}.[${c}]`;s=s.replace(u,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let _=new RegExp(`\`${o}\``,"g"),u=`[${c}]`;s=s.replace(_,u)});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 cn.getDataByValue(i);for(let c in o)this.data[n].__merged_data[c]||(this.data[n].__merged_data[c]=Object.assign({},r[n])),this.data[n].__merged_data[c][t[s.attribute]]=o[c][s.attribute]}catch(o){v.error("There was an error when processing this SQL operation. Check your logs"),v.error(o)}}return Object.values(Object.values(this.data)[0].__merged_data)}};a(yo,"SQLSearch");Jm.exports=yo});var Tt=h((LZ,zm)=>{"use strict";var iq=OS();zm.exports={searchByConditions:_q,searchByHash:uq,searchByValue:lq,search:Eq};var El=mr(),Zm=require("util"),aq=Zm.callbackify(El.searchByHash),oq=Zm.callbackify(El.searchByValue),cq=Xm();async function _q(e){return El.searchByConditions(e)}a(_q,"searchByConditions");function uq(e,t){try{aq(e,(r,s)=>{if(r){t(r);return}t(null,s)})}catch(r){return t(r)}}a(uq,"searchByHash");function lq(e,t){try{e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc),oq(e,(r,s)=>{if(r){t(r);return}t(null,s)})}catch(r){return t(r)}}a(lq,"searchByValue");function Eq(e,t){try{let r=new iq(e);r.validate(),new cq(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(Eq,"search")});var Fr=h((yZ,rR)=>{"use strict";var fi=require("crypto"),eR="aes-256-cbc",dq=32,hq=16,dl=64,tR=32,Sq=dl+tR,jm=new Map;rR.exports={encrypt:fq,decrypt:Tq,createNatsTableStreamName:mq};function fq(e){let t=fi.randomBytes(dq),r=fi.randomBytes(hq),s=fi.createCipheriv(eR,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(fq,"encrypt");function Tq(e){let t=e.substr(0,dl),r=e.substr(dl,tR),s=e.substr(Sq,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),o=fi.createDecipheriv(eR,Buffer.from(t,"hex"),n),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(Tq,"decrypt");function mq(e,t){let r=`${e}.${t}`,s=jm.get(r);return s||(s=fi.createHash("md5").update(`${e}.${t}`).digest("hex"),jm.set(r,s)),s}a(mq,"createNatsTableStreamName")});var Ss=h((DZ,_R)=>{"use strict";var nR=Tt(),Vr=g(),iR=Ka(),Rq=require("lodash"),Aq=require("path"),pq=Fr(),hl=b(),{promisify:aR}=require("util"),ee=T(),{handleHDBError:Do,hdb_errors:Oq}=D(),{HDB_ERROR_MSGS:Mo,HTTP_STATUS_CODES:oR}=Oq,Nq=V();Nq.initSync();var sR=Z(),gq=re(),Ti=aR(nR.searchByValue),Iq=aR(nR.searchByHash),_n="name",cR="hash_attribute",Sl="schema",bq="schema_table",Cq="attribute";_R.exports={describeAll:wq,describeTable:Po,describeSchema:Lq};async function wq(e){try{let t=hl.isEmptyOrZeroLength(e),r,s;t||(r=e.hdb_user.role.permission,s=r.super_user||r.cluster_user);let n={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,search_attribute:_n,search_value:ee.WILDCARD_SEARCH_VALUE,get_attributes:[_n]},i=await Ti(n);if(hl.isEmptyOrZeroLength(i))return{};let o={},c={};for(let d in i)o[i[d].name]=!0,!t&&!s&&(c[i[d].name]=r[i[d].name].describe);let _={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,search_attribute:ee.ID_ATTRIBUTE_STRING,search_value:ee.WILDCARD_SEARCH_VALUE,get_attributes:[cR,ee.ID_ATTRIBUTE_STRING,_n,Sl]},u=await Ti(_),l=[];for(let d of u)try{let S;if(t||s)S=await Po({schema:d.schema,table:d.name});else if(r&&r[d.schema].describe&&r[d.schema].tables[d.name].describe){let m=r[d.schema].tables[d.name].attribute_permissions;S=await Po({schema:d.schema,table:d.name},m)}S&&l.push(S)}catch(S){Vr.error(S)}let E={};for(let d in l)t||s?(E[l[d].schema]==null&&(E[l[d].schema]={}),E[l[d].schema][l[d].name]=l[d],o[l[d].schema]&&delete o[l[d].schema]):c[l[d].schema]&&(E[l[d].schema]==null&&(E[l[d].schema]={}),E[l[d].schema][l[d].name]=l[d],o[l[d].schema]&&delete o[l[d].schema]);for(let d in o)t||s?E[d]={}:c[d]&&(E[d]={});return E}catch(t){return Vr.error("Got an error in describeAll"),Vr.error(t),Do(new Error,Mo.DESCRIBE_ALL_ERR)}}a(wq,"describeAll");async function Po(e,t){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={},o=iR.describe_table(e);if(o)throw o;if(r===ee.SYSTEM_SCHEMA_NAME)return global.hdb_schema[ee.SYSTEM_SCHEMA_NAME][s];let c={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,hash_attribute:ee.SYSTEM_TABLE_HASH_ATTRIBUTES.TABLE_TABLE_HASH_ATTRIBUTE,search_attribute:_n,search_value:s,hash_values:[],get_attributes:[ee.WILDCARD_SEARCH_VALUE]},_=await Ti(c);if(!_||_.length===0)throw Do(new Error,Mo.TABLE_NOT_FOUND(e.schema,e.table),oR.NOT_FOUND);for await(let u of _)try{if(u.schema!==r)continue;if(i=u,!i.hash_attribute)throw Do(new Error,Mo.INVALID_TABLE_ERR(i));let l={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,hash_attribute:ee.SYSTEM_TABLE_HASH_ATTRIBUTES.ATTRIBUTE_TABLE_HASH_ATTRIBUTE,search_attribute:bq,search_value:r+"."+s,get_attributes:[Cq]},E=await Ti(l);E=Rq.uniqBy(E,d=>d.attribute),n&&n.length>0&&(E=Uq(n)),i.attributes=E,i.clustering_stream_name=pq.createNatsTableStreamName(u.schema,u.name);try{let d=Aq.join(gq.getBaseSchemaPath(),i.schema.toString()),S=await sR.openEnvironment(d,i.name),m=sR.statDBI(S,i.hash_attribute);i.record_count=m.entryCount}catch(d){Vr.warn(`unable to stat table dbi due to ${d}`)}}catch(l){Vr.error(`There was an error getting attributes for table '${u.name}'`),Vr.error(l)}return i}a(Po,"descTable");function Uq(e){return e.reduce((t,r)=>(r.describe&&t.push({attribute:r.attribute_name}),t),[])}a(Uq,"getAttrsByPerms");async function Lq(e){let t=iR.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(),n={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,hash_attribute:ee.SYSTEM_TABLE_HASH_ATTRIBUTES.TABLE_TABLE_HASH_ATTRIBUTE,search_attribute:Sl,search_value:s,hash_values:[],get_attributes:[cR,ee.ID_ATTRIBUTE_STRING,_n,Sl]},i=await Ti(n);if(i&&i.length<1){let o={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,hash_attribute:ee.SYSTEM_TABLE_HASH_ATTRIBUTES.SCHEMA_TABLE_HASH_ATTRIBUTE,hash_values:[s],get_attributes:[_n]},c=await Iq(o);if(c&&c.length<1)throw Do(new Error,Mo.SCHEMA_NOT_FOUND(e.schema),oR.NOT_FOUND);return{}}else{let o={};return await Promise.all(i.map(async c=>{try{let _;if(r&&r.tables[c.name]&&(_=r.tables[c.name]),hl.isEmpty(_)||_.describe){let u=await Po({schema:e.schema,table:c.name},_?_.attribute_permissions:null);u&&(o[u.name]=u)}}catch(_){Vr.error(`Error describing schema table '${e.schema}.${c}'`),Vr.error(_)}})),o}}a(Lq,"describeSchema")});var $r=h((BZ,hR)=>{var MZ=require("async"),un=cs(),PZ=g(),{callbackify:ER,promisify:yq}=require("util");hR.exports={setSchemaDataToGlobal:uR,getTableSchema:Pq,getSystemSchema:vq,setSchemaDataToGlobalAsync:yq(uR)};var dR=Ss(),Dq=ER(dR.describeAll),Mq=ER(dR.describeTable);function uR(e){Dq(null,(t,r)=>{if(t){e(t);return}r.system||(r.system=un),global.hdb_schema=r,e(null,null)})}a(uR,"setSchemaDataToGlobal");function lR(e,t){return e==="system"?un[t]:global.hdb_schema[e][t]}a(lR,"returnSchema");function Pq(e,t,r){!global.hdb_schema||!global.hdb_schema[e]||!global.hdb_schema[e][t]?Bq(e,t,s=>{if(s)return r(s);if(!global.hdb_schema[e])return r(`schema ${e} does not exist`);if(!global.hdb_schema[e]||!global.hdb_schema[e][t])return r(`table ${e}.${t} does not exist`);r(null,lR(e,t))}):r(null,lR(e,t))}a(Pq,"getTableSchema");function Bq(e,t,r){let s={table:t,schema:e};if(e==="system"){global.hdb_schema?global.hdb_schema.system=un:global.hdb_schema={system:un},r();return}Mq(s,(n,i)=>{if(n){r(n);return}if(!i.schema&&!i.name){r();return}global.hdb_schema||(global.hdb_schema={system:un}),global.hdb_schema[e]||(global.hdb_schema[e]={}),global.hdb_schema[e][t]=i,r()})}a(Bq,"setTableDataToGlobal");function vq(){return un}a(vq,"getSystemSchema")});var Lt=h((vZ,TR)=>{"use strict";var vo=vu(),Ut=b(),Hq=require("util"),Ho=mr(),qq=$r(),fl=g(),{handleHDBError:kr,hdb_errors:Gq}=D(),{HTTP_STATUS_CODES:fs}=Gq,Fq=Hq.promisify(qq.getTableSchema),Vq="updated",SR="inserted",fR="upserted";TR.exports={insert:kq,update:xq,upsert:Yq,validation:$q,flush:Kq};async function $q(e){if(Ut.isEmpty(e))throw new Error("invalid update parameters defined.");if(Ut.isEmptyOrZeroLength(e.schema))throw new Error("invalid schema specified.");if(Ut.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await Fq(e.schema,e.table),r=vo(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&&Ut.isEmptyOrZeroLength(c[s]))throw fl.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(!Ut.isEmptyOrZeroLength(c[s])&&(c[s]==="null"||c[s]==="undefined"))throw fl.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[s]}" is not a valid hash attribute value`);!Ut.isEmpty(c[s])&&c[s]!==""&&n.has(Ut.autoCast(c[s]))&&(c.skip=!0),n.add(Ut.autoCast(c[s]));for(let _ in c)i[_]=1}),i[s]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(i)}}a($q,"validation");async function kq(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=vo(e);if(t)throw kr(new Error,t.message,fs.BAD_REQUEST);let r=Ut.checkSchemaTableExist(e.schema,e.table);if(r)throw kr(new Error,r,fs.BAD_REQUEST);try{let s=await Ho.createRecords(e);return Bo(SR,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}catch(s){throw s}}a(kq,"insertData");async function xq(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=vo(e);if(t)throw kr(new Error,t.message,fs.BAD_REQUEST);let r=Ut.checkSchemaTableExist(e.schema,e.table);if(r)throw kr(new Error,r,fs.BAD_REQUEST);try{let s=await Ho.updateRecords(e);return Ut.isEmpty(s.existing_rows)?Bo(Vq,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time):Bo(s.update_action,[],e,s.hashes,void 0,s.txn_time)}catch(s){throw s}}a(xq,"updateData");async function Yq(e){if(e.operation!=="upsert")throw kr(new Error,"invalid operation, must be upsert",fs.INTERNAL_SERVER_ERROR);let t=vo(e);if(t)throw kr(new Error,t.message,fs.BAD_REQUEST);let r=Ut.checkSchemaTableExist(e.schema,e.table);if(r)throw kr(new Error,r,fs.BAD_REQUEST);try{let s=await Ho.upsertRecords(e);return Bo(fR,s.written_hashes,e,[],s.new_attributes,s.txn_time)}catch(s){let n=`There was an error during an upsert op: ${s}`;throw kr(s,null,null,fl.ERR,n)}}a(Yq,"upsertData");function Bo(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===SR?(o.inserted_hashes=t,o.skipped_hashes=s,o):e===fR?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=s,o)}a(Bo,"returnObject");function Kq(e){return Ho.flush(e.schema,e.table)}a(Kq,"flush")});var ml=h((HZ,AR)=>{var Wq=de(),Tl=require("joi"),{hdb_schema_table:mR}=hr(),RR={schema:mR,table:mR},Qq={date:Tl.date().iso().required()},Jq={timestamp:Tl.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};AR.exports=function(e,t){let r=t==="timestamp"?{...RR,...Jq}:{...RR,...Qq},s=Tl.object(r);return Wq.validateBySchema(e,s)}});var gR=h((qZ,NR)=>{var Xq=de(),pR=require("joi"),{hdb_schema_table:OR}=hr(),Zq=pR.object({schema:OR,table:OR,hash_values:pR.array().required()});NR.exports=function(e){return Xq.validateBySchema(e,Zq)}});var bR=h((GZ,IR)=>{"use strict";var qo=class{constructor(t,r,s,n,i){this.operation=t,this.schema=r,this.table=s,this.hash_attribute=n,this.records=i}};a(qo,"InsertObject");var Go=class{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}};a(Go,"NoSQLSeachObject");var Fo=class{constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};a(Fo,"DeleteResponseObject");IR.exports={InsertObject:qo,NoSQLSeachObject:Go,DeleteResponseObject:Fo}});var ms=h((FZ,yR)=>{"use strict";var wR=ml(),zq=gR(),Vo=b(),CR=require("moment"),UR=g(),{promisify:jq,callbackify:eG}=require("util"),Ts=T(),tG=$r(),Rl=jq(tG.getTableSchema),Al=mr(),{DeleteResponseObject:rG}=bR(),{handleHDBError:xr,hdb_errors:sG}=D(),{HDB_ERROR_MSGS:$o,HTTP_STATUS_CODES:Yr}=sG,nG="records successfully deleted",iG=eG(LR);yR.exports={delete:iG,deleteRecord:LR,deleteFilesBefore:aG,deleteAuditLogsBefore:oG};async function aG(e){let t=wR(e,"date");if(t)throw xr(t,t.message,Yr.BAD_REQUEST,void 0,void 0,!0);if(!CR(e.date,CR.ISO_8601).isValid())throw xr(new Error,$o.INVALID_DATE,Yr.BAD_REQUEST,Ts.LOG_LEVELS.ERROR,$o.INVALID_DATE,!0);let s=Vo.checkSchemaTableExist(e.schema,e.table);if(s)throw xr(new Error,s,Yr.NOT_FOUND,Ts.LOG_LEVELS.ERROR,s,!0);try{let n=await Al.deleteRecordsBefore(e);if(await Rl(e.schema,e.table),UR.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}catch(n){throw n}}a(aG,"deleteFilesBefore");async function oG(e){let t=wR(e,"timestamp");if(t)throw xr(t,t.message,Yr.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e.timestamp))throw xr(new Error,$o.INVALID_VALUE("Timestamp"),Yr.BAD_REQUEST,Ts.LOG_LEVELS.ERROR,$o.INVALID_VALUE("Timestamp"),!0);let r=Vo.checkSchemaTableExist(e.schema,e.table);if(r)throw xr(new Error,r,Yr.NOT_FOUND,Ts.LOG_LEVELS.ERROR,r,!0);try{let s=await Al.deleteAuditLogsBefore(e);return await Rl(e.schema,e.table),UR.info(`Finished deleting audit logs before ${e.timestamp}`),s}catch(s){throw s}}a(oG,"deleteAuditLogsBefore");async function LR(e){let t=zq(e);if(t)throw xr(t,t.message,Yr.BAD_REQUEST,void 0,void 0,!0);let r=Vo.checkSchemaTableExist(e.schema,e.table);if(r)throw xr(new Error,r,Yr.NOT_FOUND,Ts.LOG_LEVELS.ERROR,r,!0);try{await Rl(e.schema,e.table);let s=await Al.deleteRecords(e);return Vo.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${nG}`),s}catch(s){if(s.message===Ts.SEARCH_NOT_FOUND_MESSAGE){let n=new rG;return n.message=Ts.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}a(LR,"deleteRecord")});var ko=h((VZ,PR)=>{var cG=require("crypto"),DR=9;function _G(e){let t=lG(DR),r=MR(e+t);return t+r}a(_G,"createHash");function uG(e,t){let r=e.substr(0,DR),s=r+MR(t+r);return e===s}a(uG,"validateHash");function lG(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(lG,"generateSalt");function MR(e){return cG.createHash("md5").update(e).digest("hex")}a(MR,"md5");PR.exports={hash:_G,validate:uG}});var vR=h(($Z,BR)=>{var pl=de(),Xe={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 EG(e){return Xe.password.presence=!0,Xe.username.presence=!0,Xe.role.presence=!0,Xe.active.presence=!0,pl.validateObject(e,Xe)}a(EG,"addUserValidation");function dG(e){return Xe.password.presence=!1,Xe.username.presence=!0,Xe.role.presence=!1,Xe.active.presence=!1,pl.validateObject(e,Xe)}a(dG,"alterUserValidation");function hG(e){return Xe.password.presence=!1,Xe.username.presence=!0,Xe.role.presence=!1,Xe.active.presence=!1,pl.validateObject(e,Xe)}a(hG,"dropUserValidation");BR.exports={addUserValidation:EG,alterUserValidation:dG,dropUserValidation:hG}});var Se=h((xZ,qR)=>{"use strict";var{platform:kZ}=require("os"),SG="nats-server.zip",Ol="nats-server",fG=process.platform==="win32"?`${Ol}.exe`:Ol,Nl="HDB",TG=/^[^\s.,*>]+$/,HR="__request__",mG=a(e=>`${e}.${HR}`,"REQUEST_SUBJECT"),RG={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},AG={HUB:"hub.pid",LEAF:"leaf.pid"},pG={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},OG={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:Nl,deliver_subject:"__HDB__.WORKQUEUE"},NG={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:Nl,deliver_subject:"HDB.SCHEMAQUEUE"},gG={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:Nl,deliver_subject:"HDB.USERQUEUE"},IG={SUCCESS:"success",ERROR:"error"},bG={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},CG={TXN:"txn",MSGID:"msgid"};qR.exports={NATS_SERVER_ZIP:SG,NATS_SERVER_NAME:Ol,NATS_BINARY_NAME:fG,PID_FILES:AG,NATS_CONFIG_FILES:RG,SERVER_SUFFIX:pG,WORK_QUEUE_CONSUMER_NAMES:OG,SCHEMA_QUEUE_CONSUMER_NAMES:NG,USER_QUEUE_CONSUMER_NAMES:gG,NATS_TERM_CONSTRAINTS_RX:TG,REQUEST_SUFFIX:HR,UPDATE_REMOTE_RESPONSE_STATUSES:IG,CLUSTER_STATUS_STATUSES:bG,REQUEST_SUBJECT:mG,SUBJECT_PREFIXES:CG}});var FR=h((YZ,GR)=>{"use strict";var Kr=T(),mi=class{constructor(t=0,r=Kr.STORAGE_TYPES_ENUM.LMDB,s=Kr.LICENSE_VALUES.API_CALL_DEFAULT,n=Kr.RAM_ALLOCATION_ENUM.DEFAULT,i=Kr.LICENSE_VALUES.VERSION_DEFAULT,o){this.exp_date=t,this.storage_type=r,this.api_call=s,this.ram_allocation=n,this.version=i,this.fingerprint=o}};a(mi,"BaseLicense");var xo=class extends mi{constructor(t=0,r=Kr.STORAGE_TYPES_ENUM.LMDB,s=Kr.LICENSE_VALUES.API_CALL_DEFAULT,n=Kr.RAM_ALLOCATION_ENUM.DEFAULT,i=Kr.LICENSE_VALUES.VERSION_DEFAULT,o,c=!1){super(t,r,s,n,i,o),this.enterprise=c}};a(xo,"ExtendedLicense");GR.exports={BaseLicense:mi,ExtendedLicense:xo}});var Ri=h((KZ,KR)=>{"use strict";var En=require("fs-extra"),VR=ko(),$R=require("crypto"),wG=require("moment"),UG=require("uuid").v4,Ze=g(),Il=require("path"),LG=b(),mt=T(),yG=FR().ExtendedLicense,ln="invalid license key format",DG="061183",MG="mofi25",PG="aes-256-cbc",BG=16,vG=32,kR=V();kR.initSync();var gl;KR.exports={validateLicense:xR,generateFingerPrint:qG,licenseSearch:YR,getLicense:VG};function bl(){return Il.join(kR.getHdbBasePath(),mt.LICENSE_KEY_DIR_NAME,mt.LICENSE_FILE_NAME)}a(bl,"getLicenseDirPath");function HG(){let e=bl();return Il.join(e,mt.LICENSE_FILE_NAME)}a(HG,"getLicenseFilePath");function Cl(){let e=bl();return Il.join(e,mt.REG_KEY_FILE_NAME)}a(Cl,"getFingerPrintFilePath");async function qG(){let e=Cl();try{return await En.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await GG();throw Ze.error(`Error writing fingerprint file to ${e}`),Ze.error(t),new Error("There was an error generating the fingerprint")}}a(qG,"generateFingerPrint");async function GG(){let e=UG(),t=VR.hash(e),r=Cl();try{await En.mkdirp(bl()),await En.writeFile(r,t)}catch(s){if(s.code==="EEXIST")return t;throw Ze.error(`Error writing fingerprint file to ${r}`),Ze.error(s),new Error("There was an error generating the fingerprint")}return t}a(GG,"writeFingerprint");function xR(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,storage_type:mt.STORAGE_TYPES_ENUM.LMDB,api_call:mt.LICENSE_VALUES.API_CALL_DEFAULT,ram_allocation:mt.RAM_ALLOCATION_ENUM.DEFAULT,version:mt.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Ze.error("empty license key passed to validate."),r;let s=Cl(),n=!1;try{n=En.statSync(s)}catch(i){Ze.error(i)}if(n){let i;try{i=En.readFileSync(s,"utf8")}catch{Ze.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(MG),c=o[1];c=Buffer.concat([Buffer.from(c)],BG);let _=Buffer.concat([Buffer.from(i)],vG),u=$R.createDecipheriv(PG,_,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let l=null;try{l=u.update(o[0],"hex","utf8"),l.trim(),l+=u.final("utf8")}catch{let S=FG(o[0],i);if(S)l=S;else throw r.valid_license=!1,r.valid_machine=!1,console.error(ln),Ze.error(ln),new Error(ln)}let E;if(isNaN(l))try{E=JSON.parse(l),r.api_call=E.api_call,r.version=E.version,r.storage_type=E.storage_type,r.exp_date=E.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),E.ram_allocation&&(r.ram_allocation=E.ram_allocation)}catch{throw console.error(ln),Ze.error(ln),new Error(ln)}else r.exp_date=l;r.exp_date<wG().valueOf()&&(r.valid_date=!1),VR.validate(o[1],`${DG}${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||Ze.error("Invalid licence"),r}a(xR,"validateLicense");function FG(e,t){try{let r=$R.createDecipher("aes192",t),s=r.update(e,"hex","utf8");return s.trim(),s+=r.final("utf8"),s}catch{Ze.warn("Check old license failed")}}a(FG,"checkOldLicense");function YR(){let e=new yG;e.api_call=0;let t=[];try{t=En.readFileSync(HG(),"utf-8").split(mt.NEW_LINE)}catch(r){r.code==="ENOENT"?Ze.info("no license file found"):Ze.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let s=t[r];try{if(LG.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=xR(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.api_call+=i.api_call,e.ram_allocation=i.ram_allocation,e.storage_type=i.storage_type,e.enterprise=!0)}catch(n){Ze.error("There was an error parsing the license string."),Ze.error(n),e.api_call=mt.LICENSE_VALUES.API_CALL_DEFAULT,e.ram_allocation=mt.RAM_ALLOCATION_ENUM.DEFAULT,e.storage_type=mt.STORAGE_TYPES_ENUM.LMDB,e.enterprise=!1}}return e.api_call===0&&(e.api_call=mt.LICENSE_VALUES.API_CALL_DEFAULT),gl=e,e}a(YR,"licenseSearch");async function VG(){return gl||await YR(),gl}a(VG,"getLicense")});var Rr=h((WZ,aA)=>{"use strict";var XR="username is required",ZR="nothing to update, must supply active, role or password to update",zR="password cannot be an empty string",jR="If role is specified, it cannot be empty.",eA="active must be true or false";aA.exports={addUser:JG,alterUser:XG,dropUser:zG,userInfo:jG,listUsers:Ko,listUsersExternal:eF,setUsersToGlobal:Ai,findAndValidateUser:sF,getClusterUser:nF,USERNAME_REQUIRED:XR,ALTERUSER_NOTHING_TO_UPDATE:ZR,EMPTY_PASSWORD:zR,EMPTY_ROLE:jR,ACTIVE_BOOLEAN:eA};var tA=Lt(),$G=ms(),Ul=ko(),rA=vR(),sA=Tt(),Ll=Xs(),Ce=b(),nA=require("validate.js"),H=g(),{promisify:yl}=require("util"),Dl=Fr(),Rs=T(),WR=Se(),kG=Er(),Ml=V(),xG=Ri(),YG=cs(),{handleHDBError:tr,hdb_errors:KG}=D(),{HTTP_STATUS_CODES:rr,AUTHENTICATION_ERROR_MSGS:wl,HDB_ERROR_MSGS:dn}=KG,{UserEventMsg:Pl}=Hr(),QR=require("lodash"),iA={username:!0,active:!0,role:!0,password:!0},JR=new Map,Yo=yl(sA.searchByValue),WG=yl(sA.searchByHash),QG=yl($G.delete);async function JG(e){let t=nA.cleanAttributes(e,iA),r=rA.addUserValidation(t);if(r)throw tr(new Error,r.message,rr.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 Yo(s)}catch(u){throw H.error("There was an error searching for a role in add user"),H.error(u),u}if(!n||n.length<1)throw tr(new Error,dn.ROLE_NAME_NOT_FOUND(t.role),rr.NOT_FOUND,void 0,void 0,!0);if(n.length>1)throw tr(new Error,dn.DUP_ROLES_FOUND(t.role),rr.CONFLICT,void 0,void 0,!0);n[0].permission.cluster_user===!0&&(t.hash=Dl.encrypt(t.password)),t.password=Ul.hash(t.password),t.role=n[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await tA.insert(i)}catch(u){throw H.error("There was an error searching for a user."),H.error(u),u}H.debug(o);try{await Ai()}catch(u){throw H.error("Got an error setting users to global"),H.error(u),u}if(o.skipped_hashes.length===1)throw tr(new Error,dn.USER_ALREADY_EXISTS(t.username),rr.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);c.role=n[0];let _={user:null};return _.user=c,Ce.sendTransactionToSocketCluster(Rs.INTERNAL_SC_CHANNELS.ADD_USER,_,Ml.get(Rs.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY)),Ll.signalUserChange(new Pl(process.pid)),`${c.username} successfully added`}a(JG,"addUser");async function XG(e){let t=nA.cleanAttributes(e,iA);if(Ce.isEmptyOrZeroLength(t.username))throw new Error(XR);if(Ce.isEmptyOrZeroLength(t.password)&&Ce.isEmptyOrZeroLength(t.role)&&Ce.isEmptyOrZeroLength(t.active))throw new Error(ZR);if(!Ce.isEmpty(t.password)&&Ce.isEmptyOrZeroLength(t.password.trim()))throw new Error(zR);if(!Ce.isEmpty(t.active)&&!Ce.isBoolean(t.active))throw new Error(eA);let r=ZG(t.username);if(!Ce.isEmpty(t.password)&&!Ce.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=Dl.encrypt(t.password)),t.password=Ul.hash(t.password)),t.role==="")throw new Error(jR);if(t.role){let o={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["*"]},c;try{c=await Yo(o)}catch(_){throw H.error("Got an error searching for a role."),H.error(_),_}if(!c||c.length===0){let _=dn.ALTER_USER_ROLE_NOT_FOUND(t.role);throw H.error(_),tr(new Error,_,rr.NOT_FOUND,void 0,void 0,!0)}if(c.length>1){let _=dn.ALTER_USER_DUP_ROLES(t.role);throw H.error(_),tr(new Error,_,rr.CONFLICT,void 0,void 0,!0)}t.role=c[0].id}let s={operation:"update",schema:"system",table:"hdb_user",records:[t]},n;try{n=await tA.update(s)}catch(o){throw H.error("Error during update."),H.error(o),o}try{await Ai()}catch(o){throw H.error("Got an error setting users to global"),H.error(o),o}let i={user:null};return i.user=t,Ce.sendTransactionToSocketCluster(Rs.INTERNAL_SC_CHANNELS.ALTER_USER,i,Ml.get(Rs.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY)),Ll.signalUserChange(new Pl(process.pid)),n}a(XG,"alterUser");function ZG(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(ZG,"isClusterUser");async function zG(e){try{let t=rA.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Ce.isEmpty(global.hdb_users.get(e.username)))throw tr(new Error,dn.USER_NOT_EXIST(e.username),rr.NOT_FOUND,void 0,void 0,!0);let s;try{s=await QG(r)}catch(i){throw H.error("Got an error deleting a user."),H.error(i),i}H.debug(s);try{await Ai()}catch(i){throw H.error("Got an error setting users to global."),H.error(i),i}let n={user:null};return n.user=e,Ce.sendTransactionToSocketCluster(Rs.INTERNAL_SC_CHANNELS.DROP_USER,n,Ml.get(Rs.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY)),Ll.signalUserChange(new Pl(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(zG,"dropUser");async function jG(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 WG(r)}catch(n){throw H.error("Got an error searching for a role."),H.error(n),n}t.role=s[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw H.error(r),r}return t}a(jG,"userInfo");async function eF(){let e;try{e=await Ko()}catch(t){throw H.error("Got an error listing users."),H.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(eF,"listUsersExternal");async function Ko(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=QR.cloneDeep(await Yo(e))}catch(r){throw H.error("Got an error searching for roles."),H.error(r),r}if(!Ce.isEmptyOrZeroLength(t)){let r={};for(let o in t)r[t[o].id]=t[o];let s={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},n;try{n=QR.cloneDeep(await Yo(s))}catch(o){throw H.error("Got an error searching for users."),H.error(o),o}let i=new Map;for(let o in n){let c=n[o];c.role=r[n[o].role],tF(c.role),i.set(c.username,c)}return(await xG.getLicense()).enterprise?i:rF(i)}}catch(e){throw H.error("got an error listing users"),H.error(e),Ce.errorizeMessage(e)}return null}a(Ko,"listUsers");function tF(e){try{if(!e){H.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(YG)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){H.error("Got an error trying to set system permissions."),H.error(t)}}a(tF,"appendSystemTablesToRole");function rF(e){try{if(H.info("No enterprise license found. System is limited to 1 clustering role and 1 user role"),!e)return new Map;let t=Object.create(null),r=new Map;e.forEach((n,i)=>{n.role.permission.cluster_user===void 0||n.role.permission.cluster_user===!1?n.role.permission.super_user===!0&&(t[n.role.id]||(t[n.role.id]=new Map),t[n.role.id].set(i,n)):r.set(i,n)});let s={role:void 0,count:0};return Object.keys(t).forEach(n=>{let i=t[n];i.size>=s.count&&(s.role=n,s.count=i.size)}),s.role===void 0?(H.error("No roles found with active users. This is bad."),new Map):(r=new Map([...r,...t[s.role]]),r)}catch(t){return H.error("error filtering users."),H.error(t),new Map}}a(rF,"nonEnterpriseFilter");async function Ai(){try{let e=await Ko();global.hdb_users=e}catch(e){throw H.error(e),e}}a(Ai,"setUsersToGlobal");async function sF(e,t,r=!0){global.hdb_users||await Ai();let s=global.hdb_users.get(e);if(!s)throw tr(new Error,wl.GENERIC_AUTH_FAIL,rr.UNAUTHORIZED,void 0,void 0,!0);if(s&&!s.active)throw tr(new Error,wl.USER_INACTIVE,rr.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(JR.get(t)===s.password)return n;if(Ul.validate(s.password,t))JR.set(t,s.password);else throw tr(new Error,wl.GENERIC_AUTH_FAIL,rr.UNAUTHORIZED,void 0,void 0,!0)}return n}a(sF,"findAndValidateUser");async function nF(){let e=await Ko(),t=kG.getConfigFromFile(Rs.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Ce.isEmpty(r))return r.decrypt_hash=Dl.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+WR.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+WR.SERVER_SUFFIX.ADMIN,r}a(nF,"getClusterUser")});var uA=h((QZ,_A)=>{"use strict";var iF=require("node-ipc").IPC,oA=b(),cA=T(),Ar=g(),{IPC_ERRORS:hn}=We(),aF=require("os"),Wo=class{constructor(t,r){this.ipc=new iF,this.server_name=cA.HDB_IPC_SERVER,this.ipc.config.retry=aF.platform()=="win32"?6e5:100,this.ipc.config.id=cA.HDB_IPC_CLIENT_PREFIX+t,this.ipc.config.silent=!0,this.event_handlers=r,this.connect()}connect(){this.ipc.connectTo(this.server_name,()=>{this.generateEventHandlers(this.event_handlers)})}addEventHandler(t,r){this.ipc.of[this.server_name].on(t,r)}generateEventHandlers(t){this.ipc.of[this.server_name].on("connect",()=>{Ar.info(`IPC client ${this.ipc.config.id} connected to ${this.server_name}`)}),this.ipc.of[this.server_name].on("disconnect",()=>{Ar.info(`IPC client ${this.ipc.config.id} disconnected from ${this.server_name}`)}),this.ipc.of[this.server_name].on("error",r=>{r.code==="ECONNREFUSED"&&Ar.warn("Error connecting to HDB IPC server. Confirm that the server is running."),Ar.warn(`Error with IPC client ${this.ipc.config.id}`),Ar.warn(r)});for(let[r,s]of Object.entries(t))this.addEventHandler(r,s)}emitToServer(t){if(typeof t!="object")throw Ar.warn(hn.INVALID_IPC_DATA_TYPE),new Error(hn.INVALID_IPC_DATA_TYPE);if(oA.isEmpty(t.type))throw Ar.warn(hn.MISSING_TYPE),new Error(hn.MISSING_TYPE);if(oA.isEmpty(t.message))throw Ar.warn(hn.MISSING_MSG),new Error(hn.MISSING_MSG);Ar.trace(`IPC client ${this.ipc.config.id} emitting`,t),this.ipc.of[this.server_name].emit("message",t)}};a(Wo,"IPCClient");_A.exports=Wo});var dA=h((JZ,EA)=>{"use strict";var Bl=Z(),oF=g(),lA=We().LMDB_ERRORS_ENUM;EA.exports=cF;async function cF(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 Bl.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==lA.ENV_REQUIRED)throw c}}break;case"drop_table":let s=`${e.schema}.${e.table}`,n=`txn.${s}`;try{await Bl.closeEnvironment(global.lmdb_map[s]),await Bl.closeEnvironment(global.lmdb_map[n])}catch(i){if(i.message!==lA.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){oF.error(t)}}a(cF,"cleanLMDBMap")});var mA=h((XZ,TA)=>{"use strict";var As=g(),Qo=T(),_F=dA(),hA=$r(),uF=Ss(),lF=Rr(),{validateEvent:fA}=Hr(),EF={[Qo.IPC_EVENT_TYPES.SCHEMA]:dF,[Qo.IPC_EVENT_TYPES.USER]:SF};async function dF(e){let t=fA(e);if(t){As.error(t);return}As.trace(`IPC schemaHandler ${Qo.HDB_IPC_CLIENT_PREFIX}${process.pid} received schema event:`,e),await _F(e.message),await hF(e.message)}a(dF,"schemaHandler");async function hF(e){try{if(global.hdb_schema!==void 0&&typeof global.hdb_schema=="object"&&e.operation!==void 0)switch(e.operation){case"drop_schema":delete global.hdb_schema[e.schema];break;case"drop_table":global.hdb_schema[e.schema]!==void 0&&delete global.hdb_schema[e.schema][e.table];break;case"create_schema":global.hdb_schema[e.schema]===void 0&&(global.hdb_schema[e.schema]={});break;case"create_table":case"create_attribute":global.hdb_schema[e.schema]===void 0&&(global.hdb_schema[e.schema]={}),global.hdb_schema[e.schema][e.table]=await uF.describeTable({schema:e.schema,table:e.table});break;default:hA.setSchemaDataToGlobal(SA);break}else hA.setSchemaDataToGlobal(SA)}catch(t){As.error(t)}}a(hF,"syncSchemaMetadata");function SA(e){e&&As.error(e)}a(SA,"handleErrorCallback");async function SF(e){try{let t=fA(e);if(t){As.error(t);return}As.trace(`IPC userHandler ${Qo.HDB_IPC_CLIENT_PREFIX}${process.pid} received user event:`,e),await lF.setUsersToGlobal()}catch(t){As.error(t)}}a(SF,"userHandler");TA.exports=EF});var pA=h((ZZ,AA)=>{"use strict";var RA=require("fs"),pi=V();pi.initSync();var{CONFIG_PARAMS:Jo}=T(),fF=1024*1024*1024;function TF(e){let t=pi.get(Jo.CUSTOMFUNCTIONS_NETWORK_TIMEOUT),r=pi.get(Jo.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT),s={bodyLimit:fF,connectionTimeout:t,keepAliveTimeout:r,ignoreTrailingSlash:!0};if(e){let n=pi.get(Jo.CUSTOMFUNCTIONS_TLS_PRIVATEKEY),i=pi.get(Jo.CUSTOMFUNCTIONS_TLS_CERTIFICATE);s.https={key:RA.readFileSync(`${n}`),cert:RA.readFileSync(`${i}`)}}return s}a(TF,"getServerOptions");AA.exports=TF});var gA=h((zZ,NA)=>{"use strict";var vl=V();vl.initSync();var{CONFIG_PARAMS:OA}=T();function mF(){let e=vl.get(OA.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST),t=vl.get(OA.CUSTOMFUNCTIONS_NETWORK_CORS),r;if(t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization"],credentials:!1},e&&e.length>0&&e[0]!==null)){let s=e.split(",");r.origin=(n,i)=>s.indexOf(n)!==-1?i(null,!0):i(new Error(`domain ${n} is not on access list`))}return r}a(mF,"getCORSOptions");NA.exports=mF});var CA=h((jZ,bA)=>{"use strict";var IA=V();IA.initSync();var RF=T();function AF(){return IA.get(RF.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT)}a(AF,"getHeaderTimeoutConfig");bA.exports=AF});var UA=h((e3,wA)=>{var pF=de(),OF={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};wA.exports=function(e){return pF.validateObject(e,OF)}});var Hl=h((t3,LA)=>{"use strict";var NF=T().OPERATIONS_ENUM,Xo=class{constructor(t,r,s,n=void 0){this.operation=NF.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};a(Xo,"UpdateObject");LA.exports=Xo});var DA=h((r3,yA)=>{"use strict";var gF={OPERATION:"operation",REFRESH:"refresh"},Zo=class{constructor(t,r){this.operation_token=t,this.refresh_token=r}};a(Zo,"JWTTokens");var zo=class{constructor(t,r,s){this.public_key=t,this.private_key=r,this.passphrase=s}};a(zo,"JWTRSAKeys");yA.exports={JWTTokens:Zo,TOKEN_TYPE_ENUM:gF,JWTRSAKeys:zo}});var rc=h((s3,vA)=>{"use strict";var Ni=require("jsonwebtoken"),ql=require("fs-extra"),Gl=b(),yt=T(),{handleHDBError:ot,hdb_errors:IF}=D(),{HTTP_STATUS_CODES:ct,AUTHENTICATION_ERROR_MSGS:_t}=IF,Oi=g(),MA=ko(),$l=Rr(),bF=Lt().update,CF=Hl(),wF=Xs(),{UserEventMsg:UF}=Hr(),Wr=V();Wr.initSync();var Fl=require("path"),{JWTTokens:LF,JWTRSAKeys:yF,TOKEN_TYPE_ENUM:jo}=DA(),DF=Wr.get(yt.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?Wr.get(yt.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",MF=Wr.get(yt.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?Wr.get(yt.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",ec="RS256",Vl;vA.exports={createTokens:PF,validateOperationToken:vF,refreshOperationToken:BF,validateRefreshToken:BA};async function PF(e){if(Gl.isEmpty(e)||typeof e!="object")throw ot(new Error,_t.INVALID_AUTH_OBJECT,ct.BAD_REQUEST,void 0,void 0,!0);if(Gl.isEmpty(e.username))throw ot(new Error,_t.USERNAME_REQUIRED,ct.BAD_REQUEST,void 0,void 0,!0);if(Gl.isEmpty(e.password))throw ot(new Error,_t.PASSWORD_REQUIRED,ct.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await $l.findAndValidateUser(e.username,e.password),!t)throw ot(new Error,_t.INVALID_CREDENTIALS,ct.UNAUTHORIZED,void 0,void 0,!0)}catch(d){throw Oi.error(d),ot(new Error,_t.INVALID_CREDENTIALS,ct.UNAUTHORIZED,void 0,void 0,!0)}let r=await tc(),s=!1,n=!1;t.role&&t.role.permission&&(s=t.role.permission.super_user===!0,n=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:s,cluster_user:n},o=await PA(i,r.private_key,r.passphrase),c=await Ni.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:MF,algorithm:ec,subject:jo.REFRESH}),_=MA.hash(c),u=new CF(yt.SYSTEM_SCHEMA_NAME,yt.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:_}]),l,E;try{l=await bF(u)}catch(d){Oi.error(d),E=d}if(E!==void 0||l.skipped_hashes.length>0)throw ot(new Error,_t.REFRESH_TOKEN_SAVE_FAILED,ct.INTERNAL_SERVER_ERROR);return wF.signalUserChange(new UF(process.pid)),new LF(o,c)}a(PF,"createTokens");async function PA(e,t,r){return await Ni.sign(e,{key:t,passphrase:r},{expiresIn:DF,algorithm:ec,subject:jo.OPERATION})}a(PA,"signOperationToken");async function tc(){if(Vl===void 0)try{let e=Fl.join(Wr.getHdbBasePath(),yt.LICENSE_KEY_DIR_NAME,yt.JWT_ENUM.JWT_PASSPHRASE_NAME),t=Fl.join(Wr.getHdbBasePath(),yt.LICENSE_KEY_DIR_NAME,yt.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=Fl.join(Wr.getHdbBasePath(),yt.LICENSE_KEY_DIR_NAME,yt.JWT_ENUM.JWT_PUBLIC_KEY_NAME),s=(await ql.readFile(e)).toString(),n=(await ql.readFile(t)).toString(),i=(await ql.readFile(r)).toString();Vl=new yF(i,n,s)}catch(e){throw Oi.error(e),ot(new Error,_t.NO_ENCRYPTION_KEYS,ct.INTERNAL_SERVER_ERROR)}return Vl}a(tc,"getJWTRSAKeys");async function BF(e){if(!e)throw ot(new Error,_t.INVALID_BODY,ct.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw ot(new Error,_t.REFRESH_TOKEN_REQUIRED,ct.BAD_REQUEST,void 0,void 0,!0);await BA(e.refresh_token);let t=await tc(),r=await Ni.decode(e.refresh_token);return{operation_token:await PA({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(BF,"refreshOperationToken");async function vF(e){try{let t=await tc(),r=await Ni.verify(e,t.public_key,{algorithms:ec,subject:jo.OPERATION});return await $l.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Oi.warn(t),t.name&&t.name==="TokenExpiredError"?ot(new Error,_t.TOKEN_EXPIRED,ct.FORBIDDEN):ot(new Error,_t.INVALID_TOKEN,ct.UNAUTHORIZED)}}a(vF,"validateOperationToken");async function BA(e){let t;try{let r=await tc(),s=await Ni.verify(e,r.public_key,{algorithms:ec,subject:jo.REFRESH});t=await $l.findAndValidateUser(s.username,void 0,!1)}catch(r){throw Oi.warn(r),r.name&&r.name==="TokenExpiredError"?ot(new Error,_t.TOKEN_EXPIRED,ct.FORBIDDEN):ot(new Error,_t.INVALID_TOKEN,ct.UNAUTHORIZED)}if(!MA.validate(t.refresh_token,e))throw ot(new Error,_t.INVALID_TOKEN,ct.UNAUTHORIZED);return t}a(BA,"validateRefreshToken")});var kl=h((i3,GA)=>{"use strict";var HF=UA(),Sn=require("passport"),qF=require("passport-local").Strategy,GF=require("passport-http").BasicStrategy,FF=require("util"),VF=Rr(),qA=FF.callbackify(VF.findAndValidateUser),n3=We(),$F=T(),HA=rc();Sn.use(new qF(function(e,t,r){qA(e,t,r)}));Sn.use(new GF(function(e,t,r){qA(e,t,r)}));Sn.serializeUser(function(e,t){t(null,e)});Sn.deserializeUser(function(e,t){t(null,e)});function kF(e,t,r){let s,n;if(e.headers&&e.headers.authorization){let o=e.headers.authorization.split(" ");s=o[0],n=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("User not found")}switch(a(i,"handleResponse"),s){case"Basic":Sn.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body&&e.body.operation&&e.body.operation===$F.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?HA.validateRefreshToken(n).then(o=>{e.body.refresh_token=n,r(null,o)}).catch(o=>{r(o)}):HA.validateOperationToken(n).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Sn.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(kF,"authorize");function xF(e,t){let r=HF(e);if(r){t(r);return}let s={authorized:!0,messages:[]},n=e.user.role;if(!n||!n.permission)return t("Invalid role");let i=JSON.parse(n.permission);if(i.super_user)return t(null,s);if(!i[e.schema])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.schema} schema`),t(null,s);if(!i[e.schema].tables[e.table])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.table} table`),t(null,s);if(!i[e.schema].tables[e.table][e.operation])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,s);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return s.authorized=!1,s.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,s);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(s.authorized=!1,s.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,s)}a(xF,"checkPermissions");GA.exports={authorize:kF,checkPermissions:xF}});var sc=h((a3,FA)=>{"use strict";var YF=mr();FA.exports={writeTransaction:KF};function KF(e,t,r){return YF.writeTransaction(e,t,r)}a(KF,"writeTransaction")});var xl=h((o3,WF)=>{WF.exports={name:"harperdb",version:"4.0.5",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.13.0","go-lang":"1.19.3","nats-server":"2.9.8"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"See License in ./license/Community+Edition+and+Evaluation+End+User+License+Agreement.pdf",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ data_layer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ data_layer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",test:"rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license --storage_type=lmdb && npm run cover:upgrade && npm run cover:nats && npm run cover:cfserver && npm run cover:lmdbbridge && npm run cover:lmdbutility && npm run cover:hdbserver && npm run cover:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license --storage_type=lmdb","cover:main":"cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","cover:lmdbbridge":"cd bin/ && nyc --no-clean --reporter=lcovonly --retries 3 ../node_modules/mocha/bin/_mocha '../unitTests/data_layer/harperBridge/lmdbBridge/**/*.js' --parallel --config '../unitTests/.mocharc.json'","cover:lmdbutility":"cd bin/ && nyc --no-clean --reporter=lcovonly --retries 3 ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --config '../unitTests/.mocharc.json'","cover:hdbserver":"cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --config '../unitTests/.mocharc.json'","cover:cfserver":"npm run submodules && cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","cover:nats":"cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","cover:upgrade":"cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.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/data_layer/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:{"@fastify/accepts-serializer":"5.1.0","@fastify/autoload":"5.4.0","@fastify/compress":"6.1.1","@fastify/cors":"8.1.0","@fastify/static":"6.5.0","@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",async:"3.2.3","aws-sdk":"2.1096.0",chalk:"4.1.2","cli-progress":"3.10.0",clone:"2.1.2",esbuild:"^0.14.49","fast-glob":"3.2.11",fastify:"4.8.1","fastify-plugin":"4.2.1","fill-range":"7.0.1","fs-extra":"10.0.1","human-readable-ids":"1.0.4",inquirer:"8.2.2","is-number":"7.0.0",joi:"17.6.0",json2csv:"5.0.7",jsonata:"1.8.6",jsonwebtoken:"8.5.1",lmdb:"2.7.6",lodash:"4.17.21",mathjs:"10.4.0",microtime:"3.1.1",minimist:"1.2.6",mkcert:"1.5.0",moment:"2.29.4",msgpackr:"1.8.2",nats:"2.9.2",needle:"3.1.0","node-ipc":"9.1.4","node-stream-zip":"1.15.0","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.3.0",papaparse:"5.3.2",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.3.1",pm2:"5.2.0",prompt:"1.2.2","properties-reader":"2.2.0","recursive-iterator":"3.3.0",semver:"7.3.5","stream-chain":"2.2.5","stream-json":"1.7.4",systeminformation:"5.12.4","tar-fs":"2.1.1","truncate-utf8-bytes":"1.0.2",ulidx:"0.3.0",uuid:"9.0.0","validate.js":"0.11.1",yaml:"1.10.2"},devDependencies:{axios:"0.27.2",chai:"4.3.4","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","hook-std":"2.0.0","intercept-stdout":"0.1.2",mocha:"8.3.2","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",newman:"5.2.3","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"1.21.0","newman-reporter-teamcity":"0.1.11","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.3.2",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},"newman-reporter-html":{newman:"5.2.3"}}}});var Rt=h((m3,ap)=>{"use strict";var pr=V();pr.initSync();var QF=require("fs-extra"),JF=require("semver"),wi=require("path"),{monotonicFactory:XF}=require("ulidx"),ZF=XF(),$A=require("util"),kA=require("child_process"),zF=$A.promisify(kA.exec),jF=kA.spawn,te=Se(),ae=T(),Xl=b(),Or=g(),nc=Fr(),e0=sc(),gi=Er(),{encode:Wl,decode:xA}=require("msgpackr"),{isEmpty:ps}=Xl,YA=Rr(),c3=Es(),t0=Tt(),_3=$A.promisify(t0.searchByHash),{connect:r0,StorageType:KA,RetentionPolicy:WA,AckPolicy:QA,DeliverPolicy:Ql,NatsConnection:u3,JetStreamManager:l3,JetStreamClient:E3,StringCodec:d3,JSONCodec:s0,createInbox:Zl,StreamSource:h3,headers:n0,toJsMsg:i0,nuid:S3,JetStreamOptions:f3,ErrorCode:VA,nanos:T3}=require("nats"),{PACKAGE_ROOT:a0}=T(),o0=xl(),JA=s0(),c0="clustering",_0=o0.engines[te.NATS_SERVER_NAME],u0=wi.join(a0,"dependencies"),Jl=wi.join(u0,`${process.platform}-${process.arch}`,te.NATS_BINARY_NAME),Yl,Kl,Ii,bi,Ci,Kt;ap.exports={runCommand:XA,checkNATSServerInstalled:l0,createConnection:zl,getConnection:ic,getJetStreamManager:fn,getJetStream:ZA,getNATSReferences:Dt,getServerList:d0,createLocalStream:jl,listStreams:zA,deleteLocalStream:h0,getServerConfig:Ui,listRemoteStreams:S0,viewStream:f0,publishToStream:T0,createWorkQueueStream:m0,addSourceToWorkStream:jA,request:R0,removeSourceFromWorkStream:tp,reloadNATS:eE,reloadNATSHub:A0,reloadNATSLeaf:p0,extractServerName:ep,requestErrorHandler:O0,updateWorkStream:N0,createLocalTableStream:sp,createTableStreams:g0,purgeTableStream:np,purgeSchemaTableStreams:I0,getStreamInfo:b0,updateNodeNameLocalStreams:C0,closeConnection:E0};async function XA(e,t=void 0){let{stdout:r,stderr:s}=await zF(e,{cwd:t});if(s)throw new Error(s.replace(`
6
6
  `,""));return r.replace(`
7
- `,"")}a(tp,"runCommand");async function C0(){try{await u0.access(zl)}catch{return!1}let e=await tp(`${zl} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return l0.eq(t,I0)}a(C0,"checkNATSServerInstalled");async function tE(e,t,r,s=!0,n="127.0.0.1"){return m0({name:n,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:s,tls:{keyFile:ir.get(ne.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:ir.get(ne.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:ir.get(ne.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),insecure:ir.get(ne.CONFIG_PARAMS.CLUSTERING_TLS_INSECURE)}})}a(tE,"createConnection");async function w0(){Wt&&(await Wt.close(),Wt=void 0)}a(w0,"closeConnection");async function oc(){if(!Wt){let e=await ZA.getClusterUser();if(gs(e))throw new Error("Unable to get nats connection. Cluster user is undefined.");let t=ir.get(ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT);Wt=await tE(t,e.username,e.decrypt_hash)}return Wt}a(oc,"getConnection");async function Rn(){if(wi)return wi;gs(Wt)&&await oc();let{domain:e}=yi(ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(gs(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return wi=await Wt.jetstreamManager({domain:e}),wi}a(Rn,"getJetStreamManager");async function rp(){if(Ui)return Ui;gs(Wt)&&await oc();let{domain:e}=yi(ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(gs(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Ui=Wt.jetstream({domain:e}),Ui}a(rp,"getJetStream");async function Mt(){let e=Wt||await oc(),t=wi||await Rn(),r=Ui||await rp();return{connection:e,jsm:t,js:r}}a(Mt,"getNATSReferences");async function U0(){let e=ir.get(ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),{sys_name:t,decrypt_hash:r}=await ZA.getClusterUser(),s=await tE(e,t,r),n=eE(),i=s.subscribe(n),o=[],c=(async()=>{for await(let _ of i)o.push(ep.decode(_.data))})();return await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:n}),await s.flush(),await jl.async_set_timeout(50),await i.drain(),await s.close(),await c,o}a(U0,"getServerList");async function rE(e,t){let{jsm:r}=await Mt();await r.streams.add({name:e,storage:XA.File,retention:zA.Limits,subjects:t})}a(rE,"createLocalStream");async function sp(){let{jsm:e}=await Mt(),t=await e.streams.list().next(),r=[];return t.forEach(s=>{r.push(s)}),r}a(sp,"listStreams");async function L0(e){let{jsm:t}=await Mt();await t.streams.delete(e)}a(L0,"deleteLocalStream");async function y0(e){let{connection:t}=await Mt(),r=[],s=eE(),n=t.subscribe(s),i=(async()=>{for await(let o of n)r.push(ep.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:s}),await t.flush(),await n.drain(),await i,r}a(y0,"listRemoteStreams");async function D0(e,t=void 0,r=void 0){let{jsm:s,connection:n}=await Mt(),i=d0(),o=[],c={ack_policy:jA.None,durable_name:i,deliver_subject:i,deliver_policy:Xl.All};t&&(c.deliver_policy=Xl.StartTime,c.opt_start_time=new Date(t).toISOString());try{await s.consumers.add(e,c);let _={timeout:2e3};r&&(_.max=r);let u=await n.subscribe(i,_);for await(let l of u){let E=p0(l),d=JA(E.data),S={nats_timestamp:E.info.timestampNanos,nats_sequence:E.info.streamSequence,entry:d,originators:[]},m=[];if(E.headers){let R=E.headers.get("originators");R&&(m=R.split(","),S.originators=m)}o.push(S),u.getPending()===1&&E.info.pending===0&&u.stop()}return await s.consumers.delete(e,i),o}catch(_){if(await s.consumers.delete(e,i),_.code==="TIMEOUT")return o;throw _}}a(D0,"viewStream");async function M0(e,t,r=[],s=[]){br.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,r,"originators:",s);let{connection:n,js:i}=await Mt(),o=await cc(),c=`${e}.${o}`,_=A0();s.push(o),_.append("originators",s.join());for(let u=0,l=r.length;u<l;u++)try{br.trace(`publishToStream publishing to subject: ${c}, data:`,r[u]),await i.publish(c,Zl(r[u]),{headers:_})}catch(E){if(E.code&&E.code.toString()==="503")br.trace(`publishToStream creating stream: ${t}`),await rE(t,[c]),await i.publish(c,Zl(r[u]),{headers:_});else throw E}}a(M0,"publishToStream");function yi(e){e=e.toLowerCase();let t=Li.join(ir.get(ne.CONFIG_PARAMS.ROOTPATH),g0);if(e===ne.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return gs(Jl)&&(Jl={port:bi.getConfigFromFile(ne.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:bi.getConfigFromFile(ne.CONFIG_PARAMS.CLUSTERING_NODENAME)+te.SERVER_SUFFIX.HUB,config_file:te.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:Li.join(t,te.PID_FILES.HUB),hdb_nats_path:t}),Jl;if(e===ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return gs(Wl)&&(Wl={port:bi.getConfigFromFile(ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:bi.getConfigFromFile(ne.CONFIG_PARAMS.CLUSTERING_NODENAME)+te.SERVER_SUFFIX.LEAF,config_file:te.NATS_CONFIG_FILES.LEAF_SERVER,domain:bi.getConfigFromFile(ne.CONFIG_PARAMS.CLUSTERING_NODENAME)+te.SERVER_SUFFIX.LEAF,pid_file_path:Li.join(t,te.PID_FILES.LEAF),hdb_nats_path:t}),Wl;br.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(yi,"getServerConfig");async function P0(e){let{jsm:t}=await Mt(),r=await cc();try{await t.streams.add({name:e.stream_name,storage:XA.File,retention:zA.Workqueue,subjects:[`${te.SUBJECT_PREFIXES.MSGID}.${r}`,`${te.SUBJECT_PREFIXES.TXN}.${e.stream_name}.${r}`]})}catch(s){if(s.code!=="400")throw s}try{await t.consumers.info(e.stream_name,e.durable_name)}catch(s){if(s.code.toString()==="404")await t.consumers.add(e.stream_name,{ack_policy:jA.Explicit,deliver_subject:`${e.deliver_subject}.${r}`,durable_name:e.durable_name,deliver_policy:Xl.All,max_ack_pending:1e4,deliver_group:e.deliver_group,filter_subject:`${te.SUBJECT_PREFIXES.TXN}.>`});else throw s}}a(P0,"createWorkQueueStream");async function np(e,t,r){let{jsm:s}=await Mt(),n=await s.streams.info(t),i=ip(s.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:_}=r,u=ac.createNatsTableStreamName(c,_),l=i===e,E,d,S=!1;if(!Array.isArray(n.config.sources)||n.config.sources.length===0)n.config.sources=[];else for(let R=0,w=n.config.sources.length;R<w;R++)if(E=n.config.sources[R],d=R,l&&E.name===u||!l&&E.name===u&&E.external&&E.external.api===`$JS.${e}.API`){S=!0;break}if(S===!0){if(E.opt_start_time===o)return;await op(c,_,E,t),n.config.sources.splice(d,1),await s.streams.update(t,n.config)}let m={name:u,opt_start_time:o,filter_subject:`${te.SUBJECT_PREFIXES.TXN}.>`};l||(m.external={api:`$JS.${e}.API`,deliver:""}),n.config.sources.push(m),await s.streams.update(t,n.config)}a(np,"addSourceToWorkStream");function ip(e){return e.split(".")[1]}a(ip,"extractServerName");async function ap(e,t,r){let{schema:s,table:n}=r,i=ac.createNatsTableStreamName(s,n),{jsm:o}=await Mt(),c=await o.streams.info(t);if(!Array.isArray(c.config.sources)||c.config.sources.length===0)return;let _=c.config.sources.length,u;for(;_--;)if(u=c.config.sources[_],u.name===i&&u.external.api===`$JS.${e}.API`){c.config.sources.splice(_,1);break}await o.streams.update(t,c.config),await op(s,n,u,t)}a(ap,"removeSourceFromWorkStream");async function op(e,t,r,s){let n=await Rn(),i;try{i=up(e,t,r.external.api.split(".")[1]),await n.streams.purge(s,{filter:i})}catch{br.error("Error purging source subject",i,"from work stream",s)}}a(op,"purgeSourceFromWorkStream");async function B0(e,t,r=2e3,s=eE()){if(!jl.isObject(t))throw new Error("data param must be an object");let n=Zl(t),{connection:i}=await Mt(),o={timeout:r};s&&(o.reply=s,o.noMux=!0);let c=await i.request(e,n,o);return JA(c.data)}a(B0,"request");function sE(e){return new Promise(async(t,r)=>{let s=S0(zl,["--signal",`reload=${e}`],{cwd:__dirname}),n,i;s.on("error",o=>{r(o)}),s.stdout.on("data",o=>{i+=o.toString()}),s.stderr.on("data",o=>{n+=o.toString()}),s.stderr.on("close",o=>{n&&r(n),t(i)})})}a(sE,"reloadNATS");async function v0(){let{pid_file_path:e}=yi(ne.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await sE(e)}a(v0,"reloadNATSHub");async function H0(){let{pid_file_path:e}=yi(ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await sE(e)}a(H0,"reloadNATSLeaf");function q0(e,t,r){let s;switch(e.code){case KA.NoResponders:s=`Unable to ${t}, node '${r}' is not listening.`;break;case KA.Timeout:s=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:s=e.message;break}return s}a(q0,"requestErrorHandler");async function G0(e,t){let r=t+te.SERVER_SUFFIX.LEAF;await f0.writeTransaction(ne.SYSTEM_SCHEMA_NAME,ne.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,async()=>{e.subscribe===!0?await np(r,te.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await ap(r,te.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(G0,"updateWorkStream");async function cp(e,t){let r=ac.createNatsTableStreamName(e,t),s=await cc(),n=up(e,t,s);await rE(r,[n])}a(cp,"createLocalTableStream");async function F0(e){for(let t=0,r=e.length;t<r;t++){let s=e[t].schema,n=e[t].table;await cp(s,n)}}a(F0,"createTableStreams");async function _p(e,t){if(ir.get(ne.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let r=ac.createNatsTableStreamName(e,t),{jsm:s}=await Mt();await s.streams.purge(r)}catch(r){if(r.message==="stream not found")br.warn(r);else throw r}}a(_p,"purgeTableStream");async function V0(e,t){if(ir.get(ne.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,s=t.length;r<s;r++)await _p(e,t[r])}a(V0,"purgeSchemaTableStreams");async function k0(e){return(await Rn()).streams.info(e)}a(k0,"getStreamInfo");function up(e,t,r){return`${te.SUBJECT_PREFIXES.TXN}.${e}.${t}.${r}`}a(up,"createSubjectName");async function cc(){if(Ci)return Ci;if(Ci=(await Rn())?.nc?.info?.server_name,Ci===void 0)throw new Error("Unable to get jetstream manager server name");return Ci}a(cc,"getJsmServerName");async function x0(){let e=await Rn(),t=await cc(),r=await sp();for(let s of r){let n=s.config,i=n.subjects[0];if(!i)continue;let o=i.split(".");if(o[o.length-1]!==t){if(n.name===te.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let _=`${te.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;br.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else if(n.name===te.WORK_QUEUE_CONSUMER_NAMES.stream_name){let _=`${te.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;br.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_,await e.consumers.update(te.WORK_QUEUE_CONSUMER_NAMES.stream_name,te.WORK_QUEUE_CONSUMER_NAMES.durable_name,{deliver_subject:`${te.WORK_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`})}else{let _=i.split(".");_[_.length-1]=t;let u=_.join(".");br.trace(`Updating stream subject name from: ${i} to: ${u}`),n.subjects[0]=u}await e.streams.update(n.name,n)}}}a(x0,"updateNodeNameLocalStreams")});var nE=h((v3,Ep)=>{"use strict";var _c=class{constructor(t,r,s){this.timestamp=t,this.user=r,this.node_name=s}};a(_c,"ClusteringOriginObject");Ep.exports=_c});var On=h((H3,Sp)=>{"use strict";var dp=b(),Mi=V(),ue=T(),iE=Se(),An=At(),fe=g(),hp=nE(),$0=$r();Mi.initSync();var pn=iE.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name,Di=iE.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject;Sp.exports={sendAttributeTransaction:lc,postOperationHandler:K0};async function lc(e,t,r=[]){if(!!Mi.get(ue.CONFIG_PARAMS.CLUSTERING_ENABLED)&&!dp.isEmptyOrZeroLength(e.new_attributes)&&t.schema!==ue.SYSTEM_SCHEMA_NAME){let s=t.hdb_user?.username,n=Mi.get(ue.CONFIG_PARAMS.CLUSTERING_NODENAME);for(let i of e.new_attributes){let o={operation:ue.OPERATIONS_ENUM.CREATE_ATTRIBUTE,schema:t.schema,table:t.table,attribute:i,__origin:new hp(e.txn_time,s,n)};fe.trace(`sendAttributeTransaction publishing ${pn}`,o),await An.publishToStream(Di,pn,[o],r)}}}a(lc,"sendAttributeTransaction");async function uc(e,t,r,s=[]){if(e.schema===ue.SYSTEM_SCHEMA_NAME)return;let n=Y0(e,t,r);n&&(fe.trace(`sendOperationTransaction publishing to schema ${e.schema} table ${e.table} following transaction:`,n),await An.publishToStream(`${iE.SUBJECT_PREFIXES.TXN}.${e.schema}.${e.table}`,$0.createNatsTableStreamName(e.schema,e.table),[n],s))}a(uc,"sendOperationTransaction");function Y0(e,t,r){if(dp.isEmptyOrZeroLength(t))return null;let s={operation:e.operation,schema:e.schema,table:e.table,__origin:r};return e.operation===ue.OPERATIONS_ENUM.DELETE?s.hash_values=t:s.records=e.records,s}a(Y0,"convertCRUDOperationToTransaction");async function K0(e,t,r=[]){if(!Mi.get(ue.CONFIG_PARAMS.CLUSTERING_ENABLED))return;fe.trace(`postOperationHandler called for operation ${e.operation} on schema.table: ${e.schema}.${e.table}`);let s=e.hdb_user?.username,n=Mi.get(ue.CONFIG_PARAMS.CLUSTERING_NODENAME),i=new hp(t.txn_time,s,n);switch(e.operation){case ue.OPERATIONS_ENUM.INSERT:try{await uc(e,t.inserted_hashes,i,r),await lc(t,e,r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for insert."),fe.error(o)}break;case ue.OPERATIONS_ENUM.DELETE:try{await uc(e,t.deleted_hashes,i,r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for delete."),fe.error(o)}break;case ue.OPERATIONS_ENUM.UPDATE:try{await uc(e,t.update_hashes,i,r),await lc(t,e,r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for update."),fe.error(o)}break;case ue.OPERATIONS_ENUM.UPSERT:try{await uc(e,t.upserted_hashes,i,r),await lc(t,e,r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for upsert."),fe.error(o)}break;case ue.OPERATIONS_ENUM.CREATE_SCHEMA:try{let o={operation:ue.OPERATIONS_ENUM.CREATE_SCHEMA,schema:e.schema,__origin:i};await An.publishToStream(Di,pn,[o],r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for create_schema."),fe.error(o)}break;case ue.OPERATIONS_ENUM.CREATE_TABLE:try{let o={operation:ue.OPERATIONS_ENUM.CREATE_TABLE,schema:e.schema,table:e.table,hash_attribute:e.hash_attribute,__origin:i};await An.publishToStream(Di,pn,[o],r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for create_table."),fe.error(o)}break;case ue.OPERATIONS_ENUM.CREATE_ATTRIBUTE:try{let o={operation:ue.OPERATIONS_ENUM.CREATE_ATTRIBUTE,schema:e.schema,table:e.table,attribute:e.attribute,__origin:i};await An.publishToStream(Di,pn,[o],r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for create_attribute."),fe.error(o)}break;case ue.OPERATIONS_ENUM.CSV_DATA_LOAD:try{let o={operation:ue.OPERATIONS_ENUM.CSV_DATA_LOAD,schema:e.schema,table:e.table,attribute:e.attribute};await An.publishToStream(Di,pn,[o],r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for csv_data_load."),fe.error(o)}break;default:break}return t}a(K0,"postOperationHandler")});var Ap=h((q3,Rp)=>{"use strict";var Q0=mt(),W0=Kr(),fp=g(),Tp=yt(),J0=ic(),Z0=require("clone"),oE=require("alasql"),X0=yo(),mp=require("util"),z0=mp.promisify(W0.getTableSchema),j0=mp.promisify(Q0.search),eV=T(),aE=b(),tV=On();X0(oE);Rp.exports={update:sV};var rV="There was a problem performing this update. Please check the logs and try again.";async function sV({statement:e,hdb_user:t}){let r=await z0(e.table.databaseid,e.table.tableid),s=nV(e.columns);aE.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=Z0(n),c=aE.isEmpty(i)?"":` WHERE ${i.toString()}`,_=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,u=oE.parse(_).statements[0],l=await J0.writeTransaction(r.schema,r.name,async()=>{let E=await j0(u),d=iV(s,E);return aV(o,d,t)});return await Tp.flush({schema:r.schema,table:r.name}),l}a(sV,"update");function nV(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value:t[r.column.columnid]=oE.compile(`SELECT ${r.expression.toString()} AS [${eV.FUNC_VAL}] FROM ?`)}),t}catch(t){throw fp.error(t),new Error(rV)}}a(nV,"createUpdateRecord");function iV(e,t){return aE.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(iV,"buildUpdateRecords");async function aV(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r};try{let n=await Tp.update(s);await tV.postOperationHandler(s,n);try{delete n.new_attributes,delete n.txn_time}catch(i){fp.error(`Error delete new_attributes from update response: ${i}`)}return n}catch(n){throw n}}a(aV,"updateRecords")});var Op=h((G3,pp)=>{var oV=require("alasql"),cV=mt(),_V=g(),uV=Nr(),_E=require("util"),cE=b(),lV=T(),EV=Kr(),dV=ic(),hV=On(),SV=yt(),fV="record",TV="successfully deleted",mV=_E.callbackify(OV),RV=_E.promisify(cV.search),AV=_E.promisify(EV.getTableSchema);pp.exports={convertDelete:mV};function pV(e){return`${e.deleted_hashes.length} ${fV}${e.deleted_hashes.length===1?"":"s"} ${TV}`}a(pV,"generateReturnMessage");async function OV({statement:e,hdb_user:t}){let r=await AV(e.table.databaseid,e.table.tableid);cE.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=cE.isEmpty(n)?"":` WHERE ${n.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=oV.parse(o).statements[0],_={operation:lV.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{let u=await dV.writeTransaction(r.schema,r.name,async()=>(_.records=await RV(c),uV.deleteRecords(_)));return await SV.flush({schema:r.schema,table:r.name}),u.deleted_hashes.length>0&&await hV.postOperationHandler(_,u),cE.isEmptyOrZeroLength(u.message)&&(u.message=pV(u)),delete u.txn_time,u}catch(u){throw _V.error(u),u.hdb_code?u.message:u}}a(OV,"convertDelete")});var Ip=h((F3,gp)=>{"use strict";var lE=ms(),{hdb_errors:uE}=D();gp.exports={checkSchemaExists:Np,checkSchemaTableExists:NV,schema_describe:lE};async function Np(e){if(!global.hdb_schema[e])try{let t=await lE.describeSchema({schema:e});global.hdb_schema[e]=t}catch{return uE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}}a(Np,"checkSchemaExists");async function NV(e,t){let r=await Np(e);if(r)return r;if(!global.hdb_schema[e][t])try{let s=await lE.describeTable({schema:e,table:t});if(!s||Object.keys(s).length===0)return uE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t);global.hdb_schema[e][t]=s}catch{return uE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}}a(NV,"checkSchemaTableExists")});var Ec=h((k3,Lp)=>{"use strict";var Nn=Wa(),Is=Ip(),bp=g(),gV=require("uuid").v4,V3=require("clone"),In=js(),bs=T(),IV=require("util"),Cs=Nr(),{handleHDBError:Be,hdb_errors:bV}=D(),{HDB_ERROR_MSGS:gn,HTTP_STATUS_CODES:ve}=bV,{SchemaEventMsg:bn}=Vr(),Cp=At();Lp.exports={createSchema:CV,createSchemaStructure:wp,createTable:wV,createTableStructure:Up,createAttribute:MV,dropSchema:UV,dropTable:LV,dropAttribute:yV};async function CV(e){try{let t=await wp(e);return In.signalSchemaChange(new bn(process.pid,e.operation,e.schema)),t}catch(t){throw t}}a(CV,"createSchema");async function wp(e){let t=Nn.schema_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);if(!await Is.checkSchemaExists(e.schema))throw Be(new Error,gn.SCHEMA_EXISTS_ERR(e.schema),ve.BAD_REQUEST,bs.LOG_LEVELS.ERROR,gn.SCHEMA_EXISTS_ERR(e.schema),!0);try{return await Cs.createSchema(e),`schema '${e.schema}' successfully created`}catch(r){throw r}}a(wp,"createSchemaStructure");async function wV(e){try{let t=await Up(e);return In.signalSchemaChange(new bn(process.pid,e.operation,e.schema,e.table)),t}catch(t){throw t}}a(wV,"createTable");async function Up(e){let t=Nn.create_table_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);Nn.validateTableResidence(e.residence);let r=await Is.checkSchemaExists(e.schema);if(r)throw Be(new Error,r,ve.NOT_FOUND,bs.LOG_LEVELS.ERROR,r,!0);if(!await Is.checkSchemaTableExists(e.schema,e.table))throw Be(new Error,gn.TABLE_EXISTS_ERR(e.schema,e.table),ve.BAD_REQUEST,bs.LOG_LEVELS.ERROR,gn.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:gV(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await Cs.createTable(n,e);else throw Be(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",ve.BAD_REQUEST);else await Cs.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(i){throw i}}a(Up,"createTableStructure");async function UV(e){let t=Nn.schema_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);let r=await Is.checkSchemaExists(e.schema);if(r)throw Be(new Error,r,ve.NOT_FOUND,bs.LOG_LEVELS.ERROR,r,!0);let s=await Is.schema_describe.describeSchema({schema:e.schema});global.hdb_schema[e.schema]=s;let n=Object.keys(global.hdb_schema[e.schema]);return await Cs.dropSchema(e),In.signalSchemaChange(new bn(process.pid,e.operation,e.schema)),delete global.hdb_schema[e.schema],await Cp.purgeSchemaTableStreams(e.schema,n),`successfully deleted schema '${e.schema}'`}a(UV,"dropSchema");async function LV(e){let t=Nn.table_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);let r=await Is.checkSchemaTableExists(e.schema,e.table);if(r)throw Be(new Error,r,ve.NOT_FOUND,bs.LOG_LEVELS.ERROR,r,!0);return await Cs.dropTable(e),In.signalSchemaChange(new bn(process.pid,e.operation,e.schema,e.table)),await Cp.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(LV,"dropTable");async function yV(e){let t=Nn.attribute_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);let r=await Is.checkSchemaTableExists(e.schema,e.table);if(r)throw Be(new Error,r,ve.NOT_FOUND,bs.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw Be(new Error,"You cannot drop a hash attribute",ve.BAD_REQUEST,void 0,void 0,!0);if(bs.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw Be(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,ve.BAD_REQUEST,void 0,void 0,!0);try{return await Cs.dropAttribute(e),DV(e),In.signalSchemaChange(new bn(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw bp.error(`Got an error deleting attribute ${IV.inspect(e)}.`),s}}a(yV,"dropAttribute");function DV(e){let t=Object.values(global.hdb_schema[e.schema][e.table].attributes);for(let r=0;r<t.length;r++)t[r].attribute===e.attribute&&global.hdb_schema[e.schema][e.table].attributes.splice(r,1)}a(DV,"dropAttributeFromGlobal");async function MV(e){if(!global.hdb_schema[e.schema])throw Be(new Error,gn.SCHEMA_NOT_FOUND(e.schema),ve.NOT_FOUND,void 0,void 0,!0);if(!global.hdb_schema[e.schema][e.table])throw Be(new Error,gn.TABLE_NOT_FOUND(e.schema,e.table),ve.NOT_FOUND,void 0,void 0,!0);try{return await Cs.createAttribute(e),In.signalSchemaChange(new bn(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}catch(t){throw bp.error(t),t}}a(MV,"createAttribute")});var Dp=h((x3,yp)=>{"use strict";var{OPERATIONS_ENUM:PV}=T(),dc=class{constructor(t,r,s=void 0,n=void 0){this.operation=PV.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=s,this.search_values=n}};a(dc,"ReadAuditLogObject");yp.exports=dc});var EE=h((Y3,Hp)=>{"use strict";var BV=Nr(),$3=Dp(),hc=b(),Sc=T(),vV=V(),{handleHDBError:Mp,hdb_errors:HV}=D(),{HDB_ERROR_MSGS:Pp,HTTP_STATUS_CODES:Bp}=HV,qV=Object.values(Sc.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),vp="To use this operation audit log must be enabled in harperdb-config.yaml";Hp.exports=GV;async function GV(e){if(hc.isEmpty(e.schema))throw new Error(Pp.SCHEMA_REQUIRED_ERR);if(hc.isEmpty(e.table))throw new Error(Pp.TABLE_REQUIRED_ERR);if(!vV.get(Sc.CONFIG_PARAMS.LOGGING_AUDITLOG))throw Mp(new Error,vp,Bp.BAD_REQUEST,Sc.LOG_LEVELS.ERROR,vp,!0);let t=hc.checkSchemaTableExist(e.schema,e.table);if(t)throw Mp(new Error,t,Bp.NOT_FOUND,Sc.LOG_LEVELS.ERROR,t,!0);if(!hc.isEmpty(e.search_type)&&qV.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await BV.readAuditLog(e)}a(GV,"readAuditLog")});var xp=h((K3,kp)=>{var zr=require("validate.js"),Gp=de(),Cn=T(),{handleHDBError:FV,hdb_errors:VV}=D(),{HDB_ERROR_MSGS:le,HTTP_STATUS_CODES:kV}=VV,dE=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),xV={STRUCTURE_USER:"structure_user"},qp=Object.values(Cn.ROLE_TYPES_ENUM),$V="attribute_permissions",YV="attribute_name",{PERMS_CRUD_ENUM:wn}=Cn,KV=[$V,...Object.values(wn)],Fp=[wn.READ,wn.INSERT,wn.UPDATE],QV=[YV,...Fp];function WV(e){let t=dE();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,Vp(e,t)}a(WV,"addRoleValidation");function JV(e){let t=dE();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,Vp(e,t)}a(JV,"alterRoleValidation");function ZV(e){let t=dE();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,Gp.validateObject(e,t)}a(ZV,"dropRoleValidation");var XV=["operation","role","id","permission","hdb_user","hdb_auth_header"];function Vp(e,t){let r={main_permissions:[],schema_permissions:{}},s=Object.keys(e),n=[];for(let o=0,c=s.length;o<c;o++)XV.includes(s[o])||n.push(s[o]);n.length>0&&Te(le.INVALID_ROLE_JSON_KEYS(n),r);let i=Gp.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{Te(o,r)}),e.permission){let o=zV(e);o&&Te(o,r),qp.forEach(c=>{e.permission[c]&&!zr.isBoolean(e.permission[c])&&Te(le.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(qp.indexOf(o)<0){if(o===xV.STRUCTURE_USER){let _=e.permission[o];if(typeof _=="boolean")continue;if(Array.isArray(_)){for(let u=0,l=_.length;u<l;u++){let E=_[u];global.hdb_schema[E]||Te(le.SCHEMA_NOT_FOUND(E),r)}continue}Te(le.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){Te(le.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let _ in c.tables){let u=c.tables[_];if(!_||!global.hdb_schema[o][_]){Te(le.TABLE_NOT_FOUND(o,_),r);continue}if(Object.keys(u).forEach(l=>{KV.includes(l)||Te(le.INVALID_PERM_KEY(l),r,o,_)}),Object.values(wn).forEach(l=>{zr.isDefined(u[l])?zr.isBoolean(u[l])||Te(le.TABLE_PERM_NOT_BOOLEAN(l),r,o,_):Te(le.TABLE_PERM_MISSING(l),r,o,_)}),zr.isDefined(u.attribute_permissions)){if(!zr.isArray(u.attribute_permissions)){Te(le.ATTR_PERMS_NOT_ARRAY,r,o,_);continue}}else{Te(le.ATTR_PERMS_ARRAY_MISSING,r,o,_);continue}if(u.attribute_permissions){let l=global.hdb_schema[o][_].attributes.map(({attribute:d})=>d),E={read:!1,insert:!1,update:!1};for(let d in u.attribute_permissions){let S=u.attribute_permissions[d];if(Object.keys(S).forEach(R=>{!QV.includes(R)&&R!==wn.DELETE&&Te(le.INVALID_ATTR_PERM_KEY(R),r,o,_)}),!zr.isDefined(S.attribute_name)){Te(le.ATTR_PERM_MISSING_NAME,r,o,_);continue}let m=S.attribute_name;if(!l.includes(m)){Te(le.INVALID_ATTRIBUTE_IN_PERMS(m),r,o,_);continue}Fp.forEach(R=>{zr.isDefined(S[R])?zr.isBoolean(S[R])||Te(le.ATTR_PERM_NOT_BOOLEAN(R,m),r,o,_):Te(le.ATTR_PERM_MISSING(R,m),r,o,_)}),!E.read&&S.read===!0&&(E.read=!0),!E.insert&&S.insert===!0&&(E.insert=!0),!E.update&&S.update===!0&&(E.update=!0)}if(u.read===!1&&E.read===!0||u.insert===!1&&E.insert===!0||u.update===!1&&E.update===!0){let d=`${o}.${_}`;Te(le.MISMATCHED_TABLE_ATTR_PERMS(d),r,o,_)}}}}return jV(r)}a(Vp,"customValidate");kp.exports={addRoleValidation:WV,alterRoleValidation:JV,dropRoleValidation:ZV};function zV(e){let{operation:t,permission:r}=e;if(t===Cn.OPERATIONS_ENUM.ADD_ROLE||t===Cn.OPERATIONS_ENUM.ALTER_ROLE){let s=r.super_user===!0,n=r.cluster_user===!0;if(Object.keys(r).length>1&&(s||n)){if(n&&s)return le.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?Cn.ROLE_TYPES_ENUM.SUPER_USER:Cn.ROLE_TYPES_ENUM.CLUSTER_USER;return le.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(zV,"validateNoSUPerms");function jV(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let s={error:le.ROLE_PERMS_ERROR,...e};return FV(new Error,s,kV.BAD_REQUEST)}else return null}a(jV,"generateRolePermResponse");function Te(e,t,r,s){if(!r)t.main_permissions.push(e);else{let n=s?r+"_"+s:r;t.schema_permissions[n]?t.schema_permissions[n].push(e):t.schema_permissions[n]=[e]}}a(Te,"addPermError")});var pE=h((Q3,Jp)=>{"use strict";var $p=yt(),Yp=mt(),ek=ps(),fE=xp(),TE=js(),tk=require("uuid").v4,mE=require("util"),rk=pi(),Cr=T(),Kp=b(),RE=mE.promisify(Yp.searchByValue),sk=mE.promisify(Yp.searchByHash),nk=mE.promisify(ek.delete),ik=Qt(),ak=Ss(),{hdb_errors:ok,handleHDBError:Pi}=D(),{HDB_ERROR_MSGS:Qp,HTTP_STATUS_CODES:hE}=ok,{UserEventMsg:AE}=Vr();Jp.exports={addRole:ck,alterRole:uk,dropRole:lk,listRoles:Wp};function SE(e){try{e.hdb_auth_header&&delete e.hdb_auth_header,e.HDB_INTERNAL_PATH&&delete e.HDB_INTERNAL_PATH,e.operation&&delete e.operation,e.hdb_user&&delete e.hdb_user}catch{}return e}a(SE,"scrubRoleDetails");async function ck(e){let t=fE.addRoleValidation(e);if(t)throw t;if(!(await rk.getLicense()).enterprise){let o=await Wp();if(_k(e,o))throw new Error(`Your current license only supports ${Cr.BASIC_LICENSE_MAX_CLUSTER_USER_ROLES} cluster_user role. ${Cr.SUPPORT_HELP_MSG}`);if(o.length>=2)throw new Error(`Your current license only supports ${Cr.BASIC_LICENSE_MAX_NON_CU_ROLES+Cr.BASIC_LICENSE_MAX_CLUSTER_USER_ROLES} roles. ${Cr.SUPPORT_HELP_MSG}`)}e=SE(e);let s={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=await RE(s)}catch(o){throw Pi(o)}if(n&&n.length>0)throw Pi(new Error,Qp.ROLE_ALREADY_EXISTS(e.role),hE.CONFLICT,void 0,void 0,!0);e.id||(e.id=tk());let i={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await $p.insert(i),TE.signalUserChange(new AE(process.pid)),e=SE(e),e}a(ck,"addRole");function _k(e,t){let r=!1;if(e.permission.cluster_user===!0)for(let s=0;s<t.length;s++){let i=t[s].permission;if(!Kp.isEmpty(i)&&i.cluster_user===!0)return!0}return r}a(_k,"checkClusterUserRole");async function uk(e){let t=fE.alterRoleValidation(e);if(t)throw t;e=SE(e);let r={operation:"update",schema:"system",table:"hdb_role",hash_attribute:"rolename",records:[e]};try{await $p.update(r)}catch(s){throw Pi(s)}return TE.signalUserChange(new AE(process.pid)),e}a(uk,"alterRole");async function lk(e){let t=fE.dropRoleValidation(e);if(t)throw Pi(new Error,t,hE.BAD_REQUEST,void 0,void 0,!0);let r=new ak(Cr.SYSTEM_SCHEMA_NAME,Cr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=await sk(r);if(s.length===0)throw Pi(new Error,Qp.ROLE_NOT_FOUND,hE.NOT_FOUND,void 0,void 0,!0);let n=new ik(Cr.SYSTEM_SCHEMA_NAME,Cr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=await RE(n),o=!1;if(Kp.isEmptyOrZeroLength(i)===!1){for(let _=0;_<i.length;_++)if(i[_].active===!0){o=!0;break}}if(o===!0)throw new Error(`Cannot drop role ${s[0].role} as it has active user(s) tied to this role`);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await nk(c),TE.signalUserChange(new AE(process.pid)),`${s[0].role} successfully deleted`}a(lk,"dropRole");async function Wp(){return RE({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(Wp,"listRoles")});var jp=h((W3,zp)=>{"use strict";var Ek=V(),jr=require("joi"),dk=de(),Zp=require("moment"),hk=require("fs-extra"),OE=require("path"),Sk=require("lodash"),Bi=T(),{LOG_LEVELS:ws}=T(),fk="YYYY-MM-DD hh:mm:ss",Tk=OE.resolve(__dirname,"../logs");zp.exports=function(e){return dk.validateBySchema(e,mk)};var mk=jr.object({from:jr.custom(Xp),until:jr.custom(Xp),level:jr.valid(ws.NOTIFY,ws.FATAL,ws.ERROR,ws.WARN,ws.INFO,ws.DEBUG,ws.TRACE),order:jr.valid("asc","desc"),limit:jr.number().min(1),start:jr.number().min(0),log_name:jr.custom(Rk)});function Xp(e,t){if(Zp(e,Zp.ISO_8601).format(fk)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(Xp,"validateDatetime");function Rk(e,t){if(Sk.invert(Bi.PROCESS_LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=Ek.get(Bi.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e===void 0?Bi.PROCESS_LOG_NAMES.HDB:e,i=n===Bi.PROCESS_LOG_NAMES.INSTALL?OE.join(Tk,Bi.PROCESS_LOG_NAMES.INSTALL):OE.join(s,n);return hk.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(Rk,"validateReadLogPath")});var gE=h((J3,tO)=>{"use strict";var fc=T(),eO=g(),Ak=V(),pk=jp(),NE=require("path"),Ok=require("fs-extra"),Nk=require("readline"),{once:gk}=require("events"),{handleHDBError:Ik,hdb_errors:bk}=D(),{PACKAGE_ROOT:Ck}=T(),wk=NE.join(Ck,"logs"),Uk=1e3;tO.exports=Lk;async function Lk(e){let t=pk(e);if(t)throw Ik(t,t.message,bk.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=Ak.get(fc.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?fc.PROCESS_LOG_NAMES.HDB:e.log_name,n=s===fc.PROCESS_LOG_NAMES.INSTALL?NE.join(wk,fc.PROCESS_LOG_NAMES.INSTALL):NE.join(r,s),i=Ok.createReadStream(n);i.on("error",j=>{eO.error(j)});let o=Nk.createInterface({input:i,crlfDelay:1/0}),c=e.level!==void 0,_=c?e.level:void 0,u=e.from!==void 0,l=u?new Date(e.from):void 0,E=e.until!==void 0,d=E?new Date(e.until):void 0,S=e.limit===void 0?Uk:e.limit,m=e.order===void 0?void 0:e.order,R=e.start===void 0?0:e.start,w=R+S,U=0,B=[];return o.on("line",j=>{let k,J,xe,$e;try{k=JSON.parse(j)}catch(Ea){eO.warn(Ea.message);return}switch(!0){case(c&&u&&E):J=new Date(k.timestamp),xe=new Date(l),$e=new Date(d),k.level===_&&J>=xe&&J<=$e&&U<R?U++:k.level===_&&J>=xe&&J<=$e&&(ts(k,m,B),U++,U===w&&es(o));break;case(c&&u):J=new Date(k.timestamp),xe=new Date(l),k.level===_&&J>=xe&&U<R?U++:k.level===_&&J>=xe&&(ts(k,m,B),U++,U===w&&es(o));break;case(c&&E):J=new Date(k.timestamp),$e=new Date(d),k.level===_&&J<=$e&&U<R?U++:k.level===_&&J<=$e&&(ts(k,m,B),U++,U===w&&es(o));break;case(u&&E):J=new Date(k.timestamp),xe=new Date(l),$e=new Date(d),J>=xe&&J<=$e&&U<R?U++:J>=xe&&J<=$e&&(ts(k,m,B),U++,U===w&&es(o));break;case c:k.level===_&&U<R?U++:k.level===_&&(ts(k,m,B),U++,U===w&&es(o));break;case u:J=new Date(k.timestamp),xe=new Date(l),J>=xe&&U<R?U++:J>=xe&&U>=R&&(ts(k,m,B),U++,U===w&&es(o));break;case E:J=new Date(k.timestamp),$e=new Date(d),J<=$e&&U<R?U++:J<=$e&&U>=R&&(ts(k,m,B),U++,U===w&&es(o));break;default:U<R?U++:(ts(k,m,B),U++,U===w&&es(o))}}),await gk(o,"close"),B}a(Lk,"readLog");function es(e){e.close(),e.removeAllListeners()}a(es,"endReadLine");function ts(e,t,r){t==="desc"?yk(e,r):t==="asc"?Dk(e,r):r.push(e)}a(ts,"pushLineToResult");function yk(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)>r?s=i+1:n=i}t.splice(s,0,e)}a(yk,"insertDescending");function Dk(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)<r?s=i+1:n=i}t.splice(s,0,e)}a(Dk,"insertAscending")});var mc=h((z3,nO)=>{"use strict";var IE=require("joi"),{string:Tc,boolean:rO,date:Mk}=IE.types(),Pk=de(),{validateSchemaExists:Z3,validateTableExists:X3,validateSchemaName:Bk}=Rr(),vk=T(),Hk=Se(),qk=V(),Gk=Tc.invalid(qk.get(vk.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(Hk.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null).required(),sO={operation:Tc.valid("add_node","update_node"),node_name:Gk,subscriptions:IE.array().items({table:Tc.required(),schema:Tc.custom(Bk).required(),subscribe:rO.required(),publish:rO.required().custom(Vk),start_time:Mk.iso()}).min(1).required()};function Fk(e){return Pk.validateBySchema(e,IE.object(sO))}a(Fk,"addUpdateNodeValidator");function Vk(e,t){if(t.state.ancestors[2].operation==="add_node"&&e===!1&&t.state.ancestors[0].subscribe===!1)return t.message(`'subscriptions[${t.state.path[1]}]' subscribe and/or publish must be set to true when adding a node`)}a(Vk,"checkForFalsy");nO.exports={addUpdateNodeValidator:Fk,validation_schema:sO}});var Un=h((j3,iO)=>{"use strict";var Rc=class{constructor(t,r,s){this.name=t,this.subscriptions=r,this.system_info=s}};a(Rc,"Node");var Ac=class{constructor(t,r,s,n){this.schema=t,this.table=r,this.publish=s,this.subscribe=n}};a(Ac,"NodeSubscription");iO.exports={Node:Rc,NodeSubscription:Ac}});var oO=h((e2,aO)=>{"use strict";var kk=T().OPERATIONS_ENUM,pc=class{constructor(t,r,s,n=void 0){this.operation=kk.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};a(pc,"UpsertObject");aO.exports=pc});var vi=h((t2,cO)=>{"use strict";var Oc=class{constructor(t,r,s,n){this.operation=t,this.node_name=r,this.subscriptions=s,this.system_info=n}};a(Oc,"RemotePayloadObject");var Nc=class{constructor(t,r,s,n,i,o){this.schema=t,this.table=r,this.hash_attribute=s,this.publish=n,this.subscribe=i,this.start_time=o}};a(Nc,"RemotePayloadSubscription");cO.exports={RemotePayloadObject:Oc,RemotePayloadSubscription:Nc}});var uO=h((r2,_O)=>{"use strict";var gc=class{constructor(t,r,s=0,n=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=s,this.record_count=n,this.transaction_log_size=i,this.transaction_log_record_count=o}};a(gc,"TableSizeObject");_O.exports=gc});var hO=h((s2,dO)=>{"use strict";var xk=uO(),lO=require("path"),EO=re(),$k=Ke(),Ln=X(),Yk=g();dO.exports=Kk;async function Kk(e){let t=new xk;try{let r=lO.join(EO.getBaseSchemaPath(),e.schema.toString()),s=await Ln.openEnvironment(r,e.name),n=Ln.statDBI(s,e.hash_attribute),i=lO.join(EO.getTransactionAuditStorePath(),e.schema.toString()),o=await Ln.openEnvironment(i,e.name,!0),c=Ln.statDBI(o,$k.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP),_=await Ln.environmentDataSize(r,e.name),u=await Ln.environmentDataSize(i,e.name);t.schema=e.schema,t.table=e.name,t.table_size=_,t.record_count=n.entryCount,t.transaction_log_size=u,t.transaction_log_record_count=c.entryCount}catch(r){Yk.warn(`unable to stat table dbi due to ${r}`)}return t}a(Kk,"lmdbGetTableSize")});var fO=h((n2,SO)=>{"use strict";var Qk=T(),Ic=class{constructor(t){this.operator=Qk.OPERATIONS_ENUM.SYSTEM_INFORMATION,this.attributes=t}};a(Ic,"SystemInformationOperation");SO.exports=Ic});var mO=h((i2,TO)=>{"use strict";var bc=class{constructor(t,r,s,n,i,o,c){this.system=t,this.time=r,this.cpu=s,this.memory=n,this.disk=i,this.network=o,this.harperdb_processes=c}};a(bc,"SystemInformationObject");TO.exports=bc});var wc=h((o2,RO)=>{"use strict";var He=require("systeminformation"),yn=g(),Wk=T(),Jk=hO(),Zk=ms(),Xk=V();Xk.initSync();var a2=fO(),zk=mO(),Cc;RO.exports={getHDBProcessInfo:UE,getNetworkInfo:yE,getDiskInfo:LE,getMemoryInfo:wE,getCPUInfo:CE,getTimeInfo:bE,getSystemInformation:DE,systemInformation:jk,getTableSize:ME};function bE(){return He.time()}a(bE,"getTimeInfo");async function CE(){try{let{family:e,model:t,stepping:r,revision:s,voltage:n,speedmin:i,speedmax:o,governor:c,socket:_,cache:u,...l}=await He.cpu();l.cpu_speed=await He.cpuCurrentSpeed();let{raw_currentload:E,raw_currentload_idle:d,raw_currentload_irq:S,raw_currentload_nice:m,raw_currentload_system:R,raw_currentload_user:w,cpus:U,...B}=await He.currentLoad();return B.cpus=[],U.forEach(j=>{let{raw_load:k,raw_load_idle:J,raw_load_irq:xe,raw_load_nice:$e,raw_load_system:Ea,raw_load_user:da,...Pr}=j;B.cpus.push(Pr)}),l.current_load=B,l}catch(e){return yn.error(`error in getCPUInfo: ${e}`),{}}}a(CE,"getCPUInfo");async function wE(){try{let{buffers:e,cached:t,slab:r,buffcache:s,...n}=await He.mem();return n}catch(e){return yn.error(`error in getMemoryInfo: ${e}`),{}}}a(wE,"getMemoryInfo");async function UE(){let e={core:[],clustering:[]};try{return(await He.processes()).list.forEach(r=>{r.params.includes(Wk.HDB_PROC_NAME)?e.core.push(r):r.params.includes("socketcluster")&&e.clustering.push(r)}),e}catch(t){return yn.error(`error in getHDBProcessInfo: ${t}`),e}}a(UE,"getHDBProcessInfo");async function LE(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:s,ms:n,...i}=await He.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:_,...u}=await He.fsStats();return e.read_write=u,e.size=await He.fsSize(),e}catch(t){return yn.error(`error in getDiskInfo: ${t}`),e}}a(LE,"getDiskInfo");async function yE(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await He.networkInterfaceDefault(),e.latency=await He.inetChecksite("google.com"),(await He.networkInterfaces()).forEach(s=>{let{internal:n,virtual:i,mtu:o,dhcp:c,dnsSuffix:_,ieee8021xAuth:u,ieee8021xState:l,carrier_changes:E,...d}=s;e.interfaces.push(d)}),(await He.networkStats()).forEach(s=>{let{rx_sec:n,tx_sec:i,ms:o,...c}=s;e.stats.push(c)}),e.connections=await He.networkConnections(),e}catch(t){return yn.error(`error in getNetworkInfo: ${t}`),e}}a(yE,"getNetworkInfo");async function DE(){if(Cc!==void 0)return Cc;let e={};try{let{codepage:t,logofile:r,serial:s,build:n,servicepack:i,uefi:o,...c}=await He.osInfo();e=c;let _=await He.versions("node, npm");return e.node_version=_.node,e.npm_version=_.npm,Cc=e,Cc}catch(t){return yn.error(`error in getSystemInformation: ${t}`),e}}a(DE,"getSystemInformation");async function ME(){let e=[],t=await Zk.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await Jk(s));return e}a(ME,"getTableSize");async function jk(e){let t=new zk;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await DE(),t.time=bE(),t.cpu=await CE(),t.memory=await wE(),t.disk=await LE(),t.network=await yE(),t.harperdb_processes=await UE(),t.table_size=await ME(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await DE();break;case"time":t.time=bE();break;case"cpu":t.cpu=await CE();break;case"memory":t.memory=await wE();break;case"disk":t.disk=await LE();break;case"network":t.network=await yE();break;case"harperdb_processes":t.harperdb_processes=await UE();break;case"table_size":t.table_size=await ME();break;default:break}return t}a(jk,"systemInformation")});var PE=h((u2,AO)=>{"use strict";var c2=require("fs-extra"),_2=g();AO.exports={version:ex,printVersion:rx,nodeVersion:tx};var rs=Ql();function ex(){if(rs)return rs.version}a(ex,"version");function tx(){if(rs&&rs.engines&&rs.engines["preferred-node"])return rs.engines["preferred-node"]}a(tx,"nodeVersion");function rx(){rs&&console.log(`HarperDB Version ${rs.version}`)}a(rx,"printVersion")});var Ls=h((d2,gO)=>{"use strict";var sx=yt(),BE=b(),vE=require("util"),Us=T(),pO=V();pO.initSync();var nx=Kl(),OO=mt(),{Node:l2,NodeSubscription:E2}=Un(),ix=Ss(),ax=oO(),{RemotePayloadObject:ox,RemotePayloadSubscription:cx}=vi(),{handleHDBError:_x,hdb_errors:ux}=D(),{HTTP_STATUS_CODES:lx,HDB_ERROR_MSGS:Ex}=ux,dx=Qt(),hx=wc(),Sx=PE(),fx=vE.promisify(nx.authorize),Tx=vE.promisify(OO.searchByHash),mx=vE.promisify(OO.searchByValue);gO.exports={authHeaderToUser:Rx,isEmpty:Ax,getNodeRecord:px,upsertNodeRecord:Ox,buildNodePayloads:Nx,checkClusteringEnabled:gx,getAllNodeRecords:Ix,getSystemInfo:bx,reverseSubscription:NO};async function Rx(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await fx(t,null),e}a(Rx,"authHeaderToUser");function Ax(e){return e==null}a(Ax,"isEmpty");async function px(e){let t=new ix(Us.SYSTEM_SCHEMA_NAME,Us.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return Tx(t)}a(px,"getNodeRecord");async function Ox(e){let t=new ax(Us.SYSTEM_SCHEMA_NAME,Us.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return sx.upsert(t)}a(Ox,"upsertNodeRecord");function NO(e){if(BE.isEmpty(e.subscribe)||BE.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:s}=e,n={schema:t,table:r,hash_attribute:s};return e.subscribe===!0&&e.publish===!1?(n.subscribe=!1,n.publish=!0):e.subscribe===!1&&e.publish===!0?(n.subscribe=!0,n.publish=!1):(n.subscribe=e.subscribe,n.publish=e.publish),n}a(NO,"reverseSubscription");function Nx(e,t,r,s){let n=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:_,table:u}=c,l=BE.getTableHashAttribute(_,u),{subscribe:E,publish:d}=NO(c),S=new cx(_,u,l,d,E,c.start_time);n.push(S)}return new ox(r,t,n,s)}a(Nx,"buildNodePayloads");function gx(){if(!pO.get(Us.CONFIG_PARAMS.CLUSTERING_ENABLED))throw _x(new Error,Ex.CLUSTERING_NOT_ENABLED,lx.BAD_REQUEST,void 0,void 0,!0)}a(gx,"checkClusteringEnabled");async function Ix(){let e=new dx(Us.SYSTEM_SCHEMA_NAME,Us.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return mx(e)}a(Ix,"getAllNodeRecords");async function bx(){let e=await hx.getSystemInformation();return{hdb_version:Sx.version(),node_version:e.node_version,platform:e.platform}}a(bx,"getSystemInfo")});var qE=h((h2,LO)=>{"use strict";var HE=At(),IO=b(),bO=Se(),Cx=T(),Uc=g(),CO=Ec(),wx=sl(),{RemotePayloadObject:Ux}=vi(),{handleHDBError:wO,hdb_errors:Lx}=D(),{HTTP_STATUS_CODES:UO}=Lx,{NodeSubscription:yx}=Un();LO.exports=Dx;async function Dx(e,t){let r;try{r=await HE.request(`${t}.${bO.REQUEST_SUFFIX}`,new Ux(Cx.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Uc.trace("Response from remote describe all request:",r)}catch(o){Uc.error(`addNode received error from describe all request to remote node: ${o}`);let c=HE.requestErrorHandler(o,"add_node",t);throw wO(new Error,c,UO.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===bO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw wO(new Error,o,UO.INTERNAL_SERVER_ERROR,"error",o)}let s=r.message,n=[],i=[];for(let o of e){let{schema:c,table:_}=o,u=IO.doesSchemaExist(c),l=s[c]!==void 0,E=IO.doesTableExist(c,_),d=s?.[c]?.[_]!==void 0;if(!u&&!l||!E&&!d){n.push(o);continue}if(!u&&l&&(Uc.trace(`addNode creating schema: ${c}`),await CO.createSchema({operation:"create_schema",schema:c})),!E&&d){Uc.trace(`addNode creating table: ${_} in schema: ${c}`);let m=new wx(c,_,s[c][_].hash_attribute);await CO.createTable(m)}await HE.createLocalTableStream(c,_);let S=new yx(c,_,o.publish,o.subscribe);S.start_time=o.start_time,i.push(S)}return{added:i,skipped:n}}a(Dx,"reviewSubscriptions")});var Dc=h((S2,MO)=>{"use strict";var{handleHDBError:Lc,hdb_errors:Mx}=D(),{HTTP_STATUS_CODES:yc}=Mx,{addUpdateNodeValidator:Px}=mc(),Hi=g(),DO=T(),yO=Se(),Bx=b(),GE=At(),qi=Ls(),vx=V(),Hx=qE(),{Node:qx,NodeSubscription:Gx}=Un(),Fx="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",Vx="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",kx=vx.get(DO.CONFIG_PARAMS.CLUSTERING_NODENAME);MO.exports=xx;async function xx(e,t=!1){Hi.trace("addNode called with:",e),qi.checkClusteringEnabled();let r=Px(e);if(r)throw Lc(r,r.message,yc.BAD_REQUEST,void 0,void 0,!0);let s=e.node_name;if(!t){let E=await qi.getNodeRecord(s);if(!Bx.isEmptyOrZeroLength(E))throw Lc(new Error,`Node '${s}' has already been added, perform update_node to proceed.`,yc.BAD_REQUEST,void 0,void 0,!0)}let{added:n,skipped:i}=await Hx(e.subscriptions,s),o={message:void 0,added:n,skipped:i};if(n.length===0)return o.message=Fx,o;let c=qi.buildNodePayloads(n,kx,DO.OPERATIONS_ENUM.ADD_NODE,await qi.getSystemInfo());Hi.trace("addNode sending remote payload:",c);let _;try{_=await GE.request(`${s}.${yO.REQUEST_SUFFIX}`,c)}catch(E){Hi.error(`addNode received error from request: ${E}`);let d=GE.requestErrorHandler(E,"add_node",s);throw Lc(new Error,d,yc.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===yO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let E=`Error returned from remote node ${s}: ${_.message}`;throw Lc(new Error,E,yc.INTERNAL_SERVER_ERROR,"error",E)}Hi.trace(_);let u=[];for(let E=0,d=n.length;E<d;E++){let S=n[E];Hi.trace("Add node updating work stream for node:",s,"subscriptions:",S),await GE.updateWorkStream(S,s),n[E].start_time===void 0&&delete n[E].start_time,u.push(new Gx(S.schema,S.table,S.publish,S.subscribe))}let l=new qx(s,u,_.system_info);return await qi.upsertNodeRecord(l),i.length>0?o.message=Vx:o.message=`Successfully added '${s}' to manifest`,o}a(xx,"addNode")});var VE=h((f2,vO)=>{"use strict";var{handleHDBError:Mc,hdb_errors:$x}=D(),{HTTP_STATUS_CODES:Pc}=$x,{addUpdateNodeValidator:Yx}=mc(),Gi=g(),BO=T(),PO=Se(),Kx=b(),FE=At(),Fi=Ls(),Qx=V(),{cloneDeep:Wx}=require("lodash"),Jx=qE(),{NodeSubscription:Zx}=Un(),Xx="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",zx="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",jx=Qx.get(BO.CONFIG_PARAMS.CLUSTERING_NODENAME);vO.exports=e$;async function e$(e){Gi.trace("updateNode called with:",e),Fi.checkClusteringEnabled();let t=Yx(e);if(t)throw Mc(t,t.message,Pc.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=Wx(await Fi.getNodeRecord(r));if(Kx.isEmptyOrZeroLength(s))throw Mc(new Error,`Node '${r}' has not been added, perform add_node to proceed.`,Pc.BAD_REQUEST,void 0,void 0,!0);let{added:n,skipped:i}=await Jx(e.subscriptions,r),o={message:void 0,updated:n,skipped:i};if(n.length===0)return o.message=Xx,o;let c=Fi.buildNodePayloads(n,jx,BO.OPERATIONS_ENUM.UPDATE_NODE,await Fi.getSystemInfo());Gi.trace("updateNode sending remote payload:",c);let _;try{_=await FE.request(`${r}.${PO.REQUEST_SUFFIX}`,c)}catch(u){Gi.error(`updateNode received error from request: ${u}`);let l=FE.requestErrorHandler(u,"update_node",r);throw Mc(new Error,l,Pc.INTERNAL_SERVER_ERROR,"error",l)}if(_.status===PO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let u=`Error returned from remote node ${r}: ${_.message}`;throw Mc(new Error,u,Pc.INTERNAL_SERVER_ERROR,"error",u)}Gi.trace(_);for(let u=0,l=n.length;u<l;u++){let E=n[u];Gi.trace(`updateNode updating work stream for node: ${r} subscription:`,E),await FE.updateWorkStream(E,r),n[u].start_time===void 0&&delete n[u].start_time}return await t$(s[0],n,_.system_info),i.length>0?o.message=zx:o.message=`Successfully updated '${r}'`,o}a(e$,"updateNode");async function t$(e,t,r){let s=e;for(let n=0,i=t.length;n<i;n++){let o=t[n],c=!1;for(let _=0,u=e.subscriptions.length;_<u;_++){let l=s.subscriptions[_];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||s.subscriptions.push(new Zx(o.schema,o.table,o.publish,o.subscribe))}s.system_info=r,await Fi.upsertNodeRecord(s)}a(t$,"updateNodeTable")});var VO=h((T2,FO)=>{"use strict";var GO=require("joi"),{string:HO}=GO.types(),r$=de(),qO=T(),s$=V(),n$=Se();FO.exports=i$;function i$(e){let t=HO.invalid(s$.get(qO.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(n$.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null),r=GO.object({operation:HO.valid(qO.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return r$.validateBySchema(e,r)}a(i$,"removeNodeValidator")});var vc=h((m2,QO)=>{"use strict";var{handleHDBError:kO,hdb_errors:a$}=D(),{HTTP_STATUS_CODES:xO}=a$,o$=VO(),Vi=g(),$O=Ls(),c$=b(),Bc=T(),YO=Se(),KO=At(),_$=V(),{RemotePayloadObject:u$}=vi(),{NodeSubscription:l$}=Un(),E$=Ei(),d$=ps(),h$=_$.get(Bc.CONFIG_PARAMS.CLUSTERING_NODENAME);QO.exports=S$;async function S$(e){Vi.trace("removeNode called with:",e),$O.checkClusteringEnabled();let t=o$(e);if(t)throw kO(t,t.message,xO.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=await $O.getNodeRecord(r);if(c$.isEmptyOrZeroLength(s))throw kO(new Error,`Node '${r}' was not found.`,xO.BAD_REQUEST,void 0,void 0,!0);s=s[0];let n=new u$(Bc.OPERATIONS_ENUM.REMOVE_NODE,h$,[]),i,o=!1;try{i=await KO.request(`${r}.${YO.REQUEST_SUFFIX}`,n),Vi.trace("Remove node reply from remote node:",r,i)}catch(_){Vi.error("removeNode received error from request:",_),o=!0}for(let _=0,u=s.subscriptions.length;_<u;_++){let l=s.subscriptions[_];Vi.trace(`Remove node removing subscription: ${l.schema}.${l.table} for node: ${r}`);let E=new l$(l.schema,l.table,!1,!1);await KO.updateWorkStream(E,r)}let c=new E$(Bc.SYSTEM_SCHEMA_NAME,Bc.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await d$.deleteRecord(c),i?.status===YO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Vi.error("Error returned from remote node:",r,i?.message),`Successfully removed '${r}' from local manifest, however there was an error reaching remote node. Check the logs for more details.`):`Successfully removed '${r}' from manifest`}a(S$,"removeNode")});var ZO=h((R2,JO)=>{"use strict";var WO=require("joi"),{string:f$,array:T$}=WO.types(),m$=de(),R$=mc();JO.exports=A$;function A$(e){let t=WO.object({operation:f$.valid("configure_cluster").required(),connections:T$.items(R$.validation_schema).required()});return m$.validateBySchema(e,t)}a(A$,"configureClusterValidator")});var kE=h((A2,tN)=>{"use strict";var p$=T(),Hc=g(),O$=b(),N$=vc(),g$=Dc(),XO=Ls(),I$=ZO(),{handleHDBError:zO,hdb_errors:b$}=D(),{HTTP_STATUS_CODES:jO}=b$,C$="Configure cluster complete.",w$="Failed to configure the cluster. Check the logs for more details.",U$="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";tN.exports=L$;async function L$(e){Hc.trace("configure cluster called with:",e),XO.checkClusteringEnabled();let t=I$(e);if(t)throw zO(t,t.message,jO.BAD_REQUEST,void 0,void 0,!0);let r=await XO.getAllNodeRecords(),s=[];for(let d=0,S=r.length;d<S;d++)s.push(eN(N$,{operation:p$.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[d].name},r[d].name));let n=await Promise.allSettled(s);Hc.trace("All results from configure_cluster remove node:",n);let i=[],o=e.connections.length;for(let d=0;d<o;d++){let S=e.connections[d];i.push(eN(g$,S,S.node_name))}let c=await Promise.allSettled(i);Hc.trace("All results from configure_cluster add node:",c);let _=[],u=[],l=!1,E=n.concat(c);for(let d=0,S=E.length;d<S;d++){let m=E[d];m.status==="rejected"&&(Hc.error(m.reason),_.includes(m.reason.node_name)||_.push(m.reason.node_name)),m.status==="fulfilled"&&(l=!0);let R=m?.value?.result;typeof R=="string"&&R.includes("Successfully removed")||m.status==="rejected"||u.push({node_name:m?.value?.node_name,subscriptions:m?.value?.result})}if(O$.isEmptyOrZeroLength(_))return{message:C$,connections:u};if(l)return{message:U$,failed_nodes:_,connections:u};throw zO(new Error,w$,jO.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(L$,"configureCluster");async function eN(e,t,r){try{return{node_name:r,result:await e(t)}}catch(s){throw{node_name:r,error:s}}}a(eN,"functionWrapper")});var YE=h((p2,oN)=>{"use strict";var $E=Ls(),y$=At(),nN=V(),qc=T(),ys=Se(),D$=b(),xE=g(),{RemotePayloadObject:M$}=vi(),{ErrorCode:rN}=require("nats"),sN=nN.get(qc.CONFIG_PARAMS.CLUSTERING_ENABLED),iN=nN.get(qc.CONFIG_PARAMS.CLUSTERING_NODENAME);oN.exports={clusterStatus:P$,buildNodeStatus:aN};async function P$(){let e={node_name:iN,is_enabled:sN,connections:[]};if(!sN)return e;let t=await $E.getAllNodeRecords();if(D$.isEmptyOrZeroLength(t))return e;let r=[];for(let s=0,n=t.length;s<n;s++)r.push(aN(t[s],e.connections));return await Promise.allSettled(r),e}a(P$,"clusterStatus");async function aN(e,t){let r=e.name,s=new M$(qc.OPERATIONS_ENUM.CLUSTER_STATUS,iN,void 0,await $E.getSystemInfo()),n,i,o=ys.CLUSTER_STATUS_STATUSES.OPEN;try{let _=Date.now();n=await y$.request(ys.REQUEST_SUBJECT(r),s),i=Date.now()-_,n.status===ys.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=ys.CLUSTER_STATUS_STATUSES.CLOSED,xE.error(`Error getting node status from ${r} `,n))}catch(_){xE.warn(`Error getting node status from ${r}`,_),_.code===rN.NoResponders?o=ys.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:_.code===rN.Timeout?o=ys.CLUSTER_STATUS_STATUSES.TIMEOUT:o=ys.CLUSTER_STATUS_STATUSES.CLOSED}let c=new B$(r,o,n?.message?.ports?.clustering,n?.message?.ports?.operations_api,i,n?.message?.uptime,e.subscriptions,n?.message?.system_info);try{let _={name:r,system_info:n?.message?.system_info};e.system_info?.hdb_version!==qc.PRE_4_0_0_VERSION&&await $E.upsertNodeRecord(_)}catch(_){xE.error("Cluster status encountered an error updating system info for node:",r,_)}t.push(c)}a(aN,"buildNodeStatus");function B$(e,t,r,s,n,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:s},this.latency_ms=n,this.uptime=i,this.subscriptions=o,this.system_info=c}a(B$,"NodeStatusObject")});var lN=h((O2,uN)=>{"use strict";var KE=require("joi"),cN=de(),{route_constraints:_N}=Eu();uN.exports={setRoutesValidator:v$,deleteRoutesValidator:H$};function v$(e){let t=KE.object({server:KE.valid("hub","leaf").required(),routes:_N.required()});return cN.validateBySchema(e,t)}a(v$,"setRoutesValidator");function H$(e){let t=KE.object({routes:_N.required()});return cN.validateBySchema(e,t)}a(H$,"deleteRoutesValidator")});var WE=h((N2,SN)=>{"use strict";var Ds=Tr(),QE=b(),Gc=T(),EN=lN(),{handleHDBError:dN,hdb_errors:q$}=D(),{HTTP_STATUS_CODES:hN}=q$,G$="cluster routes successfully set",F$="cluster routes successfully deleted";SN.exports={setRoutes:V$,getRoutes:k$,deleteRoutes:x$};function V$(e){let t=EN.setRoutesValidator(e);if(t)throw dN(t,t.message,hN.BAD_REQUEST,void 0,void 0,!0);let r=Ds.getClusteringRoutes(),s=e.server==="hub"?r.hub_routes:r.leaf_routes,n=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,_=e.routes.length;c<_;c++){let u=e.routes[c];u.port=QE.autoCast(u.port);let l=s.some(d=>d.host===u.host&&d.port===u.port),E=n.some(d=>d.host===u.host&&d.port===u.port);l||E?i.push(u):(s.push(u),o.push(u))}return e.server==="hub"?Ds.updateConfigValue(Gc.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s):Ds.updateConfigValue(Gc.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s),{message:G$,set:o,skipped:i}}a(V$,"setRoutes");function k$(){let e=Ds.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(k$,"getRoutes");function x$(e){let t=EN.deleteRoutesValidator(e);if(t)throw dN(t,t.message,hN.BAD_REQUEST,void 0,void 0,!0);let r=Ds.getClusteringRoutes(),s=r.hub_routes,n=r.leaf_routes,i=[],o=[],c=!1,_=!1;for(let u=0,l=e.routes.length;u<l;u++){let E=e.routes[u],d=!1;for(let S=0,m=s.length;S<m;S++){let R=s[S];if(E.host===R.host&&E.port===R.port){s.splice(S,1),d=!0,c=!0,i.push(E);break}}if(!d){let S=!0;for(let m=0,R=n.length;m<R;m++){let w=n[m];if(E.host===w.host&&E.port===w.port){n.splice(m,1),_=!0,S=!1,i.push(E);break}}S&&o.push(E)}}return c&&(s=QE.isEmptyOrZeroLength(s)?null:s,Ds.updateConfigValue(Gc.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),_&&(n=QE.isEmptyOrZeroLength(n)?null:n,Ds.updateConfigValue(Gc.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:F$,deleted:i,skipped:o}}a(x$,"deleteRoutes")});var TN=h((g2,fN)=>{"use strict";var ki=require("alasql"),Ms=require("recursive-iterator"),Jt=g(),$$=b(),xi=T(),Fc=class{constructor(t){this.ast=t,this.affected_attributes=new Map,this.table_lookup=new Map,this.schema_lookup=new Map,this.table_to_schema_lookup=new Map,K$(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(n=>xi.SEARCH_WILDCARDS.includes(n.columnid));if(r.length===0)return this.ast;let s=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(n=>!xi.SEARCH_WILDCARDS.includes(n.columnid)),r.forEach(n=>{let i=this.table_to_schema_lookup.has(n.tableid)?this.table_to_schema_lookup.get(n.tableid):s,o=this.table_lookup.has(n.tableid)?this.table_lookup.get(n.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][xi.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=Y$(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(u=>({attribute_name:u.attribute}));let _=this.affected_attributes.get(i).get(o).filter(u=>!xi.SEARCH_WILDCARDS.includes(u));c.forEach(({attribute_name:u})=>{let l=new ki.yy.Column({columnid:u});n.tableid&&(l.tableid=n.tableid),this.ast.columns.push(l),_.includes(u)||_.push(u)}),this.affected_attributes.get(i).set(o,_)}}),this.ast}};a(Fc,"sql_statement_bucket");function Y$(e){return e.filter(t=>t[xi.PERMS_CRUD_ENUM.READ])}a(Y$,"filterReadRestrictedAttrs");function K$(e,t,r,s,n){Q$(e,t,r,s,n)}a(K$,"interpretAST");function $i(e,t,r,s,n){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),s&&!s.has(e.as)&&s.set(e.as,e.databaseid)),n)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),n.set(o,i)}}a($i,"addSchemaTableToMap");function Q$(e,t,r,s,n){if(!e){Jt.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof ki.yy.Insert?X$(e,t,r):e instanceof ki.yy.Select?W$(e,t,r,s,n):e instanceof ki.yy.Update?J$(e,t,r):e instanceof ki.yy.Delete?Z$(e,t,r):Jt.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(Q$,"getRecordAttributesAST");function W$(e,t,r,s,n){if(!e){Jt.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if($$.isEmptyOrZeroLength(i)){Jt.error("No schema specified");return}e.from.forEach(c=>{$i(c,t,r,s,n)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),$i(c.table,t,r,s,n)});let o=new Ms(e.columns);for(let{node:c}of o)if(c&&c.columnid){let _=c.tableid,u=s.has(_)?s.get(_):i;if(_||(_=e.from[0].tableid),!t.get(u).has(_))if(r.has(_))_=r.get(_);else{Jt.info(`table specified as ${_} not found.`);return}t.get(u).get(_).indexOf(c.columnid)<0&&t.get(u).get(_).push(c.columnid)}if(e.where){let c=new Ms(e.where),_=e.from[0].tableid;for(let{node:u}of c)if(u&&u.columnid){let l=u.tableid?u.tableid:_;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{Jt.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(u.columnid)<0&&t.get(i).get(l).push(u.columnid)}}if(e.joins&&e.joins.forEach(c=>{let _=new Ms(c.on);for(let{node:u}of _)if(u&&u.columnid){let l=u.tableid,E=n.get(l);if(!t.get(E).has(l))if(r.has(l))l=r.get(l);else{Jt.info(`table specified as ${l} not found.`);continue}t.get(E).get(l).indexOf(u.columnid)<0&&t.get(E).get(l).push(u.columnid)}}),e.order){let c=new Ms(e.order);for(let{node:_}of c)if(_&&_.columnid){let u=_.tableid,l=s.has(u)?s.get(u):i;if(u||(u=e.from[0].tableid),!t.get(l).has(u))if(r.has(u))u=r.get(u);else{Jt.info(`table specified as ${u} not found.`);return}t.get(l).get(u).indexOf(_.columnid)<0&&t.get(l).get(u).push(_.columnid)}}}a(W$,"getSelectAttributes");function J$(e,t,r){if(!e){Jt.info("getUpdateAttributes: invalid SQL syntax tree");return}let s=new Ms(e.columns),n=e.table.databaseid;$i(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&JE(e.table.tableid,n,i.columnid,t,r)}a(J$,"getUpdateAttributes");function Z$(e,t,r){if(!e){Jt.info("getDeleteAttributes: invalid SQL syntax tree");return}let s=new Ms(e.where),n=e.table.databaseid;$i(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&JE(e.table.tableid,n,i.columnid,t,r)}a(Z$,"getDeleteAttributes");function X$(e,t,r){if(!e){Jt.info("getInsertAttributes: invalid SQL syntax tree");return}let s=new Ms(e.columns),n=e.into.databaseid;$i(e.into,t,r);for(let{node:i}of s)i&&i.columnid&&JE(e.into.tableid,n,i.columnid,t,r)}a(X$,"getInsertAttributes");function JE(e,t,r,s,n){if(!s.get(t))return;let i=e;s.get(t).has(i)||(i=n.get(i)),s.get(t).get(i).push(r)}a(JE,"pushAttribute");fN.exports=Fc});var AN=h((I2,RN)=>{var z$=require("os"),mN=V();RN.exports={checkPermission:j$};function j$(){if(z$.userInfo().username!==mN.get("install_user"))throw new Error(`Error: Must execute as ${mN.get("install_user")}`)}a(j$,"checkPermission")});var XE=h((b2,IN)=>{var kc=pi(),pN=require("chalk"),ar=g(),ON=AN(),NN=require("prompt"),{promisify:eY}=require("util"),Vc=T(),tY=require("fs-extra"),rY=require("path"),sY=b(),nY=PE(),gN=V();gN.initSync();var iY=require("moment"),aY=eY(NN.get),oY=rY.join(gN.getHdbBasePath(),Vc.LICENSE_KEY_DIR_NAME,Vc.LICENSE_FILE_NAME,Vc.LICENSE_FILE_NAME);IN.exports={getFingerprint:_Y,setLicense:cY,parseLicense:ZE,register:uY,getRegistrationInfo:EY};async function cY(e){if(e&&e.key&&e.company){try{ar.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await ZE(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw ar.error(r),ar.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(cY,"setLicense");async function _Y(){try{ON.checkPermission()}catch(t){throw ar.error(t),new Error("You do not have permission to generate a fingerprint.")}let e={};try{e=await kc.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw ar.error(r),ar.error(t),new Error(r)}return e}a(_Y,"getFingerprint");async function ZE(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");console.log("Validating license input...");let r=kc.validateLicense(e,t);if(console.log("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(console.log("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(console.log(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{ar.info("writing license to disk"),await tY.writeFile(oY,JSON.stringify({license_key:e,company:t}))}catch(s){throw ar.error("Failed to write License"),s}return"Registration successful."}a(ZE,"parseLicense");async function uY(){let e=await lY();return ZE(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(uY,"register");async function lY(){try{ON.checkPermission()}catch(s){return console.error(s.message)}let e=await kc.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:pN.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:pN.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{NN.start()}catch(s){ar.error(s)}let r;try{r=await aY(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}a(lY,"promptForRegistration");async function EY(){let e={registered:!1,version:null,storage_type:null,ram_allocation:null,license_expiration_date:null},t;try{t=await kc.getLicense()}catch(r){throw ar.error(`There was an error when searching licenses due to: ${r.message}`),r}if(sY.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=nY.version(),e.storage_type=Vc.STORAGE_TYPES_ENUM.LMDB,e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=iY.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(EY,"getRegistrationInfo")});var CN=h((C2,bN)=>{"use strict";var dY=Se(),xc=class{constructor(t,r,s,n,i,o,c,_,u,l,E,d,S){this.port=t,this.server_name=r+dY.SERVER_SUFFIX.HUB,this.pid_file=s,this.max_payload=1e7,this.jetstream={enabled:!1},this.tls={cert_file:n,key_file:i,ca_file:o,insecure:c},this.leafnodes={port:_,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c}},this.cluster={name:u,port:l,routes:E,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c}},this.accounts={SYS:{users:d},HDB:{users:S}},this.system_account="SYS"}};a(xc,"HubConfigObject");bN.exports=xc});var LN=h((w2,UN)=>{"use strict";var wN=Se(),$c=class{constructor(t,r,s,n,i,o,c,_,u,l,E,d){this.port=t,this.server_name=r+wN.SERVER_SUFFIX.LEAF,this.pid_file=s,this.max_payload=1e7,this.jetstream={enabled:!0,store_dir:n,domain:r+wN.SERVER_SUFFIX.LEAF},this.tls={cert_file:u,key_file:l,ca_file:E,insecure:d},this.leafnodes={remotes:[{tls:{ca_file:E,insecure:d},urls:i,account:"SYS"},{tls:{ca_file:E,insecure:d},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:_,jetstream:"enabled"}},this.system_account="SYS"}};a($c,"LeafConfigObject");UN.exports=$c});var DN=h((U2,yN)=>{"use strict";var Yc=class{constructor(t,r){this.user=t,this.password=r}};a(Yc,"HdbUserObject");yN.exports=Yc});var PN=h((L2,MN)=>{"use strict";var hY=Se(),Kc=class{constructor(t,r){this.user=t+hY.SERVER_SUFFIX.ADMIN,this.password=r}};a(Kc,"SysUserObject");MN.exports=Kc});var ed=h((y2,HN)=>{"use strict";var Dn=require("path"),Zc=require("fs-extra"),SY=CN(),fY=LN(),TY=DN(),mY=PN(),zE=gr(),Pn=b(),Pt=Tr(),Jc=T(),Qc=Se(),{CONFIG_PARAMS:we}=Jc,Xc=g(),zc=V(),BN=$r(),jE=At(),Mn="clustering",RY=1e4,vN=5;HN.exports={generateNatsConfig:AY,removeNatsConfig:pY};async function AY(e=!1,t=void 0){zc.initSync();let r=zc.get(we.ROOTPATH),s=Dn.join(r,Mn,Qc.PID_FILES.HUB),n=Dn.join(r,Mn,Qc.PID_FILES.LEAF),i=Dn.join(r,Mn,"leaf"),o=Dn.join(r,Mn,Qc.NATS_CONFIG_FILES.HUB_SERVER),c=Dn.join(r,Mn,Qc.NATS_CONFIG_FILES.LEAF_SERVER),_=Pt.getConfigFromFile(we.CLUSTERING_TLS_CERTIFICATE),u=Pt.getConfigFromFile(we.CLUSTERING_TLS_PRIVATEKEY),l=Pt.getConfigFromFile(we.CLUSTERING_TLS_CERT_AUTH),E=Pt.getConfigFromFile(we.CLUSTERING_TLS_INSECURE),d=Pt.getConfigFromFile(we.CLUSTERING_NODENAME),S=Pt.getConfigFromFile(we.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await jE.checkNATSServerInstalled()||jc("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let m=await zE.listUsers(),R=Pt.getConfigFromFile(we.CLUSTERING_USER),w=await zE.getClusterUser();(Pn.isEmpty(w)||w.active!==!0)&&jc(`invalid cluster user '${R}'`),e||(await Wc(we.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await Wc(we.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await Wc(we.CLUSTERING_HUBSERVER_NETWORK_PORT),await Wc(we.CLUSTERING_LEAFSERVER_NETWORK_PORT));let U=[],B=[];for(let[da,Pr]of m.entries())Pr.role.role===Jc.ROLE_TYPES_ENUM.CLUSTER_USER&&Pr.active&&(U.push(new mY(Pr.username,BN.decrypt(Pr.hash))),B.push(new TY(Pr.username,BN.decrypt(Pr.hash))));let j=[],{hub_routes:k}=Pt.getClusteringRoutes();if(!Pn.isEmptyOrZeroLength(k))for(let da of k)j.push(`tls://${w.sys_name_encoded}:${w.uri_encoded_d_hash}@${da.host}:${da.port}`);let J=new SY(Pt.getConfigFromFile(we.CLUSTERING_HUBSERVER_NETWORK_PORT),d,s,_,u,l,E,S,Pt.getConfigFromFile(we.CLUSTERING_HUBSERVER_CLUSTER_NAME),Pt.getConfigFromFile(we.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),j,U,B);t=Pn.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===Jc.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await Zc.writeJson(o,J),Xc.trace(`Hub server config written to ${o}`));let xe=`tls://${w.sys_name_encoded}:${w.uri_encoded_d_hash}@0.0.0.0:${S}`,$e=`tls://${w.uri_encoded_name}:${w.uri_encoded_d_hash}@0.0.0.0:${S}`,Ea=new fY(Pt.getConfigFromFile(we.CLUSTERING_LEAFSERVER_NETWORK_PORT),d,n,i,[xe],[$e],U,B,_,u,l,E);(t===void 0||t===Jc.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await Zc.writeJson(c,Ea),Xc.trace(`Leaf server config written to ${c}`))}a(AY,"generateNatsConfig");async function Wc(e){let t=zc.get(e);Pn.isEmpty(t)&&jc(`port undefined for '${e}'`),await Pn.isPortTaken(t)&&jc(`'${e}' port '${t}' is is in use by another process, check to see if HarperDB is already running or another process is using this port.`)}a(Wc,"isPortAvailable");function jc(e){let t=`Error generating clustering config: ${e}`;Xc.error(t),console.error(t),process.exit(1)}a(jc,"generateNatsConfigError");async function pY(e){let{port:t,config_file:r}=jE.getServerConfig(e),{username:s,decrypt_hash:n}=await zE.getClusterUser(),i=0,o=500;for(;i<vN;){try{let u=await jE.createConnection(t,s,n,!1);if(u.protocol.connected===!0){u.close();break}}catch(u){Xc.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${u}`)}if(i++,i>=vN)throw new Error(`removeNatsConfig timed out waiting to connect to ${e}`);await Pn.async_set_timeout(o*i)}let c="0".repeat(RY),_=Dn.join(zc.get(we.ROOTPATH),Mn,r);await Zc.writeFile(_,c),await Zc.remove(_)}a(pY,"removeNatsConfig")});var t_=h((D2,$N)=>{"use strict";var ie=V(),qN=pi(),C=T(),td=Se(),pe=require("path"),{PACKAGE_ROOT:e_}=T(),Ee="/dev/null",Bn=pe.join(e_,"launchServiceScripts"),GN=pe.join(e_,"utility/scripts"),OY=pe.join(GN,C.HDB_RESTART_SCRIPT),FN=pe.resolve(e_,"dependencies",`${process.platform}-${process.arch}`,td.NATS_BINARY_NAME),qe,Ge;function or(){(qe===void 0||Ge===void 0)&&(ie.initSync(),qe=ie.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ie.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY))}a(or,"initLogConfig");function VN(){or();let e=pe.join(Ge,C.PROCESS_LOG_NAMES.IPC),t={name:C.PROCESS_DESCRIPTORS.IPC,exec_mode:"fork",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.IPC},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:C.SERVICE_SERVERS_CWD.IPC};return qe||(t.out_file=Ee,t.error_file=Ee),{...t,script:C.SERVICE_SERVERS.IPC}}a(VN,"generateIPCServerConfig");function kN(){or(),ie.initSync(),qe=ie.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ie.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=pe.join(Ge,C.PROCESS_LOG_NAMES.HDB),t=qN.licenseSearch(),r=t.ram_allocation?C.MEM_SETTING_KEY+t.ram_allocation:C.MEM_SETTING_KEY+C.RAM_ALLOCATION_ENUM.DEFAULT,s={name:C.PROCESS_DESCRIPTORS.HDB,script:C.LAUNCH_SERVICE_SCRIPTS.HDB,exec_mode:"cluster",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.HDB},merge_logs:!0,out_file:e,error_file:e,instances:ie.get(C.CONFIG_PARAMS.HTTP_THREADS),node_args:r,cwd:Bn};return qe||(s.out_file=Ee,s.error_file=Ee),s}a(kN,"generateHDBServerConfig");function xN(){or(),ie.initSync(),qe=ie.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ie.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=pe.join(Ge,C.PROCESS_LOG_NAMES.CUSTOM_FUNCTIONS),t=qN.licenseSearch(),r=t.ram_allocation?C.MEM_SETTING_KEY+t.ram_allocation:C.MEM_SETTING_KEY+C.RAM_ALLOCATION_ENUM.DEFAULT,s={name:C.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS,script:C.LAUNCH_SERVICE_SCRIPTS.CUSTOM_FUNCTIONS,exec_mode:"cluster",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS},merge_logs:!0,out_file:e,error_file:e,instances:ie.get(C.CONFIG_PARAMS.HTTP_THREADS),node_args:r,cwd:Bn};return qe||(s.out_file=Ee,s.error_file=Ee),s}a(xN,"generateCFServerConfig");function NY(){or(),ie.initSync(),qe=ie.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ie.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=ie.get(C.CONFIG_PARAMS.ROOTPATH),t=pe.join(e,"clustering",td.NATS_CONFIG_FILES.HUB_SERVER),r=pe.join(Ge,C.PROCESS_LOG_NAMES.CLUSTERING_HUB),s={name:C.PROCESS_DESCRIPTORS.CLUSTERING_HUB,script:FN,args:`-c ${t}`,exec_mode:"fork",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return qe||(s.out_file=Ee,s.error_file=Ee),s}a(NY,"generateNatsHubServerConfig");function gY(){or(),ie.initSync(),qe=ie.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ie.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=ie.get(C.CONFIG_PARAMS.ROOTPATH),t=pe.join(e,"clustering",td.NATS_CONFIG_FILES.LEAF_SERVER),r=pe.join(Ge,C.PROCESS_LOG_NAMES.CLUSTERING_LEAF),s={name:C.PROCESS_DESCRIPTORS.CLUSTERING_LEAF,script:FN,args:`-c ${t}`,exec_mode:"fork",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return qe||(s.out_file=Ee,s.error_file=Ee),s}a(gY,"generateNatsLeafServerConfig");function IY(){or(),ie.initSync();let e=pe.join(Ge,C.PROCESS_LOG_NAMES.CLUSTERING_INGEST_SERVICE),t={name:C.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE,script:C.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE,exec_mode:"cluster",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:Bn};return qe||(t.out_file=Ee,t.error_file=Ee),t}a(IY,"generateNatsIngestServiceConfig");function bY(){or(),ie.initSync();let e=pe.join(Ge,C.PROCESS_LOG_NAMES.CLUSTERING_REPLY_SERVICE),t={name:C.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE,script:C.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,exec_mode:"cluster",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:Bn};return qe||(t.out_file=Ee,t.error_file=Ee),t}a(bY,"generateNatsReplyServiceConfig");function CY(){or(),ie.initSync();let e=pe.join(Ge,C.PROCESS_LOG_NAMES.CLUSTERING_UPGRADE),t={name:C.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:C.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:Bn,autorestart:!1};return qe||(t.out_file=Ee,t.error_file=Ee),t}a(CY,"generateClusteringUpgradeV4ServiceConfig");function wY(){or();let e=pe.join(Ge,C.PROCESS_LOG_NAMES.PM2),t={name:C.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.RESTART_HDB},merge_logs:!0,out_file:e,error_file:e,instances:1,autorestart:!1,cwd:GN};return qe||(t.out_file=Ee,t.error_file=Ee),{...t,script:OY}}a(wY,"generateRestart");function UY(e){or();let t=pe.join(Ge,C.PROCESS_LOG_NAMES.JOBS),r=pe.join(e_,"server/jobs"),s={name:`JOB-${e}`,exec_mode:"fork",env:{[C.PROCESS_NAME_ENV_PROP]:`JOB-${e}`},merge_logs:!0,out_file:t,error_file:t,instances:1,cwd:Bn,autorestart:!1};return qe||(s.out_file=Ee,s.error_file=Ee),{...s,script:pe.join(r,"jobProcess.js")}}a(UY,"generateJobConfig");function LY(){return{apps:[VN(),kN(),xN()]}}a(LY,"generateAllServiceConfigs");$N.exports={generateAllServiceConfigs:LY,generateIPCServerConfig:VN,generateHDBServerConfig:kN,generateCFServerConfig:xN,generateRestart:wY,generateNatsHubServerConfig:NY,generateNatsLeafServerConfig:gY,generateNatsIngestServiceConfig:IY,generateNatsReplyServiceConfig:bY,generateClusteringUpgradeV4ServiceConfig:CY,generateJobConfig:UY}});var Ki=h((M2,tg)=>{"use strict";var P=T(),r_=b(),Yi=ed(),s_=At(),yY=Se(),$=require("pm2"),DY=require("fs-extra"),wr=t_(),lt=V(),Ur=g(),MY=t_(),PY=Ls(),BY=require("util"),KN=BY.promisify(require("child_process").exec),QN=require("path");tg.exports={start:Ps,stop:i_,reload:JN,restart:ZN,list:sd,describe:a_,connect:cr,kill:zN,startAllServices:YY,startService:n_,getUniqueServicesList:nd,restartAllServices:KY,stopAllServices:QY,isServiceRegistered:jN,reloadStopStart:rd,restartHdb:XN,deleteProcess:xY,configureLogRotate:ZY,startClustering:eg,isHdbRestartRunning:$Y,isClusteringRunning:zY,stopClustering:XY,reloadClustering:jY};var{PACKAGE_ROOT:vY}=T(),HY="2.7.0",WN=QN.join(vY,"node_modules/pm2/bin/pm2"),qY="Log rotate installed.",GY="Error installing log rotate.",FY="Log rotate updated.",VY="Error updating log rotate.",kY="The number of HarperDB processes running is different from the settings value. To restart and update the number HarperDB processes running you must stop and then start HarperDB";function cr(){return new Promise((e,t)=>{$.connect((r,s)=>{r&&t(r),e(s)})})}a(cr,"connect");function Ps(e){return new Promise(async(t,r)=>{try{await cr()}catch(s){r(s)}$.start(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(Ps,"start");function i_(e){return new Promise(async(t,r)=>{try{await cr()}catch(s){r(s)}$.stop(e,(s,n)=>{s&&($.disconnect(),r(s)),$.delete(e,(i,o)=>{i&&($.disconnect(),r(s)),$.disconnect(),t(o)})})})}a(i_,"stop");function JN(e){return new Promise(async(t,r)=>{try{await cr()}catch(s){r(s)}$.reload(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(JN,"reload");function ZN(e){return new Promise(async(t,r)=>{try{await cr()}catch(s){r(s)}$.restart(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(ZN,"restart");function xY(e){return new Promise(async(t,r)=>{try{await cr()}catch(s){r(s)}$.delete(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(xY,"deleteProcess");async function XN(){await Ps(MY.generateRestart())}a(XN,"restartHdb");async function $Y(){let e=await sd();for(let t in e)if(e[t].name===P.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a($Y,"isHdbRestartRunning");function sd(){return new Promise(async(e,t)=>{try{await cr()}catch(r){t(r)}$.list((r,s)=>{r&&($.disconnect(),t(r)),$.disconnect(),e(s)})})}a(sd,"list");function a_(e){return new Promise(async(t,r)=>{try{await cr()}catch(s){r(s)}$.describe(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(a_,"describe");function zN(){return new Promise(async(e,t)=>{try{await cr()}catch(r){t(r)}$.killDaemon((r,s)=>{r&&($.disconnect(),t(r)),$.disconnect(),e(s)})})}a(zN,"kill");async function YY(){try{await eg(),await Ps(wr.generateAllServiceConfigs())}catch(e){throw $.disconnect(),e}}a(YY,"startAllServices");async function n_(e){try{let t;switch(e=e.toLowerCase(),e){case P.PROCESS_DESCRIPTORS.IPC.toLowerCase():t=wr.generateIPCServerConfig();break;case P.PROCESS_DESCRIPTORS.HDB.toLowerCase():t=wr.generateHDBServerConfig();break;case P.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS.toLowerCase():t=wr.generateCFServerConfig();break;case P.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():t=wr.generateNatsIngestServiceConfig();break;case P.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():t=wr.generateNatsReplyServiceConfig();break;case P.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():t=wr.generateNatsHubServerConfig(),await Ps(t),await Yi.removeNatsConfig(e);return;case P.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():t=wr.generateNatsLeafServerConfig(),await Ps(t),await Yi.removeNatsConfig(e);return;case P.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():t=wr.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await Ps(t)}catch(t){throw $.disconnect(),t}}a(n_,"startService");async function nd(){try{let e=await sd(),t={};for(let r=0,s=e.length;r<s;r++){let n=e[r];t[n.name]===void 0&&(t[n.name]={name:n.name,exec_mode:n.pm2_env.exec_mode})}return t}catch(e){throw $.disconnect(),e}}a(nd,"getUniqueServicesList");async function KY(e=[]){try{let t=!1,r=await nd();for(let s=0,n=Object.values(r).length;s<n;s++){let i=Object.values(r)[s],o=i.name;e.includes(o)||(i.exec_mode==="cluster_mode"?o===P.PROCESS_DESCRIPTORS.HDB?t=!0:await rd(o):await ZN(o))}t&&await rd(P.PROCESS_DESCRIPTORS.HDB)}catch(t){throw $.disconnect(),t}}a(KY,"restartAllServices");async function QY(){try{let e=await nd();for(let t=0,r=Object.values(e).length;t<r;t++){let s=Object.values(e)[t];await i_(s.name)}if(await zN(),lt.get(P.CONFIG_PARAMS.OPERATIONSAPI_FOREGROUND)===!0){let t=(await DY.readFile(QN.join(lt.get(P.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),P.FOREGROUND_PID_FILE))).toString();try{process.kill(t,"SIGTERM")}catch(r){Ur.warn(`Error terminating foreground process: ${r}`)}}}catch(e){throw $.disconnect(),e}}a(QY,"stopAllServices");async function jN(e){return!r_.isEmptyOrZeroLength(await a_(e))}a(jN,"isServiceRegistered");async function rd(e){let t=e===P.PROCESS_DESCRIPTORS.HDB?lt.get(P.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES):lt.get(P.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES),r=await a_(e),s=r_.isEmptyOrZeroLength(r)?0:r.length;t!==s?e===P.PROCESS_DESCRIPTORS.HDB?Ur.error(kY):(await i_(e),await n_(e)):e===P.PROCESS_DESCRIPTORS.HDB?await XN():await JN(e)}a(rd,"reloadStopStart");function WY(){return new Promise(async(e,t)=>{try{await cr()}catch(r){t(r)}$.stop(P.PROCESS_DESCRIPTORS.PM2_LOGROTATE,(r,s)=>{r&&($.disconnect(),t(r)),$.disconnect(),e(s)})})}a(WY,"stopLogrotate");async function JY(){let{stdout:e,stderr:t}=await KN(`${process.platform==="win32"?"node":""} ${WN} install pm2-logrotate@${HY}`);if(Ur.debug(`loadLogRotate stdout: ${e}`),t)throw Ur.error(GY),t;Ur.info(qY)}a(JY,"installLogRotate");async function YN(){let e={max_size:lt.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_MAX_SIZE),retain:lt.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_RETAIN),compress:lt.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_COMPRESS),dateFormat:lt.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_DATE_FORMAT),rotateModule:lt.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_ROTATE_MODULE),workerInterval:lt.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_WORKER_INTERVAL),rotateInterval:lt.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_ROTATE_INTERVAL),TZ:lt.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_TIMEZONE)},t="";for(let n in e)t+=`${process.platform==="win32"?"node":""} ${WN} set pm2-logrotate:${n} ${e[n]}`,n!=="TZ"&&(t+=" && ");let{stdout:r,stderr:s}=await KN(t);if(Ur.debug(`updateLogRotateConfig stdout: ${r}`),s)throw Ur.error(VY),s;Ur.info(FY)}a(YN,"updateLogRotateConfig");async function ZY(){lt.initSync();let e=r_.autoCastBoolean(lt.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE)),t=await a_(P.PROCESS_DESCRIPTORS.PM2_LOGROTATE),r,s=!1;if(r_.isEmptyOrZeroLength(t)||(s=!0,r=t[0].pm2_env.status),e&&!s){await JY(),await YN();return}if(e&&s){await Ps(P.PROCESS_DESCRIPTORS.PM2_LOGROTATE),await YN();return}!e&&r===P.PM2_PROCESS_STATUSES.ONLINE&&await WY()}a(ZY,"configureLogRotate");async function eg(){for(let t in P.CLUSTERING_PROCESSES){let r=P.CLUSTERING_PROCESSES[t];await n_(r)}await s_.createWorkQueueStream(yY.WORK_QUEUE_CONSUMER_NAMES),await s_.updateNodeNameLocalStreams();let e=await PY.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===P.PRE_4_0_0_VERSION){Ur.info("Starting clustering upgrade 4.0.0 process"),await n_(P.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0);break}}a(eg,"startClustering");async function XY(){for(let e in P.CLUSTERING_PROCESSES){let t=P.CLUSTERING_PROCESSES[e];await i_(t)}}a(XY,"stopClustering");async function zY(){for(let e in P.CLUSTERING_PROCESSES){let t=P.CLUSTERING_PROCESSES[e];if(await jN(t)===!1)return!1}return!0}a(zY,"isClusteringRunning");async function jY(){await Yi.generateNatsConfig(!0),await s_.reloadNATSHub(),await s_.reloadNATSLeaf(),await Yi.removeNatsConfig(P.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Yi.removeNatsConfig(P.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(jY,"reloadClustering")});var _d=h((P2,ag)=>{"use strict";var y=T(),K=g(),o_=b(),eK=su(),id=ed(),cd=At(),tK=Se(),sg=require("minimist"),{handleHDBError:ad,hdb_errors:rK}=D(),Qi=Tr(),{HTTP_STATUS_CODES:od}=rK,G,rg=`Restarting HarperDB. This may take up to ${y.RESTART_TIMEOUT_MS/1e3} seconds.`,Bs="HarperDB is currently restarting and must complete before another HarperDB restart can be initialized.",sK="Invalid service",nK="'service' is required",iK="Restarting all services",aK="Clustering is not enabled so cannot be restarted";ag.exports={stop:cK,restartProcesses:oK,restartService:ng};async function oK(){K.createLogFile(y.PROCESS_LOG_NAMES.CLI,y.PROCESS_DESCRIPTORS.STOP);try{G===void 0&&(G=Ki());let e=eK(Object.keys(y.CONFIG_PARAM_MAP),!0);o_.isEmptyOrZeroLength(Object.keys(e))||Qi.updateConfigValue(void 0,void 0,e,!0,!0);let t=Qi.getConfigFromFile(y.CONFIG_PARAMS.CLUSTERING_ENABLED),r=Qi.getConfigFromFile(y.CONFIG_PARAMS.CUSTOMFUNCTIONS_ENABLED),s=sg(process.argv);if(!o_.isEmpty(s.service)){if(typeof s.service!="string"){let c=`Restart service argument expected a string but received: ${s.service}`;return K.error(c),c}let o=s.service.split(",");for(let c of o){let _=c.toLowerCase();if(_===y.HDB_PROC_DESCRIPTOR.toLowerCase()&&await G.isHdbRestartRunning()===!0){K.notify(Bs),console.error(Bs);continue}if(y.PROCESS_DESCRIPTORS_VALIDATE[_]===void 0){console.error(`Restart received unrecognized service command argument: ${_}`),K.error(`Restart received unrecognized service command argument: ${_}`);continue}let u=y.PROCESS_DESCRIPTORS_VALIDATE[_];if(console.log(`Restarting ${u}`),K.trace(`Restarting ${u}`),u===y.PROCESS_DESCRIPTORS.PM2_LOGROTATE)await G.configureLogRotate();else if(_.toLowerCase().includes("clustering"))await vn(_);else if(await G.isServiceRegistered(u))u===y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS&&!r?(await G.stop(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS),K.trace(`Stopping ${y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS}`)):await ng({service:u});else if(u===y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS)if(r)await G.startService(u),K.trace(`Starting ${u}`);else{let l=`${u} is not enabled in harperdb-config.yaml and cannot be restarted.`;K.error(l),console.log(l)}else await G.startService(u);K.notify(`${u} successfully restarted.`)}return}if(await G.isHdbRestartRunning()===!0)return K.notify(Bs),console.error(Bs),Bs;console.log(rg),t&&await ig();let n=await G.isServiceRegistered(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS);r&&!n&&(await G.startService(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS),K.trace(`Starting ${y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS}`));let i=[y.PROCESS_DESCRIPTORS.CLUSTERING_HUB,y.PROCESS_DESCRIPTORS.CLUSTERING_LEAF,y.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE,y.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE];return!r&&n&&(i.push(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS),await G.stop(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS),K.trace(`Stopping ${y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS}`)),await G.configureLogRotate(),K.notify(iK),await G.restartAllServices(i),rg}catch(e){let t=`There was an error restarting HarperDB. ${e}`;return K.error(t),t}}a(oK,"restartProcesses");async function ng(e){if(K.createLogFile(y.PROCESS_LOG_NAMES.CLI,y.PROCESS_DESCRIPTORS.STOP),G===void 0&&(G=Ki()),o_.isEmpty(e.service))throw ad(new Error,nK,od.BAD_REQUEST,void 0,void 0,!0);let t=e.service.toLowerCase();if(y.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw ad(new Error,sK,od.BAD_REQUEST,void 0,void 0,!0);let r=Qi.getConfigFromFile(y.CONFIG_PARAMS.CUSTOMFUNCTIONS_ENABLED),s=y.PROCESS_DESCRIPTORS_VALIDATE[t];if(s===y.PROCESS_DESCRIPTORS.HDB){if(await G.isHdbRestartRunning()===!0)return K.notify(Bs),Bs;await G.reloadStopStart(s)}else if(s===y.PROCESS_DESCRIPTORS.PM2_LOGROTATE)await G.configureLogRotate();else if(s.toLowerCase().includes("clustering"))await vn(s);else if(s===y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS||s===y.SERVICES.CUSTOM_FUNCTIONS){let i=await G.isServiceRegistered(s);if(r)i?(await G.reloadStopStart(s),K.trace(`Reloading ${s}`)):(await G.startService(s),K.trace(`Starting ${s}`));else if(!r&&i)await G.stop(s),K.trace(`Stopping ${s}`);else{let o=`${s} is not enabled in harperdb-config.yaml and cannot be restarted.`;throw K.error(o),ad(new Error,o,od.BAD_REQUEST,void 0,void 0,!0)}}else await G.restart(s);let n=`Restarting ${s}`;return K.notify(n),n}a(ng,"restartService");async function cK(){K.createLogFile(y.PROCESS_LOG_NAMES.CLI,y.PROCESS_DESCRIPTORS.STOP);try{G===void 0&&(G=Ki());let e=sg(process.argv);if(o_.isEmpty(e.service))console.log("Stopping HarperDB."),await G.stopAllServices(),K.notify("HarperDB has stopped");else{if(typeof e.service!="string"){let r=`Stop service argument expected a string but received: ${e.service}`;K.error(r),console.log(r)}let t=e.service.split(",");for(let r of t){let s=r.toLowerCase();if(y.PROCESS_DESCRIPTORS_VALIDATE[s]===void 0){K.error(`Stop received unrecognized service command argument: ${s}`);continue}s==="clustering"?await G.stopClustering():await G.stop(y.PROCESS_DESCRIPTORS_VALIDATE[s]);let n=`${y.PROCESS_DESCRIPTORS_VALIDATE[s]} successfully stopped.`;K.notify(n),console.log(n)}}}catch(e){throw console.error(e),e}}a(cK,"stop");async function ig(){await vn(y.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await vn(y.PROCESS_DESCRIPTORS.CLUSTERING_LEAF),await vn(y.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE),await vn(y.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE),await cd.updateNodeNameLocalStreams(),await cd.closeConnection()}a(ig,"restartAllClusteringServices");async function vn(e){e=y.PROCESS_DESCRIPTORS_VALIDATE[e.toLowerCase()];let t=Qi.getConfigFromFile(y.CONFIG_PARAMS.CLUSTERING_ENABLED),r=e==="clustering",s=e==="clustering config",n=r?void 0:await G.isServiceRegistered(e),i=r||s?await G.isClusteringRunning():void 0;switch(!0){case s:if(!i){K.error(aK);break}await G.reloadClustering();break;case(r&&i&&!t):await G.stopClustering();break;case(r&&!i&&t):await G.startClustering();break;case(r&&i&&t):await ig();break;case(r&&!i&&!t):K.error(`${e} is not enabled in harperdb-config.yaml and cannot be restarted.`);break;case(n&&!t):await G.stop(e),K.trace(`Stopping ${e}`);break;case(!n&&t):e!==y.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE&&e!==y.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE&&await id.generateNatsConfig(!0,e),await G.startService(e),K.trace(`Starting ${e}`),e===y.PROCESS_DESCRIPTORS.CLUSTERING_LEAF&&await cd.createWorkQueueStream(tK.WORK_QUEUE_CONSUMER_NAMES);break;case(!n&&!t):K.error(`${e} is not enabled in harperdb-config.yaml and cannot be restarted.`);break;case(n&&t):e===y.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE||e===y.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE?await G.reload(e):(await id.generateNatsConfig(!0,e),await G.restart(e),await id.removeNatsConfig(e));break;default:K.error(`Error restarting ${e}`)}}a(vn,"restartClustering")});var Tg=h((v2,fg)=>{"use strict";var B2=require("lodash"),ze=T(),{handleHDBError:og,hdb_errors:_K}=D(),{HDB_ERROR_MSGS:uK,HTTP_STATUS_CODES:lK}=_K,ud=g();fg.exports={getRolePermissions:dK};var vs=Object.create(null),EK=a(e=>({key:e,perms:{}}),"perms_template_obj"),lg=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),Eg=a((e=!1,t=!1,r=!1,s=!1)=>({[ze.PERMS_CRUD_ENUM.READ]:e,[ze.PERMS_CRUD_ENUM.INSERT]:t,[ze.PERMS_CRUD_ENUM.UPDATE]:r,[ze.PERMS_CRUD_ENUM.DELETE]:s}),"permissions_template"),ld=a((e=!1,t=!1,r=!1,s=!1,n=!1)=>({attribute_permissions:[],describe:e,...Eg(t,r,s,n)}),"table_perms_template"),cg=a((e,t=Eg())=>({attribute_name:e,describe:Sg(t),[Wi]:t[Wi],[Ed]:t[Ed],[dd]:t[dd]}),"attr_perms_template"),_g=a((e,t=!1)=>({attribute_name:e,describe:t,[Wi]:t}),"timestamp_attr_perms_template"),{READ:Wi,INSERT:Ed,UPDATE:dd}=ze.PERMS_CRUD_ENUM,dg=Object.values(ze.PERMS_CRUD_ENUM),hg=[Wi,Ed,dd];function dK(e){let t;try{if(e.permission.super_user||e.permission.cluster_user)return e.permission;let r=Object.assign({},global.hdb_schema);delete r[ze.SYSTEM_SCHEMA_NAME],t=e.role;let s=JSON.stringify([e.__updatedtime__,r]);if(vs[t]&&vs[t].key===s)return vs[t].perms;let n=hK(e,r);return vs[t]?vs[t].key=s:vs[t]=EK(s),vs[t].perms=n,n}catch(r){if(!e[ze.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[ze.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<ze.PERMS_UPDATE_RELEASE_TIMESTAMP){let s=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw ud.error(s),ud.debug(r),og(new Error,uK.OUTDATED_PERMS_TRANSLATION_ERROR,lK.BAD_REQUEST)}else{let s=`There was an error while translating role permissions for role: ${t}.
8
- ${r.stack}`;throw ud.error(s),og(new Error)}}}a(dK,"getRolePermissions");function hK(e,t){let r=Object.create(null);r.super_user=!1;let s=e.permission;r[ze.SYSTEM_SCHEMA_NAME]=s[ze.SYSTEM_SCHEMA_NAME],r.structure_user=s.structure_user;let n=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(n===!0||n.indexOf(i)>-1){r[i]=SK(t[i]);return}r[i]=lg(),s[i]?Object.keys(t[i]).forEach(o=>{if(s[i].tables[o]){let c=s[i].tables[o],_=t[i][o],u=fK(c,_);r[i].describe||dg.forEach(l=>{u[l]&&(r[i].describe=!0)}),r[i].tables[o]=u}else r[i].tables[o]=ld()}):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=ld()})}),r}a(hK,"translateRolePermissions");function SK(e){let t=lg(!0);return Object.keys(e).forEach(r=>{t.tables[r]=ld(!0,!0,!0,!0,!0)}),t}a(SK,"createStructureUserPermissions");function fK(e,t){let{attribute_permissions:r}=e;if(r.length>0){let n=Object.assign({},e);n.attribute_permissions=[];let i=r.reduce((u,l)=>{let{attribute_name:E}=l,d=l;return ze.TIME_STAMP_NAMES.includes(E)&&(d=_g(E,l[Wi])),u[E]=d,u},{}),o=t[ze.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_HASH_ATTRIBUTE_KEY],c=!!i[o],_=cg(o);return t.attributes.forEach(({attribute:u})=>{if(i[u]){let l=i[u];l.describe=Sg(l),n.attribute_permissions.push(l),c||TK(l,_)}else if(u!==o){let l;ze.TIME_STAMP_NAMES.includes(u)?l=_g(u):l=cg(u),n.attribute_permissions.push(l)}}),c||n.attribute_permissions.push(_),n.describe=ug(n),n}else return e.describe=ug(e),e}a(fK,"getTableAttrPerms");function ug(e){return dg.filter(t=>e[t]).length>0}a(ug,"getSchemaTableDescribePerm");function Sg(e){return hg.filter(t=>e[t]).length>0}a(Sg,"getAttributeDescribePerm");function TK(e,t){hg.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(TK,"checkForHashPerms")});var gg=h((H2,Ng)=>{"use strict";var me=require("joi"),mg=require("fs-extra"),Rg=require("path"),Hn=de(),Ag=V(),pg=T(),Og=g(),{hdb_errors:mK}=D(),{HDB_ERROR_MSGS:Et}=mK,ss=/^[a-zA-Z0-9-_]+$/;Ng.exports={getDropCustomFunctionValidator:AK,setCustomFunctionValidator:pK,addCustomFunctionProjectValidator:OK,dropCustomFunctionProjectValidator:NK,packageCustomFunctionProjectValidator:gK,deployCustomFunctionProjectValidator:IK};function Ji(e,t,r){try{let s=Ag.get(pg.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),n=Rg.join(s,t);return mg.existsSync(n)?e?t:r.message(Et.PROJECT_EXISTS):e?r.message(Et.NO_PROJECT):t}catch(s){return Og.error(s),r.message(Et.VALIDATION_ERR)}}a(Ji,"checkProjectExists");function RK(e,t,r,s){try{let n=Ag.get(pg.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),i=Rg.join(n,e,t,r+".js");return mg.existsSync(i)?r:s.message(Et.NO_FILE)}catch(n){return Og.error(n),s.message(Et.VALIDATION_ERR)}}a(RK,"checkFileExists");function AK(e){let t=me.object({project:me.string().pattern(ss).custom(Ji.bind(null,!0)).required().messages({"string.pattern.base":Et.BAD_PROJECT_NAME}),type:me.string().valid("helpers","routes").required(),file:me.string().pattern(ss).custom(RK.bind(null,e.project,e.type)).required().messages({"string.pattern.base":Et.BAD_FILE_NAME})});return Hn.validateBySchema(e,t)}a(AK,"getDropCustomFunctionValidator");function pK(e){let t=me.object({project:me.string().pattern(ss).custom(Ji.bind(null,!0)).required().messages({"string.pattern.base":Et.BAD_PROJECT_NAME}),type:me.string().valid("helpers","routes").required(),file:me.string().pattern(ss).required().messages({"string.pattern.base":Et.BAD_FILE_NAME}),function_content:me.string().required()});return Hn.validateBySchema(e,t)}a(pK,"setCustomFunctionValidator");function OK(e){let t=me.object({project:me.string().pattern(ss).custom(Ji.bind(null,!1)).required().messages({"string.pattern.base":Et.BAD_PROJECT_NAME})});return Hn.validateBySchema(e,t)}a(OK,"addCustomFunctionProjectValidator");function NK(e){let t=me.object({project:me.string().pattern(ss).custom(Ji.bind(null,!0)).required().messages({"string.pattern.base":Et.BAD_PROJECT_NAME})});return Hn.validateBySchema(e,t)}a(NK,"dropCustomFunctionProjectValidator");function gK(e){let t=me.object({project:me.string().pattern(ss).custom(Ji.bind(null,!0)).required().messages({"string.pattern.base":Et.BAD_PROJECT_NAME}),skip_node_modules:me.boolean()});return Hn.validateBySchema(e,t)}a(gK,"packageCustomFunctionProjectValidator");function IK(e){let t=me.object({project:me.string().pattern(ss).required().messages({"string.pattern.base":Et.BAD_PROJECT_NAME}),payload:me.string().required().messages({"string.pattern.base":Et.BAD_PACKAGE})});return Hn.validateBySchema(e,t)}a(IK,"deployCustomFunctionProjectValidator")});var fd=h((q2,Cg)=>{"use strict";var Ue=require("fs-extra"),c_=require("fast-glob"),ae=require("path"),Ig=require("tar-fs"),bg=require("uuid").v4,Zi=require("normalize-path"),Hs=gg(),Le=g(),pt=T(),Ot=V(),{PACKAGE_ROOT:bK}=T(),{handleHDBError:je,hdb_errors:CK}=D(),{HDB_ERROR_MSGS:ns,HTTP_STATUS_CODES:et}=CK,wK=ae.join(bK,"custom_function_template"),hd=ae.join(Ot.get(pt.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function Sd(){let e=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY);if(!(e==="true"||e===!0||e==="TRUE"))throw je(new Error,ns.NOT_ENABLED,et.BAD_REQUEST,void 0,void 0,!0)}a(Sd,"isCFEnabled");function UK(){Le.trace("getting custom api status");let e={};try{e={is_enabled:Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY),port:Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY),directory:Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY)}}catch(t){throw je(new Error,ns.FUNCTION_STATUS,et.INTERNAL_SERVER_ERROR,Le.ERR,t)}return e}a(UK,"customFunctionsStatus");function LK(){Le.trace("getting custom api endpoints");let e={},t=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY);try{c_.sync(Zi(`${t}/*`),{onlyDirectories:!0}).forEach(s=>{let n=s.split("/").pop();e[n]={routes:c_.sync(Zi(`${s}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:c_.sync(Zi(`${s}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),static:Ue.existsSync(Zi(`${s}/static`))&&c_.sync(Zi(`${s}/static/**/*`)).length}})}catch(r){throw je(new Error,ns.GET_FUNCTIONS,et.INTERNAL_SERVER_ERROR,Le.ERR,r)}return e}a(LK,"getCustomFunctions");function yK(e){e.project&&(e.project=ae.parse(e.project).name),e.file&&(e.file=ae.parse(e.file).name);let t=Hs.getDropCustomFunctionValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("getting custom api endpoint file content");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e,o=ae.join(r,s,n,i+".js");try{return Ue.readFileSync(o,{encoding:"utf8"})}catch(c){throw je(new Error,ns.GET_FUNCTION,et.INTERNAL_SERVER_ERROR,Le.ERR,c)}}a(yK,"getCustomFunction");function DK(e){Sd(),e.project&&(e.project=ae.parse(e.project).name),e.file&&(e.file=ae.parse(e.file).name);let t=Hs.setCustomFunctionValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("setting custom function file content");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i,function_content:o}=e;try{return Ue.outputFileSync(ae.join(r,s,n,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw je(new Error,ns.SET_FUNCTION,et.INTERNAL_SERVER_ERROR,Le.ERR,c)}}a(DK,"setCustomFunction");function MK(e){e.project&&(e.project=ae.parse(e.project).name),e.file&&(e.file=ae.parse(e.file).name);let t=Hs.getDropCustomFunctionValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("dropping custom function file");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e;try{return Ue.unlinkSync(ae.join(r,s,n,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw je(new Error,ns.DROP_FUNCTION,et.INTERNAL_SERVER_ERROR,Le.ERR,o)}}a(MK,"dropCustomFunction");function PK(e){Sd(),e.project&&(e.project=ae.parse(e.project).name);let t=Hs.addCustomFunctionProjectValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("adding custom function project");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;try{let n=ae.join(r,s);return Ue.mkdirSync(n,{recursive:!0}),Ue.copySync(wK,n),`Successfully created custom function project: ${s}`}catch(n){throw je(new Error,ns.ADD_FUNCTION,et.INTERNAL_SERVER_ERROR,Le.ERR,n)}}a(PK,"addCustomFunctionProject");function BK(e){e.project&&(e.project=ae.parse(e.project).name);let t=Hs.dropCustomFunctionProjectValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("dropping custom function project");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;try{let n=ae.join(r,s);return Ue.rmSync(n,{recursive:!0}),`Successfully deleted project: ${s}`}catch(n){throw je(new Error,ns.DROP_FUNCTION_PROJECT,et.INTERNAL_SERVER_ERROR,Le.ERR,n)}}a(BK,"dropCustomFunctionProject");async function vK(e){e.project&&(e.project=ae.parse(e.project).name);let t=Hs.packageCustomFunctionProjectValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("packaging custom function project");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e,n=ae.join(r,s),i=bg();if(!Ue.existsSync(n)){let l=`Unable to locate custom function project: ${s}`;throw Le.error(l),l}Ue.ensureDirSync(hd);let c=ae.join(hd,`${i}.tar`),_={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(_={ignore:l=>l.includes(ae.join(n,"node_modules"))}),Ig.pack(n,_).pipe(Ue.createWriteStream(c)),await new Promise(l=>setTimeout(l,2e3));let u=Ue.readFileSync(c,{encoding:"base64"});return Ue.unlinkSync(c),{project:s,payload:u,file:c}}a(vK,"packageCustomFunctionProject");async function HK(e){Sd(),e.project&&(e.project=ae.parse(e.project).name);let t=Hs.deployCustomFunctionProjectValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("deploying custom function project");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,payload:n,file:i}=e,o=ae.join(r,s);await Ue.ensureDir(o);let c,_;do c=ae.join(hd,bg()+".tar"),_=await Ue.pathExists(c);while(_);await Ue.outputFile(c,n,{encoding:"base64"});let u=Ue.createReadStream(c);return u.pipe(Ig.extract(o)),await new Promise(l=>u.on("end",l)),await Ue.unlink(c),`Successfully deployed project: ${s}`}a(HK,"deployCustomFunctionProject");Cg.exports={customFunctionsStatus:UK,getCustomFunctions:LK,getCustomFunction:yK,setCustomFunction:DK,dropCustomFunction:MK,addCustomFunctionProject:PK,dropCustomFunctionProject:BK,packageCustomFunctionProject:vK,deployCustomFunctionProject:HK}});var Td=h((G2,Ug)=>{"use strict";var _r=require("joi"),wg=de();Ug.exports={readTransactionLogValidator:qK,deleteTransactionLogsBeforeValidator:GK};function qK(e){let t=_r.object({schema:_r.string().required(),table:_r.string().required(),from:_r.date().timestamp(),to:_r.date().timestamp(),limit:_r.number().min(1)});return wg.validateBySchema(e,t)}a(qK,"readTransactionLogValidator");function GK(e){let t=_r.object({schema:_r.string().required(),table:_r.string().required(),timestamp:_r.date().timestamp().required()});return wg.validateBySchema(e,t)}a(GK,"deleteTransactionLogsBeforeValidator")});var u_=h((F2,Pg)=>{"use strict";var md=T(),__=At(),Lg=b(),yg=V(),Dg=$r(),{handleHDBError:qn,hdb_errors:FK}=D(),{HTTP_STATUS_CODES:Gn}=FK,{readTransactionLogValidator:VK,deleteTransactionLogsBeforeValidator:kK}=Td(),Mg="This operation relies on clustering and cannot run with it disable.",xK="Logs successfully deleted from transaction log.",$K="All logs successfully deleted from transaction log.";Pg.exports={readTransactionLog:YK,deleteTransactionLogsBefore:KK};async function YK(e){let t=VK(e);if(t)throw qn(t,t.message,Gn.BAD_REQUEST,void 0,void 0,!0);if(!yg.get(md.CONFIG_PARAMS.CLUSTERING_ENABLED))throw qn(new Error,Mg,Gn.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s}=e,n=Lg.checkSchemaTableExist(r,s);if(n)throw qn(new Error,n,Gn.NOT_FOUND,void 0,void 0,!0);let i=Dg.createNatsTableStreamName(r,s),o=await __.viewStream(i,parseInt(e.from),e.limit),c=[];for(let _=0,u=o.length;_<u;_++){let l=o[_],E=Math.floor(l?.nats_timestamp/1e6);if(e.to&&E>e.to)break;let d={operation:l?.entry?.operation,user:l?.entry?.__origin?.user,timestamp:E,records:l?.entry?.records};l?.entry?.operation===md.OPERATIONS_ENUM.DELETE&&(d.hash_values=l?.entry?.hash_values),c.push(d)}return c}a(YK,"readTransactionLog");async function KK(e){let t=kK(e);if(t)throw qn(t,t.message,Gn.BAD_REQUEST,void 0,void 0,!0);if(!yg.get(md.CONFIG_PARAMS.CLUSTERING_ENABLED))throw qn(new Error,Mg,Gn.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s,timestamp:n}=e,i=Lg.checkSchemaTableExist(r,s);if(i)throw qn(new Error,i,Gn.NOT_FOUND,void 0,void 0,!0);let o=Dg.createNatsTableStreamName(r,s),{jsm:c}=await __.getNATSReferences(),_=await __.getStreamInfo(o),u=new Date(_.state.first_ts).getTime();if(n<=u)return`No transactions exist before: ${n}`;let l=xK,E,d=new Date(_.state.last_ts).getTime();return n>d?(E=_.state.last_seq+1,l=$K):E=(await __.viewStream(o,parseInt(n),1))[0].nats_sequence,await c.streams.purge(o,{seq:E}),l}a(KK,"deleteTransactionLogsBefore")});var Ad=h((V2,$g)=>{"use strict";var l_=require("joi"),E_=require("path"),Bg=require("fs-extra"),{exec:QK}=require("child_process"),WK=require("util"),vg=WK.promisify(QK),JK=T(),{handleHDBError:Fn,hdb_errors:ZK}=D(),{HTTP_STATUS_CODES:Vn}=ZK,Hg=V(),XK=de(),d_=g();Hg.initSync();var Rd=Hg.get(JK.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),qg="npm install --omit=dev --json",zK=`${qg} --dry-run`;$g.exports={installModules:jK,auditModules:eQ};async function Gg(e,t=void 0){let{stdout:r,stderr:s}=await vg(e,{cwd:t});if(s)throw new Error(s.replace(`
7
+ `,"")}a(XA,"runCommand");async function l0(){try{await QF.access(Jl)}catch{return!1}let e=await XA(`${Jl} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return JF.eq(t,_0)}a(l0,"checkNATSServerInstalled");async function zl(e,t,r,s=!0,n="127.0.0.1"){return r0({name:n,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:s,tls:{keyFile:pr.get(ae.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:pr.get(ae.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:pr.get(ae.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}})}a(zl,"createConnection");async function E0(){Kt&&(await Kt.close(),Kt=void 0)}a(E0,"closeConnection");async function ic(){if(!Kt){let e=await YA.getClusterUser();if(ps(e))throw new Error("Unable to get nats connection. Cluster user is undefined.");let t=pr.get(ae.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT);Kt=await zl(t,e.username,e.decrypt_hash)}return Kt}a(ic,"getConnection");async function fn(){if(bi)return bi;ps(Kt)&&await ic();let{domain:e}=Ui(ae.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ps(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return bi=await Kt.jetstreamManager({domain:e}),bi}a(fn,"getJetStreamManager");async function ZA(){if(Ci)return Ci;ps(Kt)&&await ic();let{domain:e}=Ui(ae.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ps(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Ci=Kt.jetstream({domain:e}),Ci}a(ZA,"getJetStream");async function Dt(){let e=Kt||await ic(),t=bi||await fn(),r=Ci||await ZA();return{connection:e,jsm:t,js:r}}a(Dt,"getNATSReferences");async function d0(){let e=pr.get(ae.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),{sys_name:t,decrypt_hash:r}=await YA.getClusterUser(),s=await zl(e,t,r),n=Zl(),i=s.subscribe(n),o=[],c=(async()=>{for await(let _ of i)o.push(JA.decode(_.data))})();return await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:n}),await s.flush(),await Xl.async_set_timeout(50),await i.drain(),await s.close(),await c,o}a(d0,"getServerList");async function jl(e,t){let{jsm:r}=await Dt();await r.streams.add({name:e,storage:KA.File,retention:WA.Limits,subjects:t})}a(jl,"createLocalStream");async function zA(){let{jsm:e}=await Dt(),t=await e.streams.list().next(),r=[];return t.forEach(s=>{r.push(s)}),r}a(zA,"listStreams");async function h0(e){let{jsm:t}=await Dt();await t.streams.delete(e)}a(h0,"deleteLocalStream");async function S0(e){let{connection:t}=await Dt(),r=[],s=Zl(),n=t.subscribe(s),i=(async()=>{for await(let o of n)r.push(JA.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:s}),await t.flush(),await n.drain(),await i,r}a(S0,"listRemoteStreams");async function f0(e,t=void 0,r=void 0){let{jsm:s,connection:n}=await Dt(),i=ZF(),o=[],c={ack_policy:QA.None,durable_name:i,deliver_subject:i,deliver_policy:Ql.All};t&&(c.deliver_policy=Ql.StartTime,c.opt_start_time=new Date(t).toISOString());try{await s.consumers.add(e,c);let _={timeout:2e3};r&&(_.max=r);let u=await n.subscribe(i,_);for await(let l of u){let E=i0(l),d=xA(E.data),S={nats_timestamp:E.info.timestampNanos,nats_sequence:E.info.streamSequence,entry:d,originators:[]},m=[];if(E.headers){let R=E.headers.get("originators");R&&(m=R.split(","),S.originators=m)}o.push(S),u.getPending()===1&&E.info.pending===0&&u.stop()}return await s.consumers.delete(e,i),o}catch(_){if(await s.consumers.delete(e,i),_.code==="TIMEOUT")return o;throw _}}a(f0,"viewStream");async function T0(e,t,r=[],s=[]){Or.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,r,"originators:",s);let{connection:n,js:i}=await Dt(),o=await ac(),c=`${e}.${o}`,_=n0();s.push(o),_.append("originators",s.join());for(let u=0,l=r.length;u<l;u++)try{Or.trace(`publishToStream publishing to subject: ${c}, data:`,r[u]),await i.publish(c,Wl(r[u]),{headers:_})}catch(E){if(E.code&&E.code.toString()==="503")Or.trace(`publishToStream creating stream: ${t}`),await jl(t,[c]),await i.publish(c,Wl(r[u]),{headers:_});else throw E}}a(T0,"publishToStream");function Ui(e){e=e.toLowerCase();let t=wi.join(pr.get(ae.CONFIG_PARAMS.ROOTPATH),c0);if(e===ae.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return ps(Kl)&&(Kl={port:gi.getConfigFromFile(ae.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:gi.getConfigFromFile(ae.CONFIG_PARAMS.CLUSTERING_NODENAME)+te.SERVER_SUFFIX.HUB,config_file:te.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:wi.join(t,te.PID_FILES.HUB),hdb_nats_path:t}),Kl;if(e===ae.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return ps(Yl)&&(Yl={port:gi.getConfigFromFile(ae.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:gi.getConfigFromFile(ae.CONFIG_PARAMS.CLUSTERING_NODENAME)+te.SERVER_SUFFIX.LEAF,config_file:te.NATS_CONFIG_FILES.LEAF_SERVER,domain:gi.getConfigFromFile(ae.CONFIG_PARAMS.CLUSTERING_NODENAME)+te.SERVER_SUFFIX.LEAF,pid_file_path:wi.join(t,te.PID_FILES.LEAF),hdb_nats_path:t}),Yl;Or.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(Ui,"getServerConfig");async function m0(e){let{jsm:t}=await Dt(),r=await ac();try{await t.streams.add({name:e.stream_name,storage:KA.File,retention:WA.Workqueue,subjects:[`${te.SUBJECT_PREFIXES.MSGID}.${r}`,`${te.SUBJECT_PREFIXES.TXN}.${e.stream_name}.${r}`]})}catch(s){if(s.code!=="400")throw s}try{await t.consumers.info(e.stream_name,e.durable_name)}catch(s){if(s.code.toString()==="404")await t.consumers.add(e.stream_name,{ack_policy:QA.Explicit,deliver_subject:`${e.deliver_subject}.${r}`,durable_name:e.durable_name,deliver_policy:Ql.All,max_ack_pending:1e4,deliver_group:e.deliver_group,filter_subject:`${te.SUBJECT_PREFIXES.TXN}.>`});else throw s}}a(m0,"createWorkQueueStream");async function jA(e,t,r){let{jsm:s}=await Dt(),n=await s.streams.info(t),i=ep(s.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:_}=r,u=nc.createNatsTableStreamName(c,_),l=i===e,E,d,S=!1;if(!Array.isArray(n.config.sources)||n.config.sources.length===0)n.config.sources=[];else for(let R=0,w=n.config.sources.length;R<w;R++)if(E=n.config.sources[R],d=R,l&&E.name===u||!l&&E.name===u&&E.external&&E.external.api===`$JS.${e}.API`){S=!0;break}if(S===!0){if(E.opt_start_time===o)return;await rp(c,_,E,t),n.config.sources.splice(d,1),await s.streams.update(t,n.config)}let m={name:u,opt_start_time:o,filter_subject:`${te.SUBJECT_PREFIXES.TXN}.>`};l||(m.external={api:`$JS.${e}.API`,deliver:""}),n.config.sources.push(m),await s.streams.update(t,n.config)}a(jA,"addSourceToWorkStream");function ep(e){return e.split(".")[1]}a(ep,"extractServerName");async function tp(e,t,r){let{schema:s,table:n}=r,i=nc.createNatsTableStreamName(s,n),{jsm:o}=await Dt(),c=await o.streams.info(t);if(!Array.isArray(c.config.sources)||c.config.sources.length===0)return;let _=c.config.sources.length,u;for(;_--;)if(u=c.config.sources[_],u.name===i&&u.external.api===`$JS.${e}.API`){c.config.sources.splice(_,1);break}await o.streams.update(t,c.config),await rp(s,n,u,t)}a(tp,"removeSourceFromWorkStream");async function rp(e,t,r,s){let n=await fn(),i;try{i=ip(e,t,r.external.api.split(".")[1]),await n.streams.purge(s,{filter:i})}catch{Or.error("Error purging source subject",i,"from work stream",s)}}a(rp,"purgeSourceFromWorkStream");async function R0(e,t,r=2e3,s=Zl()){if(!Xl.isObject(t))throw new Error("data param must be an object");let n=Wl(t),{connection:i}=await Dt(),o={timeout:r};s&&(o.reply=s,o.noMux=!0);let c=await i.request(e,n,o);return xA(c.data)}a(R0,"request");function eE(e){return new Promise(async(t,r)=>{let s=jF(Jl,["--signal",`reload=${e}`],{cwd:__dirname}),n,i;s.on("error",o=>{r(o)}),s.stdout.on("data",o=>{i+=o.toString()}),s.stderr.on("data",o=>{n+=o.toString()}),s.stderr.on("close",o=>{n&&r(n),t(i)})})}a(eE,"reloadNATS");async function A0(){let{pid_file_path:e}=Ui(ae.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await eE(e)}a(A0,"reloadNATSHub");async function p0(){let{pid_file_path:e}=Ui(ae.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await eE(e)}a(p0,"reloadNATSLeaf");function O0(e,t,r){let s;switch(e.code){case VA.NoResponders:s=`Unable to ${t}, node '${r}' is not listening.`;break;case VA.Timeout:s=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:s=e.message;break}return s}a(O0,"requestErrorHandler");async function N0(e,t){let r=t+te.SERVER_SUFFIX.LEAF;await e0.writeTransaction(ae.SYSTEM_SCHEMA_NAME,ae.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,async()=>{e.subscribe===!0?await jA(r,te.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await tp(r,te.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(N0,"updateWorkStream");async function sp(e,t){let r=nc.createNatsTableStreamName(e,t),s=await ac(),n=ip(e,t,s);await jl(r,[n])}a(sp,"createLocalTableStream");async function g0(e){for(let t=0,r=e.length;t<r;t++){let s=e[t].schema,n=e[t].table;await sp(s,n)}}a(g0,"createTableStreams");async function np(e,t){if(pr.get(ae.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let r=nc.createNatsTableStreamName(e,t),{jsm:s}=await Dt();await s.streams.purge(r)}catch(r){if(r.message==="stream not found")Or.warn(r);else throw r}}a(np,"purgeTableStream");async function I0(e,t){if(pr.get(ae.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,s=t.length;r<s;r++)await np(e,t[r])}a(I0,"purgeSchemaTableStreams");async function b0(e){return(await fn()).streams.info(e)}a(b0,"getStreamInfo");function ip(e,t,r){return`${te.SUBJECT_PREFIXES.TXN}.${e}.${t}.${r}`}a(ip,"createSubjectName");async function ac(){if(Ii)return Ii;if(Ii=(await fn())?.nc?.info?.server_name,Ii===void 0)throw new Error("Unable to get jetstream manager server name");return Ii}a(ac,"getJsmServerName");async function C0(){let e=await fn(),t=await ac(),r=await zA();for(let s of r){let n=s.config,i=n.subjects[0];if(!i)continue;let o=i.split(".");if(o[o.length-1]!==t){if(n.name===te.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let _=`${te.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;Or.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else if(n.name===te.WORK_QUEUE_CONSUMER_NAMES.stream_name){let _=`${te.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;Or.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_,await e.consumers.update(te.WORK_QUEUE_CONSUMER_NAMES.stream_name,te.WORK_QUEUE_CONSUMER_NAMES.durable_name,{deliver_subject:`${te.WORK_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`})}else{let _=i.split(".");_[_.length-1]=t;let u=_.join(".");Or.trace(`Updating stream subject name from: ${i} to: ${u}`),n.subjects[0]=u}await e.streams.update(n.name,n)}}}a(C0,"updateNodeNameLocalStreams")});var tE=h((R3,op)=>{"use strict";var oc=class{constructor(t,r,s){this.timestamp=t,this.user=r,this.node_name=s}};a(oc,"ClusteringOriginObject");op.exports=oc});var Rn=h((A3,up)=>{"use strict";var cp=b(),yi=V(),ue=T(),rE=Se(),Tn=Rt(),fe=g(),_p=tE(),w0=Fr();yi.initSync();var mn=rE.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name,Li=rE.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject;up.exports={sendAttributeTransaction:_c,postOperationHandler:L0};async function _c(e,t,r=[]){if(!!yi.get(ue.CONFIG_PARAMS.CLUSTERING_ENABLED)&&!cp.isEmptyOrZeroLength(e.new_attributes)&&t.schema!==ue.SYSTEM_SCHEMA_NAME){let s=t.hdb_user?.username,n=yi.get(ue.CONFIG_PARAMS.CLUSTERING_NODENAME);for(let i of e.new_attributes){let o={operation:ue.OPERATIONS_ENUM.CREATE_ATTRIBUTE,schema:t.schema,table:t.table,attribute:i,__origin:new _p(e.txn_time,s,n)};fe.trace(`sendAttributeTransaction publishing ${mn}`,o),await Tn.publishToStream(Li,mn,[o],r)}}}a(_c,"sendAttributeTransaction");async function cc(e,t,r,s=[]){if(e.schema===ue.SYSTEM_SCHEMA_NAME)return;let n=U0(e,t,r);n&&(fe.trace(`sendOperationTransaction publishing to schema ${e.schema} table ${e.table} following transaction:`,n),await Tn.publishToStream(`${rE.SUBJECT_PREFIXES.TXN}.${e.schema}.${e.table}`,w0.createNatsTableStreamName(e.schema,e.table),[n],s))}a(cc,"sendOperationTransaction");function U0(e,t,r){if(cp.isEmptyOrZeroLength(t))return null;let s={operation:e.operation,schema:e.schema,table:e.table,__origin:r};return e.operation===ue.OPERATIONS_ENUM.DELETE?s.hash_values=t:s.records=e.records,s}a(U0,"convertCRUDOperationToTransaction");async function L0(e,t,r=[]){if(!yi.get(ue.CONFIG_PARAMS.CLUSTERING_ENABLED))return;fe.trace(`postOperationHandler called for operation ${e.operation} on schema.table: ${e.schema}.${e.table}`);let s=e.hdb_user?.username,n=yi.get(ue.CONFIG_PARAMS.CLUSTERING_NODENAME),i=new _p(t.txn_time,s,n);switch(e.operation){case ue.OPERATIONS_ENUM.INSERT:try{await cc(e,t.inserted_hashes,i,r),await _c(t,e,r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for insert."),fe.error(o)}break;case ue.OPERATIONS_ENUM.DELETE:try{await cc(e,t.deleted_hashes,i,r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for delete."),fe.error(o)}break;case ue.OPERATIONS_ENUM.UPDATE:try{await cc(e,t.update_hashes,i,r),await _c(t,e,r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for update."),fe.error(o)}break;case ue.OPERATIONS_ENUM.UPSERT:try{await cc(e,t.upserted_hashes,i,r),await _c(t,e,r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for upsert."),fe.error(o)}break;case ue.OPERATIONS_ENUM.CREATE_SCHEMA:try{let o={operation:ue.OPERATIONS_ENUM.CREATE_SCHEMA,schema:e.schema,__origin:i};await Tn.publishToStream(Li,mn,[o],r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for create_schema."),fe.error(o)}break;case ue.OPERATIONS_ENUM.CREATE_TABLE:try{let o={operation:ue.OPERATIONS_ENUM.CREATE_TABLE,schema:e.schema,table:e.table,hash_attribute:e.hash_attribute,__origin:i};await Tn.publishToStream(Li,mn,[o],r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for create_table."),fe.error(o)}break;case ue.OPERATIONS_ENUM.CREATE_ATTRIBUTE:try{let o={operation:ue.OPERATIONS_ENUM.CREATE_ATTRIBUTE,schema:e.schema,table:e.table,attribute:e.attribute,__origin:i};await Tn.publishToStream(Li,mn,[o],r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for create_attribute."),fe.error(o)}break;case ue.OPERATIONS_ENUM.CSV_DATA_LOAD:try{let o={operation:ue.OPERATIONS_ENUM.CSV_DATA_LOAD,schema:e.schema,table:e.table,attribute:e.attribute};await Tn.publishToStream(Li,mn,[o],r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for csv_data_load."),fe.error(o)}break;default:break}return t}a(L0,"postOperationHandler")});var Sp=h((p3,hp)=>{"use strict";var y0=Tt(),D0=$r(),lp=g(),Ep=Lt(),M0=sc(),P0=require("clone"),nE=require("alasql"),B0=Uo(),dp=require("util"),v0=dp.promisify(D0.getTableSchema),H0=dp.promisify(y0.search),q0=T(),sE=b(),G0=Rn();B0(nE);hp.exports={update:V0};var F0="There was a problem performing this update. Please check the logs and try again.";async function V0({statement:e,hdb_user:t}){let r=await v0(e.table.databaseid,e.table.tableid),s=$0(e.columns);sE.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=P0(n),c=sE.isEmpty(i)?"":` WHERE ${i.toString()}`,_=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,u=nE.parse(_).statements[0],l=await M0.writeTransaction(r.schema,r.name,async()=>{let E=await H0(u),d=k0(s,E);return x0(o,d,t)});return await Ep.flush({schema:r.schema,table:r.name}),l}a(V0,"update");function $0(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value:t[r.column.columnid]=nE.compile(`SELECT ${r.expression.toString()} AS [${q0.FUNC_VAL}] FROM ?`)}),t}catch(t){throw lp.error(t),new Error(F0)}}a($0,"createUpdateRecord");function k0(e,t){return sE.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(k0,"buildUpdateRecords");async function x0(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r};try{let n=await Ep.update(s);await G0.postOperationHandler(s,n);try{delete n.new_attributes,delete n.txn_time}catch(i){lp.error(`Error delete new_attributes from update response: ${i}`)}return n}catch(n){throw n}}a(x0,"updateRecords")});var Tp=h((O3,fp)=>{var Y0=require("alasql"),K0=Tt(),W0=g(),Q0=mr(),aE=require("util"),iE=b(),J0=T(),X0=$r(),Z0=sc(),z0=Rn(),j0=Lt(),eV="record",tV="successfully deleted",rV=aE.callbackify(aV),sV=aE.promisify(K0.search),nV=aE.promisify(X0.getTableSchema);fp.exports={convertDelete:rV};function iV(e){return`${e.deleted_hashes.length} ${eV}${e.deleted_hashes.length===1?"":"s"} ${tV}`}a(iV,"generateReturnMessage");async function aV({statement:e,hdb_user:t}){let r=await nV(e.table.databaseid,e.table.tableid);iE.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=iE.isEmpty(n)?"":` WHERE ${n.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=Y0.parse(o).statements[0],_={operation:J0.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{let u=await Z0.writeTransaction(r.schema,r.name,async()=>(_.records=await sV(c),Q0.deleteRecords(_)));return await j0.flush({schema:r.schema,table:r.name}),u.deleted_hashes.length>0&&await z0.postOperationHandler(_,u),iE.isEmptyOrZeroLength(u.message)&&(u.message=iV(u)),delete u.txn_time,u}catch(u){throw W0.error(u),u.hdb_code?u.message:u}}a(aV,"convertDelete")});var Ap=h((N3,Rp)=>{"use strict";var cE=Ss(),{hdb_errors:oE}=D();Rp.exports={checkSchemaExists:mp,checkSchemaTableExists:oV,schema_describe:cE};async function mp(e){if(!global.hdb_schema[e])try{let t=await cE.describeSchema({schema:e});global.hdb_schema[e]=t}catch{return oE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}}a(mp,"checkSchemaExists");async function oV(e,t){let r=await mp(e);if(r)return r;if(!global.hdb_schema[e][t])try{let s=await cE.describeTable({schema:e,table:t});if(!s||Object.keys(s).length===0)return oE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t);global.hdb_schema[e][t]=s}catch{return oE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}}a(oV,"checkSchemaTableExists")});var uc=h((I3,Ip)=>{"use strict";var An=Ka(),Os=Ap(),pp=g(),cV=require("uuid").v4,g3=require("clone"),On=Xs(),Ns=T(),_V=require("util"),gs=mr(),{handleHDBError:Be,hdb_errors:uV}=D(),{HDB_ERROR_MSGS:pn,HTTP_STATUS_CODES:ve}=uV,{SchemaEventMsg:Nn}=Hr(),Op=Rt();Ip.exports={createSchema:lV,createSchemaStructure:Np,createTable:EV,createTableStructure:gp,createAttribute:TV,dropSchema:dV,dropTable:hV,dropAttribute:SV};async function lV(e){try{let t=await Np(e);return On.signalSchemaChange(new Nn(process.pid,e.operation,e.schema)),t}catch(t){throw t}}a(lV,"createSchema");async function Np(e){let t=An.schema_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);if(!await Os.checkSchemaExists(e.schema))throw Be(new Error,pn.SCHEMA_EXISTS_ERR(e.schema),ve.BAD_REQUEST,Ns.LOG_LEVELS.ERROR,pn.SCHEMA_EXISTS_ERR(e.schema),!0);try{return await gs.createSchema(e),`schema '${e.schema}' successfully created`}catch(r){throw r}}a(Np,"createSchemaStructure");async function EV(e){try{let t=await gp(e);return On.signalSchemaChange(new Nn(process.pid,e.operation,e.schema,e.table)),t}catch(t){throw t}}a(EV,"createTable");async function gp(e){let t=An.create_table_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);An.validateTableResidence(e.residence);let r=await Os.checkSchemaExists(e.schema);if(r)throw Be(new Error,r,ve.NOT_FOUND,Ns.LOG_LEVELS.ERROR,r,!0);if(!await Os.checkSchemaTableExists(e.schema,e.table))throw Be(new Error,pn.TABLE_EXISTS_ERR(e.schema,e.table),ve.BAD_REQUEST,Ns.LOG_LEVELS.ERROR,pn.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:cV(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await gs.createTable(n,e);else throw Be(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",ve.BAD_REQUEST);else await gs.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(i){throw i}}a(gp,"createTableStructure");async function dV(e){let t=An.schema_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);let r=await Os.checkSchemaExists(e.schema);if(r)throw Be(new Error,r,ve.NOT_FOUND,Ns.LOG_LEVELS.ERROR,r,!0);let s=await Os.schema_describe.describeSchema({schema:e.schema});global.hdb_schema[e.schema]=s;let n=Object.keys(global.hdb_schema[e.schema]);return await gs.dropSchema(e),On.signalSchemaChange(new Nn(process.pid,e.operation,e.schema)),delete global.hdb_schema[e.schema],await Op.purgeSchemaTableStreams(e.schema,n),`successfully deleted schema '${e.schema}'`}a(dV,"dropSchema");async function hV(e){let t=An.table_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);let r=await Os.checkSchemaTableExists(e.schema,e.table);if(r)throw Be(new Error,r,ve.NOT_FOUND,Ns.LOG_LEVELS.ERROR,r,!0);return await gs.dropTable(e),On.signalSchemaChange(new Nn(process.pid,e.operation,e.schema,e.table)),await Op.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(hV,"dropTable");async function SV(e){let t=An.attribute_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);let r=await Os.checkSchemaTableExists(e.schema,e.table);if(r)throw Be(new Error,r,ve.NOT_FOUND,Ns.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw Be(new Error,"You cannot drop a hash attribute",ve.BAD_REQUEST,void 0,void 0,!0);if(Ns.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw Be(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,ve.BAD_REQUEST,void 0,void 0,!0);try{return await gs.dropAttribute(e),fV(e),On.signalSchemaChange(new Nn(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw pp.error(`Got an error deleting attribute ${_V.inspect(e)}.`),s}}a(SV,"dropAttribute");function fV(e){let t=Object.values(global.hdb_schema[e.schema][e.table].attributes);for(let r=0;r<t.length;r++)t[r].attribute===e.attribute&&global.hdb_schema[e.schema][e.table].attributes.splice(r,1)}a(fV,"dropAttributeFromGlobal");async function TV(e){if(!global.hdb_schema[e.schema])throw Be(new Error,pn.SCHEMA_NOT_FOUND(e.schema),ve.NOT_FOUND,void 0,void 0,!0);if(!global.hdb_schema[e.schema][e.table])throw Be(new Error,pn.TABLE_NOT_FOUND(e.schema,e.table),ve.NOT_FOUND,void 0,void 0,!0);try{return await gs.createAttribute(e),On.signalSchemaChange(new Nn(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}catch(t){throw pp.error(t),t}}a(TV,"createAttribute")});var Cp=h((b3,bp)=>{"use strict";var{OPERATIONS_ENUM:mV}=T(),lc=class{constructor(t,r,s=void 0,n=void 0){this.operation=mV.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=s,this.search_values=n}};a(lc,"ReadAuditLogObject");bp.exports=lc});var _E=h((w3,Dp)=>{"use strict";var RV=mr(),C3=Cp(),Ec=b(),dc=T(),AV=V(),{handleHDBError:wp,hdb_errors:pV}=D(),{HDB_ERROR_MSGS:Up,HTTP_STATUS_CODES:Lp}=pV,OV=Object.values(dc.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),yp="To use this operation audit log must be enabled in harperdb-config.yaml";Dp.exports=NV;async function NV(e){if(Ec.isEmpty(e.schema))throw new Error(Up.SCHEMA_REQUIRED_ERR);if(Ec.isEmpty(e.table))throw new Error(Up.TABLE_REQUIRED_ERR);if(!AV.get(dc.CONFIG_PARAMS.LOGGING_AUDITLOG))throw wp(new Error,yp,Lp.BAD_REQUEST,dc.LOG_LEVELS.ERROR,yp,!0);let t=Ec.checkSchemaTableExist(e.schema,e.table);if(t)throw wp(new Error,t,Lp.NOT_FOUND,dc.LOG_LEVELS.ERROR,t,!0);if(!Ec.isEmpty(e.search_type)&&OV.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await RV.readAuditLog(e)}a(NV,"readAuditLog")});var qp=h((U3,Hp)=>{var Qr=require("validate.js"),Pp=de(),gn=T(),{handleHDBError:gV,hdb_errors:IV}=D(),{HDB_ERROR_MSGS:le,HTTP_STATUS_CODES:bV}=IV,uE=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),CV={STRUCTURE_USER:"structure_user"},Mp=Object.values(gn.ROLE_TYPES_ENUM),wV="attribute_permissions",UV="attribute_name",{PERMS_CRUD_ENUM:In}=gn,LV=[wV,...Object.values(In)],Bp=[In.READ,In.INSERT,In.UPDATE],yV=[UV,...Bp];function DV(e){let t=uE();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,vp(e,t)}a(DV,"addRoleValidation");function MV(e){let t=uE();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,vp(e,t)}a(MV,"alterRoleValidation");function PV(e){let t=uE();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,Pp.validateObject(e,t)}a(PV,"dropRoleValidation");var BV=["operation","role","id","permission","hdb_user","hdb_auth_header"];function vp(e,t){let r={main_permissions:[],schema_permissions:{}},s=Object.keys(e),n=[];for(let o=0,c=s.length;o<c;o++)BV.includes(s[o])||n.push(s[o]);n.length>0&&Te(le.INVALID_ROLE_JSON_KEYS(n),r);let i=Pp.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{Te(o,r)}),e.permission){let o=vV(e);o&&Te(o,r),Mp.forEach(c=>{e.permission[c]&&!Qr.isBoolean(e.permission[c])&&Te(le.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(Mp.indexOf(o)<0){if(o===CV.STRUCTURE_USER){let _=e.permission[o];if(typeof _=="boolean")continue;if(Array.isArray(_)){for(let u=0,l=_.length;u<l;u++){let E=_[u];global.hdb_schema[E]||Te(le.SCHEMA_NOT_FOUND(E),r)}continue}Te(le.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){Te(le.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let _ in c.tables){let u=c.tables[_];if(!_||!global.hdb_schema[o][_]){Te(le.TABLE_NOT_FOUND(o,_),r);continue}if(Object.keys(u).forEach(l=>{LV.includes(l)||Te(le.INVALID_PERM_KEY(l),r,o,_)}),Object.values(In).forEach(l=>{Qr.isDefined(u[l])?Qr.isBoolean(u[l])||Te(le.TABLE_PERM_NOT_BOOLEAN(l),r,o,_):Te(le.TABLE_PERM_MISSING(l),r,o,_)}),Qr.isDefined(u.attribute_permissions)){if(!Qr.isArray(u.attribute_permissions)){Te(le.ATTR_PERMS_NOT_ARRAY,r,o,_);continue}}else{Te(le.ATTR_PERMS_ARRAY_MISSING,r,o,_);continue}if(u.attribute_permissions){let l=global.hdb_schema[o][_].attributes.map(({attribute:d})=>d),E={read:!1,insert:!1,update:!1};for(let d in u.attribute_permissions){let S=u.attribute_permissions[d];if(Object.keys(S).forEach(R=>{!yV.includes(R)&&R!==In.DELETE&&Te(le.INVALID_ATTR_PERM_KEY(R),r,o,_)}),!Qr.isDefined(S.attribute_name)){Te(le.ATTR_PERM_MISSING_NAME,r,o,_);continue}let m=S.attribute_name;if(!l.includes(m)){Te(le.INVALID_ATTRIBUTE_IN_PERMS(m),r,o,_);continue}Bp.forEach(R=>{Qr.isDefined(S[R])?Qr.isBoolean(S[R])||Te(le.ATTR_PERM_NOT_BOOLEAN(R,m),r,o,_):Te(le.ATTR_PERM_MISSING(R,m),r,o,_)}),!E.read&&S.read===!0&&(E.read=!0),!E.insert&&S.insert===!0&&(E.insert=!0),!E.update&&S.update===!0&&(E.update=!0)}if(u.read===!1&&E.read===!0||u.insert===!1&&E.insert===!0||u.update===!1&&E.update===!0){let d=`${o}.${_}`;Te(le.MISMATCHED_TABLE_ATTR_PERMS(d),r,o,_)}}}}return HV(r)}a(vp,"customValidate");Hp.exports={addRoleValidation:DV,alterRoleValidation:MV,dropRoleValidation:PV};function vV(e){let{operation:t,permission:r}=e;if(t===gn.OPERATIONS_ENUM.ADD_ROLE||t===gn.OPERATIONS_ENUM.ALTER_ROLE){let s=r.super_user===!0,n=r.cluster_user===!0;if(Object.keys(r).length>1&&(s||n)){if(n&&s)return le.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?gn.ROLE_TYPES_ENUM.SUPER_USER:gn.ROLE_TYPES_ENUM.CLUSTER_USER;return le.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(vV,"validateNoSUPerms");function HV(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let s={error:le.ROLE_PERMS_ERROR,...e};return gV(new Error,s,bV.BAD_REQUEST)}else return null}a(HV,"generateRolePermResponse");function Te(e,t,r,s){if(!r)t.main_permissions.push(e);else{let n=s?r+"_"+s:r;t.schema_permissions[n]?t.schema_permissions[n].push(e):t.schema_permissions[n]=[e]}}a(Te,"addPermError")});var mE=h((L3,xp)=>{"use strict";var Gp=Lt(),Fp=Tt(),qV=ms(),dE=qp(),hE=Xs(),GV=require("uuid").v4,SE=require("util"),FV=Ri(),Nr=T(),Vp=b(),fE=SE.promisify(Fp.searchByValue),VV=SE.promisify(Fp.searchByHash),$V=SE.promisify(qV.delete),kV=Yt(),xV=Es(),{hdb_errors:YV,handleHDBError:Di}=D(),{HDB_ERROR_MSGS:$p,HTTP_STATUS_CODES:lE}=YV,{UserEventMsg:TE}=Hr();xp.exports={addRole:KV,alterRole:QV,dropRole:JV,listRoles:kp};function EE(e){try{e.hdb_auth_header&&delete e.hdb_auth_header,e.HDB_INTERNAL_PATH&&delete e.HDB_INTERNAL_PATH,e.operation&&delete e.operation,e.hdb_user&&delete e.hdb_user}catch{}return e}a(EE,"scrubRoleDetails");async function KV(e){let t=dE.addRoleValidation(e);if(t)throw t;if(!(await FV.getLicense()).enterprise){let o=await kp();if(WV(e,o))throw new Error(`Your current license only supports ${Nr.BASIC_LICENSE_MAX_CLUSTER_USER_ROLES} cluster_user role. ${Nr.SUPPORT_HELP_MSG}`);if(o.length>=2)throw new Error(`Your current license only supports ${Nr.BASIC_LICENSE_MAX_NON_CU_ROLES+Nr.BASIC_LICENSE_MAX_CLUSTER_USER_ROLES} roles. ${Nr.SUPPORT_HELP_MSG}`)}e=EE(e);let s={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=await fE(s)}catch(o){throw Di(o)}if(n&&n.length>0)throw Di(new Error,$p.ROLE_ALREADY_EXISTS(e.role),lE.CONFLICT,void 0,void 0,!0);e.id||(e.id=GV());let i={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await Gp.insert(i),hE.signalUserChange(new TE(process.pid)),e=EE(e),e}a(KV,"addRole");function WV(e,t){let r=!1;if(e.permission.cluster_user===!0)for(let s=0;s<t.length;s++){let i=t[s].permission;if(!Vp.isEmpty(i)&&i.cluster_user===!0)return!0}return r}a(WV,"checkClusterUserRole");async function QV(e){let t=dE.alterRoleValidation(e);if(t)throw t;e=EE(e);let r={operation:"update",schema:"system",table:"hdb_role",hash_attribute:"rolename",records:[e]};try{await Gp.update(r)}catch(s){throw Di(s)}return hE.signalUserChange(new TE(process.pid)),e}a(QV,"alterRole");async function JV(e){let t=dE.dropRoleValidation(e);if(t)throw Di(new Error,t,lE.BAD_REQUEST,void 0,void 0,!0);let r=new xV(Nr.SYSTEM_SCHEMA_NAME,Nr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=await VV(r);if(s.length===0)throw Di(new Error,$p.ROLE_NOT_FOUND,lE.NOT_FOUND,void 0,void 0,!0);let n=new kV(Nr.SYSTEM_SCHEMA_NAME,Nr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=await fE(n),o=!1;if(Vp.isEmptyOrZeroLength(i)===!1){for(let _=0;_<i.length;_++)if(i[_].active===!0){o=!0;break}}if(o===!0)throw new Error(`Cannot drop role ${s[0].role} as it has active user(s) tied to this role`);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await $V(c),hE.signalUserChange(new TE(process.pid)),`${s[0].role} successfully deleted`}a(JV,"dropRole");async function kp(){return fE({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(kp,"listRoles")});var Qp=h((y3,Wp)=>{"use strict";var XV=V(),Jr=require("joi"),ZV=de(),Yp=require("moment"),zV=require("fs-extra"),RE=require("path"),jV=require("lodash"),Mi=T(),{LOG_LEVELS:Is}=T(),e$="YYYY-MM-DD hh:mm:ss",t$=RE.resolve(__dirname,"../logs");Wp.exports=function(e){return ZV.validateBySchema(e,r$)};var r$=Jr.object({from:Jr.custom(Kp),until:Jr.custom(Kp),level:Jr.valid(Is.NOTIFY,Is.FATAL,Is.ERROR,Is.WARN,Is.INFO,Is.DEBUG,Is.TRACE),order:Jr.valid("asc","desc"),limit:Jr.number().min(1),start:Jr.number().min(0),log_name:Jr.custom(s$)});function Kp(e,t){if(Yp(e,Yp.ISO_8601).format(e$)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(Kp,"validateDatetime");function s$(e,t){if(jV.invert(Mi.PROCESS_LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=XV.get(Mi.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e===void 0?Mi.PROCESS_LOG_NAMES.HDB:e,i=n===Mi.PROCESS_LOG_NAMES.INSTALL?RE.join(t$,Mi.PROCESS_LOG_NAMES.INSTALL):RE.join(s,n);return zV.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(s$,"validateReadLogPath")});var pE=h((D3,Xp)=>{"use strict";var hc=T(),Jp=g(),n$=V(),i$=Qp(),AE=require("path"),a$=require("fs-extra"),o$=require("readline"),{once:c$}=require("events"),{handleHDBError:_$,hdb_errors:u$}=D(),{PACKAGE_ROOT:l$}=T(),E$=AE.join(l$,"logs"),d$=1e3;Xp.exports=h$;async function h$(e){let t=i$(e);if(t)throw _$(t,t.message,u$.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=n$.get(hc.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?hc.PROCESS_LOG_NAMES.HDB:e.log_name,n=s===hc.PROCESS_LOG_NAMES.INSTALL?AE.join(E$,hc.PROCESS_LOG_NAMES.INSTALL):AE.join(r,s),i=a$.createReadStream(n);i.on("error",j=>{Jp.error(j)});let o=o$.createInterface({input:i,crlfDelay:1/0}),c=e.level!==void 0,_=c?e.level:void 0,u=e.from!==void 0,l=u?new Date(e.from):void 0,E=e.until!==void 0,d=E?new Date(e.until):void 0,S=e.limit===void 0?d$:e.limit,m=e.order===void 0?void 0:e.order,R=e.start===void 0?0:e.start,w=R+S,U=0,B=[];return o.on("line",j=>{let $,J,ke,xe;try{$=JSON.parse(j)}catch(ua){Jp.warn(ua.message);return}switch(!0){case(c&&u&&E):J=new Date($.timestamp),ke=new Date(l),xe=new Date(d),$.level===_&&J>=ke&&J<=xe&&U<R?U++:$.level===_&&J>=ke&&J<=xe&&(Zr($,m,B),U++,U===w&&Xr(o));break;case(c&&u):J=new Date($.timestamp),ke=new Date(l),$.level===_&&J>=ke&&U<R?U++:$.level===_&&J>=ke&&(Zr($,m,B),U++,U===w&&Xr(o));break;case(c&&E):J=new Date($.timestamp),xe=new Date(d),$.level===_&&J<=xe&&U<R?U++:$.level===_&&J<=xe&&(Zr($,m,B),U++,U===w&&Xr(o));break;case(u&&E):J=new Date($.timestamp),ke=new Date(l),xe=new Date(d),J>=ke&&J<=xe&&U<R?U++:J>=ke&&J<=xe&&(Zr($,m,B),U++,U===w&&Xr(o));break;case c:$.level===_&&U<R?U++:$.level===_&&(Zr($,m,B),U++,U===w&&Xr(o));break;case u:J=new Date($.timestamp),ke=new Date(l),J>=ke&&U<R?U++:J>=ke&&U>=R&&(Zr($,m,B),U++,U===w&&Xr(o));break;case E:J=new Date($.timestamp),xe=new Date(d),J<=xe&&U<R?U++:J<=xe&&U>=R&&(Zr($,m,B),U++,U===w&&Xr(o));break;default:U<R?U++:(Zr($,m,B),U++,U===w&&Xr(o))}}),await c$(o,"close"),B}a(h$,"readLog");function Xr(e){e.close(),e.removeAllListeners()}a(Xr,"endReadLine");function Zr(e,t,r){t==="desc"?S$(e,r):t==="asc"?f$(e,r):r.push(e)}a(Zr,"pushLineToResult");function S$(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)>r?s=i+1:n=i}t.splice(s,0,e)}a(S$,"insertDescending");function f$(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)<r?s=i+1:n=i}t.splice(s,0,e)}a(f$,"insertAscending")});var fc=h((B3,jp)=>{"use strict";var OE=require("joi"),{string:Sc,boolean:Zp,date:T$}=OE.types(),m$=de(),{validateSchemaExists:M3,validateTableExists:P3,validateSchemaName:R$}=hr(),A$=T(),p$=Se(),O$=V(),N$=Sc.invalid(O$.get(A$.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(p$.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null).required(),zp={operation:Sc.valid("add_node","update_node"),node_name:N$,subscriptions:OE.array().items({table:Sc.required(),schema:Sc.custom(R$).required(),subscribe:Zp.required(),publish:Zp.required().custom(I$),start_time:T$.iso()}).min(1).required()};function g$(e){return m$.validateBySchema(e,OE.object(zp))}a(g$,"addUpdateNodeValidator");function I$(e,t){if(t.state.ancestors[2].operation==="add_node"&&e===!1&&t.state.ancestors[0].subscribe===!1)return t.message(`'subscriptions[${t.state.path[1]}]' subscribe and/or publish must be set to true when adding a node`)}a(I$,"checkForFalsy");jp.exports={addUpdateNodeValidator:g$,validation_schema:zp}});var bn=h((v3,eO)=>{"use strict";var Tc=class{constructor(t,r,s){this.name=t,this.subscriptions=r,this.system_info=s}};a(Tc,"Node");var mc=class{constructor(t,r,s,n){this.schema=t,this.table=r,this.publish=s,this.subscribe=n}};a(mc,"NodeSubscription");eO.exports={Node:Tc,NodeSubscription:mc}});var rO=h((H3,tO)=>{"use strict";var b$=T().OPERATIONS_ENUM,Rc=class{constructor(t,r,s,n=void 0){this.operation=b$.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};a(Rc,"UpsertObject");tO.exports=Rc});var Pi=h((q3,sO)=>{"use strict";var Ac=class{constructor(t,r,s,n){this.operation=t,this.node_name=r,this.subscriptions=s,this.system_info=n}};a(Ac,"RemotePayloadObject");var pc=class{constructor(t,r,s,n,i,o){this.schema=t,this.table=r,this.hash_attribute=s,this.publish=n,this.subscribe=i,this.start_time=o}};a(pc,"RemotePayloadSubscription");sO.exports={RemotePayloadObject:Ac,RemotePayloadSubscription:pc}});var iO=h((G3,nO)=>{"use strict";var Oc=class{constructor(t,r,s=0,n=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=s,this.record_count=n,this.transaction_log_size=i,this.transaction_log_record_count=o}};a(Oc,"TableSizeObject");nO.exports=Oc});var _O=h((F3,cO)=>{"use strict";var C$=iO(),aO=require("path"),oO=re(),w$=Ke(),Cn=Z(),U$=g();cO.exports=L$;async function L$(e){let t=new C$;try{let r=aO.join(oO.getBaseSchemaPath(),e.schema.toString()),s=await Cn.openEnvironment(r,e.name),n=Cn.statDBI(s,e.hash_attribute),i=aO.join(oO.getTransactionAuditStorePath(),e.schema.toString()),o=await Cn.openEnvironment(i,e.name,!0),c=Cn.statDBI(o,w$.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP),_=await Cn.environmentDataSize(r,e.name),u=await Cn.environmentDataSize(i,e.name);t.schema=e.schema,t.table=e.name,t.table_size=_,t.record_count=n.entryCount,t.transaction_log_size=u,t.transaction_log_record_count=c.entryCount}catch(r){U$.warn(`unable to stat table dbi due to ${r}`)}return t}a(L$,"lmdbGetTableSize")});var lO=h((V3,uO)=>{"use strict";var y$=T(),Nc=class{constructor(t){this.operator=y$.OPERATIONS_ENUM.SYSTEM_INFORMATION,this.attributes=t}};a(Nc,"SystemInformationOperation");uO.exports=Nc});var dO=h(($3,EO)=>{"use strict";var gc=class{constructor(t,r,s,n,i,o,c){this.system=t,this.time=r,this.cpu=s,this.memory=n,this.disk=i,this.network=o,this.harperdb_processes=c}};a(gc,"SystemInformationObject");EO.exports=gc});var bc=h((x3,hO)=>{"use strict";var He=require("systeminformation"),wn=g(),D$=T(),M$=_O(),P$=Ss(),B$=V();B$.initSync();var k3=lO(),v$=dO(),Ic;hO.exports={getHDBProcessInfo:bE,getNetworkInfo:wE,getDiskInfo:CE,getMemoryInfo:IE,getCPUInfo:gE,getTimeInfo:NE,getSystemInformation:UE,systemInformation:H$,getTableSize:LE};function NE(){return He.time()}a(NE,"getTimeInfo");async function gE(){try{let{family:e,model:t,stepping:r,revision:s,voltage:n,speedmin:i,speedmax:o,governor:c,socket:_,cache:u,...l}=await He.cpu();l.cpu_speed=await He.cpuCurrentSpeed();let{raw_currentload:E,raw_currentload_idle:d,raw_currentload_irq:S,raw_currentload_nice:m,raw_currentload_system:R,raw_currentload_user:w,cpus:U,...B}=await He.currentLoad();return B.cpus=[],U.forEach(j=>{let{raw_load:$,raw_load_idle:J,raw_load_irq:ke,raw_load_nice:xe,raw_load_system:ua,raw_load_user:la,...Lr}=j;B.cpus.push(Lr)}),l.current_load=B,l}catch(e){return wn.error(`error in getCPUInfo: ${e}`),{}}}a(gE,"getCPUInfo");async function IE(){try{let{buffers:e,cached:t,slab:r,buffcache:s,...n}=await He.mem();return n}catch(e){return wn.error(`error in getMemoryInfo: ${e}`),{}}}a(IE,"getMemoryInfo");async function bE(){let e={core:[],clustering:[]};try{return(await He.processes()).list.forEach(r=>{r.params.includes(D$.HDB_PROC_NAME)?e.core.push(r):r.params.includes("socketcluster")&&e.clustering.push(r)}),e}catch(t){return wn.error(`error in getHDBProcessInfo: ${t}`),e}}a(bE,"getHDBProcessInfo");async function CE(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:s,ms:n,...i}=await He.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:_,...u}=await He.fsStats();return e.read_write=u,e.size=await He.fsSize(),e}catch(t){return wn.error(`error in getDiskInfo: ${t}`),e}}a(CE,"getDiskInfo");async function wE(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await He.networkInterfaceDefault(),e.latency=await He.inetChecksite("google.com"),(await He.networkInterfaces()).forEach(s=>{let{internal:n,virtual:i,mtu:o,dhcp:c,dnsSuffix:_,ieee8021xAuth:u,ieee8021xState:l,carrier_changes:E,...d}=s;e.interfaces.push(d)}),(await He.networkStats()).forEach(s=>{let{rx_sec:n,tx_sec:i,ms:o,...c}=s;e.stats.push(c)}),e.connections=await He.networkConnections(),e}catch(t){return wn.error(`error in getNetworkInfo: ${t}`),e}}a(wE,"getNetworkInfo");async function UE(){if(Ic!==void 0)return Ic;let e={};try{let{codepage:t,logofile:r,serial:s,build:n,servicepack:i,uefi:o,...c}=await He.osInfo();e=c;let _=await He.versions("node, npm");return e.node_version=_.node,e.npm_version=_.npm,Ic=e,Ic}catch(t){return wn.error(`error in getSystemInformation: ${t}`),e}}a(UE,"getSystemInformation");async function LE(){let e=[],t=await P$.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await M$(s));return e}a(LE,"getTableSize");async function H$(e){let t=new v$;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await UE(),t.time=NE(),t.cpu=await gE(),t.memory=await IE(),t.disk=await CE(),t.network=await wE(),t.harperdb_processes=await bE(),t.table_size=await LE(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await UE();break;case"time":t.time=NE();break;case"cpu":t.cpu=await gE();break;case"memory":t.memory=await IE();break;case"disk":t.disk=await CE();break;case"network":t.network=await wE();break;case"harperdb_processes":t.harperdb_processes=await bE();break;case"table_size":t.table_size=await LE();break;default:break}return t}a(H$,"systemInformation")});var yE=h((W3,SO)=>{"use strict";var Y3=require("fs-extra"),K3=g();SO.exports={version:q$,printVersion:F$,nodeVersion:G$};var zr=xl();function q$(){if(zr)return zr.version}a(q$,"version");function G$(){if(zr&&zr.engines&&zr.engines["preferred-node"])return zr.engines["preferred-node"]}a(G$,"nodeVersion");function F$(){zr&&console.log(`HarperDB Version ${zr.version}`)}a(F$,"printVersion")});var Cs=h((X3,RO)=>{"use strict";var V$=Lt(),DE=b(),ME=require("util"),bs=T(),fO=V();fO.initSync();var $$=kl(),TO=Tt(),{Node:Q3,NodeSubscription:J3}=bn(),k$=Es(),x$=rO(),{RemotePayloadObject:Y$,RemotePayloadSubscription:K$}=Pi(),{handleHDBError:W$,hdb_errors:Q$}=D(),{HTTP_STATUS_CODES:J$,HDB_ERROR_MSGS:X$}=Q$,Z$=Yt(),z$=bc(),j$=yE(),ek=ME.promisify($$.authorize),tk=ME.promisify(TO.searchByHash),rk=ME.promisify(TO.searchByValue);RO.exports={authHeaderToUser:sk,isEmpty:nk,getNodeRecord:ik,upsertNodeRecord:ak,buildNodePayloads:ok,checkClusteringEnabled:ck,getAllNodeRecords:_k,getSystemInfo:uk,reverseSubscription:mO};async function sk(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await ek(t,null),e}a(sk,"authHeaderToUser");function nk(e){return e==null}a(nk,"isEmpty");async function ik(e){let t=new k$(bs.SYSTEM_SCHEMA_NAME,bs.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return tk(t)}a(ik,"getNodeRecord");async function ak(e){let t=new x$(bs.SYSTEM_SCHEMA_NAME,bs.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return V$.upsert(t)}a(ak,"upsertNodeRecord");function mO(e){if(DE.isEmpty(e.subscribe)||DE.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:s}=e,n={schema:t,table:r,hash_attribute:s};return e.subscribe===!0&&e.publish===!1?(n.subscribe=!1,n.publish=!0):e.subscribe===!1&&e.publish===!0?(n.subscribe=!0,n.publish=!1):(n.subscribe=e.subscribe,n.publish=e.publish),n}a(mO,"reverseSubscription");function ok(e,t,r,s){let n=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:_,table:u}=c,l=DE.getTableHashAttribute(_,u),{subscribe:E,publish:d}=mO(c),S=new K$(_,u,l,d,E,c.start_time);n.push(S)}return new Y$(r,t,n,s)}a(ok,"buildNodePayloads");function ck(){if(!fO.get(bs.CONFIG_PARAMS.CLUSTERING_ENABLED))throw W$(new Error,X$.CLUSTERING_NOT_ENABLED,J$.BAD_REQUEST,void 0,void 0,!0)}a(ck,"checkClusteringEnabled");async function _k(){let e=new Z$(bs.SYSTEM_SCHEMA_NAME,bs.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return rk(e)}a(_k,"getAllNodeRecords");async function uk(){let e=await z$.getSystemInformation();return{hdb_version:j$.version(),node_version:e.node_version,platform:e.platform}}a(uk,"getSystemInfo")});var BE=h((Z3,IO)=>{"use strict";var PE=Rt(),AO=b(),pO=Se(),lk=T(),Cc=g(),OO=uc(),Ek=el(),{RemotePayloadObject:dk}=Pi(),{handleHDBError:NO,hdb_errors:hk}=D(),{HTTP_STATUS_CODES:gO}=hk,{NodeSubscription:Sk}=bn();IO.exports=fk;async function fk(e,t){let r;try{r=await PE.request(`${t}.${pO.REQUEST_SUFFIX}`,new dk(lk.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Cc.trace("Response from remote describe all request:",r)}catch(o){Cc.error(`addNode received error from describe all request to remote node: ${o}`);let c=PE.requestErrorHandler(o,"add_node",t);throw NO(new Error,c,gO.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===pO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw NO(new Error,o,gO.INTERNAL_SERVER_ERROR,"error",o)}let s=r.message,n=[],i=[];for(let o of e){let{schema:c,table:_}=o,u=AO.doesSchemaExist(c),l=s[c]!==void 0,E=AO.doesTableExist(c,_),d=s?.[c]?.[_]!==void 0;if(!u&&!l||!E&&!d){n.push(o);continue}if(!u&&l&&(Cc.trace(`addNode creating schema: ${c}`),await OO.createSchema({operation:"create_schema",schema:c})),!E&&d){Cc.trace(`addNode creating table: ${_} in schema: ${c}`);let m=new Ek(c,_,s[c][_].hash_attribute);await OO.createTable(m)}await PE.createLocalTableStream(c,_);let S=new Sk(c,_,o.publish,o.subscribe);S.start_time=o.start_time,i.push(S)}return{added:i,skipped:n}}a(fk,"reviewSubscriptions")});var Lc=h((z3,wO)=>{"use strict";var{handleHDBError:wc,hdb_errors:Tk}=D(),{HTTP_STATUS_CODES:Uc}=Tk,{addUpdateNodeValidator:mk}=fc(),Bi=g(),CO=T(),bO=Se(),Rk=b(),vE=Rt(),vi=Cs(),Ak=V(),pk=BE(),{Node:Ok,NodeSubscription:Nk}=bn(),gk="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",Ik="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",bk=Ak.get(CO.CONFIG_PARAMS.CLUSTERING_NODENAME);wO.exports=Ck;async function Ck(e,t=!1){Bi.trace("addNode called with:",e),vi.checkClusteringEnabled();let r=mk(e);if(r)throw wc(r,r.message,Uc.BAD_REQUEST,void 0,void 0,!0);let s=e.node_name;if(!t){let E=await vi.getNodeRecord(s);if(!Rk.isEmptyOrZeroLength(E))throw wc(new Error,`Node '${s}' has already been added, perform update_node to proceed.`,Uc.BAD_REQUEST,void 0,void 0,!0)}let{added:n,skipped:i}=await pk(e.subscriptions,s),o={message:void 0,added:n,skipped:i};if(n.length===0)return o.message=gk,o;let c=vi.buildNodePayloads(n,bk,CO.OPERATIONS_ENUM.ADD_NODE,await vi.getSystemInfo());Bi.trace("addNode sending remote payload:",c);let _;try{_=await vE.request(`${s}.${bO.REQUEST_SUFFIX}`,c)}catch(E){Bi.error(`addNode received error from request: ${E}`);let d=vE.requestErrorHandler(E,"add_node",s);throw wc(new Error,d,Uc.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===bO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let E=`Error returned from remote node ${s}: ${_.message}`;throw wc(new Error,E,Uc.INTERNAL_SERVER_ERROR,"error",E)}Bi.trace(_);let u=[];for(let E=0,d=n.length;E<d;E++){let S=n[E];Bi.trace("Add node updating work stream for node:",s,"subscriptions:",S),await vE.updateWorkStream(S,s),n[E].start_time===void 0&&delete n[E].start_time,u.push(new Nk(S.schema,S.table,S.publish,S.subscribe))}let l=new Ok(s,u,_.system_info);return await vi.upsertNodeRecord(l),i.length>0?o.message=Ik:o.message=`Successfully added '${s}' to manifest`,o}a(Ck,"addNode")});var qE=h((j3,yO)=>{"use strict";var{handleHDBError:yc,hdb_errors:wk}=D(),{HTTP_STATUS_CODES:Dc}=wk,{addUpdateNodeValidator:Uk}=fc(),Hi=g(),LO=T(),UO=Se(),Lk=b(),HE=Rt(),qi=Cs(),yk=V(),{cloneDeep:Dk}=require("lodash"),Mk=BE(),{NodeSubscription:Pk}=bn(),Bk="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",vk="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Hk=yk.get(LO.CONFIG_PARAMS.CLUSTERING_NODENAME);yO.exports=qk;async function qk(e){Hi.trace("updateNode called with:",e),qi.checkClusteringEnabled();let t=Uk(e);if(t)throw yc(t,t.message,Dc.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=Dk(await qi.getNodeRecord(r));if(Lk.isEmptyOrZeroLength(s))throw yc(new Error,`Node '${r}' has not been added, perform add_node to proceed.`,Dc.BAD_REQUEST,void 0,void 0,!0);let{added:n,skipped:i}=await Mk(e.subscriptions,r),o={message:void 0,updated:n,skipped:i};if(n.length===0)return o.message=Bk,o;let c=qi.buildNodePayloads(n,Hk,LO.OPERATIONS_ENUM.UPDATE_NODE,await qi.getSystemInfo());Hi.trace("updateNode sending remote payload:",c);let _;try{_=await HE.request(`${r}.${UO.REQUEST_SUFFIX}`,c)}catch(u){Hi.error(`updateNode received error from request: ${u}`);let l=HE.requestErrorHandler(u,"update_node",r);throw yc(new Error,l,Dc.INTERNAL_SERVER_ERROR,"error",l)}if(_.status===UO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let u=`Error returned from remote node ${r}: ${_.message}`;throw yc(new Error,u,Dc.INTERNAL_SERVER_ERROR,"error",u)}Hi.trace(_);for(let u=0,l=n.length;u<l;u++){let E=n[u];Hi.trace(`updateNode updating work stream for node: ${r} subscription:`,E),await HE.updateWorkStream(E,r),n[u].start_time===void 0&&delete n[u].start_time}return await Gk(s[0],n,_.system_info),i.length>0?o.message=vk:o.message=`Successfully updated '${r}'`,o}a(qk,"updateNode");async function Gk(e,t,r){let s=e;for(let n=0,i=t.length;n<i;n++){let o=t[n],c=!1;for(let _=0,u=e.subscriptions.length;_<u;_++){let l=s.subscriptions[_];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||s.subscriptions.push(new Pk(o.schema,o.table,o.publish,o.subscribe))}s.system_info=r,await qi.upsertNodeRecord(s)}a(Gk,"updateNodeTable")});var vO=h((e2,BO)=>{"use strict";var PO=require("joi"),{string:DO}=PO.types(),Fk=de(),MO=T(),Vk=V(),$k=Se();BO.exports=kk;function kk(e){let t=DO.invalid(Vk.get(MO.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern($k.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null),r=PO.object({operation:DO.valid(MO.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return Fk.validateBySchema(e,r)}a(kk,"removeNodeValidator")});var Pc=h((t2,$O)=>{"use strict";var{handleHDBError:HO,hdb_errors:xk}=D(),{HTTP_STATUS_CODES:qO}=xk,Yk=vO(),Gi=g(),GO=Cs(),Kk=b(),Mc=T(),FO=Se(),VO=Rt(),Wk=V(),{RemotePayloadObject:Qk}=Pi(),{NodeSubscription:Jk}=bn(),Xk=ui(),Zk=ms(),zk=Wk.get(Mc.CONFIG_PARAMS.CLUSTERING_NODENAME);$O.exports=jk;async function jk(e){Gi.trace("removeNode called with:",e),GO.checkClusteringEnabled();let t=Yk(e);if(t)throw HO(t,t.message,qO.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=await GO.getNodeRecord(r);if(Kk.isEmptyOrZeroLength(s))throw HO(new Error,`Node '${r}' was not found.`,qO.BAD_REQUEST,void 0,void 0,!0);s=s[0];let n=new Qk(Mc.OPERATIONS_ENUM.REMOVE_NODE,zk,[]),i,o=!1;try{i=await VO.request(`${r}.${FO.REQUEST_SUFFIX}`,n),Gi.trace("Remove node reply from remote node:",r,i)}catch(_){Gi.error("removeNode received error from request:",_),o=!0}for(let _=0,u=s.subscriptions.length;_<u;_++){let l=s.subscriptions[_];Gi.trace(`Remove node removing subscription: ${l.schema}.${l.table} for node: ${r}`);let E=new Jk(l.schema,l.table,!1,!1);await VO.updateWorkStream(E,r)}let c=new Xk(Mc.SYSTEM_SCHEMA_NAME,Mc.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await Zk.deleteRecord(c),i?.status===FO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Gi.error("Error returned from remote node:",r,i?.message),`Successfully removed '${r}' from local manifest, however there was an error reaching remote node. Check the logs for more details.`):`Successfully removed '${r}' from manifest`}a(jk,"removeNode")});var YO=h((r2,xO)=>{"use strict";var kO=require("joi"),{string:ex,array:tx}=kO.types(),rx=de(),sx=fc();xO.exports=nx;function nx(e){let t=kO.object({operation:ex.valid("configure_cluster").required(),connections:tx.items(sx.validation_schema).required()});return rx.validateBySchema(e,t)}a(nx,"configureClusterValidator")});var GE=h((s2,XO)=>{"use strict";var ix=T(),Bc=g(),ax=b(),ox=Pc(),cx=Lc(),KO=Cs(),_x=YO(),{handleHDBError:WO,hdb_errors:ux}=D(),{HTTP_STATUS_CODES:QO}=ux,lx="Configure cluster complete.",Ex="Failed to configure the cluster. Check the logs for more details.",dx="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";XO.exports=hx;async function hx(e){Bc.trace("configure cluster called with:",e),KO.checkClusteringEnabled();let t=_x(e);if(t)throw WO(t,t.message,QO.BAD_REQUEST,void 0,void 0,!0);let r=await KO.getAllNodeRecords(),s=[];for(let d=0,S=r.length;d<S;d++)s.push(JO(ox,{operation:ix.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[d].name},r[d].name));let n=await Promise.allSettled(s);Bc.trace("All results from configure_cluster remove node:",n);let i=[],o=e.connections.length;for(let d=0;d<o;d++){let S=e.connections[d];i.push(JO(cx,S,S.node_name))}let c=await Promise.allSettled(i);Bc.trace("All results from configure_cluster add node:",c);let _=[],u=[],l=!1,E=n.concat(c);for(let d=0,S=E.length;d<S;d++){let m=E[d];m.status==="rejected"&&(Bc.error(m.reason),_.includes(m.reason.node_name)||_.push(m.reason.node_name)),m.status==="fulfilled"&&(l=!0);let R=m?.value?.result;typeof R=="string"&&R.includes("Successfully removed")||m.status==="rejected"||u.push({node_name:m?.value?.node_name,subscriptions:m?.value?.result})}if(ax.isEmptyOrZeroLength(_))return{message:lx,connections:u};if(l)return{message:dx,failed_nodes:_,connections:u};throw WO(new Error,Ex,QO.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(hx,"configureCluster");async function JO(e,t,r){try{return{node_name:r,result:await e(t)}}catch(s){throw{node_name:r,error:s}}}a(JO,"functionWrapper")});var $E=h((n2,rN)=>{"use strict";var VE=Cs(),Sx=Rt(),jO=V(),vc=T(),ws=Se(),fx=b(),FE=g(),{RemotePayloadObject:Tx}=Pi(),{ErrorCode:ZO}=require("nats"),zO=jO.get(vc.CONFIG_PARAMS.CLUSTERING_ENABLED),eN=jO.get(vc.CONFIG_PARAMS.CLUSTERING_NODENAME);rN.exports={clusterStatus:mx,buildNodeStatus:tN};async function mx(){let e={node_name:eN,is_enabled:zO,connections:[]};if(!zO)return e;let t=await VE.getAllNodeRecords();if(fx.isEmptyOrZeroLength(t))return e;let r=[];for(let s=0,n=t.length;s<n;s++)r.push(tN(t[s],e.connections));return await Promise.allSettled(r),e}a(mx,"clusterStatus");async function tN(e,t){let r=e.name,s=new Tx(vc.OPERATIONS_ENUM.CLUSTER_STATUS,eN,void 0,await VE.getSystemInfo()),n,i,o=ws.CLUSTER_STATUS_STATUSES.OPEN;try{let _=Date.now();n=await Sx.request(ws.REQUEST_SUBJECT(r),s),i=Date.now()-_,n.status===ws.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=ws.CLUSTER_STATUS_STATUSES.CLOSED,FE.error(`Error getting node status from ${r} `,n))}catch(_){FE.warn(`Error getting node status from ${r}`,_),_.code===ZO.NoResponders?o=ws.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:_.code===ZO.Timeout?o=ws.CLUSTER_STATUS_STATUSES.TIMEOUT:o=ws.CLUSTER_STATUS_STATUSES.CLOSED}let c=new Rx(r,o,n?.message?.ports?.clustering,n?.message?.ports?.operations_api,i,n?.message?.uptime,e.subscriptions,n?.message?.system_info);try{let _={name:r,system_info:n?.message?.system_info};e.system_info?.hdb_version!==vc.PRE_4_0_0_VERSION&&await VE.upsertNodeRecord(_)}catch(_){FE.error("Cluster status encountered an error updating system info for node:",r,_)}t.push(c)}a(tN,"buildNodeStatus");function Rx(e,t,r,s,n,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:s},this.latency_ms=n,this.uptime=i,this.subscriptions=o,this.system_info=c}a(Rx,"NodeStatusObject")});var aN=h((i2,iN)=>{"use strict";var kE=require("joi"),sN=de(),{route_constraints:nN}=_u();iN.exports={setRoutesValidator:Ax,deleteRoutesValidator:px};function Ax(e){let t=kE.object({server:kE.valid("hub","leaf").required(),routes:nN.required()});return sN.validateBySchema(e,t)}a(Ax,"setRoutesValidator");function px(e){let t=kE.object({routes:nN.required()});return sN.validateBySchema(e,t)}a(px,"deleteRoutesValidator")});var YE=h((a2,uN)=>{"use strict";var Us=Er(),xE=b(),Hc=T(),oN=aN(),{handleHDBError:cN,hdb_errors:Ox}=D(),{HTTP_STATUS_CODES:_N}=Ox,Nx="cluster routes successfully set",gx="cluster routes successfully deleted";uN.exports={setRoutes:Ix,getRoutes:bx,deleteRoutes:Cx};function Ix(e){let t=oN.setRoutesValidator(e);if(t)throw cN(t,t.message,_N.BAD_REQUEST,void 0,void 0,!0);let r=Us.getClusteringRoutes(),s=e.server==="hub"?r.hub_routes:r.leaf_routes,n=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,_=e.routes.length;c<_;c++){let u=e.routes[c];u.port=xE.autoCast(u.port);let l=s.some(d=>d.host===u.host&&d.port===u.port),E=n.some(d=>d.host===u.host&&d.port===u.port);l||E?i.push(u):(s.push(u),o.push(u))}return e.server==="hub"?Us.updateConfigValue(Hc.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s):Us.updateConfigValue(Hc.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s),{message:Nx,set:o,skipped:i}}a(Ix,"setRoutes");function bx(){let e=Us.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(bx,"getRoutes");function Cx(e){let t=oN.deleteRoutesValidator(e);if(t)throw cN(t,t.message,_N.BAD_REQUEST,void 0,void 0,!0);let r=Us.getClusteringRoutes(),s=r.hub_routes,n=r.leaf_routes,i=[],o=[],c=!1,_=!1;for(let u=0,l=e.routes.length;u<l;u++){let E=e.routes[u],d=!1;for(let S=0,m=s.length;S<m;S++){let R=s[S];if(E.host===R.host&&E.port===R.port){s.splice(S,1),d=!0,c=!0,i.push(E);break}}if(!d){let S=!0;for(let m=0,R=n.length;m<R;m++){let w=n[m];if(E.host===w.host&&E.port===w.port){n.splice(m,1),_=!0,S=!1,i.push(E);break}}S&&o.push(E)}}return c&&(s=xE.isEmptyOrZeroLength(s)?null:s,Us.updateConfigValue(Hc.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),_&&(n=xE.isEmptyOrZeroLength(n)?null:n,Us.updateConfigValue(Hc.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:gx,deleted:i,skipped:o}}a(Cx,"deleteRoutes")});var EN=h((o2,lN)=>{"use strict";var Fi=require("alasql"),Ls=require("recursive-iterator"),Wt=g(),wx=b(),Vi=T(),qc=class{constructor(t){this.ast=t,this.affected_attributes=new Map,this.table_lookup=new Map,this.schema_lookup=new Map,this.table_to_schema_lookup=new Map,Lx(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(n=>Vi.SEARCH_WILDCARDS.includes(n.columnid));if(r.length===0)return this.ast;let s=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(n=>!Vi.SEARCH_WILDCARDS.includes(n.columnid)),r.forEach(n=>{let i=this.table_to_schema_lookup.has(n.tableid)?this.table_to_schema_lookup.get(n.tableid):s,o=this.table_lookup.has(n.tableid)?this.table_lookup.get(n.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][Vi.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=Ux(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(u=>({attribute_name:u.attribute}));let _=this.affected_attributes.get(i).get(o).filter(u=>!Vi.SEARCH_WILDCARDS.includes(u));c.forEach(({attribute_name:u})=>{let l=new Fi.yy.Column({columnid:u});n.tableid&&(l.tableid=n.tableid),this.ast.columns.push(l),_.includes(u)||_.push(u)}),this.affected_attributes.get(i).set(o,_)}}),this.ast}};a(qc,"sql_statement_bucket");function Ux(e){return e.filter(t=>t[Vi.PERMS_CRUD_ENUM.READ])}a(Ux,"filterReadRestrictedAttrs");function Lx(e,t,r,s,n){yx(e,t,r,s,n)}a(Lx,"interpretAST");function $i(e,t,r,s,n){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),s&&!s.has(e.as)&&s.set(e.as,e.databaseid)),n)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),n.set(o,i)}}a($i,"addSchemaTableToMap");function yx(e,t,r,s,n){if(!e){Wt.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Fi.yy.Insert?Bx(e,t,r):e instanceof Fi.yy.Select?Dx(e,t,r,s,n):e instanceof Fi.yy.Update?Mx(e,t,r):e instanceof Fi.yy.Delete?Px(e,t,r):Wt.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(yx,"getRecordAttributesAST");function Dx(e,t,r,s,n){if(!e){Wt.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(wx.isEmptyOrZeroLength(i)){Wt.error("No schema specified");return}e.from.forEach(c=>{$i(c,t,r,s,n)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),$i(c.table,t,r,s,n)});let o=new Ls(e.columns);for(let{node:c}of o)if(c&&c.columnid){let _=c.tableid,u=s.has(_)?s.get(_):i;if(_||(_=e.from[0].tableid),!t.get(u).has(_))if(r.has(_))_=r.get(_);else{Wt.info(`table specified as ${_} not found.`);return}t.get(u).get(_).indexOf(c.columnid)<0&&t.get(u).get(_).push(c.columnid)}if(e.where){let c=new Ls(e.where),_=e.from[0].tableid;for(let{node:u}of c)if(u&&u.columnid){let l=u.tableid?u.tableid:_;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{Wt.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(u.columnid)<0&&t.get(i).get(l).push(u.columnid)}}if(e.joins&&e.joins.forEach(c=>{let _=new Ls(c.on);for(let{node:u}of _)if(u&&u.columnid){let l=u.tableid,E=n.get(l);if(!t.get(E).has(l))if(r.has(l))l=r.get(l);else{Wt.info(`table specified as ${l} not found.`);continue}t.get(E).get(l).indexOf(u.columnid)<0&&t.get(E).get(l).push(u.columnid)}}),e.order){let c=new Ls(e.order);for(let{node:_}of c)if(_&&_.columnid){let u=_.tableid,l=s.has(u)?s.get(u):i;if(u||(u=e.from[0].tableid),!t.get(l).has(u))if(r.has(u))u=r.get(u);else{Wt.info(`table specified as ${u} not found.`);return}t.get(l).get(u).indexOf(_.columnid)<0&&t.get(l).get(u).push(_.columnid)}}}a(Dx,"getSelectAttributes");function Mx(e,t,r){if(!e){Wt.info("getUpdateAttributes: invalid SQL syntax tree");return}let s=new Ls(e.columns),n=e.table.databaseid;$i(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&KE(e.table.tableid,n,i.columnid,t,r)}a(Mx,"getUpdateAttributes");function Px(e,t,r){if(!e){Wt.info("getDeleteAttributes: invalid SQL syntax tree");return}let s=new Ls(e.where),n=e.table.databaseid;$i(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&KE(e.table.tableid,n,i.columnid,t,r)}a(Px,"getDeleteAttributes");function Bx(e,t,r){if(!e){Wt.info("getInsertAttributes: invalid SQL syntax tree");return}let s=new Ls(e.columns),n=e.into.databaseid;$i(e.into,t,r);for(let{node:i}of s)i&&i.columnid&&KE(e.into.tableid,n,i.columnid,t,r)}a(Bx,"getInsertAttributes");function KE(e,t,r,s,n){if(!s.get(t))return;let i=e;s.get(t).has(i)||(i=n.get(i)),s.get(t).get(i).push(r)}a(KE,"pushAttribute");lN.exports=qc});var SN=h((c2,hN)=>{var vx=require("os"),dN=V();hN.exports={checkPermission:Hx};function Hx(){if(vx.userInfo().username!==dN.get("install_user"))throw new Error(`Error: Must execute as ${dN.get("install_user")}`)}a(Hx,"checkPermission")});var QE=h((_2,AN)=>{var Fc=Ri(),fN=require("chalk"),sr=g(),TN=SN(),mN=require("prompt"),{promisify:qx}=require("util"),Gc=T(),Gx=require("fs-extra"),Fx=require("path"),Vx=b(),$x=yE(),RN=V();RN.initSync();var kx=require("moment"),xx=qx(mN.get),Yx=Fx.join(RN.getHdbBasePath(),Gc.LICENSE_KEY_DIR_NAME,Gc.LICENSE_FILE_NAME,Gc.LICENSE_FILE_NAME);AN.exports={getFingerprint:Wx,setLicense:Kx,parseLicense:WE,register:Qx,getRegistrationInfo:Xx};async function Kx(e){if(e&&e.key&&e.company){try{sr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await WE(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw sr.error(r),sr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(Kx,"setLicense");async function Wx(){try{TN.checkPermission()}catch(t){throw sr.error(t),new Error("You do not have permission to generate a fingerprint.")}let e={};try{e=await Fc.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw sr.error(r),sr.error(t),new Error(r)}return e}a(Wx,"getFingerprint");async function WE(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");console.log("Validating license input...");let r=Fc.validateLicense(e,t);if(console.log("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(console.log("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(console.log(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{sr.info("writing license to disk"),await Gx.writeFile(Yx,JSON.stringify({license_key:e,company:t}))}catch(s){throw sr.error("Failed to write License"),s}return"Registration successful."}a(WE,"parseLicense");async function Qx(){let e=await Jx();return WE(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(Qx,"register");async function Jx(){try{TN.checkPermission()}catch(s){return console.error(s.message)}let e=await Fc.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:fN.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:fN.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{mN.start()}catch(s){sr.error(s)}let r;try{r=await xx(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}a(Jx,"promptForRegistration");async function Xx(){let e={registered:!1,version:null,storage_type:null,ram_allocation:null,license_expiration_date:null},t;try{t=await Fc.getLicense()}catch(r){throw sr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(Vx.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=$x.version(),e.storage_type=Gc.STORAGE_TYPES_ENUM.LMDB,e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=kx.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(Xx,"getRegistrationInfo")});var ON=h((u2,pN)=>{"use strict";var Zx=Se(),Vc=class{constructor(t,r,s,n,i,o,c,_,u,l,E,d,S){this.port=t,o===null&&(o=void 0),this.server_name=r+Zx.SERVER_SUFFIX.HUB,this.pid_file=s,this.max_payload=1e7,this.jetstream={enabled:!1},this.tls={cert_file:n,key_file:i,ca_file:o,insecure:c},this.leafnodes={port:_,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c}},this.cluster={name:u,port:l,routes:E,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c}},this.accounts={SYS:{users:d},HDB:{users:S}},this.system_account="SYS"}};a(Vc,"HubConfigObject");pN.exports=Vc});var IN=h((l2,gN)=>{"use strict";var NN=Se(),$c=class{constructor(t,r,s,n,i,o,c,_,u,l,E){this.port=t,E===null&&(E=void 0),this.server_name=r+NN.SERVER_SUFFIX.LEAF,this.pid_file=s,this.max_payload=1e7,this.jetstream={enabled:!0,store_dir:n,domain:r+NN.SERVER_SUFFIX.LEAF},this.tls={cert_file:u,key_file:l,ca_file:E,insecure:!0},this.leafnodes={remotes:[{tls:{ca_file:E,insecure:!0},urls:i,account:"SYS"},{tls:{ca_file:E,insecure:!0},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:_,jetstream:"enabled"}},this.system_account="SYS"}};a($c,"LeafConfigObject");gN.exports=$c});var CN=h((E2,bN)=>{"use strict";var kc=class{constructor(t,r){this.user=t,this.password=r}};a(kc,"HdbUserObject");bN.exports=kc});var UN=h((d2,wN)=>{"use strict";var zx=Se(),xc=class{constructor(t,r){this.user=t+zx.SERVER_SUFFIX.ADMIN,this.password=r}};a(xc,"SysUserObject");wN.exports=xc});var ZE=h((h2,DN)=>{"use strict";var Un=require("path"),Qc=require("fs-extra"),jx=ON(),eY=IN(),tY=CN(),rY=UN(),JE=Rr(),yn=b(),Mt=Er(),Wc=T(),Yc=Se(),{CONFIG_PARAMS:we}=Wc,Jc=g(),Xc=V(),LN=Fr(),XE=Rt(),Ln="clustering",sY=1e4,yN=5;DN.exports={generateNatsConfig:nY,removeNatsConfig:iY};async function nY(e=!1,t=void 0){Xc.initSync();let r=Xc.get(we.ROOTPATH),s=Un.join(r,Ln,Yc.PID_FILES.HUB),n=Un.join(r,Ln,Yc.PID_FILES.LEAF),i=Un.join(r,Ln,"leaf"),o=Un.join(r,Ln,Yc.NATS_CONFIG_FILES.HUB_SERVER),c=Un.join(r,Ln,Yc.NATS_CONFIG_FILES.LEAF_SERVER),_=Mt.getConfigFromFile(we.CLUSTERING_TLS_CERTIFICATE),u=Mt.getConfigFromFile(we.CLUSTERING_TLS_PRIVATEKEY),l=Mt.getConfigFromFile(we.CLUSTERING_TLS_CERT_AUTH),E=Mt.getConfigFromFile(we.CLUSTERING_TLS_INSECURE),d=Mt.getConfigFromFile(we.CLUSTERING_NODENAME),S=Mt.getConfigFromFile(we.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await XE.checkNATSServerInstalled()||Zc("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let m=await JE.listUsers(),R=Mt.getConfigFromFile(we.CLUSTERING_USER),w=await JE.getClusterUser();(yn.isEmpty(w)||w.active!==!0)&&Zc(`invalid cluster user '${R}'`),e||(await Kc(we.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await Kc(we.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await Kc(we.CLUSTERING_HUBSERVER_NETWORK_PORT),await Kc(we.CLUSTERING_LEAFSERVER_NETWORK_PORT));let U=[],B=[];for(let[la,Lr]of m.entries())Lr.role.role===Wc.ROLE_TYPES_ENUM.CLUSTER_USER&&Lr.active&&(U.push(new rY(Lr.username,LN.decrypt(Lr.hash))),B.push(new tY(Lr.username,LN.decrypt(Lr.hash))));let j=[],{hub_routes:$}=Mt.getClusteringRoutes();if(!yn.isEmptyOrZeroLength($))for(let la of $)j.push(`tls://${w.sys_name_encoded}:${w.uri_encoded_d_hash}@${la.host}:${la.port}`);let J=new jx(Mt.getConfigFromFile(we.CLUSTERING_HUBSERVER_NETWORK_PORT),d,s,_,u,l,E,S,Mt.getConfigFromFile(we.CLUSTERING_HUBSERVER_CLUSTER_NAME),Mt.getConfigFromFile(we.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),j,U,B);t=yn.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===Wc.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await Qc.writeJson(o,J),Jc.trace(`Hub server config written to ${o}`));let ke=`tls://${w.sys_name_encoded}:${w.uri_encoded_d_hash}@0.0.0.0:${S}`,xe=`tls://${w.uri_encoded_name}:${w.uri_encoded_d_hash}@0.0.0.0:${S}`,ua=new eY(Mt.getConfigFromFile(we.CLUSTERING_LEAFSERVER_NETWORK_PORT),d,n,i,[ke],[xe],U,B,_,u,l,E);(t===void 0||t===Wc.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await Qc.writeJson(c,ua),Jc.trace(`Leaf server config written to ${c}`))}a(nY,"generateNatsConfig");async function Kc(e){let t=Xc.get(e);yn.isEmpty(t)&&Zc(`port undefined for '${e}'`),await yn.isPortTaken(t)&&Zc(`'${e}' port '${t}' is is in use by another process, check to see if HarperDB is already running or another process is using this port.`)}a(Kc,"isPortAvailable");function Zc(e){let t=`Error generating clustering config: ${e}`;Jc.error(t),console.error(t),process.exit(1)}a(Zc,"generateNatsConfigError");async function iY(e){let{port:t,config_file:r}=XE.getServerConfig(e),{username:s,decrypt_hash:n}=await JE.getClusterUser(),i=0,o=500;for(;i<yN;){try{let u=await XE.createConnection(t,s,n,!1);if(u.protocol.connected===!0){u.close();break}}catch(u){Jc.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${u}`)}if(i++,i>=yN)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check the ${e} log for further details.`);await yn.async_set_timeout(o*i)}let c="0".repeat(sY),_=Un.join(Xc.get(we.ROOTPATH),Ln,r);await Qc.writeFile(_,c),await Qc.remove(_)}a(iY,"removeNatsConfig")});var jc=h((S2,GN)=>{"use strict";var ne=V(),MN=Ri(),C=T(),zE=Se(),pe=require("path"),{PACKAGE_ROOT:zc}=T(),Ee="/dev/null",Dn=pe.join(zc,"launchServiceScripts"),PN=pe.join(zc,"utility/scripts"),aY=pe.join(PN,C.HDB_RESTART_SCRIPT),BN=pe.resolve(zc,"dependencies",`${process.platform}-${process.arch}`,zE.NATS_BINARY_NAME),qe,Ge;function nr(){(qe===void 0||Ge===void 0)&&(ne.initSync(),qe=ne.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ne.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY))}a(nr,"initLogConfig");function vN(){nr();let e=pe.join(Ge,C.PROCESS_LOG_NAMES.IPC),t={name:C.PROCESS_DESCRIPTORS.IPC,exec_mode:"fork",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.IPC},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:C.SERVICE_SERVERS_CWD.IPC};return qe||(t.out_file=Ee,t.error_file=Ee),{...t,script:C.SERVICE_SERVERS.IPC}}a(vN,"generateIPCServerConfig");function HN(){nr(),ne.initSync(),qe=ne.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ne.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=pe.join(Ge,C.PROCESS_LOG_NAMES.HDB),t=MN.licenseSearch(),r=t.ram_allocation?C.MEM_SETTING_KEY+t.ram_allocation:C.MEM_SETTING_KEY+C.RAM_ALLOCATION_ENUM.DEFAULT,s={name:C.PROCESS_DESCRIPTORS.HDB,script:C.LAUNCH_SERVICE_SCRIPTS.HDB,exec_mode:"cluster",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.HDB},merge_logs:!0,out_file:e,error_file:e,instances:ne.get(C.CONFIG_PARAMS.HTTP_THREADS),node_args:r,cwd:Dn};return qe||(s.out_file=Ee,s.error_file=Ee),s}a(HN,"generateHDBServerConfig");function qN(){nr(),ne.initSync(),qe=ne.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ne.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=pe.join(Ge,C.PROCESS_LOG_NAMES.CUSTOM_FUNCTIONS),t=MN.licenseSearch(),r=t.ram_allocation?C.MEM_SETTING_KEY+t.ram_allocation:C.MEM_SETTING_KEY+C.RAM_ALLOCATION_ENUM.DEFAULT,s={name:C.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS,script:C.LAUNCH_SERVICE_SCRIPTS.CUSTOM_FUNCTIONS,exec_mode:"cluster",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS},merge_logs:!0,out_file:e,error_file:e,instances:ne.get(C.CONFIG_PARAMS.HTTP_THREADS),node_args:r,cwd:Dn};return qe||(s.out_file=Ee,s.error_file=Ee),s}a(qN,"generateCFServerConfig");function oY(){nr(),ne.initSync(),qe=ne.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ne.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=ne.get(C.CONFIG_PARAMS.ROOTPATH),t=pe.join(e,"clustering",zE.NATS_CONFIG_FILES.HUB_SERVER),r=pe.join(Ge,C.PROCESS_LOG_NAMES.CLUSTERING_HUB),s={name:C.PROCESS_DESCRIPTORS.CLUSTERING_HUB,script:BN,args:`-c ${t}`,exec_mode:"fork",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return qe||(s.out_file=Ee,s.error_file=Ee),s}a(oY,"generateNatsHubServerConfig");function cY(){nr(),ne.initSync(),qe=ne.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ne.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=ne.get(C.CONFIG_PARAMS.ROOTPATH),t=pe.join(e,"clustering",zE.NATS_CONFIG_FILES.LEAF_SERVER),r=pe.join(Ge,C.PROCESS_LOG_NAMES.CLUSTERING_LEAF),s={name:C.PROCESS_DESCRIPTORS.CLUSTERING_LEAF,script:BN,args:`-c ${t}`,exec_mode:"fork",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return qe||(s.out_file=Ee,s.error_file=Ee),s}a(cY,"generateNatsLeafServerConfig");function _Y(){nr(),ne.initSync();let e=pe.join(Ge,C.PROCESS_LOG_NAMES.CLUSTERING_INGEST_SERVICE),t={name:C.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE,script:C.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE,exec_mode:"cluster",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:Dn};return qe||(t.out_file=Ee,t.error_file=Ee),t}a(_Y,"generateNatsIngestServiceConfig");function uY(){nr(),ne.initSync();let e=pe.join(Ge,C.PROCESS_LOG_NAMES.CLUSTERING_REPLY_SERVICE),t={name:C.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE,script:C.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,exec_mode:"cluster",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:Dn};return qe||(t.out_file=Ee,t.error_file=Ee),t}a(uY,"generateNatsReplyServiceConfig");function lY(){nr(),ne.initSync();let e=pe.join(Ge,C.PROCESS_LOG_NAMES.CLUSTERING_UPGRADE),t={name:C.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:C.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:Dn,autorestart:!1};return qe||(t.out_file=Ee,t.error_file=Ee),t}a(lY,"generateClusteringUpgradeV4ServiceConfig");function EY(){nr();let e=pe.join(Ge,C.PROCESS_LOG_NAMES.PM2),t={name:C.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.RESTART_HDB},merge_logs:!0,out_file:e,error_file:e,instances:1,autorestart:!1,cwd:PN};return qe||(t.out_file=Ee,t.error_file=Ee),{...t,script:aY}}a(EY,"generateRestart");function dY(e){nr();let t=pe.join(Ge,C.PROCESS_LOG_NAMES.JOBS),r=pe.join(zc,"server/jobs"),s={name:`JOB-${e}`,exec_mode:"fork",env:{[C.PROCESS_NAME_ENV_PROP]:`JOB-${e}`},merge_logs:!0,out_file:t,error_file:t,instances:1,cwd:Dn,autorestart:!1};return qe||(s.out_file=Ee,s.error_file=Ee),{...s,script:pe.join(r,"jobProcess.js")}}a(dY,"generateJobConfig");function hY(){return{apps:[vN(),HN(),qN()]}}a(hY,"generateAllServiceConfigs");GN.exports={generateAllServiceConfigs:hY,generateIPCServerConfig:vN,generateHDBServerConfig:HN,generateCFServerConfig:qN,generateRestart:EY,generateNatsHubServerConfig:oY,generateNatsLeafServerConfig:cY,generateNatsIngestServiceConfig:_Y,generateNatsReplyServiceConfig:uY,generateClusteringUpgradeV4ServiceConfig:lY,generateJobConfig:dY}});var xi=h((f2,XN)=>{"use strict";var P=T(),e_=b(),ki=ZE(),t_=Rt(),SY=Se(),x=require("pm2"),fY=require("fs-extra"),gr=jc(),ut=V(),Ir=g(),TY=jc(),mY=Cs(),RY=require("util"),VN=RY.promisify(require("child_process").exec),$N=require("path");XN.exports={start:ys,stop:s_,reload:xN,restart:YN,list:ed,describe:n_,connect:ir,kill:WN,startAllServices:UY,startService:r_,getUniqueServicesList:td,restartAllServices:LY,stopAllServices:yY,isServiceRegistered:QN,reloadStopStart:jE,restartHdb:KN,deleteProcess:CY,configureLogRotate:PY,startClustering:JN,isHdbRestartRunning:wY,isClusteringRunning:vY,stopClustering:BY,reloadClustering:HY};var{PACKAGE_ROOT:AY}=T(),pY="2.7.0",kN=$N.join(AY,"node_modules/pm2/bin/pm2"),OY="Log rotate installed.",NY="Error installing log rotate.",gY="Log rotate updated.",IY="Error updating log rotate.",bY="The number of HarperDB processes running is different from the settings value. To restart and update the number HarperDB processes running you must stop and then start HarperDB";function ir(){return new Promise((e,t)=>{x.connect((r,s)=>{r&&t(r),e(s)})})}a(ir,"connect");function ys(e){return new Promise(async(t,r)=>{try{await ir()}catch(s){r(s)}x.start(e,(s,n)=>{s&&(x.disconnect(),r(s)),x.disconnect(),t(n)})})}a(ys,"start");function s_(e){return new Promise(async(t,r)=>{try{await ir()}catch(s){r(s)}x.stop(e,(s,n)=>{s&&(x.disconnect(),r(s)),x.delete(e,(i,o)=>{i&&(x.disconnect(),r(s)),x.disconnect(),t(o)})})})}a(s_,"stop");function xN(e){return new Promise(async(t,r)=>{try{await ir()}catch(s){r(s)}x.reload(e,(s,n)=>{s&&(x.disconnect(),r(s)),x.disconnect(),t(n)})})}a(xN,"reload");function YN(e){return new Promise(async(t,r)=>{try{await ir()}catch(s){r(s)}x.restart(e,(s,n)=>{s&&(x.disconnect(),r(s)),x.disconnect(),t(n)})})}a(YN,"restart");function CY(e){return new Promise(async(t,r)=>{try{await ir()}catch(s){r(s)}x.delete(e,(s,n)=>{s&&(x.disconnect(),r(s)),x.disconnect(),t(n)})})}a(CY,"deleteProcess");async function KN(){await ys(TY.generateRestart())}a(KN,"restartHdb");async function wY(){let e=await ed();for(let t in e)if(e[t].name===P.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(wY,"isHdbRestartRunning");function ed(){return new Promise(async(e,t)=>{try{await ir()}catch(r){t(r)}x.list((r,s)=>{r&&(x.disconnect(),t(r)),x.disconnect(),e(s)})})}a(ed,"list");function n_(e){return new Promise(async(t,r)=>{try{await ir()}catch(s){r(s)}x.describe(e,(s,n)=>{s&&(x.disconnect(),r(s)),x.disconnect(),t(n)})})}a(n_,"describe");function WN(){return new Promise(async(e,t)=>{try{await ir()}catch(r){t(r)}x.killDaemon((r,s)=>{r&&(x.disconnect(),t(r)),x.disconnect(),e(s)})})}a(WN,"kill");async function UY(){try{await JN(),await ys(gr.generateAllServiceConfigs())}catch(e){throw x.disconnect(),e}}a(UY,"startAllServices");async function r_(e){try{let t;switch(e=e.toLowerCase(),e){case P.PROCESS_DESCRIPTORS.IPC.toLowerCase():t=gr.generateIPCServerConfig();break;case P.PROCESS_DESCRIPTORS.HDB.toLowerCase():t=gr.generateHDBServerConfig();break;case P.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS.toLowerCase():t=gr.generateCFServerConfig();break;case P.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():t=gr.generateNatsIngestServiceConfig();break;case P.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():t=gr.generateNatsReplyServiceConfig();break;case P.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():t=gr.generateNatsHubServerConfig(),await ys(t),await ki.removeNatsConfig(e);return;case P.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():t=gr.generateNatsLeafServerConfig(),await ys(t),await ki.removeNatsConfig(e);return;case P.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():t=gr.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await ys(t)}catch(t){throw x.disconnect(),t}}a(r_,"startService");async function td(){try{let e=await ed(),t={};for(let r=0,s=e.length;r<s;r++){let n=e[r];t[n.name]===void 0&&(t[n.name]={name:n.name,exec_mode:n.pm2_env.exec_mode})}return t}catch(e){throw x.disconnect(),e}}a(td,"getUniqueServicesList");async function LY(e=[]){try{let t=!1,r=await td();for(let s=0,n=Object.values(r).length;s<n;s++){let i=Object.values(r)[s],o=i.name;e.includes(o)||(i.exec_mode==="cluster_mode"?o===P.PROCESS_DESCRIPTORS.HDB?t=!0:await jE(o):await YN(o))}t&&await jE(P.PROCESS_DESCRIPTORS.HDB)}catch(t){throw x.disconnect(),t}}a(LY,"restartAllServices");async function yY(){try{let e=await td();for(let t=0,r=Object.values(e).length;t<r;t++){let s=Object.values(e)[t];await s_(s.name)}if(await WN(),ut.get(P.CONFIG_PARAMS.OPERATIONSAPI_FOREGROUND)===!0){let t=(await fY.readFile($N.join(ut.get(P.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),P.FOREGROUND_PID_FILE))).toString();try{process.kill(t,"SIGTERM")}catch(r){Ir.warn(`Error terminating foreground process: ${r}`)}}}catch(e){throw x.disconnect(),e}}a(yY,"stopAllServices");async function QN(e){return!e_.isEmptyOrZeroLength(await n_(e))}a(QN,"isServiceRegistered");async function jE(e){let t=e===P.PROCESS_DESCRIPTORS.HDB?ut.get(P.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES):ut.get(P.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES),r=await n_(e),s=e_.isEmptyOrZeroLength(r)?0:r.length;t!==s?e===P.PROCESS_DESCRIPTORS.HDB?Ir.error(bY):(await s_(e),await r_(e)):e===P.PROCESS_DESCRIPTORS.HDB?await KN():await xN(e)}a(jE,"reloadStopStart");function DY(){return new Promise(async(e,t)=>{try{await ir()}catch(r){t(r)}x.stop(P.PROCESS_DESCRIPTORS.PM2_LOGROTATE,(r,s)=>{r&&(x.disconnect(),t(r)),x.disconnect(),e(s)})})}a(DY,"stopLogrotate");async function MY(){let{stdout:e,stderr:t}=await VN(`${process.platform==="win32"?"node":""} ${kN} install pm2-logrotate@${pY}`);if(Ir.debug(`loadLogRotate stdout: ${e}`),t)throw Ir.error(NY),t;Ir.info(OY)}a(MY,"installLogRotate");async function FN(){let e={max_size:ut.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_MAX_SIZE),retain:ut.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_RETAIN),compress:ut.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_COMPRESS),dateFormat:ut.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_DATE_FORMAT),rotateModule:ut.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_ROTATE_MODULE),workerInterval:ut.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_WORKER_INTERVAL),rotateInterval:ut.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_ROTATE_INTERVAL),TZ:ut.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_TIMEZONE)},t="";for(let n in e)t+=`${process.platform==="win32"?"node":""} ${kN} set pm2-logrotate:${n} ${e[n]}`,n!=="TZ"&&(t+=" && ");let{stdout:r,stderr:s}=await VN(t);if(Ir.debug(`updateLogRotateConfig stdout: ${r}`),s)throw Ir.error(IY),s;Ir.info(gY)}a(FN,"updateLogRotateConfig");async function PY(){ut.initSync();let e=e_.autoCastBoolean(ut.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE)),t=await n_(P.PROCESS_DESCRIPTORS.PM2_LOGROTATE),r,s=!1;if(e_.isEmptyOrZeroLength(t)||(s=!0,r=t[0].pm2_env.status),e&&!s){await MY(),await FN();return}if(e&&s){await ys(P.PROCESS_DESCRIPTORS.PM2_LOGROTATE),await FN();return}!e&&r===P.PM2_PROCESS_STATUSES.ONLINE&&await DY()}a(PY,"configureLogRotate");async function JN(){for(let t in P.CLUSTERING_PROCESSES){let r=P.CLUSTERING_PROCESSES[t];await r_(r)}await t_.createWorkQueueStream(SY.WORK_QUEUE_CONSUMER_NAMES),await t_.updateNodeNameLocalStreams();let e=await mY.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===P.PRE_4_0_0_VERSION){Ir.info("Starting clustering upgrade 4.0.0 process"),await r_(P.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0);break}}a(JN,"startClustering");async function BY(){for(let e in P.CLUSTERING_PROCESSES){let t=P.CLUSTERING_PROCESSES[e];await s_(t)}}a(BY,"stopClustering");async function vY(){for(let e in P.CLUSTERING_PROCESSES){let t=P.CLUSTERING_PROCESSES[e];if(await QN(t)===!1)return!1}return!0}a(vY,"isClusteringRunning");async function HY(){await ki.generateNatsConfig(!0),await t_.reloadNATSHub(),await t_.reloadNATSLeaf(),await ki.removeNatsConfig(P.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await ki.removeNatsConfig(P.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(HY,"reloadClustering")});var ad=h((T2,tg)=>{"use strict";var y=T(),K=g(),i_=b(),qY=tu(),rd=ZE(),id=Rt(),GY=Se(),zN=require("minimist"),{handleHDBError:sd,hdb_errors:FY}=D(),Yi=Er(),{HTTP_STATUS_CODES:nd}=FY,G,ZN=`Restarting HarperDB. This may take up to ${y.RESTART_TIMEOUT_MS/1e3} seconds.`,Ds="HarperDB is currently restarting and must complete before another HarperDB restart can be initialized.",VY="Invalid service",$Y="'service' is required",kY="Restarting all services",xY="Clustering is not enabled so cannot be restarted";tg.exports={stop:KY,restartProcesses:YY,restartService:jN};async function YY(){K.createLogFile(y.PROCESS_LOG_NAMES.CLI,y.PROCESS_DESCRIPTORS.STOP);try{G===void 0&&(G=xi());let e=qY(Object.keys(y.CONFIG_PARAM_MAP),!0);i_.isEmptyOrZeroLength(Object.keys(e))||Yi.updateConfigValue(void 0,void 0,e,!0,!0);let t=Yi.getConfigFromFile(y.CONFIG_PARAMS.CLUSTERING_ENABLED),r=Yi.getConfigFromFile(y.CONFIG_PARAMS.CUSTOMFUNCTIONS_ENABLED),s=zN(process.argv);if(!i_.isEmpty(s.service)){if(typeof s.service!="string"){let c=`Restart service argument expected a string but received: ${s.service}`;return K.error(c),c}let o=s.service.split(",");for(let c of o){let _=c.toLowerCase();if(_===y.HDB_PROC_DESCRIPTOR.toLowerCase()&&await G.isHdbRestartRunning()===!0){K.notify(Ds),console.error(Ds);continue}if(y.PROCESS_DESCRIPTORS_VALIDATE[_]===void 0){console.error(`Restart received unrecognized service command argument: ${_}`),K.error(`Restart received unrecognized service command argument: ${_}`);continue}let u=y.PROCESS_DESCRIPTORS_VALIDATE[_];if(console.log(`Restarting ${u}`),K.trace(`Restarting ${u}`),u===y.PROCESS_DESCRIPTORS.PM2_LOGROTATE)await G.configureLogRotate();else if(_.toLowerCase().includes("clustering"))await Mn(_);else if(await G.isServiceRegistered(u))u===y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS&&!r?(await G.stop(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS),K.trace(`Stopping ${y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS}`)):await jN({service:u});else if(u===y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS)if(r)await G.startService(u),K.trace(`Starting ${u}`);else{let l=`${u} is not enabled in harperdb-config.yaml and cannot be restarted.`;K.error(l),console.log(l)}else await G.startService(u);K.notify(`${u} successfully restarted.`)}return}if(await G.isHdbRestartRunning()===!0)return K.notify(Ds),console.error(Ds),Ds;console.log(ZN),t&&await eg();let n=await G.isServiceRegistered(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS);r&&!n&&(await G.startService(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS),K.trace(`Starting ${y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS}`));let i=[y.PROCESS_DESCRIPTORS.CLUSTERING_HUB,y.PROCESS_DESCRIPTORS.CLUSTERING_LEAF,y.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE,y.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE];return!r&&n&&(i.push(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS),await G.stop(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS),K.trace(`Stopping ${y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS}`)),await G.configureLogRotate(),K.notify(kY),await G.restartAllServices(i),ZN}catch(e){let t=`There was an error restarting HarperDB. ${e}`;return K.error(t),t}}a(YY,"restartProcesses");async function jN(e){if(K.createLogFile(y.PROCESS_LOG_NAMES.CLI,y.PROCESS_DESCRIPTORS.STOP),G===void 0&&(G=xi()),i_.isEmpty(e.service))throw sd(new Error,$Y,nd.BAD_REQUEST,void 0,void 0,!0);let t=e.service.toLowerCase();if(y.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw sd(new Error,VY,nd.BAD_REQUEST,void 0,void 0,!0);let r=Yi.getConfigFromFile(y.CONFIG_PARAMS.CUSTOMFUNCTIONS_ENABLED),s=y.PROCESS_DESCRIPTORS_VALIDATE[t];if(s===y.PROCESS_DESCRIPTORS.HDB){if(await G.isHdbRestartRunning()===!0)return K.notify(Ds),Ds;await G.reloadStopStart(s)}else if(s===y.PROCESS_DESCRIPTORS.PM2_LOGROTATE)await G.configureLogRotate();else if(s.toLowerCase().includes("clustering"))await Mn(s);else if(s===y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS||s===y.SERVICES.CUSTOM_FUNCTIONS){let i=await G.isServiceRegistered(s);if(r)i?(await G.reloadStopStart(s),K.trace(`Reloading ${s}`)):(await G.startService(s),K.trace(`Starting ${s}`));else if(!r&&i)await G.stop(s),K.trace(`Stopping ${s}`);else{let o=`${s} is not enabled in harperdb-config.yaml and cannot be restarted.`;throw K.error(o),sd(new Error,o,nd.BAD_REQUEST,void 0,void 0,!0)}}else await G.restart(s);let n=`Restarting ${s}`;return K.notify(n),n}a(jN,"restartService");async function KY(){K.createLogFile(y.PROCESS_LOG_NAMES.CLI,y.PROCESS_DESCRIPTORS.STOP);try{G===void 0&&(G=xi());let e=zN(process.argv);if(i_.isEmpty(e.service))console.log("Stopping HarperDB."),await G.stopAllServices(),K.notify("HarperDB has stopped");else{if(typeof e.service!="string"){let r=`Stop service argument expected a string but received: ${e.service}`;K.error(r),console.log(r)}let t=e.service.split(",");for(let r of t){let s=r.toLowerCase();if(y.PROCESS_DESCRIPTORS_VALIDATE[s]===void 0){K.error(`Stop received unrecognized service command argument: ${s}`);continue}s==="clustering"?await G.stopClustering():await G.stop(y.PROCESS_DESCRIPTORS_VALIDATE[s]);let n=`${y.PROCESS_DESCRIPTORS_VALIDATE[s]} successfully stopped.`;K.notify(n),console.log(n)}}}catch(e){throw console.error(e),e}}a(KY,"stop");async function eg(){await Mn(y.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Mn(y.PROCESS_DESCRIPTORS.CLUSTERING_LEAF),await Mn(y.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE),await Mn(y.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE),await id.updateNodeNameLocalStreams(),await id.closeConnection()}a(eg,"restartAllClusteringServices");async function Mn(e){e=y.PROCESS_DESCRIPTORS_VALIDATE[e.toLowerCase()];let t=Yi.getConfigFromFile(y.CONFIG_PARAMS.CLUSTERING_ENABLED),r=e==="clustering",s=e==="clustering config",n=r?void 0:await G.isServiceRegistered(e),i=r||s?await G.isClusteringRunning():void 0;switch(!0){case s:if(!i){K.error(xY);break}await G.reloadClustering();break;case(r&&i&&!t):await G.stopClustering();break;case(r&&!i&&t):await G.startClustering();break;case(r&&i&&t):await eg();break;case(r&&!i&&!t):K.error(`${e} is not enabled in harperdb-config.yaml and cannot be restarted.`);break;case(n&&!t):await G.stop(e),K.trace(`Stopping ${e}`);break;case(!n&&t):e!==y.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE&&e!==y.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE&&await rd.generateNatsConfig(!0,e),await G.startService(e),K.trace(`Starting ${e}`),e===y.PROCESS_DESCRIPTORS.CLUSTERING_LEAF&&await id.createWorkQueueStream(GY.WORK_QUEUE_CONSUMER_NAMES);break;case(!n&&!t):K.error(`${e} is not enabled in harperdb-config.yaml and cannot be restarted.`);break;case(n&&t):e===y.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE||e===y.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE?await G.reload(e):(await rd.generateNatsConfig(!0,e),await G.restart(e),await rd.removeNatsConfig(e));break;default:K.error(`Error restarting ${e}`)}}a(Mn,"restartClustering")});var Eg=h((R2,lg)=>{"use strict";var m2=require("lodash"),ze=T(),{handleHDBError:rg,hdb_errors:WY}=D(),{HDB_ERROR_MSGS:QY,HTTP_STATUS_CODES:JY}=WY,od=g();lg.exports={getRolePermissions:ZY};var Ms=Object.create(null),XY=a(e=>({key:e,perms:{}}),"perms_template_obj"),ag=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),og=a((e=!1,t=!1,r=!1,s=!1)=>({[ze.PERMS_CRUD_ENUM.READ]:e,[ze.PERMS_CRUD_ENUM.INSERT]:t,[ze.PERMS_CRUD_ENUM.UPDATE]:r,[ze.PERMS_CRUD_ENUM.DELETE]:s}),"permissions_template"),cd=a((e=!1,t=!1,r=!1,s=!1,n=!1)=>({attribute_permissions:[],describe:e,...og(t,r,s,n)}),"table_perms_template"),sg=a((e,t=og())=>({attribute_name:e,describe:ug(t),[Ki]:t[Ki],[_d]:t[_d],[ud]:t[ud]}),"attr_perms_template"),ng=a((e,t=!1)=>({attribute_name:e,describe:t,[Ki]:t}),"timestamp_attr_perms_template"),{READ:Ki,INSERT:_d,UPDATE:ud}=ze.PERMS_CRUD_ENUM,cg=Object.values(ze.PERMS_CRUD_ENUM),_g=[Ki,_d,ud];function ZY(e){let t;try{if(e.permission.super_user||e.permission.cluster_user)return e.permission;let r=Object.assign({},global.hdb_schema);delete r[ze.SYSTEM_SCHEMA_NAME],t=e.role;let s=JSON.stringify([e.__updatedtime__,r]);if(Ms[t]&&Ms[t].key===s)return Ms[t].perms;let n=zY(e,r);return Ms[t]?Ms[t].key=s:Ms[t]=XY(s),Ms[t].perms=n,n}catch(r){if(!e[ze.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[ze.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<ze.PERMS_UPDATE_RELEASE_TIMESTAMP){let s=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw od.error(s),od.debug(r),rg(new Error,QY.OUTDATED_PERMS_TRANSLATION_ERROR,JY.BAD_REQUEST)}else{let s=`There was an error while translating role permissions for role: ${t}.
8
+ ${r.stack}`;throw od.error(s),rg(new Error)}}}a(ZY,"getRolePermissions");function zY(e,t){let r=Object.create(null);r.super_user=!1;let s=e.permission;r[ze.SYSTEM_SCHEMA_NAME]=s[ze.SYSTEM_SCHEMA_NAME],r.structure_user=s.structure_user;let n=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(n===!0||n.indexOf(i)>-1){r[i]=jY(t[i]);return}r[i]=ag(),s[i]?Object.keys(t[i]).forEach(o=>{if(s[i].tables[o]){let c=s[i].tables[o],_=t[i][o],u=eK(c,_);r[i].describe||cg.forEach(l=>{u[l]&&(r[i].describe=!0)}),r[i].tables[o]=u}else r[i].tables[o]=cd()}):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=cd()})}),r}a(zY,"translateRolePermissions");function jY(e){let t=ag(!0);return Object.keys(e).forEach(r=>{t.tables[r]=cd(!0,!0,!0,!0,!0)}),t}a(jY,"createStructureUserPermissions");function eK(e,t){let{attribute_permissions:r}=e;if(r.length>0){let n=Object.assign({},e);n.attribute_permissions=[];let i=r.reduce((u,l)=>{let{attribute_name:E}=l,d=l;return ze.TIME_STAMP_NAMES.includes(E)&&(d=ng(E,l[Ki])),u[E]=d,u},{}),o=t[ze.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_HASH_ATTRIBUTE_KEY],c=!!i[o],_=sg(o);return t.attributes.forEach(({attribute:u})=>{if(i[u]){let l=i[u];l.describe=ug(l),n.attribute_permissions.push(l),c||tK(l,_)}else if(u!==o){let l;ze.TIME_STAMP_NAMES.includes(u)?l=ng(u):l=sg(u),n.attribute_permissions.push(l)}}),c||n.attribute_permissions.push(_),n.describe=ig(n),n}else return e.describe=ig(e),e}a(eK,"getTableAttrPerms");function ig(e){return cg.filter(t=>e[t]).length>0}a(ig,"getSchemaTableDescribePerm");function ug(e){return _g.filter(t=>e[t]).length>0}a(ug,"getAttributeDescribePerm");function tK(e,t){_g.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(tK,"checkForHashPerms")});var Rg=h((A2,mg)=>{"use strict";var me=require("joi"),dg=require("fs-extra"),hg=require("path"),Pn=de(),Sg=V(),fg=T(),Tg=g(),{hdb_errors:rK}=D(),{HDB_ERROR_MSGS:lt}=rK,jr=/^[a-zA-Z0-9-_]+$/;mg.exports={getDropCustomFunctionValidator:nK,setCustomFunctionValidator:iK,addCustomFunctionProjectValidator:aK,dropCustomFunctionProjectValidator:oK,packageCustomFunctionProjectValidator:cK,deployCustomFunctionProjectValidator:_K};function Wi(e,t,r){try{let s=Sg.get(fg.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),n=hg.join(s,t);return dg.existsSync(n)?e?t:r.message(lt.PROJECT_EXISTS):e?r.message(lt.NO_PROJECT):t}catch(s){return Tg.error(s),r.message(lt.VALIDATION_ERR)}}a(Wi,"checkProjectExists");function sK(e,t,r,s){try{let n=Sg.get(fg.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),i=hg.join(n,e,t,r+".js");return dg.existsSync(i)?r:s.message(lt.NO_FILE)}catch(n){return Tg.error(n),s.message(lt.VALIDATION_ERR)}}a(sK,"checkFileExists");function nK(e){let t=me.object({project:me.string().pattern(jr).custom(Wi.bind(null,!0)).required().messages({"string.pattern.base":lt.BAD_PROJECT_NAME}),type:me.string().valid("helpers","routes").required(),file:me.string().pattern(jr).custom(sK.bind(null,e.project,e.type)).required().messages({"string.pattern.base":lt.BAD_FILE_NAME})});return Pn.validateBySchema(e,t)}a(nK,"getDropCustomFunctionValidator");function iK(e){let t=me.object({project:me.string().pattern(jr).custom(Wi.bind(null,!0)).required().messages({"string.pattern.base":lt.BAD_PROJECT_NAME}),type:me.string().valid("helpers","routes").required(),file:me.string().pattern(jr).required().messages({"string.pattern.base":lt.BAD_FILE_NAME}),function_content:me.string().required()});return Pn.validateBySchema(e,t)}a(iK,"setCustomFunctionValidator");function aK(e){let t=me.object({project:me.string().pattern(jr).custom(Wi.bind(null,!1)).required().messages({"string.pattern.base":lt.BAD_PROJECT_NAME})});return Pn.validateBySchema(e,t)}a(aK,"addCustomFunctionProjectValidator");function oK(e){let t=me.object({project:me.string().pattern(jr).custom(Wi.bind(null,!0)).required().messages({"string.pattern.base":lt.BAD_PROJECT_NAME})});return Pn.validateBySchema(e,t)}a(oK,"dropCustomFunctionProjectValidator");function cK(e){let t=me.object({project:me.string().pattern(jr).custom(Wi.bind(null,!0)).required().messages({"string.pattern.base":lt.BAD_PROJECT_NAME}),skip_node_modules:me.boolean()});return Pn.validateBySchema(e,t)}a(cK,"packageCustomFunctionProjectValidator");function _K(e){let t=me.object({project:me.string().pattern(jr).required().messages({"string.pattern.base":lt.BAD_PROJECT_NAME}),payload:me.string().required().messages({"string.pattern.base":lt.BAD_PACKAGE})});return Pn.validateBySchema(e,t)}a(_K,"deployCustomFunctionProjectValidator")});var dd=h((p2,Og)=>{"use strict";var Ue=require("fs-extra"),a_=require("fast-glob"),ie=require("path"),Ag=require("tar-fs"),pg=require("uuid").v4,Qi=require("normalize-path"),Ps=Rg(),Le=g(),At=T(),pt=V(),{PACKAGE_ROOT:uK}=T(),{handleHDBError:je,hdb_errors:lK}=D(),{HDB_ERROR_MSGS:es,HTTP_STATUS_CODES:et}=lK,EK=ie.join(uK,"custom_function_template"),ld=ie.join(pt.get(At.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function Ed(){let e=pt.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY);if(!(e==="true"||e===!0||e==="TRUE"))throw je(new Error,es.NOT_ENABLED,et.BAD_REQUEST,void 0,void 0,!0)}a(Ed,"isCFEnabled");function dK(){Le.trace("getting custom api status");let e={};try{e={is_enabled:pt.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY),port:pt.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY),directory:pt.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY)}}catch(t){throw je(new Error,es.FUNCTION_STATUS,et.INTERNAL_SERVER_ERROR,Le.ERR,t)}return e}a(dK,"customFunctionsStatus");function hK(){Le.trace("getting custom api endpoints");let e={},t=pt.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY);try{a_.sync(Qi(`${t}/*`),{onlyDirectories:!0}).forEach(s=>{let n=s.split("/").pop();e[n]={routes:a_.sync(Qi(`${s}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:a_.sync(Qi(`${s}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),static:Ue.existsSync(Qi(`${s}/static`))&&a_.sync(Qi(`${s}/static/**/*`)).length}})}catch(r){throw je(new Error,es.GET_FUNCTIONS,et.INTERNAL_SERVER_ERROR,Le.ERR,r)}return e}a(hK,"getCustomFunctions");function SK(e){e.project&&(e.project=ie.parse(e.project).name),e.file&&(e.file=ie.parse(e.file).name);let t=Ps.getDropCustomFunctionValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("getting custom api endpoint file content");let r=pt.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e,o=ie.join(r,s,n,i+".js");try{return Ue.readFileSync(o,{encoding:"utf8"})}catch(c){throw je(new Error,es.GET_FUNCTION,et.INTERNAL_SERVER_ERROR,Le.ERR,c)}}a(SK,"getCustomFunction");function fK(e){Ed(),e.project&&(e.project=ie.parse(e.project).name),e.file&&(e.file=ie.parse(e.file).name);let t=Ps.setCustomFunctionValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("setting custom function file content");let r=pt.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i,function_content:o}=e;try{return Ue.outputFileSync(ie.join(r,s,n,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw je(new Error,es.SET_FUNCTION,et.INTERNAL_SERVER_ERROR,Le.ERR,c)}}a(fK,"setCustomFunction");function TK(e){e.project&&(e.project=ie.parse(e.project).name),e.file&&(e.file=ie.parse(e.file).name);let t=Ps.getDropCustomFunctionValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("dropping custom function file");let r=pt.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e;try{return Ue.unlinkSync(ie.join(r,s,n,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw je(new Error,es.DROP_FUNCTION,et.INTERNAL_SERVER_ERROR,Le.ERR,o)}}a(TK,"dropCustomFunction");function mK(e){Ed(),e.project&&(e.project=ie.parse(e.project).name);let t=Ps.addCustomFunctionProjectValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("adding custom function project");let r=pt.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;try{let n=ie.join(r,s);return Ue.mkdirSync(n,{recursive:!0}),Ue.copySync(EK,n),`Successfully created custom function project: ${s}`}catch(n){throw je(new Error,es.ADD_FUNCTION,et.INTERNAL_SERVER_ERROR,Le.ERR,n)}}a(mK,"addCustomFunctionProject");function RK(e){e.project&&(e.project=ie.parse(e.project).name);let t=Ps.dropCustomFunctionProjectValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("dropping custom function project");let r=pt.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;try{let n=ie.join(r,s);return Ue.rmSync(n,{recursive:!0}),`Successfully deleted project: ${s}`}catch(n){throw je(new Error,es.DROP_FUNCTION_PROJECT,et.INTERNAL_SERVER_ERROR,Le.ERR,n)}}a(RK,"dropCustomFunctionProject");async function AK(e){e.project&&(e.project=ie.parse(e.project).name);let t=Ps.packageCustomFunctionProjectValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("packaging custom function project");let r=pt.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e,n=ie.join(r,s),i=pg();if(!Ue.existsSync(n)){let l=`Unable to locate custom function project: ${s}`;throw Le.error(l),l}Ue.ensureDirSync(ld);let c=ie.join(ld,`${i}.tar`),_={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(_={ignore:l=>l.includes(ie.join(n,"node_modules"))}),Ag.pack(n,_).pipe(Ue.createWriteStream(c)),await new Promise(l=>setTimeout(l,2e3));let u=Ue.readFileSync(c,{encoding:"base64"});return Ue.unlinkSync(c),{project:s,payload:u,file:c}}a(AK,"packageCustomFunctionProject");async function pK(e){Ed(),e.project&&(e.project=ie.parse(e.project).name);let t=Ps.deployCustomFunctionProjectValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("deploying custom function project");let r=pt.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,payload:n,file:i}=e,o=ie.join(r,s);await Ue.ensureDir(o);let c,_;do c=ie.join(ld,pg()+".tar"),_=await Ue.pathExists(c);while(_);await Ue.outputFile(c,n,{encoding:"base64"});let u=Ue.createReadStream(c);return u.pipe(Ag.extract(o)),await new Promise(l=>u.on("end",l)),await Ue.unlink(c),`Successfully deployed project: ${s}`}a(pK,"deployCustomFunctionProject");Og.exports={customFunctionsStatus:dK,getCustomFunctions:hK,getCustomFunction:SK,setCustomFunction:fK,dropCustomFunction:TK,addCustomFunctionProject:mK,dropCustomFunctionProject:RK,packageCustomFunctionProject:AK,deployCustomFunctionProject:pK}});var hd=h((O2,gg)=>{"use strict";var ar=require("joi"),Ng=de();gg.exports={readTransactionLogValidator:OK,deleteTransactionLogsBeforeValidator:NK};function OK(e){let t=ar.object({schema:ar.string().required(),table:ar.string().required(),from:ar.date().timestamp(),to:ar.date().timestamp(),limit:ar.number().min(1)});return Ng.validateBySchema(e,t)}a(OK,"readTransactionLogValidator");function NK(e){let t=ar.object({schema:ar.string().required(),table:ar.string().required(),timestamp:ar.date().timestamp().required()});return Ng.validateBySchema(e,t)}a(NK,"deleteTransactionLogsBeforeValidator")});var c_=h((N2,Ug)=>{"use strict";var Sd=T(),o_=Rt(),Ig=b(),bg=V(),Cg=Fr(),{handleHDBError:Bn,hdb_errors:gK}=D(),{HTTP_STATUS_CODES:vn}=gK,{readTransactionLogValidator:IK,deleteTransactionLogsBeforeValidator:bK}=hd(),wg="This operation relies on clustering and cannot run with it disable.",CK="Logs successfully deleted from transaction log.",wK="All logs successfully deleted from transaction log.";Ug.exports={readTransactionLog:UK,deleteTransactionLogsBefore:LK};async function UK(e){let t=IK(e);if(t)throw Bn(t,t.message,vn.BAD_REQUEST,void 0,void 0,!0);if(!bg.get(Sd.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Bn(new Error,wg,vn.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s}=e,n=Ig.checkSchemaTableExist(r,s);if(n)throw Bn(new Error,n,vn.NOT_FOUND,void 0,void 0,!0);let i=Cg.createNatsTableStreamName(r,s),o=await o_.viewStream(i,parseInt(e.from),e.limit),c=[];for(let _=0,u=o.length;_<u;_++){let l=o[_],E=Math.floor(l?.nats_timestamp/1e6);if(e.to&&E>e.to)break;let d={operation:l?.entry?.operation,user:l?.entry?.__origin?.user,timestamp:E,records:l?.entry?.records};l?.entry?.operation===Sd.OPERATIONS_ENUM.DELETE&&(d.hash_values=l?.entry?.hash_values),c.push(d)}return c}a(UK,"readTransactionLog");async function LK(e){let t=bK(e);if(t)throw Bn(t,t.message,vn.BAD_REQUEST,void 0,void 0,!0);if(!bg.get(Sd.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Bn(new Error,wg,vn.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s,timestamp:n}=e,i=Ig.checkSchemaTableExist(r,s);if(i)throw Bn(new Error,i,vn.NOT_FOUND,void 0,void 0,!0);let o=Cg.createNatsTableStreamName(r,s),{jsm:c}=await o_.getNATSReferences(),_=await o_.getStreamInfo(o),u=new Date(_.state.first_ts).getTime();if(n<=u)return`No transactions exist before: ${n}`;let l=CK,E,d=new Date(_.state.last_ts).getTime();return n>d?(E=_.state.last_seq+1,l=wK):E=(await o_.viewStream(o,parseInt(n),1))[0].nats_sequence,await c.streams.purge(o,{seq:E}),l}a(LK,"deleteTransactionLogsBefore")});var Td=h((g2,Gg)=>{"use strict";var __=require("joi"),u_=require("path"),Lg=require("fs-extra"),{exec:yK}=require("child_process"),DK=require("util"),yg=DK.promisify(yK),MK=T(),{handleHDBError:Hn,hdb_errors:PK}=D(),{HTTP_STATUS_CODES:qn}=PK,Dg=V(),BK=de(),l_=g();Dg.initSync();var fd=Dg.get(MK.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),Mg="npm install --omit=dev --json",vK=`${Mg} --dry-run`;Gg.exports={installModules:HK,auditModules:qK};async function Pg(e,t=void 0){let{stdout:r,stderr:s}=await yg(e,{cwd:t});if(s)throw new Error(s.replace(`
9
9
  `,""));return r.replace(`
10
- `,"")}a(Gg,"runCommand");async function jK(e){d_.info(`starting installModules for request: ${e}`);let t=xg(e);if(t)throw Fn(t,t.message,Vn.BAD_REQUEST);let{projects:r,dry_run:s}=e,n=s===!0?zK:qg;await Vg(),await kg(r);let i={};for(let o=0,c=r.length;o<c;o++){let _=r[o];i[_]={npm_output:null,npm_error:null};let u=E_.join(Rd,_),l,E=null;try{let{stdout:d,stderr:S}=await vg(n,{cwd:u});l=d?d.replace(`
10
+ `,"")}a(Pg,"runCommand");async function HK(e){l_.info(`starting installModules for request: ${e}`);let t=qg(e);if(t)throw Hn(t,t.message,qn.BAD_REQUEST);let{projects:r,dry_run:s}=e,n=s===!0?vK:Mg;await vg(),await Hg(r);let i={};for(let o=0,c=r.length;o<c;o++){let _=r[o];i[_]={npm_output:null,npm_error:null};let u=u_.join(fd,_),l,E=null;try{let{stdout:d,stderr:S}=await yg(n,{cwd:u});l=d?d.replace(`
11
11
  `,""):null,E=S?S.replace(`
12
- `,""):null}catch(d){d.stderr?i[_].npm_error=Fg(d.stderr):i[_].npm_error=d.message;continue}try{i[_].npm_output=JSON.parse(l)}catch{i[_].npm_output=l}try{i[_].npm_error=JSON.parse(E)}catch{i[_].npm_error=E}}return d_.info(`finished installModules with response ${i}`),i}a(jK,"installModules");function Fg(e){let t='"error": {',r=e.indexOf('"error": {'),s=e.indexOf(`}
13
- `);return r>-1&&s>-1?JSON.parse(e.substring(r+t.length-1,s+1)):e}a(Fg,"parseNPMStdErr");async function eQ(e){d_.info(`starting auditModules for request: ${e}`);let t=xg(e);if(t)throw Fn(t,t.message,Vn.BAD_REQUEST);let{projects:r}=e;await Vg(),await kg(r);let s={};for(let n=0,i=r.length;n<i;n++){let o=r[n],c=E_.join(Rd,o);s[o]={npm_output:null,npm_error:null};try{let _=await Gg("npm audit --json",c);s[o].npm_output=JSON.parse(_)}catch(_){s[o].npm_error=Fg(_.stderr)}}return d_.info(`finished auditModules with response ${s}`),s}a(eQ,"auditModules");async function Vg(){try{return await Gg("npm -v"),!0}catch{throw Fn(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",Vn.BAD_REQUEST,void 0,void 0,!0)}}a(Vg,"checkNPMInstalled");async function kg(e){if(!Array.isArray(e)||e.length===0)throw Fn(new Error,"projects argument must be an array with at least 1 element",Vn.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s],o=E_.join(Rd,i.toString());if(!await Bg.pathExists(o)){t.push(i);continue}let _=E_.join(o,"package.json");await Bg.pathExists(_)||r.push(i)}if(t.length>0)throw Fn(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,Vn.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Fn(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,Vn.BAD_REQUEST,void 0,void 0,!0)}a(kg,"checkProjectPaths");function xg(e){let t=l_.object({projects:l_.array().min(1).items(l_.string()).required(),dry_run:l_.boolean().default(!1)});return XK.validateBySchema(e,t)}a(xg,"modulesValidator")});var Kg=h((k2,Yg)=>{"use strict";var h_=class{constructor(t,r,s=[],n=[]){this.schema=t,this.table=r,this.required_table_permissions=s,this.required_attribute_permissions=n}};a(h_,"PermissionTableResponseObject");Yg.exports=h_});var Wg=h((x2,Qg)=>{"use strict";var S_=class{constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};a(S_,"PermissionAttributeResponseObject");Qg.exports=S_});var pd=h(($2,Zg)=>{"use strict";var Jg=Kg(),tQ=Wg(),{HDB_ERROR_MSGS:rQ}=Qe(),f_=class{constructor(){this.error=rQ.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,s){if(r&&s){let n=`${r}_${s}`;if(this.unauthorized_access[n])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,s){let n=new Jg(t,r,s),i=`${t}_${r}`;this.unauthorized_access[i]=n}addUnauthorizedAttributes(t,r,s,n){let i=[];t.forEach(c=>{let _=new tQ(c,n[c]);i.push(_)});let o=`${r}_${s}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new Jg(r,s,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};a(f_,"PermissionResponseObject");Zg.exports=f_});var A_=h((Y2,lI)=>{"use strict";var Od=yt(),T_=mt(),vt=Ec(),ji=ms(),Nd=ps(),sQ=EE(),ea=gr(),m_=pE(),Oe=g(),nQ=gE(),iQ=Dc(),aQ=VE(),oQ=vc(),cQ=kE(),_Q=YE(),gd=WE(),Lr=b(),uQ=TN(),Id=XE(),jg=_d(),Bt=T(),eI=Tg(),lQ=wc(),tI=nc(),rI=Tr(),yr=fd(),EQ=require("alasql"),sI=u_(),nI=Ad(),iI=pd(),{handleHDBError:dt,hdb_errors:aI}=D(),{HDB_ERROR_MSGS:Fe,HTTP_STATUS_CODES:Xi}=aI,p=new Map,oI="delete",is="insert",ur="read",qs="update",zi="describe",Xg=ji.describeSchema.name,zg=ji.describeTable.name,cI={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},dQ="catchup",hQ="handleGetJob",SQ="handleGetJobsByStartDate",R_={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},fQ=[vt.createTable.name,vt.createAttribute.name,vt.dropTable.name,vt.dropAttribute.name],_I={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},O=class{constructor(t,r){this.requires_su=t,this.perms=r}};a(O,"permission");p.set(Od.insert.name,new O(!1,[is]));p.set(Od.update.name,new O(!1,[qs]));p.set(Od.upsert.name,new O(!1,[is,qs]));p.set(T_.searchByConditions.name,new O(!1,[ur]));p.set(T_.searchByHash.name,new O(!1,[ur]));p.set(T_.searchByValue.name,new O(!1,[ur]));p.set(T_.search.name,new O(!1,[ur]));p.set(vt.createSchema.name,new O(!0,[]));p.set(vt.createTable.name,new O(!0,[]));p.set(vt.createAttribute.name,new O(!1,[is]));p.set(vt.dropSchema.name,new O(!0,[]));p.set(vt.dropTable.name,new O(!0,[]));p.set(vt.dropAttribute.name,new O(!0,[]));p.set(ji.describeSchema.name,new O(!1,[ur]));p.set(ji.describeTable.name,new O(!1,[ur]));p.set(Nd.deleteRecord.name,new O(!1,[oI]));p.set(ea.addUser.name,new O(!0,[]));p.set(ea.alterUser.name,new O(!0,[]));p.set(ea.dropUser.name,new O(!0,[]));p.set(ea.listUsersExternal.name,new O(!0,[]));p.set(m_.listRoles.name,new O(!0,[]));p.set(m_.addRole.name,new O(!0,[]));p.set(m_.alterRole.name,new O(!0,[]));p.set(m_.dropRole.name,new O(!0,[]));p.set(nQ.name,new O(!0,[]));p.set(iQ.name,new O(!0,[]));p.set(aQ.name,new O(!0,[]));p.set(oQ.name,new O(!0,[]));p.set(cQ.name,new O(!0,[]));p.set(gd.setRoutes.name,new O(!0,[]));p.set(gd.getRoutes.name,new O(!0,[]));p.set(gd.deleteRoutes.name,new O(!0,[]));p.set(rI.setConfiguration.name,new O(!0,[]));p.set(_Q.clusterStatus.name,new O(!0,[]));p.set(Id.getFingerprint.name,new O(!0,[]));p.set(Id.setLicense.name,new O(!0,[]));p.set(Nd.deleteFilesBefore.name,new O(!0,[]));p.set(Nd.deleteAuditLogsBefore.name,new O(!0,[]));p.set(jg.restartProcesses.name,new O(!0,[]));p.set(jg.restartService.name,new O(!0,[]));p.set(sQ.name,new O(!0,[]));p.set(lQ.systemInformation.name,new O(!0,[]));p.set(rI.getConfiguration.name,new O(!0,[]));p.set(sI.readTransactionLog.name,new O(!0,[]));p.set(sI.deleteTransactionLogsBefore.name,new O(!0,[]));p.set(nI.installModules.name,new O(!0,[]));p.set(nI.auditModules.name,new O(!0,[]));p.set(tI.createTokens.name,new O(!1,[]));p.set(tI.refreshOperationToken.name,new O(!1,[]));p.set(yr.customFunctionsStatus.name,new O(!0,[]));p.set(yr.getCustomFunctions.name,new O(!0,[]));p.set(yr.getCustomFunction.name,new O(!0,[]));p.set(yr.setCustomFunction.name,new O(!0,[]));p.set(yr.dropCustomFunction.name,new O(!0,[]));p.set(yr.addCustomFunctionProject.name,new O(!0,[]));p.set(yr.dropCustomFunctionProject.name,new O(!0,[]));p.set(yr.packageCustomFunctionProject.name,new O(!0,[]));p.set(yr.deployCustomFunctionProject.name,new O(!0,[]));p.set(Id.getRegistrationInfo.name,new O(!1,[]));p.set(ea.userInfo.name,new O(!1,[]));p.set(ji.describeAll.name,new O(!1,[]));p.set(hQ,new O(!1,[]));p.set(SQ,new O(!0,[]));p.set(dQ,new O(!0,[]));p.set(R_.CSV_DATA_LOAD,new O(!1,[is,qs]));p.set(R_.CSV_URL_LOAD,new O(!1,[is,qs]));p.set(R_.CSV_FILE_LOAD,new O(!1,[is,qs]));p.set(R_.IMPORT_FROM_S3,new O(!1,[is,qs]));p.set(_I.EXPORT_TO_S3,new O(!1,[ur]));p.set(_I.EXPORT_LOCAL,new O(!1,[ur]));p.set(Bt.VALID_SQL_OPS_ENUM.DELETE,new O(!1,[oI]));p.set(Bt.VALID_SQL_OPS_ENUM.SELECT,new O(!1,[ur]));p.set(Bt.VALID_SQL_OPS_ENUM.INSERT,new O(!1,[is]));p.set(Bt.VALID_SQL_OPS_ENUM.UPDATE,new O(!1,[qs]));lI.exports={verifyPerms:mQ,verifyPermsAst:TQ,verifyBulkLoadAttributePerms:AQ};function TQ(e,t,r){if(Lr.isEmptyOrZeroLength(e))throw Oe.info("verify_perms_ast has an empty user parameter"),dt(new Error);if(Lr.isEmptyOrZeroLength(t))throw Oe.info("verify_perms_ast has an empty user parameter"),dt(new Error);if(Lr.isEmptyOrZeroLength(r))throw Oe.info("verify_perms_ast has a null operation parameter"),dt(new Error);try{let s=new iI,n=new uQ(e),i=n.getSchemas(),o=new Map;if((!i||i.length===0)&&n.affected_attributes&&n.affected_attributes.size>0)throw Oe.info("No schemas defined in verifyPermsAst(), will not continue."),dt(new Error);let c=!!t.role.permission.super_user,_=i.includes("system");if(_&&cI[r])throw dt(new Error,Fe.DROP_SYSTEM,Xi.FORBIDDEN);if(c&&!_)return null;let u=eI.getRolePermissions(t.role);t.role.permission=u,!c&&e instanceof EQ.yy.Select&&(e=n.updateAttributeWildcardsForRolePerms(u));for(let E=0;E<i.length;E++){let d=n.getTablesBySchemaName(i[E]);d&&o.set(i[E],d)}let l=uI(t,r,o,s);return l||(o.forEach((E,d)=>{for(let S=0;S<E.length;S++){let m=n.getAttributesBySchemaTableName(d,E[S]),R=Cd(t.role.permission,d,E[S]);bd(m,R,r,E[S],d,s)}}),s.getPermsResponse())}catch(s){throw dt(s)}}a(TQ,"verifyPermsAst");function mQ(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw Oe.info("null required parameter in verifyPerms"),dt(new Error,Fe.DEFAULT_INVALID_REQUEST,Xi.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let s=e.action,n=e.schema,i=e.table,o=new Map;n&&i&&o.set(n,[i]);let c=new iI;if(Lr.isEmptyOrZeroLength(e.hdb_user.role)||Lr.isEmptyOrZeroLength(e.hdb_user.role.permission))return Oe.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Fe.USER_HAS_NO_PERMS(e.hdb_user.username));let _=!!e.hdb_user.role.permission.super_user,u=e.hdb_user.role.permission.structure_user,l=o.has(Bt.SYSTEM_SCHEMA_NAME)||n===Bt.SYSTEM_SCHEMA_NAME;if(l&&cI[r])throw dt(new Error,Fe.DROP_SYSTEM,Xi.FORBIDDEN);if(_&&!l||u===!0&&(r===vt.createSchema.name||r===vt.dropSchema.name))return null;if(fQ.indexOf(r)>=0&&(u===!0||Array.isArray(u)))return u===!0||u.indexOf(n)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${n}'`);let E=eI.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=E,r===Xg||r===zg){if(n===Bt.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Fe.SCHEMA_PERM_ERROR(n));if(!E.super_user){if(r===Xg&&(!E[n]||!E[n][zi]))return c.handleInvalidItem(Fe.SCHEMA_NOT_FOUND(n));if(r===zg&&(!E[n]||!E[n].tables[i]||!E[n].tables[i][zi]))return c.handleInvalidItem(Fe.TABLE_NOT_FOUND(n,i))}}let d=uI(e.hdb_user,r,o,c,s);if(d)return d;if(p.get(r)&&p.get(r).perms.length===0)return null;if(!_&&e.get_attributes&&Bt.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let R=[],w=E[n].tables[i];w[Bt.PERMS_CRUD_ENUM.READ]&&(w.attribute_permissions.length>0?w.attribute_permissions.filter(B=>B[Bt.PERMS_CRUD_ENUM.READ]).forEach(B=>{R.push(B.attribute_name)}):R=global.hdb_schema[n][i].attributes.map(U=>U.attribute),e.get_attributes=R)}let S=RQ(e),m=Cd(e.hdb_user.role.permission,n,i);return bd(S,m,r,i,n,c,s),c.getPermsResponse()}a(mQ,"verifyPerms");function uI(e,t,r,s,n){if(Lr.arrayHasEmptyValues([e,t,r]))throw Oe.info("hasPermissions has an invalid parameter"),dt(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&!i)return null;if(!p.get(t))throw Oe.info(`operation ${t} not found.`),dt(new Error,Fe.OP_NOT_FOUND(t),Xi.BAD_REQUEST);if(p.get(t)&&p.get(t).requires_su)return Oe.info(`operation ${t} requires SU permissions.`),s.handleUnauthorizedItem(Fe.OP_IS_SU_ONLY(t));let c=r.keys();for(let _ of c){try{if(_&&!o[_]||o[_][zi]===!1){s.addInvalidItem(Fe.SCHEMA_NOT_FOUND(_));continue}}catch{s.addInvalidItem(Fe.SCHEMA_NOT_FOUND(_));continue}let u=r.get(_);for(let l of u){let E=o[_].tables[l];if(!E||E[zi]===!1)s.addInvalidItem(Fe.TABLE_NOT_FOUND(_,l));else try{let d=[],S=p.get(t).perms;!Lr.isEmpty(n)&&S.includes(n)&&(S=[n]);for(let m=0;m<S.length;m++){let R=S[m],w=E[R];(w==null||w===!1)&&(Oe.info(`Required ${R} permission not found for ${t} ${n?`${n} `:""}operation in role ${e.role.id}`),d.push(R))}d.length>0&&s.addUnauthorizedTable(_,l,d)}catch(d){let S=Fe.UNKNOWN_OP_AUTH_ERROR(t,_,l);throw Oe.error(S),Oe.error(d),dt(aI.CHECK_LOGS_WRAPPER(S))}}}return r.size<2?s.getPermsResponse():null}a(uI,"hasPermissions");function bd(e,t,r,s,n,i,o){if(!e||!t)throw Oe.info("no attributes specified in checkAttributePerms."),dt(new Error);let c=p.get(r).perms;if(!c||c==="")throw Oe.info(`no permissions found for ${r} in checkAttributePerms().`),dt(new Error);if(Lr.isEmptyOrZeroLength(t))return Oe.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let _={};for(let l of e){let E=t.get(l);if(E){if(E[zi]===!1){i.addInvalidItem(Fe.ATTR_NOT_FOUND(n,s,l),n,s);continue}if(c)for(let d of c){if(Bt.TIME_STAMP_NAMES.includes(E.attribute_name)&&d!==ur)throw dt(new Error,Fe.SYSTEM_TIMESTAMP_PERMS_ERR,Xi.FORBIDDEN);E[d]===!1&&(_[E.attribute_name]?_[E.attribute_name].push(d):_[E.attribute_name]=[d])}}else i.addInvalidItem(Fe.ATTR_NOT_FOUND(n,s,l),n,s)}let u=Object.keys(_);u.length>0&&i.addUnauthorizedAttributes(u,n,s,_)}a(bd,"checkAttributePerms");function RQ(e){let t=new Set;try{if(e.action)return t;if(e.operation===Bt.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let s=Object.keys(e.records[r]);for(let n=0;n<s.length;n++)t.add(s[n])}}catch(r){Oe.info(r)}return t}a(RQ,"getRecordAttributes");function Cd(e,t,r){let s=new Map;if(Lr.isEmpty(e))return Oe.info("no hdb_user specified in getAttributePermissions"),s;if(e.super_user||!t||!r)return s;try{e[t].tables[r].attribute_permissions.forEach(n=>{s.has(n.attribute_name)||s.set(n.attribute_name,n)})}catch{Oe.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return s}a(Cd,"getAttributePermissions");function AQ(e,t,r,s,n,i,o){let c=new Set(i),_=Cd(e,s,n);bd(c,_,t,n,s,o,r)}a(AQ,"verifyBulkLoadAttributePerms")});var O_=h((K2,fI)=>{"use strict";fI.exports={evaluateSQL:BQ,processAST:SI,convertSQLToAST:hI,checkASTPermissions:dI};var EI=yt(),Ld=require("util"),pQ=Ld.callbackify(EI.insert),OQ=mt().search,NQ=Ap().update,gQ=Ld.callbackify(NQ),IQ=Op().convertDelete,as=require("alasql"),bQ=A_(),ra=g(),CQ=yo(),wQ=b(),ta=T(),{hdb_errors:UQ,handleHDBError:wd}=D(),{HTTP_STATUS_CODES:Ud}=UQ,LQ=On();function yQ(e,t,r){return Promise.all([LQ.postOperationHandler(e,t,r),EI.flush(e)])}a(yQ,"postWrite");var DQ=Ld.callbackify(yQ);CQ(as);var MQ=403,PQ="There was a problem performing this insert. Please check the logs and try again.",p_=class{constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};a(p_,"ParsedSQLObject");function BQ(e,t){let r=e.parsed_sql_object;if(!r){r=hI(e.sql);let s,n=r.ast.statements[0];if(n instanceof as.yy.Insert?s=n.into.databaseid:n instanceof as.yy.Select?s=n.from?n.from[0].databaseid:null:n instanceof as.yy.Update||n instanceof as.yy.Delete?s=n.table.databaseid:ra.error("AST in evaluateSQL is not a valid SQL type."),!(n instanceof as.yy.Select)&&wQ.isEmptyOrZeroLength(s))return t("No schema specified",null)}SI(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}a(BQ,"evaluateSQL");function dI(e,t){let r;try{r=bQ.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(s){throw s}return r||null}a(dI,"checkASTPermissions");function hI(e){let t=new p_;if(!e)throw wd(new Error,"The 'sql' parameter is missing from the request body",Ud.BAD_REQUEST);try{let r=e.trim(),s=as.parse(r),n=r.split(" ")[0].toLowerCase();t.ast=s,t.variant=n}catch(r){let s=r.message.split(`
14
- `);throw s[1]?wd(r,`Invalid SQL at: ${s[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,Ud.BAD_REQUEST):wd(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",Ud.BAD_REQUEST)}return t}a(hI,"convertSQLToAST");function SI(e,t,r){try{let s=vQ;if(!e.bypass_auth&&!t.permissions_checked){let i=dI(e,t);if(i&&i.length>0)return r(MQ,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case ta.VALID_SQL_OPS_ENUM.SELECT:s=OQ,n=t.ast.statements[0];break;case ta.VALID_SQL_OPS_ENUM.INSERT:s=HQ;break;case ta.VALID_SQL_OPS_ENUM.UPDATE:s=gQ;break;case ta.VALID_SQL_OPS_ENUM.DELETE:s=IQ;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}s(n,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(s){return r(s)}}a(SI,"processAST");function vQ(e,t){ra.info(e),t("unknown sql statement")}a(vQ,"nullFunction");function HQ({statement:e,hdb_user:t},r){let s=e.into,n={schema:s.databaseid,table:s.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{n.records=qQ(i,e.values)}catch(o){return r(o)}pQ(n,(o,c)=>{if(o)return r(o);DQ(n,c,_=>{_&&ra.error(_)});try{delete c.new_attributes,delete c.txn_time}catch(_){ra.error(`Error delete new_attributes from insert response: ${_}`)}r(null,c)})}a(HQ,"convertInsert");function qQ(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let s={};return r.forEach((n,i)=>{if(n.columnid)throw"cannot use a column in insert value";"value"in n?s[e[i]]=n.value:s[e[i]]=as.compile(`SELECT ${n.toString()} AS [${ta.FUNC_VAL}] FROM ?`)}),s})}catch(r){throw ra.error(r),new Error(PQ)}}a(qQ,"createDataObjects")});var Dd=h((Q2,pI)=>{var C_=require("clone"),w_=de(),GQ=b(),b_=T(),FQ=g(),N_=require("fs"),{hdb_errors:VQ,handleHDBError:sa}=D(),{HDB_ERROR_MSGS:kQ,HTTP_STATUS_CODES:g_}=VQ,{common_validators:I_}=Rr(),TI=1e9,yd=" is required",xQ=["insert","update","upsert"],U_={schema:{presence:!0,format:I_.schema_format,length:I_.schema_length},table:{presence:!0,format:I_.schema_format,length:I_.schema_length},action:{inclusion:{within:xQ,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{}},{AWS_ACCESS_KEY:$Q,AWS_SECRET:YQ,AWS_BUCKET:KQ,AWS_FILE_KEY:QQ}=b_.S3_BUCKET_AUTH_KEYS,WQ={s3:{presence:!0},[`s3.${$Q}`]:{presence:!0,type:"String"},[`s3.${YQ}`]:{presence:!0,type:"String"},[`s3.${KQ}`]:{presence:!0,type:"String"},[`s3.${QQ}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]}},mI=C_(U_);mI.data.presence={message:yd};var RI=C_(U_);RI.file_path.presence={message:yd};var JQ=Object.assign(C_(U_),WQ),AI=C_(U_);AI.csv_url.presence={message:yd};function ZQ(e){let t=w_.validateObject(e,mI);return L_(e,t)}a(ZQ,"dataObject");function XQ(e){let t=w_.validateObject(e,AI);return L_(e,t)}a(XQ,"urlObject");function zQ(e){let t=w_.validateObject(e,RI);return L_(e,t)}a(zQ,"fileObject");function jQ(e){let t=w_.validateObject(e,JQ);return L_(e,t)}a(jQ,"s3FileObject");function L_(e,t){if(!t){let r=GQ.checkGlobalSchemaTable(e.schema,e.table);if(r)return sa(new Error,r,g_.BAD_REQUEST);if(e.operation===b_.OPERATIONS_ENUM.CSV_FILE_LOAD){try{N_.accessSync(e.file_path,N_.constants.R_OK|N_.constants.F_OK)}catch(s){return s.code===b_.NODE_ERROR_CODES.ENOENT?sa(s,`No such file or directory ${s.path}`,g_.BAD_REQUEST):s.code===b_.NODE_ERROR_CODES.EACCES?sa(s,`Permission denied ${s.path}`,g_.BAD_REQUEST):sa(s)}try{let s=N_.statSync(e.file_path).size;if(s>TI)return sa(new Error,kQ.MAX_FILE_SIZE_ERR(s,TI),g_.BAD_REQUEST)}catch(s){FQ.error(s),console.error(s)}}}return t}a(L_,"postValidateChecks");pI.exports={dataObject:ZQ,urlObject:XQ,fileObject:zQ,s3FileObject:jQ}});var Md=h((W2,OI)=>{"use strict";var na=g(),y_=T();async function eW(e,t,r,s=[]){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let n;try{return n=await e(t),r&&await r(t,n,s),t.operation===y_.OPERATIONS_ENUM.INSERT||t.operation===y_.OPERATIONS_ENUM.UPDATE||t.operation===y_.OPERATIONS_ENUM.UPSERT?(delete n.new_attributes,delete n.txn_time):t.operation===y_.OPERATIONS_ENUM.DELETE&&delete n.txn_time,n}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(na.info(i.message),i):i.http_resp_msg?(na.error(`Error calling operation: ${e.name}`),na.error(i.http_resp_msg),i):(na.error(`Error calling operation: ${e.name}`),na.error(i),i)}}a(eW,"callOperationFunctionAsAwait");OI.exports={callOperationFunctionAsAwait:eW}});var Pd=h((J2,gI)=>{"use strict";var tW=require("aws-sdk/clients/s3");gI.exports={getFileStreamFromS3:rW,getS3AuthObj:NI};function rW(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return NI(t.aws_access_key_id,t.aws_secret_access_key).getObject(r).createReadStream()}a(rW,"getFileStreamFromS3");function NI(e,t){return new tW({accessKeyId:e,secretAccessKey:t})}a(NI,"getS3AuthObj")});var bI=h((Z2,II)=>{"use strict";var D_=class{constructor(t,r,s,n,i,o,c=null){this.op=t,this.action=r,this.schema=s,this.table=n,this.file_path=i,this.file_type=o,this.role_perms=c}};a(D_,"BulkLoadFileObject");var M_=class{constructor(t,r,s,n){this.action=t,this.schema=r,this.table=s,this.data=n}};a(M_,"BulkLoadDataObject");II.exports={BulkLoadFileObject:D_,BulkLoadDataObject:M_}});var Gd=h((X2,xI)=>{"use strict";var P_=yt(),H_=Dd(),sW=require("needle"),Nt=T(),nW=Se(),ia=b(),{handleHDBError:oe,hdb_errors:BI}=D(),{HTTP_STATUS_CODES:Ve,HDB_ERROR_MSGS:Ne,CHECK_LOGS_WRAPPER:Vs}=BI,Fs=g(),B_=require("papaparse");ia.promisifyPapaParse();var Zt=require("fs-extra"),iW=require("path"),{chain:CI}=require("stream-chain"),wI=require("stream-json/streamers/StreamArray"),UI=require("stream-json/utils/Batch"),LI=require("stream-chain/utils/comp"),{finished:yI}=require("stream"),Bd=V(),aW=On(),vI=Md(),oW=Pd(),{BulkLoadFileObject:vd,BulkLoadDataObject:cW}=bI(),Hd=pd(),{verifyBulkLoadAttributePerms:HI}=A_(),_W=nE(),uW=At(),lW=$r(),DI="No records parsed from csv file.",Gs=`${Bd.get("HDB_ROOT")}/tmp`,{schema_regex:EW}=Rr(),MI=1024*1024*5,PI=5e3,dW={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};xI.exports={csvDataLoad:hW,csvURLLoad:SW,csvFileLoad:fW,importFromS3:TW};async function hW(e,t=[]){let r=H_.dataObject(e);if(r)throw oe(r,r.message,Ve.BAD_REQUEST,void 0,void 0,!0);let s={};try{let n=B_.parse(e.data,{header:!0,skipEmptyLines:!0,dynamicTyping:!0}),i=new Hd;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&HI(e.hdb_user.role.permission,this.job_operation_function.name,e.action,e.schema,e.table,n.meta.fields,i);let o=i.getPermsResponse();if(o)throw oe(new Error,o,Ve.BAD_REQUEST,void 0,void 0,!0);let c=new cW(e.action,e.schema,e.table,n.data);return s=await vI.callOperationFunctionAsAwait(FI,c,VI.bind(null,n.meta.fields),t),s.message===DI?DI:kI(s.records,s.number_written)}catch(n){throw ks(n)}}a(hW,"csvDataLoad");async function SW(e){let t=H_.urlObject(e);if(t)throw oe(t,t.message,Ve.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,s=`${Gs}/${r}`;try{await mW(e.csv_url,r)}catch(n){throw Fs.error(Ne.DOWNLOAD_FILE_ERR(r)+" - "+n),oe(n,Vs(Ne.DOWNLOAD_FILE_ERR(r)))}try{let n=new vd(this.job_operation_function.name,e.action,e.schema,e.table,s,Nt.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await qd(n);return await v_(s),i}catch(n){throw await v_(s),ks(n)}}a(SW,"csvURLLoad");async function fW(e){let t=H_.fileObject(e);if(t)throw oe(t,t.message,Ve.BAD_REQUEST,void 0,void 0,!0);let r=new vd(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Nt.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await qd(r)}catch(s){throw ks(s)}}a(fW,"csvFileLoad");async function TW(e){let t=H_.s3FileObject(e);if(t)throw oe(t,t.message,Ve.BAD_REQUEST,void 0,void 0,!0);let r;try{let s=iW.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${Gs}/${n}`;let i=new vd(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await RW(n,e);let o=await qd(i);return await v_(r),o}catch(s){throw await v_(r),ks(s)}}a(TW,"importFromS3");async function mW(e,t){let r;try{r=await sW("get",e)}catch(s){let n=`Error downloading CSV file from ${e}, status code: ${s.statusCode}. Check the log for more information.`;throw oe(s,n,s.statusCode,Nt.LOG_LEVELS.ERROR,"Error downloading CSV file - "+s)}pW(r,e),await AW(t,r.raw)}a(mW,"downloadCSVFile");async function RW(e,t){try{let r=`${Gs}/${e}`;await Zt.mkdirp(Gs),await Zt.writeFile(`${Gs}/${e}`,"",{flag:"a+"});let s=await Zt.createWriteStream(r),n=oW.getFileStreamFromS3(t);await new Promise((i,o)=>{n.on("error",function(c){o(c)}),n.pipe(s).on("error",function(c){o(c)}).on("close",function(){Fs.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Fs.error(Ne.S3_DOWNLOAD_ERR+" - "+r),oe(r,Vs(Ne.S3_DOWNLOAD_ERR))}}a(RW,"downloadFileFromS3");async function AW(e,t){try{await Zt.mkdirp(Gs),await Zt.writeFile(`${Gs}/${e}`,t)}catch(r){throw Fs.error(Ne.WRITE_TEMP_FILE_ERR),oe(r,Vs(Ne.DEFAULT_BULK_LOAD_ERR))}}a(AW,"writeFileToTempFolder");async function v_(e){if(e)try{await Zt.access(e),await Zt.unlink(e)}catch{Fs.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(v_,"deleteTempFile");function pW(e,t){if(e.statusCode!==BI.HTTP_STATUS_CODES.OK)throw oe(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Ve.BAD_REQUEST);if(!dW[e.headers["content-type"]])throw oe(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Ve.BAD_REQUEST);if(!e.raw)throw oe(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Ve.BAD_REQUEST)}a(pW,"validateURLResponse");async function qd(e){try{let t;switch(e.file_type){case Nt.VALID_S3_FILE_TYPES.CSV:t=await OW(e);break;case Nt.VALID_S3_FILE_TYPES.JSON:t=await NW(e);break;default:throw oe(new Error,Ne.DEFAULT_BULK_LOAD_ERR,Ve.BAD_REQUEST,Nt.LOG_LEVELS.ERROR,Ne.INVALID_FILE_EXT_ERR(e))}return kI(t.records,t.number_written)}catch(t){throw ks(t)}}a(qd,"fileLoad");async function qI(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;n&&n.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await P_.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&HI(e.role_perms,e.op,e.action,e.schema,e.table,c,t),n&&n.resume()}catch(c){let _=oe(c);r(_)}}a(qI,"validateChunk");async function GI(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;ia.autoCastJSONDeep(i),n&&n.pause();let o=s.meta?s.meta.fields:null;if(o)i.forEach(c=>{!ia.isEmpty(c)&&!ia.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(_=>{Object.keys(_).forEach(u=>c.add(u))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},_=await vI.callOperationFunctionAsAwait(FI,c,VI.bind(null,o));t.records+=_.records,t.number_written+=_.number_written,n&&n.resume()}catch(c){let _=oe(c,Vs(Ne.INSERT_CSV_ERR),Ve.INTERNAL_SERVER_ERROR,Nt.LOG_LEVELS.ERROR,Ne.INSERT_CSV_ERR+" - "+c);r(_)}}a(GI,"insertChunk");async function OW(e){let t={records:0,number_written:0};try{let r=new Hd,s=Zt.createReadStream(e.file_path,{highWaterMark:MI});s.setEncoding("utf8"),await B_.parsePromise(s,qI.bind(null,e,r));let n=r.getPermsResponse();if(n)throw oe(new Error,n,Ve.BAD_REQUEST);return s=Zt.createReadStream(e.file_path,{highWaterMark:MI}),s.setEncoding("utf8"),await B_.parsePromise(s,GI.bind(null,e,t)),s.destroy(),t}catch(r){throw oe(r,Vs(Ne.PAPA_PARSE_ERR),Ve.INTERNAL_SERVER_ERROR,Nt.LOG_LEVELS.ERROR,Ne.PAPA_PARSE_ERR+r)}}a(OW,"callPapaParse");async function NW(e){let t={records:0,number_written:0},r=a(s=>{throw s},"throwErr");try{let s=new Hd,n=CI([Zt.createReadStream(e.file_path,{encoding:"utf-8"}),wI.withParser(),c=>c.value,new UI({batchSize:PI}),LI(async c=>{await qI(e,s,r,c)})]);await new Promise((c,_)=>{yI(n,u=>{u?_(u):c()}),n.resume()});let i=s.getPermsResponse();if(i)throw oe(new Error,i,Ve.BAD_REQUEST);let o=CI([Zt.createReadStream(e.file_path,{encoding:"utf-8"}),wI.withParser(),c=>c.value,new UI({batchSize:PI}),LI(async c=>{await GI(e,t,r,c)})]);return await new Promise((c,_)=>{yI(o,u=>{u?_(u):c()}),o.resume()}),t}catch(s){throw oe(s,Vs(Ne.INSERT_JSON_ERR),Ve.INTERNAL_SERVER_ERROR,Nt.LOG_LEVELS.ERROR,Ne.INSERT_JSON_ERR+s)}}a(NW,"insertJson");async function FI(e){let t={};try{e.data&&e.data.length>0&&gW(e.data[0])?t=await IW(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Fs.info(t.message))}catch(r){throw ks(r)}return t}a(FI,"callBulkFileLoad");function gW(e){let t=Object.keys(e);for(let r of t)if(!EW.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(gW,"validateColumnNames");async function IW(e,t,r,s){s||(s="insert");let n={operation:s,schema:t,table:r,records:e},i;switch(s){case"insert":i=P_.insert;break;case"update":i=P_.update;break;case"upsert":i=P_.upsert;break;default:throw oe(new Error,Ne.INVALID_ACTION_PARAM_ERR(s),Ve.BAD_REQUEST,Nt.LOG_LEVELS.ERROR,Ne.INVALID_ACTION_PARAM_ERR(s))}try{let o=await i(n),c;switch(s){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,E=e.length;for(;E--;)o.skipped_hashes.indexOf(e[E][l])>=0&&e.splice(E,1)}let _=ia.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:_,new_attributes:o.new_attributes}}catch(o){throw ks(o)}}a(IW,"bulkFileLoad");async function VI(e,t,r,s=[]){try{if(t.data.length===0||!Bd.get(Nt.CONFIG_PARAMS.CLUSTERING_ENABLED))return;let n=B_.unparse(t.data,{header:!0,skipEmptyLines:!0,columns:e}),i;t.hdb_user&&t.hdb_user.username&&(i=t.hdb_user.username);let o={operation:"csv_data_load",action:t.action?t.action:"insert",schema:t.schema,table:t.table,data:n,__origin:new _W(r.txn_time,i,Bd.get(Nt.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY))};await uW.publishToStream(`${nW.SUBJECT_PREFIXES.TXN}.${t.schema}.${t.table}`,lW.createNatsTableStreamName(t.schema,t.table),[o],s),await aW.sendAttributeTransaction(r,t,s),delete r.new_attributes}catch(n){Fs.error(n)}}a(VI,"postCSVLoadFunction");function kI(e,t){return`successfully loaded ${t} of ${e} records`}a(kI,"buildResponseMsg");function ks(e){return oe(e,Vs(Ne.DEFAULT_BULK_LOAD_ERR),Ve.INTERNAL_SERVER_ERROR,Nt.LOG_LEVELS.ERROR,Ne.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(ks,"buildTopLevelErrMsg")});var Vd=h((z2,XI)=>{"use strict";var KI=mt(),bW=O_(),CW=Pd(),{AsyncParser:wW,Transform:UW}=require("json2csv"),aa=require("stream"),LW=require("events"),Ht=b(),Fd=require("fs-extra"),yW=require("path"),tt=g(),{promisify:q_}=require("util"),oa=b(),{handleHDBError:ge,hdb_errors:DW}=D(),{HDB_ERROR_MSGS:gt,HTTP_STATUS_CODES:Ie}=DW,$I=["search_by_value","search_by_hash","sql"],YI=["json","csv"],QI="json",WI="csv",MW="Successfully exported JSON locally.",PW="Successfully exported CSV locally.",BW=1e3,vW=1e3,HW=q_(KI.searchByHash),qW=q_(KI.searchByValue),GW=q_(bW.evaluateSQL),FW=q_(aa.finished);XI.exports={export_to_s3:$W,export_local:VW};async function VW(e){tt.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=JI(e);if(!Ht.isEmpty(t))throw tt.error(t),ge(new Error,t,Ie.BAD_REQUEST,void 0,void 0,!0);if(Ht.isEmpty(e.path))throw tt.error(gt.MISSING_VALUE("path")),ge(new Error,gt.MISSING_VALUE("path"),Ie.BAD_REQUEST,void 0,void 0,!0);let r=(Ht.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(yW.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=Ht.buildFolderPath(e.path,r);try{await kW(e.path);let n=await ZI(e);return await xW(s,e.format,n)}catch(n){throw tt.error(n),new Error(n)}}a(VW,"export_local");async function kW(e){if(tt.trace("in confirmPath"),Ht.isEmptyOrZeroLength(e))throw ge(new Error,`Invalid path: ${e}`,Ie.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Fd.stat(e)}catch(r){let s;throw r.code==="ENOENT"?s=`path '${e}' does not exist`:r.code==="EACCES"?s=`access to path '${e}' is denied`:s=r.message,tt.error(s),ge(new Error,s,Ie.BAD_REQUEST,void 0,void 0,!0)}if(!t.isDirectory()){let r=`path '${e}' is not a directory, please supply a valid folder path`;throw tt.error(r),ge(new Error,r,Ie.BAD_REQUEST,void 0,void 0,!0)}return!0}a(kW,"confirmPath");async function xW(e,t,r){if(tt.trace("in saveToLocal"),oa.isEmptyOrZeroLength(e))throw ge(new Error,gt.INVALID_VALUE("file_path"),Ie.BAD_REQUEST,void 0,void 0,!0);if(oa.isEmptyOrZeroLength(t))throw ge(new Error,gt.INVALID_VALUE("Source format"),Ie.BAD_REQUEST,void 0,void 0,!0);if(oa.isEmpty(r))throw ge(new Error,gt.NOT_FOUND("Data"),Ie.BAD_REQUEST,void 0,void 0,!0);if(t===QI){let s=Fd.createWriteStream(e),n=r.length;s.write("[");let i="";for await(let[o,c]of r.entries())i+=o===n-1?JSON.stringify(c):JSON.stringify(c)+",",o!==0&&o%vW===0&&(s.write(i)||await LW.once(s,"drain"),i="");return i.length!==0&&s.write(i),s.write("]"),s.end(),await FW(s),MW}else if(t===WI){let s=Fd.createWriteStream(e),n=aa.Readable.from(r),i={},o={objectMode:!0};return await new wW(i,o).fromInput(n).toOutput(s).promise(!1),PW}throw ge(new Error,gt.INVALID_VALUE("format"),Ie.BAD_REQUEST)}a(xW,"saveToLocal");async function $W(e){if(!e.s3||Object.keys(e.s3).length===0)throw ge(new Error,gt.MISSING_VALUE("S3 object"),Ie.BAD_REQUEST);if(Ht.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw ge(new Error,gt.MISSING_VALUE("aws_access_key_id"),Ie.BAD_REQUEST);if(Ht.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw ge(new Error,gt.MISSING_VALUE("aws_secret_access_key"),Ie.BAD_REQUEST);if(Ht.isEmptyOrZeroLength(e.s3.bucket))throw ge(new Error,gt.MISSING_VALUE("bucket"),Ie.BAD_REQUEST);if(Ht.isEmptyOrZeroLength(e.s3.key))throw ge(new Error,gt.MISSING_VALUE("key"),Ie.BAD_REQUEST);let t=JI(e);if(!Ht.isEmpty(t))throw ge(new Error,t,Ie.BAD_REQUEST);tt.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await ZI(e)}catch(c){throw tt.error(c),c}let s,n=CW.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key),i,o=new aa.PassThrough;if(e.format===WI){i=e.s3.key+".csv";let c=aa.Readable.from(r),_={},u={objectMode:!0},l=new UW(_,u);l.on("error",E=>{throw E}),c.pipe(l).pipe(o)}else if(e.format===QI){i=e.s3.key+".json";let c=new aa.Readable;c.pipe(o),c.on("error",l=>{throw l}),c.push("[");let _=r.length,u="";for(let[l,E]of r.entries())u+=l===_-1?JSON.stringify(E):JSON.stringify(E)+",",l!==0&&l%BW===0&&(c.push(u),u="");u.length!==0&&c.push(u),c.push("]"),c.push(null)}else throw ge(new Error,gt.INVALID_VALUE("format"),Ie.BAD_REQUEST);try{s=await n.upload({Bucket:e.s3.bucket,Key:i,Body:o}).promise()}catch(c){throw tt.error(c),c}return s}a($W,"export_to_s3");function JI(e){if(tt.trace("in exportCoreValidation"),Ht.isEmpty(e.format))return"format missing";if(YI.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${YI.join(", ")}`;let t=e.search_operation.operation;if(Ht.isEmpty(t))return"search_operation.operation missing";if($I.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${$I.join(", ")}`}a(JI,"exportCoreValidation");async function ZI(e){tt.trace("in getRecords");let t,r;if(oa.isEmpty(e.search_operation)||oa.isEmptyOrZeroLength(e.search_operation.operation))throw ge(new Error,gt.INVALID_VALUE("Search operation"),Ie.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=qW;break;case"search_by_hash":t=HW;break;case"sql":t=GW;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,tt.error(r),ge(new Error,r,Ie.BAD_REQUEST)}e.search_operation.hdb_user=e.hdb_user;try{return t(e.search_operation)}catch(s){throw tt.error(s),s}}a(ZI,"getRecords")});var jI=h((j2,zI)=>{"use strict";var G_=class{constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};a(G_,"SqlSearchObject");zI.exports=G_});var rb=h((ez,tb)=>{"use strict";var YW=T(),eb=require("moment"),KW=require("uuid").v4,F_=class{constructor(){this.id=KW(),this.type=void 0,this.start_datetime=eb().valueOf(),this.created_datetime=eb().valueOf(),this.end_datetime=void 0,this.status=YW.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};a(F_,"JobObject");tb.exports=F_});var xd=h((tz,cb)=>{"use strict";var QW=require("uuid").v4,ib=yt(),ab=mt(),WW=Qt(),JW=Ss(),ZW=jI(),ce=T(),XW=rb(),zW=Fl(),qt=g(),jW=ti(),kn=b(),{promisify:kd}=require("util"),xs=require("moment"),e1=O_(),V_=Dd(),sb=pl(),{deleteTransactionLogsBeforeValidator:t1}=Td(),{handleHDBError:r1,hdb_errors:s1}=D(),{HTTP_STATUS_CODES:n1}=s1,nb=kd(ab.searchByValue),i1=kd(ab.searchByHash),a1=ib.insert,o1=kd(e1.evaluateSQL),c1=ib.update;cb.exports={addJob:l1,updateJob:d1,handleGetJob:_1,handleGetJobsByStartDate:u1,getJobById:ob};async function _1(e){try{let t=await ob(e.id);return kn.isEmptyOrZeroLength(t)||(t[0].request!==void 0&&delete t[0].request,delete t[0].__createdtime__,delete t[0].__updatedtime__),t}catch(t){let r=`There was an error getting job: ${t}`;throw qt.error(r),new Error(r)}}a(_1,"handleGetJob");async function u1(e){try{let t=await E1(e);if(qt.trace(`Searching for jobs from ${e.from_date} to ${e.to_date}`),t&&t.length>0)for(let r of t)r.start_datetime&&(r.start_datetime_converted=xs(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=xs(r.end_datetime)),r.request!==void 0&&delete r.request,delete r.__createdtime__,delete r.__updatedtime__;return t}catch(t){let r=`There was an error searching jobs by date: ${t}`;throw qt.error(r),new Error(r)}}a(u1,"handleGetJobsByStartDate");async function l1(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||kn.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return qt.info(l),t.error=l,t}if(!ce.JOB_TYPE_ENUM[e.operation])return qt.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,s;switch(r){case ce.OPERATIONS_ENUM.CSV_FILE_LOAD:s=V_.fileObject(e);break;case ce.OPERATIONS_ENUM.CSV_URL_LOAD:s=V_.urlObject(e);break;case ce.OPERATIONS_ENUM.CSV_DATA_LOAD:s=V_.dataObject(e);break;case ce.OPERATIONS_ENUM.IMPORT_FROM_S3:s=V_.s3FileObject(e);break;case ce.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case ce.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:s=sb(e,"date");break;case ce.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:s=sb(e,"timestamp");break;case ce.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:s=t1(e);break;default:break}if(s)throw r1(s,s.message,n1.BAD_REQUEST,void 0,void 0,!0);let n=new XW;n.type=e.operation===ce.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?ce.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,n.type=e.operation,n.user=e.hdb_user.username;let i=new WW(ce.SYSTEM_SCHEMA_NAME,ce.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",n.id,"id",["id"]),o;try{o=await nb(i)}catch(l){let E=`There was an error inserting a new job: ${l}`;return qt.error(E),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){n.id=QW();try{o=await nb(i)}catch(l){let E=`There was an error inserting a new job: ${l}`;return qt.error(E),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return qt.error("Error creating a job, could not find a unique job id."),t}n.request=e;let _=new jW(ce.SYSTEM_SCHEMA_NAME,ce.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),u;try{u=await a1(_)}catch(l){return qt.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(u.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${n.operation} and id ${n.id}`;else{let l=`Created a job with type ${n.type} and id ${n.id}`;t.message=l,t.createdJob=n,t.success=!0,qt.trace(l)}return t}a(l1,"addJob");async function E1(e){let t=xs(e.from_date,xs.ISO_8601),r=xs(e.to_date,xs.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let s=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,n=new ZW(s,e.hdb_user);try{return await o1(n)}catch(i){throw qt.error(`there was a problem searching for jobs from date ${e.from_date} to date ${e.to_date} ${i}`),new Error("there was an error searching for jobs. Please check the log for details.")}}a(E1,"getJobsInDateRange");async function ob(e){if(kn.isEmptyOrZeroLength(e))return kn.errorizeMessage("Invalid job ID specified.");let t=new JW(ce.SYSTEM_SCHEMA_NAME,ce.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await i1(t)}catch(r){let s=`There was an error searching for a job by id: ${e} ${r}`;return qt.error(s),kn.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(ob,"getJobById");async function d1(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(kn.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===ce.JOB_STATUS_ENUM.COMPLETE||e.status===ce.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=xs().valueOf());let t=new zW(ce.SYSTEM_SCHEMA_NAME,ce.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;try{r=await c1(t)}catch(s){throw new Error(s)}return r}a(d1,"updateJob")});var hb=h((rz,db)=>{"use strict";var _b=b(),It=T(),h1=require("moment"),k_=Gd(),x_=g(),ub=xd(),lb=Vd(),Eb=ps(),S1=t_(),f1=Ki(),T1=u_(),$_=class{constructor(t,r){this.job=t,this.json=r}};a($_,"RunnerMessage");async function m1(e){if(!e||Object.keys(e).length===0)throw new Error("Empty runner passed to parseMessage");if(!e.json||Object.keys(e.json).length===0)throw new Error("Empty JSON passed to parseMessage");if(!e.job||Object.keys(e.job).length===0)throw new Error("Empty job passed to parseMessage");if(_b.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(_b.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case It.JOB_TYPE_ENUM.csv_file_load:await Dr(e,k_.csvFileLoad);break;case It.JOB_TYPE_ENUM.csv_url_load:await Dr(e,k_.csvURLLoad);break;case It.JOB_TYPE_ENUM.csv_data_load:await Dr(e,k_.csvDataLoad);break;case It.JOB_TYPE_ENUM.import_from_s3:await Dr(e,k_.importFromS3);break;case It.JOB_TYPE_ENUM.empty_trash:break;case It.JOB_TYPE_ENUM.export_local:await Dr(e,lb.export_local);break;case It.JOB_TYPE_ENUM.export_to_s3:await Dr(e,lb.export_to_s3);break;case It.JOB_TYPE_ENUM.delete_files_before:case It.JOB_TYPE_ENUM.delete_records_before:await Dr(e,Eb.deleteFilesBefore);break;case It.JOB_TYPE_ENUM.delete_audit_logs_before:await Dr(e,Eb.deleteAuditLogsBefore);break;case It.JOB_TYPE_ENUM.delete_transaction_logs_before:await Dr(e,T1.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(m1,"parseMessage");async function Dr(e,t){try{e.job.status=It.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=h1().valueOf(),await ub.updateJob(e.job),await R1(e.job.id)}catch(r){let s=r.message!==void 0?r.message:r;typeof s=="string"?(s=`There was an error running ${t.name} job with id ${e.job.id} - ${s}`,r.message=s):x_.error(`There was an error running ${t.name} job with id ${e.job.id}`),x_.error(s),e.job.message=s,e.job.status=It.JOB_STATUS_ENUM.ERROR;try{await ub.updateJob(e.job)}catch(n){throw x_.error(`Unable to update job with id ${e.job.id}`),n}throw r}}a(Dr,"runJob");async function R1(e){let t=S1.generateJobConfig(e);x_.trace("launching job process:",e),await f1.start(t)}a(R1,"launchJobProcess");db.exports={parseMessage:m1,RunnerMessage:$_}});var fb=h((sz,Sb)=>{"use strict";var Y_=class{constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};a(Y_,"OperationFunctionObject");Sb.exports=Y_});var Ub=h((nz,wb)=>{"use strict";var W_=mt(),Qd=O_(),K_=Gd(),xn=Ec(),$d=ms(),_a=ps(),A1=EE(),ca=gr(),Q_=pE(),Mr=fd(),ke=g(),p1=gE(),O1=Dc(),N1=VE(),g1=vc(),I1=kE(),b1=YE(),Yd=WE(),Tb=Vd(),C1=A_(),Wd=xd(),A=T(),{hdb_errors:la,handleHDBError:ua}=D(),{HTTP_STATUS_CODES:mb}=la,Kd=XE(),Rb=_d(),J_=require("util"),$s=yt(),w1=Kr(),U1=wc(),bb=On(),Ab=hb(),pb=nc(),Ob=Tr(),Nb=u_(),gb=Ad(),L1=Md(),y1=J_.promisify(W_.searchByHash),D1=J_.promisify(W_.searchByValue),M1=J_.promisify(W_.search),P1=J_.promisify(Qd.evaluateSQL),B1={[A.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[A.OPERATIONS_ENUM.CREATE_TABLE]:!0,[A.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[A.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[A.OPERATIONS_ENUM.DROP_TABLE]:!0,[A.OPERATIONS_ENUM.DROP_SCHEMA]:!0},N=fb();function v1(e,t,r){return Promise.all([bb.postOperationHandler(e,t,r),e.table?$s.flush(e):null])}a(v1,"postWrite");async function H1(e,t){try{if(e.body.operation!=="read_log"&&(ke.log_level===A.LOG_LEVELS.INFO||ke.log_level===A.LOG_LEVELS.DEBUG||ke.log_level===A.LOG_LEVELS.TRACE)){let{hdb_user:s,hdb_auth_header:n,password:i,...o}=e.body;ke.info(o)}}catch(s){ke.error(s)}let r=A.CLUSTER_OPERATIONS[e.body.operation]===void 0?null:v1;try{let s=await L1.callOperationFunctionAsAwait(t,e.body,r);if(typeof s!="object"&&(s={message:s}),s instanceof Error)throw s;return B1[e.body.operation]&&w1.setSchemaDataToGlobal(n=>{n&&ke.error(n)}),s}catch(s){throw ke.info(s),s}}a(H1,"processLocalTransaction");var Ib=F1();wb.exports={chooseOperation:q1,getOperationFunction:Cb,processLocalTransaction:H1};function q1(e){let t;try{t=Cb(e)}catch(n){throw ke.error(`Error when selecting operation function - ${n}`),n}let{operation_function:r,job_operation_function:s}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let n=e.operation==="sql"?e.sql:e.search_operation.sql,i=Qd.convertSQLToAST(n);if(e.parsed_sql_object=i,!e.bypass_auth){let o=Qd.checkASTPermissions(e,i);if(o)throw ke.error(`${mb.FORBIDDEN} from operation ${e.search_operation}`),ua(new Error,o,la.HTTP_STATUS_CODES.FORBIDDEN)}}else if(!e.bypass_auth&&e.operation!==A.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS){let n=s===void 0?r:s,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=C1.verifyPerms(i,n);if(o)throw ke.error(`${mb.FORBIDDEN} from operation ${e.operation}`),ua(new Error,o,la.HTTP_STATUS_CODES.FORBIDDEN)}}catch(n){throw ua(n,"There was an error when trying to choose an operation path")}return r}a(q1,"chooseOperation");function Cb(e){if(ke.trace(`getOperationFunction with operation: ${e.operation}`),Ib.has(e.operation))return Ib.get(e.operation);throw ua(new Error,la.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),la.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(Cb,"getOperationFunction");async function G1(e){ke.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),s=r[0],n=r[1];for(let i of t.transactions)try{i.schema=s,i.table=n,i[A.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case A.OPERATIONS_ENUM.INSERT:o=await $s.insert(i);break;case A.OPERATIONS_ENUM.UPDATE:o=await $s.update(i);break;case A.OPERATIONS_ENUM.UPSERT:o=await $s.upsert(i);break;case A.OPERATIONS_ENUM.DELETE:o=await _a.deleteRecord(i);break;default:ke.warn("invalid operation in catchup");break}await bb.postOperationHandler(i,o,e)}catch(o){ke.info("Invalid operation in transaction"),ke.error(o)}}a(G1,"catchup");async function lr(e){let t,r;try{r=await Wd.addJob(e),t=r.createdJob;let s=new Ab.RunnerMessage(t,e);return await Ab.parseMessage(s),`Starting job with id ${t.id}`}catch(s){let n=`There was an error executing job: ${s.http_resp_msg?s.http_resp_msg:s}`;throw ke.error(n),ua(s,n)}}a(lr,"executeJob");function F1(){let e=new Map;return e.set(A.OPERATIONS_ENUM.INSERT,new N($s.insert)),e.set(A.OPERATIONS_ENUM.UPDATE,new N($s.update)),e.set(A.OPERATIONS_ENUM.UPSERT,new N($s.upsert)),e.set(A.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new N(W_.searchByConditions)),e.set(A.OPERATIONS_ENUM.SEARCH_BY_HASH,new N(y1)),e.set(A.OPERATIONS_ENUM.SEARCH_BY_VALUE,new N(D1)),e.set(A.OPERATIONS_ENUM.SEARCH,new N(M1)),e.set(A.OPERATIONS_ENUM.SQL,new N(P1)),e.set(A.OPERATIONS_ENUM.CSV_DATA_LOAD,new N(lr,K_.csvDataLoad)),e.set(A.OPERATIONS_ENUM.CSV_FILE_LOAD,new N(lr,K_.csvFileLoad)),e.set(A.OPERATIONS_ENUM.CSV_URL_LOAD,new N(lr,K_.csvURLLoad)),e.set(A.OPERATIONS_ENUM.IMPORT_FROM_S3,new N(lr,K_.importFromS3)),e.set(A.OPERATIONS_ENUM.CREATE_SCHEMA,new N(xn.createSchema)),e.set(A.OPERATIONS_ENUM.CREATE_TABLE,new N(xn.createTable)),e.set(A.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new N(xn.createAttribute)),e.set(A.OPERATIONS_ENUM.DROP_SCHEMA,new N(xn.dropSchema)),e.set(A.OPERATIONS_ENUM.DROP_TABLE,new N(xn.dropTable)),e.set(A.OPERATIONS_ENUM.DROP_ATTRIBUTE,new N(xn.dropAttribute)),e.set(A.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new N($d.describeSchema)),e.set(A.OPERATIONS_ENUM.DESCRIBE_TABLE,new N($d.describeTable)),e.set(A.OPERATIONS_ENUM.DESCRIBE_ALL,new N($d.describeAll)),e.set(A.OPERATIONS_ENUM.DELETE,new N(_a.deleteRecord)),e.set(A.OPERATIONS_ENUM.ADD_USER,new N(ca.addUser)),e.set(A.OPERATIONS_ENUM.ALTER_USER,new N(ca.alterUser)),e.set(A.OPERATIONS_ENUM.DROP_USER,new N(ca.dropUser)),e.set(A.OPERATIONS_ENUM.LIST_USERS,new N(ca.listUsersExternal)),e.set(A.OPERATIONS_ENUM.LIST_ROLES,new N(Q_.listRoles)),e.set(A.OPERATIONS_ENUM.ADD_ROLE,new N(Q_.addRole)),e.set(A.OPERATIONS_ENUM.ALTER_ROLE,new N(Q_.alterRole)),e.set(A.OPERATIONS_ENUM.DROP_ROLE,new N(Q_.dropRole)),e.set(A.OPERATIONS_ENUM.USER_INFO,new N(ca.userInfo)),e.set(A.OPERATIONS_ENUM.READ_LOG,new N(p1)),e.set(A.OPERATIONS_ENUM.ADD_NODE,new N(O1)),e.set(A.OPERATIONS_ENUM.UPDATE_NODE,new N(N1)),e.set(A.OPERATIONS_ENUM.REMOVE_NODE,new N(g1)),e.set(A.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new N(I1)),e.set(A.OPERATIONS_ENUM.SET_CONFIGURATION,new N(Ob.setConfiguration)),e.set(A.OPERATIONS_ENUM.CLUSTER_STATUS,new N(b1.clusterStatus)),e.set(A.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new N(Yd.setRoutes)),e.set(A.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new N(Yd.getRoutes)),e.set(A.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new N(Yd.deleteRoutes)),e.set(A.OPERATIONS_ENUM.EXPORT_TO_S3,new N(lr,Tb.export_to_s3)),e.set(A.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new N(lr,_a.deleteFilesBefore)),e.set(A.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new N(lr,_a.deleteFilesBefore)),e.set(A.OPERATIONS_ENUM.EXPORT_LOCAL,new N(lr,Tb.export_local)),e.set(A.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new N(Wd.handleGetJobsByStartDate)),e.set(A.OPERATIONS_ENUM.GET_JOB,new N(Wd.handleGetJob)),e.set(A.OPERATIONS_ENUM.GET_FINGERPRINT,new N(Kd.getFingerprint)),e.set(A.OPERATIONS_ENUM.SET_LICENSE,new N(Kd.setLicense)),e.set(A.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new N(Kd.getRegistrationInfo)),e.set(A.OPERATIONS_ENUM.RESTART,new N(Rb.restartProcesses)),e.set(A.OPERATIONS_ENUM.RESTART_SERVICE,new N(Rb.restartService)),e.set(A.OPERATIONS_ENUM.CATCHUP,new N(G1)),e.set(A.OPERATIONS_ENUM.SYSTEM_INFORMATION,new N(U1.systemInformation)),e.set(A.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new N(lr,_a.deleteAuditLogsBefore)),e.set(A.OPERATIONS_ENUM.READ_AUDIT_LOG,new N(A1)),e.set(A.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new N(pb.createTokens)),e.set(A.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new N(pb.refreshOperationToken)),e.set(A.OPERATIONS_ENUM.GET_CONFIGURATION,new N(Ob.getConfiguration)),e.set(A.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new N(Mr.customFunctionsStatus)),e.set(A.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new N(Mr.getCustomFunctions)),e.set(A.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new N(Mr.getCustomFunction)),e.set(A.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new N(Mr.setCustomFunction)),e.set(A.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new N(Mr.dropCustomFunction)),e.set(A.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new N(Mr.addCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new N(Mr.dropCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new N(Mr.packageCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new N(Mr.deployCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new N(Nb.readTransactionLog)),e.set(A.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new N(lr,Nb.deleteTransactionLogsBefore)),e.set(A.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new N(gb.installModules)),e.set(A.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new N(gb.auditModules)),e}a(F1,"initializeOperationFunctionMap")});var Zd=h((iz,Db)=>{"use strict";var V1=T(),k1=b(),Er=g(),{handleHDBError:Jd,hdb_errors:Z_}=D(),Lb=require("os"),x1=require("util"),$1=Kl(),Y1=x1.promisify($1.authorize),yb=Ub();function K1(e){let t=`Found an uncaught exception with message: ${e.message}. ${Lb.EOL}Stack: ${e.stack} ${Lb.EOL}Terminating HDB.`;console.error(t),Er.fatal(t),process.exit(1)}a(K1,"handleServerUncaughtException");function Q1(){Er.info("beforeExit caught"),process.exit(0)}a(Q1,"handleBeforeExit");function W1(){Er.info("exit caught"),process.exit(0)}a(W1,"handleExit");function J1(){Er.info("SIGINT caught"),process.exit(0)}a(J1,"handleSigint");function Z1(){Er.info("SIGQUIT caught"),process.exit(0)}a(Z1,"handleSigquit");function X1(){Er.info("SIGTERM caught"),process.exit(0)}a(X1,"handleSigterm");function z1(e,t,r){if(Er.error(e),e.http_resp_code)return typeof e.http_resp_msg=="string"?r.code(e.http_resp_code).send({error:e.http_resp_msg}):r.code(e.http_resp_code).send(e.http_resp_msg);let s=e.statusCode?e.statusCode:Z_.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(s).send({error:e}):r.code(s).send(e.message?{error:e.message}:e)}a(z1,"serverErrorHandler");function j1(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let s=Jd(new Error,"Invalid JSON.",Z_.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}if(k1.isEmpty(e.body.operation)){let s=Jd(new Error,"Request body must include an 'operation' property.",Z_.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}r()}a(j1,"reqBodyValidationHandler");function eJ(e,t,r){let s;e.body.operation!==V1.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS?Y1(e,t).then(n=>{s=n,e.body.hdb_user=s,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(n=>{Er.warn(n),Er.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${n.stack}"`);let i=typeof n=="string"?{error:n}:{error:n.message};r(Jd(n,i,Z_.HTTP_STATUS_CODES.UNAUTHORIZED),null)}):(e.body.hdb_user=null,e.body.hdb_auth_header=e.headers.authorization,r())}a(eJ,"authHandler");async function tJ(e,t=!1){let r;try{return t&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=t),r=yb.chooseOperation(e.body),yb.processLocalTransaction(e,r)}catch(s){throw Er.error(s),s}}a(tJ,"handlePostRequest");Db.exports={authHandler:eJ,handlePostRequest:tJ,handleServerUncaughtException:K1,serverErrorHandler:z1,reqBodyValidationHandler:j1,handleBeforeExit:Q1,handleExit:W1,handleSigint:J1,handleSigquit:Z1,handleSigterm:X1}});var Bb=h((az,Pb)=>{"use strict";var rJ=require("fastify-plugin"),{handlePostRequest:Mb,authHandler:sJ,reqBodyValidationHandler:nJ}=Zd();async function iJ(e){e.decorate("hdbCore",{preValidation:[nJ,sJ],request:Mb,requestWithoutAuthentication:t=>Mb(t,!0)})}a(iJ,"hdbCore");Pb.exports=rJ(iJ)});var Hb=h(()=>{"use strict";var aJ=require("util"),oJ=require("path"),oz=require("fast-glob"),X_=require("fs"),cJ=require("fastify"),_J=require("@fastify/cors"),uJ=require("@fastify/static"),lJ=require("@fastify/autoload"),EJ=eh(),Xd=V(),zd=T(),W=g(),dJ=Kr(),hJ=gr(),SJ=SA(),fJ=NA(),{PACKAGE_ROOT:cz}=T(),TJ=bA(),mJ=UA(),RJ=DA(),AJ=aJ.promisify(dJ.setSchemaDataToGlobal),{handleServerUncaughtException:pJ,serverErrorHandler:OJ,handleBeforeExit:NJ,handleExit:gJ,handleSigint:IJ,handleSigquit:bJ,handleSigterm:CJ}=Zd(),wJ="TRUE",z_,vb=Xd.get(zd.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY);async function UJ(){try{try{global.hdb_ipc=new SJ(process.pid,fJ)}catch(s){throw W.error("Error instantiating new instance of IPC client in Custom Functions server"),W.error(s),s}W.info("In Custom Functions Fastify server"+process.cwd()),W.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),W.debug(`Custom Functions server process ${process.pid} starting up.`),process.on("uncaughtException",pJ),process.on("beforeExit",NJ),process.on("exit",gJ),process.on("SIGINT",IJ),process.on("SIGQUIT",bJ),process.on("SIGTERM",CJ),await LJ();let e=Xd.get(zd.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS),t=parseInt(Xd.get(zd.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_PORT),10),r=e&&(e===!0||e.toUpperCase()===wJ);try{z_=DJ(r)}catch(s){throw W.error(`Custom Functions buildServer error: ${s}`),s}try{await z_.ready()}catch(s){throw W.error(`Custom Functions server.ready() error: ${s}`),s}try{W.info(`Custom Functions process starting on port ${t}`),await z_.listen({port:t,host:"::"}),W.info(`Custom Functions process running on port ${t}`)}catch(s){throw z_.close(),W.error(`Custom Functions server.listen() error: ${s}`),s}}catch(e){W.error(`Custom Functions ${process.pid} Error: ${e}`),W.error(e),process.exit(1)}}a(UJ,"customFunctionsServer");async function LJ(){try{W.info("Custom Functions starting configuration."),await AJ(),await hJ.setUsersToGlobal(),W.info("Custom Functions completed configuration.")}catch(e){W.error(e)}}a(LJ,"setUp");async function yJ(e){try{W.info("Custom Functions starting buildRoutes"),await e.register(Bb()),await e.after(),X_.readdirSync(vb,{withFileTypes:!0}).forEach(r=>{if(!r.isDirectory()&&!r.isSymbolicLink())return;let s=r.name,n=oJ.join(vb,s);W.trace("Loading project folder "+n);let i=`${n}/routes`,o=`${n}/static`,c=`${n}/static/index.html`,_=`/${s}/static`,u=X_.existsSync(i),l=X_.existsSync(o)&&X_.existsSync(c);u&&e.register(lJ,E=>({dir:i,dirNameRoutePrefix:!1,options:{hdbCore:E.hdbCore,logger:W,prefix:`/${s}`}})).after((E,d,S)=>{E&&E.message?W.error(E.message):E&&W.error(E),S()}),l&&(W.info(`Custom Functions setting up webserver for ${s}`),e.register(uJ,{root:o}).after((E,d,S)=>{E&&E.message?W.error(E.message):E&&W.error(E),S()}),e.get(_,(E,d)=>d.sendFile("index.html",o)))}),W.info("Custom Functions completed buildRoutes")}catch(t){W.error(`Custom Functions errored buildRoutes: ${t}`)}}a(yJ,"buildRoutes");function DJ(e){try{W.info("Custom Functions starting buildServer.");let t=TJ(e),r=cJ(t);r.server.headersTimeout=RJ(),r.setErrorHandler(OJ);let s=mJ();return s&&r.register(_J,s),r.register(EJ),r.register(yJ),W.info("Custom Functions completed buildServer."),r}catch(t){W.error(`Custom Functions process ${process.pid} buildServer error: ${t}`),W.fatal(t),process.exit(1)}}a(DJ,"buildServer");(async()=>await UJ())()});Hb();
12
+ `,""):null}catch(d){d.stderr?i[_].npm_error=Bg(d.stderr):i[_].npm_error=d.message;continue}try{i[_].npm_output=JSON.parse(l)}catch{i[_].npm_output=l}try{i[_].npm_error=JSON.parse(E)}catch{i[_].npm_error=E}}return l_.info(`finished installModules with response ${i}`),i}a(HK,"installModules");function Bg(e){let t='"error": {',r=e.indexOf('"error": {'),s=e.indexOf(`}
13
+ `);return r>-1&&s>-1?JSON.parse(e.substring(r+t.length-1,s+1)):e}a(Bg,"parseNPMStdErr");async function qK(e){l_.info(`starting auditModules for request: ${e}`);let t=qg(e);if(t)throw Hn(t,t.message,qn.BAD_REQUEST);let{projects:r}=e;await vg(),await Hg(r);let s={};for(let n=0,i=r.length;n<i;n++){let o=r[n],c=u_.join(fd,o);s[o]={npm_output:null,npm_error:null};try{let _=await Pg("npm audit --json",c);s[o].npm_output=JSON.parse(_)}catch(_){s[o].npm_error=Bg(_.stderr)}}return l_.info(`finished auditModules with response ${s}`),s}a(qK,"auditModules");async function vg(){try{return await Pg("npm -v"),!0}catch{throw Hn(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",qn.BAD_REQUEST,void 0,void 0,!0)}}a(vg,"checkNPMInstalled");async function Hg(e){if(!Array.isArray(e)||e.length===0)throw Hn(new Error,"projects argument must be an array with at least 1 element",qn.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s],o=u_.join(fd,i.toString());if(!await Lg.pathExists(o)){t.push(i);continue}let _=u_.join(o,"package.json");await Lg.pathExists(_)||r.push(i)}if(t.length>0)throw Hn(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,qn.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Hn(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,qn.BAD_REQUEST,void 0,void 0,!0)}a(Hg,"checkProjectPaths");function qg(e){let t=__.object({projects:__.array().min(1).items(__.string()).required(),dry_run:__.boolean().default(!1)});return BK.validateBySchema(e,t)}a(qg,"modulesValidator")});var Vg=h((I2,Fg)=>{"use strict";var E_=class{constructor(t,r,s=[],n=[]){this.schema=t,this.table=r,this.required_table_permissions=s,this.required_attribute_permissions=n}};a(E_,"PermissionTableResponseObject");Fg.exports=E_});var kg=h((b2,$g)=>{"use strict";var d_=class{constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};a(d_,"PermissionAttributeResponseObject");$g.exports=d_});var md=h((C2,Yg)=>{"use strict";var xg=Vg(),GK=kg(),{HDB_ERROR_MSGS:FK}=We(),h_=class{constructor(){this.error=FK.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,s){if(r&&s){let n=`${r}_${s}`;if(this.unauthorized_access[n])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,s){let n=new xg(t,r,s),i=`${t}_${r}`;this.unauthorized_access[i]=n}addUnauthorizedAttributes(t,r,s,n){let i=[];t.forEach(c=>{let _=new GK(c,n[c]);i.push(_)});let o=`${r}_${s}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new xg(r,s,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};a(h_,"PermissionResponseObject");Yg.exports=h_});var m_=h((w2,aI)=>{"use strict";var Rd=Lt(),S_=Tt(),Bt=uc(),Zi=Ss(),Ad=ms(),VK=_E(),zi=Rr(),f_=mE(),Oe=g(),$K=pE(),kK=Lc(),xK=qE(),YK=Pc(),KK=GE(),WK=$E(),pd=YE(),br=b(),QK=EN(),Od=QE(),Qg=ad(),Pt=T(),Jg=Eg(),JK=bc(),Xg=rc(),Zg=Er(),Cr=dd(),XK=require("alasql"),zg=c_(),jg=Td(),eI=md(),{handleHDBError:Et,hdb_errors:tI}=D(),{HDB_ERROR_MSGS:Fe,HTTP_STATUS_CODES:Ji}=tI,p=new Map,rI="delete",ts="insert",or="read",Bs="update",Xi="describe",Kg=Zi.describeSchema.name,Wg=Zi.describeTable.name,sI={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},ZK="catchup",zK="handleGetJob",jK="handleGetJobsByStartDate",T_={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},eW=[Bt.createTable.name,Bt.createAttribute.name,Bt.dropTable.name,Bt.dropAttribute.name],nI={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},O=class{constructor(t,r){this.requires_su=t,this.perms=r}};a(O,"permission");p.set(Rd.insert.name,new O(!1,[ts]));p.set(Rd.update.name,new O(!1,[Bs]));p.set(Rd.upsert.name,new O(!1,[ts,Bs]));p.set(S_.searchByConditions.name,new O(!1,[or]));p.set(S_.searchByHash.name,new O(!1,[or]));p.set(S_.searchByValue.name,new O(!1,[or]));p.set(S_.search.name,new O(!1,[or]));p.set(Bt.createSchema.name,new O(!0,[]));p.set(Bt.createTable.name,new O(!0,[]));p.set(Bt.createAttribute.name,new O(!1,[ts]));p.set(Bt.dropSchema.name,new O(!0,[]));p.set(Bt.dropTable.name,new O(!0,[]));p.set(Bt.dropAttribute.name,new O(!0,[]));p.set(Zi.describeSchema.name,new O(!1,[or]));p.set(Zi.describeTable.name,new O(!1,[or]));p.set(Ad.deleteRecord.name,new O(!1,[rI]));p.set(zi.addUser.name,new O(!0,[]));p.set(zi.alterUser.name,new O(!0,[]));p.set(zi.dropUser.name,new O(!0,[]));p.set(zi.listUsersExternal.name,new O(!0,[]));p.set(f_.listRoles.name,new O(!0,[]));p.set(f_.addRole.name,new O(!0,[]));p.set(f_.alterRole.name,new O(!0,[]));p.set(f_.dropRole.name,new O(!0,[]));p.set($K.name,new O(!0,[]));p.set(kK.name,new O(!0,[]));p.set(xK.name,new O(!0,[]));p.set(YK.name,new O(!0,[]));p.set(KK.name,new O(!0,[]));p.set(pd.setRoutes.name,new O(!0,[]));p.set(pd.getRoutes.name,new O(!0,[]));p.set(pd.deleteRoutes.name,new O(!0,[]));p.set(Zg.setConfiguration.name,new O(!0,[]));p.set(WK.clusterStatus.name,new O(!0,[]));p.set(Od.getFingerprint.name,new O(!0,[]));p.set(Od.setLicense.name,new O(!0,[]));p.set(Ad.deleteFilesBefore.name,new O(!0,[]));p.set(Ad.deleteAuditLogsBefore.name,new O(!0,[]));p.set(Qg.restartProcesses.name,new O(!0,[]));p.set(Qg.restartService.name,new O(!0,[]));p.set(VK.name,new O(!0,[]));p.set(JK.systemInformation.name,new O(!0,[]));p.set(Zg.getConfiguration.name,new O(!0,[]));p.set(zg.readTransactionLog.name,new O(!0,[]));p.set(zg.deleteTransactionLogsBefore.name,new O(!0,[]));p.set(jg.installModules.name,new O(!0,[]));p.set(jg.auditModules.name,new O(!0,[]));p.set(Xg.createTokens.name,new O(!1,[]));p.set(Xg.refreshOperationToken.name,new O(!1,[]));p.set(Cr.customFunctionsStatus.name,new O(!0,[]));p.set(Cr.getCustomFunctions.name,new O(!0,[]));p.set(Cr.getCustomFunction.name,new O(!0,[]));p.set(Cr.setCustomFunction.name,new O(!0,[]));p.set(Cr.dropCustomFunction.name,new O(!0,[]));p.set(Cr.addCustomFunctionProject.name,new O(!0,[]));p.set(Cr.dropCustomFunctionProject.name,new O(!0,[]));p.set(Cr.packageCustomFunctionProject.name,new O(!0,[]));p.set(Cr.deployCustomFunctionProject.name,new O(!0,[]));p.set(Od.getRegistrationInfo.name,new O(!1,[]));p.set(zi.userInfo.name,new O(!1,[]));p.set(Zi.describeAll.name,new O(!1,[]));p.set(zK,new O(!1,[]));p.set(jK,new O(!0,[]));p.set(ZK,new O(!0,[]));p.set(T_.CSV_DATA_LOAD,new O(!1,[ts,Bs]));p.set(T_.CSV_URL_LOAD,new O(!1,[ts,Bs]));p.set(T_.CSV_FILE_LOAD,new O(!1,[ts,Bs]));p.set(T_.IMPORT_FROM_S3,new O(!1,[ts,Bs]));p.set(nI.EXPORT_TO_S3,new O(!1,[or]));p.set(nI.EXPORT_LOCAL,new O(!1,[or]));p.set(Pt.VALID_SQL_OPS_ENUM.DELETE,new O(!1,[rI]));p.set(Pt.VALID_SQL_OPS_ENUM.SELECT,new O(!1,[or]));p.set(Pt.VALID_SQL_OPS_ENUM.INSERT,new O(!1,[ts]));p.set(Pt.VALID_SQL_OPS_ENUM.UPDATE,new O(!1,[Bs]));aI.exports={verifyPerms:rW,verifyPermsAst:tW,verifyBulkLoadAttributePerms:nW};function tW(e,t,r){if(br.isEmptyOrZeroLength(e))throw Oe.info("verify_perms_ast has an empty user parameter"),Et(new Error);if(br.isEmptyOrZeroLength(t))throw Oe.info("verify_perms_ast has an empty user parameter"),Et(new Error);if(br.isEmptyOrZeroLength(r))throw Oe.info("verify_perms_ast has a null operation parameter"),Et(new Error);try{let s=new eI,n=new QK(e),i=n.getSchemas(),o=new Map;if((!i||i.length===0)&&n.affected_attributes&&n.affected_attributes.size>0)throw Oe.info("No schemas defined in verifyPermsAst(), will not continue."),Et(new Error);let c=!!t.role.permission.super_user,_=i.includes("system");if(_&&sI[r])throw Et(new Error,Fe.DROP_SYSTEM,Ji.FORBIDDEN);if(c&&!_)return null;let u=Jg.getRolePermissions(t.role);t.role.permission=u,!c&&e instanceof XK.yy.Select&&(e=n.updateAttributeWildcardsForRolePerms(u));for(let E=0;E<i.length;E++){let d=n.getTablesBySchemaName(i[E]);d&&o.set(i[E],d)}let l=iI(t,r,o,s);return l||(o.forEach((E,d)=>{for(let S=0;S<E.length;S++){let m=n.getAttributesBySchemaTableName(d,E[S]),R=gd(t.role.permission,d,E[S]);Nd(m,R,r,E[S],d,s)}}),s.getPermsResponse())}catch(s){throw Et(s)}}a(tW,"verifyPermsAst");function rW(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw Oe.info("null required parameter in verifyPerms"),Et(new Error,Fe.DEFAULT_INVALID_REQUEST,Ji.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let s=e.action,n=e.schema,i=e.table,o=new Map;n&&i&&o.set(n,[i]);let c=new eI;if(br.isEmptyOrZeroLength(e.hdb_user.role)||br.isEmptyOrZeroLength(e.hdb_user.role.permission))return Oe.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Fe.USER_HAS_NO_PERMS(e.hdb_user.username));let _=!!e.hdb_user.role.permission.super_user,u=e.hdb_user.role.permission.structure_user,l=o.has(Pt.SYSTEM_SCHEMA_NAME)||n===Pt.SYSTEM_SCHEMA_NAME;if(l&&sI[r])throw Et(new Error,Fe.DROP_SYSTEM,Ji.FORBIDDEN);if(_&&!l||u===!0&&(r===Bt.createSchema.name||r===Bt.dropSchema.name))return null;if(eW.indexOf(r)>=0&&(u===!0||Array.isArray(u)))return u===!0||u.indexOf(n)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${n}'`);let E=Jg.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=E,r===Kg||r===Wg){if(n===Pt.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Fe.SCHEMA_PERM_ERROR(n));if(!E.super_user){if(r===Kg&&(!E[n]||!E[n][Xi]))return c.handleInvalidItem(Fe.SCHEMA_NOT_FOUND(n));if(r===Wg&&(!E[n]||!E[n].tables[i]||!E[n].tables[i][Xi]))return c.handleInvalidItem(Fe.TABLE_NOT_FOUND(n,i))}}let d=iI(e.hdb_user,r,o,c,s);if(d)return d;if(p.get(r)&&p.get(r).perms.length===0)return null;if(!_&&e.get_attributes&&Pt.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let R=[],w=E[n].tables[i];w[Pt.PERMS_CRUD_ENUM.READ]&&(w.attribute_permissions.length>0?w.attribute_permissions.filter(B=>B[Pt.PERMS_CRUD_ENUM.READ]).forEach(B=>{R.push(B.attribute_name)}):R=global.hdb_schema[n][i].attributes.map(U=>U.attribute),e.get_attributes=R)}let S=sW(e),m=gd(e.hdb_user.role.permission,n,i);return Nd(S,m,r,i,n,c,s),c.getPermsResponse()}a(rW,"verifyPerms");function iI(e,t,r,s,n){if(br.arrayHasEmptyValues([e,t,r]))throw Oe.info("hasPermissions has an invalid parameter"),Et(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&!i)return null;if(!p.get(t))throw Oe.info(`operation ${t} not found.`),Et(new Error,Fe.OP_NOT_FOUND(t),Ji.BAD_REQUEST);if(p.get(t)&&p.get(t).requires_su)return Oe.info(`operation ${t} requires SU permissions.`),s.handleUnauthorizedItem(Fe.OP_IS_SU_ONLY(t));let c=r.keys();for(let _ of c){try{if(_&&!o[_]||o[_][Xi]===!1){s.addInvalidItem(Fe.SCHEMA_NOT_FOUND(_));continue}}catch{s.addInvalidItem(Fe.SCHEMA_NOT_FOUND(_));continue}let u=r.get(_);for(let l of u){let E=o[_].tables[l];if(!E||E[Xi]===!1)s.addInvalidItem(Fe.TABLE_NOT_FOUND(_,l));else try{let d=[],S=p.get(t).perms;!br.isEmpty(n)&&S.includes(n)&&(S=[n]);for(let m=0;m<S.length;m++){let R=S[m],w=E[R];(w==null||w===!1)&&(Oe.info(`Required ${R} permission not found for ${t} ${n?`${n} `:""}operation in role ${e.role.id}`),d.push(R))}d.length>0&&s.addUnauthorizedTable(_,l,d)}catch(d){let S=Fe.UNKNOWN_OP_AUTH_ERROR(t,_,l);throw Oe.error(S),Oe.error(d),Et(tI.CHECK_LOGS_WRAPPER(S))}}}return r.size<2?s.getPermsResponse():null}a(iI,"hasPermissions");function Nd(e,t,r,s,n,i,o){if(!e||!t)throw Oe.info("no attributes specified in checkAttributePerms."),Et(new Error);let c=p.get(r).perms;if(!c||c==="")throw Oe.info(`no permissions found for ${r} in checkAttributePerms().`),Et(new Error);if(br.isEmptyOrZeroLength(t))return Oe.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let _={};for(let l of e){let E=t.get(l);if(E){if(E[Xi]===!1){i.addInvalidItem(Fe.ATTR_NOT_FOUND(n,s,l),n,s);continue}if(c)for(let d of c){if(Pt.TIME_STAMP_NAMES.includes(E.attribute_name)&&d!==or)throw Et(new Error,Fe.SYSTEM_TIMESTAMP_PERMS_ERR,Ji.FORBIDDEN);E[d]===!1&&(_[E.attribute_name]?_[E.attribute_name].push(d):_[E.attribute_name]=[d])}}else i.addInvalidItem(Fe.ATTR_NOT_FOUND(n,s,l),n,s)}let u=Object.keys(_);u.length>0&&i.addUnauthorizedAttributes(u,n,s,_)}a(Nd,"checkAttributePerms");function sW(e){let t=new Set;try{if(e.action)return t;if(e.operation===Pt.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let s=Object.keys(e.records[r]);for(let n=0;n<s.length;n++)t.add(s[n])}}catch(r){Oe.info(r)}return t}a(sW,"getRecordAttributes");function gd(e,t,r){let s=new Map;if(br.isEmpty(e))return Oe.info("no hdb_user specified in getAttributePermissions"),s;if(e.super_user||!t||!r)return s;try{e[t].tables[r].attribute_permissions.forEach(n=>{s.has(n.attribute_name)||s.set(n.attribute_name,n)})}catch{Oe.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return s}a(gd,"getAttributePermissions");function nW(e,t,r,s,n,i,o){let c=new Set(i),_=gd(e,s,n);Nd(c,_,t,n,s,o,r)}a(nW,"verifyBulkLoadAttributePerms")});var A_=h((U2,lI)=>{"use strict";lI.exports={evaluateSQL:RW,processAST:uI,convertSQLToAST:_I,checkASTPermissions:cI};var oI=Lt(),Cd=require("util"),iW=Cd.callbackify(oI.insert),aW=Tt().search,oW=Sp().update,cW=Cd.callbackify(oW),_W=Tp().convertDelete,rs=require("alasql"),uW=m_(),ea=g(),lW=Uo(),EW=b(),ji=T(),{hdb_errors:dW,handleHDBError:Id}=D(),{HTTP_STATUS_CODES:bd}=dW,hW=Rn();function SW(e,t,r){return Promise.all([hW.postOperationHandler(e,t,r),oI.flush(e)])}a(SW,"postWrite");var fW=Cd.callbackify(SW);lW(rs);var TW=403,mW="There was a problem performing this insert. Please check the logs and try again.",R_=class{constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};a(R_,"ParsedSQLObject");function RW(e,t){let r=e.parsed_sql_object;if(!r){r=_I(e.sql);let s,n=r.ast.statements[0];if(n instanceof rs.yy.Insert?s=n.into.databaseid:n instanceof rs.yy.Select?s=n.from?n.from[0].databaseid:null:n instanceof rs.yy.Update||n instanceof rs.yy.Delete?s=n.table.databaseid:ea.error("AST in evaluateSQL is not a valid SQL type."),!(n instanceof rs.yy.Select)&&EW.isEmptyOrZeroLength(s))return t("No schema specified",null)}uI(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}a(RW,"evaluateSQL");function cI(e,t){let r;try{r=uW.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(s){throw s}return r||null}a(cI,"checkASTPermissions");function _I(e){let t=new R_;if(!e)throw Id(new Error,"The 'sql' parameter is missing from the request body",bd.BAD_REQUEST);try{let r=e.trim(),s=rs.parse(r),n=r.split(" ")[0].toLowerCase();t.ast=s,t.variant=n}catch(r){let s=r.message.split(`
14
+ `);throw s[1]?Id(r,`Invalid SQL at: ${s[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,bd.BAD_REQUEST):Id(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",bd.BAD_REQUEST)}return t}a(_I,"convertSQLToAST");function uI(e,t,r){try{let s=AW;if(!e.bypass_auth&&!t.permissions_checked){let i=cI(e,t);if(i&&i.length>0)return r(TW,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case ji.VALID_SQL_OPS_ENUM.SELECT:s=aW,n=t.ast.statements[0];break;case ji.VALID_SQL_OPS_ENUM.INSERT:s=pW;break;case ji.VALID_SQL_OPS_ENUM.UPDATE:s=cW;break;case ji.VALID_SQL_OPS_ENUM.DELETE:s=_W;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}s(n,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(s){return r(s)}}a(uI,"processAST");function AW(e,t){ea.info(e),t("unknown sql statement")}a(AW,"nullFunction");function pW({statement:e,hdb_user:t},r){let s=e.into,n={schema:s.databaseid,table:s.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{n.records=OW(i,e.values)}catch(o){return r(o)}iW(n,(o,c)=>{if(o)return r(o);fW(n,c,_=>{_&&ea.error(_)});try{delete c.new_attributes,delete c.txn_time}catch(_){ea.error(`Error delete new_attributes from insert response: ${_}`)}r(null,c)})}a(pW,"convertInsert");function OW(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let s={};return r.forEach((n,i)=>{if(n.columnid)throw"cannot use a column in insert value";"value"in n?s[e[i]]=n.value:s[e[i]]=rs.compile(`SELECT ${n.toString()} AS [${ji.FUNC_VAL}] FROM ?`)}),s})}catch(r){throw ea.error(r),new Error(mW)}}a(OW,"createDataObjects")});var Ud=h((L2,fI)=>{var I_=require("clone"),b_=de(),NW=b(),g_=T(),gW=g(),p_=require("fs"),{hdb_errors:IW,handleHDBError:ta}=D(),{HDB_ERROR_MSGS:bW,HTTP_STATUS_CODES:O_}=IW,{common_validators:N_}=hr(),EI=1e9,wd=" is required",CW=["insert","update","upsert"],C_={schema:{presence:!0,format:N_.schema_format,length:N_.schema_length},table:{presence:!0,format:N_.schema_format,length:N_.schema_length},action:{inclusion:{within:CW,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{}},{AWS_ACCESS_KEY:wW,AWS_SECRET:UW,AWS_BUCKET:LW,AWS_FILE_KEY:yW}=g_.S3_BUCKET_AUTH_KEYS,DW={s3:{presence:!0},[`s3.${wW}`]:{presence:!0,type:"String"},[`s3.${UW}`]:{presence:!0,type:"String"},[`s3.${LW}`]:{presence:!0,type:"String"},[`s3.${yW}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]}},dI=I_(C_);dI.data.presence={message:wd};var hI=I_(C_);hI.file_path.presence={message:wd};var MW=Object.assign(I_(C_),DW),SI=I_(C_);SI.csv_url.presence={message:wd};function PW(e){let t=b_.validateObject(e,dI);return w_(e,t)}a(PW,"dataObject");function BW(e){let t=b_.validateObject(e,SI);return w_(e,t)}a(BW,"urlObject");function vW(e){let t=b_.validateObject(e,hI);return w_(e,t)}a(vW,"fileObject");function HW(e){let t=b_.validateObject(e,MW);return w_(e,t)}a(HW,"s3FileObject");function w_(e,t){if(!t){let r=NW.checkGlobalSchemaTable(e.schema,e.table);if(r)return ta(new Error,r,O_.BAD_REQUEST);if(e.operation===g_.OPERATIONS_ENUM.CSV_FILE_LOAD){try{p_.accessSync(e.file_path,p_.constants.R_OK|p_.constants.F_OK)}catch(s){return s.code===g_.NODE_ERROR_CODES.ENOENT?ta(s,`No such file or directory ${s.path}`,O_.BAD_REQUEST):s.code===g_.NODE_ERROR_CODES.EACCES?ta(s,`Permission denied ${s.path}`,O_.BAD_REQUEST):ta(s)}try{let s=p_.statSync(e.file_path).size;if(s>EI)return ta(new Error,bW.MAX_FILE_SIZE_ERR(s,EI),O_.BAD_REQUEST)}catch(s){gW.error(s),console.error(s)}}}return t}a(w_,"postValidateChecks");fI.exports={dataObject:PW,urlObject:BW,fileObject:vW,s3FileObject:HW}});var Ld=h((y2,TI)=>{"use strict";var ra=g(),U_=T();async function qW(e,t,r,s=[]){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let n;try{return n=await e(t),r&&await r(t,n,s),t.operation===U_.OPERATIONS_ENUM.INSERT||t.operation===U_.OPERATIONS_ENUM.UPDATE||t.operation===U_.OPERATIONS_ENUM.UPSERT?(delete n.new_attributes,delete n.txn_time):t.operation===U_.OPERATIONS_ENUM.DELETE&&delete n.txn_time,n}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(ra.info(i.message),i):i.http_resp_msg?(ra.error(`Error calling operation: ${e.name}`),ra.error(i.http_resp_msg),i):(ra.error(`Error calling operation: ${e.name}`),ra.error(i),i)}}a(qW,"callOperationFunctionAsAwait");TI.exports={callOperationFunctionAsAwait:qW}});var yd=h((D2,RI)=>{"use strict";var GW=require("aws-sdk/clients/s3");RI.exports={getFileStreamFromS3:FW,getS3AuthObj:mI};function FW(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return mI(t.aws_access_key_id,t.aws_secret_access_key).getObject(r).createReadStream()}a(FW,"getFileStreamFromS3");function mI(e,t){return new GW({accessKeyId:e,secretAccessKey:t})}a(mI,"getS3AuthObj")});var pI=h((M2,AI)=>{"use strict";var L_=class{constructor(t,r,s,n,i,o,c=null){this.op=t,this.action=r,this.schema=s,this.table=n,this.file_path=i,this.file_type=o,this.role_perms=c}};a(L_,"BulkLoadFileObject");var y_=class{constructor(t,r,s,n){this.action=t,this.schema=r,this.table=s,this.data=n}};a(y_,"BulkLoadDataObject");AI.exports={BulkLoadFileObject:L_,BulkLoadDataObject:y_}});var vd=h((P2,qI)=>{"use strict";var D_=Lt(),B_=Ud(),VW=require("needle"),Ot=T(),$W=Se(),sa=b(),{handleHDBError:oe,hdb_errors:LI}=D(),{HTTP_STATUS_CODES:Ve,HDB_ERROR_MSGS:Ne,CHECK_LOGS_WRAPPER:qs}=LI,Hs=g(),M_=require("papaparse");sa.promisifyPapaParse();var Qt=require("fs-extra"),kW=require("path"),{chain:OI}=require("stream-chain"),NI=require("stream-json/streamers/StreamArray"),gI=require("stream-json/utils/Batch"),II=require("stream-chain/utils/comp"),{finished:bI}=require("stream"),Dd=V(),xW=Rn(),yI=Ld(),YW=yd(),{BulkLoadFileObject:Md,BulkLoadDataObject:KW}=pI(),Pd=md(),{verifyBulkLoadAttributePerms:DI}=m_(),WW=tE(),QW=Rt(),JW=Fr(),CI="No records parsed from csv file.",vs=`${Dd.get("HDB_ROOT")}/tmp`,{schema_regex:XW}=hr(),wI=1024*1024*5,UI=5e3,ZW={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};qI.exports={csvDataLoad:zW,csvURLLoad:jW,csvFileLoad:eQ,importFromS3:tQ};async function zW(e,t=[]){let r=B_.dataObject(e);if(r)throw oe(r,r.message,Ve.BAD_REQUEST,void 0,void 0,!0);let s={};try{let n=M_.parse(e.data,{header:!0,skipEmptyLines:!0,dynamicTyping:!0}),i=new Pd;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&DI(e.hdb_user.role.permission,this.job_operation_function.name,e.action,e.schema,e.table,n.meta.fields,i);let o=i.getPermsResponse();if(o)throw oe(new Error,o,Ve.BAD_REQUEST,void 0,void 0,!0);let c=new KW(e.action,e.schema,e.table,n.data);return s=await yI.callOperationFunctionAsAwait(BI,c,vI.bind(null,n.meta.fields),t),s.message===CI?CI:HI(s.records,s.number_written)}catch(n){throw Gs(n)}}a(zW,"csvDataLoad");async function jW(e){let t=B_.urlObject(e);if(t)throw oe(t,t.message,Ve.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,s=`${vs}/${r}`;try{await rQ(e.csv_url,r)}catch(n){throw Hs.error(Ne.DOWNLOAD_FILE_ERR(r)+" - "+n),oe(n,qs(Ne.DOWNLOAD_FILE_ERR(r)))}try{let n=new Md(this.job_operation_function.name,e.action,e.schema,e.table,s,Ot.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await Bd(n);return await P_(s),i}catch(n){throw await P_(s),Gs(n)}}a(jW,"csvURLLoad");async function eQ(e){let t=B_.fileObject(e);if(t)throw oe(t,t.message,Ve.BAD_REQUEST,void 0,void 0,!0);let r=new Md(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Ot.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await Bd(r)}catch(s){throw Gs(s)}}a(eQ,"csvFileLoad");async function tQ(e){let t=B_.s3FileObject(e);if(t)throw oe(t,t.message,Ve.BAD_REQUEST,void 0,void 0,!0);let r;try{let s=kW.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${vs}/${n}`;let i=new Md(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await sQ(n,e);let o=await Bd(i);return await P_(r),o}catch(s){throw await P_(r),Gs(s)}}a(tQ,"importFromS3");async function rQ(e,t){let r;try{r=await VW("get",e)}catch(s){let n=`Error downloading CSV file from ${e}, status code: ${s.statusCode}. Check the log for more information.`;throw oe(s,n,s.statusCode,Ot.LOG_LEVELS.ERROR,"Error downloading CSV file - "+s)}iQ(r,e),await nQ(t,r.raw)}a(rQ,"downloadCSVFile");async function sQ(e,t){try{let r=`${vs}/${e}`;await Qt.mkdirp(vs),await Qt.writeFile(`${vs}/${e}`,"",{flag:"a+"});let s=await Qt.createWriteStream(r),n=YW.getFileStreamFromS3(t);await new Promise((i,o)=>{n.on("error",function(c){o(c)}),n.pipe(s).on("error",function(c){o(c)}).on("close",function(){Hs.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Hs.error(Ne.S3_DOWNLOAD_ERR+" - "+r),oe(r,qs(Ne.S3_DOWNLOAD_ERR))}}a(sQ,"downloadFileFromS3");async function nQ(e,t){try{await Qt.mkdirp(vs),await Qt.writeFile(`${vs}/${e}`,t)}catch(r){throw Hs.error(Ne.WRITE_TEMP_FILE_ERR),oe(r,qs(Ne.DEFAULT_BULK_LOAD_ERR))}}a(nQ,"writeFileToTempFolder");async function P_(e){if(e)try{await Qt.access(e),await Qt.unlink(e)}catch{Hs.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(P_,"deleteTempFile");function iQ(e,t){if(e.statusCode!==LI.HTTP_STATUS_CODES.OK)throw oe(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Ve.BAD_REQUEST);if(!ZW[e.headers["content-type"]])throw oe(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Ve.BAD_REQUEST);if(!e.raw)throw oe(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Ve.BAD_REQUEST)}a(iQ,"validateURLResponse");async function Bd(e){try{let t;switch(e.file_type){case Ot.VALID_S3_FILE_TYPES.CSV:t=await aQ(e);break;case Ot.VALID_S3_FILE_TYPES.JSON:t=await oQ(e);break;default:throw oe(new Error,Ne.DEFAULT_BULK_LOAD_ERR,Ve.BAD_REQUEST,Ot.LOG_LEVELS.ERROR,Ne.INVALID_FILE_EXT_ERR(e))}return HI(t.records,t.number_written)}catch(t){throw Gs(t)}}a(Bd,"fileLoad");async function MI(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;n&&n.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await D_.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&DI(e.role_perms,e.op,e.action,e.schema,e.table,c,t),n&&n.resume()}catch(c){let _=oe(c);r(_)}}a(MI,"validateChunk");async function PI(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;sa.autoCastJSONDeep(i),n&&n.pause();let o=s.meta?s.meta.fields:null;if(o)i.forEach(c=>{!sa.isEmpty(c)&&!sa.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(_=>{Object.keys(_).forEach(u=>c.add(u))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},_=await yI.callOperationFunctionAsAwait(BI,c,vI.bind(null,o));t.records+=_.records,t.number_written+=_.number_written,n&&n.resume()}catch(c){let _=oe(c,qs(Ne.INSERT_CSV_ERR),Ve.INTERNAL_SERVER_ERROR,Ot.LOG_LEVELS.ERROR,Ne.INSERT_CSV_ERR+" - "+c);r(_)}}a(PI,"insertChunk");async function aQ(e){let t={records:0,number_written:0};try{let r=new Pd,s=Qt.createReadStream(e.file_path,{highWaterMark:wI});s.setEncoding("utf8"),await M_.parsePromise(s,MI.bind(null,e,r));let n=r.getPermsResponse();if(n)throw oe(new Error,n,Ve.BAD_REQUEST);return s=Qt.createReadStream(e.file_path,{highWaterMark:wI}),s.setEncoding("utf8"),await M_.parsePromise(s,PI.bind(null,e,t)),s.destroy(),t}catch(r){throw oe(r,qs(Ne.PAPA_PARSE_ERR),Ve.INTERNAL_SERVER_ERROR,Ot.LOG_LEVELS.ERROR,Ne.PAPA_PARSE_ERR+r)}}a(aQ,"callPapaParse");async function oQ(e){let t={records:0,number_written:0},r=a(s=>{throw s},"throwErr");try{let s=new Pd,n=OI([Qt.createReadStream(e.file_path,{encoding:"utf-8"}),NI.withParser(),c=>c.value,new gI({batchSize:UI}),II(async c=>{await MI(e,s,r,c)})]);await new Promise((c,_)=>{bI(n,u=>{u?_(u):c()}),n.resume()});let i=s.getPermsResponse();if(i)throw oe(new Error,i,Ve.BAD_REQUEST);let o=OI([Qt.createReadStream(e.file_path,{encoding:"utf-8"}),NI.withParser(),c=>c.value,new gI({batchSize:UI}),II(async c=>{await PI(e,t,r,c)})]);return await new Promise((c,_)=>{bI(o,u=>{u?_(u):c()}),o.resume()}),t}catch(s){throw oe(s,qs(Ne.INSERT_JSON_ERR),Ve.INTERNAL_SERVER_ERROR,Ot.LOG_LEVELS.ERROR,Ne.INSERT_JSON_ERR+s)}}a(oQ,"insertJson");async function BI(e){let t={};try{e.data&&e.data.length>0&&cQ(e.data[0])?t=await _Q(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Hs.info(t.message))}catch(r){throw Gs(r)}return t}a(BI,"callBulkFileLoad");function cQ(e){let t=Object.keys(e);for(let r of t)if(!XW.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(cQ,"validateColumnNames");async function _Q(e,t,r,s){s||(s="insert");let n={operation:s,schema:t,table:r,records:e},i;switch(s){case"insert":i=D_.insert;break;case"update":i=D_.update;break;case"upsert":i=D_.upsert;break;default:throw oe(new Error,Ne.INVALID_ACTION_PARAM_ERR(s),Ve.BAD_REQUEST,Ot.LOG_LEVELS.ERROR,Ne.INVALID_ACTION_PARAM_ERR(s))}try{let o=await i(n),c;switch(s){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,E=e.length;for(;E--;)o.skipped_hashes.indexOf(e[E][l])>=0&&e.splice(E,1)}let _=sa.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:_,new_attributes:o.new_attributes}}catch(o){throw Gs(o)}}a(_Q,"bulkFileLoad");async function vI(e,t,r,s=[]){try{if(t.data.length===0||!Dd.get(Ot.CONFIG_PARAMS.CLUSTERING_ENABLED))return;let n=M_.unparse(t.data,{header:!0,skipEmptyLines:!0,columns:e}),i;t.hdb_user&&t.hdb_user.username&&(i=t.hdb_user.username);let o={operation:"csv_data_load",action:t.action?t.action:"insert",schema:t.schema,table:t.table,data:n,__origin:new WW(r.txn_time,i,Dd.get(Ot.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY))};await QW.publishToStream(`${$W.SUBJECT_PREFIXES.TXN}.${t.schema}.${t.table}`,JW.createNatsTableStreamName(t.schema,t.table),[o],s),await xW.sendAttributeTransaction(r,t,s),delete r.new_attributes}catch(n){Hs.error(n)}}a(vI,"postCSVLoadFunction");function HI(e,t){return`successfully loaded ${t} of ${e} records`}a(HI,"buildResponseMsg");function Gs(e){return oe(e,qs(Ne.DEFAULT_BULK_LOAD_ERR),Ve.INTERNAL_SERVER_ERROR,Ot.LOG_LEVELS.ERROR,Ne.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(Gs,"buildTopLevelErrMsg")});var qd=h((B2,KI)=>{"use strict";var VI=Tt(),uQ=A_(),lQ=yd(),{AsyncParser:EQ,Transform:dQ}=require("json2csv"),na=require("stream"),hQ=require("events"),vt=b(),Hd=require("fs-extra"),SQ=require("path"),tt=g(),{promisify:v_}=require("util"),ia=b(),{handleHDBError:ge,hdb_errors:fQ}=D(),{HDB_ERROR_MSGS:Nt,HTTP_STATUS_CODES:Ie}=fQ,GI=["search_by_value","search_by_hash","sql"],FI=["json","csv"],$I="json",kI="csv",TQ="Successfully exported JSON locally.",mQ="Successfully exported CSV locally.",RQ=1e3,AQ=1e3,pQ=v_(VI.searchByHash),OQ=v_(VI.searchByValue),NQ=v_(uQ.evaluateSQL),gQ=v_(na.finished);KI.exports={export_to_s3:wQ,export_local:IQ};async function IQ(e){tt.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=xI(e);if(!vt.isEmpty(t))throw tt.error(t),ge(new Error,t,Ie.BAD_REQUEST,void 0,void 0,!0);if(vt.isEmpty(e.path))throw tt.error(Nt.MISSING_VALUE("path")),ge(new Error,Nt.MISSING_VALUE("path"),Ie.BAD_REQUEST,void 0,void 0,!0);let r=(vt.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(SQ.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=vt.buildFolderPath(e.path,r);try{await bQ(e.path);let n=await YI(e);return await CQ(s,e.format,n)}catch(n){throw tt.error(n),new Error(n)}}a(IQ,"export_local");async function bQ(e){if(tt.trace("in confirmPath"),vt.isEmptyOrZeroLength(e))throw ge(new Error,`Invalid path: ${e}`,Ie.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Hd.stat(e)}catch(r){let s;throw r.code==="ENOENT"?s=`path '${e}' does not exist`:r.code==="EACCES"?s=`access to path '${e}' is denied`:s=r.message,tt.error(s),ge(new Error,s,Ie.BAD_REQUEST,void 0,void 0,!0)}if(!t.isDirectory()){let r=`path '${e}' is not a directory, please supply a valid folder path`;throw tt.error(r),ge(new Error,r,Ie.BAD_REQUEST,void 0,void 0,!0)}return!0}a(bQ,"confirmPath");async function CQ(e,t,r){if(tt.trace("in saveToLocal"),ia.isEmptyOrZeroLength(e))throw ge(new Error,Nt.INVALID_VALUE("file_path"),Ie.BAD_REQUEST,void 0,void 0,!0);if(ia.isEmptyOrZeroLength(t))throw ge(new Error,Nt.INVALID_VALUE("Source format"),Ie.BAD_REQUEST,void 0,void 0,!0);if(ia.isEmpty(r))throw ge(new Error,Nt.NOT_FOUND("Data"),Ie.BAD_REQUEST,void 0,void 0,!0);if(t===$I){let s=Hd.createWriteStream(e),n=r.length;s.write("[");let i="";for await(let[o,c]of r.entries())i+=o===n-1?JSON.stringify(c):JSON.stringify(c)+",",o!==0&&o%AQ===0&&(s.write(i)||await hQ.once(s,"drain"),i="");return i.length!==0&&s.write(i),s.write("]"),s.end(),await gQ(s),TQ}else if(t===kI){let s=Hd.createWriteStream(e),n=na.Readable.from(r),i={},o={objectMode:!0};return await new EQ(i,o).fromInput(n).toOutput(s).promise(!1),mQ}throw ge(new Error,Nt.INVALID_VALUE("format"),Ie.BAD_REQUEST)}a(CQ,"saveToLocal");async function wQ(e){if(!e.s3||Object.keys(e.s3).length===0)throw ge(new Error,Nt.MISSING_VALUE("S3 object"),Ie.BAD_REQUEST);if(vt.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw ge(new Error,Nt.MISSING_VALUE("aws_access_key_id"),Ie.BAD_REQUEST);if(vt.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw ge(new Error,Nt.MISSING_VALUE("aws_secret_access_key"),Ie.BAD_REQUEST);if(vt.isEmptyOrZeroLength(e.s3.bucket))throw ge(new Error,Nt.MISSING_VALUE("bucket"),Ie.BAD_REQUEST);if(vt.isEmptyOrZeroLength(e.s3.key))throw ge(new Error,Nt.MISSING_VALUE("key"),Ie.BAD_REQUEST);let t=xI(e);if(!vt.isEmpty(t))throw ge(new Error,t,Ie.BAD_REQUEST);tt.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await YI(e)}catch(c){throw tt.error(c),c}let s,n=lQ.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key),i,o=new na.PassThrough;if(e.format===kI){i=e.s3.key+".csv";let c=na.Readable.from(r),_={},u={objectMode:!0},l=new dQ(_,u);l.on("error",E=>{throw E}),c.pipe(l).pipe(o)}else if(e.format===$I){i=e.s3.key+".json";let c=new na.Readable;c.pipe(o),c.on("error",l=>{throw l}),c.push("[");let _=r.length,u="";for(let[l,E]of r.entries())u+=l===_-1?JSON.stringify(E):JSON.stringify(E)+",",l!==0&&l%RQ===0&&(c.push(u),u="");u.length!==0&&c.push(u),c.push("]"),c.push(null)}else throw ge(new Error,Nt.INVALID_VALUE("format"),Ie.BAD_REQUEST);try{s=await n.upload({Bucket:e.s3.bucket,Key:i,Body:o}).promise()}catch(c){throw tt.error(c),c}return s}a(wQ,"export_to_s3");function xI(e){if(tt.trace("in exportCoreValidation"),vt.isEmpty(e.format))return"format missing";if(FI.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${FI.join(", ")}`;let t=e.search_operation.operation;if(vt.isEmpty(t))return"search_operation.operation missing";if(GI.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${GI.join(", ")}`}a(xI,"exportCoreValidation");async function YI(e){tt.trace("in getRecords");let t,r;if(ia.isEmpty(e.search_operation)||ia.isEmptyOrZeroLength(e.search_operation.operation))throw ge(new Error,Nt.INVALID_VALUE("Search operation"),Ie.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=OQ;break;case"search_by_hash":t=pQ;break;case"sql":t=NQ;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,tt.error(r),ge(new Error,r,Ie.BAD_REQUEST)}e.search_operation.hdb_user=e.hdb_user;try{return t(e.search_operation)}catch(s){throw tt.error(s),s}}a(YI,"getRecords")});var QI=h((v2,WI)=>{"use strict";var H_=class{constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};a(H_,"SqlSearchObject");WI.exports=H_});var ZI=h((H2,XI)=>{"use strict";var UQ=T(),JI=require("moment"),LQ=require("uuid").v4,q_=class{constructor(){this.id=LQ(),this.type=void 0,this.start_datetime=JI().valueOf(),this.created_datetime=JI().valueOf(),this.end_datetime=void 0,this.status=UQ.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};a(q_,"JobObject");XI.exports=q_});var Fd=h((q2,sb)=>{"use strict";var yQ=require("uuid").v4,eb=Lt(),tb=Tt(),DQ=Yt(),MQ=Es(),PQ=QI(),ce=T(),BQ=ZI(),vQ=Hl(),Ht=g(),HQ=jn(),Gn=b(),{promisify:Gd}=require("util"),Fs=require("moment"),qQ=A_(),G_=Ud(),zI=ml(),{deleteTransactionLogsBeforeValidator:GQ}=hd(),{handleHDBError:FQ,hdb_errors:VQ}=D(),{HTTP_STATUS_CODES:$Q}=VQ,jI=Gd(tb.searchByValue),kQ=Gd(tb.searchByHash),xQ=eb.insert,YQ=Gd(qQ.evaluateSQL),KQ=eb.update;sb.exports={addJob:JQ,updateJob:ZQ,handleGetJob:WQ,handleGetJobsByStartDate:QQ,getJobById:rb};async function WQ(e){try{let t=await rb(e.id);return Gn.isEmptyOrZeroLength(t)||(t[0].request!==void 0&&delete t[0].request,delete t[0].__createdtime__,delete t[0].__updatedtime__),t}catch(t){let r=`There was an error getting job: ${t}`;throw Ht.error(r),new Error(r)}}a(WQ,"handleGetJob");async function QQ(e){try{let t=await XQ(e);if(Ht.trace(`Searching for jobs from ${e.from_date} to ${e.to_date}`),t&&t.length>0)for(let r of t)r.start_datetime&&(r.start_datetime_converted=Fs(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=Fs(r.end_datetime)),r.request!==void 0&&delete r.request,delete r.__createdtime__,delete r.__updatedtime__;return t}catch(t){let r=`There was an error searching jobs by date: ${t}`;throw Ht.error(r),new Error(r)}}a(QQ,"handleGetJobsByStartDate");async function JQ(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Gn.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return Ht.info(l),t.error=l,t}if(!ce.JOB_TYPE_ENUM[e.operation])return Ht.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,s;switch(r){case ce.OPERATIONS_ENUM.CSV_FILE_LOAD:s=G_.fileObject(e);break;case ce.OPERATIONS_ENUM.CSV_URL_LOAD:s=G_.urlObject(e);break;case ce.OPERATIONS_ENUM.CSV_DATA_LOAD:s=G_.dataObject(e);break;case ce.OPERATIONS_ENUM.IMPORT_FROM_S3:s=G_.s3FileObject(e);break;case ce.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case ce.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:s=zI(e,"date");break;case ce.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:s=zI(e,"timestamp");break;case ce.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:s=GQ(e);break;default:break}if(s)throw FQ(s,s.message,$Q.BAD_REQUEST,void 0,void 0,!0);let n=new BQ;n.type=e.operation===ce.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?ce.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,n.type=e.operation,n.user=e.hdb_user.username;let i=new DQ(ce.SYSTEM_SCHEMA_NAME,ce.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",n.id,"id",["id"]),o;try{o=await jI(i)}catch(l){let E=`There was an error inserting a new job: ${l}`;return Ht.error(E),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){n.id=yQ();try{o=await jI(i)}catch(l){let E=`There was an error inserting a new job: ${l}`;return Ht.error(E),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return Ht.error("Error creating a job, could not find a unique job id."),t}n.request=e;let _=new HQ(ce.SYSTEM_SCHEMA_NAME,ce.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),u;try{u=await xQ(_)}catch(l){return Ht.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(u.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${n.operation} and id ${n.id}`;else{let l=`Created a job with type ${n.type} and id ${n.id}`;t.message=l,t.createdJob=n,t.success=!0,Ht.trace(l)}return t}a(JQ,"addJob");async function XQ(e){let t=Fs(e.from_date,Fs.ISO_8601),r=Fs(e.to_date,Fs.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let s=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,n=new PQ(s,e.hdb_user);try{return await YQ(n)}catch(i){throw Ht.error(`there was a problem searching for jobs from date ${e.from_date} to date ${e.to_date} ${i}`),new Error("there was an error searching for jobs. Please check the log for details.")}}a(XQ,"getJobsInDateRange");async function rb(e){if(Gn.isEmptyOrZeroLength(e))return Gn.errorizeMessage("Invalid job ID specified.");let t=new MQ(ce.SYSTEM_SCHEMA_NAME,ce.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await kQ(t)}catch(r){let s=`There was an error searching for a job by id: ${e} ${r}`;return Ht.error(s),Gn.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(rb,"getJobById");async function ZQ(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Gn.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===ce.JOB_STATUS_ENUM.COMPLETE||e.status===ce.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=Fs().valueOf());let t=new vQ(ce.SYSTEM_SCHEMA_NAME,ce.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;try{r=await KQ(t)}catch(s){throw new Error(s)}return r}a(ZQ,"updateJob")});var _b=h((G2,cb)=>{"use strict";var nb=b(),gt=T(),zQ=require("moment"),F_=vd(),V_=g(),ib=Fd(),ab=qd(),ob=ms(),jQ=jc(),e1=xi(),t1=c_(),$_=class{constructor(t,r){this.job=t,this.json=r}};a($_,"RunnerMessage");async function r1(e){if(!e||Object.keys(e).length===0)throw new Error("Empty runner passed to parseMessage");if(!e.json||Object.keys(e.json).length===0)throw new Error("Empty JSON passed to parseMessage");if(!e.job||Object.keys(e.job).length===0)throw new Error("Empty job passed to parseMessage");if(nb.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(nb.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case gt.JOB_TYPE_ENUM.csv_file_load:await wr(e,F_.csvFileLoad);break;case gt.JOB_TYPE_ENUM.csv_url_load:await wr(e,F_.csvURLLoad);break;case gt.JOB_TYPE_ENUM.csv_data_load:await wr(e,F_.csvDataLoad);break;case gt.JOB_TYPE_ENUM.import_from_s3:await wr(e,F_.importFromS3);break;case gt.JOB_TYPE_ENUM.empty_trash:break;case gt.JOB_TYPE_ENUM.export_local:await wr(e,ab.export_local);break;case gt.JOB_TYPE_ENUM.export_to_s3:await wr(e,ab.export_to_s3);break;case gt.JOB_TYPE_ENUM.delete_files_before:case gt.JOB_TYPE_ENUM.delete_records_before:await wr(e,ob.deleteFilesBefore);break;case gt.JOB_TYPE_ENUM.delete_audit_logs_before:await wr(e,ob.deleteAuditLogsBefore);break;case gt.JOB_TYPE_ENUM.delete_transaction_logs_before:await wr(e,t1.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(r1,"parseMessage");async function wr(e,t){try{e.job.status=gt.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=zQ().valueOf(),await ib.updateJob(e.job),await s1(e.job.id)}catch(r){let s=r.message!==void 0?r.message:r;typeof s=="string"?(s=`There was an error running ${t.name} job with id ${e.job.id} - ${s}`,r.message=s):V_.error(`There was an error running ${t.name} job with id ${e.job.id}`),V_.error(s),e.job.message=s,e.job.status=gt.JOB_STATUS_ENUM.ERROR;try{await ib.updateJob(e.job)}catch(n){throw V_.error(`Unable to update job with id ${e.job.id}`),n}throw r}}a(wr,"runJob");async function s1(e){let t=jQ.generateJobConfig(e);V_.trace("launching job process:",e),await e1.start(t)}a(s1,"launchJobProcess");cb.exports={parseMessage:r1,RunnerMessage:$_}});var lb=h((F2,ub)=>{"use strict";var k_=class{constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};a(k_,"OperationFunctionObject");ub.exports=k_});var gb=h((V2,Nb)=>{"use strict";var K_=Tt(),xd=A_(),x_=vd(),Fn=uc(),Vd=Ss(),oa=ms(),n1=_E(),aa=Rr(),Y_=mE(),Ur=dd(),$e=g(),i1=pE(),a1=Lc(),o1=qE(),c1=Pc(),_1=GE(),u1=$E(),$d=YE(),Eb=qd(),l1=m_(),Yd=Fd(),A=T(),{hdb_errors:_a,handleHDBError:ca}=D(),{HTTP_STATUS_CODES:db}=_a,kd=QE(),hb=ad(),W_=require("util"),Vs=Lt(),E1=$r(),d1=bc(),pb=Rn(),Sb=_b(),fb=rc(),Tb=Er(),mb=c_(),Rb=Td(),h1=Ld(),S1=W_.promisify(K_.searchByHash),f1=W_.promisify(K_.searchByValue),T1=W_.promisify(K_.search),m1=W_.promisify(xd.evaluateSQL),R1={[A.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[A.OPERATIONS_ENUM.CREATE_TABLE]:!0,[A.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[A.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[A.OPERATIONS_ENUM.DROP_TABLE]:!0,[A.OPERATIONS_ENUM.DROP_SCHEMA]:!0},N=lb();function A1(e,t,r){return Promise.all([pb.postOperationHandler(e,t,r),e.table?Vs.flush(e):null])}a(A1,"postWrite");async function p1(e,t){try{if(e.body.operation!=="read_log"&&($e.log_level===A.LOG_LEVELS.INFO||$e.log_level===A.LOG_LEVELS.DEBUG||$e.log_level===A.LOG_LEVELS.TRACE)){let{hdb_user:s,hdb_auth_header:n,password:i,...o}=e.body;$e.info(o)}}catch(s){$e.error(s)}let r=A.CLUSTER_OPERATIONS[e.body.operation]===void 0?null:A1;try{let s=await h1.callOperationFunctionAsAwait(t,e.body,r);if(typeof s!="object"&&(s={message:s}),s instanceof Error)throw s;return R1[e.body.operation]&&E1.setSchemaDataToGlobal(n=>{n&&$e.error(n)}),s}catch(s){throw $e.info(s),s}}a(p1,"processLocalTransaction");var Ab=g1();Nb.exports={chooseOperation:O1,getOperationFunction:Ob,processLocalTransaction:p1};function O1(e){let t;try{t=Ob(e)}catch(n){throw $e.error(`Error when selecting operation function - ${n}`),n}let{operation_function:r,job_operation_function:s}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let n=e.operation==="sql"?e.sql:e.search_operation.sql,i=xd.convertSQLToAST(n);if(e.parsed_sql_object=i,!e.bypass_auth){let o=xd.checkASTPermissions(e,i);if(o)throw $e.error(`${db.FORBIDDEN} from operation ${e.search_operation}`),ca(new Error,o,_a.HTTP_STATUS_CODES.FORBIDDEN)}}else if(!e.bypass_auth&&e.operation!==A.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS){let n=s===void 0?r:s,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=l1.verifyPerms(i,n);if(o)throw $e.error(`${db.FORBIDDEN} from operation ${e.operation}`),ca(new Error,o,_a.HTTP_STATUS_CODES.FORBIDDEN)}}catch(n){throw ca(n,"There was an error when trying to choose an operation path")}return r}a(O1,"chooseOperation");function Ob(e){if($e.trace(`getOperationFunction with operation: ${e.operation}`),Ab.has(e.operation))return Ab.get(e.operation);throw ca(new Error,_a.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),_a.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(Ob,"getOperationFunction");async function N1(e){$e.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),s=r[0],n=r[1];for(let i of t.transactions)try{i.schema=s,i.table=n,i[A.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case A.OPERATIONS_ENUM.INSERT:o=await Vs.insert(i);break;case A.OPERATIONS_ENUM.UPDATE:o=await Vs.update(i);break;case A.OPERATIONS_ENUM.UPSERT:o=await Vs.upsert(i);break;case A.OPERATIONS_ENUM.DELETE:o=await oa.deleteRecord(i);break;default:$e.warn("invalid operation in catchup");break}await pb.postOperationHandler(i,o,e)}catch(o){$e.info("Invalid operation in transaction"),$e.error(o)}}a(N1,"catchup");async function cr(e){let t,r;try{r=await Yd.addJob(e),t=r.createdJob;let s=new Sb.RunnerMessage(t,e);return await Sb.parseMessage(s),`Starting job with id ${t.id}`}catch(s){let n=`There was an error executing job: ${s.http_resp_msg?s.http_resp_msg:s}`;throw $e.error(n),ca(s,n)}}a(cr,"executeJob");function g1(){let e=new Map;return e.set(A.OPERATIONS_ENUM.INSERT,new N(Vs.insert)),e.set(A.OPERATIONS_ENUM.UPDATE,new N(Vs.update)),e.set(A.OPERATIONS_ENUM.UPSERT,new N(Vs.upsert)),e.set(A.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new N(K_.searchByConditions)),e.set(A.OPERATIONS_ENUM.SEARCH_BY_HASH,new N(S1)),e.set(A.OPERATIONS_ENUM.SEARCH_BY_VALUE,new N(f1)),e.set(A.OPERATIONS_ENUM.SEARCH,new N(T1)),e.set(A.OPERATIONS_ENUM.SQL,new N(m1)),e.set(A.OPERATIONS_ENUM.CSV_DATA_LOAD,new N(cr,x_.csvDataLoad)),e.set(A.OPERATIONS_ENUM.CSV_FILE_LOAD,new N(cr,x_.csvFileLoad)),e.set(A.OPERATIONS_ENUM.CSV_URL_LOAD,new N(cr,x_.csvURLLoad)),e.set(A.OPERATIONS_ENUM.IMPORT_FROM_S3,new N(cr,x_.importFromS3)),e.set(A.OPERATIONS_ENUM.CREATE_SCHEMA,new N(Fn.createSchema)),e.set(A.OPERATIONS_ENUM.CREATE_TABLE,new N(Fn.createTable)),e.set(A.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new N(Fn.createAttribute)),e.set(A.OPERATIONS_ENUM.DROP_SCHEMA,new N(Fn.dropSchema)),e.set(A.OPERATIONS_ENUM.DROP_TABLE,new N(Fn.dropTable)),e.set(A.OPERATIONS_ENUM.DROP_ATTRIBUTE,new N(Fn.dropAttribute)),e.set(A.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new N(Vd.describeSchema)),e.set(A.OPERATIONS_ENUM.DESCRIBE_TABLE,new N(Vd.describeTable)),e.set(A.OPERATIONS_ENUM.DESCRIBE_ALL,new N(Vd.describeAll)),e.set(A.OPERATIONS_ENUM.DELETE,new N(oa.deleteRecord)),e.set(A.OPERATIONS_ENUM.ADD_USER,new N(aa.addUser)),e.set(A.OPERATIONS_ENUM.ALTER_USER,new N(aa.alterUser)),e.set(A.OPERATIONS_ENUM.DROP_USER,new N(aa.dropUser)),e.set(A.OPERATIONS_ENUM.LIST_USERS,new N(aa.listUsersExternal)),e.set(A.OPERATIONS_ENUM.LIST_ROLES,new N(Y_.listRoles)),e.set(A.OPERATIONS_ENUM.ADD_ROLE,new N(Y_.addRole)),e.set(A.OPERATIONS_ENUM.ALTER_ROLE,new N(Y_.alterRole)),e.set(A.OPERATIONS_ENUM.DROP_ROLE,new N(Y_.dropRole)),e.set(A.OPERATIONS_ENUM.USER_INFO,new N(aa.userInfo)),e.set(A.OPERATIONS_ENUM.READ_LOG,new N(i1)),e.set(A.OPERATIONS_ENUM.ADD_NODE,new N(a1)),e.set(A.OPERATIONS_ENUM.UPDATE_NODE,new N(o1)),e.set(A.OPERATIONS_ENUM.REMOVE_NODE,new N(c1)),e.set(A.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new N(_1)),e.set(A.OPERATIONS_ENUM.SET_CONFIGURATION,new N(Tb.setConfiguration)),e.set(A.OPERATIONS_ENUM.CLUSTER_STATUS,new N(u1.clusterStatus)),e.set(A.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new N($d.setRoutes)),e.set(A.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new N($d.getRoutes)),e.set(A.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new N($d.deleteRoutes)),e.set(A.OPERATIONS_ENUM.EXPORT_TO_S3,new N(cr,Eb.export_to_s3)),e.set(A.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new N(cr,oa.deleteFilesBefore)),e.set(A.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new N(cr,oa.deleteFilesBefore)),e.set(A.OPERATIONS_ENUM.EXPORT_LOCAL,new N(cr,Eb.export_local)),e.set(A.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new N(Yd.handleGetJobsByStartDate)),e.set(A.OPERATIONS_ENUM.GET_JOB,new N(Yd.handleGetJob)),e.set(A.OPERATIONS_ENUM.GET_FINGERPRINT,new N(kd.getFingerprint)),e.set(A.OPERATIONS_ENUM.SET_LICENSE,new N(kd.setLicense)),e.set(A.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new N(kd.getRegistrationInfo)),e.set(A.OPERATIONS_ENUM.RESTART,new N(hb.restartProcesses)),e.set(A.OPERATIONS_ENUM.RESTART_SERVICE,new N(hb.restartService)),e.set(A.OPERATIONS_ENUM.CATCHUP,new N(N1)),e.set(A.OPERATIONS_ENUM.SYSTEM_INFORMATION,new N(d1.systemInformation)),e.set(A.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new N(cr,oa.deleteAuditLogsBefore)),e.set(A.OPERATIONS_ENUM.READ_AUDIT_LOG,new N(n1)),e.set(A.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new N(fb.createTokens)),e.set(A.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new N(fb.refreshOperationToken)),e.set(A.OPERATIONS_ENUM.GET_CONFIGURATION,new N(Tb.getConfiguration)),e.set(A.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new N(Ur.customFunctionsStatus)),e.set(A.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new N(Ur.getCustomFunctions)),e.set(A.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new N(Ur.getCustomFunction)),e.set(A.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new N(Ur.setCustomFunction)),e.set(A.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new N(Ur.dropCustomFunction)),e.set(A.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new N(Ur.addCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new N(Ur.dropCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new N(Ur.packageCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new N(Ur.deployCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new N(mb.readTransactionLog)),e.set(A.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new N(cr,mb.deleteTransactionLogsBefore)),e.set(A.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new N(Rb.installModules)),e.set(A.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new N(Rb.auditModules)),e}a(g1,"initializeOperationFunctionMap")});var Wd=h(($2,Cb)=>{"use strict";var I1=T(),b1=b(),_r=g(),{handleHDBError:Kd,hdb_errors:Q_}=D(),Ib=require("os"),C1=require("util"),w1=kl(),U1=C1.promisify(w1.authorize),bb=gb();function L1(e){let t=`Found an uncaught exception with message: ${e.message}. ${Ib.EOL}Stack: ${e.stack} ${Ib.EOL}Terminating HDB.`;console.error(t),_r.fatal(t),process.exit(1)}a(L1,"handleServerUncaughtException");function y1(){_r.info("beforeExit caught"),process.exit(0)}a(y1,"handleBeforeExit");function D1(){_r.info("exit caught"),process.exit(0)}a(D1,"handleExit");function M1(){_r.info("SIGINT caught"),process.exit(0)}a(M1,"handleSigint");function P1(){_r.info("SIGQUIT caught"),process.exit(0)}a(P1,"handleSigquit");function B1(){_r.info("SIGTERM caught"),process.exit(0)}a(B1,"handleSigterm");function v1(e,t,r){if(_r.error(e),e.http_resp_code)return typeof e.http_resp_msg=="string"?r.code(e.http_resp_code).send({error:e.http_resp_msg}):r.code(e.http_resp_code).send(e.http_resp_msg);let s=e.statusCode?e.statusCode:Q_.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(s).send({error:e}):r.code(s).send(e.message?{error:e.message}:e)}a(v1,"serverErrorHandler");function H1(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let s=Kd(new Error,"Invalid JSON.",Q_.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}if(b1.isEmpty(e.body.operation)){let s=Kd(new Error,"Request body must include an 'operation' property.",Q_.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}r()}a(H1,"reqBodyValidationHandler");function q1(e,t,r){let s;e.body.operation!==I1.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS?U1(e,t).then(n=>{s=n,e.body.hdb_user=s,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(n=>{_r.warn(n),_r.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${n.stack}"`);let i=typeof n=="string"?{error:n}:{error:n.message};r(Kd(n,i,Q_.HTTP_STATUS_CODES.UNAUTHORIZED),null)}):(e.body.hdb_user=null,e.body.hdb_auth_header=e.headers.authorization,r())}a(q1,"authHandler");async function G1(e,t=!1){let r;try{return t&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=t),r=bb.chooseOperation(e.body),bb.processLocalTransaction(e,r)}catch(s){throw _r.error(s),s}}a(G1,"handlePostRequest");Cb.exports={authHandler:q1,handlePostRequest:G1,handleServerUncaughtException:L1,serverErrorHandler:v1,reqBodyValidationHandler:H1,handleBeforeExit:y1,handleExit:D1,handleSigint:M1,handleSigquit:P1,handleSigterm:B1}});var Lb=h((k2,Ub)=>{"use strict";var F1=require("fastify-plugin"),{handlePostRequest:wb,authHandler:V1,reqBodyValidationHandler:$1}=Wd();async function k1(e){e.decorate("hdbCore",{preValidation:[$1,V1],request:wb,requestWithoutAuthentication:t=>wb(t,!0)})}a(k1,"hdbCore");Ub.exports=F1(k1)});var Db=h(()=>{"use strict";var x1=require("util"),Y1=require("path"),x2=require("fast-glob"),J_=require("fs"),K1=require("fastify"),W1=require("@fastify/cors"),Q1=require("@fastify/static"),J1=require("@fastify/autoload"),X1=Zd(),Qd=V(),Jd=T(),Q=g(),Z1=$r(),z1=Rr(),j1=uA(),eJ=mA(),{PACKAGE_ROOT:Y2}=T(),tJ=pA(),rJ=gA(),sJ=CA(),nJ=x1.promisify(Z1.setSchemaDataToGlobal),{handleServerUncaughtException:iJ,serverErrorHandler:aJ,handleBeforeExit:oJ,handleExit:cJ,handleSigint:_J,handleSigquit:uJ,handleSigterm:lJ}=Wd(),EJ="TRUE",X_,yb=Qd.get(Jd.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY);async function dJ(){try{try{global.hdb_ipc=new j1(process.pid,eJ)}catch(s){throw Q.error("Error instantiating new instance of IPC client in Custom Functions server"),Q.error(s),s}Q.info("In Custom Functions Fastify server"+process.cwd()),Q.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Q.debug(`Custom Functions server process ${process.pid} starting up.`),process.on("uncaughtException",iJ),process.on("beforeExit",oJ),process.on("exit",cJ),process.on("SIGINT",_J),process.on("SIGQUIT",uJ),process.on("SIGTERM",lJ),await hJ();let e=Qd.get(Jd.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS),t=parseInt(Qd.get(Jd.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_PORT),10),r=e&&(e===!0||e.toUpperCase()===EJ);try{X_=fJ(r)}catch(s){throw Q.error(`Custom Functions buildServer error: ${s}`),s}try{await X_.ready()}catch(s){throw Q.error(`Custom Functions server.ready() error: ${s}`),s}try{Q.info(`Custom Functions process starting on port ${t}`),await X_.listen({port:t,host:"::"}),Q.info(`Custom Functions process running on port ${t}`)}catch(s){throw X_.close(),Q.error(`Custom Functions server.listen() error: ${s}`),s}}catch(e){Q.error(`Custom Functions ${process.pid} Error: ${e}`),Q.error(e),process.exit(1)}}a(dJ,"customFunctionsServer");async function hJ(){try{Q.info("Custom Functions starting configuration."),await nJ(),await z1.setUsersToGlobal(),Q.info("Custom Functions completed configuration.")}catch(e){Q.error(e)}}a(hJ,"setUp");async function SJ(e){try{Q.info("Custom Functions starting buildRoutes"),await e.register(Lb()),await e.after(),J_.readdirSync(yb,{withFileTypes:!0}).forEach(r=>{if(!r.isDirectory()&&!r.isSymbolicLink())return;let s=r.name,n=Y1.join(yb,s);Q.trace("Loading project folder "+n);let i=`${n}/routes`,o=`${n}/static`,c=`${n}/static/index.html`,_=`/${s}/static`,u=J_.existsSync(i),l=J_.existsSync(o)&&J_.existsSync(c);u&&e.register(J1,E=>({dir:i,dirNameRoutePrefix:!1,options:{hdbCore:E.hdbCore,logger:Q,prefix:`/${s}`}})).after((E,d,S)=>{E&&E.message?Q.error(E.message):E&&Q.error(E),S()}),l&&(Q.info(`Custom Functions setting up webserver for ${s}`),e.register(Q1,{root:o}).after((E,d,S)=>{E&&E.message?Q.error(E.message):E&&Q.error(E),S()}),e.get(_,(E,d)=>d.sendFile("index.html",o)))}),Q.info("Custom Functions completed buildRoutes")}catch(t){Q.error(`Custom Functions errored buildRoutes: ${t}`)}}a(SJ,"buildRoutes");function fJ(e){try{Q.info("Custom Functions starting buildServer.");let t=tJ(e),r=K1(t);r.server.headersTimeout=sJ(),r.setErrorHandler(aJ);let s=rJ();return s&&r.register(W1,s),r.register(X1),r.register(SJ),Q.info("Custom Functions completed buildServer."),r}catch(t){Q.error(`Custom Functions process ${process.pid} buildServer error: ${t}`),Q.fatal(t),process.exit(1)}}a(fJ,"buildServer");(async()=>await dJ())()});Db();